Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
3 роки тому
3 роки тому
2 роки тому
3 роки тому
3 роки тому
3 роки тому
3 роки тому
3 роки тому
3 роки тому
2 роки тому
2 роки тому
3 роки тому
2 роки тому
2 роки тому
2 роки тому
3 роки тому
2 роки тому
2 роки тому
3 роки тому
2 роки тому
3 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
3 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
3 роки тому
2 роки тому
2 роки тому
2 роки тому
3 роки тому
3 роки тому
3 роки тому
2 роки тому
3 роки тому
3 роки тому
3 роки тому
3 роки тому
3 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
3 роки тому
3 роки тому
2 роки тому
3 роки тому
3 роки тому
3 роки тому
2 роки тому
2 роки тому
2 роки тому
3 роки тому
2 роки тому
3 роки тому
2 роки тому
2 роки тому
3 роки тому
2 роки тому
2 роки тому
3 роки тому
2 роки тому
2 роки тому
3 роки тому
2 роки тому
2 роки тому
3 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
3 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
3 роки тому
3 роки тому
2 роки тому
2 роки тому
2 роки тому
3 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
3 роки тому
2 роки тому
3 роки тому
2 роки тому
2 роки тому
2 роки тому
3 роки тому
3 роки тому
2 роки тому
2 роки тому
3 роки тому
3 роки тому
3 роки тому
2 роки тому
3 роки тому
3 роки тому
2 роки тому
2 роки тому
2 роки тому
3 роки тому
3 роки тому
2 роки тому
2 роки тому
3 роки тому
3 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
3 роки тому
2 роки тому
3 роки тому
2 роки тому
3 роки тому
2 роки тому
3 роки тому
3 роки тому
3 роки тому
2 роки тому
2 роки тому
2 роки тому
3 роки тому
2 роки тому
2 роки тому
3 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
3 роки тому
3 роки тому
3 роки тому
3 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
3 роки тому
3 роки тому
2 роки тому
3 роки тому
2 роки тому
3 роки тому
3 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
3 роки тому
2 роки тому
3 роки тому
2 роки тому
3 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
3 роки тому
3 роки тому
3 роки тому
3 роки тому
3 роки тому
3 роки тому
3 роки тому
3 роки тому
3 роки тому
2 роки тому
3 роки тому
2 роки тому
3 роки тому
2 роки тому
3 роки тому
3 роки тому
3 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
3 роки тому
2 роки тому
3 роки тому
2 роки тому
3 роки тому
2 роки тому
3 роки тому
3 роки тому
2 роки тому
2 роки тому
2 роки тому
3 роки тому
3 роки тому
3 роки тому
3 роки тому
3 роки тому
3 роки тому
3 роки тому
2 роки тому
2 роки тому
3 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
3 роки тому
3 роки тому
3 роки тому
3 роки тому
3 роки тому
3 роки тому
3 роки тому
3 роки тому
3 роки тому
3 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
3 роки тому
2 роки тому
2 роки тому
2 роки тому
3 роки тому
3 роки тому
3 роки тому
3 роки тому
3 роки тому
2 роки тому
3 роки тому
2 роки тому
3 роки тому
2 роки тому
3 роки тому
2 роки тому
3 роки тому
2 роки тому
3 роки тому
2 роки тому
3 роки тому
3 роки тому
2 роки тому
3 роки тому
3 роки тому
3 роки тому
3 роки тому
2 роки тому
3 роки тому
2 роки тому
3 роки тому
2 роки тому
2 роки тому
2 роки тому
3 роки тому
3 роки тому
3 роки тому
2 роки тому
2 роки тому
3 роки тому
2 роки тому
3 роки тому
2 роки тому
3 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
3 роки тому
3 роки тому
2 роки тому
3 роки тому
3 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
3 роки тому
2 роки тому
2 роки тому
3 роки тому
2 роки тому
3 роки тому
2 роки тому
3 роки тому
3 роки тому
2 роки тому
3 роки тому
2 роки тому
3 роки тому
2 роки тому
3 роки тому
2 роки тому
3 роки тому
3 роки тому
3 роки тому
2 роки тому
3 роки тому
2 роки тому
3 роки тому
2 роки тому
3 роки тому
2 роки тому
3 роки тому
3 роки тому
3 роки тому
3 роки тому
2 роки тому
3 роки тому
2 роки тому
3 роки тому
2 роки тому
3 роки тому
2 роки тому
3 роки тому
2 роки тому
3 роки тому
2 роки тому
3 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
3 роки тому
3 роки тому
2 роки тому
2 роки тому
2 роки тому
3 роки тому
2 роки тому
3 роки тому
2 роки тому
3 роки тому
3 роки тому
2 роки тому
3 роки тому
2 роки тому
3 роки тому
2 роки тому
3 роки тому
3 роки тому
3 роки тому
3 роки тому
3 роки тому
2 роки тому
2 роки тому
3 роки тому
2 роки тому
2 роки тому
2 роки тому
3 роки тому
3 роки тому
3 роки тому
2 роки тому
3 роки тому
3 роки тому
3 роки тому
3 роки тому
3 роки тому
2 роки тому
3 роки тому
3 роки тому
3 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
3 роки тому
3 роки тому
2 роки тому
3 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
3 роки тому
2 роки тому
2 роки тому
2 роки тому
2 роки тому
3 роки тому
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124
  1. /* Version: 1.0.0 - July 25, 2022 18:16:21 */
  2. 'use strict';
  3. var fs$1 = require('fs');
  4. var path$1 = require('path');
  5. var childProcess = require('child_process');
  6. var readline = require('readline');
  7. var os = require('os');
  8. var tty = require('tty');
  9. var require$$0 = require('util');
  10. var require$$0$1 = require('events');
  11. var assert = require('assert');
  12. var https = require('https');
  13. var http = require('http');
  14. require('console');
  15. function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
  16. var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs$1);
  17. var path__default = /*#__PURE__*/_interopDefaultLegacy(path$1);
  18. var childProcess__default = /*#__PURE__*/_interopDefaultLegacy(childProcess);
  19. var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);
  20. var os__default = /*#__PURE__*/_interopDefaultLegacy(os);
  21. var tty__default = /*#__PURE__*/_interopDefaultLegacy(tty);
  22. var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0);
  23. var require$$0__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$0$1);
  24. var assert__default = /*#__PURE__*/_interopDefaultLegacy(assert);
  25. var https__default = /*#__PURE__*/_interopDefaultLegacy(https);
  26. var http__default = /*#__PURE__*/_interopDefaultLegacy(http);
  27. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  28. function getAugmentedNamespace(n) {
  29. if (n.__esModule) return n;
  30. var a = Object.defineProperty({}, '__esModule', {value: true});
  31. Object.keys(n).forEach(function (k) {
  32. var d = Object.getOwnPropertyDescriptor(n, k);
  33. Object.defineProperty(a, k, d.get ? d : {
  34. enumerable: true,
  35. get: function () {
  36. return n[k];
  37. }
  38. });
  39. });
  40. return a;
  41. }
  42. function createCommonjsModule(fn, basedir, module) {
  43. return module = {
  44. path: basedir,
  45. exports: {},
  46. require: function (path, base) {
  47. return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
  48. }
  49. }, fn(module, module.exports), module.exports;
  50. }
  51. function commonjsRegister (path, loader) {
  52. DYNAMIC_REQUIRE_LOADERS[path] = loader;
  53. }
  54. const DYNAMIC_REQUIRE_LOADERS = Object.create(null);
  55. const DYNAMIC_REQUIRE_CACHE = Object.create(null);
  56. const DEFAULT_PARENT_MODULE = {
  57. id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []
  58. };
  59. const CHECKED_EXTENSIONS = ['', '.js', '.json'];
  60. function normalize (path) {
  61. path = path.replace(/\\/g, '/');
  62. const parts = path.split('/');
  63. const slashed = parts[0] === '';
  64. for (let i = 1; i < parts.length; i++) {
  65. if (parts[i] === '.' || parts[i] === '') {
  66. parts.splice(i--, 1);
  67. }
  68. }
  69. for (let i = 1; i < parts.length; i++) {
  70. if (parts[i] !== '..') continue;
  71. if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {
  72. parts.splice(--i, 2);
  73. i--;
  74. }
  75. }
  76. path = parts.join('/');
  77. if (slashed && path[0] !== '/')
  78. path = '/' + path;
  79. else if (path.length === 0)
  80. path = '.';
  81. return path;
  82. }
  83. function join () {
  84. if (arguments.length === 0)
  85. return '.';
  86. let joined;
  87. for (let i = 0; i < arguments.length; ++i) {
  88. let arg = arguments[i];
  89. if (arg.length > 0) {
  90. if (joined === undefined)
  91. joined = arg;
  92. else
  93. joined += '/' + arg;
  94. }
  95. }
  96. if (joined === undefined)
  97. return '.';
  98. return joined;
  99. }
  100. function isPossibleNodeModulesPath (modulePath) {
  101. let c0 = modulePath[0];
  102. if (c0 === '/' || c0 === '\\') return false;
  103. let c1 = modulePath[1], c2 = modulePath[2];
  104. if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\')) ||
  105. (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\'))) return false;
  106. if (c1 === ':' && (c2 === '/' || c2 === '\\'))
  107. return false;
  108. return true;
  109. }
  110. function dirname (path) {
  111. if (path.length === 0)
  112. return '.';
  113. let i = path.length - 1;
  114. while (i > 0) {
  115. const c = path.charCodeAt(i);
  116. if ((c === 47 || c === 92) && i !== path.length - 1)
  117. break;
  118. i--;
  119. }
  120. if (i > 0)
  121. return path.substr(0, i);
  122. if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)
  123. return path.charAt(0);
  124. return '.';
  125. }
  126. function commonjsResolveImpl (path, originalModuleDir, testCache) {
  127. const shouldTryNodeModules = isPossibleNodeModulesPath(path);
  128. path = normalize(path);
  129. let relPath;
  130. if (path[0] === '/') {
  131. originalModuleDir = '/';
  132. }
  133. while (true) {
  134. if (!shouldTryNodeModules) {
  135. relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;
  136. } else if (originalModuleDir) {
  137. relPath = normalize(originalModuleDir + '/node_modules/' + path);
  138. } else {
  139. relPath = normalize(join('node_modules', path));
  140. }
  141. if (relPath.endsWith('/..')) {
  142. break; // Travelled too far up, avoid infinite loop
  143. }
  144. for (let extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {
  145. const resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];
  146. if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {
  147. return resolvedPath;
  148. } if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {
  149. return resolvedPath;
  150. } }
  151. if (!shouldTryNodeModules) break;
  152. const nextDir = normalize(originalModuleDir + '/..');
  153. if (nextDir === originalModuleDir) break;
  154. originalModuleDir = nextDir;
  155. }
  156. return null;
  157. }
  158. function commonjsResolve (path, originalModuleDir) {
  159. const resolvedPath = commonjsResolveImpl(path, originalModuleDir);
  160. if (resolvedPath !== null) {
  161. return resolvedPath;
  162. }
  163. return require.resolve(path);
  164. }
  165. function commonjsRequire (path, originalModuleDir) {
  166. const resolvedPath = commonjsResolveImpl(path, originalModuleDir);
  167. if (resolvedPath !== null) {
  168. let cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];
  169. if (cachedModule) return cachedModule.exports;
  170. const loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];
  171. if (loader) {
  172. DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {
  173. id: resolvedPath,
  174. filename: resolvedPath,
  175. path: dirname(resolvedPath),
  176. exports: {},
  177. parent: DEFAULT_PARENT_MODULE,
  178. loaded: false,
  179. children: [],
  180. paths: [],
  181. require: function (path, base) {
  182. return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);
  183. }
  184. };
  185. try {
  186. loader.call(commonjsGlobal, cachedModule, cachedModule.exports);
  187. } catch (error) {
  188. delete DYNAMIC_REQUIRE_CACHE[resolvedPath];
  189. throw error;
  190. }
  191. cachedModule.loaded = true;
  192. return cachedModule.exports;
  193. } }
  194. return require(path);
  195. }
  196. commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;
  197. commonjsRequire.resolve = commonjsResolve;
  198. /**
  199. * This method returns the first argument it receives.
  200. *
  201. * @static
  202. * @since 0.1.0
  203. * @memberOf _
  204. * @category Util
  205. * @param {*} value Any value.
  206. * @returns {*} Returns `value`.
  207. * @example
  208. *
  209. * var object = { 'a': 1 };
  210. *
  211. * console.log(_.identity(object) === object);
  212. * // => true
  213. */
  214. function identity(value) {
  215. return value;
  216. }
  217. var identity_1 = identity;
  218. /** Detect free variable `global` from Node.js. */
  219. var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
  220. var _freeGlobal = freeGlobal;
  221. /** Detect free variable `self`. */
  222. var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
  223. /** Used as a reference to the global object. */
  224. var root = _freeGlobal || freeSelf || Function('return this')();
  225. var _root = root;
  226. /** Built-in value references. */
  227. var Symbol$1 = _root.Symbol;
  228. var _Symbol = Symbol$1;
  229. /** Used for built-in method references. */
  230. var objectProto$h = Object.prototype;
  231. /** Used to check objects for own properties. */
  232. var hasOwnProperty$e = objectProto$h.hasOwnProperty;
  233. /**
  234. * Used to resolve the
  235. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  236. * of values.
  237. */
  238. var nativeObjectToString$1 = objectProto$h.toString;
  239. /** Built-in value references. */
  240. var symToStringTag$1 = _Symbol ? _Symbol.toStringTag : undefined;
  241. /**
  242. * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
  243. *
  244. * @private
  245. * @param {*} value The value to query.
  246. * @returns {string} Returns the raw `toStringTag`.
  247. */
  248. function getRawTag(value) {
  249. var isOwn = hasOwnProperty$e.call(value, symToStringTag$1),
  250. tag = value[symToStringTag$1];
  251. try {
  252. value[symToStringTag$1] = undefined;
  253. var unmasked = true;
  254. } catch (e) {}
  255. var result = nativeObjectToString$1.call(value);
  256. if (unmasked) {
  257. if (isOwn) {
  258. value[symToStringTag$1] = tag;
  259. } else {
  260. delete value[symToStringTag$1];
  261. }
  262. }
  263. return result;
  264. }
  265. var _getRawTag = getRawTag;
  266. /** Used for built-in method references. */
  267. var objectProto$g = Object.prototype;
  268. /**
  269. * Used to resolve the
  270. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  271. * of values.
  272. */
  273. var nativeObjectToString = objectProto$g.toString;
  274. /**
  275. * Converts `value` to a string using `Object.prototype.toString`.
  276. *
  277. * @private
  278. * @param {*} value The value to convert.
  279. * @returns {string} Returns the converted string.
  280. */
  281. function objectToString(value) {
  282. return nativeObjectToString.call(value);
  283. }
  284. var _objectToString = objectToString;
  285. /** `Object#toString` result references. */
  286. var nullTag = '[object Null]',
  287. undefinedTag = '[object Undefined]';
  288. /** Built-in value references. */
  289. var symToStringTag = _Symbol ? _Symbol.toStringTag : undefined;
  290. /**
  291. * The base implementation of `getTag` without fallbacks for buggy environments.
  292. *
  293. * @private
  294. * @param {*} value The value to query.
  295. * @returns {string} Returns the `toStringTag`.
  296. */
  297. function baseGetTag(value) {
  298. if (value == null) {
  299. return value === undefined ? undefinedTag : nullTag;
  300. }
  301. return (symToStringTag && symToStringTag in Object(value))
  302. ? _getRawTag(value)
  303. : _objectToString(value);
  304. }
  305. var _baseGetTag = baseGetTag;
  306. /**
  307. * Checks if `value` is the
  308. * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
  309. * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
  310. *
  311. * @static
  312. * @memberOf _
  313. * @since 0.1.0
  314. * @category Lang
  315. * @param {*} value The value to check.
  316. * @returns {boolean} Returns `true` if `value` is an object, else `false`.
  317. * @example
  318. *
  319. * _.isObject({});
  320. * // => true
  321. *
  322. * _.isObject([1, 2, 3]);
  323. * // => true
  324. *
  325. * _.isObject(_.noop);
  326. * // => true
  327. *
  328. * _.isObject(null);
  329. * // => false
  330. */
  331. function isObject$1(value) {
  332. var type = typeof value;
  333. return value != null && (type == 'object' || type == 'function');
  334. }
  335. var isObject_1 = isObject$1;
  336. /** `Object#toString` result references. */
  337. var asyncTag = '[object AsyncFunction]',
  338. funcTag$2 = '[object Function]',
  339. genTag$1 = '[object GeneratorFunction]',
  340. proxyTag = '[object Proxy]';
  341. /**
  342. * Checks if `value` is classified as a `Function` object.
  343. *
  344. * @static
  345. * @memberOf _
  346. * @since 0.1.0
  347. * @category Lang
  348. * @param {*} value The value to check.
  349. * @returns {boolean} Returns `true` if `value` is a function, else `false`.
  350. * @example
  351. *
  352. * _.isFunction(_);
  353. * // => true
  354. *
  355. * _.isFunction(/abc/);
  356. * // => false
  357. */
  358. function isFunction(value) {
  359. if (!isObject_1(value)) {
  360. return false;
  361. }
  362. // The use of `Object#toString` avoids issues with the `typeof` operator
  363. // in Safari 9 which returns 'object' for typed arrays and other constructors.
  364. var tag = _baseGetTag(value);
  365. return tag == funcTag$2 || tag == genTag$1 || tag == asyncTag || tag == proxyTag;
  366. }
  367. var isFunction_1 = isFunction;
  368. /** Used to detect overreaching core-js shims. */
  369. var coreJsData = _root['__core-js_shared__'];
  370. var _coreJsData = coreJsData;
  371. /** Used to detect methods masquerading as native. */
  372. var maskSrcKey = (function() {
  373. var uid = /[^.]+$/.exec(_coreJsData && _coreJsData.keys && _coreJsData.keys.IE_PROTO || '');
  374. return uid ? ('Symbol(src)_1.' + uid) : '';
  375. }());
  376. /**
  377. * Checks if `func` has its source masked.
  378. *
  379. * @private
  380. * @param {Function} func The function to check.
  381. * @returns {boolean} Returns `true` if `func` is masked, else `false`.
  382. */
  383. function isMasked(func) {
  384. return !!maskSrcKey && (maskSrcKey in func);
  385. }
  386. var _isMasked = isMasked;
  387. /** Used for built-in method references. */
  388. var funcProto$2 = Function.prototype;
  389. /** Used to resolve the decompiled source of functions. */
  390. var funcToString$2 = funcProto$2.toString;
  391. /**
  392. * Converts `func` to its source code.
  393. *
  394. * @private
  395. * @param {Function} func The function to convert.
  396. * @returns {string} Returns the source code.
  397. */
  398. function toSource(func) {
  399. if (func != null) {
  400. try {
  401. return funcToString$2.call(func);
  402. } catch (e) {}
  403. try {
  404. return (func + '');
  405. } catch (e) {}
  406. }
  407. return '';
  408. }
  409. var _toSource = toSource;
  410. /**
  411. * Used to match `RegExp`
  412. * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
  413. */
  414. var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
  415. /** Used to detect host constructors (Safari). */
  416. var reIsHostCtor = /^\[object .+?Constructor\]$/;
  417. /** Used for built-in method references. */
  418. var funcProto$1 = Function.prototype,
  419. objectProto$f = Object.prototype;
  420. /** Used to resolve the decompiled source of functions. */
  421. var funcToString$1 = funcProto$1.toString;
  422. /** Used to check objects for own properties. */
  423. var hasOwnProperty$d = objectProto$f.hasOwnProperty;
  424. /** Used to detect if a method is native. */
  425. var reIsNative = RegExp('^' +
  426. funcToString$1.call(hasOwnProperty$d).replace(reRegExpChar, '\\$&')
  427. .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
  428. );
  429. /**
  430. * The base implementation of `_.isNative` without bad shim checks.
  431. *
  432. * @private
  433. * @param {*} value The value to check.
  434. * @returns {boolean} Returns `true` if `value` is a native function,
  435. * else `false`.
  436. */
  437. function baseIsNative(value) {
  438. if (!isObject_1(value) || _isMasked(value)) {
  439. return false;
  440. }
  441. var pattern = isFunction_1(value) ? reIsNative : reIsHostCtor;
  442. return pattern.test(_toSource(value));
  443. }
  444. var _baseIsNative = baseIsNative;
  445. /**
  446. * Gets the value at `key` of `object`.
  447. *
  448. * @private
  449. * @param {Object} [object] The object to query.
  450. * @param {string} key The key of the property to get.
  451. * @returns {*} Returns the property value.
  452. */
  453. function getValue(object, key) {
  454. return object == null ? undefined : object[key];
  455. }
  456. var _getValue = getValue;
  457. /**
  458. * Gets the native function at `key` of `object`.
  459. *
  460. * @private
  461. * @param {Object} object The object to query.
  462. * @param {string} key The key of the method to get.
  463. * @returns {*} Returns the function if it's native, else `undefined`.
  464. */
  465. function getNative(object, key) {
  466. var value = _getValue(object, key);
  467. return _baseIsNative(value) ? value : undefined;
  468. }
  469. var _getNative = getNative;
  470. /* Built-in method references that are verified to be native. */
  471. var WeakMap$1 = _getNative(_root, 'WeakMap');
  472. var _WeakMap = WeakMap$1;
  473. /** Used to store function metadata. */
  474. var metaMap = _WeakMap && new _WeakMap;
  475. var _metaMap = metaMap;
  476. /**
  477. * The base implementation of `setData` without support for hot loop shorting.
  478. *
  479. * @private
  480. * @param {Function} func The function to associate metadata with.
  481. * @param {*} data The metadata.
  482. * @returns {Function} Returns `func`.
  483. */
  484. var baseSetData = !_metaMap ? identity_1 : function(func, data) {
  485. _metaMap.set(func, data);
  486. return func;
  487. };
  488. var _baseSetData = baseSetData;
  489. /** Built-in value references. */
  490. var objectCreate = Object.create;
  491. /**
  492. * The base implementation of `_.create` without support for assigning
  493. * properties to the created object.
  494. *
  495. * @private
  496. * @param {Object} proto The object to inherit from.
  497. * @returns {Object} Returns the new object.
  498. */
  499. var baseCreate = (function() {
  500. function object() {}
  501. return function(proto) {
  502. if (!isObject_1(proto)) {
  503. return {};
  504. }
  505. if (objectCreate) {
  506. return objectCreate(proto);
  507. }
  508. object.prototype = proto;
  509. var result = new object;
  510. object.prototype = undefined;
  511. return result;
  512. };
  513. }());
  514. var _baseCreate = baseCreate;
  515. /**
  516. * Creates a function that produces an instance of `Ctor` regardless of
  517. * whether it was invoked as part of a `new` expression or by `call` or `apply`.
  518. *
  519. * @private
  520. * @param {Function} Ctor The constructor to wrap.
  521. * @returns {Function} Returns the new wrapped function.
  522. */
  523. function createCtor(Ctor) {
  524. return function() {
  525. // Use a `switch` statement to work with class constructors. See
  526. // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist
  527. // for more details.
  528. var args = arguments;
  529. switch (args.length) {
  530. case 0: return new Ctor;
  531. case 1: return new Ctor(args[0]);
  532. case 2: return new Ctor(args[0], args[1]);
  533. case 3: return new Ctor(args[0], args[1], args[2]);
  534. case 4: return new Ctor(args[0], args[1], args[2], args[3]);
  535. case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]);
  536. case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);
  537. case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
  538. }
  539. var thisBinding = _baseCreate(Ctor.prototype),
  540. result = Ctor.apply(thisBinding, args);
  541. // Mimic the constructor's `return` behavior.
  542. // See https://es5.github.io/#x13.2.2 for more details.
  543. return isObject_1(result) ? result : thisBinding;
  544. };
  545. }
  546. var _createCtor = createCtor;
  547. /** Used to compose bitmasks for function metadata. */
  548. var WRAP_BIND_FLAG$6 = 1;
  549. /**
  550. * Creates a function that wraps `func` to invoke it with the optional `this`
  551. * binding of `thisArg`.
  552. *
  553. * @private
  554. * @param {Function} func The function to wrap.
  555. * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
  556. * @param {*} [thisArg] The `this` binding of `func`.
  557. * @returns {Function} Returns the new wrapped function.
  558. */
  559. function createBind(func, bitmask, thisArg) {
  560. var isBind = bitmask & WRAP_BIND_FLAG$6,
  561. Ctor = _createCtor(func);
  562. function wrapper() {
  563. var fn = (this && this !== _root && this instanceof wrapper) ? Ctor : func;
  564. return fn.apply(isBind ? thisArg : this, arguments);
  565. }
  566. return wrapper;
  567. }
  568. var _createBind = createBind;
  569. /**
  570. * A faster alternative to `Function#apply`, this function invokes `func`
  571. * with the `this` binding of `thisArg` and the arguments of `args`.
  572. *
  573. * @private
  574. * @param {Function} func The function to invoke.
  575. * @param {*} thisArg The `this` binding of `func`.
  576. * @param {Array} args The arguments to invoke `func` with.
  577. * @returns {*} Returns the result of `func`.
  578. */
  579. function apply(func, thisArg, args) {
  580. switch (args.length) {
  581. case 0: return func.call(thisArg);
  582. case 1: return func.call(thisArg, args[0]);
  583. case 2: return func.call(thisArg, args[0], args[1]);
  584. case 3: return func.call(thisArg, args[0], args[1], args[2]);
  585. }
  586. return func.apply(thisArg, args);
  587. }
  588. var _apply = apply;
  589. /* Built-in method references for those with the same name as other `lodash` methods. */
  590. var nativeMax$3 = Math.max;
  591. /**
  592. * Creates an array that is the composition of partially applied arguments,
  593. * placeholders, and provided arguments into a single array of arguments.
  594. *
  595. * @private
  596. * @param {Array} args The provided arguments.
  597. * @param {Array} partials The arguments to prepend to those provided.
  598. * @param {Array} holders The `partials` placeholder indexes.
  599. * @params {boolean} [isCurried] Specify composing for a curried function.
  600. * @returns {Array} Returns the new array of composed arguments.
  601. */
  602. function composeArgs(args, partials, holders, isCurried) {
  603. var argsIndex = -1,
  604. argsLength = args.length,
  605. holdersLength = holders.length,
  606. leftIndex = -1,
  607. leftLength = partials.length,
  608. rangeLength = nativeMax$3(argsLength - holdersLength, 0),
  609. result = Array(leftLength + rangeLength),
  610. isUncurried = !isCurried;
  611. while (++leftIndex < leftLength) {
  612. result[leftIndex] = partials[leftIndex];
  613. }
  614. while (++argsIndex < holdersLength) {
  615. if (isUncurried || argsIndex < argsLength) {
  616. result[holders[argsIndex]] = args[argsIndex];
  617. }
  618. }
  619. while (rangeLength--) {
  620. result[leftIndex++] = args[argsIndex++];
  621. }
  622. return result;
  623. }
  624. var _composeArgs = composeArgs;
  625. /* Built-in method references for those with the same name as other `lodash` methods. */
  626. var nativeMax$2 = Math.max;
  627. /**
  628. * This function is like `composeArgs` except that the arguments composition
  629. * is tailored for `_.partialRight`.
  630. *
  631. * @private
  632. * @param {Array} args The provided arguments.
  633. * @param {Array} partials The arguments to append to those provided.
  634. * @param {Array} holders The `partials` placeholder indexes.
  635. * @params {boolean} [isCurried] Specify composing for a curried function.
  636. * @returns {Array} Returns the new array of composed arguments.
  637. */
  638. function composeArgsRight(args, partials, holders, isCurried) {
  639. var argsIndex = -1,
  640. argsLength = args.length,
  641. holdersIndex = -1,
  642. holdersLength = holders.length,
  643. rightIndex = -1,
  644. rightLength = partials.length,
  645. rangeLength = nativeMax$2(argsLength - holdersLength, 0),
  646. result = Array(rangeLength + rightLength),
  647. isUncurried = !isCurried;
  648. while (++argsIndex < rangeLength) {
  649. result[argsIndex] = args[argsIndex];
  650. }
  651. var offset = argsIndex;
  652. while (++rightIndex < rightLength) {
  653. result[offset + rightIndex] = partials[rightIndex];
  654. }
  655. while (++holdersIndex < holdersLength) {
  656. if (isUncurried || argsIndex < argsLength) {
  657. result[offset + holders[holdersIndex]] = args[argsIndex++];
  658. }
  659. }
  660. return result;
  661. }
  662. var _composeArgsRight = composeArgsRight;
  663. /**
  664. * Gets the number of `placeholder` occurrences in `array`.
  665. *
  666. * @private
  667. * @param {Array} array The array to inspect.
  668. * @param {*} placeholder The placeholder to search for.
  669. * @returns {number} Returns the placeholder count.
  670. */
  671. function countHolders(array, placeholder) {
  672. var length = array.length,
  673. result = 0;
  674. while (length--) {
  675. if (array[length] === placeholder) {
  676. ++result;
  677. }
  678. }
  679. return result;
  680. }
  681. var _countHolders = countHolders;
  682. /**
  683. * The function whose prototype chain sequence wrappers inherit from.
  684. *
  685. * @private
  686. */
  687. function baseLodash() {
  688. // No operation performed.
  689. }
  690. var _baseLodash = baseLodash;
  691. /** Used as references for the maximum length and index of an array. */
  692. var MAX_ARRAY_LENGTH = 4294967295;
  693. /**
  694. * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.
  695. *
  696. * @private
  697. * @constructor
  698. * @param {*} value The value to wrap.
  699. */
  700. function LazyWrapper(value) {
  701. this.__wrapped__ = value;
  702. this.__actions__ = [];
  703. this.__dir__ = 1;
  704. this.__filtered__ = false;
  705. this.__iteratees__ = [];
  706. this.__takeCount__ = MAX_ARRAY_LENGTH;
  707. this.__views__ = [];
  708. }
  709. // Ensure `LazyWrapper` is an instance of `baseLodash`.
  710. LazyWrapper.prototype = _baseCreate(_baseLodash.prototype);
  711. LazyWrapper.prototype.constructor = LazyWrapper;
  712. var _LazyWrapper = LazyWrapper;
  713. /**
  714. * This method returns `undefined`.
  715. *
  716. * @static
  717. * @memberOf _
  718. * @since 2.3.0
  719. * @category Util
  720. * @example
  721. *
  722. * _.times(2, _.noop);
  723. * // => [undefined, undefined]
  724. */
  725. function noop() {
  726. // No operation performed.
  727. }
  728. var noop_1 = noop;
  729. /**
  730. * Gets metadata for `func`.
  731. *
  732. * @private
  733. * @param {Function} func The function to query.
  734. * @returns {*} Returns the metadata for `func`.
  735. */
  736. var getData = !_metaMap ? noop_1 : function(func) {
  737. return _metaMap.get(func);
  738. };
  739. var _getData = getData;
  740. /** Used to lookup unminified function names. */
  741. var realNames = {};
  742. var _realNames = realNames;
  743. /** Used for built-in method references. */
  744. var objectProto$e = Object.prototype;
  745. /** Used to check objects for own properties. */
  746. var hasOwnProperty$c = objectProto$e.hasOwnProperty;
  747. /**
  748. * Gets the name of `func`.
  749. *
  750. * @private
  751. * @param {Function} func The function to query.
  752. * @returns {string} Returns the function name.
  753. */
  754. function getFuncName(func) {
  755. var result = (func.name + ''),
  756. array = _realNames[result],
  757. length = hasOwnProperty$c.call(_realNames, result) ? array.length : 0;
  758. while (length--) {
  759. var data = array[length],
  760. otherFunc = data.func;
  761. if (otherFunc == null || otherFunc == func) {
  762. return data.name;
  763. }
  764. }
  765. return result;
  766. }
  767. var _getFuncName = getFuncName;
  768. /**
  769. * The base constructor for creating `lodash` wrapper objects.
  770. *
  771. * @private
  772. * @param {*} value The value to wrap.
  773. * @param {boolean} [chainAll] Enable explicit method chain sequences.
  774. */
  775. function LodashWrapper(value, chainAll) {
  776. this.__wrapped__ = value;
  777. this.__actions__ = [];
  778. this.__chain__ = !!chainAll;
  779. this.__index__ = 0;
  780. this.__values__ = undefined;
  781. }
  782. LodashWrapper.prototype = _baseCreate(_baseLodash.prototype);
  783. LodashWrapper.prototype.constructor = LodashWrapper;
  784. var _LodashWrapper = LodashWrapper;
  785. /**
  786. * Checks if `value` is classified as an `Array` object.
  787. *
  788. * @static
  789. * @memberOf _
  790. * @since 0.1.0
  791. * @category Lang
  792. * @param {*} value The value to check.
  793. * @returns {boolean} Returns `true` if `value` is an array, else `false`.
  794. * @example
  795. *
  796. * _.isArray([1, 2, 3]);
  797. * // => true
  798. *
  799. * _.isArray(document.body.children);
  800. * // => false
  801. *
  802. * _.isArray('abc');
  803. * // => false
  804. *
  805. * _.isArray(_.noop);
  806. * // => false
  807. */
  808. var isArray$3 = Array.isArray;
  809. var isArray_1 = isArray$3;
  810. /**
  811. * Checks if `value` is object-like. A value is object-like if it's not `null`
  812. * and has a `typeof` result of "object".
  813. *
  814. * @static
  815. * @memberOf _
  816. * @since 4.0.0
  817. * @category Lang
  818. * @param {*} value The value to check.
  819. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  820. * @example
  821. *
  822. * _.isObjectLike({});
  823. * // => true
  824. *
  825. * _.isObjectLike([1, 2, 3]);
  826. * // => true
  827. *
  828. * _.isObjectLike(_.noop);
  829. * // => false
  830. *
  831. * _.isObjectLike(null);
  832. * // => false
  833. */
  834. function isObjectLike(value) {
  835. return value != null && typeof value == 'object';
  836. }
  837. var isObjectLike_1 = isObjectLike;
  838. /**
  839. * Copies the values of `source` to `array`.
  840. *
  841. * @private
  842. * @param {Array} source The array to copy values from.
  843. * @param {Array} [array=[]] The array to copy values to.
  844. * @returns {Array} Returns `array`.
  845. */
  846. function copyArray(source, array) {
  847. var index = -1,
  848. length = source.length;
  849. array || (array = Array(length));
  850. while (++index < length) {
  851. array[index] = source[index];
  852. }
  853. return array;
  854. }
  855. var _copyArray = copyArray;
  856. /**
  857. * Creates a clone of `wrapper`.
  858. *
  859. * @private
  860. * @param {Object} wrapper The wrapper to clone.
  861. * @returns {Object} Returns the cloned wrapper.
  862. */
  863. function wrapperClone(wrapper) {
  864. if (wrapper instanceof _LazyWrapper) {
  865. return wrapper.clone();
  866. }
  867. var result = new _LodashWrapper(wrapper.__wrapped__, wrapper.__chain__);
  868. result.__actions__ = _copyArray(wrapper.__actions__);
  869. result.__index__ = wrapper.__index__;
  870. result.__values__ = wrapper.__values__;
  871. return result;
  872. }
  873. var _wrapperClone = wrapperClone;
  874. /** Used for built-in method references. */
  875. var objectProto$d = Object.prototype;
  876. /** Used to check objects for own properties. */
  877. var hasOwnProperty$b = objectProto$d.hasOwnProperty;
  878. /**
  879. * Creates a `lodash` object which wraps `value` to enable implicit method
  880. * chain sequences. Methods that operate on and return arrays, collections,
  881. * and functions can be chained together. Methods that retrieve a single value
  882. * or may return a primitive value will automatically end the chain sequence
  883. * and return the unwrapped value. Otherwise, the value must be unwrapped
  884. * with `_#value`.
  885. *
  886. * Explicit chain sequences, which must be unwrapped with `_#value`, may be
  887. * enabled using `_.chain`.
  888. *
  889. * The execution of chained methods is lazy, that is, it's deferred until
  890. * `_#value` is implicitly or explicitly called.
  891. *
  892. * Lazy evaluation allows several methods to support shortcut fusion.
  893. * Shortcut fusion is an optimization to merge iteratee calls; this avoids
  894. * the creation of intermediate arrays and can greatly reduce the number of
  895. * iteratee executions. Sections of a chain sequence qualify for shortcut
  896. * fusion if the section is applied to an array and iteratees accept only
  897. * one argument. The heuristic for whether a section qualifies for shortcut
  898. * fusion is subject to change.
  899. *
  900. * Chaining is supported in custom builds as long as the `_#value` method is
  901. * directly or indirectly included in the build.
  902. *
  903. * In addition to lodash methods, wrappers have `Array` and `String` methods.
  904. *
  905. * The wrapper `Array` methods are:
  906. * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift`
  907. *
  908. * The wrapper `String` methods are:
  909. * `replace` and `split`
  910. *
  911. * The wrapper methods that support shortcut fusion are:
  912. * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`,
  913. * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`,
  914. * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray`
  915. *
  916. * The chainable wrapper methods are:
  917. * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`,
  918. * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`,
  919. * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`,
  920. * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`,
  921. * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`,
  922. * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`,
  923. * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`,
  924. * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`,
  925. * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`,
  926. * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`,
  927. * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`,
  928. * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`,
  929. * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`,
  930. * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`,
  931. * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`,
  932. * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`,
  933. * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`,
  934. * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`,
  935. * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`,
  936. * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`,
  937. * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`,
  938. * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`,
  939. * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`,
  940. * `zipObject`, `zipObjectDeep`, and `zipWith`
  941. *
  942. * The wrapper methods that are **not** chainable by default are:
  943. * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`,
  944. * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`,
  945. * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`,
  946. * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`,
  947. * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`,
  948. * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`,
  949. * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`,
  950. * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`,
  951. * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`,
  952. * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`,
  953. * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`,
  954. * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`,
  955. * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`,
  956. * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`,
  957. * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`,
  958. * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`,
  959. * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`,
  960. * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`,
  961. * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`,
  962. * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`,
  963. * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`,
  964. * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`,
  965. * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`,
  966. * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`,
  967. * `upperFirst`, `value`, and `words`
  968. *
  969. * @name _
  970. * @constructor
  971. * @category Seq
  972. * @param {*} value The value to wrap in a `lodash` instance.
  973. * @returns {Object} Returns the new `lodash` wrapper instance.
  974. * @example
  975. *
  976. * function square(n) {
  977. * return n * n;
  978. * }
  979. *
  980. * var wrapped = _([1, 2, 3]);
  981. *
  982. * // Returns an unwrapped value.
  983. * wrapped.reduce(_.add);
  984. * // => 6
  985. *
  986. * // Returns a wrapped value.
  987. * var squares = wrapped.map(square);
  988. *
  989. * _.isArray(squares);
  990. * // => false
  991. *
  992. * _.isArray(squares.value());
  993. * // => true
  994. */
  995. function lodash(value) {
  996. if (isObjectLike_1(value) && !isArray_1(value) && !(value instanceof _LazyWrapper)) {
  997. if (value instanceof _LodashWrapper) {
  998. return value;
  999. }
  1000. if (hasOwnProperty$b.call(value, '__wrapped__')) {
  1001. return _wrapperClone(value);
  1002. }
  1003. }
  1004. return new _LodashWrapper(value);
  1005. }
  1006. // Ensure wrappers are instances of `baseLodash`.
  1007. lodash.prototype = _baseLodash.prototype;
  1008. lodash.prototype.constructor = lodash;
  1009. var wrapperLodash = lodash;
  1010. /**
  1011. * Checks if `func` has a lazy counterpart.
  1012. *
  1013. * @private
  1014. * @param {Function} func The function to check.
  1015. * @returns {boolean} Returns `true` if `func` has a lazy counterpart,
  1016. * else `false`.
  1017. */
  1018. function isLaziable(func) {
  1019. var funcName = _getFuncName(func),
  1020. other = wrapperLodash[funcName];
  1021. if (typeof other != 'function' || !(funcName in _LazyWrapper.prototype)) {
  1022. return false;
  1023. }
  1024. if (func === other) {
  1025. return true;
  1026. }
  1027. var data = _getData(other);
  1028. return !!data && func === data[0];
  1029. }
  1030. var _isLaziable = isLaziable;
  1031. /** Used to detect hot functions by number of calls within a span of milliseconds. */
  1032. var HOT_COUNT = 800,
  1033. HOT_SPAN = 16;
  1034. /* Built-in method references for those with the same name as other `lodash` methods. */
  1035. var nativeNow = Date.now;
  1036. /**
  1037. * Creates a function that'll short out and invoke `identity` instead
  1038. * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
  1039. * milliseconds.
  1040. *
  1041. * @private
  1042. * @param {Function} func The function to restrict.
  1043. * @returns {Function} Returns the new shortable function.
  1044. */
  1045. function shortOut(func) {
  1046. var count = 0,
  1047. lastCalled = 0;
  1048. return function() {
  1049. var stamp = nativeNow(),
  1050. remaining = HOT_SPAN - (stamp - lastCalled);
  1051. lastCalled = stamp;
  1052. if (remaining > 0) {
  1053. if (++count >= HOT_COUNT) {
  1054. return arguments[0];
  1055. }
  1056. } else {
  1057. count = 0;
  1058. }
  1059. return func.apply(undefined, arguments);
  1060. };
  1061. }
  1062. var _shortOut = shortOut;
  1063. /**
  1064. * Sets metadata for `func`.
  1065. *
  1066. * **Note:** If this function becomes hot, i.e. is invoked a lot in a short
  1067. * period of time, it will trip its breaker and transition to an identity
  1068. * function to avoid garbage collection pauses in V8. See
  1069. * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070)
  1070. * for more details.
  1071. *
  1072. * @private
  1073. * @param {Function} func The function to associate metadata with.
  1074. * @param {*} data The metadata.
  1075. * @returns {Function} Returns `func`.
  1076. */
  1077. var setData = _shortOut(_baseSetData);
  1078. var _setData = setData;
  1079. /** Used to match wrap detail comments. */
  1080. var reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/,
  1081. reSplitDetails = /,? & /;
  1082. /**
  1083. * Extracts wrapper details from the `source` body comment.
  1084. *
  1085. * @private
  1086. * @param {string} source The source to inspect.
  1087. * @returns {Array} Returns the wrapper details.
  1088. */
  1089. function getWrapDetails(source) {
  1090. var match = source.match(reWrapDetails);
  1091. return match ? match[1].split(reSplitDetails) : [];
  1092. }
  1093. var _getWrapDetails = getWrapDetails;
  1094. /** Used to match wrap detail comments. */
  1095. var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/;
  1096. /**
  1097. * Inserts wrapper `details` in a comment at the top of the `source` body.
  1098. *
  1099. * @private
  1100. * @param {string} source The source to modify.
  1101. * @returns {Array} details The details to insert.
  1102. * @returns {string} Returns the modified source.
  1103. */
  1104. function insertWrapDetails(source, details) {
  1105. var length = details.length;
  1106. if (!length) {
  1107. return source;
  1108. }
  1109. var lastIndex = length - 1;
  1110. details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex];
  1111. details = details.join(length > 2 ? ', ' : ' ');
  1112. return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n');
  1113. }
  1114. var _insertWrapDetails = insertWrapDetails;
  1115. /**
  1116. * Creates a function that returns `value`.
  1117. *
  1118. * @static
  1119. * @memberOf _
  1120. * @since 2.4.0
  1121. * @category Util
  1122. * @param {*} value The value to return from the new function.
  1123. * @returns {Function} Returns the new constant function.
  1124. * @example
  1125. *
  1126. * var objects = _.times(2, _.constant({ 'a': 1 }));
  1127. *
  1128. * console.log(objects);
  1129. * // => [{ 'a': 1 }, { 'a': 1 }]
  1130. *
  1131. * console.log(objects[0] === objects[1]);
  1132. * // => true
  1133. */
  1134. function constant(value) {
  1135. return function() {
  1136. return value;
  1137. };
  1138. }
  1139. var constant_1 = constant;
  1140. var defineProperty = (function() {
  1141. try {
  1142. var func = _getNative(Object, 'defineProperty');
  1143. func({}, '', {});
  1144. return func;
  1145. } catch (e) {}
  1146. }());
  1147. var _defineProperty = defineProperty;
  1148. /**
  1149. * The base implementation of `setToString` without support for hot loop shorting.
  1150. *
  1151. * @private
  1152. * @param {Function} func The function to modify.
  1153. * @param {Function} string The `toString` result.
  1154. * @returns {Function} Returns `func`.
  1155. */
  1156. var baseSetToString = !_defineProperty ? identity_1 : function(func, string) {
  1157. return _defineProperty(func, 'toString', {
  1158. 'configurable': true,
  1159. 'enumerable': false,
  1160. 'value': constant_1(string),
  1161. 'writable': true
  1162. });
  1163. };
  1164. var _baseSetToString = baseSetToString;
  1165. /**
  1166. * Sets the `toString` method of `func` to return `string`.
  1167. *
  1168. * @private
  1169. * @param {Function} func The function to modify.
  1170. * @param {Function} string The `toString` result.
  1171. * @returns {Function} Returns `func`.
  1172. */
  1173. var setToString = _shortOut(_baseSetToString);
  1174. var _setToString = setToString;
  1175. /**
  1176. * A specialized version of `_.forEach` for arrays without support for
  1177. * iteratee shorthands.
  1178. *
  1179. * @private
  1180. * @param {Array} [array] The array to iterate over.
  1181. * @param {Function} iteratee The function invoked per iteration.
  1182. * @returns {Array} Returns `array`.
  1183. */
  1184. function arrayEach(array, iteratee) {
  1185. var index = -1,
  1186. length = array == null ? 0 : array.length;
  1187. while (++index < length) {
  1188. if (iteratee(array[index], index, array) === false) {
  1189. break;
  1190. }
  1191. }
  1192. return array;
  1193. }
  1194. var _arrayEach = arrayEach;
  1195. /**
  1196. * The base implementation of `_.findIndex` and `_.findLastIndex` without
  1197. * support for iteratee shorthands.
  1198. *
  1199. * @private
  1200. * @param {Array} array The array to inspect.
  1201. * @param {Function} predicate The function invoked per iteration.
  1202. * @param {number} fromIndex The index to search from.
  1203. * @param {boolean} [fromRight] Specify iterating from right to left.
  1204. * @returns {number} Returns the index of the matched value, else `-1`.
  1205. */
  1206. function baseFindIndex(array, predicate, fromIndex, fromRight) {
  1207. var length = array.length,
  1208. index = fromIndex + (fromRight ? 1 : -1);
  1209. while ((fromRight ? index-- : ++index < length)) {
  1210. if (predicate(array[index], index, array)) {
  1211. return index;
  1212. }
  1213. }
  1214. return -1;
  1215. }
  1216. var _baseFindIndex = baseFindIndex;
  1217. /**
  1218. * The base implementation of `_.isNaN` without support for number objects.
  1219. *
  1220. * @private
  1221. * @param {*} value The value to check.
  1222. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
  1223. */
  1224. function baseIsNaN(value) {
  1225. return value !== value;
  1226. }
  1227. var _baseIsNaN = baseIsNaN;
  1228. /**
  1229. * A specialized version of `_.indexOf` which performs strict equality
  1230. * comparisons of values, i.e. `===`.
  1231. *
  1232. * @private
  1233. * @param {Array} array The array to inspect.
  1234. * @param {*} value The value to search for.
  1235. * @param {number} fromIndex The index to search from.
  1236. * @returns {number} Returns the index of the matched value, else `-1`.
  1237. */
  1238. function strictIndexOf(array, value, fromIndex) {
  1239. var index = fromIndex - 1,
  1240. length = array.length;
  1241. while (++index < length) {
  1242. if (array[index] === value) {
  1243. return index;
  1244. }
  1245. }
  1246. return -1;
  1247. }
  1248. var _strictIndexOf = strictIndexOf;
  1249. /**
  1250. * The base implementation of `_.indexOf` without `fromIndex` bounds checks.
  1251. *
  1252. * @private
  1253. * @param {Array} array The array to inspect.
  1254. * @param {*} value The value to search for.
  1255. * @param {number} fromIndex The index to search from.
  1256. * @returns {number} Returns the index of the matched value, else `-1`.
  1257. */
  1258. function baseIndexOf(array, value, fromIndex) {
  1259. return value === value
  1260. ? _strictIndexOf(array, value, fromIndex)
  1261. : _baseFindIndex(array, _baseIsNaN, fromIndex);
  1262. }
  1263. var _baseIndexOf = baseIndexOf;
  1264. /**
  1265. * A specialized version of `_.includes` for arrays without support for
  1266. * specifying an index to search from.
  1267. *
  1268. * @private
  1269. * @param {Array} [array] The array to inspect.
  1270. * @param {*} target The value to search for.
  1271. * @returns {boolean} Returns `true` if `target` is found, else `false`.
  1272. */
  1273. function arrayIncludes(array, value) {
  1274. var length = array == null ? 0 : array.length;
  1275. return !!length && _baseIndexOf(array, value, 0) > -1;
  1276. }
  1277. var _arrayIncludes = arrayIncludes;
  1278. /** Used to compose bitmasks for function metadata. */
  1279. var WRAP_BIND_FLAG$5 = 1,
  1280. WRAP_BIND_KEY_FLAG$4 = 2,
  1281. WRAP_CURRY_FLAG$4 = 8,
  1282. WRAP_CURRY_RIGHT_FLAG$2 = 16,
  1283. WRAP_PARTIAL_FLAG$2 = 32,
  1284. WRAP_PARTIAL_RIGHT_FLAG$2 = 64,
  1285. WRAP_ARY_FLAG$3 = 128,
  1286. WRAP_REARG_FLAG$2 = 256,
  1287. WRAP_FLIP_FLAG$1 = 512;
  1288. /** Used to associate wrap methods with their bit flags. */
  1289. var wrapFlags = [
  1290. ['ary', WRAP_ARY_FLAG$3],
  1291. ['bind', WRAP_BIND_FLAG$5],
  1292. ['bindKey', WRAP_BIND_KEY_FLAG$4],
  1293. ['curry', WRAP_CURRY_FLAG$4],
  1294. ['curryRight', WRAP_CURRY_RIGHT_FLAG$2],
  1295. ['flip', WRAP_FLIP_FLAG$1],
  1296. ['partial', WRAP_PARTIAL_FLAG$2],
  1297. ['partialRight', WRAP_PARTIAL_RIGHT_FLAG$2],
  1298. ['rearg', WRAP_REARG_FLAG$2]
  1299. ];
  1300. /**
  1301. * Updates wrapper `details` based on `bitmask` flags.
  1302. *
  1303. * @private
  1304. * @returns {Array} details The details to modify.
  1305. * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
  1306. * @returns {Array} Returns `details`.
  1307. */
  1308. function updateWrapDetails(details, bitmask) {
  1309. _arrayEach(wrapFlags, function(pair) {
  1310. var value = '_.' + pair[0];
  1311. if ((bitmask & pair[1]) && !_arrayIncludes(details, value)) {
  1312. details.push(value);
  1313. }
  1314. });
  1315. return details.sort();
  1316. }
  1317. var _updateWrapDetails = updateWrapDetails;
  1318. /**
  1319. * Sets the `toString` method of `wrapper` to mimic the source of `reference`
  1320. * with wrapper details in a comment at the top of the source body.
  1321. *
  1322. * @private
  1323. * @param {Function} wrapper The function to modify.
  1324. * @param {Function} reference The reference function.
  1325. * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
  1326. * @returns {Function} Returns `wrapper`.
  1327. */
  1328. function setWrapToString(wrapper, reference, bitmask) {
  1329. var source = (reference + '');
  1330. return _setToString(wrapper, _insertWrapDetails(source, _updateWrapDetails(_getWrapDetails(source), bitmask)));
  1331. }
  1332. var _setWrapToString = setWrapToString;
  1333. /** Used to compose bitmasks for function metadata. */
  1334. var WRAP_BIND_FLAG$4 = 1,
  1335. WRAP_BIND_KEY_FLAG$3 = 2,
  1336. WRAP_CURRY_BOUND_FLAG$1 = 4,
  1337. WRAP_CURRY_FLAG$3 = 8,
  1338. WRAP_PARTIAL_FLAG$1 = 32,
  1339. WRAP_PARTIAL_RIGHT_FLAG$1 = 64;
  1340. /**
  1341. * Creates a function that wraps `func` to continue currying.
  1342. *
  1343. * @private
  1344. * @param {Function} func The function to wrap.
  1345. * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
  1346. * @param {Function} wrapFunc The function to create the `func` wrapper.
  1347. * @param {*} placeholder The placeholder value.
  1348. * @param {*} [thisArg] The `this` binding of `func`.
  1349. * @param {Array} [partials] The arguments to prepend to those provided to
  1350. * the new function.
  1351. * @param {Array} [holders] The `partials` placeholder indexes.
  1352. * @param {Array} [argPos] The argument positions of the new function.
  1353. * @param {number} [ary] The arity cap of `func`.
  1354. * @param {number} [arity] The arity of `func`.
  1355. * @returns {Function} Returns the new wrapped function.
  1356. */
  1357. function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) {
  1358. var isCurry = bitmask & WRAP_CURRY_FLAG$3,
  1359. newHolders = isCurry ? holders : undefined,
  1360. newHoldersRight = isCurry ? undefined : holders,
  1361. newPartials = isCurry ? partials : undefined,
  1362. newPartialsRight = isCurry ? undefined : partials;
  1363. bitmask |= (isCurry ? WRAP_PARTIAL_FLAG$1 : WRAP_PARTIAL_RIGHT_FLAG$1);
  1364. bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG$1 : WRAP_PARTIAL_FLAG$1);
  1365. if (!(bitmask & WRAP_CURRY_BOUND_FLAG$1)) {
  1366. bitmask &= ~(WRAP_BIND_FLAG$4 | WRAP_BIND_KEY_FLAG$3);
  1367. }
  1368. var newData = [
  1369. func, bitmask, thisArg, newPartials, newHolders, newPartialsRight,
  1370. newHoldersRight, argPos, ary, arity
  1371. ];
  1372. var result = wrapFunc.apply(undefined, newData);
  1373. if (_isLaziable(func)) {
  1374. _setData(result, newData);
  1375. }
  1376. result.placeholder = placeholder;
  1377. return _setWrapToString(result, func, bitmask);
  1378. }
  1379. var _createRecurry = createRecurry;
  1380. /**
  1381. * Gets the argument placeholder value for `func`.
  1382. *
  1383. * @private
  1384. * @param {Function} func The function to inspect.
  1385. * @returns {*} Returns the placeholder value.
  1386. */
  1387. function getHolder(func) {
  1388. var object = func;
  1389. return object.placeholder;
  1390. }
  1391. var _getHolder = getHolder;
  1392. /** Used as references for various `Number` constants. */
  1393. var MAX_SAFE_INTEGER$1 = 9007199254740991;
  1394. /** Used to detect unsigned integer values. */
  1395. var reIsUint = /^(?:0|[1-9]\d*)$/;
  1396. /**
  1397. * Checks if `value` is a valid array-like index.
  1398. *
  1399. * @private
  1400. * @param {*} value The value to check.
  1401. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
  1402. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
  1403. */
  1404. function isIndex(value, length) {
  1405. var type = typeof value;
  1406. length = length == null ? MAX_SAFE_INTEGER$1 : length;
  1407. return !!length &&
  1408. (type == 'number' ||
  1409. (type != 'symbol' && reIsUint.test(value))) &&
  1410. (value > -1 && value % 1 == 0 && value < length);
  1411. }
  1412. var _isIndex = isIndex;
  1413. /* Built-in method references for those with the same name as other `lodash` methods. */
  1414. var nativeMin$1 = Math.min;
  1415. /**
  1416. * Reorder `array` according to the specified indexes where the element at
  1417. * the first index is assigned as the first element, the element at
  1418. * the second index is assigned as the second element, and so on.
  1419. *
  1420. * @private
  1421. * @param {Array} array The array to reorder.
  1422. * @param {Array} indexes The arranged array indexes.
  1423. * @returns {Array} Returns `array`.
  1424. */
  1425. function reorder(array, indexes) {
  1426. var arrLength = array.length,
  1427. length = nativeMin$1(indexes.length, arrLength),
  1428. oldArray = _copyArray(array);
  1429. while (length--) {
  1430. var index = indexes[length];
  1431. array[length] = _isIndex(index, arrLength) ? oldArray[index] : undefined;
  1432. }
  1433. return array;
  1434. }
  1435. var _reorder = reorder;
  1436. /** Used as the internal argument placeholder. */
  1437. var PLACEHOLDER$1 = '__lodash_placeholder__';
  1438. /**
  1439. * Replaces all `placeholder` elements in `array` with an internal placeholder
  1440. * and returns an array of their indexes.
  1441. *
  1442. * @private
  1443. * @param {Array} array The array to modify.
  1444. * @param {*} placeholder The placeholder to replace.
  1445. * @returns {Array} Returns the new array of placeholder indexes.
  1446. */
  1447. function replaceHolders(array, placeholder) {
  1448. var index = -1,
  1449. length = array.length,
  1450. resIndex = 0,
  1451. result = [];
  1452. while (++index < length) {
  1453. var value = array[index];
  1454. if (value === placeholder || value === PLACEHOLDER$1) {
  1455. array[index] = PLACEHOLDER$1;
  1456. result[resIndex++] = index;
  1457. }
  1458. }
  1459. return result;
  1460. }
  1461. var _replaceHolders = replaceHolders;
  1462. /** Used to compose bitmasks for function metadata. */
  1463. var WRAP_BIND_FLAG$3 = 1,
  1464. WRAP_BIND_KEY_FLAG$2 = 2,
  1465. WRAP_CURRY_FLAG$2 = 8,
  1466. WRAP_CURRY_RIGHT_FLAG$1 = 16,
  1467. WRAP_ARY_FLAG$2 = 128,
  1468. WRAP_FLIP_FLAG = 512;
  1469. /**
  1470. * Creates a function that wraps `func` to invoke it with optional `this`
  1471. * binding of `thisArg`, partial application, and currying.
  1472. *
  1473. * @private
  1474. * @param {Function|string} func The function or method name to wrap.
  1475. * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
  1476. * @param {*} [thisArg] The `this` binding of `func`.
  1477. * @param {Array} [partials] The arguments to prepend to those provided to
  1478. * the new function.
  1479. * @param {Array} [holders] The `partials` placeholder indexes.
  1480. * @param {Array} [partialsRight] The arguments to append to those provided
  1481. * to the new function.
  1482. * @param {Array} [holdersRight] The `partialsRight` placeholder indexes.
  1483. * @param {Array} [argPos] The argument positions of the new function.
  1484. * @param {number} [ary] The arity cap of `func`.
  1485. * @param {number} [arity] The arity of `func`.
  1486. * @returns {Function} Returns the new wrapped function.
  1487. */
  1488. function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {
  1489. var isAry = bitmask & WRAP_ARY_FLAG$2,
  1490. isBind = bitmask & WRAP_BIND_FLAG$3,
  1491. isBindKey = bitmask & WRAP_BIND_KEY_FLAG$2,
  1492. isCurried = bitmask & (WRAP_CURRY_FLAG$2 | WRAP_CURRY_RIGHT_FLAG$1),
  1493. isFlip = bitmask & WRAP_FLIP_FLAG,
  1494. Ctor = isBindKey ? undefined : _createCtor(func);
  1495. function wrapper() {
  1496. var length = arguments.length,
  1497. args = Array(length),
  1498. index = length;
  1499. while (index--) {
  1500. args[index] = arguments[index];
  1501. }
  1502. if (isCurried) {
  1503. var placeholder = _getHolder(wrapper),
  1504. holdersCount = _countHolders(args, placeholder);
  1505. }
  1506. if (partials) {
  1507. args = _composeArgs(args, partials, holders, isCurried);
  1508. }
  1509. if (partialsRight) {
  1510. args = _composeArgsRight(args, partialsRight, holdersRight, isCurried);
  1511. }
  1512. length -= holdersCount;
  1513. if (isCurried && length < arity) {
  1514. var newHolders = _replaceHolders(args, placeholder);
  1515. return _createRecurry(
  1516. func, bitmask, createHybrid, wrapper.placeholder, thisArg,
  1517. args, newHolders, argPos, ary, arity - length
  1518. );
  1519. }
  1520. var thisBinding = isBind ? thisArg : this,
  1521. fn = isBindKey ? thisBinding[func] : func;
  1522. length = args.length;
  1523. if (argPos) {
  1524. args = _reorder(args, argPos);
  1525. } else if (isFlip && length > 1) {
  1526. args.reverse();
  1527. }
  1528. if (isAry && ary < length) {
  1529. args.length = ary;
  1530. }
  1531. if (this && this !== _root && this instanceof wrapper) {
  1532. fn = Ctor || _createCtor(fn);
  1533. }
  1534. return fn.apply(thisBinding, args);
  1535. }
  1536. return wrapper;
  1537. }
  1538. var _createHybrid = createHybrid;
  1539. /**
  1540. * Creates a function that wraps `func` to enable currying.
  1541. *
  1542. * @private
  1543. * @param {Function} func The function to wrap.
  1544. * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
  1545. * @param {number} arity The arity of `func`.
  1546. * @returns {Function} Returns the new wrapped function.
  1547. */
  1548. function createCurry(func, bitmask, arity) {
  1549. var Ctor = _createCtor(func);
  1550. function wrapper() {
  1551. var length = arguments.length,
  1552. args = Array(length),
  1553. index = length,
  1554. placeholder = _getHolder(wrapper);
  1555. while (index--) {
  1556. args[index] = arguments[index];
  1557. }
  1558. var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder)
  1559. ? []
  1560. : _replaceHolders(args, placeholder);
  1561. length -= holders.length;
  1562. if (length < arity) {
  1563. return _createRecurry(
  1564. func, bitmask, _createHybrid, wrapper.placeholder, undefined,
  1565. args, holders, undefined, undefined, arity - length);
  1566. }
  1567. var fn = (this && this !== _root && this instanceof wrapper) ? Ctor : func;
  1568. return _apply(fn, this, args);
  1569. }
  1570. return wrapper;
  1571. }
  1572. var _createCurry = createCurry;
  1573. /** Used to compose bitmasks for function metadata. */
  1574. var WRAP_BIND_FLAG$2 = 1;
  1575. /**
  1576. * Creates a function that wraps `func` to invoke it with the `this` binding
  1577. * of `thisArg` and `partials` prepended to the arguments it receives.
  1578. *
  1579. * @private
  1580. * @param {Function} func The function to wrap.
  1581. * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
  1582. * @param {*} thisArg The `this` binding of `func`.
  1583. * @param {Array} partials The arguments to prepend to those provided to
  1584. * the new function.
  1585. * @returns {Function} Returns the new wrapped function.
  1586. */
  1587. function createPartial(func, bitmask, thisArg, partials) {
  1588. var isBind = bitmask & WRAP_BIND_FLAG$2,
  1589. Ctor = _createCtor(func);
  1590. function wrapper() {
  1591. var argsIndex = -1,
  1592. argsLength = arguments.length,
  1593. leftIndex = -1,
  1594. leftLength = partials.length,
  1595. args = Array(leftLength + argsLength),
  1596. fn = (this && this !== _root && this instanceof wrapper) ? Ctor : func;
  1597. while (++leftIndex < leftLength) {
  1598. args[leftIndex] = partials[leftIndex];
  1599. }
  1600. while (argsLength--) {
  1601. args[leftIndex++] = arguments[++argsIndex];
  1602. }
  1603. return _apply(fn, isBind ? thisArg : this, args);
  1604. }
  1605. return wrapper;
  1606. }
  1607. var _createPartial = createPartial;
  1608. /** Used as the internal argument placeholder. */
  1609. var PLACEHOLDER = '__lodash_placeholder__';
  1610. /** Used to compose bitmasks for function metadata. */
  1611. var WRAP_BIND_FLAG$1 = 1,
  1612. WRAP_BIND_KEY_FLAG$1 = 2,
  1613. WRAP_CURRY_BOUND_FLAG = 4,
  1614. WRAP_CURRY_FLAG$1 = 8,
  1615. WRAP_ARY_FLAG$1 = 128,
  1616. WRAP_REARG_FLAG$1 = 256;
  1617. /* Built-in method references for those with the same name as other `lodash` methods. */
  1618. var nativeMin = Math.min;
  1619. /**
  1620. * Merges the function metadata of `source` into `data`.
  1621. *
  1622. * Merging metadata reduces the number of wrappers used to invoke a function.
  1623. * This is possible because methods like `_.bind`, `_.curry`, and `_.partial`
  1624. * may be applied regardless of execution order. Methods like `_.ary` and
  1625. * `_.rearg` modify function arguments, making the order in which they are
  1626. * executed important, preventing the merging of metadata. However, we make
  1627. * an exception for a safe combined case where curried functions have `_.ary`
  1628. * and or `_.rearg` applied.
  1629. *
  1630. * @private
  1631. * @param {Array} data The destination metadata.
  1632. * @param {Array} source The source metadata.
  1633. * @returns {Array} Returns `data`.
  1634. */
  1635. function mergeData(data, source) {
  1636. var bitmask = data[1],
  1637. srcBitmask = source[1],
  1638. newBitmask = bitmask | srcBitmask,
  1639. isCommon = newBitmask < (WRAP_BIND_FLAG$1 | WRAP_BIND_KEY_FLAG$1 | WRAP_ARY_FLAG$1);
  1640. var isCombo =
  1641. ((srcBitmask == WRAP_ARY_FLAG$1) && (bitmask == WRAP_CURRY_FLAG$1)) ||
  1642. ((srcBitmask == WRAP_ARY_FLAG$1) && (bitmask == WRAP_REARG_FLAG$1) && (data[7].length <= source[8])) ||
  1643. ((srcBitmask == (WRAP_ARY_FLAG$1 | WRAP_REARG_FLAG$1)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG$1));
  1644. // Exit early if metadata can't be merged.
  1645. if (!(isCommon || isCombo)) {
  1646. return data;
  1647. }
  1648. // Use source `thisArg` if available.
  1649. if (srcBitmask & WRAP_BIND_FLAG$1) {
  1650. data[2] = source[2];
  1651. // Set when currying a bound function.
  1652. newBitmask |= bitmask & WRAP_BIND_FLAG$1 ? 0 : WRAP_CURRY_BOUND_FLAG;
  1653. }
  1654. // Compose partial arguments.
  1655. var value = source[3];
  1656. if (value) {
  1657. var partials = data[3];
  1658. data[3] = partials ? _composeArgs(partials, value, source[4]) : value;
  1659. data[4] = partials ? _replaceHolders(data[3], PLACEHOLDER) : source[4];
  1660. }
  1661. // Compose partial right arguments.
  1662. value = source[5];
  1663. if (value) {
  1664. partials = data[5];
  1665. data[5] = partials ? _composeArgsRight(partials, value, source[6]) : value;
  1666. data[6] = partials ? _replaceHolders(data[5], PLACEHOLDER) : source[6];
  1667. }
  1668. // Use source `argPos` if available.
  1669. value = source[7];
  1670. if (value) {
  1671. data[7] = value;
  1672. }
  1673. // Use source `ary` if it's smaller.
  1674. if (srcBitmask & WRAP_ARY_FLAG$1) {
  1675. data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]);
  1676. }
  1677. // Use source `arity` if one is not provided.
  1678. if (data[9] == null) {
  1679. data[9] = source[9];
  1680. }
  1681. // Use source `func` and merge bitmasks.
  1682. data[0] = source[0];
  1683. data[1] = newBitmask;
  1684. return data;
  1685. }
  1686. var _mergeData = mergeData;
  1687. /** Used to match a single whitespace character. */
  1688. var reWhitespace = /\s/;
  1689. /**
  1690. * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace
  1691. * character of `string`.
  1692. *
  1693. * @private
  1694. * @param {string} string The string to inspect.
  1695. * @returns {number} Returns the index of the last non-whitespace character.
  1696. */
  1697. function trimmedEndIndex(string) {
  1698. var index = string.length;
  1699. while (index-- && reWhitespace.test(string.charAt(index))) {}
  1700. return index;
  1701. }
  1702. var _trimmedEndIndex = trimmedEndIndex;
  1703. /** Used to match leading whitespace. */
  1704. var reTrimStart = /^\s+/;
  1705. /**
  1706. * The base implementation of `_.trim`.
  1707. *
  1708. * @private
  1709. * @param {string} string The string to trim.
  1710. * @returns {string} Returns the trimmed string.
  1711. */
  1712. function baseTrim(string) {
  1713. return string
  1714. ? string.slice(0, _trimmedEndIndex(string) + 1).replace(reTrimStart, '')
  1715. : string;
  1716. }
  1717. var _baseTrim = baseTrim;
  1718. /** `Object#toString` result references. */
  1719. var symbolTag$3 = '[object Symbol]';
  1720. /**
  1721. * Checks if `value` is classified as a `Symbol` primitive or object.
  1722. *
  1723. * @static
  1724. * @memberOf _
  1725. * @since 4.0.0
  1726. * @category Lang
  1727. * @param {*} value The value to check.
  1728. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
  1729. * @example
  1730. *
  1731. * _.isSymbol(Symbol.iterator);
  1732. * // => true
  1733. *
  1734. * _.isSymbol('abc');
  1735. * // => false
  1736. */
  1737. function isSymbol(value) {
  1738. return typeof value == 'symbol' ||
  1739. (isObjectLike_1(value) && _baseGetTag(value) == symbolTag$3);
  1740. }
  1741. var isSymbol_1 = isSymbol;
  1742. /** Used as references for various `Number` constants. */
  1743. var NAN = 0 / 0;
  1744. /** Used to detect bad signed hexadecimal string values. */
  1745. var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
  1746. /** Used to detect binary string values. */
  1747. var reIsBinary = /^0b[01]+$/i;
  1748. /** Used to detect octal string values. */
  1749. var reIsOctal = /^0o[0-7]+$/i;
  1750. /** Built-in method references without a dependency on `root`. */
  1751. var freeParseInt = parseInt;
  1752. /**
  1753. * Converts `value` to a number.
  1754. *
  1755. * @static
  1756. * @memberOf _
  1757. * @since 4.0.0
  1758. * @category Lang
  1759. * @param {*} value The value to process.
  1760. * @returns {number} Returns the number.
  1761. * @example
  1762. *
  1763. * _.toNumber(3.2);
  1764. * // => 3.2
  1765. *
  1766. * _.toNumber(Number.MIN_VALUE);
  1767. * // => 5e-324
  1768. *
  1769. * _.toNumber(Infinity);
  1770. * // => Infinity
  1771. *
  1772. * _.toNumber('3.2');
  1773. * // => 3.2
  1774. */
  1775. function toNumber(value) {
  1776. if (typeof value == 'number') {
  1777. return value;
  1778. }
  1779. if (isSymbol_1(value)) {
  1780. return NAN;
  1781. }
  1782. if (isObject_1(value)) {
  1783. var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
  1784. value = isObject_1(other) ? (other + '') : other;
  1785. }
  1786. if (typeof value != 'string') {
  1787. return value === 0 ? value : +value;
  1788. }
  1789. value = _baseTrim(value);
  1790. var isBinary = reIsBinary.test(value);
  1791. return (isBinary || reIsOctal.test(value))
  1792. ? freeParseInt(value.slice(2), isBinary ? 2 : 8)
  1793. : (reIsBadHex.test(value) ? NAN : +value);
  1794. }
  1795. var toNumber_1 = toNumber;
  1796. /** Used as references for various `Number` constants. */
  1797. var INFINITY$2 = 1 / 0,
  1798. MAX_INTEGER = 1.7976931348623157e+308;
  1799. /**
  1800. * Converts `value` to a finite number.
  1801. *
  1802. * @static
  1803. * @memberOf _
  1804. * @since 4.12.0
  1805. * @category Lang
  1806. * @param {*} value The value to convert.
  1807. * @returns {number} Returns the converted number.
  1808. * @example
  1809. *
  1810. * _.toFinite(3.2);
  1811. * // => 3.2
  1812. *
  1813. * _.toFinite(Number.MIN_VALUE);
  1814. * // => 5e-324
  1815. *
  1816. * _.toFinite(Infinity);
  1817. * // => 1.7976931348623157e+308
  1818. *
  1819. * _.toFinite('3.2');
  1820. * // => 3.2
  1821. */
  1822. function toFinite(value) {
  1823. if (!value) {
  1824. return value === 0 ? value : 0;
  1825. }
  1826. value = toNumber_1(value);
  1827. if (value === INFINITY$2 || value === -INFINITY$2) {
  1828. var sign = (value < 0 ? -1 : 1);
  1829. return sign * MAX_INTEGER;
  1830. }
  1831. return value === value ? value : 0;
  1832. }
  1833. var toFinite_1 = toFinite;
  1834. /**
  1835. * Converts `value` to an integer.
  1836. *
  1837. * **Note:** This method is loosely based on
  1838. * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).
  1839. *
  1840. * @static
  1841. * @memberOf _
  1842. * @since 4.0.0
  1843. * @category Lang
  1844. * @param {*} value The value to convert.
  1845. * @returns {number} Returns the converted integer.
  1846. * @example
  1847. *
  1848. * _.toInteger(3.2);
  1849. * // => 3
  1850. *
  1851. * _.toInteger(Number.MIN_VALUE);
  1852. * // => 0
  1853. *
  1854. * _.toInteger(Infinity);
  1855. * // => 1.7976931348623157e+308
  1856. *
  1857. * _.toInteger('3.2');
  1858. * // => 3
  1859. */
  1860. function toInteger(value) {
  1861. var result = toFinite_1(value),
  1862. remainder = result % 1;
  1863. return result === result ? (remainder ? result - remainder : result) : 0;
  1864. }
  1865. var toInteger_1 = toInteger;
  1866. /** Error message constants. */
  1867. var FUNC_ERROR_TEXT$1 = 'Expected a function';
  1868. /** Used to compose bitmasks for function metadata. */
  1869. var WRAP_BIND_FLAG = 1,
  1870. WRAP_BIND_KEY_FLAG = 2,
  1871. WRAP_CURRY_FLAG = 8,
  1872. WRAP_CURRY_RIGHT_FLAG = 16,
  1873. WRAP_PARTIAL_FLAG = 32,
  1874. WRAP_PARTIAL_RIGHT_FLAG = 64;
  1875. /* Built-in method references for those with the same name as other `lodash` methods. */
  1876. var nativeMax$1 = Math.max;
  1877. /**
  1878. * Creates a function that either curries or invokes `func` with optional
  1879. * `this` binding and partially applied arguments.
  1880. *
  1881. * @private
  1882. * @param {Function|string} func The function or method name to wrap.
  1883. * @param {number} bitmask The bitmask flags.
  1884. * 1 - `_.bind`
  1885. * 2 - `_.bindKey`
  1886. * 4 - `_.curry` or `_.curryRight` of a bound function
  1887. * 8 - `_.curry`
  1888. * 16 - `_.curryRight`
  1889. * 32 - `_.partial`
  1890. * 64 - `_.partialRight`
  1891. * 128 - `_.rearg`
  1892. * 256 - `_.ary`
  1893. * 512 - `_.flip`
  1894. * @param {*} [thisArg] The `this` binding of `func`.
  1895. * @param {Array} [partials] The arguments to be partially applied.
  1896. * @param {Array} [holders] The `partials` placeholder indexes.
  1897. * @param {Array} [argPos] The argument positions of the new function.
  1898. * @param {number} [ary] The arity cap of `func`.
  1899. * @param {number} [arity] The arity of `func`.
  1900. * @returns {Function} Returns the new wrapped function.
  1901. */
  1902. function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {
  1903. var isBindKey = bitmask & WRAP_BIND_KEY_FLAG;
  1904. if (!isBindKey && typeof func != 'function') {
  1905. throw new TypeError(FUNC_ERROR_TEXT$1);
  1906. }
  1907. var length = partials ? partials.length : 0;
  1908. if (!length) {
  1909. bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG);
  1910. partials = holders = undefined;
  1911. }
  1912. ary = ary === undefined ? ary : nativeMax$1(toInteger_1(ary), 0);
  1913. arity = arity === undefined ? arity : toInteger_1(arity);
  1914. length -= holders ? holders.length : 0;
  1915. if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) {
  1916. var partialsRight = partials,
  1917. holdersRight = holders;
  1918. partials = holders = undefined;
  1919. }
  1920. var data = isBindKey ? undefined : _getData(func);
  1921. var newData = [
  1922. func, bitmask, thisArg, partials, holders, partialsRight, holdersRight,
  1923. argPos, ary, arity
  1924. ];
  1925. if (data) {
  1926. _mergeData(newData, data);
  1927. }
  1928. func = newData[0];
  1929. bitmask = newData[1];
  1930. thisArg = newData[2];
  1931. partials = newData[3];
  1932. holders = newData[4];
  1933. arity = newData[9] = newData[9] === undefined
  1934. ? (isBindKey ? 0 : func.length)
  1935. : nativeMax$1(newData[9] - length, 0);
  1936. if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) {
  1937. bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG);
  1938. }
  1939. if (!bitmask || bitmask == WRAP_BIND_FLAG) {
  1940. var result = _createBind(func, bitmask, thisArg);
  1941. } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) {
  1942. result = _createCurry(func, bitmask, arity);
  1943. } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) {
  1944. result = _createPartial(func, bitmask, thisArg, partials);
  1945. } else {
  1946. result = _createHybrid.apply(undefined, newData);
  1947. }
  1948. var setter = data ? _baseSetData : _setData;
  1949. return _setWrapToString(setter(result, newData), func, bitmask);
  1950. }
  1951. var _createWrap = createWrap;
  1952. commonjsRegister("/$$rollup_base$$/node_modules/lodash/curry.js", function (module, exports) {
  1953. var createWrap = _createWrap;
  1954. /** Used to compose bitmasks for function metadata. */
  1955. var WRAP_CURRY_FLAG = 8;
  1956. /**
  1957. * Creates a function that accepts arguments of `func` and either invokes
  1958. * `func` returning its result, if at least `arity` number of arguments have
  1959. * been provided, or returns a function that accepts the remaining `func`
  1960. * arguments, and so on. The arity of `func` may be specified if `func.length`
  1961. * is not sufficient.
  1962. *
  1963. * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds,
  1964. * may be used as a placeholder for provided arguments.
  1965. *
  1966. * **Note:** This method doesn't set the "length" property of curried functions.
  1967. *
  1968. * @static
  1969. * @memberOf _
  1970. * @since 2.0.0
  1971. * @category Function
  1972. * @param {Function} func The function to curry.
  1973. * @param {number} [arity=func.length] The arity of `func`.
  1974. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  1975. * @returns {Function} Returns the new curried function.
  1976. * @example
  1977. *
  1978. * var abc = function(a, b, c) {
  1979. * return [a, b, c];
  1980. * };
  1981. *
  1982. * var curried = _.curry(abc);
  1983. *
  1984. * curried(1)(2)(3);
  1985. * // => [1, 2, 3]
  1986. *
  1987. * curried(1, 2)(3);
  1988. * // => [1, 2, 3]
  1989. *
  1990. * curried(1, 2, 3);
  1991. * // => [1, 2, 3]
  1992. *
  1993. * // Curried with placeholders.
  1994. * curried(1)(_, 3)(2);
  1995. * // => [1, 2, 3]
  1996. */
  1997. function curry(func, arity, guard) {
  1998. arity = guard ? undefined : arity;
  1999. var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity);
  2000. result.placeholder = curry.placeholder;
  2001. return result;
  2002. }
  2003. // Assign default placeholders.
  2004. curry.placeholder = {};
  2005. module.exports = curry;
  2006. });
  2007. commonjsRegister("/$$rollup_base$$/node_modules/lodash/curryRight.js", function (module, exports) {
  2008. var createWrap = _createWrap;
  2009. /** Used to compose bitmasks for function metadata. */
  2010. var WRAP_CURRY_RIGHT_FLAG = 16;
  2011. /**
  2012. * This method is like `_.curry` except that arguments are applied to `func`
  2013. * in the manner of `_.partialRight` instead of `_.partial`.
  2014. *
  2015. * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic
  2016. * builds, may be used as a placeholder for provided arguments.
  2017. *
  2018. * **Note:** This method doesn't set the "length" property of curried functions.
  2019. *
  2020. * @static
  2021. * @memberOf _
  2022. * @since 3.0.0
  2023. * @category Function
  2024. * @param {Function} func The function to curry.
  2025. * @param {number} [arity=func.length] The arity of `func`.
  2026. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  2027. * @returns {Function} Returns the new curried function.
  2028. * @example
  2029. *
  2030. * var abc = function(a, b, c) {
  2031. * return [a, b, c];
  2032. * };
  2033. *
  2034. * var curried = _.curryRight(abc);
  2035. *
  2036. * curried(3)(2)(1);
  2037. * // => [1, 2, 3]
  2038. *
  2039. * curried(2, 3)(1);
  2040. * // => [1, 2, 3]
  2041. *
  2042. * curried(1, 2, 3);
  2043. * // => [1, 2, 3]
  2044. *
  2045. * // Curried with placeholders.
  2046. * curried(3)(1, _)(2);
  2047. * // => [1, 2, 3]
  2048. */
  2049. function curryRight(func, arity, guard) {
  2050. arity = guard ? undefined : arity;
  2051. var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity);
  2052. result.placeholder = curryRight.placeholder;
  2053. return result;
  2054. }
  2055. // Assign default placeholders.
  2056. curryRight.placeholder = {};
  2057. module.exports = curryRight;
  2058. });
  2059. /** Used to map aliases to their real names. */
  2060. var _mapping = createCommonjsModule(function (module, exports) {
  2061. exports.aliasToReal = {
  2062. // Lodash aliases.
  2063. 'each': 'forEach',
  2064. 'eachRight': 'forEachRight',
  2065. 'entries': 'toPairs',
  2066. 'entriesIn': 'toPairsIn',
  2067. 'extend': 'assignIn',
  2068. 'extendAll': 'assignInAll',
  2069. 'extendAllWith': 'assignInAllWith',
  2070. 'extendWith': 'assignInWith',
  2071. 'first': 'head',
  2072. // Methods that are curried variants of others.
  2073. 'conforms': 'conformsTo',
  2074. 'matches': 'isMatch',
  2075. 'property': 'get',
  2076. // Ramda aliases.
  2077. '__': 'placeholder',
  2078. 'F': 'stubFalse',
  2079. 'T': 'stubTrue',
  2080. 'all': 'every',
  2081. 'allPass': 'overEvery',
  2082. 'always': 'constant',
  2083. 'any': 'some',
  2084. 'anyPass': 'overSome',
  2085. 'apply': 'spread',
  2086. 'assoc': 'set',
  2087. 'assocPath': 'set',
  2088. 'complement': 'negate',
  2089. 'compose': 'flowRight',
  2090. 'contains': 'includes',
  2091. 'dissoc': 'unset',
  2092. 'dissocPath': 'unset',
  2093. 'dropLast': 'dropRight',
  2094. 'dropLastWhile': 'dropRightWhile',
  2095. 'equals': 'isEqual',
  2096. 'identical': 'eq',
  2097. 'indexBy': 'keyBy',
  2098. 'init': 'initial',
  2099. 'invertObj': 'invert',
  2100. 'juxt': 'over',
  2101. 'omitAll': 'omit',
  2102. 'nAry': 'ary',
  2103. 'path': 'get',
  2104. 'pathEq': 'matchesProperty',
  2105. 'pathOr': 'getOr',
  2106. 'paths': 'at',
  2107. 'pickAll': 'pick',
  2108. 'pipe': 'flow',
  2109. 'pluck': 'map',
  2110. 'prop': 'get',
  2111. 'propEq': 'matchesProperty',
  2112. 'propOr': 'getOr',
  2113. 'props': 'at',
  2114. 'symmetricDifference': 'xor',
  2115. 'symmetricDifferenceBy': 'xorBy',
  2116. 'symmetricDifferenceWith': 'xorWith',
  2117. 'takeLast': 'takeRight',
  2118. 'takeLastWhile': 'takeRightWhile',
  2119. 'unapply': 'rest',
  2120. 'unnest': 'flatten',
  2121. 'useWith': 'overArgs',
  2122. 'where': 'conformsTo',
  2123. 'whereEq': 'isMatch',
  2124. 'zipObj': 'zipObject'
  2125. };
  2126. /** Used to map ary to method names. */
  2127. exports.aryMethod = {
  2128. '1': [
  2129. 'assignAll', 'assignInAll', 'attempt', 'castArray', 'ceil', 'create',
  2130. 'curry', 'curryRight', 'defaultsAll', 'defaultsDeepAll', 'floor', 'flow',
  2131. 'flowRight', 'fromPairs', 'invert', 'iteratee', 'memoize', 'method', 'mergeAll',
  2132. 'methodOf', 'mixin', 'nthArg', 'over', 'overEvery', 'overSome','rest', 'reverse',
  2133. 'round', 'runInContext', 'spread', 'template', 'trim', 'trimEnd', 'trimStart',
  2134. 'uniqueId', 'words', 'zipAll'
  2135. ],
  2136. '2': [
  2137. 'add', 'after', 'ary', 'assign', 'assignAllWith', 'assignIn', 'assignInAllWith',
  2138. 'at', 'before', 'bind', 'bindAll', 'bindKey', 'chunk', 'cloneDeepWith',
  2139. 'cloneWith', 'concat', 'conformsTo', 'countBy', 'curryN', 'curryRightN',
  2140. 'debounce', 'defaults', 'defaultsDeep', 'defaultTo', 'delay', 'difference',
  2141. 'divide', 'drop', 'dropRight', 'dropRightWhile', 'dropWhile', 'endsWith', 'eq',
  2142. 'every', 'filter', 'find', 'findIndex', 'findKey', 'findLast', 'findLastIndex',
  2143. 'findLastKey', 'flatMap', 'flatMapDeep', 'flattenDepth', 'forEach',
  2144. 'forEachRight', 'forIn', 'forInRight', 'forOwn', 'forOwnRight', 'get',
  2145. 'groupBy', 'gt', 'gte', 'has', 'hasIn', 'includes', 'indexOf', 'intersection',
  2146. 'invertBy', 'invoke', 'invokeMap', 'isEqual', 'isMatch', 'join', 'keyBy',
  2147. 'lastIndexOf', 'lt', 'lte', 'map', 'mapKeys', 'mapValues', 'matchesProperty',
  2148. 'maxBy', 'meanBy', 'merge', 'mergeAllWith', 'minBy', 'multiply', 'nth', 'omit',
  2149. 'omitBy', 'overArgs', 'pad', 'padEnd', 'padStart', 'parseInt', 'partial',
  2150. 'partialRight', 'partition', 'pick', 'pickBy', 'propertyOf', 'pull', 'pullAll',
  2151. 'pullAt', 'random', 'range', 'rangeRight', 'rearg', 'reject', 'remove',
  2152. 'repeat', 'restFrom', 'result', 'sampleSize', 'some', 'sortBy', 'sortedIndex',
  2153. 'sortedIndexOf', 'sortedLastIndex', 'sortedLastIndexOf', 'sortedUniqBy',
  2154. 'split', 'spreadFrom', 'startsWith', 'subtract', 'sumBy', 'take', 'takeRight',
  2155. 'takeRightWhile', 'takeWhile', 'tap', 'throttle', 'thru', 'times', 'trimChars',
  2156. 'trimCharsEnd', 'trimCharsStart', 'truncate', 'union', 'uniqBy', 'uniqWith',
  2157. 'unset', 'unzipWith', 'without', 'wrap', 'xor', 'zip', 'zipObject',
  2158. 'zipObjectDeep'
  2159. ],
  2160. '3': [
  2161. 'assignInWith', 'assignWith', 'clamp', 'differenceBy', 'differenceWith',
  2162. 'findFrom', 'findIndexFrom', 'findLastFrom', 'findLastIndexFrom', 'getOr',
  2163. 'includesFrom', 'indexOfFrom', 'inRange', 'intersectionBy', 'intersectionWith',
  2164. 'invokeArgs', 'invokeArgsMap', 'isEqualWith', 'isMatchWith', 'flatMapDepth',
  2165. 'lastIndexOfFrom', 'mergeWith', 'orderBy', 'padChars', 'padCharsEnd',
  2166. 'padCharsStart', 'pullAllBy', 'pullAllWith', 'rangeStep', 'rangeStepRight',
  2167. 'reduce', 'reduceRight', 'replace', 'set', 'slice', 'sortedIndexBy',
  2168. 'sortedLastIndexBy', 'transform', 'unionBy', 'unionWith', 'update', 'xorBy',
  2169. 'xorWith', 'zipWith'
  2170. ],
  2171. '4': [
  2172. 'fill', 'setWith', 'updateWith'
  2173. ]
  2174. };
  2175. /** Used to map ary to rearg configs. */
  2176. exports.aryRearg = {
  2177. '2': [1, 0],
  2178. '3': [2, 0, 1],
  2179. '4': [3, 2, 0, 1]
  2180. };
  2181. /** Used to map method names to their iteratee ary. */
  2182. exports.iterateeAry = {
  2183. 'dropRightWhile': 1,
  2184. 'dropWhile': 1,
  2185. 'every': 1,
  2186. 'filter': 1,
  2187. 'find': 1,
  2188. 'findFrom': 1,
  2189. 'findIndex': 1,
  2190. 'findIndexFrom': 1,
  2191. 'findKey': 1,
  2192. 'findLast': 1,
  2193. 'findLastFrom': 1,
  2194. 'findLastIndex': 1,
  2195. 'findLastIndexFrom': 1,
  2196. 'findLastKey': 1,
  2197. 'flatMap': 1,
  2198. 'flatMapDeep': 1,
  2199. 'flatMapDepth': 1,
  2200. 'forEach': 1,
  2201. 'forEachRight': 1,
  2202. 'forIn': 1,
  2203. 'forInRight': 1,
  2204. 'forOwn': 1,
  2205. 'forOwnRight': 1,
  2206. 'map': 1,
  2207. 'mapKeys': 1,
  2208. 'mapValues': 1,
  2209. 'partition': 1,
  2210. 'reduce': 2,
  2211. 'reduceRight': 2,
  2212. 'reject': 1,
  2213. 'remove': 1,
  2214. 'some': 1,
  2215. 'takeRightWhile': 1,
  2216. 'takeWhile': 1,
  2217. 'times': 1,
  2218. 'transform': 2
  2219. };
  2220. /** Used to map method names to iteratee rearg configs. */
  2221. exports.iterateeRearg = {
  2222. 'mapKeys': [1],
  2223. 'reduceRight': [1, 0]
  2224. };
  2225. /** Used to map method names to rearg configs. */
  2226. exports.methodRearg = {
  2227. 'assignInAllWith': [1, 0],
  2228. 'assignInWith': [1, 2, 0],
  2229. 'assignAllWith': [1, 0],
  2230. 'assignWith': [1, 2, 0],
  2231. 'differenceBy': [1, 2, 0],
  2232. 'differenceWith': [1, 2, 0],
  2233. 'getOr': [2, 1, 0],
  2234. 'intersectionBy': [1, 2, 0],
  2235. 'intersectionWith': [1, 2, 0],
  2236. 'isEqualWith': [1, 2, 0],
  2237. 'isMatchWith': [2, 1, 0],
  2238. 'mergeAllWith': [1, 0],
  2239. 'mergeWith': [1, 2, 0],
  2240. 'padChars': [2, 1, 0],
  2241. 'padCharsEnd': [2, 1, 0],
  2242. 'padCharsStart': [2, 1, 0],
  2243. 'pullAllBy': [2, 1, 0],
  2244. 'pullAllWith': [2, 1, 0],
  2245. 'rangeStep': [1, 2, 0],
  2246. 'rangeStepRight': [1, 2, 0],
  2247. 'setWith': [3, 1, 2, 0],
  2248. 'sortedIndexBy': [2, 1, 0],
  2249. 'sortedLastIndexBy': [2, 1, 0],
  2250. 'unionBy': [1, 2, 0],
  2251. 'unionWith': [1, 2, 0],
  2252. 'updateWith': [3, 1, 2, 0],
  2253. 'xorBy': [1, 2, 0],
  2254. 'xorWith': [1, 2, 0],
  2255. 'zipWith': [1, 2, 0]
  2256. };
  2257. /** Used to map method names to spread configs. */
  2258. exports.methodSpread = {
  2259. 'assignAll': { 'start': 0 },
  2260. 'assignAllWith': { 'start': 0 },
  2261. 'assignInAll': { 'start': 0 },
  2262. 'assignInAllWith': { 'start': 0 },
  2263. 'defaultsAll': { 'start': 0 },
  2264. 'defaultsDeepAll': { 'start': 0 },
  2265. 'invokeArgs': { 'start': 2 },
  2266. 'invokeArgsMap': { 'start': 2 },
  2267. 'mergeAll': { 'start': 0 },
  2268. 'mergeAllWith': { 'start': 0 },
  2269. 'partial': { 'start': 1 },
  2270. 'partialRight': { 'start': 1 },
  2271. 'without': { 'start': 1 },
  2272. 'zipAll': { 'start': 0 }
  2273. };
  2274. /** Used to identify methods which mutate arrays or objects. */
  2275. exports.mutate = {
  2276. 'array': {
  2277. 'fill': true,
  2278. 'pull': true,
  2279. 'pullAll': true,
  2280. 'pullAllBy': true,
  2281. 'pullAllWith': true,
  2282. 'pullAt': true,
  2283. 'remove': true,
  2284. 'reverse': true
  2285. },
  2286. 'object': {
  2287. 'assign': true,
  2288. 'assignAll': true,
  2289. 'assignAllWith': true,
  2290. 'assignIn': true,
  2291. 'assignInAll': true,
  2292. 'assignInAllWith': true,
  2293. 'assignInWith': true,
  2294. 'assignWith': true,
  2295. 'defaults': true,
  2296. 'defaultsAll': true,
  2297. 'defaultsDeep': true,
  2298. 'defaultsDeepAll': true,
  2299. 'merge': true,
  2300. 'mergeAll': true,
  2301. 'mergeAllWith': true,
  2302. 'mergeWith': true,
  2303. },
  2304. 'set': {
  2305. 'set': true,
  2306. 'setWith': true,
  2307. 'unset': true,
  2308. 'update': true,
  2309. 'updateWith': true
  2310. }
  2311. };
  2312. /** Used to map real names to their aliases. */
  2313. exports.realToAlias = (function() {
  2314. var hasOwnProperty = Object.prototype.hasOwnProperty,
  2315. object = exports.aliasToReal,
  2316. result = {};
  2317. for (var key in object) {
  2318. var value = object[key];
  2319. if (hasOwnProperty.call(result, value)) {
  2320. result[value].push(key);
  2321. } else {
  2322. result[value] = [key];
  2323. }
  2324. }
  2325. return result;
  2326. }());
  2327. /** Used to map method names to other names. */
  2328. exports.remap = {
  2329. 'assignAll': 'assign',
  2330. 'assignAllWith': 'assignWith',
  2331. 'assignInAll': 'assignIn',
  2332. 'assignInAllWith': 'assignInWith',
  2333. 'curryN': 'curry',
  2334. 'curryRightN': 'curryRight',
  2335. 'defaultsAll': 'defaults',
  2336. 'defaultsDeepAll': 'defaultsDeep',
  2337. 'findFrom': 'find',
  2338. 'findIndexFrom': 'findIndex',
  2339. 'findLastFrom': 'findLast',
  2340. 'findLastIndexFrom': 'findLastIndex',
  2341. 'getOr': 'get',
  2342. 'includesFrom': 'includes',
  2343. 'indexOfFrom': 'indexOf',
  2344. 'invokeArgs': 'invoke',
  2345. 'invokeArgsMap': 'invokeMap',
  2346. 'lastIndexOfFrom': 'lastIndexOf',
  2347. 'mergeAll': 'merge',
  2348. 'mergeAllWith': 'mergeWith',
  2349. 'padChars': 'pad',
  2350. 'padCharsEnd': 'padEnd',
  2351. 'padCharsStart': 'padStart',
  2352. 'propertyOf': 'get',
  2353. 'rangeStep': 'range',
  2354. 'rangeStepRight': 'rangeRight',
  2355. 'restFrom': 'rest',
  2356. 'spreadFrom': 'spread',
  2357. 'trimChars': 'trim',
  2358. 'trimCharsEnd': 'trimEnd',
  2359. 'trimCharsStart': 'trimStart',
  2360. 'zipAll': 'zip'
  2361. };
  2362. /** Used to track methods that skip fixing their arity. */
  2363. exports.skipFixed = {
  2364. 'castArray': true,
  2365. 'flow': true,
  2366. 'flowRight': true,
  2367. 'iteratee': true,
  2368. 'mixin': true,
  2369. 'rearg': true,
  2370. 'runInContext': true
  2371. };
  2372. /** Used to track methods that skip rearranging arguments. */
  2373. exports.skipRearg = {
  2374. 'add': true,
  2375. 'assign': true,
  2376. 'assignIn': true,
  2377. 'bind': true,
  2378. 'bindKey': true,
  2379. 'concat': true,
  2380. 'difference': true,
  2381. 'divide': true,
  2382. 'eq': true,
  2383. 'gt': true,
  2384. 'gte': true,
  2385. 'isEqual': true,
  2386. 'lt': true,
  2387. 'lte': true,
  2388. 'matchesProperty': true,
  2389. 'merge': true,
  2390. 'multiply': true,
  2391. 'overArgs': true,
  2392. 'partial': true,
  2393. 'partialRight': true,
  2394. 'propertyOf': true,
  2395. 'random': true,
  2396. 'range': true,
  2397. 'rangeRight': true,
  2398. 'subtract': true,
  2399. 'zip': true,
  2400. 'zipObject': true,
  2401. 'zipObjectDeep': true
  2402. };
  2403. }, "/$$rollup_base$$/node_modules/lodash/fp");
  2404. /**
  2405. * The default argument placeholder value for methods.
  2406. *
  2407. * @type {Object}
  2408. */
  2409. var placeholder = {};
  2410. /** Built-in value reference. */
  2411. var push = Array.prototype.push;
  2412. /**
  2413. * Creates a function, with an arity of `n`, that invokes `func` with the
  2414. * arguments it receives.
  2415. *
  2416. * @private
  2417. * @param {Function} func The function to wrap.
  2418. * @param {number} n The arity of the new function.
  2419. * @returns {Function} Returns the new function.
  2420. */
  2421. function baseArity(func, n) {
  2422. return n == 2
  2423. ? function(a, b) { return func.apply(undefined, arguments); }
  2424. : function(a) { return func.apply(undefined, arguments); };
  2425. }
  2426. /**
  2427. * Creates a function that invokes `func`, with up to `n` arguments, ignoring
  2428. * any additional arguments.
  2429. *
  2430. * @private
  2431. * @param {Function} func The function to cap arguments for.
  2432. * @param {number} n The arity cap.
  2433. * @returns {Function} Returns the new function.
  2434. */
  2435. function baseAry(func, n) {
  2436. return n == 2
  2437. ? function(a, b) { return func(a, b); }
  2438. : function(a) { return func(a); };
  2439. }
  2440. /**
  2441. * Creates a clone of `array`.
  2442. *
  2443. * @private
  2444. * @param {Array} array The array to clone.
  2445. * @returns {Array} Returns the cloned array.
  2446. */
  2447. function cloneArray(array) {
  2448. var length = array ? array.length : 0,
  2449. result = Array(length);
  2450. while (length--) {
  2451. result[length] = array[length];
  2452. }
  2453. return result;
  2454. }
  2455. /**
  2456. * Creates a function that clones a given object using the assignment `func`.
  2457. *
  2458. * @private
  2459. * @param {Function} func The assignment function.
  2460. * @returns {Function} Returns the new cloner function.
  2461. */
  2462. function createCloner(func) {
  2463. return function(object) {
  2464. return func({}, object);
  2465. };
  2466. }
  2467. /**
  2468. * A specialized version of `_.spread` which flattens the spread array into
  2469. * the arguments of the invoked `func`.
  2470. *
  2471. * @private
  2472. * @param {Function} func The function to spread arguments over.
  2473. * @param {number} start The start position of the spread.
  2474. * @returns {Function} Returns the new function.
  2475. */
  2476. function flatSpread(func, start) {
  2477. return function() {
  2478. var length = arguments.length,
  2479. lastIndex = length - 1,
  2480. args = Array(length);
  2481. while (length--) {
  2482. args[length] = arguments[length];
  2483. }
  2484. var array = args[start],
  2485. otherArgs = args.slice(0, start);
  2486. if (array) {
  2487. push.apply(otherArgs, array);
  2488. }
  2489. if (start != lastIndex) {
  2490. push.apply(otherArgs, args.slice(start + 1));
  2491. }
  2492. return func.apply(this, otherArgs);
  2493. };
  2494. }
  2495. /**
  2496. * Creates a function that wraps `func` and uses `cloner` to clone the first
  2497. * argument it receives.
  2498. *
  2499. * @private
  2500. * @param {Function} func The function to wrap.
  2501. * @param {Function} cloner The function to clone arguments.
  2502. * @returns {Function} Returns the new immutable function.
  2503. */
  2504. function wrapImmutable(func, cloner) {
  2505. return function() {
  2506. var length = arguments.length;
  2507. if (!length) {
  2508. return;
  2509. }
  2510. var args = Array(length);
  2511. while (length--) {
  2512. args[length] = arguments[length];
  2513. }
  2514. var result = args[0] = cloner.apply(undefined, args);
  2515. func.apply(undefined, args);
  2516. return result;
  2517. };
  2518. }
  2519. /**
  2520. * The base implementation of `convert` which accepts a `util` object of methods
  2521. * required to perform conversions.
  2522. *
  2523. * @param {Object} util The util object.
  2524. * @param {string} name The name of the function to convert.
  2525. * @param {Function} func The function to convert.
  2526. * @param {Object} [options] The options object.
  2527. * @param {boolean} [options.cap=true] Specify capping iteratee arguments.
  2528. * @param {boolean} [options.curry=true] Specify currying.
  2529. * @param {boolean} [options.fixed=true] Specify fixed arity.
  2530. * @param {boolean} [options.immutable=true] Specify immutable operations.
  2531. * @param {boolean} [options.rearg=true] Specify rearranging arguments.
  2532. * @returns {Function|Object} Returns the converted function or object.
  2533. */
  2534. function baseConvert(util, name, func, options) {
  2535. var isLib = typeof name == 'function',
  2536. isObj = name === Object(name);
  2537. if (isObj) {
  2538. options = func;
  2539. func = name;
  2540. name = undefined;
  2541. }
  2542. if (func == null) {
  2543. throw new TypeError;
  2544. }
  2545. options || (options = {});
  2546. var config = {
  2547. 'cap': 'cap' in options ? options.cap : true,
  2548. 'curry': 'curry' in options ? options.curry : true,
  2549. 'fixed': 'fixed' in options ? options.fixed : true,
  2550. 'immutable': 'immutable' in options ? options.immutable : true,
  2551. 'rearg': 'rearg' in options ? options.rearg : true
  2552. };
  2553. var defaultHolder = isLib ? func : placeholder,
  2554. forceCurry = ('curry' in options) && options.curry,
  2555. forceFixed = ('fixed' in options) && options.fixed,
  2556. forceRearg = ('rearg' in options) && options.rearg,
  2557. pristine = isLib ? func.runInContext() : undefined;
  2558. var helpers = isLib ? func : {
  2559. 'ary': util.ary,
  2560. 'assign': util.assign,
  2561. 'clone': util.clone,
  2562. 'curry': util.curry,
  2563. 'forEach': util.forEach,
  2564. 'isArray': util.isArray,
  2565. 'isError': util.isError,
  2566. 'isFunction': util.isFunction,
  2567. 'isWeakMap': util.isWeakMap,
  2568. 'iteratee': util.iteratee,
  2569. 'keys': util.keys,
  2570. 'rearg': util.rearg,
  2571. 'toInteger': util.toInteger,
  2572. 'toPath': util.toPath
  2573. };
  2574. var ary = helpers.ary,
  2575. assign = helpers.assign,
  2576. clone = helpers.clone,
  2577. curry = helpers.curry,
  2578. each = helpers.forEach,
  2579. isArray = helpers.isArray,
  2580. isError = helpers.isError,
  2581. isFunction = helpers.isFunction,
  2582. isWeakMap = helpers.isWeakMap,
  2583. keys = helpers.keys,
  2584. rearg = helpers.rearg,
  2585. toInteger = helpers.toInteger,
  2586. toPath = helpers.toPath;
  2587. var aryMethodKeys = keys(_mapping.aryMethod);
  2588. var wrappers = {
  2589. 'castArray': function(castArray) {
  2590. return function() {
  2591. var value = arguments[0];
  2592. return isArray(value)
  2593. ? castArray(cloneArray(value))
  2594. : castArray.apply(undefined, arguments);
  2595. };
  2596. },
  2597. 'iteratee': function(iteratee) {
  2598. return function() {
  2599. var func = arguments[0],
  2600. arity = arguments[1],
  2601. result = iteratee(func, arity),
  2602. length = result.length;
  2603. if (config.cap && typeof arity == 'number') {
  2604. arity = arity > 2 ? (arity - 2) : 1;
  2605. return (length && length <= arity) ? result : baseAry(result, arity);
  2606. }
  2607. return result;
  2608. };
  2609. },
  2610. 'mixin': function(mixin) {
  2611. return function(source) {
  2612. var func = this;
  2613. if (!isFunction(func)) {
  2614. return mixin(func, Object(source));
  2615. }
  2616. var pairs = [];
  2617. each(keys(source), function(key) {
  2618. if (isFunction(source[key])) {
  2619. pairs.push([key, func.prototype[key]]);
  2620. }
  2621. });
  2622. mixin(func, Object(source));
  2623. each(pairs, function(pair) {
  2624. var value = pair[1];
  2625. if (isFunction(value)) {
  2626. func.prototype[pair[0]] = value;
  2627. } else {
  2628. delete func.prototype[pair[0]];
  2629. }
  2630. });
  2631. return func;
  2632. };
  2633. },
  2634. 'nthArg': function(nthArg) {
  2635. return function(n) {
  2636. var arity = n < 0 ? 1 : (toInteger(n) + 1);
  2637. return curry(nthArg(n), arity);
  2638. };
  2639. },
  2640. 'rearg': function(rearg) {
  2641. return function(func, indexes) {
  2642. var arity = indexes ? indexes.length : 0;
  2643. return curry(rearg(func, indexes), arity);
  2644. };
  2645. },
  2646. 'runInContext': function(runInContext) {
  2647. return function(context) {
  2648. return baseConvert(util, runInContext(context), options);
  2649. };
  2650. }
  2651. };
  2652. /*--------------------------------------------------------------------------*/
  2653. /**
  2654. * Casts `func` to a function with an arity capped iteratee if needed.
  2655. *
  2656. * @private
  2657. * @param {string} name The name of the function to inspect.
  2658. * @param {Function} func The function to inspect.
  2659. * @returns {Function} Returns the cast function.
  2660. */
  2661. function castCap(name, func) {
  2662. if (config.cap) {
  2663. var indexes = _mapping.iterateeRearg[name];
  2664. if (indexes) {
  2665. return iterateeRearg(func, indexes);
  2666. }
  2667. var n = !isLib && _mapping.iterateeAry[name];
  2668. if (n) {
  2669. return iterateeAry(func, n);
  2670. }
  2671. }
  2672. return func;
  2673. }
  2674. /**
  2675. * Casts `func` to a curried function if needed.
  2676. *
  2677. * @private
  2678. * @param {string} name The name of the function to inspect.
  2679. * @param {Function} func The function to inspect.
  2680. * @param {number} n The arity of `func`.
  2681. * @returns {Function} Returns the cast function.
  2682. */
  2683. function castCurry(name, func, n) {
  2684. return (forceCurry || (config.curry && n > 1))
  2685. ? curry(func, n)
  2686. : func;
  2687. }
  2688. /**
  2689. * Casts `func` to a fixed arity function if needed.
  2690. *
  2691. * @private
  2692. * @param {string} name The name of the function to inspect.
  2693. * @param {Function} func The function to inspect.
  2694. * @param {number} n The arity cap.
  2695. * @returns {Function} Returns the cast function.
  2696. */
  2697. function castFixed(name, func, n) {
  2698. if (config.fixed && (forceFixed || !_mapping.skipFixed[name])) {
  2699. var data = _mapping.methodSpread[name],
  2700. start = data && data.start;
  2701. return start === undefined ? ary(func, n) : flatSpread(func, start);
  2702. }
  2703. return func;
  2704. }
  2705. /**
  2706. * Casts `func` to an rearged function if needed.
  2707. *
  2708. * @private
  2709. * @param {string} name The name of the function to inspect.
  2710. * @param {Function} func The function to inspect.
  2711. * @param {number} n The arity of `func`.
  2712. * @returns {Function} Returns the cast function.
  2713. */
  2714. function castRearg(name, func, n) {
  2715. return (config.rearg && n > 1 && (forceRearg || !_mapping.skipRearg[name]))
  2716. ? rearg(func, _mapping.methodRearg[name] || _mapping.aryRearg[n])
  2717. : func;
  2718. }
  2719. /**
  2720. * Creates a clone of `object` by `path`.
  2721. *
  2722. * @private
  2723. * @param {Object} object The object to clone.
  2724. * @param {Array|string} path The path to clone by.
  2725. * @returns {Object} Returns the cloned object.
  2726. */
  2727. function cloneByPath(object, path) {
  2728. path = toPath(path);
  2729. var index = -1,
  2730. length = path.length,
  2731. lastIndex = length - 1,
  2732. result = clone(Object(object)),
  2733. nested = result;
  2734. while (nested != null && ++index < length) {
  2735. var key = path[index],
  2736. value = nested[key];
  2737. if (value != null &&
  2738. !(isFunction(value) || isError(value) || isWeakMap(value))) {
  2739. nested[key] = clone(index == lastIndex ? value : Object(value));
  2740. }
  2741. nested = nested[key];
  2742. }
  2743. return result;
  2744. }
  2745. /**
  2746. * Converts `lodash` to an immutable auto-curried iteratee-first data-last
  2747. * version with conversion `options` applied.
  2748. *
  2749. * @param {Object} [options] The options object. See `baseConvert` for more details.
  2750. * @returns {Function} Returns the converted `lodash`.
  2751. */
  2752. function convertLib(options) {
  2753. return _.runInContext.convert(options)(undefined);
  2754. }
  2755. /**
  2756. * Create a converter function for `func` of `name`.
  2757. *
  2758. * @param {string} name The name of the function to convert.
  2759. * @param {Function} func The function to convert.
  2760. * @returns {Function} Returns the new converter function.
  2761. */
  2762. function createConverter(name, func) {
  2763. var realName = _mapping.aliasToReal[name] || name,
  2764. methodName = _mapping.remap[realName] || realName,
  2765. oldOptions = options;
  2766. return function(options) {
  2767. var newUtil = isLib ? pristine : helpers,
  2768. newFunc = isLib ? pristine[methodName] : func,
  2769. newOptions = assign(assign({}, oldOptions), options);
  2770. return baseConvert(newUtil, realName, newFunc, newOptions);
  2771. };
  2772. }
  2773. /**
  2774. * Creates a function that wraps `func` to invoke its iteratee, with up to `n`
  2775. * arguments, ignoring any additional arguments.
  2776. *
  2777. * @private
  2778. * @param {Function} func The function to cap iteratee arguments for.
  2779. * @param {number} n The arity cap.
  2780. * @returns {Function} Returns the new function.
  2781. */
  2782. function iterateeAry(func, n) {
  2783. return overArg(func, function(func) {
  2784. return typeof func == 'function' ? baseAry(func, n) : func;
  2785. });
  2786. }
  2787. /**
  2788. * Creates a function that wraps `func` to invoke its iteratee with arguments
  2789. * arranged according to the specified `indexes` where the argument value at
  2790. * the first index is provided as the first argument, the argument value at
  2791. * the second index is provided as the second argument, and so on.
  2792. *
  2793. * @private
  2794. * @param {Function} func The function to rearrange iteratee arguments for.
  2795. * @param {number[]} indexes The arranged argument indexes.
  2796. * @returns {Function} Returns the new function.
  2797. */
  2798. function iterateeRearg(func, indexes) {
  2799. return overArg(func, function(func) {
  2800. var n = indexes.length;
  2801. return baseArity(rearg(baseAry(func, n), indexes), n);
  2802. });
  2803. }
  2804. /**
  2805. * Creates a function that invokes `func` with its first argument transformed.
  2806. *
  2807. * @private
  2808. * @param {Function} func The function to wrap.
  2809. * @param {Function} transform The argument transform.
  2810. * @returns {Function} Returns the new function.
  2811. */
  2812. function overArg(func, transform) {
  2813. return function() {
  2814. var length = arguments.length;
  2815. if (!length) {
  2816. return func();
  2817. }
  2818. var args = Array(length);
  2819. while (length--) {
  2820. args[length] = arguments[length];
  2821. }
  2822. var index = config.rearg ? 0 : (length - 1);
  2823. args[index] = transform(args[index]);
  2824. return func.apply(undefined, args);
  2825. };
  2826. }
  2827. /**
  2828. * Creates a function that wraps `func` and applys the conversions
  2829. * rules by `name`.
  2830. *
  2831. * @private
  2832. * @param {string} name The name of the function to wrap.
  2833. * @param {Function} func The function to wrap.
  2834. * @returns {Function} Returns the converted function.
  2835. */
  2836. function wrap(name, func, placeholder) {
  2837. var result,
  2838. realName = _mapping.aliasToReal[name] || name,
  2839. wrapped = func,
  2840. wrapper = wrappers[realName];
  2841. if (wrapper) {
  2842. wrapped = wrapper(func);
  2843. }
  2844. else if (config.immutable) {
  2845. if (_mapping.mutate.array[realName]) {
  2846. wrapped = wrapImmutable(func, cloneArray);
  2847. }
  2848. else if (_mapping.mutate.object[realName]) {
  2849. wrapped = wrapImmutable(func, createCloner(func));
  2850. }
  2851. else if (_mapping.mutate.set[realName]) {
  2852. wrapped = wrapImmutable(func, cloneByPath);
  2853. }
  2854. }
  2855. each(aryMethodKeys, function(aryKey) {
  2856. each(_mapping.aryMethod[aryKey], function(otherName) {
  2857. if (realName == otherName) {
  2858. var data = _mapping.methodSpread[realName],
  2859. afterRearg = data && data.afterRearg;
  2860. result = afterRearg
  2861. ? castFixed(realName, castRearg(realName, wrapped, aryKey), aryKey)
  2862. : castRearg(realName, castFixed(realName, wrapped, aryKey), aryKey);
  2863. result = castCap(realName, result);
  2864. result = castCurry(realName, result, aryKey);
  2865. return false;
  2866. }
  2867. });
  2868. return !result;
  2869. });
  2870. result || (result = wrapped);
  2871. if (result == func) {
  2872. result = forceCurry ? curry(result, 1) : function() {
  2873. return func.apply(this, arguments);
  2874. };
  2875. }
  2876. result.convert = createConverter(realName, func);
  2877. result.placeholder = func.placeholder = placeholder;
  2878. return result;
  2879. }
  2880. /*--------------------------------------------------------------------------*/
  2881. if (!isObj) {
  2882. return wrap(name, func, defaultHolder);
  2883. }
  2884. var _ = func;
  2885. // Convert methods by ary cap.
  2886. var pairs = [];
  2887. each(aryMethodKeys, function(aryKey) {
  2888. each(_mapping.aryMethod[aryKey], function(key) {
  2889. var func = _[_mapping.remap[key] || key];
  2890. if (func) {
  2891. pairs.push([key, wrap(key, func, _)]);
  2892. }
  2893. });
  2894. });
  2895. // Convert remaining methods.
  2896. each(keys(_), function(key) {
  2897. var func = _[key];
  2898. if (typeof func == 'function') {
  2899. var length = pairs.length;
  2900. while (length--) {
  2901. if (pairs[length][0] == key) {
  2902. return;
  2903. }
  2904. }
  2905. func.convert = createConverter(key, func);
  2906. pairs.push([key, func]);
  2907. }
  2908. });
  2909. // Assign to `_` leaving `_.prototype` unchanged to allow chaining.
  2910. each(pairs, function(pair) {
  2911. _[pair[0]] = pair[1];
  2912. });
  2913. _.convert = convertLib;
  2914. _.placeholder = _;
  2915. // Assign aliases.
  2916. each(keys(_), function(key) {
  2917. each(_mapping.realToAlias[key] || [], function(alias) {
  2918. _[alias] = _[key];
  2919. });
  2920. });
  2921. return _;
  2922. }
  2923. var _baseConvert = baseConvert;
  2924. /** Used to compose bitmasks for function metadata. */
  2925. var WRAP_ARY_FLAG = 128;
  2926. /**
  2927. * Creates a function that invokes `func`, with up to `n` arguments,
  2928. * ignoring any additional arguments.
  2929. *
  2930. * @static
  2931. * @memberOf _
  2932. * @since 3.0.0
  2933. * @category Function
  2934. * @param {Function} func The function to cap arguments for.
  2935. * @param {number} [n=func.length] The arity cap.
  2936. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  2937. * @returns {Function} Returns the new capped function.
  2938. * @example
  2939. *
  2940. * _.map(['6', '8', '10'], _.ary(parseInt, 1));
  2941. * // => [6, 8, 10]
  2942. */
  2943. function ary(func, n, guard) {
  2944. n = guard ? undefined : n;
  2945. n = (func && n == null) ? func.length : n;
  2946. return _createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n);
  2947. }
  2948. var ary_1 = ary;
  2949. /**
  2950. * The base implementation of `assignValue` and `assignMergeValue` without
  2951. * value checks.
  2952. *
  2953. * @private
  2954. * @param {Object} object The object to modify.
  2955. * @param {string} key The key of the property to assign.
  2956. * @param {*} value The value to assign.
  2957. */
  2958. function baseAssignValue(object, key, value) {
  2959. if (key == '__proto__' && _defineProperty) {
  2960. _defineProperty(object, key, {
  2961. 'configurable': true,
  2962. 'enumerable': true,
  2963. 'value': value,
  2964. 'writable': true
  2965. });
  2966. } else {
  2967. object[key] = value;
  2968. }
  2969. }
  2970. var _baseAssignValue = baseAssignValue;
  2971. /**
  2972. * Performs a
  2973. * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
  2974. * comparison between two values to determine if they are equivalent.
  2975. *
  2976. * @static
  2977. * @memberOf _
  2978. * @since 4.0.0
  2979. * @category Lang
  2980. * @param {*} value The value to compare.
  2981. * @param {*} other The other value to compare.
  2982. * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
  2983. * @example
  2984. *
  2985. * var object = { 'a': 1 };
  2986. * var other = { 'a': 1 };
  2987. *
  2988. * _.eq(object, object);
  2989. * // => true
  2990. *
  2991. * _.eq(object, other);
  2992. * // => false
  2993. *
  2994. * _.eq('a', 'a');
  2995. * // => true
  2996. *
  2997. * _.eq('a', Object('a'));
  2998. * // => false
  2999. *
  3000. * _.eq(NaN, NaN);
  3001. * // => true
  3002. */
  3003. function eq(value, other) {
  3004. return value === other || (value !== value && other !== other);
  3005. }
  3006. var eq_1 = eq;
  3007. /** Used for built-in method references. */
  3008. var objectProto$c = Object.prototype;
  3009. /** Used to check objects for own properties. */
  3010. var hasOwnProperty$a = objectProto$c.hasOwnProperty;
  3011. /**
  3012. * Assigns `value` to `key` of `object` if the existing value is not equivalent
  3013. * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
  3014. * for equality comparisons.
  3015. *
  3016. * @private
  3017. * @param {Object} object The object to modify.
  3018. * @param {string} key The key of the property to assign.
  3019. * @param {*} value The value to assign.
  3020. */
  3021. function assignValue(object, key, value) {
  3022. var objValue = object[key];
  3023. if (!(hasOwnProperty$a.call(object, key) && eq_1(objValue, value)) ||
  3024. (value === undefined && !(key in object))) {
  3025. _baseAssignValue(object, key, value);
  3026. }
  3027. }
  3028. var _assignValue = assignValue;
  3029. /**
  3030. * Copies properties of `source` to `object`.
  3031. *
  3032. * @private
  3033. * @param {Object} source The object to copy properties from.
  3034. * @param {Array} props The property identifiers to copy.
  3035. * @param {Object} [object={}] The object to copy properties to.
  3036. * @param {Function} [customizer] The function to customize copied values.
  3037. * @returns {Object} Returns `object`.
  3038. */
  3039. function copyObject(source, props, object, customizer) {
  3040. var isNew = !object;
  3041. object || (object = {});
  3042. var index = -1,
  3043. length = props.length;
  3044. while (++index < length) {
  3045. var key = props[index];
  3046. var newValue = customizer
  3047. ? customizer(object[key], source[key], key, object, source)
  3048. : undefined;
  3049. if (newValue === undefined) {
  3050. newValue = source[key];
  3051. }
  3052. if (isNew) {
  3053. _baseAssignValue(object, key, newValue);
  3054. } else {
  3055. _assignValue(object, key, newValue);
  3056. }
  3057. }
  3058. return object;
  3059. }
  3060. var _copyObject = copyObject;
  3061. /**
  3062. * The base implementation of `_.times` without support for iteratee shorthands
  3063. * or max array length checks.
  3064. *
  3065. * @private
  3066. * @param {number} n The number of times to invoke `iteratee`.
  3067. * @param {Function} iteratee The function invoked per iteration.
  3068. * @returns {Array} Returns the array of results.
  3069. */
  3070. function baseTimes(n, iteratee) {
  3071. var index = -1,
  3072. result = Array(n);
  3073. while (++index < n) {
  3074. result[index] = iteratee(index);
  3075. }
  3076. return result;
  3077. }
  3078. var _baseTimes = baseTimes;
  3079. /** `Object#toString` result references. */
  3080. var argsTag$3 = '[object Arguments]';
  3081. /**
  3082. * The base implementation of `_.isArguments`.
  3083. *
  3084. * @private
  3085. * @param {*} value The value to check.
  3086. * @returns {boolean} Returns `true` if `value` is an `arguments` object,
  3087. */
  3088. function baseIsArguments(value) {
  3089. return isObjectLike_1(value) && _baseGetTag(value) == argsTag$3;
  3090. }
  3091. var _baseIsArguments = baseIsArguments;
  3092. /** Used for built-in method references. */
  3093. var objectProto$b = Object.prototype;
  3094. /** Used to check objects for own properties. */
  3095. var hasOwnProperty$9 = objectProto$b.hasOwnProperty;
  3096. /** Built-in value references. */
  3097. var propertyIsEnumerable$1 = objectProto$b.propertyIsEnumerable;
  3098. /**
  3099. * Checks if `value` is likely an `arguments` object.
  3100. *
  3101. * @static
  3102. * @memberOf _
  3103. * @since 0.1.0
  3104. * @category Lang
  3105. * @param {*} value The value to check.
  3106. * @returns {boolean} Returns `true` if `value` is an `arguments` object,
  3107. * else `false`.
  3108. * @example
  3109. *
  3110. * _.isArguments(function() { return arguments; }());
  3111. * // => true
  3112. *
  3113. * _.isArguments([1, 2, 3]);
  3114. * // => false
  3115. */
  3116. var isArguments = _baseIsArguments(function() { return arguments; }()) ? _baseIsArguments : function(value) {
  3117. return isObjectLike_1(value) && hasOwnProperty$9.call(value, 'callee') &&
  3118. !propertyIsEnumerable$1.call(value, 'callee');
  3119. };
  3120. var isArguments_1 = isArguments;
  3121. /**
  3122. * This method returns `false`.
  3123. *
  3124. * @static
  3125. * @memberOf _
  3126. * @since 4.13.0
  3127. * @category Util
  3128. * @returns {boolean} Returns `false`.
  3129. * @example
  3130. *
  3131. * _.times(2, _.stubFalse);
  3132. * // => [false, false]
  3133. */
  3134. function stubFalse() {
  3135. return false;
  3136. }
  3137. var stubFalse_1 = stubFalse;
  3138. var isBuffer_1 = createCommonjsModule(function (module, exports) {
  3139. /** Detect free variable `exports`. */
  3140. var freeExports = exports && !exports.nodeType && exports;
  3141. /** Detect free variable `module`. */
  3142. var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
  3143. /** Detect the popular CommonJS extension `module.exports`. */
  3144. var moduleExports = freeModule && freeModule.exports === freeExports;
  3145. /** Built-in value references. */
  3146. var Buffer = moduleExports ? _root.Buffer : undefined;
  3147. /* Built-in method references for those with the same name as other `lodash` methods. */
  3148. var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
  3149. /**
  3150. * Checks if `value` is a buffer.
  3151. *
  3152. * @static
  3153. * @memberOf _
  3154. * @since 4.3.0
  3155. * @category Lang
  3156. * @param {*} value The value to check.
  3157. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
  3158. * @example
  3159. *
  3160. * _.isBuffer(new Buffer(2));
  3161. * // => true
  3162. *
  3163. * _.isBuffer(new Uint8Array(2));
  3164. * // => false
  3165. */
  3166. var isBuffer = nativeIsBuffer || stubFalse_1;
  3167. module.exports = isBuffer;
  3168. }, "/$$rollup_base$$/node_modules/lodash");
  3169. /** Used as references for various `Number` constants. */
  3170. var MAX_SAFE_INTEGER = 9007199254740991;
  3171. /**
  3172. * Checks if `value` is a valid array-like length.
  3173. *
  3174. * **Note:** This method is loosely based on
  3175. * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
  3176. *
  3177. * @static
  3178. * @memberOf _
  3179. * @since 4.0.0
  3180. * @category Lang
  3181. * @param {*} value The value to check.
  3182. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
  3183. * @example
  3184. *
  3185. * _.isLength(3);
  3186. * // => true
  3187. *
  3188. * _.isLength(Number.MIN_VALUE);
  3189. * // => false
  3190. *
  3191. * _.isLength(Infinity);
  3192. * // => false
  3193. *
  3194. * _.isLength('3');
  3195. * // => false
  3196. */
  3197. function isLength(value) {
  3198. return typeof value == 'number' &&
  3199. value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
  3200. }
  3201. var isLength_1 = isLength;
  3202. /** `Object#toString` result references. */
  3203. var argsTag$2 = '[object Arguments]',
  3204. arrayTag$2 = '[object Array]',
  3205. boolTag$3 = '[object Boolean]',
  3206. dateTag$3 = '[object Date]',
  3207. errorTag$3 = '[object Error]',
  3208. funcTag$1 = '[object Function]',
  3209. mapTag$5 = '[object Map]',
  3210. numberTag$3 = '[object Number]',
  3211. objectTag$4 = '[object Object]',
  3212. regexpTag$3 = '[object RegExp]',
  3213. setTag$5 = '[object Set]',
  3214. stringTag$3 = '[object String]',
  3215. weakMapTag$3 = '[object WeakMap]';
  3216. var arrayBufferTag$3 = '[object ArrayBuffer]',
  3217. dataViewTag$4 = '[object DataView]',
  3218. float32Tag$2 = '[object Float32Array]',
  3219. float64Tag$2 = '[object Float64Array]',
  3220. int8Tag$2 = '[object Int8Array]',
  3221. int16Tag$2 = '[object Int16Array]',
  3222. int32Tag$2 = '[object Int32Array]',
  3223. uint8Tag$2 = '[object Uint8Array]',
  3224. uint8ClampedTag$2 = '[object Uint8ClampedArray]',
  3225. uint16Tag$2 = '[object Uint16Array]',
  3226. uint32Tag$2 = '[object Uint32Array]';
  3227. /** Used to identify `toStringTag` values of typed arrays. */
  3228. var typedArrayTags = {};
  3229. typedArrayTags[float32Tag$2] = typedArrayTags[float64Tag$2] =
  3230. typedArrayTags[int8Tag$2] = typedArrayTags[int16Tag$2] =
  3231. typedArrayTags[int32Tag$2] = typedArrayTags[uint8Tag$2] =
  3232. typedArrayTags[uint8ClampedTag$2] = typedArrayTags[uint16Tag$2] =
  3233. typedArrayTags[uint32Tag$2] = true;
  3234. typedArrayTags[argsTag$2] = typedArrayTags[arrayTag$2] =
  3235. typedArrayTags[arrayBufferTag$3] = typedArrayTags[boolTag$3] =
  3236. typedArrayTags[dataViewTag$4] = typedArrayTags[dateTag$3] =
  3237. typedArrayTags[errorTag$3] = typedArrayTags[funcTag$1] =
  3238. typedArrayTags[mapTag$5] = typedArrayTags[numberTag$3] =
  3239. typedArrayTags[objectTag$4] = typedArrayTags[regexpTag$3] =
  3240. typedArrayTags[setTag$5] = typedArrayTags[stringTag$3] =
  3241. typedArrayTags[weakMapTag$3] = false;
  3242. /**
  3243. * The base implementation of `_.isTypedArray` without Node.js optimizations.
  3244. *
  3245. * @private
  3246. * @param {*} value The value to check.
  3247. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
  3248. */
  3249. function baseIsTypedArray(value) {
  3250. return isObjectLike_1(value) &&
  3251. isLength_1(value.length) && !!typedArrayTags[_baseGetTag(value)];
  3252. }
  3253. var _baseIsTypedArray = baseIsTypedArray;
  3254. /**
  3255. * The base implementation of `_.unary` without support for storing metadata.
  3256. *
  3257. * @private
  3258. * @param {Function} func The function to cap arguments for.
  3259. * @returns {Function} Returns the new capped function.
  3260. */
  3261. function baseUnary(func) {
  3262. return function(value) {
  3263. return func(value);
  3264. };
  3265. }
  3266. var _baseUnary = baseUnary;
  3267. var _nodeUtil = createCommonjsModule(function (module, exports) {
  3268. /** Detect free variable `exports`. */
  3269. var freeExports = exports && !exports.nodeType && exports;
  3270. /** Detect free variable `module`. */
  3271. var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
  3272. /** Detect the popular CommonJS extension `module.exports`. */
  3273. var moduleExports = freeModule && freeModule.exports === freeExports;
  3274. /** Detect free variable `process` from Node.js. */
  3275. var freeProcess = moduleExports && _freeGlobal.process;
  3276. /** Used to access faster Node.js helpers. */
  3277. var nodeUtil = (function() {
  3278. try {
  3279. // Use `util.types` for Node.js 10+.
  3280. var types = freeModule && freeModule.require && freeModule.require('util').types;
  3281. if (types) {
  3282. return types;
  3283. }
  3284. // Legacy `process.binding('util')` for Node.js < 10.
  3285. return freeProcess && freeProcess.binding && freeProcess.binding('util');
  3286. } catch (e) {}
  3287. }());
  3288. module.exports = nodeUtil;
  3289. }, "/$$rollup_base$$/node_modules/lodash");
  3290. /* Node.js helper references. */
  3291. var nodeIsTypedArray = _nodeUtil && _nodeUtil.isTypedArray;
  3292. /**
  3293. * Checks if `value` is classified as a typed array.
  3294. *
  3295. * @static
  3296. * @memberOf _
  3297. * @since 3.0.0
  3298. * @category Lang
  3299. * @param {*} value The value to check.
  3300. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
  3301. * @example
  3302. *
  3303. * _.isTypedArray(new Uint8Array);
  3304. * // => true
  3305. *
  3306. * _.isTypedArray([]);
  3307. * // => false
  3308. */
  3309. var isTypedArray = nodeIsTypedArray ? _baseUnary(nodeIsTypedArray) : _baseIsTypedArray;
  3310. var isTypedArray_1 = isTypedArray;
  3311. /** Used for built-in method references. */
  3312. var objectProto$a = Object.prototype;
  3313. /** Used to check objects for own properties. */
  3314. var hasOwnProperty$8 = objectProto$a.hasOwnProperty;
  3315. /**
  3316. * Creates an array of the enumerable property names of the array-like `value`.
  3317. *
  3318. * @private
  3319. * @param {*} value The value to query.
  3320. * @param {boolean} inherited Specify returning inherited property names.
  3321. * @returns {Array} Returns the array of property names.
  3322. */
  3323. function arrayLikeKeys(value, inherited) {
  3324. var isArr = isArray_1(value),
  3325. isArg = !isArr && isArguments_1(value),
  3326. isBuff = !isArr && !isArg && isBuffer_1(value),
  3327. isType = !isArr && !isArg && !isBuff && isTypedArray_1(value),
  3328. skipIndexes = isArr || isArg || isBuff || isType,
  3329. result = skipIndexes ? _baseTimes(value.length, String) : [],
  3330. length = result.length;
  3331. for (var key in value) {
  3332. if ((inherited || hasOwnProperty$8.call(value, key)) &&
  3333. !(skipIndexes && (
  3334. // Safari 9 has enumerable `arguments.length` in strict mode.
  3335. key == 'length' ||
  3336. // Node.js 0.10 has enumerable non-index properties on buffers.
  3337. (isBuff && (key == 'offset' || key == 'parent')) ||
  3338. // PhantomJS 2 has enumerable non-index properties on typed arrays.
  3339. (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
  3340. // Skip index properties.
  3341. _isIndex(key, length)
  3342. ))) {
  3343. result.push(key);
  3344. }
  3345. }
  3346. return result;
  3347. }
  3348. var _arrayLikeKeys = arrayLikeKeys;
  3349. /** Used for built-in method references. */
  3350. var objectProto$9 = Object.prototype;
  3351. /**
  3352. * Checks if `value` is likely a prototype object.
  3353. *
  3354. * @private
  3355. * @param {*} value The value to check.
  3356. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
  3357. */
  3358. function isPrototype(value) {
  3359. var Ctor = value && value.constructor,
  3360. proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$9;
  3361. return value === proto;
  3362. }
  3363. var _isPrototype = isPrototype;
  3364. /**
  3365. * Creates a unary function that invokes `func` with its argument transformed.
  3366. *
  3367. * @private
  3368. * @param {Function} func The function to wrap.
  3369. * @param {Function} transform The argument transform.
  3370. * @returns {Function} Returns the new function.
  3371. */
  3372. function overArg(func, transform) {
  3373. return function(arg) {
  3374. return func(transform(arg));
  3375. };
  3376. }
  3377. var _overArg = overArg;
  3378. /* Built-in method references for those with the same name as other `lodash` methods. */
  3379. var nativeKeys = _overArg(Object.keys, Object);
  3380. var _nativeKeys = nativeKeys;
  3381. /** Used for built-in method references. */
  3382. var objectProto$8 = Object.prototype;
  3383. /** Used to check objects for own properties. */
  3384. var hasOwnProperty$7 = objectProto$8.hasOwnProperty;
  3385. /**
  3386. * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
  3387. *
  3388. * @private
  3389. * @param {Object} object The object to query.
  3390. * @returns {Array} Returns the array of property names.
  3391. */
  3392. function baseKeys(object) {
  3393. if (!_isPrototype(object)) {
  3394. return _nativeKeys(object);
  3395. }
  3396. var result = [];
  3397. for (var key in Object(object)) {
  3398. if (hasOwnProperty$7.call(object, key) && key != 'constructor') {
  3399. result.push(key);
  3400. }
  3401. }
  3402. return result;
  3403. }
  3404. var _baseKeys = baseKeys;
  3405. /**
  3406. * Checks if `value` is array-like. A value is considered array-like if it's
  3407. * not a function and has a `value.length` that's an integer greater than or
  3408. * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
  3409. *
  3410. * @static
  3411. * @memberOf _
  3412. * @since 4.0.0
  3413. * @category Lang
  3414. * @param {*} value The value to check.
  3415. * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
  3416. * @example
  3417. *
  3418. * _.isArrayLike([1, 2, 3]);
  3419. * // => true
  3420. *
  3421. * _.isArrayLike(document.body.children);
  3422. * // => true
  3423. *
  3424. * _.isArrayLike('abc');
  3425. * // => true
  3426. *
  3427. * _.isArrayLike(_.noop);
  3428. * // => false
  3429. */
  3430. function isArrayLike(value) {
  3431. return value != null && isLength_1(value.length) && !isFunction_1(value);
  3432. }
  3433. var isArrayLike_1 = isArrayLike;
  3434. /**
  3435. * Creates an array of the own enumerable property names of `object`.
  3436. *
  3437. * **Note:** Non-object values are coerced to objects. See the
  3438. * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
  3439. * for more details.
  3440. *
  3441. * @static
  3442. * @since 0.1.0
  3443. * @memberOf _
  3444. * @category Object
  3445. * @param {Object} object The object to query.
  3446. * @returns {Array} Returns the array of property names.
  3447. * @example
  3448. *
  3449. * function Foo() {
  3450. * this.a = 1;
  3451. * this.b = 2;
  3452. * }
  3453. *
  3454. * Foo.prototype.c = 3;
  3455. *
  3456. * _.keys(new Foo);
  3457. * // => ['a', 'b'] (iteration order is not guaranteed)
  3458. *
  3459. * _.keys('hi');
  3460. * // => ['0', '1']
  3461. */
  3462. function keys(object) {
  3463. return isArrayLike_1(object) ? _arrayLikeKeys(object) : _baseKeys(object);
  3464. }
  3465. var keys_1 = keys;
  3466. /**
  3467. * The base implementation of `_.assign` without support for multiple sources
  3468. * or `customizer` functions.
  3469. *
  3470. * @private
  3471. * @param {Object} object The destination object.
  3472. * @param {Object} source The source object.
  3473. * @returns {Object} Returns `object`.
  3474. */
  3475. function baseAssign(object, source) {
  3476. return object && _copyObject(source, keys_1(source), object);
  3477. }
  3478. var _baseAssign = baseAssign;
  3479. /**
  3480. * Removes all key-value entries from the list cache.
  3481. *
  3482. * @private
  3483. * @name clear
  3484. * @memberOf ListCache
  3485. */
  3486. function listCacheClear() {
  3487. this.__data__ = [];
  3488. this.size = 0;
  3489. }
  3490. var _listCacheClear = listCacheClear;
  3491. /**
  3492. * Gets the index at which the `key` is found in `array` of key-value pairs.
  3493. *
  3494. * @private
  3495. * @param {Array} array The array to inspect.
  3496. * @param {*} key The key to search for.
  3497. * @returns {number} Returns the index of the matched value, else `-1`.
  3498. */
  3499. function assocIndexOf(array, key) {
  3500. var length = array.length;
  3501. while (length--) {
  3502. if (eq_1(array[length][0], key)) {
  3503. return length;
  3504. }
  3505. }
  3506. return -1;
  3507. }
  3508. var _assocIndexOf = assocIndexOf;
  3509. /** Used for built-in method references. */
  3510. var arrayProto = Array.prototype;
  3511. /** Built-in value references. */
  3512. var splice = arrayProto.splice;
  3513. /**
  3514. * Removes `key` and its value from the list cache.
  3515. *
  3516. * @private
  3517. * @name delete
  3518. * @memberOf ListCache
  3519. * @param {string} key The key of the value to remove.
  3520. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  3521. */
  3522. function listCacheDelete(key) {
  3523. var data = this.__data__,
  3524. index = _assocIndexOf(data, key);
  3525. if (index < 0) {
  3526. return false;
  3527. }
  3528. var lastIndex = data.length - 1;
  3529. if (index == lastIndex) {
  3530. data.pop();
  3531. } else {
  3532. splice.call(data, index, 1);
  3533. }
  3534. --this.size;
  3535. return true;
  3536. }
  3537. var _listCacheDelete = listCacheDelete;
  3538. /**
  3539. * Gets the list cache value for `key`.
  3540. *
  3541. * @private
  3542. * @name get
  3543. * @memberOf ListCache
  3544. * @param {string} key The key of the value to get.
  3545. * @returns {*} Returns the entry value.
  3546. */
  3547. function listCacheGet(key) {
  3548. var data = this.__data__,
  3549. index = _assocIndexOf(data, key);
  3550. return index < 0 ? undefined : data[index][1];
  3551. }
  3552. var _listCacheGet = listCacheGet;
  3553. /**
  3554. * Checks if a list cache value for `key` exists.
  3555. *
  3556. * @private
  3557. * @name has
  3558. * @memberOf ListCache
  3559. * @param {string} key The key of the entry to check.
  3560. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  3561. */
  3562. function listCacheHas(key) {
  3563. return _assocIndexOf(this.__data__, key) > -1;
  3564. }
  3565. var _listCacheHas = listCacheHas;
  3566. /**
  3567. * Sets the list cache `key` to `value`.
  3568. *
  3569. * @private
  3570. * @name set
  3571. * @memberOf ListCache
  3572. * @param {string} key The key of the value to set.
  3573. * @param {*} value The value to set.
  3574. * @returns {Object} Returns the list cache instance.
  3575. */
  3576. function listCacheSet(key, value) {
  3577. var data = this.__data__,
  3578. index = _assocIndexOf(data, key);
  3579. if (index < 0) {
  3580. ++this.size;
  3581. data.push([key, value]);
  3582. } else {
  3583. data[index][1] = value;
  3584. }
  3585. return this;
  3586. }
  3587. var _listCacheSet = listCacheSet;
  3588. /**
  3589. * Creates an list cache object.
  3590. *
  3591. * @private
  3592. * @constructor
  3593. * @param {Array} [entries] The key-value pairs to cache.
  3594. */
  3595. function ListCache(entries) {
  3596. var index = -1,
  3597. length = entries == null ? 0 : entries.length;
  3598. this.clear();
  3599. while (++index < length) {
  3600. var entry = entries[index];
  3601. this.set(entry[0], entry[1]);
  3602. }
  3603. }
  3604. // Add methods to `ListCache`.
  3605. ListCache.prototype.clear = _listCacheClear;
  3606. ListCache.prototype['delete'] = _listCacheDelete;
  3607. ListCache.prototype.get = _listCacheGet;
  3608. ListCache.prototype.has = _listCacheHas;
  3609. ListCache.prototype.set = _listCacheSet;
  3610. var _ListCache = ListCache;
  3611. /**
  3612. * Removes all key-value entries from the stack.
  3613. *
  3614. * @private
  3615. * @name clear
  3616. * @memberOf Stack
  3617. */
  3618. function stackClear() {
  3619. this.__data__ = new _ListCache;
  3620. this.size = 0;
  3621. }
  3622. var _stackClear = stackClear;
  3623. /**
  3624. * Removes `key` and its value from the stack.
  3625. *
  3626. * @private
  3627. * @name delete
  3628. * @memberOf Stack
  3629. * @param {string} key The key of the value to remove.
  3630. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  3631. */
  3632. function stackDelete(key) {
  3633. var data = this.__data__,
  3634. result = data['delete'](key);
  3635. this.size = data.size;
  3636. return result;
  3637. }
  3638. var _stackDelete = stackDelete;
  3639. /**
  3640. * Gets the stack value for `key`.
  3641. *
  3642. * @private
  3643. * @name get
  3644. * @memberOf Stack
  3645. * @param {string} key The key of the value to get.
  3646. * @returns {*} Returns the entry value.
  3647. */
  3648. function stackGet(key) {
  3649. return this.__data__.get(key);
  3650. }
  3651. var _stackGet = stackGet;
  3652. /**
  3653. * Checks if a stack value for `key` exists.
  3654. *
  3655. * @private
  3656. * @name has
  3657. * @memberOf Stack
  3658. * @param {string} key The key of the entry to check.
  3659. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  3660. */
  3661. function stackHas(key) {
  3662. return this.__data__.has(key);
  3663. }
  3664. var _stackHas = stackHas;
  3665. /* Built-in method references that are verified to be native. */
  3666. var Map$1 = _getNative(_root, 'Map');
  3667. var _Map = Map$1;
  3668. /* Built-in method references that are verified to be native. */
  3669. var nativeCreate = _getNative(Object, 'create');
  3670. var _nativeCreate = nativeCreate;
  3671. /**
  3672. * Removes all key-value entries from the hash.
  3673. *
  3674. * @private
  3675. * @name clear
  3676. * @memberOf Hash
  3677. */
  3678. function hashClear() {
  3679. this.__data__ = _nativeCreate ? _nativeCreate(null) : {};
  3680. this.size = 0;
  3681. }
  3682. var _hashClear = hashClear;
  3683. /**
  3684. * Removes `key` and its value from the hash.
  3685. *
  3686. * @private
  3687. * @name delete
  3688. * @memberOf Hash
  3689. * @param {Object} hash The hash to modify.
  3690. * @param {string} key The key of the value to remove.
  3691. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  3692. */
  3693. function hashDelete(key) {
  3694. var result = this.has(key) && delete this.__data__[key];
  3695. this.size -= result ? 1 : 0;
  3696. return result;
  3697. }
  3698. var _hashDelete = hashDelete;
  3699. /** Used to stand-in for `undefined` hash values. */
  3700. var HASH_UNDEFINED$2 = '__lodash_hash_undefined__';
  3701. /** Used for built-in method references. */
  3702. var objectProto$7 = Object.prototype;
  3703. /** Used to check objects for own properties. */
  3704. var hasOwnProperty$6 = objectProto$7.hasOwnProperty;
  3705. /**
  3706. * Gets the hash value for `key`.
  3707. *
  3708. * @private
  3709. * @name get
  3710. * @memberOf Hash
  3711. * @param {string} key The key of the value to get.
  3712. * @returns {*} Returns the entry value.
  3713. */
  3714. function hashGet(key) {
  3715. var data = this.__data__;
  3716. if (_nativeCreate) {
  3717. var result = data[key];
  3718. return result === HASH_UNDEFINED$2 ? undefined : result;
  3719. }
  3720. return hasOwnProperty$6.call(data, key) ? data[key] : undefined;
  3721. }
  3722. var _hashGet = hashGet;
  3723. /** Used for built-in method references. */
  3724. var objectProto$6 = Object.prototype;
  3725. /** Used to check objects for own properties. */
  3726. var hasOwnProperty$5 = objectProto$6.hasOwnProperty;
  3727. /**
  3728. * Checks if a hash value for `key` exists.
  3729. *
  3730. * @private
  3731. * @name has
  3732. * @memberOf Hash
  3733. * @param {string} key The key of the entry to check.
  3734. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  3735. */
  3736. function hashHas(key) {
  3737. var data = this.__data__;
  3738. return _nativeCreate ? (data[key] !== undefined) : hasOwnProperty$5.call(data, key);
  3739. }
  3740. var _hashHas = hashHas;
  3741. /** Used to stand-in for `undefined` hash values. */
  3742. var HASH_UNDEFINED$1 = '__lodash_hash_undefined__';
  3743. /**
  3744. * Sets the hash `key` to `value`.
  3745. *
  3746. * @private
  3747. * @name set
  3748. * @memberOf Hash
  3749. * @param {string} key The key of the value to set.
  3750. * @param {*} value The value to set.
  3751. * @returns {Object} Returns the hash instance.
  3752. */
  3753. function hashSet(key, value) {
  3754. var data = this.__data__;
  3755. this.size += this.has(key) ? 0 : 1;
  3756. data[key] = (_nativeCreate && value === undefined) ? HASH_UNDEFINED$1 : value;
  3757. return this;
  3758. }
  3759. var _hashSet = hashSet;
  3760. /**
  3761. * Creates a hash object.
  3762. *
  3763. * @private
  3764. * @constructor
  3765. * @param {Array} [entries] The key-value pairs to cache.
  3766. */
  3767. function Hash(entries) {
  3768. var index = -1,
  3769. length = entries == null ? 0 : entries.length;
  3770. this.clear();
  3771. while (++index < length) {
  3772. var entry = entries[index];
  3773. this.set(entry[0], entry[1]);
  3774. }
  3775. }
  3776. // Add methods to `Hash`.
  3777. Hash.prototype.clear = _hashClear;
  3778. Hash.prototype['delete'] = _hashDelete;
  3779. Hash.prototype.get = _hashGet;
  3780. Hash.prototype.has = _hashHas;
  3781. Hash.prototype.set = _hashSet;
  3782. var _Hash = Hash;
  3783. /**
  3784. * Removes all key-value entries from the map.
  3785. *
  3786. * @private
  3787. * @name clear
  3788. * @memberOf MapCache
  3789. */
  3790. function mapCacheClear() {
  3791. this.size = 0;
  3792. this.__data__ = {
  3793. 'hash': new _Hash,
  3794. 'map': new (_Map || _ListCache),
  3795. 'string': new _Hash
  3796. };
  3797. }
  3798. var _mapCacheClear = mapCacheClear;
  3799. /**
  3800. * Checks if `value` is suitable for use as unique object key.
  3801. *
  3802. * @private
  3803. * @param {*} value The value to check.
  3804. * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
  3805. */
  3806. function isKeyable(value) {
  3807. var type = typeof value;
  3808. return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
  3809. ? (value !== '__proto__')
  3810. : (value === null);
  3811. }
  3812. var _isKeyable = isKeyable;
  3813. /**
  3814. * Gets the data for `map`.
  3815. *
  3816. * @private
  3817. * @param {Object} map The map to query.
  3818. * @param {string} key The reference key.
  3819. * @returns {*} Returns the map data.
  3820. */
  3821. function getMapData(map, key) {
  3822. var data = map.__data__;
  3823. return _isKeyable(key)
  3824. ? data[typeof key == 'string' ? 'string' : 'hash']
  3825. : data.map;
  3826. }
  3827. var _getMapData = getMapData;
  3828. /**
  3829. * Removes `key` and its value from the map.
  3830. *
  3831. * @private
  3832. * @name delete
  3833. * @memberOf MapCache
  3834. * @param {string} key The key of the value to remove.
  3835. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  3836. */
  3837. function mapCacheDelete(key) {
  3838. var result = _getMapData(this, key)['delete'](key);
  3839. this.size -= result ? 1 : 0;
  3840. return result;
  3841. }
  3842. var _mapCacheDelete = mapCacheDelete;
  3843. /**
  3844. * Gets the map value for `key`.
  3845. *
  3846. * @private
  3847. * @name get
  3848. * @memberOf MapCache
  3849. * @param {string} key The key of the value to get.
  3850. * @returns {*} Returns the entry value.
  3851. */
  3852. function mapCacheGet(key) {
  3853. return _getMapData(this, key).get(key);
  3854. }
  3855. var _mapCacheGet = mapCacheGet;
  3856. /**
  3857. * Checks if a map value for `key` exists.
  3858. *
  3859. * @private
  3860. * @name has
  3861. * @memberOf MapCache
  3862. * @param {string} key The key of the entry to check.
  3863. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  3864. */
  3865. function mapCacheHas(key) {
  3866. return _getMapData(this, key).has(key);
  3867. }
  3868. var _mapCacheHas = mapCacheHas;
  3869. /**
  3870. * Sets the map `key` to `value`.
  3871. *
  3872. * @private
  3873. * @name set
  3874. * @memberOf MapCache
  3875. * @param {string} key The key of the value to set.
  3876. * @param {*} value The value to set.
  3877. * @returns {Object} Returns the map cache instance.
  3878. */
  3879. function mapCacheSet(key, value) {
  3880. var data = _getMapData(this, key),
  3881. size = data.size;
  3882. data.set(key, value);
  3883. this.size += data.size == size ? 0 : 1;
  3884. return this;
  3885. }
  3886. var _mapCacheSet = mapCacheSet;
  3887. /**
  3888. * Creates a map cache object to store key-value pairs.
  3889. *
  3890. * @private
  3891. * @constructor
  3892. * @param {Array} [entries] The key-value pairs to cache.
  3893. */
  3894. function MapCache(entries) {
  3895. var index = -1,
  3896. length = entries == null ? 0 : entries.length;
  3897. this.clear();
  3898. while (++index < length) {
  3899. var entry = entries[index];
  3900. this.set(entry[0], entry[1]);
  3901. }
  3902. }
  3903. // Add methods to `MapCache`.
  3904. MapCache.prototype.clear = _mapCacheClear;
  3905. MapCache.prototype['delete'] = _mapCacheDelete;
  3906. MapCache.prototype.get = _mapCacheGet;
  3907. MapCache.prototype.has = _mapCacheHas;
  3908. MapCache.prototype.set = _mapCacheSet;
  3909. var _MapCache = MapCache;
  3910. /** Used as the size to enable large array optimizations. */
  3911. var LARGE_ARRAY_SIZE = 200;
  3912. /**
  3913. * Sets the stack `key` to `value`.
  3914. *
  3915. * @private
  3916. * @name set
  3917. * @memberOf Stack
  3918. * @param {string} key The key of the value to set.
  3919. * @param {*} value The value to set.
  3920. * @returns {Object} Returns the stack cache instance.
  3921. */
  3922. function stackSet(key, value) {
  3923. var data = this.__data__;
  3924. if (data instanceof _ListCache) {
  3925. var pairs = data.__data__;
  3926. if (!_Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
  3927. pairs.push([key, value]);
  3928. this.size = ++data.size;
  3929. return this;
  3930. }
  3931. data = this.__data__ = new _MapCache(pairs);
  3932. }
  3933. data.set(key, value);
  3934. this.size = data.size;
  3935. return this;
  3936. }
  3937. var _stackSet = stackSet;
  3938. /**
  3939. * Creates a stack cache object to store key-value pairs.
  3940. *
  3941. * @private
  3942. * @constructor
  3943. * @param {Array} [entries] The key-value pairs to cache.
  3944. */
  3945. function Stack(entries) {
  3946. var data = this.__data__ = new _ListCache(entries);
  3947. this.size = data.size;
  3948. }
  3949. // Add methods to `Stack`.
  3950. Stack.prototype.clear = _stackClear;
  3951. Stack.prototype['delete'] = _stackDelete;
  3952. Stack.prototype.get = _stackGet;
  3953. Stack.prototype.has = _stackHas;
  3954. Stack.prototype.set = _stackSet;
  3955. var _Stack = Stack;
  3956. /**
  3957. * This function is like
  3958. * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
  3959. * except that it includes inherited enumerable properties.
  3960. *
  3961. * @private
  3962. * @param {Object} object The object to query.
  3963. * @returns {Array} Returns the array of property names.
  3964. */
  3965. function nativeKeysIn(object) {
  3966. var result = [];
  3967. if (object != null) {
  3968. for (var key in Object(object)) {
  3969. result.push(key);
  3970. }
  3971. }
  3972. return result;
  3973. }
  3974. var _nativeKeysIn = nativeKeysIn;
  3975. /** Used for built-in method references. */
  3976. var objectProto$5 = Object.prototype;
  3977. /** Used to check objects for own properties. */
  3978. var hasOwnProperty$4 = objectProto$5.hasOwnProperty;
  3979. /**
  3980. * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
  3981. *
  3982. * @private
  3983. * @param {Object} object The object to query.
  3984. * @returns {Array} Returns the array of property names.
  3985. */
  3986. function baseKeysIn(object) {
  3987. if (!isObject_1(object)) {
  3988. return _nativeKeysIn(object);
  3989. }
  3990. var isProto = _isPrototype(object),
  3991. result = [];
  3992. for (var key in object) {
  3993. if (!(key == 'constructor' && (isProto || !hasOwnProperty$4.call(object, key)))) {
  3994. result.push(key);
  3995. }
  3996. }
  3997. return result;
  3998. }
  3999. var _baseKeysIn = baseKeysIn;
  4000. /**
  4001. * Creates an array of the own and inherited enumerable property names of `object`.
  4002. *
  4003. * **Note:** Non-object values are coerced to objects.
  4004. *
  4005. * @static
  4006. * @memberOf _
  4007. * @since 3.0.0
  4008. * @category Object
  4009. * @param {Object} object The object to query.
  4010. * @returns {Array} Returns the array of property names.
  4011. * @example
  4012. *
  4013. * function Foo() {
  4014. * this.a = 1;
  4015. * this.b = 2;
  4016. * }
  4017. *
  4018. * Foo.prototype.c = 3;
  4019. *
  4020. * _.keysIn(new Foo);
  4021. * // => ['a', 'b', 'c'] (iteration order is not guaranteed)
  4022. */
  4023. function keysIn(object) {
  4024. return isArrayLike_1(object) ? _arrayLikeKeys(object, true) : _baseKeysIn(object);
  4025. }
  4026. var keysIn_1 = keysIn;
  4027. /**
  4028. * The base implementation of `_.assignIn` without support for multiple sources
  4029. * or `customizer` functions.
  4030. *
  4031. * @private
  4032. * @param {Object} object The destination object.
  4033. * @param {Object} source The source object.
  4034. * @returns {Object} Returns `object`.
  4035. */
  4036. function baseAssignIn(object, source) {
  4037. return object && _copyObject(source, keysIn_1(source), object);
  4038. }
  4039. var _baseAssignIn = baseAssignIn;
  4040. var _cloneBuffer = createCommonjsModule(function (module, exports) {
  4041. /** Detect free variable `exports`. */
  4042. var freeExports = exports && !exports.nodeType && exports;
  4043. /** Detect free variable `module`. */
  4044. var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
  4045. /** Detect the popular CommonJS extension `module.exports`. */
  4046. var moduleExports = freeModule && freeModule.exports === freeExports;
  4047. /** Built-in value references. */
  4048. var Buffer = moduleExports ? _root.Buffer : undefined,
  4049. allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined;
  4050. /**
  4051. * Creates a clone of `buffer`.
  4052. *
  4053. * @private
  4054. * @param {Buffer} buffer The buffer to clone.
  4055. * @param {boolean} [isDeep] Specify a deep clone.
  4056. * @returns {Buffer} Returns the cloned buffer.
  4057. */
  4058. function cloneBuffer(buffer, isDeep) {
  4059. if (isDeep) {
  4060. return buffer.slice();
  4061. }
  4062. var length = buffer.length,
  4063. result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
  4064. buffer.copy(result);
  4065. return result;
  4066. }
  4067. module.exports = cloneBuffer;
  4068. }, "/$$rollup_base$$/node_modules/lodash");
  4069. /**
  4070. * A specialized version of `_.filter` for arrays without support for
  4071. * iteratee shorthands.
  4072. *
  4073. * @private
  4074. * @param {Array} [array] The array to iterate over.
  4075. * @param {Function} predicate The function invoked per iteration.
  4076. * @returns {Array} Returns the new filtered array.
  4077. */
  4078. function arrayFilter(array, predicate) {
  4079. var index = -1,
  4080. length = array == null ? 0 : array.length,
  4081. resIndex = 0,
  4082. result = [];
  4083. while (++index < length) {
  4084. var value = array[index];
  4085. if (predicate(value, index, array)) {
  4086. result[resIndex++] = value;
  4087. }
  4088. }
  4089. return result;
  4090. }
  4091. var _arrayFilter = arrayFilter;
  4092. /**
  4093. * This method returns a new empty array.
  4094. *
  4095. * @static
  4096. * @memberOf _
  4097. * @since 4.13.0
  4098. * @category Util
  4099. * @returns {Array} Returns the new empty array.
  4100. * @example
  4101. *
  4102. * var arrays = _.times(2, _.stubArray);
  4103. *
  4104. * console.log(arrays);
  4105. * // => [[], []]
  4106. *
  4107. * console.log(arrays[0] === arrays[1]);
  4108. * // => false
  4109. */
  4110. function stubArray() {
  4111. return [];
  4112. }
  4113. var stubArray_1 = stubArray;
  4114. /** Used for built-in method references. */
  4115. var objectProto$4 = Object.prototype;
  4116. /** Built-in value references. */
  4117. var propertyIsEnumerable = objectProto$4.propertyIsEnumerable;
  4118. /* Built-in method references for those with the same name as other `lodash` methods. */
  4119. var nativeGetSymbols$1 = Object.getOwnPropertySymbols;
  4120. /**
  4121. * Creates an array of the own enumerable symbols of `object`.
  4122. *
  4123. * @private
  4124. * @param {Object} object The object to query.
  4125. * @returns {Array} Returns the array of symbols.
  4126. */
  4127. var getSymbols = !nativeGetSymbols$1 ? stubArray_1 : function(object) {
  4128. if (object == null) {
  4129. return [];
  4130. }
  4131. object = Object(object);
  4132. return _arrayFilter(nativeGetSymbols$1(object), function(symbol) {
  4133. return propertyIsEnumerable.call(object, symbol);
  4134. });
  4135. };
  4136. var _getSymbols = getSymbols;
  4137. /**
  4138. * Copies own symbols of `source` to `object`.
  4139. *
  4140. * @private
  4141. * @param {Object} source The object to copy symbols from.
  4142. * @param {Object} [object={}] The object to copy symbols to.
  4143. * @returns {Object} Returns `object`.
  4144. */
  4145. function copySymbols(source, object) {
  4146. return _copyObject(source, _getSymbols(source), object);
  4147. }
  4148. var _copySymbols = copySymbols;
  4149. /**
  4150. * Appends the elements of `values` to `array`.
  4151. *
  4152. * @private
  4153. * @param {Array} array The array to modify.
  4154. * @param {Array} values The values to append.
  4155. * @returns {Array} Returns `array`.
  4156. */
  4157. function arrayPush(array, values) {
  4158. var index = -1,
  4159. length = values.length,
  4160. offset = array.length;
  4161. while (++index < length) {
  4162. array[offset + index] = values[index];
  4163. }
  4164. return array;
  4165. }
  4166. var _arrayPush = arrayPush;
  4167. /** Built-in value references. */
  4168. var getPrototype = _overArg(Object.getPrototypeOf, Object);
  4169. var _getPrototype = getPrototype;
  4170. /* Built-in method references for those with the same name as other `lodash` methods. */
  4171. var nativeGetSymbols = Object.getOwnPropertySymbols;
  4172. /**
  4173. * Creates an array of the own and inherited enumerable symbols of `object`.
  4174. *
  4175. * @private
  4176. * @param {Object} object The object to query.
  4177. * @returns {Array} Returns the array of symbols.
  4178. */
  4179. var getSymbolsIn = !nativeGetSymbols ? stubArray_1 : function(object) {
  4180. var result = [];
  4181. while (object) {
  4182. _arrayPush(result, _getSymbols(object));
  4183. object = _getPrototype(object);
  4184. }
  4185. return result;
  4186. };
  4187. var _getSymbolsIn = getSymbolsIn;
  4188. /**
  4189. * Copies own and inherited symbols of `source` to `object`.
  4190. *
  4191. * @private
  4192. * @param {Object} source The object to copy symbols from.
  4193. * @param {Object} [object={}] The object to copy symbols to.
  4194. * @returns {Object} Returns `object`.
  4195. */
  4196. function copySymbolsIn(source, object) {
  4197. return _copyObject(source, _getSymbolsIn(source), object);
  4198. }
  4199. var _copySymbolsIn = copySymbolsIn;
  4200. /**
  4201. * The base implementation of `getAllKeys` and `getAllKeysIn` which uses
  4202. * `keysFunc` and `symbolsFunc` to get the enumerable property names and
  4203. * symbols of `object`.
  4204. *
  4205. * @private
  4206. * @param {Object} object The object to query.
  4207. * @param {Function} keysFunc The function to get the keys of `object`.
  4208. * @param {Function} symbolsFunc The function to get the symbols of `object`.
  4209. * @returns {Array} Returns the array of property names and symbols.
  4210. */
  4211. function baseGetAllKeys(object, keysFunc, symbolsFunc) {
  4212. var result = keysFunc(object);
  4213. return isArray_1(object) ? result : _arrayPush(result, symbolsFunc(object));
  4214. }
  4215. var _baseGetAllKeys = baseGetAllKeys;
  4216. /**
  4217. * Creates an array of own enumerable property names and symbols of `object`.
  4218. *
  4219. * @private
  4220. * @param {Object} object The object to query.
  4221. * @returns {Array} Returns the array of property names and symbols.
  4222. */
  4223. function getAllKeys(object) {
  4224. return _baseGetAllKeys(object, keys_1, _getSymbols);
  4225. }
  4226. var _getAllKeys = getAllKeys;
  4227. /**
  4228. * Creates an array of own and inherited enumerable property names and
  4229. * symbols of `object`.
  4230. *
  4231. * @private
  4232. * @param {Object} object The object to query.
  4233. * @returns {Array} Returns the array of property names and symbols.
  4234. */
  4235. function getAllKeysIn(object) {
  4236. return _baseGetAllKeys(object, keysIn_1, _getSymbolsIn);
  4237. }
  4238. var _getAllKeysIn = getAllKeysIn;
  4239. /* Built-in method references that are verified to be native. */
  4240. var DataView = _getNative(_root, 'DataView');
  4241. var _DataView = DataView;
  4242. /* Built-in method references that are verified to be native. */
  4243. var Promise$1 = _getNative(_root, 'Promise');
  4244. var _Promise = Promise$1;
  4245. /* Built-in method references that are verified to be native. */
  4246. var Set$1 = _getNative(_root, 'Set');
  4247. var _Set = Set$1;
  4248. /** `Object#toString` result references. */
  4249. var mapTag$4 = '[object Map]',
  4250. objectTag$3 = '[object Object]',
  4251. promiseTag = '[object Promise]',
  4252. setTag$4 = '[object Set]',
  4253. weakMapTag$2 = '[object WeakMap]';
  4254. var dataViewTag$3 = '[object DataView]';
  4255. /** Used to detect maps, sets, and weakmaps. */
  4256. var dataViewCtorString = _toSource(_DataView),
  4257. mapCtorString = _toSource(_Map),
  4258. promiseCtorString = _toSource(_Promise),
  4259. setCtorString = _toSource(_Set),
  4260. weakMapCtorString = _toSource(_WeakMap);
  4261. /**
  4262. * Gets the `toStringTag` of `value`.
  4263. *
  4264. * @private
  4265. * @param {*} value The value to query.
  4266. * @returns {string} Returns the `toStringTag`.
  4267. */
  4268. var getTag = _baseGetTag;
  4269. // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
  4270. if ((_DataView && getTag(new _DataView(new ArrayBuffer(1))) != dataViewTag$3) ||
  4271. (_Map && getTag(new _Map) != mapTag$4) ||
  4272. (_Promise && getTag(_Promise.resolve()) != promiseTag) ||
  4273. (_Set && getTag(new _Set) != setTag$4) ||
  4274. (_WeakMap && getTag(new _WeakMap) != weakMapTag$2)) {
  4275. getTag = function(value) {
  4276. var result = _baseGetTag(value),
  4277. Ctor = result == objectTag$3 ? value.constructor : undefined,
  4278. ctorString = Ctor ? _toSource(Ctor) : '';
  4279. if (ctorString) {
  4280. switch (ctorString) {
  4281. case dataViewCtorString: return dataViewTag$3;
  4282. case mapCtorString: return mapTag$4;
  4283. case promiseCtorString: return promiseTag;
  4284. case setCtorString: return setTag$4;
  4285. case weakMapCtorString: return weakMapTag$2;
  4286. }
  4287. }
  4288. return result;
  4289. };
  4290. }
  4291. var _getTag = getTag;
  4292. /** Used for built-in method references. */
  4293. var objectProto$3 = Object.prototype;
  4294. /** Used to check objects for own properties. */
  4295. var hasOwnProperty$3 = objectProto$3.hasOwnProperty;
  4296. /**
  4297. * Initializes an array clone.
  4298. *
  4299. * @private
  4300. * @param {Array} array The array to clone.
  4301. * @returns {Array} Returns the initialized clone.
  4302. */
  4303. function initCloneArray(array) {
  4304. var length = array.length,
  4305. result = new array.constructor(length);
  4306. // Add properties assigned by `RegExp#exec`.
  4307. if (length && typeof array[0] == 'string' && hasOwnProperty$3.call(array, 'index')) {
  4308. result.index = array.index;
  4309. result.input = array.input;
  4310. }
  4311. return result;
  4312. }
  4313. var _initCloneArray = initCloneArray;
  4314. /** Built-in value references. */
  4315. var Uint8Array$1 = _root.Uint8Array;
  4316. var _Uint8Array = Uint8Array$1;
  4317. /**
  4318. * Creates a clone of `arrayBuffer`.
  4319. *
  4320. * @private
  4321. * @param {ArrayBuffer} arrayBuffer The array buffer to clone.
  4322. * @returns {ArrayBuffer} Returns the cloned array buffer.
  4323. */
  4324. function cloneArrayBuffer(arrayBuffer) {
  4325. var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
  4326. new _Uint8Array(result).set(new _Uint8Array(arrayBuffer));
  4327. return result;
  4328. }
  4329. var _cloneArrayBuffer = cloneArrayBuffer;
  4330. /**
  4331. * Creates a clone of `dataView`.
  4332. *
  4333. * @private
  4334. * @param {Object} dataView The data view to clone.
  4335. * @param {boolean} [isDeep] Specify a deep clone.
  4336. * @returns {Object} Returns the cloned data view.
  4337. */
  4338. function cloneDataView(dataView, isDeep) {
  4339. var buffer = isDeep ? _cloneArrayBuffer(dataView.buffer) : dataView.buffer;
  4340. return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
  4341. }
  4342. var _cloneDataView = cloneDataView;
  4343. /** Used to match `RegExp` flags from their coerced string values. */
  4344. var reFlags = /\w*$/;
  4345. /**
  4346. * Creates a clone of `regexp`.
  4347. *
  4348. * @private
  4349. * @param {Object} regexp The regexp to clone.
  4350. * @returns {Object} Returns the cloned regexp.
  4351. */
  4352. function cloneRegExp(regexp) {
  4353. var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
  4354. result.lastIndex = regexp.lastIndex;
  4355. return result;
  4356. }
  4357. var _cloneRegExp = cloneRegExp;
  4358. /** Used to convert symbols to primitives and strings. */
  4359. var symbolProto$2 = _Symbol ? _Symbol.prototype : undefined,
  4360. symbolValueOf$1 = symbolProto$2 ? symbolProto$2.valueOf : undefined;
  4361. /**
  4362. * Creates a clone of the `symbol` object.
  4363. *
  4364. * @private
  4365. * @param {Object} symbol The symbol object to clone.
  4366. * @returns {Object} Returns the cloned symbol object.
  4367. */
  4368. function cloneSymbol(symbol) {
  4369. return symbolValueOf$1 ? Object(symbolValueOf$1.call(symbol)) : {};
  4370. }
  4371. var _cloneSymbol = cloneSymbol;
  4372. /**
  4373. * Creates a clone of `typedArray`.
  4374. *
  4375. * @private
  4376. * @param {Object} typedArray The typed array to clone.
  4377. * @param {boolean} [isDeep] Specify a deep clone.
  4378. * @returns {Object} Returns the cloned typed array.
  4379. */
  4380. function cloneTypedArray(typedArray, isDeep) {
  4381. var buffer = isDeep ? _cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
  4382. return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
  4383. }
  4384. var _cloneTypedArray = cloneTypedArray;
  4385. /** `Object#toString` result references. */
  4386. var boolTag$2 = '[object Boolean]',
  4387. dateTag$2 = '[object Date]',
  4388. mapTag$3 = '[object Map]',
  4389. numberTag$2 = '[object Number]',
  4390. regexpTag$2 = '[object RegExp]',
  4391. setTag$3 = '[object Set]',
  4392. stringTag$2 = '[object String]',
  4393. symbolTag$2 = '[object Symbol]';
  4394. var arrayBufferTag$2 = '[object ArrayBuffer]',
  4395. dataViewTag$2 = '[object DataView]',
  4396. float32Tag$1 = '[object Float32Array]',
  4397. float64Tag$1 = '[object Float64Array]',
  4398. int8Tag$1 = '[object Int8Array]',
  4399. int16Tag$1 = '[object Int16Array]',
  4400. int32Tag$1 = '[object Int32Array]',
  4401. uint8Tag$1 = '[object Uint8Array]',
  4402. uint8ClampedTag$1 = '[object Uint8ClampedArray]',
  4403. uint16Tag$1 = '[object Uint16Array]',
  4404. uint32Tag$1 = '[object Uint32Array]';
  4405. /**
  4406. * Initializes an object clone based on its `toStringTag`.
  4407. *
  4408. * **Note:** This function only supports cloning values with tags of
  4409. * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.
  4410. *
  4411. * @private
  4412. * @param {Object} object The object to clone.
  4413. * @param {string} tag The `toStringTag` of the object to clone.
  4414. * @param {boolean} [isDeep] Specify a deep clone.
  4415. * @returns {Object} Returns the initialized clone.
  4416. */
  4417. function initCloneByTag(object, tag, isDeep) {
  4418. var Ctor = object.constructor;
  4419. switch (tag) {
  4420. case arrayBufferTag$2:
  4421. return _cloneArrayBuffer(object);
  4422. case boolTag$2:
  4423. case dateTag$2:
  4424. return new Ctor(+object);
  4425. case dataViewTag$2:
  4426. return _cloneDataView(object, isDeep);
  4427. case float32Tag$1: case float64Tag$1:
  4428. case int8Tag$1: case int16Tag$1: case int32Tag$1:
  4429. case uint8Tag$1: case uint8ClampedTag$1: case uint16Tag$1: case uint32Tag$1:
  4430. return _cloneTypedArray(object, isDeep);
  4431. case mapTag$3:
  4432. return new Ctor;
  4433. case numberTag$2:
  4434. case stringTag$2:
  4435. return new Ctor(object);
  4436. case regexpTag$2:
  4437. return _cloneRegExp(object);
  4438. case setTag$3:
  4439. return new Ctor;
  4440. case symbolTag$2:
  4441. return _cloneSymbol(object);
  4442. }
  4443. }
  4444. var _initCloneByTag = initCloneByTag;
  4445. /**
  4446. * Initializes an object clone.
  4447. *
  4448. * @private
  4449. * @param {Object} object The object to clone.
  4450. * @returns {Object} Returns the initialized clone.
  4451. */
  4452. function initCloneObject(object) {
  4453. return (typeof object.constructor == 'function' && !_isPrototype(object))
  4454. ? _baseCreate(_getPrototype(object))
  4455. : {};
  4456. }
  4457. var _initCloneObject = initCloneObject;
  4458. /** `Object#toString` result references. */
  4459. var mapTag$2 = '[object Map]';
  4460. /**
  4461. * The base implementation of `_.isMap` without Node.js optimizations.
  4462. *
  4463. * @private
  4464. * @param {*} value The value to check.
  4465. * @returns {boolean} Returns `true` if `value` is a map, else `false`.
  4466. */
  4467. function baseIsMap(value) {
  4468. return isObjectLike_1(value) && _getTag(value) == mapTag$2;
  4469. }
  4470. var _baseIsMap = baseIsMap;
  4471. /* Node.js helper references. */
  4472. var nodeIsMap = _nodeUtil && _nodeUtil.isMap;
  4473. /**
  4474. * Checks if `value` is classified as a `Map` object.
  4475. *
  4476. * @static
  4477. * @memberOf _
  4478. * @since 4.3.0
  4479. * @category Lang
  4480. * @param {*} value The value to check.
  4481. * @returns {boolean} Returns `true` if `value` is a map, else `false`.
  4482. * @example
  4483. *
  4484. * _.isMap(new Map);
  4485. * // => true
  4486. *
  4487. * _.isMap(new WeakMap);
  4488. * // => false
  4489. */
  4490. var isMap = nodeIsMap ? _baseUnary(nodeIsMap) : _baseIsMap;
  4491. var isMap_1 = isMap;
  4492. /** `Object#toString` result references. */
  4493. var setTag$2 = '[object Set]';
  4494. /**
  4495. * The base implementation of `_.isSet` without Node.js optimizations.
  4496. *
  4497. * @private
  4498. * @param {*} value The value to check.
  4499. * @returns {boolean} Returns `true` if `value` is a set, else `false`.
  4500. */
  4501. function baseIsSet(value) {
  4502. return isObjectLike_1(value) && _getTag(value) == setTag$2;
  4503. }
  4504. var _baseIsSet = baseIsSet;
  4505. /* Node.js helper references. */
  4506. var nodeIsSet = _nodeUtil && _nodeUtil.isSet;
  4507. /**
  4508. * Checks if `value` is classified as a `Set` object.
  4509. *
  4510. * @static
  4511. * @memberOf _
  4512. * @since 4.3.0
  4513. * @category Lang
  4514. * @param {*} value The value to check.
  4515. * @returns {boolean} Returns `true` if `value` is a set, else `false`.
  4516. * @example
  4517. *
  4518. * _.isSet(new Set);
  4519. * // => true
  4520. *
  4521. * _.isSet(new WeakSet);
  4522. * // => false
  4523. */
  4524. var isSet = nodeIsSet ? _baseUnary(nodeIsSet) : _baseIsSet;
  4525. var isSet_1 = isSet;
  4526. /** Used to compose bitmasks for cloning. */
  4527. var CLONE_DEEP_FLAG$1 = 1,
  4528. CLONE_FLAT_FLAG = 2,
  4529. CLONE_SYMBOLS_FLAG$1 = 4;
  4530. /** `Object#toString` result references. */
  4531. var argsTag$1 = '[object Arguments]',
  4532. arrayTag$1 = '[object Array]',
  4533. boolTag$1 = '[object Boolean]',
  4534. dateTag$1 = '[object Date]',
  4535. errorTag$2 = '[object Error]',
  4536. funcTag = '[object Function]',
  4537. genTag = '[object GeneratorFunction]',
  4538. mapTag$1 = '[object Map]',
  4539. numberTag$1 = '[object Number]',
  4540. objectTag$2 = '[object Object]',
  4541. regexpTag$1 = '[object RegExp]',
  4542. setTag$1 = '[object Set]',
  4543. stringTag$1 = '[object String]',
  4544. symbolTag$1 = '[object Symbol]',
  4545. weakMapTag$1 = '[object WeakMap]';
  4546. var arrayBufferTag$1 = '[object ArrayBuffer]',
  4547. dataViewTag$1 = '[object DataView]',
  4548. float32Tag = '[object Float32Array]',
  4549. float64Tag = '[object Float64Array]',
  4550. int8Tag = '[object Int8Array]',
  4551. int16Tag = '[object Int16Array]',
  4552. int32Tag = '[object Int32Array]',
  4553. uint8Tag = '[object Uint8Array]',
  4554. uint8ClampedTag = '[object Uint8ClampedArray]',
  4555. uint16Tag = '[object Uint16Array]',
  4556. uint32Tag = '[object Uint32Array]';
  4557. /** Used to identify `toStringTag` values supported by `_.clone`. */
  4558. var cloneableTags = {};
  4559. cloneableTags[argsTag$1] = cloneableTags[arrayTag$1] =
  4560. cloneableTags[arrayBufferTag$1] = cloneableTags[dataViewTag$1] =
  4561. cloneableTags[boolTag$1] = cloneableTags[dateTag$1] =
  4562. cloneableTags[float32Tag] = cloneableTags[float64Tag] =
  4563. cloneableTags[int8Tag] = cloneableTags[int16Tag] =
  4564. cloneableTags[int32Tag] = cloneableTags[mapTag$1] =
  4565. cloneableTags[numberTag$1] = cloneableTags[objectTag$2] =
  4566. cloneableTags[regexpTag$1] = cloneableTags[setTag$1] =
  4567. cloneableTags[stringTag$1] = cloneableTags[symbolTag$1] =
  4568. cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =
  4569. cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
  4570. cloneableTags[errorTag$2] = cloneableTags[funcTag] =
  4571. cloneableTags[weakMapTag$1] = false;
  4572. /**
  4573. * The base implementation of `_.clone` and `_.cloneDeep` which tracks
  4574. * traversed objects.
  4575. *
  4576. * @private
  4577. * @param {*} value The value to clone.
  4578. * @param {boolean} bitmask The bitmask flags.
  4579. * 1 - Deep clone
  4580. * 2 - Flatten inherited properties
  4581. * 4 - Clone symbols
  4582. * @param {Function} [customizer] The function to customize cloning.
  4583. * @param {string} [key] The key of `value`.
  4584. * @param {Object} [object] The parent object of `value`.
  4585. * @param {Object} [stack] Tracks traversed objects and their clone counterparts.
  4586. * @returns {*} Returns the cloned value.
  4587. */
  4588. function baseClone(value, bitmask, customizer, key, object, stack) {
  4589. var result,
  4590. isDeep = bitmask & CLONE_DEEP_FLAG$1,
  4591. isFlat = bitmask & CLONE_FLAT_FLAG,
  4592. isFull = bitmask & CLONE_SYMBOLS_FLAG$1;
  4593. if (customizer) {
  4594. result = object ? customizer(value, key, object, stack) : customizer(value);
  4595. }
  4596. if (result !== undefined) {
  4597. return result;
  4598. }
  4599. if (!isObject_1(value)) {
  4600. return value;
  4601. }
  4602. var isArr = isArray_1(value);
  4603. if (isArr) {
  4604. result = _initCloneArray(value);
  4605. if (!isDeep) {
  4606. return _copyArray(value, result);
  4607. }
  4608. } else {
  4609. var tag = _getTag(value),
  4610. isFunc = tag == funcTag || tag == genTag;
  4611. if (isBuffer_1(value)) {
  4612. return _cloneBuffer(value, isDeep);
  4613. }
  4614. if (tag == objectTag$2 || tag == argsTag$1 || (isFunc && !object)) {
  4615. result = (isFlat || isFunc) ? {} : _initCloneObject(value);
  4616. if (!isDeep) {
  4617. return isFlat
  4618. ? _copySymbolsIn(value, _baseAssignIn(result, value))
  4619. : _copySymbols(value, _baseAssign(result, value));
  4620. }
  4621. } else {
  4622. if (!cloneableTags[tag]) {
  4623. return object ? value : {};
  4624. }
  4625. result = _initCloneByTag(value, tag, isDeep);
  4626. }
  4627. }
  4628. // Check for circular references and return its corresponding clone.
  4629. stack || (stack = new _Stack);
  4630. var stacked = stack.get(value);
  4631. if (stacked) {
  4632. return stacked;
  4633. }
  4634. stack.set(value, result);
  4635. if (isSet_1(value)) {
  4636. value.forEach(function(subValue) {
  4637. result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));
  4638. });
  4639. } else if (isMap_1(value)) {
  4640. value.forEach(function(subValue, key) {
  4641. result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));
  4642. });
  4643. }
  4644. var keysFunc = isFull
  4645. ? (isFlat ? _getAllKeysIn : _getAllKeys)
  4646. : (isFlat ? keysIn_1 : keys_1);
  4647. var props = isArr ? undefined : keysFunc(value);
  4648. _arrayEach(props || value, function(subValue, key) {
  4649. if (props) {
  4650. key = subValue;
  4651. subValue = value[key];
  4652. }
  4653. // Recursively populate clone (susceptible to call stack limits).
  4654. _assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));
  4655. });
  4656. return result;
  4657. }
  4658. var _baseClone = baseClone;
  4659. /** Used to compose bitmasks for cloning. */
  4660. var CLONE_SYMBOLS_FLAG = 4;
  4661. /**
  4662. * Creates a shallow clone of `value`.
  4663. *
  4664. * **Note:** This method is loosely based on the
  4665. * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm)
  4666. * and supports cloning arrays, array buffers, booleans, date objects, maps,
  4667. * numbers, `Object` objects, regexes, sets, strings, symbols, and typed
  4668. * arrays. The own enumerable properties of `arguments` objects are cloned
  4669. * as plain objects. An empty object is returned for uncloneable values such
  4670. * as error objects, functions, DOM nodes, and WeakMaps.
  4671. *
  4672. * @static
  4673. * @memberOf _
  4674. * @since 0.1.0
  4675. * @category Lang
  4676. * @param {*} value The value to clone.
  4677. * @returns {*} Returns the cloned value.
  4678. * @see _.cloneDeep
  4679. * @example
  4680. *
  4681. * var objects = [{ 'a': 1 }, { 'b': 2 }];
  4682. *
  4683. * var shallow = _.clone(objects);
  4684. * console.log(shallow[0] === objects[0]);
  4685. * // => true
  4686. */
  4687. function clone(value) {
  4688. return _baseClone(value, CLONE_SYMBOLS_FLAG);
  4689. }
  4690. var clone_1 = clone;
  4691. /** `Object#toString` result references. */
  4692. var objectTag$1 = '[object Object]';
  4693. /** Used for built-in method references. */
  4694. var funcProto = Function.prototype,
  4695. objectProto$2 = Object.prototype;
  4696. /** Used to resolve the decompiled source of functions. */
  4697. var funcToString = funcProto.toString;
  4698. /** Used to check objects for own properties. */
  4699. var hasOwnProperty$2 = objectProto$2.hasOwnProperty;
  4700. /** Used to infer the `Object` constructor. */
  4701. var objectCtorString = funcToString.call(Object);
  4702. /**
  4703. * Checks if `value` is a plain object, that is, an object created by the
  4704. * `Object` constructor or one with a `[[Prototype]]` of `null`.
  4705. *
  4706. * @static
  4707. * @memberOf _
  4708. * @since 0.8.0
  4709. * @category Lang
  4710. * @param {*} value The value to check.
  4711. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
  4712. * @example
  4713. *
  4714. * function Foo() {
  4715. * this.a = 1;
  4716. * }
  4717. *
  4718. * _.isPlainObject(new Foo);
  4719. * // => false
  4720. *
  4721. * _.isPlainObject([1, 2, 3]);
  4722. * // => false
  4723. *
  4724. * _.isPlainObject({ 'x': 0, 'y': 0 });
  4725. * // => true
  4726. *
  4727. * _.isPlainObject(Object.create(null));
  4728. * // => true
  4729. */
  4730. function isPlainObject(value) {
  4731. if (!isObjectLike_1(value) || _baseGetTag(value) != objectTag$1) {
  4732. return false;
  4733. }
  4734. var proto = _getPrototype(value);
  4735. if (proto === null) {
  4736. return true;
  4737. }
  4738. var Ctor = hasOwnProperty$2.call(proto, 'constructor') && proto.constructor;
  4739. return typeof Ctor == 'function' && Ctor instanceof Ctor &&
  4740. funcToString.call(Ctor) == objectCtorString;
  4741. }
  4742. var isPlainObject_1 = isPlainObject;
  4743. /** `Object#toString` result references. */
  4744. var domExcTag = '[object DOMException]',
  4745. errorTag$1 = '[object Error]';
  4746. /**
  4747. * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`,
  4748. * `SyntaxError`, `TypeError`, or `URIError` object.
  4749. *
  4750. * @static
  4751. * @memberOf _
  4752. * @since 3.0.0
  4753. * @category Lang
  4754. * @param {*} value The value to check.
  4755. * @returns {boolean} Returns `true` if `value` is an error object, else `false`.
  4756. * @example
  4757. *
  4758. * _.isError(new Error);
  4759. * // => true
  4760. *
  4761. * _.isError(Error);
  4762. * // => false
  4763. */
  4764. function isError(value) {
  4765. if (!isObjectLike_1(value)) {
  4766. return false;
  4767. }
  4768. var tag = _baseGetTag(value);
  4769. return tag == errorTag$1 || tag == domExcTag ||
  4770. (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject_1(value));
  4771. }
  4772. var isError_1 = isError;
  4773. /** `Object#toString` result references. */
  4774. var weakMapTag = '[object WeakMap]';
  4775. /**
  4776. * Checks if `value` is classified as a `WeakMap` object.
  4777. *
  4778. * @static
  4779. * @memberOf _
  4780. * @since 4.3.0
  4781. * @category Lang
  4782. * @param {*} value The value to check.
  4783. * @returns {boolean} Returns `true` if `value` is a weak map, else `false`.
  4784. * @example
  4785. *
  4786. * _.isWeakMap(new WeakMap);
  4787. * // => true
  4788. *
  4789. * _.isWeakMap(new Map);
  4790. * // => false
  4791. */
  4792. function isWeakMap(value) {
  4793. return isObjectLike_1(value) && _getTag(value) == weakMapTag;
  4794. }
  4795. var isWeakMap_1 = isWeakMap;
  4796. /** Used to stand-in for `undefined` hash values. */
  4797. var HASH_UNDEFINED = '__lodash_hash_undefined__';
  4798. /**
  4799. * Adds `value` to the array cache.
  4800. *
  4801. * @private
  4802. * @name add
  4803. * @memberOf SetCache
  4804. * @alias push
  4805. * @param {*} value The value to cache.
  4806. * @returns {Object} Returns the cache instance.
  4807. */
  4808. function setCacheAdd(value) {
  4809. this.__data__.set(value, HASH_UNDEFINED);
  4810. return this;
  4811. }
  4812. var _setCacheAdd = setCacheAdd;
  4813. /**
  4814. * Checks if `value` is in the array cache.
  4815. *
  4816. * @private
  4817. * @name has
  4818. * @memberOf SetCache
  4819. * @param {*} value The value to search for.
  4820. * @returns {number} Returns `true` if `value` is found, else `false`.
  4821. */
  4822. function setCacheHas(value) {
  4823. return this.__data__.has(value);
  4824. }
  4825. var _setCacheHas = setCacheHas;
  4826. /**
  4827. *
  4828. * Creates an array cache object to store unique values.
  4829. *
  4830. * @private
  4831. * @constructor
  4832. * @param {Array} [values] The values to cache.
  4833. */
  4834. function SetCache(values) {
  4835. var index = -1,
  4836. length = values == null ? 0 : values.length;
  4837. this.__data__ = new _MapCache;
  4838. while (++index < length) {
  4839. this.add(values[index]);
  4840. }
  4841. }
  4842. // Add methods to `SetCache`.
  4843. SetCache.prototype.add = SetCache.prototype.push = _setCacheAdd;
  4844. SetCache.prototype.has = _setCacheHas;
  4845. var _SetCache = SetCache;
  4846. /**
  4847. * A specialized version of `_.some` for arrays without support for iteratee
  4848. * shorthands.
  4849. *
  4850. * @private
  4851. * @param {Array} [array] The array to iterate over.
  4852. * @param {Function} predicate The function invoked per iteration.
  4853. * @returns {boolean} Returns `true` if any element passes the predicate check,
  4854. * else `false`.
  4855. */
  4856. function arraySome(array, predicate) {
  4857. var index = -1,
  4858. length = array == null ? 0 : array.length;
  4859. while (++index < length) {
  4860. if (predicate(array[index], index, array)) {
  4861. return true;
  4862. }
  4863. }
  4864. return false;
  4865. }
  4866. var _arraySome = arraySome;
  4867. /**
  4868. * Checks if a `cache` value for `key` exists.
  4869. *
  4870. * @private
  4871. * @param {Object} cache The cache to query.
  4872. * @param {string} key The key of the entry to check.
  4873. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  4874. */
  4875. function cacheHas(cache, key) {
  4876. return cache.has(key);
  4877. }
  4878. var _cacheHas = cacheHas;
  4879. /** Used to compose bitmasks for value comparisons. */
  4880. var COMPARE_PARTIAL_FLAG$5 = 1,
  4881. COMPARE_UNORDERED_FLAG$3 = 2;
  4882. /**
  4883. * A specialized version of `baseIsEqualDeep` for arrays with support for
  4884. * partial deep comparisons.
  4885. *
  4886. * @private
  4887. * @param {Array} array The array to compare.
  4888. * @param {Array} other The other array to compare.
  4889. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
  4890. * @param {Function} customizer The function to customize comparisons.
  4891. * @param {Function} equalFunc The function to determine equivalents of values.
  4892. * @param {Object} stack Tracks traversed `array` and `other` objects.
  4893. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
  4894. */
  4895. function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
  4896. var isPartial = bitmask & COMPARE_PARTIAL_FLAG$5,
  4897. arrLength = array.length,
  4898. othLength = other.length;
  4899. if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
  4900. return false;
  4901. }
  4902. // Check that cyclic values are equal.
  4903. var arrStacked = stack.get(array);
  4904. var othStacked = stack.get(other);
  4905. if (arrStacked && othStacked) {
  4906. return arrStacked == other && othStacked == array;
  4907. }
  4908. var index = -1,
  4909. result = true,
  4910. seen = (bitmask & COMPARE_UNORDERED_FLAG$3) ? new _SetCache : undefined;
  4911. stack.set(array, other);
  4912. stack.set(other, array);
  4913. // Ignore non-index properties.
  4914. while (++index < arrLength) {
  4915. var arrValue = array[index],
  4916. othValue = other[index];
  4917. if (customizer) {
  4918. var compared = isPartial
  4919. ? customizer(othValue, arrValue, index, other, array, stack)
  4920. : customizer(arrValue, othValue, index, array, other, stack);
  4921. }
  4922. if (compared !== undefined) {
  4923. if (compared) {
  4924. continue;
  4925. }
  4926. result = false;
  4927. break;
  4928. }
  4929. // Recursively compare arrays (susceptible to call stack limits).
  4930. if (seen) {
  4931. if (!_arraySome(other, function(othValue, othIndex) {
  4932. if (!_cacheHas(seen, othIndex) &&
  4933. (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
  4934. return seen.push(othIndex);
  4935. }
  4936. })) {
  4937. result = false;
  4938. break;
  4939. }
  4940. } else if (!(
  4941. arrValue === othValue ||
  4942. equalFunc(arrValue, othValue, bitmask, customizer, stack)
  4943. )) {
  4944. result = false;
  4945. break;
  4946. }
  4947. }
  4948. stack['delete'](array);
  4949. stack['delete'](other);
  4950. return result;
  4951. }
  4952. var _equalArrays = equalArrays;
  4953. /**
  4954. * Converts `map` to its key-value pairs.
  4955. *
  4956. * @private
  4957. * @param {Object} map The map to convert.
  4958. * @returns {Array} Returns the key-value pairs.
  4959. */
  4960. function mapToArray(map) {
  4961. var index = -1,
  4962. result = Array(map.size);
  4963. map.forEach(function(value, key) {
  4964. result[++index] = [key, value];
  4965. });
  4966. return result;
  4967. }
  4968. var _mapToArray = mapToArray;
  4969. /**
  4970. * Converts `set` to an array of its values.
  4971. *
  4972. * @private
  4973. * @param {Object} set The set to convert.
  4974. * @returns {Array} Returns the values.
  4975. */
  4976. function setToArray(set) {
  4977. var index = -1,
  4978. result = Array(set.size);
  4979. set.forEach(function(value) {
  4980. result[++index] = value;
  4981. });
  4982. return result;
  4983. }
  4984. var _setToArray = setToArray;
  4985. /** Used to compose bitmasks for value comparisons. */
  4986. var COMPARE_PARTIAL_FLAG$4 = 1,
  4987. COMPARE_UNORDERED_FLAG$2 = 2;
  4988. /** `Object#toString` result references. */
  4989. var boolTag = '[object Boolean]',
  4990. dateTag = '[object Date]',
  4991. errorTag = '[object Error]',
  4992. mapTag = '[object Map]',
  4993. numberTag = '[object Number]',
  4994. regexpTag = '[object RegExp]',
  4995. setTag = '[object Set]',
  4996. stringTag = '[object String]',
  4997. symbolTag = '[object Symbol]';
  4998. var arrayBufferTag = '[object ArrayBuffer]',
  4999. dataViewTag = '[object DataView]';
  5000. /** Used to convert symbols to primitives and strings. */
  5001. var symbolProto$1 = _Symbol ? _Symbol.prototype : undefined,
  5002. symbolValueOf = symbolProto$1 ? symbolProto$1.valueOf : undefined;
  5003. /**
  5004. * A specialized version of `baseIsEqualDeep` for comparing objects of
  5005. * the same `toStringTag`.
  5006. *
  5007. * **Note:** This function only supports comparing values with tags of
  5008. * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
  5009. *
  5010. * @private
  5011. * @param {Object} object The object to compare.
  5012. * @param {Object} other The other object to compare.
  5013. * @param {string} tag The `toStringTag` of the objects to compare.
  5014. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
  5015. * @param {Function} customizer The function to customize comparisons.
  5016. * @param {Function} equalFunc The function to determine equivalents of values.
  5017. * @param {Object} stack Tracks traversed `object` and `other` objects.
  5018. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
  5019. */
  5020. function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
  5021. switch (tag) {
  5022. case dataViewTag:
  5023. if ((object.byteLength != other.byteLength) ||
  5024. (object.byteOffset != other.byteOffset)) {
  5025. return false;
  5026. }
  5027. object = object.buffer;
  5028. other = other.buffer;
  5029. case arrayBufferTag:
  5030. if ((object.byteLength != other.byteLength) ||
  5031. !equalFunc(new _Uint8Array(object), new _Uint8Array(other))) {
  5032. return false;
  5033. }
  5034. return true;
  5035. case boolTag:
  5036. case dateTag:
  5037. case numberTag:
  5038. // Coerce booleans to `1` or `0` and dates to milliseconds.
  5039. // Invalid dates are coerced to `NaN`.
  5040. return eq_1(+object, +other);
  5041. case errorTag:
  5042. return object.name == other.name && object.message == other.message;
  5043. case regexpTag:
  5044. case stringTag:
  5045. // Coerce regexes to strings and treat strings, primitives and objects,
  5046. // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
  5047. // for more details.
  5048. return object == (other + '');
  5049. case mapTag:
  5050. var convert = _mapToArray;
  5051. case setTag:
  5052. var isPartial = bitmask & COMPARE_PARTIAL_FLAG$4;
  5053. convert || (convert = _setToArray);
  5054. if (object.size != other.size && !isPartial) {
  5055. return false;
  5056. }
  5057. // Assume cyclic values are equal.
  5058. var stacked = stack.get(object);
  5059. if (stacked) {
  5060. return stacked == other;
  5061. }
  5062. bitmask |= COMPARE_UNORDERED_FLAG$2;
  5063. // Recursively compare objects (susceptible to call stack limits).
  5064. stack.set(object, other);
  5065. var result = _equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
  5066. stack['delete'](object);
  5067. return result;
  5068. case symbolTag:
  5069. if (symbolValueOf) {
  5070. return symbolValueOf.call(object) == symbolValueOf.call(other);
  5071. }
  5072. }
  5073. return false;
  5074. }
  5075. var _equalByTag = equalByTag;
  5076. /** Used to compose bitmasks for value comparisons. */
  5077. var COMPARE_PARTIAL_FLAG$3 = 1;
  5078. /** Used for built-in method references. */
  5079. var objectProto$1 = Object.prototype;
  5080. /** Used to check objects for own properties. */
  5081. var hasOwnProperty$1 = objectProto$1.hasOwnProperty;
  5082. /**
  5083. * A specialized version of `baseIsEqualDeep` for objects with support for
  5084. * partial deep comparisons.
  5085. *
  5086. * @private
  5087. * @param {Object} object The object to compare.
  5088. * @param {Object} other The other object to compare.
  5089. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
  5090. * @param {Function} customizer The function to customize comparisons.
  5091. * @param {Function} equalFunc The function to determine equivalents of values.
  5092. * @param {Object} stack Tracks traversed `object` and `other` objects.
  5093. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
  5094. */
  5095. function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
  5096. var isPartial = bitmask & COMPARE_PARTIAL_FLAG$3,
  5097. objProps = _getAllKeys(object),
  5098. objLength = objProps.length,
  5099. othProps = _getAllKeys(other),
  5100. othLength = othProps.length;
  5101. if (objLength != othLength && !isPartial) {
  5102. return false;
  5103. }
  5104. var index = objLength;
  5105. while (index--) {
  5106. var key = objProps[index];
  5107. if (!(isPartial ? key in other : hasOwnProperty$1.call(other, key))) {
  5108. return false;
  5109. }
  5110. }
  5111. // Check that cyclic values are equal.
  5112. var objStacked = stack.get(object);
  5113. var othStacked = stack.get(other);
  5114. if (objStacked && othStacked) {
  5115. return objStacked == other && othStacked == object;
  5116. }
  5117. var result = true;
  5118. stack.set(object, other);
  5119. stack.set(other, object);
  5120. var skipCtor = isPartial;
  5121. while (++index < objLength) {
  5122. key = objProps[index];
  5123. var objValue = object[key],
  5124. othValue = other[key];
  5125. if (customizer) {
  5126. var compared = isPartial
  5127. ? customizer(othValue, objValue, key, other, object, stack)
  5128. : customizer(objValue, othValue, key, object, other, stack);
  5129. }
  5130. // Recursively compare objects (susceptible to call stack limits).
  5131. if (!(compared === undefined
  5132. ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))
  5133. : compared
  5134. )) {
  5135. result = false;
  5136. break;
  5137. }
  5138. skipCtor || (skipCtor = key == 'constructor');
  5139. }
  5140. if (result && !skipCtor) {
  5141. var objCtor = object.constructor,
  5142. othCtor = other.constructor;
  5143. // Non `Object` object instances with different constructors are not equal.
  5144. if (objCtor != othCtor &&
  5145. ('constructor' in object && 'constructor' in other) &&
  5146. !(typeof objCtor == 'function' && objCtor instanceof objCtor &&
  5147. typeof othCtor == 'function' && othCtor instanceof othCtor)) {
  5148. result = false;
  5149. }
  5150. }
  5151. stack['delete'](object);
  5152. stack['delete'](other);
  5153. return result;
  5154. }
  5155. var _equalObjects = equalObjects;
  5156. /** Used to compose bitmasks for value comparisons. */
  5157. var COMPARE_PARTIAL_FLAG$2 = 1;
  5158. /** `Object#toString` result references. */
  5159. var argsTag = '[object Arguments]',
  5160. arrayTag = '[object Array]',
  5161. objectTag = '[object Object]';
  5162. /** Used for built-in method references. */
  5163. var objectProto = Object.prototype;
  5164. /** Used to check objects for own properties. */
  5165. var hasOwnProperty = objectProto.hasOwnProperty;
  5166. /**
  5167. * A specialized version of `baseIsEqual` for arrays and objects which performs
  5168. * deep comparisons and tracks traversed objects enabling objects with circular
  5169. * references to be compared.
  5170. *
  5171. * @private
  5172. * @param {Object} object The object to compare.
  5173. * @param {Object} other The other object to compare.
  5174. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
  5175. * @param {Function} customizer The function to customize comparisons.
  5176. * @param {Function} equalFunc The function to determine equivalents of values.
  5177. * @param {Object} [stack] Tracks traversed `object` and `other` objects.
  5178. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
  5179. */
  5180. function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
  5181. var objIsArr = isArray_1(object),
  5182. othIsArr = isArray_1(other),
  5183. objTag = objIsArr ? arrayTag : _getTag(object),
  5184. othTag = othIsArr ? arrayTag : _getTag(other);
  5185. objTag = objTag == argsTag ? objectTag : objTag;
  5186. othTag = othTag == argsTag ? objectTag : othTag;
  5187. var objIsObj = objTag == objectTag,
  5188. othIsObj = othTag == objectTag,
  5189. isSameTag = objTag == othTag;
  5190. if (isSameTag && isBuffer_1(object)) {
  5191. if (!isBuffer_1(other)) {
  5192. return false;
  5193. }
  5194. objIsArr = true;
  5195. objIsObj = false;
  5196. }
  5197. if (isSameTag && !objIsObj) {
  5198. stack || (stack = new _Stack);
  5199. return (objIsArr || isTypedArray_1(object))
  5200. ? _equalArrays(object, other, bitmask, customizer, equalFunc, stack)
  5201. : _equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
  5202. }
  5203. if (!(bitmask & COMPARE_PARTIAL_FLAG$2)) {
  5204. var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
  5205. othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
  5206. if (objIsWrapped || othIsWrapped) {
  5207. var objUnwrapped = objIsWrapped ? object.value() : object,
  5208. othUnwrapped = othIsWrapped ? other.value() : other;
  5209. stack || (stack = new _Stack);
  5210. return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
  5211. }
  5212. }
  5213. if (!isSameTag) {
  5214. return false;
  5215. }
  5216. stack || (stack = new _Stack);
  5217. return _equalObjects(object, other, bitmask, customizer, equalFunc, stack);
  5218. }
  5219. var _baseIsEqualDeep = baseIsEqualDeep;
  5220. /**
  5221. * The base implementation of `_.isEqual` which supports partial comparisons
  5222. * and tracks traversed objects.
  5223. *
  5224. * @private
  5225. * @param {*} value The value to compare.
  5226. * @param {*} other The other value to compare.
  5227. * @param {boolean} bitmask The bitmask flags.
  5228. * 1 - Unordered comparison
  5229. * 2 - Partial comparison
  5230. * @param {Function} [customizer] The function to customize comparisons.
  5231. * @param {Object} [stack] Tracks traversed `value` and `other` objects.
  5232. * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
  5233. */
  5234. function baseIsEqual(value, other, bitmask, customizer, stack) {
  5235. if (value === other) {
  5236. return true;
  5237. }
  5238. if (value == null || other == null || (!isObjectLike_1(value) && !isObjectLike_1(other))) {
  5239. return value !== value && other !== other;
  5240. }
  5241. return _baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
  5242. }
  5243. var _baseIsEqual = baseIsEqual;
  5244. /** Used to compose bitmasks for value comparisons. */
  5245. var COMPARE_PARTIAL_FLAG$1 = 1,
  5246. COMPARE_UNORDERED_FLAG$1 = 2;
  5247. /**
  5248. * The base implementation of `_.isMatch` without support for iteratee shorthands.
  5249. *
  5250. * @private
  5251. * @param {Object} object The object to inspect.
  5252. * @param {Object} source The object of property values to match.
  5253. * @param {Array} matchData The property names, values, and compare flags to match.
  5254. * @param {Function} [customizer] The function to customize comparisons.
  5255. * @returns {boolean} Returns `true` if `object` is a match, else `false`.
  5256. */
  5257. function baseIsMatch(object, source, matchData, customizer) {
  5258. var index = matchData.length,
  5259. length = index,
  5260. noCustomizer = !customizer;
  5261. if (object == null) {
  5262. return !length;
  5263. }
  5264. object = Object(object);
  5265. while (index--) {
  5266. var data = matchData[index];
  5267. if ((noCustomizer && data[2])
  5268. ? data[1] !== object[data[0]]
  5269. : !(data[0] in object)
  5270. ) {
  5271. return false;
  5272. }
  5273. }
  5274. while (++index < length) {
  5275. data = matchData[index];
  5276. var key = data[0],
  5277. objValue = object[key],
  5278. srcValue = data[1];
  5279. if (noCustomizer && data[2]) {
  5280. if (objValue === undefined && !(key in object)) {
  5281. return false;
  5282. }
  5283. } else {
  5284. var stack = new _Stack;
  5285. if (customizer) {
  5286. var result = customizer(objValue, srcValue, key, object, source, stack);
  5287. }
  5288. if (!(result === undefined
  5289. ? _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$1 | COMPARE_UNORDERED_FLAG$1, customizer, stack)
  5290. : result
  5291. )) {
  5292. return false;
  5293. }
  5294. }
  5295. }
  5296. return true;
  5297. }
  5298. var _baseIsMatch = baseIsMatch;
  5299. /**
  5300. * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
  5301. *
  5302. * @private
  5303. * @param {*} value The value to check.
  5304. * @returns {boolean} Returns `true` if `value` if suitable for strict
  5305. * equality comparisons, else `false`.
  5306. */
  5307. function isStrictComparable(value) {
  5308. return value === value && !isObject_1(value);
  5309. }
  5310. var _isStrictComparable = isStrictComparable;
  5311. /**
  5312. * Gets the property names, values, and compare flags of `object`.
  5313. *
  5314. * @private
  5315. * @param {Object} object The object to query.
  5316. * @returns {Array} Returns the match data of `object`.
  5317. */
  5318. function getMatchData(object) {
  5319. var result = keys_1(object),
  5320. length = result.length;
  5321. while (length--) {
  5322. var key = result[length],
  5323. value = object[key];
  5324. result[length] = [key, value, _isStrictComparable(value)];
  5325. }
  5326. return result;
  5327. }
  5328. var _getMatchData = getMatchData;
  5329. /**
  5330. * A specialized version of `matchesProperty` for source values suitable
  5331. * for strict equality comparisons, i.e. `===`.
  5332. *
  5333. * @private
  5334. * @param {string} key The key of the property to get.
  5335. * @param {*} srcValue The value to match.
  5336. * @returns {Function} Returns the new spec function.
  5337. */
  5338. function matchesStrictComparable(key, srcValue) {
  5339. return function(object) {
  5340. if (object == null) {
  5341. return false;
  5342. }
  5343. return object[key] === srcValue &&
  5344. (srcValue !== undefined || (key in Object(object)));
  5345. };
  5346. }
  5347. var _matchesStrictComparable = matchesStrictComparable;
  5348. /**
  5349. * The base implementation of `_.matches` which doesn't clone `source`.
  5350. *
  5351. * @private
  5352. * @param {Object} source The object of property values to match.
  5353. * @returns {Function} Returns the new spec function.
  5354. */
  5355. function baseMatches(source) {
  5356. var matchData = _getMatchData(source);
  5357. if (matchData.length == 1 && matchData[0][2]) {
  5358. return _matchesStrictComparable(matchData[0][0], matchData[0][1]);
  5359. }
  5360. return function(object) {
  5361. return object === source || _baseIsMatch(object, source, matchData);
  5362. };
  5363. }
  5364. var _baseMatches = baseMatches;
  5365. /** Used to match property names within property paths. */
  5366. var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
  5367. reIsPlainProp = /^\w*$/;
  5368. /**
  5369. * Checks if `value` is a property name and not a property path.
  5370. *
  5371. * @private
  5372. * @param {*} value The value to check.
  5373. * @param {Object} [object] The object to query keys on.
  5374. * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
  5375. */
  5376. function isKey(value, object) {
  5377. if (isArray_1(value)) {
  5378. return false;
  5379. }
  5380. var type = typeof value;
  5381. if (type == 'number' || type == 'symbol' || type == 'boolean' ||
  5382. value == null || isSymbol_1(value)) {
  5383. return true;
  5384. }
  5385. return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
  5386. (object != null && value in Object(object));
  5387. }
  5388. var _isKey = isKey;
  5389. /** Error message constants. */
  5390. var FUNC_ERROR_TEXT = 'Expected a function';
  5391. /**
  5392. * Creates a function that memoizes the result of `func`. If `resolver` is
  5393. * provided, it determines the cache key for storing the result based on the
  5394. * arguments provided to the memoized function. By default, the first argument
  5395. * provided to the memoized function is used as the map cache key. The `func`
  5396. * is invoked with the `this` binding of the memoized function.
  5397. *
  5398. * **Note:** The cache is exposed as the `cache` property on the memoized
  5399. * function. Its creation may be customized by replacing the `_.memoize.Cache`
  5400. * constructor with one whose instances implement the
  5401. * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
  5402. * method interface of `clear`, `delete`, `get`, `has`, and `set`.
  5403. *
  5404. * @static
  5405. * @memberOf _
  5406. * @since 0.1.0
  5407. * @category Function
  5408. * @param {Function} func The function to have its output memoized.
  5409. * @param {Function} [resolver] The function to resolve the cache key.
  5410. * @returns {Function} Returns the new memoized function.
  5411. * @example
  5412. *
  5413. * var object = { 'a': 1, 'b': 2 };
  5414. * var other = { 'c': 3, 'd': 4 };
  5415. *
  5416. * var values = _.memoize(_.values);
  5417. * values(object);
  5418. * // => [1, 2]
  5419. *
  5420. * values(other);
  5421. * // => [3, 4]
  5422. *
  5423. * object.a = 2;
  5424. * values(object);
  5425. * // => [1, 2]
  5426. *
  5427. * // Modify the result cache.
  5428. * values.cache.set(object, ['a', 'b']);
  5429. * values(object);
  5430. * // => ['a', 'b']
  5431. *
  5432. * // Replace `_.memoize.Cache`.
  5433. * _.memoize.Cache = WeakMap;
  5434. */
  5435. function memoize(func, resolver) {
  5436. if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {
  5437. throw new TypeError(FUNC_ERROR_TEXT);
  5438. }
  5439. var memoized = function() {
  5440. var args = arguments,
  5441. key = resolver ? resolver.apply(this, args) : args[0],
  5442. cache = memoized.cache;
  5443. if (cache.has(key)) {
  5444. return cache.get(key);
  5445. }
  5446. var result = func.apply(this, args);
  5447. memoized.cache = cache.set(key, result) || cache;
  5448. return result;
  5449. };
  5450. memoized.cache = new (memoize.Cache || _MapCache);
  5451. return memoized;
  5452. }
  5453. // Expose `MapCache`.
  5454. memoize.Cache = _MapCache;
  5455. var memoize_1 = memoize;
  5456. /** Used as the maximum memoize cache size. */
  5457. var MAX_MEMOIZE_SIZE = 500;
  5458. /**
  5459. * A specialized version of `_.memoize` which clears the memoized function's
  5460. * cache when it exceeds `MAX_MEMOIZE_SIZE`.
  5461. *
  5462. * @private
  5463. * @param {Function} func The function to have its output memoized.
  5464. * @returns {Function} Returns the new memoized function.
  5465. */
  5466. function memoizeCapped(func) {
  5467. var result = memoize_1(func, function(key) {
  5468. if (cache.size === MAX_MEMOIZE_SIZE) {
  5469. cache.clear();
  5470. }
  5471. return key;
  5472. });
  5473. var cache = result.cache;
  5474. return result;
  5475. }
  5476. var _memoizeCapped = memoizeCapped;
  5477. /** Used to match property names within property paths. */
  5478. var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
  5479. /** Used to match backslashes in property paths. */
  5480. var reEscapeChar = /\\(\\)?/g;
  5481. /**
  5482. * Converts `string` to a property path array.
  5483. *
  5484. * @private
  5485. * @param {string} string The string to convert.
  5486. * @returns {Array} Returns the property path array.
  5487. */
  5488. var stringToPath = _memoizeCapped(function(string) {
  5489. var result = [];
  5490. if (string.charCodeAt(0) === 46 /* . */) {
  5491. result.push('');
  5492. }
  5493. string.replace(rePropName, function(match, number, quote, subString) {
  5494. result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));
  5495. });
  5496. return result;
  5497. });
  5498. var _stringToPath = stringToPath;
  5499. /**
  5500. * A specialized version of `_.map` for arrays without support for iteratee
  5501. * shorthands.
  5502. *
  5503. * @private
  5504. * @param {Array} [array] The array to iterate over.
  5505. * @param {Function} iteratee The function invoked per iteration.
  5506. * @returns {Array} Returns the new mapped array.
  5507. */
  5508. function arrayMap(array, iteratee) {
  5509. var index = -1,
  5510. length = array == null ? 0 : array.length,
  5511. result = Array(length);
  5512. while (++index < length) {
  5513. result[index] = iteratee(array[index], index, array);
  5514. }
  5515. return result;
  5516. }
  5517. var _arrayMap = arrayMap;
  5518. /** Used as references for various `Number` constants. */
  5519. var INFINITY$1 = 1 / 0;
  5520. /** Used to convert symbols to primitives and strings. */
  5521. var symbolProto = _Symbol ? _Symbol.prototype : undefined,
  5522. symbolToString = symbolProto ? symbolProto.toString : undefined;
  5523. /**
  5524. * The base implementation of `_.toString` which doesn't convert nullish
  5525. * values to empty strings.
  5526. *
  5527. * @private
  5528. * @param {*} value The value to process.
  5529. * @returns {string} Returns the string.
  5530. */
  5531. function baseToString(value) {
  5532. // Exit early for strings to avoid a performance hit in some environments.
  5533. if (typeof value == 'string') {
  5534. return value;
  5535. }
  5536. if (isArray_1(value)) {
  5537. // Recursively convert values (susceptible to call stack limits).
  5538. return _arrayMap(value, baseToString) + '';
  5539. }
  5540. if (isSymbol_1(value)) {
  5541. return symbolToString ? symbolToString.call(value) : '';
  5542. }
  5543. var result = (value + '');
  5544. return (result == '0' && (1 / value) == -INFINITY$1) ? '-0' : result;
  5545. }
  5546. var _baseToString = baseToString;
  5547. /**
  5548. * Converts `value` to a string. An empty string is returned for `null`
  5549. * and `undefined` values. The sign of `-0` is preserved.
  5550. *
  5551. * @static
  5552. * @memberOf _
  5553. * @since 4.0.0
  5554. * @category Lang
  5555. * @param {*} value The value to convert.
  5556. * @returns {string} Returns the converted string.
  5557. * @example
  5558. *
  5559. * _.toString(null);
  5560. * // => ''
  5561. *
  5562. * _.toString(-0);
  5563. * // => '-0'
  5564. *
  5565. * _.toString([1, 2, 3]);
  5566. * // => '1,2,3'
  5567. */
  5568. function toString(value) {
  5569. return value == null ? '' : _baseToString(value);
  5570. }
  5571. var toString_1 = toString;
  5572. /**
  5573. * Casts `value` to a path array if it's not one.
  5574. *
  5575. * @private
  5576. * @param {*} value The value to inspect.
  5577. * @param {Object} [object] The object to query keys on.
  5578. * @returns {Array} Returns the cast property path array.
  5579. */
  5580. function castPath(value, object) {
  5581. if (isArray_1(value)) {
  5582. return value;
  5583. }
  5584. return _isKey(value, object) ? [value] : _stringToPath(toString_1(value));
  5585. }
  5586. var _castPath = castPath;
  5587. /** Used as references for various `Number` constants. */
  5588. var INFINITY = 1 / 0;
  5589. /**
  5590. * Converts `value` to a string key if it's not a string or symbol.
  5591. *
  5592. * @private
  5593. * @param {*} value The value to inspect.
  5594. * @returns {string|symbol} Returns the key.
  5595. */
  5596. function toKey(value) {
  5597. if (typeof value == 'string' || isSymbol_1(value)) {
  5598. return value;
  5599. }
  5600. var result = (value + '');
  5601. return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
  5602. }
  5603. var _toKey = toKey;
  5604. /**
  5605. * The base implementation of `_.get` without support for default values.
  5606. *
  5607. * @private
  5608. * @param {Object} object The object to query.
  5609. * @param {Array|string} path The path of the property to get.
  5610. * @returns {*} Returns the resolved value.
  5611. */
  5612. function baseGet(object, path) {
  5613. path = _castPath(path, object);
  5614. var index = 0,
  5615. length = path.length;
  5616. while (object != null && index < length) {
  5617. object = object[_toKey(path[index++])];
  5618. }
  5619. return (index && index == length) ? object : undefined;
  5620. }
  5621. var _baseGet = baseGet;
  5622. /**
  5623. * Gets the value at `path` of `object`. If the resolved value is
  5624. * `undefined`, the `defaultValue` is returned in its place.
  5625. *
  5626. * @static
  5627. * @memberOf _
  5628. * @since 3.7.0
  5629. * @category Object
  5630. * @param {Object} object The object to query.
  5631. * @param {Array|string} path The path of the property to get.
  5632. * @param {*} [defaultValue] The value returned for `undefined` resolved values.
  5633. * @returns {*} Returns the resolved value.
  5634. * @example
  5635. *
  5636. * var object = { 'a': [{ 'b': { 'c': 3 } }] };
  5637. *
  5638. * _.get(object, 'a[0].b.c');
  5639. * // => 3
  5640. *
  5641. * _.get(object, ['a', '0', 'b', 'c']);
  5642. * // => 3
  5643. *
  5644. * _.get(object, 'a.b.c', 'default');
  5645. * // => 'default'
  5646. */
  5647. function get$1(object, path, defaultValue) {
  5648. var result = object == null ? undefined : _baseGet(object, path);
  5649. return result === undefined ? defaultValue : result;
  5650. }
  5651. var get_1 = get$1;
  5652. /**
  5653. * The base implementation of `_.hasIn` without support for deep paths.
  5654. *
  5655. * @private
  5656. * @param {Object} [object] The object to query.
  5657. * @param {Array|string} key The key to check.
  5658. * @returns {boolean} Returns `true` if `key` exists, else `false`.
  5659. */
  5660. function baseHasIn(object, key) {
  5661. return object != null && key in Object(object);
  5662. }
  5663. var _baseHasIn = baseHasIn;
  5664. /**
  5665. * Checks if `path` exists on `object`.
  5666. *
  5667. * @private
  5668. * @param {Object} object The object to query.
  5669. * @param {Array|string} path The path to check.
  5670. * @param {Function} hasFunc The function to check properties.
  5671. * @returns {boolean} Returns `true` if `path` exists, else `false`.
  5672. */
  5673. function hasPath(object, path, hasFunc) {
  5674. path = _castPath(path, object);
  5675. var index = -1,
  5676. length = path.length,
  5677. result = false;
  5678. while (++index < length) {
  5679. var key = _toKey(path[index]);
  5680. if (!(result = object != null && hasFunc(object, key))) {
  5681. break;
  5682. }
  5683. object = object[key];
  5684. }
  5685. if (result || ++index != length) {
  5686. return result;
  5687. }
  5688. length = object == null ? 0 : object.length;
  5689. return !!length && isLength_1(length) && _isIndex(key, length) &&
  5690. (isArray_1(object) || isArguments_1(object));
  5691. }
  5692. var _hasPath = hasPath;
  5693. /**
  5694. * Checks if `path` is a direct or inherited property of `object`.
  5695. *
  5696. * @static
  5697. * @memberOf _
  5698. * @since 4.0.0
  5699. * @category Object
  5700. * @param {Object} object The object to query.
  5701. * @param {Array|string} path The path to check.
  5702. * @returns {boolean} Returns `true` if `path` exists, else `false`.
  5703. * @example
  5704. *
  5705. * var object = _.create({ 'a': _.create({ 'b': 2 }) });
  5706. *
  5707. * _.hasIn(object, 'a');
  5708. * // => true
  5709. *
  5710. * _.hasIn(object, 'a.b');
  5711. * // => true
  5712. *
  5713. * _.hasIn(object, ['a', 'b']);
  5714. * // => true
  5715. *
  5716. * _.hasIn(object, 'b');
  5717. * // => false
  5718. */
  5719. function hasIn(object, path) {
  5720. return object != null && _hasPath(object, path, _baseHasIn);
  5721. }
  5722. var hasIn_1 = hasIn;
  5723. /** Used to compose bitmasks for value comparisons. */
  5724. var COMPARE_PARTIAL_FLAG = 1,
  5725. COMPARE_UNORDERED_FLAG = 2;
  5726. /**
  5727. * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
  5728. *
  5729. * @private
  5730. * @param {string} path The path of the property to get.
  5731. * @param {*} srcValue The value to match.
  5732. * @returns {Function} Returns the new spec function.
  5733. */
  5734. function baseMatchesProperty(path, srcValue) {
  5735. if (_isKey(path) && _isStrictComparable(srcValue)) {
  5736. return _matchesStrictComparable(_toKey(path), srcValue);
  5737. }
  5738. return function(object) {
  5739. var objValue = get_1(object, path);
  5740. return (objValue === undefined && objValue === srcValue)
  5741. ? hasIn_1(object, path)
  5742. : _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);
  5743. };
  5744. }
  5745. var _baseMatchesProperty = baseMatchesProperty;
  5746. /**
  5747. * The base implementation of `_.property` without support for deep paths.
  5748. *
  5749. * @private
  5750. * @param {string} key The key of the property to get.
  5751. * @returns {Function} Returns the new accessor function.
  5752. */
  5753. function baseProperty(key) {
  5754. return function(object) {
  5755. return object == null ? undefined : object[key];
  5756. };
  5757. }
  5758. var _baseProperty = baseProperty;
  5759. /**
  5760. * A specialized version of `baseProperty` which supports deep paths.
  5761. *
  5762. * @private
  5763. * @param {Array|string} path The path of the property to get.
  5764. * @returns {Function} Returns the new accessor function.
  5765. */
  5766. function basePropertyDeep(path) {
  5767. return function(object) {
  5768. return _baseGet(object, path);
  5769. };
  5770. }
  5771. var _basePropertyDeep = basePropertyDeep;
  5772. /**
  5773. * Creates a function that returns the value at `path` of a given object.
  5774. *
  5775. * @static
  5776. * @memberOf _
  5777. * @since 2.4.0
  5778. * @category Util
  5779. * @param {Array|string} path The path of the property to get.
  5780. * @returns {Function} Returns the new accessor function.
  5781. * @example
  5782. *
  5783. * var objects = [
  5784. * { 'a': { 'b': 2 } },
  5785. * { 'a': { 'b': 1 } }
  5786. * ];
  5787. *
  5788. * _.map(objects, _.property('a.b'));
  5789. * // => [2, 1]
  5790. *
  5791. * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
  5792. * // => [1, 2]
  5793. */
  5794. function property(path) {
  5795. return _isKey(path) ? _baseProperty(_toKey(path)) : _basePropertyDeep(path);
  5796. }
  5797. var property_1 = property;
  5798. /**
  5799. * The base implementation of `_.iteratee`.
  5800. *
  5801. * @private
  5802. * @param {*} [value=_.identity] The value to convert to an iteratee.
  5803. * @returns {Function} Returns the iteratee.
  5804. */
  5805. function baseIteratee(value) {
  5806. // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
  5807. // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
  5808. if (typeof value == 'function') {
  5809. return value;
  5810. }
  5811. if (value == null) {
  5812. return identity_1;
  5813. }
  5814. if (typeof value == 'object') {
  5815. return isArray_1(value)
  5816. ? _baseMatchesProperty(value[0], value[1])
  5817. : _baseMatches(value);
  5818. }
  5819. return property_1(value);
  5820. }
  5821. var _baseIteratee = baseIteratee;
  5822. /** Used to compose bitmasks for cloning. */
  5823. var CLONE_DEEP_FLAG = 1;
  5824. /**
  5825. * Creates a function that invokes `func` with the arguments of the created
  5826. * function. If `func` is a property name, the created function returns the
  5827. * property value for a given element. If `func` is an array or object, the
  5828. * created function returns `true` for elements that contain the equivalent
  5829. * source properties, otherwise it returns `false`.
  5830. *
  5831. * @static
  5832. * @since 4.0.0
  5833. * @memberOf _
  5834. * @category Util
  5835. * @param {*} [func=_.identity] The value to convert to a callback.
  5836. * @returns {Function} Returns the callback.
  5837. * @example
  5838. *
  5839. * var users = [
  5840. * { 'user': 'barney', 'age': 36, 'active': true },
  5841. * { 'user': 'fred', 'age': 40, 'active': false }
  5842. * ];
  5843. *
  5844. * // The `_.matches` iteratee shorthand.
  5845. * _.filter(users, _.iteratee({ 'user': 'barney', 'active': true }));
  5846. * // => [{ 'user': 'barney', 'age': 36, 'active': true }]
  5847. *
  5848. * // The `_.matchesProperty` iteratee shorthand.
  5849. * _.filter(users, _.iteratee(['user', 'fred']));
  5850. * // => [{ 'user': 'fred', 'age': 40 }]
  5851. *
  5852. * // The `_.property` iteratee shorthand.
  5853. * _.map(users, _.iteratee('user'));
  5854. * // => ['barney', 'fred']
  5855. *
  5856. * // Create custom iteratee shorthands.
  5857. * _.iteratee = _.wrap(_.iteratee, function(iteratee, func) {
  5858. * return !_.isRegExp(func) ? iteratee(func) : function(string) {
  5859. * return func.test(string);
  5860. * };
  5861. * });
  5862. *
  5863. * _.filter(['abc', 'def'], /ef/);
  5864. * // => ['def']
  5865. */
  5866. function iteratee(func) {
  5867. return _baseIteratee(typeof func == 'function' ? func : _baseClone(func, CLONE_DEEP_FLAG));
  5868. }
  5869. var iteratee_1 = iteratee;
  5870. /** Built-in value references. */
  5871. var spreadableSymbol = _Symbol ? _Symbol.isConcatSpreadable : undefined;
  5872. /**
  5873. * Checks if `value` is a flattenable `arguments` object or array.
  5874. *
  5875. * @private
  5876. * @param {*} value The value to check.
  5877. * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
  5878. */
  5879. function isFlattenable(value) {
  5880. return isArray_1(value) || isArguments_1(value) ||
  5881. !!(spreadableSymbol && value && value[spreadableSymbol]);
  5882. }
  5883. var _isFlattenable = isFlattenable;
  5884. /**
  5885. * The base implementation of `_.flatten` with support for restricting flattening.
  5886. *
  5887. * @private
  5888. * @param {Array} array The array to flatten.
  5889. * @param {number} depth The maximum recursion depth.
  5890. * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
  5891. * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
  5892. * @param {Array} [result=[]] The initial result value.
  5893. * @returns {Array} Returns the new flattened array.
  5894. */
  5895. function baseFlatten(array, depth, predicate, isStrict, result) {
  5896. var index = -1,
  5897. length = array.length;
  5898. predicate || (predicate = _isFlattenable);
  5899. result || (result = []);
  5900. while (++index < length) {
  5901. var value = array[index];
  5902. if (depth > 0 && predicate(value)) {
  5903. if (depth > 1) {
  5904. // Recursively flatten arrays (susceptible to call stack limits).
  5905. baseFlatten(value, depth - 1, predicate, isStrict, result);
  5906. } else {
  5907. _arrayPush(result, value);
  5908. }
  5909. } else if (!isStrict) {
  5910. result[result.length] = value;
  5911. }
  5912. }
  5913. return result;
  5914. }
  5915. var _baseFlatten = baseFlatten;
  5916. /**
  5917. * Flattens `array` a single level deep.
  5918. *
  5919. * @static
  5920. * @memberOf _
  5921. * @since 0.1.0
  5922. * @category Array
  5923. * @param {Array} array The array to flatten.
  5924. * @returns {Array} Returns the new flattened array.
  5925. * @example
  5926. *
  5927. * _.flatten([1, [2, [3, [4]], 5]]);
  5928. * // => [1, 2, [3, [4]], 5]
  5929. */
  5930. function flatten(array) {
  5931. var length = array == null ? 0 : array.length;
  5932. return length ? _baseFlatten(array, 1) : [];
  5933. }
  5934. var flatten_1 = flatten;
  5935. /* Built-in method references for those with the same name as other `lodash` methods. */
  5936. var nativeMax = Math.max;
  5937. /**
  5938. * A specialized version of `baseRest` which transforms the rest array.
  5939. *
  5940. * @private
  5941. * @param {Function} func The function to apply a rest parameter to.
  5942. * @param {number} [start=func.length-1] The start position of the rest parameter.
  5943. * @param {Function} transform The rest array transform.
  5944. * @returns {Function} Returns the new function.
  5945. */
  5946. function overRest(func, start, transform) {
  5947. start = nativeMax(start === undefined ? (func.length - 1) : start, 0);
  5948. return function() {
  5949. var args = arguments,
  5950. index = -1,
  5951. length = nativeMax(args.length - start, 0),
  5952. array = Array(length);
  5953. while (++index < length) {
  5954. array[index] = args[start + index];
  5955. }
  5956. index = -1;
  5957. var otherArgs = Array(start + 1);
  5958. while (++index < start) {
  5959. otherArgs[index] = args[index];
  5960. }
  5961. otherArgs[start] = transform(array);
  5962. return _apply(func, this, otherArgs);
  5963. };
  5964. }
  5965. var _overRest = overRest;
  5966. /**
  5967. * A specialized version of `baseRest` which flattens the rest array.
  5968. *
  5969. * @private
  5970. * @param {Function} func The function to apply a rest parameter to.
  5971. * @returns {Function} Returns the new function.
  5972. */
  5973. function flatRest(func) {
  5974. return _setToString(_overRest(func, undefined, flatten_1), func + '');
  5975. }
  5976. var _flatRest = flatRest;
  5977. /** Used to compose bitmasks for function metadata. */
  5978. var WRAP_REARG_FLAG = 256;
  5979. /**
  5980. * Creates a function that invokes `func` with arguments arranged according
  5981. * to the specified `indexes` where the argument value at the first index is
  5982. * provided as the first argument, the argument value at the second index is
  5983. * provided as the second argument, and so on.
  5984. *
  5985. * @static
  5986. * @memberOf _
  5987. * @since 3.0.0
  5988. * @category Function
  5989. * @param {Function} func The function to rearrange arguments for.
  5990. * @param {...(number|number[])} indexes The arranged argument indexes.
  5991. * @returns {Function} Returns the new function.
  5992. * @example
  5993. *
  5994. * var rearged = _.rearg(function(a, b, c) {
  5995. * return [a, b, c];
  5996. * }, [2, 0, 1]);
  5997. *
  5998. * rearged('b', 'c', 'a')
  5999. * // => ['a', 'b', 'c']
  6000. */
  6001. var rearg = _flatRest(function(func, indexes) {
  6002. return _createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes);
  6003. });
  6004. var rearg_1 = rearg;
  6005. /**
  6006. * Converts `value` to a property path array.
  6007. *
  6008. * @static
  6009. * @memberOf _
  6010. * @since 4.0.0
  6011. * @category Util
  6012. * @param {*} value The value to convert.
  6013. * @returns {Array} Returns the new property path array.
  6014. * @example
  6015. *
  6016. * _.toPath('a.b.c');
  6017. * // => ['a', 'b', 'c']
  6018. *
  6019. * _.toPath('a[0].b.c');
  6020. * // => ['a', '0', 'b', 'c']
  6021. */
  6022. function toPath(value) {
  6023. if (isArray_1(value)) {
  6024. return _arrayMap(value, _toKey);
  6025. }
  6026. return isSymbol_1(value) ? [value] : _copyArray(_stringToPath(toString_1(value)));
  6027. }
  6028. var toPath_1 = toPath;
  6029. var _util = {
  6030. 'ary': ary_1,
  6031. 'assign': _baseAssign,
  6032. 'clone': clone_1,
  6033. 'curry': commonjsRequire("../curry", "/$$rollup_base$$/node_modules/lodash/fp"),
  6034. 'forEach': _arrayEach,
  6035. 'isArray': isArray_1,
  6036. 'isError': isError_1,
  6037. 'isFunction': isFunction_1,
  6038. 'isWeakMap': isWeakMap_1,
  6039. 'iteratee': iteratee_1,
  6040. 'keys': _baseKeys,
  6041. 'rearg': rearg_1,
  6042. 'toInteger': toInteger_1,
  6043. 'toPath': toPath_1
  6044. };
  6045. /**
  6046. * Converts `func` of `name` to an immutable auto-curried iteratee-first data-last
  6047. * version with conversion `options` applied. If `name` is an object its methods
  6048. * will be converted.
  6049. *
  6050. * @param {string} name The name of the function to wrap.
  6051. * @param {Function} [func] The function to wrap.
  6052. * @param {Object} [options] The options object. See `baseConvert` for more details.
  6053. * @returns {Function|Object} Returns the converted function or object.
  6054. */
  6055. function convert$2(name, func, options) {
  6056. return _baseConvert(_util, name, func, options);
  6057. }
  6058. var convert_1 = convert$2;
  6059. commonjsRegister("/$$rollup_base$$/node_modules/lodash/fp/curry.js", function (module, exports) {
  6060. var convert = convert_1,
  6061. func = convert('curry', commonjsRequire("../curry", "/$$rollup_base$$/node_modules/lodash/fp"));
  6062. func.placeholder = placeholder;
  6063. module.exports = func;
  6064. });
  6065. commonjsRegister("/$$rollup_base$$/node_modules/lodash/fp/curryN.js", function (module, exports) {
  6066. var convert = convert_1,
  6067. func = convert('curryN', commonjsRequire("../curry", "/$$rollup_base$$/node_modules/lodash/fp"));
  6068. func.placeholder = placeholder;
  6069. module.exports = func;
  6070. });
  6071. commonjsRegister("/$$rollup_base$$/node_modules/lodash/fp/curryRight.js", function (module, exports) {
  6072. var convert = convert_1,
  6073. func = convert('curryRight', commonjsRequire("../curryRight", "/$$rollup_base$$/node_modules/lodash/fp"));
  6074. func.placeholder = placeholder;
  6075. module.exports = func;
  6076. });
  6077. commonjsRegister("/$$rollup_base$$/node_modules/lodash/fp/curryRightN.js", function (module, exports) {
  6078. var convert = convert_1,
  6079. func = convert('curryRightN', commonjsRequire("../curryRight", "/$$rollup_base$$/node_modules/lodash/fp"));
  6080. func.placeholder = placeholder;
  6081. module.exports = func;
  6082. });
  6083. var moment = createCommonjsModule(function (module, exports) {
  6084. (function (global, factory) {
  6085. module.exports = factory() ;
  6086. }(commonjsGlobal, (function () {
  6087. var hookCallback;
  6088. function hooks() {
  6089. return hookCallback.apply(null, arguments);
  6090. }
  6091. // This is done to register the method called with moment()
  6092. // without creating circular dependencies.
  6093. function setHookCallback(callback) {
  6094. hookCallback = callback;
  6095. }
  6096. function isArray(input) {
  6097. return (
  6098. input instanceof Array ||
  6099. Object.prototype.toString.call(input) === '[object Array]'
  6100. );
  6101. }
  6102. function isObject(input) {
  6103. // IE8 will treat undefined and null as object if it wasn't for
  6104. // input != null
  6105. return (
  6106. input != null &&
  6107. Object.prototype.toString.call(input) === '[object Object]'
  6108. );
  6109. }
  6110. function hasOwnProp(a, b) {
  6111. return Object.prototype.hasOwnProperty.call(a, b);
  6112. }
  6113. function isObjectEmpty(obj) {
  6114. if (Object.getOwnPropertyNames) {
  6115. return Object.getOwnPropertyNames(obj).length === 0;
  6116. } else {
  6117. var k;
  6118. for (k in obj) {
  6119. if (hasOwnProp(obj, k)) {
  6120. return false;
  6121. }
  6122. }
  6123. return true;
  6124. }
  6125. }
  6126. function isUndefined(input) {
  6127. return input === void 0;
  6128. }
  6129. function isNumber(input) {
  6130. return (
  6131. typeof input === 'number' ||
  6132. Object.prototype.toString.call(input) === '[object Number]'
  6133. );
  6134. }
  6135. function isDate(input) {
  6136. return (
  6137. input instanceof Date ||
  6138. Object.prototype.toString.call(input) === '[object Date]'
  6139. );
  6140. }
  6141. function map(arr, fn) {
  6142. var res = [],
  6143. i;
  6144. for (i = 0; i < arr.length; ++i) {
  6145. res.push(fn(arr[i], i));
  6146. }
  6147. return res;
  6148. }
  6149. function extend(a, b) {
  6150. for (var i in b) {
  6151. if (hasOwnProp(b, i)) {
  6152. a[i] = b[i];
  6153. }
  6154. }
  6155. if (hasOwnProp(b, 'toString')) {
  6156. a.toString = b.toString;
  6157. }
  6158. if (hasOwnProp(b, 'valueOf')) {
  6159. a.valueOf = b.valueOf;
  6160. }
  6161. return a;
  6162. }
  6163. function createUTC(input, format, locale, strict) {
  6164. return createLocalOrUTC(input, format, locale, strict, true).utc();
  6165. }
  6166. function defaultParsingFlags() {
  6167. // We need to deep clone this object.
  6168. return {
  6169. empty: false,
  6170. unusedTokens: [],
  6171. unusedInput: [],
  6172. overflow: -2,
  6173. charsLeftOver: 0,
  6174. nullInput: false,
  6175. invalidEra: null,
  6176. invalidMonth: null,
  6177. invalidFormat: false,
  6178. userInvalidated: false,
  6179. iso: false,
  6180. parsedDateParts: [],
  6181. era: null,
  6182. meridiem: null,
  6183. rfc2822: false,
  6184. weekdayMismatch: false,
  6185. };
  6186. }
  6187. function getParsingFlags(m) {
  6188. if (m._pf == null) {
  6189. m._pf = defaultParsingFlags();
  6190. }
  6191. return m._pf;
  6192. }
  6193. var some;
  6194. if (Array.prototype.some) {
  6195. some = Array.prototype.some;
  6196. } else {
  6197. some = function (fun) {
  6198. var t = Object(this),
  6199. len = t.length >>> 0,
  6200. i;
  6201. for (i = 0; i < len; i++) {
  6202. if (i in t && fun.call(this, t[i], i, t)) {
  6203. return true;
  6204. }
  6205. }
  6206. return false;
  6207. };
  6208. }
  6209. function isValid(m) {
  6210. if (m._isValid == null) {
  6211. var flags = getParsingFlags(m),
  6212. parsedParts = some.call(flags.parsedDateParts, function (i) {
  6213. return i != null;
  6214. }),
  6215. isNowValid =
  6216. !isNaN(m._d.getTime()) &&
  6217. flags.overflow < 0 &&
  6218. !flags.empty &&
  6219. !flags.invalidEra &&
  6220. !flags.invalidMonth &&
  6221. !flags.invalidWeekday &&
  6222. !flags.weekdayMismatch &&
  6223. !flags.nullInput &&
  6224. !flags.invalidFormat &&
  6225. !flags.userInvalidated &&
  6226. (!flags.meridiem || (flags.meridiem && parsedParts));
  6227. if (m._strict) {
  6228. isNowValid =
  6229. isNowValid &&
  6230. flags.charsLeftOver === 0 &&
  6231. flags.unusedTokens.length === 0 &&
  6232. flags.bigHour === undefined;
  6233. }
  6234. if (Object.isFrozen == null || !Object.isFrozen(m)) {
  6235. m._isValid = isNowValid;
  6236. } else {
  6237. return isNowValid;
  6238. }
  6239. }
  6240. return m._isValid;
  6241. }
  6242. function createInvalid(flags) {
  6243. var m = createUTC(NaN);
  6244. if (flags != null) {
  6245. extend(getParsingFlags(m), flags);
  6246. } else {
  6247. getParsingFlags(m).userInvalidated = true;
  6248. }
  6249. return m;
  6250. }
  6251. // Plugins that add properties should also add the key here (null value),
  6252. // so we can properly clone ourselves.
  6253. var momentProperties = (hooks.momentProperties = []),
  6254. updateInProgress = false;
  6255. function copyConfig(to, from) {
  6256. var i, prop, val;
  6257. if (!isUndefined(from._isAMomentObject)) {
  6258. to._isAMomentObject = from._isAMomentObject;
  6259. }
  6260. if (!isUndefined(from._i)) {
  6261. to._i = from._i;
  6262. }
  6263. if (!isUndefined(from._f)) {
  6264. to._f = from._f;
  6265. }
  6266. if (!isUndefined(from._l)) {
  6267. to._l = from._l;
  6268. }
  6269. if (!isUndefined(from._strict)) {
  6270. to._strict = from._strict;
  6271. }
  6272. if (!isUndefined(from._tzm)) {
  6273. to._tzm = from._tzm;
  6274. }
  6275. if (!isUndefined(from._isUTC)) {
  6276. to._isUTC = from._isUTC;
  6277. }
  6278. if (!isUndefined(from._offset)) {
  6279. to._offset = from._offset;
  6280. }
  6281. if (!isUndefined(from._pf)) {
  6282. to._pf = getParsingFlags(from);
  6283. }
  6284. if (!isUndefined(from._locale)) {
  6285. to._locale = from._locale;
  6286. }
  6287. if (momentProperties.length > 0) {
  6288. for (i = 0; i < momentProperties.length; i++) {
  6289. prop = momentProperties[i];
  6290. val = from[prop];
  6291. if (!isUndefined(val)) {
  6292. to[prop] = val;
  6293. }
  6294. }
  6295. }
  6296. return to;
  6297. }
  6298. // Moment prototype object
  6299. function Moment(config) {
  6300. copyConfig(this, config);
  6301. this._d = new Date(config._d != null ? config._d.getTime() : NaN);
  6302. if (!this.isValid()) {
  6303. this._d = new Date(NaN);
  6304. }
  6305. // Prevent infinite loop in case updateOffset creates new moment
  6306. // objects.
  6307. if (updateInProgress === false) {
  6308. updateInProgress = true;
  6309. hooks.updateOffset(this);
  6310. updateInProgress = false;
  6311. }
  6312. }
  6313. function isMoment(obj) {
  6314. return (
  6315. obj instanceof Moment || (obj != null && obj._isAMomentObject != null)
  6316. );
  6317. }
  6318. function warn(msg) {
  6319. if (
  6320. hooks.suppressDeprecationWarnings === false &&
  6321. typeof console !== 'undefined' &&
  6322. console.warn
  6323. ) {
  6324. console.warn('Deprecation warning: ' + msg);
  6325. }
  6326. }
  6327. function deprecate(msg, fn) {
  6328. var firstTime = true;
  6329. return extend(function () {
  6330. if (hooks.deprecationHandler != null) {
  6331. hooks.deprecationHandler(null, msg);
  6332. }
  6333. if (firstTime) {
  6334. var args = [],
  6335. arg,
  6336. i,
  6337. key;
  6338. for (i = 0; i < arguments.length; i++) {
  6339. arg = '';
  6340. if (typeof arguments[i] === 'object') {
  6341. arg += '\n[' + i + '] ';
  6342. for (key in arguments[0]) {
  6343. if (hasOwnProp(arguments[0], key)) {
  6344. arg += key + ': ' + arguments[0][key] + ', ';
  6345. }
  6346. }
  6347. arg = arg.slice(0, -2); // Remove trailing comma and space
  6348. } else {
  6349. arg = arguments[i];
  6350. }
  6351. args.push(arg);
  6352. }
  6353. warn(
  6354. msg +
  6355. '\nArguments: ' +
  6356. Array.prototype.slice.call(args).join('') +
  6357. '\n' +
  6358. new Error().stack
  6359. );
  6360. firstTime = false;
  6361. }
  6362. return fn.apply(this, arguments);
  6363. }, fn);
  6364. }
  6365. var deprecations = {};
  6366. function deprecateSimple(name, msg) {
  6367. if (hooks.deprecationHandler != null) {
  6368. hooks.deprecationHandler(name, msg);
  6369. }
  6370. if (!deprecations[name]) {
  6371. warn(msg);
  6372. deprecations[name] = true;
  6373. }
  6374. }
  6375. hooks.suppressDeprecationWarnings = false;
  6376. hooks.deprecationHandler = null;
  6377. function isFunction(input) {
  6378. return (
  6379. (typeof Function !== 'undefined' && input instanceof Function) ||
  6380. Object.prototype.toString.call(input) === '[object Function]'
  6381. );
  6382. }
  6383. function set(config) {
  6384. var prop, i;
  6385. for (i in config) {
  6386. if (hasOwnProp(config, i)) {
  6387. prop = config[i];
  6388. if (isFunction(prop)) {
  6389. this[i] = prop;
  6390. } else {
  6391. this['_' + i] = prop;
  6392. }
  6393. }
  6394. }
  6395. this._config = config;
  6396. // Lenient ordinal parsing accepts just a number in addition to
  6397. // number + (possibly) stuff coming from _dayOfMonthOrdinalParse.
  6398. // TODO: Remove "ordinalParse" fallback in next major release.
  6399. this._dayOfMonthOrdinalParseLenient = new RegExp(
  6400. (this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) +
  6401. '|' +
  6402. /\d{1,2}/.source
  6403. );
  6404. }
  6405. function mergeConfigs(parentConfig, childConfig) {
  6406. var res = extend({}, parentConfig),
  6407. prop;
  6408. for (prop in childConfig) {
  6409. if (hasOwnProp(childConfig, prop)) {
  6410. if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) {
  6411. res[prop] = {};
  6412. extend(res[prop], parentConfig[prop]);
  6413. extend(res[prop], childConfig[prop]);
  6414. } else if (childConfig[prop] != null) {
  6415. res[prop] = childConfig[prop];
  6416. } else {
  6417. delete res[prop];
  6418. }
  6419. }
  6420. }
  6421. for (prop in parentConfig) {
  6422. if (
  6423. hasOwnProp(parentConfig, prop) &&
  6424. !hasOwnProp(childConfig, prop) &&
  6425. isObject(parentConfig[prop])
  6426. ) {
  6427. // make sure changes to properties don't modify parent config
  6428. res[prop] = extend({}, res[prop]);
  6429. }
  6430. }
  6431. return res;
  6432. }
  6433. function Locale(config) {
  6434. if (config != null) {
  6435. this.set(config);
  6436. }
  6437. }
  6438. var keys;
  6439. if (Object.keys) {
  6440. keys = Object.keys;
  6441. } else {
  6442. keys = function (obj) {
  6443. var i,
  6444. res = [];
  6445. for (i in obj) {
  6446. if (hasOwnProp(obj, i)) {
  6447. res.push(i);
  6448. }
  6449. }
  6450. return res;
  6451. };
  6452. }
  6453. var defaultCalendar = {
  6454. sameDay: '[Today at] LT',
  6455. nextDay: '[Tomorrow at] LT',
  6456. nextWeek: 'dddd [at] LT',
  6457. lastDay: '[Yesterday at] LT',
  6458. lastWeek: '[Last] dddd [at] LT',
  6459. sameElse: 'L',
  6460. };
  6461. function calendar(key, mom, now) {
  6462. var output = this._calendar[key] || this._calendar['sameElse'];
  6463. return isFunction(output) ? output.call(mom, now) : output;
  6464. }
  6465. function zeroFill(number, targetLength, forceSign) {
  6466. var absNumber = '' + Math.abs(number),
  6467. zerosToFill = targetLength - absNumber.length,
  6468. sign = number >= 0;
  6469. return (
  6470. (sign ? (forceSign ? '+' : '') : '-') +
  6471. Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) +
  6472. absNumber
  6473. );
  6474. }
  6475. var formattingTokens = /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|N{1,5}|YYYYYY|YYYYY|YYYY|YY|y{2,4}|yo?|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g,
  6476. localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,
  6477. formatFunctions = {},
  6478. formatTokenFunctions = {};
  6479. // token: 'M'
  6480. // padded: ['MM', 2]
  6481. // ordinal: 'Mo'
  6482. // callback: function () { this.month() + 1 }
  6483. function addFormatToken(token, padded, ordinal, callback) {
  6484. var func = callback;
  6485. if (typeof callback === 'string') {
  6486. func = function () {
  6487. return this[callback]();
  6488. };
  6489. }
  6490. if (token) {
  6491. formatTokenFunctions[token] = func;
  6492. }
  6493. if (padded) {
  6494. formatTokenFunctions[padded[0]] = function () {
  6495. return zeroFill(func.apply(this, arguments), padded[1], padded[2]);
  6496. };
  6497. }
  6498. if (ordinal) {
  6499. formatTokenFunctions[ordinal] = function () {
  6500. return this.localeData().ordinal(
  6501. func.apply(this, arguments),
  6502. token
  6503. );
  6504. };
  6505. }
  6506. }
  6507. function removeFormattingTokens(input) {
  6508. if (input.match(/\[[\s\S]/)) {
  6509. return input.replace(/^\[|\]$/g, '');
  6510. }
  6511. return input.replace(/\\/g, '');
  6512. }
  6513. function makeFormatFunction(format) {
  6514. var array = format.match(formattingTokens),
  6515. i,
  6516. length;
  6517. for (i = 0, length = array.length; i < length; i++) {
  6518. if (formatTokenFunctions[array[i]]) {
  6519. array[i] = formatTokenFunctions[array[i]];
  6520. } else {
  6521. array[i] = removeFormattingTokens(array[i]);
  6522. }
  6523. }
  6524. return function (mom) {
  6525. var output = '',
  6526. i;
  6527. for (i = 0; i < length; i++) {
  6528. output += isFunction(array[i])
  6529. ? array[i].call(mom, format)
  6530. : array[i];
  6531. }
  6532. return output;
  6533. };
  6534. }
  6535. // format date using native date object
  6536. function formatMoment(m, format) {
  6537. if (!m.isValid()) {
  6538. return m.localeData().invalidDate();
  6539. }
  6540. format = expandFormat(format, m.localeData());
  6541. formatFunctions[format] =
  6542. formatFunctions[format] || makeFormatFunction(format);
  6543. return formatFunctions[format](m);
  6544. }
  6545. function expandFormat(format, locale) {
  6546. var i = 5;
  6547. function replaceLongDateFormatTokens(input) {
  6548. return locale.longDateFormat(input) || input;
  6549. }
  6550. localFormattingTokens.lastIndex = 0;
  6551. while (i >= 0 && localFormattingTokens.test(format)) {
  6552. format = format.replace(
  6553. localFormattingTokens,
  6554. replaceLongDateFormatTokens
  6555. );
  6556. localFormattingTokens.lastIndex = 0;
  6557. i -= 1;
  6558. }
  6559. return format;
  6560. }
  6561. var defaultLongDateFormat = {
  6562. LTS: 'h:mm:ss A',
  6563. LT: 'h:mm A',
  6564. L: 'MM/DD/YYYY',
  6565. LL: 'MMMM D, YYYY',
  6566. LLL: 'MMMM D, YYYY h:mm A',
  6567. LLLL: 'dddd, MMMM D, YYYY h:mm A',
  6568. };
  6569. function longDateFormat(key) {
  6570. var format = this._longDateFormat[key],
  6571. formatUpper = this._longDateFormat[key.toUpperCase()];
  6572. if (format || !formatUpper) {
  6573. return format;
  6574. }
  6575. this._longDateFormat[key] = formatUpper
  6576. .match(formattingTokens)
  6577. .map(function (tok) {
  6578. if (
  6579. tok === 'MMMM' ||
  6580. tok === 'MM' ||
  6581. tok === 'DD' ||
  6582. tok === 'dddd'
  6583. ) {
  6584. return tok.slice(1);
  6585. }
  6586. return tok;
  6587. })
  6588. .join('');
  6589. return this._longDateFormat[key];
  6590. }
  6591. var defaultInvalidDate = 'Invalid date';
  6592. function invalidDate() {
  6593. return this._invalidDate;
  6594. }
  6595. var defaultOrdinal = '%d',
  6596. defaultDayOfMonthOrdinalParse = /\d{1,2}/;
  6597. function ordinal(number) {
  6598. return this._ordinal.replace('%d', number);
  6599. }
  6600. var defaultRelativeTime = {
  6601. future: 'in %s',
  6602. past: '%s ago',
  6603. s: 'a few seconds',
  6604. ss: '%d seconds',
  6605. m: 'a minute',
  6606. mm: '%d minutes',
  6607. h: 'an hour',
  6608. hh: '%d hours',
  6609. d: 'a day',
  6610. dd: '%d days',
  6611. w: 'a week',
  6612. ww: '%d weeks',
  6613. M: 'a month',
  6614. MM: '%d months',
  6615. y: 'a year',
  6616. yy: '%d years',
  6617. };
  6618. function relativeTime(number, withoutSuffix, string, isFuture) {
  6619. var output = this._relativeTime[string];
  6620. return isFunction(output)
  6621. ? output(number, withoutSuffix, string, isFuture)
  6622. : output.replace(/%d/i, number);
  6623. }
  6624. function pastFuture(diff, output) {
  6625. var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
  6626. return isFunction(format) ? format(output) : format.replace(/%s/i, output);
  6627. }
  6628. var aliases = {};
  6629. function addUnitAlias(unit, shorthand) {
  6630. var lowerCase = unit.toLowerCase();
  6631. aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit;
  6632. }
  6633. function normalizeUnits(units) {
  6634. return typeof units === 'string'
  6635. ? aliases[units] || aliases[units.toLowerCase()]
  6636. : undefined;
  6637. }
  6638. function normalizeObjectUnits(inputObject) {
  6639. var normalizedInput = {},
  6640. normalizedProp,
  6641. prop;
  6642. for (prop in inputObject) {
  6643. if (hasOwnProp(inputObject, prop)) {
  6644. normalizedProp = normalizeUnits(prop);
  6645. if (normalizedProp) {
  6646. normalizedInput[normalizedProp] = inputObject[prop];
  6647. }
  6648. }
  6649. }
  6650. return normalizedInput;
  6651. }
  6652. var priorities = {};
  6653. function addUnitPriority(unit, priority) {
  6654. priorities[unit] = priority;
  6655. }
  6656. function getPrioritizedUnits(unitsObj) {
  6657. var units = [],
  6658. u;
  6659. for (u in unitsObj) {
  6660. if (hasOwnProp(unitsObj, u)) {
  6661. units.push({ unit: u, priority: priorities[u] });
  6662. }
  6663. }
  6664. units.sort(function (a, b) {
  6665. return a.priority - b.priority;
  6666. });
  6667. return units;
  6668. }
  6669. function isLeapYear(year) {
  6670. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  6671. }
  6672. function absFloor(number) {
  6673. if (number < 0) {
  6674. // -0 -> 0
  6675. return Math.ceil(number) || 0;
  6676. } else {
  6677. return Math.floor(number);
  6678. }
  6679. }
  6680. function toInt(argumentForCoercion) {
  6681. var coercedNumber = +argumentForCoercion,
  6682. value = 0;
  6683. if (coercedNumber !== 0 && isFinite(coercedNumber)) {
  6684. value = absFloor(coercedNumber);
  6685. }
  6686. return value;
  6687. }
  6688. function makeGetSet(unit, keepTime) {
  6689. return function (value) {
  6690. if (value != null) {
  6691. set$1(this, unit, value);
  6692. hooks.updateOffset(this, keepTime);
  6693. return this;
  6694. } else {
  6695. return get(this, unit);
  6696. }
  6697. };
  6698. }
  6699. function get(mom, unit) {
  6700. return mom.isValid()
  6701. ? mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]()
  6702. : NaN;
  6703. }
  6704. function set$1(mom, unit, value) {
  6705. if (mom.isValid() && !isNaN(value)) {
  6706. if (
  6707. unit === 'FullYear' &&
  6708. isLeapYear(mom.year()) &&
  6709. mom.month() === 1 &&
  6710. mom.date() === 29
  6711. ) {
  6712. value = toInt(value);
  6713. mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](
  6714. value,
  6715. mom.month(),
  6716. daysInMonth(value, mom.month())
  6717. );
  6718. } else {
  6719. mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
  6720. }
  6721. }
  6722. }
  6723. // MOMENTS
  6724. function stringGet(units) {
  6725. units = normalizeUnits(units);
  6726. if (isFunction(this[units])) {
  6727. return this[units]();
  6728. }
  6729. return this;
  6730. }
  6731. function stringSet(units, value) {
  6732. if (typeof units === 'object') {
  6733. units = normalizeObjectUnits(units);
  6734. var prioritized = getPrioritizedUnits(units),
  6735. i;
  6736. for (i = 0; i < prioritized.length; i++) {
  6737. this[prioritized[i].unit](units[prioritized[i].unit]);
  6738. }
  6739. } else {
  6740. units = normalizeUnits(units);
  6741. if (isFunction(this[units])) {
  6742. return this[units](value);
  6743. }
  6744. }
  6745. return this;
  6746. }
  6747. var match1 = /\d/, // 0 - 9
  6748. match2 = /\d\d/, // 00 - 99
  6749. match3 = /\d{3}/, // 000 - 999
  6750. match4 = /\d{4}/, // 0000 - 9999
  6751. match6 = /[+-]?\d{6}/, // -999999 - 999999
  6752. match1to2 = /\d\d?/, // 0 - 99
  6753. match3to4 = /\d\d\d\d?/, // 999 - 9999
  6754. match5to6 = /\d\d\d\d\d\d?/, // 99999 - 999999
  6755. match1to3 = /\d{1,3}/, // 0 - 999
  6756. match1to4 = /\d{1,4}/, // 0 - 9999
  6757. match1to6 = /[+-]?\d{1,6}/, // -999999 - 999999
  6758. matchUnsigned = /\d+/, // 0 - inf
  6759. matchSigned = /[+-]?\d+/, // -inf - inf
  6760. matchOffset = /Z|[+-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z
  6761. matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi, // +00 -00 +00:00 -00:00 +0000 -0000 or Z
  6762. matchTimestamp = /[+-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123
  6763. // any word (or two) characters or numbers including two/three word month in arabic.
  6764. // includes scottish gaelic two word and hyphenated months
  6765. matchWord = /[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i,
  6766. regexes;
  6767. regexes = {};
  6768. function addRegexToken(token, regex, strictRegex) {
  6769. regexes[token] = isFunction(regex)
  6770. ? regex
  6771. : function (isStrict, localeData) {
  6772. return isStrict && strictRegex ? strictRegex : regex;
  6773. };
  6774. }
  6775. function getParseRegexForToken(token, config) {
  6776. if (!hasOwnProp(regexes, token)) {
  6777. return new RegExp(unescapeFormat(token));
  6778. }
  6779. return regexes[token](config._strict, config._locale);
  6780. }
  6781. // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
  6782. function unescapeFormat(s) {
  6783. return regexEscape(
  6784. s
  6785. .replace('\\', '')
  6786. .replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (
  6787. matched,
  6788. p1,
  6789. p2,
  6790. p3,
  6791. p4
  6792. ) {
  6793. return p1 || p2 || p3 || p4;
  6794. })
  6795. );
  6796. }
  6797. function regexEscape(s) {
  6798. return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  6799. }
  6800. var tokens = {};
  6801. function addParseToken(token, callback) {
  6802. var i,
  6803. func = callback;
  6804. if (typeof token === 'string') {
  6805. token = [token];
  6806. }
  6807. if (isNumber(callback)) {
  6808. func = function (input, array) {
  6809. array[callback] = toInt(input);
  6810. };
  6811. }
  6812. for (i = 0; i < token.length; i++) {
  6813. tokens[token[i]] = func;
  6814. }
  6815. }
  6816. function addWeekParseToken(token, callback) {
  6817. addParseToken(token, function (input, array, config, token) {
  6818. config._w = config._w || {};
  6819. callback(input, config._w, config, token);
  6820. });
  6821. }
  6822. function addTimeToArrayFromToken(token, input, config) {
  6823. if (input != null && hasOwnProp(tokens, token)) {
  6824. tokens[token](input, config._a, config, token);
  6825. }
  6826. }
  6827. var YEAR = 0,
  6828. MONTH = 1,
  6829. DATE = 2,
  6830. HOUR = 3,
  6831. MINUTE = 4,
  6832. SECOND = 5,
  6833. MILLISECOND = 6,
  6834. WEEK = 7,
  6835. WEEKDAY = 8;
  6836. function mod(n, x) {
  6837. return ((n % x) + x) % x;
  6838. }
  6839. var indexOf;
  6840. if (Array.prototype.indexOf) {
  6841. indexOf = Array.prototype.indexOf;
  6842. } else {
  6843. indexOf = function (o) {
  6844. // I know
  6845. var i;
  6846. for (i = 0; i < this.length; ++i) {
  6847. if (this[i] === o) {
  6848. return i;
  6849. }
  6850. }
  6851. return -1;
  6852. };
  6853. }
  6854. function daysInMonth(year, month) {
  6855. if (isNaN(year) || isNaN(month)) {
  6856. return NaN;
  6857. }
  6858. var modMonth = mod(month, 12);
  6859. year += (month - modMonth) / 12;
  6860. return modMonth === 1
  6861. ? isLeapYear(year)
  6862. ? 29
  6863. : 28
  6864. : 31 - ((modMonth % 7) % 2);
  6865. }
  6866. // FORMATTING
  6867. addFormatToken('M', ['MM', 2], 'Mo', function () {
  6868. return this.month() + 1;
  6869. });
  6870. addFormatToken('MMM', 0, 0, function (format) {
  6871. return this.localeData().monthsShort(this, format);
  6872. });
  6873. addFormatToken('MMMM', 0, 0, function (format) {
  6874. return this.localeData().months(this, format);
  6875. });
  6876. // ALIASES
  6877. addUnitAlias('month', 'M');
  6878. // PRIORITY
  6879. addUnitPriority('month', 8);
  6880. // PARSING
  6881. addRegexToken('M', match1to2);
  6882. addRegexToken('MM', match1to2, match2);
  6883. addRegexToken('MMM', function (isStrict, locale) {
  6884. return locale.monthsShortRegex(isStrict);
  6885. });
  6886. addRegexToken('MMMM', function (isStrict, locale) {
  6887. return locale.monthsRegex(isStrict);
  6888. });
  6889. addParseToken(['M', 'MM'], function (input, array) {
  6890. array[MONTH] = toInt(input) - 1;
  6891. });
  6892. addParseToken(['MMM', 'MMMM'], function (input, array, config, token) {
  6893. var month = config._locale.monthsParse(input, token, config._strict);
  6894. // if we didn't find a month name, mark the date as invalid.
  6895. if (month != null) {
  6896. array[MONTH] = month;
  6897. } else {
  6898. getParsingFlags(config).invalidMonth = input;
  6899. }
  6900. });
  6901. // LOCALES
  6902. var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split(
  6903. '_'
  6904. ),
  6905. defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split(
  6906. '_'
  6907. ),
  6908. MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/,
  6909. defaultMonthsShortRegex = matchWord,
  6910. defaultMonthsRegex = matchWord;
  6911. function localeMonths(m, format) {
  6912. if (!m) {
  6913. return isArray(this._months)
  6914. ? this._months
  6915. : this._months['standalone'];
  6916. }
  6917. return isArray(this._months)
  6918. ? this._months[m.month()]
  6919. : this._months[
  6920. (this._months.isFormat || MONTHS_IN_FORMAT).test(format)
  6921. ? 'format'
  6922. : 'standalone'
  6923. ][m.month()];
  6924. }
  6925. function localeMonthsShort(m, format) {
  6926. if (!m) {
  6927. return isArray(this._monthsShort)
  6928. ? this._monthsShort
  6929. : this._monthsShort['standalone'];
  6930. }
  6931. return isArray(this._monthsShort)
  6932. ? this._monthsShort[m.month()]
  6933. : this._monthsShort[
  6934. MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone'
  6935. ][m.month()];
  6936. }
  6937. function handleStrictParse(monthName, format, strict) {
  6938. var i,
  6939. ii,
  6940. mom,
  6941. llc = monthName.toLocaleLowerCase();
  6942. if (!this._monthsParse) {
  6943. // this is not used
  6944. this._monthsParse = [];
  6945. this._longMonthsParse = [];
  6946. this._shortMonthsParse = [];
  6947. for (i = 0; i < 12; ++i) {
  6948. mom = createUTC([2000, i]);
  6949. this._shortMonthsParse[i] = this.monthsShort(
  6950. mom,
  6951. ''
  6952. ).toLocaleLowerCase();
  6953. this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase();
  6954. }
  6955. }
  6956. if (strict) {
  6957. if (format === 'MMM') {
  6958. ii = indexOf.call(this._shortMonthsParse, llc);
  6959. return ii !== -1 ? ii : null;
  6960. } else {
  6961. ii = indexOf.call(this._longMonthsParse, llc);
  6962. return ii !== -1 ? ii : null;
  6963. }
  6964. } else {
  6965. if (format === 'MMM') {
  6966. ii = indexOf.call(this._shortMonthsParse, llc);
  6967. if (ii !== -1) {
  6968. return ii;
  6969. }
  6970. ii = indexOf.call(this._longMonthsParse, llc);
  6971. return ii !== -1 ? ii : null;
  6972. } else {
  6973. ii = indexOf.call(this._longMonthsParse, llc);
  6974. if (ii !== -1) {
  6975. return ii;
  6976. }
  6977. ii = indexOf.call(this._shortMonthsParse, llc);
  6978. return ii !== -1 ? ii : null;
  6979. }
  6980. }
  6981. }
  6982. function localeMonthsParse(monthName, format, strict) {
  6983. var i, mom, regex;
  6984. if (this._monthsParseExact) {
  6985. return handleStrictParse.call(this, monthName, format, strict);
  6986. }
  6987. if (!this._monthsParse) {
  6988. this._monthsParse = [];
  6989. this._longMonthsParse = [];
  6990. this._shortMonthsParse = [];
  6991. }
  6992. // TODO: add sorting
  6993. // Sorting makes sure if one month (or abbr) is a prefix of another
  6994. // see sorting in computeMonthsParse
  6995. for (i = 0; i < 12; i++) {
  6996. // make the regex if we don't have it already
  6997. mom = createUTC([2000, i]);
  6998. if (strict && !this._longMonthsParse[i]) {
  6999. this._longMonthsParse[i] = new RegExp(
  7000. '^' + this.months(mom, '').replace('.', '') + '$',
  7001. 'i'
  7002. );
  7003. this._shortMonthsParse[i] = new RegExp(
  7004. '^' + this.monthsShort(mom, '').replace('.', '') + '$',
  7005. 'i'
  7006. );
  7007. }
  7008. if (!strict && !this._monthsParse[i]) {
  7009. regex =
  7010. '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
  7011. this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
  7012. }
  7013. // test the regex
  7014. if (
  7015. strict &&
  7016. format === 'MMMM' &&
  7017. this._longMonthsParse[i].test(monthName)
  7018. ) {
  7019. return i;
  7020. } else if (
  7021. strict &&
  7022. format === 'MMM' &&
  7023. this._shortMonthsParse[i].test(monthName)
  7024. ) {
  7025. return i;
  7026. } else if (!strict && this._monthsParse[i].test(monthName)) {
  7027. return i;
  7028. }
  7029. }
  7030. }
  7031. // MOMENTS
  7032. function setMonth(mom, value) {
  7033. var dayOfMonth;
  7034. if (!mom.isValid()) {
  7035. // No op
  7036. return mom;
  7037. }
  7038. if (typeof value === 'string') {
  7039. if (/^\d+$/.test(value)) {
  7040. value = toInt(value);
  7041. } else {
  7042. value = mom.localeData().monthsParse(value);
  7043. // TODO: Another silent failure?
  7044. if (!isNumber(value)) {
  7045. return mom;
  7046. }
  7047. }
  7048. }
  7049. dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value));
  7050. mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
  7051. return mom;
  7052. }
  7053. function getSetMonth(value) {
  7054. if (value != null) {
  7055. setMonth(this, value);
  7056. hooks.updateOffset(this, true);
  7057. return this;
  7058. } else {
  7059. return get(this, 'Month');
  7060. }
  7061. }
  7062. function getDaysInMonth() {
  7063. return daysInMonth(this.year(), this.month());
  7064. }
  7065. function monthsShortRegex(isStrict) {
  7066. if (this._monthsParseExact) {
  7067. if (!hasOwnProp(this, '_monthsRegex')) {
  7068. computeMonthsParse.call(this);
  7069. }
  7070. if (isStrict) {
  7071. return this._monthsShortStrictRegex;
  7072. } else {
  7073. return this._monthsShortRegex;
  7074. }
  7075. } else {
  7076. if (!hasOwnProp(this, '_monthsShortRegex')) {
  7077. this._monthsShortRegex = defaultMonthsShortRegex;
  7078. }
  7079. return this._monthsShortStrictRegex && isStrict
  7080. ? this._monthsShortStrictRegex
  7081. : this._monthsShortRegex;
  7082. }
  7083. }
  7084. function monthsRegex(isStrict) {
  7085. if (this._monthsParseExact) {
  7086. if (!hasOwnProp(this, '_monthsRegex')) {
  7087. computeMonthsParse.call(this);
  7088. }
  7089. if (isStrict) {
  7090. return this._monthsStrictRegex;
  7091. } else {
  7092. return this._monthsRegex;
  7093. }
  7094. } else {
  7095. if (!hasOwnProp(this, '_monthsRegex')) {
  7096. this._monthsRegex = defaultMonthsRegex;
  7097. }
  7098. return this._monthsStrictRegex && isStrict
  7099. ? this._monthsStrictRegex
  7100. : this._monthsRegex;
  7101. }
  7102. }
  7103. function computeMonthsParse() {
  7104. function cmpLenRev(a, b) {
  7105. return b.length - a.length;
  7106. }
  7107. var shortPieces = [],
  7108. longPieces = [],
  7109. mixedPieces = [],
  7110. i,
  7111. mom;
  7112. for (i = 0; i < 12; i++) {
  7113. // make the regex if we don't have it already
  7114. mom = createUTC([2000, i]);
  7115. shortPieces.push(this.monthsShort(mom, ''));
  7116. longPieces.push(this.months(mom, ''));
  7117. mixedPieces.push(this.months(mom, ''));
  7118. mixedPieces.push(this.monthsShort(mom, ''));
  7119. }
  7120. // Sorting makes sure if one month (or abbr) is a prefix of another it
  7121. // will match the longer piece.
  7122. shortPieces.sort(cmpLenRev);
  7123. longPieces.sort(cmpLenRev);
  7124. mixedPieces.sort(cmpLenRev);
  7125. for (i = 0; i < 12; i++) {
  7126. shortPieces[i] = regexEscape(shortPieces[i]);
  7127. longPieces[i] = regexEscape(longPieces[i]);
  7128. }
  7129. for (i = 0; i < 24; i++) {
  7130. mixedPieces[i] = regexEscape(mixedPieces[i]);
  7131. }
  7132. this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
  7133. this._monthsShortRegex = this._monthsRegex;
  7134. this._monthsStrictRegex = new RegExp(
  7135. '^(' + longPieces.join('|') + ')',
  7136. 'i'
  7137. );
  7138. this._monthsShortStrictRegex = new RegExp(
  7139. '^(' + shortPieces.join('|') + ')',
  7140. 'i'
  7141. );
  7142. }
  7143. // FORMATTING
  7144. addFormatToken('Y', 0, 0, function () {
  7145. var y = this.year();
  7146. return y <= 9999 ? zeroFill(y, 4) : '+' + y;
  7147. });
  7148. addFormatToken(0, ['YY', 2], 0, function () {
  7149. return this.year() % 100;
  7150. });
  7151. addFormatToken(0, ['YYYY', 4], 0, 'year');
  7152. addFormatToken(0, ['YYYYY', 5], 0, 'year');
  7153. addFormatToken(0, ['YYYYYY', 6, true], 0, 'year');
  7154. // ALIASES
  7155. addUnitAlias('year', 'y');
  7156. // PRIORITIES
  7157. addUnitPriority('year', 1);
  7158. // PARSING
  7159. addRegexToken('Y', matchSigned);
  7160. addRegexToken('YY', match1to2, match2);
  7161. addRegexToken('YYYY', match1to4, match4);
  7162. addRegexToken('YYYYY', match1to6, match6);
  7163. addRegexToken('YYYYYY', match1to6, match6);
  7164. addParseToken(['YYYYY', 'YYYYYY'], YEAR);
  7165. addParseToken('YYYY', function (input, array) {
  7166. array[YEAR] =
  7167. input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input);
  7168. });
  7169. addParseToken('YY', function (input, array) {
  7170. array[YEAR] = hooks.parseTwoDigitYear(input);
  7171. });
  7172. addParseToken('Y', function (input, array) {
  7173. array[YEAR] = parseInt(input, 10);
  7174. });
  7175. // HELPERS
  7176. function daysInYear(year) {
  7177. return isLeapYear(year) ? 366 : 365;
  7178. }
  7179. // HOOKS
  7180. hooks.parseTwoDigitYear = function (input) {
  7181. return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
  7182. };
  7183. // MOMENTS
  7184. var getSetYear = makeGetSet('FullYear', true);
  7185. function getIsLeapYear() {
  7186. return isLeapYear(this.year());
  7187. }
  7188. function createDate(y, m, d, h, M, s, ms) {
  7189. // can't just apply() to create a date:
  7190. // https://stackoverflow.com/q/181348
  7191. var date;
  7192. // the date constructor remaps years 0-99 to 1900-1999
  7193. if (y < 100 && y >= 0) {
  7194. // preserve leap years using a full 400 year cycle, then reset
  7195. date = new Date(y + 400, m, d, h, M, s, ms);
  7196. if (isFinite(date.getFullYear())) {
  7197. date.setFullYear(y);
  7198. }
  7199. } else {
  7200. date = new Date(y, m, d, h, M, s, ms);
  7201. }
  7202. return date;
  7203. }
  7204. function createUTCDate(y) {
  7205. var date, args;
  7206. // the Date.UTC function remaps years 0-99 to 1900-1999
  7207. if (y < 100 && y >= 0) {
  7208. args = Array.prototype.slice.call(arguments);
  7209. // preserve leap years using a full 400 year cycle, then reset
  7210. args[0] = y + 400;
  7211. date = new Date(Date.UTC.apply(null, args));
  7212. if (isFinite(date.getUTCFullYear())) {
  7213. date.setUTCFullYear(y);
  7214. }
  7215. } else {
  7216. date = new Date(Date.UTC.apply(null, arguments));
  7217. }
  7218. return date;
  7219. }
  7220. // start-of-first-week - start-of-year
  7221. function firstWeekOffset(year, dow, doy) {
  7222. var // first-week day -- which january is always in the first week (4 for iso, 1 for other)
  7223. fwd = 7 + dow - doy,
  7224. // first-week day local weekday -- which local weekday is fwd
  7225. fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7;
  7226. return -fwdlw + fwd - 1;
  7227. }
  7228. // https://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
  7229. function dayOfYearFromWeeks(year, week, weekday, dow, doy) {
  7230. var localWeekday = (7 + weekday - dow) % 7,
  7231. weekOffset = firstWeekOffset(year, dow, doy),
  7232. dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset,
  7233. resYear,
  7234. resDayOfYear;
  7235. if (dayOfYear <= 0) {
  7236. resYear = year - 1;
  7237. resDayOfYear = daysInYear(resYear) + dayOfYear;
  7238. } else if (dayOfYear > daysInYear(year)) {
  7239. resYear = year + 1;
  7240. resDayOfYear = dayOfYear - daysInYear(year);
  7241. } else {
  7242. resYear = year;
  7243. resDayOfYear = dayOfYear;
  7244. }
  7245. return {
  7246. year: resYear,
  7247. dayOfYear: resDayOfYear,
  7248. };
  7249. }
  7250. function weekOfYear(mom, dow, doy) {
  7251. var weekOffset = firstWeekOffset(mom.year(), dow, doy),
  7252. week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1,
  7253. resWeek,
  7254. resYear;
  7255. if (week < 1) {
  7256. resYear = mom.year() - 1;
  7257. resWeek = week + weeksInYear(resYear, dow, doy);
  7258. } else if (week > weeksInYear(mom.year(), dow, doy)) {
  7259. resWeek = week - weeksInYear(mom.year(), dow, doy);
  7260. resYear = mom.year() + 1;
  7261. } else {
  7262. resYear = mom.year();
  7263. resWeek = week;
  7264. }
  7265. return {
  7266. week: resWeek,
  7267. year: resYear,
  7268. };
  7269. }
  7270. function weeksInYear(year, dow, doy) {
  7271. var weekOffset = firstWeekOffset(year, dow, doy),
  7272. weekOffsetNext = firstWeekOffset(year + 1, dow, doy);
  7273. return (daysInYear(year) - weekOffset + weekOffsetNext) / 7;
  7274. }
  7275. // FORMATTING
  7276. addFormatToken('w', ['ww', 2], 'wo', 'week');
  7277. addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek');
  7278. // ALIASES
  7279. addUnitAlias('week', 'w');
  7280. addUnitAlias('isoWeek', 'W');
  7281. // PRIORITIES
  7282. addUnitPriority('week', 5);
  7283. addUnitPriority('isoWeek', 5);
  7284. // PARSING
  7285. addRegexToken('w', match1to2);
  7286. addRegexToken('ww', match1to2, match2);
  7287. addRegexToken('W', match1to2);
  7288. addRegexToken('WW', match1to2, match2);
  7289. addWeekParseToken(['w', 'ww', 'W', 'WW'], function (
  7290. input,
  7291. week,
  7292. config,
  7293. token
  7294. ) {
  7295. week[token.substr(0, 1)] = toInt(input);
  7296. });
  7297. // HELPERS
  7298. // LOCALES
  7299. function localeWeek(mom) {
  7300. return weekOfYear(mom, this._week.dow, this._week.doy).week;
  7301. }
  7302. var defaultLocaleWeek = {
  7303. dow: 0, // Sunday is the first day of the week.
  7304. doy: 6, // The week that contains Jan 6th is the first week of the year.
  7305. };
  7306. function localeFirstDayOfWeek() {
  7307. return this._week.dow;
  7308. }
  7309. function localeFirstDayOfYear() {
  7310. return this._week.doy;
  7311. }
  7312. // MOMENTS
  7313. function getSetWeek(input) {
  7314. var week = this.localeData().week(this);
  7315. return input == null ? week : this.add((input - week) * 7, 'd');
  7316. }
  7317. function getSetISOWeek(input) {
  7318. var week = weekOfYear(this, 1, 4).week;
  7319. return input == null ? week : this.add((input - week) * 7, 'd');
  7320. }
  7321. // FORMATTING
  7322. addFormatToken('d', 0, 'do', 'day');
  7323. addFormatToken('dd', 0, 0, function (format) {
  7324. return this.localeData().weekdaysMin(this, format);
  7325. });
  7326. addFormatToken('ddd', 0, 0, function (format) {
  7327. return this.localeData().weekdaysShort(this, format);
  7328. });
  7329. addFormatToken('dddd', 0, 0, function (format) {
  7330. return this.localeData().weekdays(this, format);
  7331. });
  7332. addFormatToken('e', 0, 0, 'weekday');
  7333. addFormatToken('E', 0, 0, 'isoWeekday');
  7334. // ALIASES
  7335. addUnitAlias('day', 'd');
  7336. addUnitAlias('weekday', 'e');
  7337. addUnitAlias('isoWeekday', 'E');
  7338. // PRIORITY
  7339. addUnitPriority('day', 11);
  7340. addUnitPriority('weekday', 11);
  7341. addUnitPriority('isoWeekday', 11);
  7342. // PARSING
  7343. addRegexToken('d', match1to2);
  7344. addRegexToken('e', match1to2);
  7345. addRegexToken('E', match1to2);
  7346. addRegexToken('dd', function (isStrict, locale) {
  7347. return locale.weekdaysMinRegex(isStrict);
  7348. });
  7349. addRegexToken('ddd', function (isStrict, locale) {
  7350. return locale.weekdaysShortRegex(isStrict);
  7351. });
  7352. addRegexToken('dddd', function (isStrict, locale) {
  7353. return locale.weekdaysRegex(isStrict);
  7354. });
  7355. addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) {
  7356. var weekday = config._locale.weekdaysParse(input, token, config._strict);
  7357. // if we didn't get a weekday name, mark the date as invalid
  7358. if (weekday != null) {
  7359. week.d = weekday;
  7360. } else {
  7361. getParsingFlags(config).invalidWeekday = input;
  7362. }
  7363. });
  7364. addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) {
  7365. week[token] = toInt(input);
  7366. });
  7367. // HELPERS
  7368. function parseWeekday(input, locale) {
  7369. if (typeof input !== 'string') {
  7370. return input;
  7371. }
  7372. if (!isNaN(input)) {
  7373. return parseInt(input, 10);
  7374. }
  7375. input = locale.weekdaysParse(input);
  7376. if (typeof input === 'number') {
  7377. return input;
  7378. }
  7379. return null;
  7380. }
  7381. function parseIsoWeekday(input, locale) {
  7382. if (typeof input === 'string') {
  7383. return locale.weekdaysParse(input) % 7 || 7;
  7384. }
  7385. return isNaN(input) ? null : input;
  7386. }
  7387. // LOCALES
  7388. function shiftWeekdays(ws, n) {
  7389. return ws.slice(n, 7).concat(ws.slice(0, n));
  7390. }
  7391. var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split(
  7392. '_'
  7393. ),
  7394. defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),
  7395. defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),
  7396. defaultWeekdaysRegex = matchWord,
  7397. defaultWeekdaysShortRegex = matchWord,
  7398. defaultWeekdaysMinRegex = matchWord;
  7399. function localeWeekdays(m, format) {
  7400. var weekdays = isArray(this._weekdays)
  7401. ? this._weekdays
  7402. : this._weekdays[
  7403. m && m !== true && this._weekdays.isFormat.test(format)
  7404. ? 'format'
  7405. : 'standalone'
  7406. ];
  7407. return m === true
  7408. ? shiftWeekdays(weekdays, this._week.dow)
  7409. : m
  7410. ? weekdays[m.day()]
  7411. : weekdays;
  7412. }
  7413. function localeWeekdaysShort(m) {
  7414. return m === true
  7415. ? shiftWeekdays(this._weekdaysShort, this._week.dow)
  7416. : m
  7417. ? this._weekdaysShort[m.day()]
  7418. : this._weekdaysShort;
  7419. }
  7420. function localeWeekdaysMin(m) {
  7421. return m === true
  7422. ? shiftWeekdays(this._weekdaysMin, this._week.dow)
  7423. : m
  7424. ? this._weekdaysMin[m.day()]
  7425. : this._weekdaysMin;
  7426. }
  7427. function handleStrictParse$1(weekdayName, format, strict) {
  7428. var i,
  7429. ii,
  7430. mom,
  7431. llc = weekdayName.toLocaleLowerCase();
  7432. if (!this._weekdaysParse) {
  7433. this._weekdaysParse = [];
  7434. this._shortWeekdaysParse = [];
  7435. this._minWeekdaysParse = [];
  7436. for (i = 0; i < 7; ++i) {
  7437. mom = createUTC([2000, 1]).day(i);
  7438. this._minWeekdaysParse[i] = this.weekdaysMin(
  7439. mom,
  7440. ''
  7441. ).toLocaleLowerCase();
  7442. this._shortWeekdaysParse[i] = this.weekdaysShort(
  7443. mom,
  7444. ''
  7445. ).toLocaleLowerCase();
  7446. this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase();
  7447. }
  7448. }
  7449. if (strict) {
  7450. if (format === 'dddd') {
  7451. ii = indexOf.call(this._weekdaysParse, llc);
  7452. return ii !== -1 ? ii : null;
  7453. } else if (format === 'ddd') {
  7454. ii = indexOf.call(this._shortWeekdaysParse, llc);
  7455. return ii !== -1 ? ii : null;
  7456. } else {
  7457. ii = indexOf.call(this._minWeekdaysParse, llc);
  7458. return ii !== -1 ? ii : null;
  7459. }
  7460. } else {
  7461. if (format === 'dddd') {
  7462. ii = indexOf.call(this._weekdaysParse, llc);
  7463. if (ii !== -1) {
  7464. return ii;
  7465. }
  7466. ii = indexOf.call(this._shortWeekdaysParse, llc);
  7467. if (ii !== -1) {
  7468. return ii;
  7469. }
  7470. ii = indexOf.call(this._minWeekdaysParse, llc);
  7471. return ii !== -1 ? ii : null;
  7472. } else if (format === 'ddd') {
  7473. ii = indexOf.call(this._shortWeekdaysParse, llc);
  7474. if (ii !== -1) {
  7475. return ii;
  7476. }
  7477. ii = indexOf.call(this._weekdaysParse, llc);
  7478. if (ii !== -1) {
  7479. return ii;
  7480. }
  7481. ii = indexOf.call(this._minWeekdaysParse, llc);
  7482. return ii !== -1 ? ii : null;
  7483. } else {
  7484. ii = indexOf.call(this._minWeekdaysParse, llc);
  7485. if (ii !== -1) {
  7486. return ii;
  7487. }
  7488. ii = indexOf.call(this._weekdaysParse, llc);
  7489. if (ii !== -1) {
  7490. return ii;
  7491. }
  7492. ii = indexOf.call(this._shortWeekdaysParse, llc);
  7493. return ii !== -1 ? ii : null;
  7494. }
  7495. }
  7496. }
  7497. function localeWeekdaysParse(weekdayName, format, strict) {
  7498. var i, mom, regex;
  7499. if (this._weekdaysParseExact) {
  7500. return handleStrictParse$1.call(this, weekdayName, format, strict);
  7501. }
  7502. if (!this._weekdaysParse) {
  7503. this._weekdaysParse = [];
  7504. this._minWeekdaysParse = [];
  7505. this._shortWeekdaysParse = [];
  7506. this._fullWeekdaysParse = [];
  7507. }
  7508. for (i = 0; i < 7; i++) {
  7509. // make the regex if we don't have it already
  7510. mom = createUTC([2000, 1]).day(i);
  7511. if (strict && !this._fullWeekdaysParse[i]) {
  7512. this._fullWeekdaysParse[i] = new RegExp(
  7513. '^' + this.weekdays(mom, '').replace('.', '\\.?') + '$',
  7514. 'i'
  7515. );
  7516. this._shortWeekdaysParse[i] = new RegExp(
  7517. '^' + this.weekdaysShort(mom, '').replace('.', '\\.?') + '$',
  7518. 'i'
  7519. );
  7520. this._minWeekdaysParse[i] = new RegExp(
  7521. '^' + this.weekdaysMin(mom, '').replace('.', '\\.?') + '$',
  7522. 'i'
  7523. );
  7524. }
  7525. if (!this._weekdaysParse[i]) {
  7526. regex =
  7527. '^' +
  7528. this.weekdays(mom, '') +
  7529. '|^' +
  7530. this.weekdaysShort(mom, '') +
  7531. '|^' +
  7532. this.weekdaysMin(mom, '');
  7533. this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
  7534. }
  7535. // test the regex
  7536. if (
  7537. strict &&
  7538. format === 'dddd' &&
  7539. this._fullWeekdaysParse[i].test(weekdayName)
  7540. ) {
  7541. return i;
  7542. } else if (
  7543. strict &&
  7544. format === 'ddd' &&
  7545. this._shortWeekdaysParse[i].test(weekdayName)
  7546. ) {
  7547. return i;
  7548. } else if (
  7549. strict &&
  7550. format === 'dd' &&
  7551. this._minWeekdaysParse[i].test(weekdayName)
  7552. ) {
  7553. return i;
  7554. } else if (!strict && this._weekdaysParse[i].test(weekdayName)) {
  7555. return i;
  7556. }
  7557. }
  7558. }
  7559. // MOMENTS
  7560. function getSetDayOfWeek(input) {
  7561. if (!this.isValid()) {
  7562. return input != null ? this : NaN;
  7563. }
  7564. var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
  7565. if (input != null) {
  7566. input = parseWeekday(input, this.localeData());
  7567. return this.add(input - day, 'd');
  7568. } else {
  7569. return day;
  7570. }
  7571. }
  7572. function getSetLocaleDayOfWeek(input) {
  7573. if (!this.isValid()) {
  7574. return input != null ? this : NaN;
  7575. }
  7576. var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7;
  7577. return input == null ? weekday : this.add(input - weekday, 'd');
  7578. }
  7579. function getSetISODayOfWeek(input) {
  7580. if (!this.isValid()) {
  7581. return input != null ? this : NaN;
  7582. }
  7583. // behaves the same as moment#day except
  7584. // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
  7585. // as a setter, sunday should belong to the previous week.
  7586. if (input != null) {
  7587. var weekday = parseIsoWeekday(input, this.localeData());
  7588. return this.day(this.day() % 7 ? weekday : weekday - 7);
  7589. } else {
  7590. return this.day() || 7;
  7591. }
  7592. }
  7593. function weekdaysRegex(isStrict) {
  7594. if (this._weekdaysParseExact) {
  7595. if (!hasOwnProp(this, '_weekdaysRegex')) {
  7596. computeWeekdaysParse.call(this);
  7597. }
  7598. if (isStrict) {
  7599. return this._weekdaysStrictRegex;
  7600. } else {
  7601. return this._weekdaysRegex;
  7602. }
  7603. } else {
  7604. if (!hasOwnProp(this, '_weekdaysRegex')) {
  7605. this._weekdaysRegex = defaultWeekdaysRegex;
  7606. }
  7607. return this._weekdaysStrictRegex && isStrict
  7608. ? this._weekdaysStrictRegex
  7609. : this._weekdaysRegex;
  7610. }
  7611. }
  7612. function weekdaysShortRegex(isStrict) {
  7613. if (this._weekdaysParseExact) {
  7614. if (!hasOwnProp(this, '_weekdaysRegex')) {
  7615. computeWeekdaysParse.call(this);
  7616. }
  7617. if (isStrict) {
  7618. return this._weekdaysShortStrictRegex;
  7619. } else {
  7620. return this._weekdaysShortRegex;
  7621. }
  7622. } else {
  7623. if (!hasOwnProp(this, '_weekdaysShortRegex')) {
  7624. this._weekdaysShortRegex = defaultWeekdaysShortRegex;
  7625. }
  7626. return this._weekdaysShortStrictRegex && isStrict
  7627. ? this._weekdaysShortStrictRegex
  7628. : this._weekdaysShortRegex;
  7629. }
  7630. }
  7631. function weekdaysMinRegex(isStrict) {
  7632. if (this._weekdaysParseExact) {
  7633. if (!hasOwnProp(this, '_weekdaysRegex')) {
  7634. computeWeekdaysParse.call(this);
  7635. }
  7636. if (isStrict) {
  7637. return this._weekdaysMinStrictRegex;
  7638. } else {
  7639. return this._weekdaysMinRegex;
  7640. }
  7641. } else {
  7642. if (!hasOwnProp(this, '_weekdaysMinRegex')) {
  7643. this._weekdaysMinRegex = defaultWeekdaysMinRegex;
  7644. }
  7645. return this._weekdaysMinStrictRegex && isStrict
  7646. ? this._weekdaysMinStrictRegex
  7647. : this._weekdaysMinRegex;
  7648. }
  7649. }
  7650. function computeWeekdaysParse() {
  7651. function cmpLenRev(a, b) {
  7652. return b.length - a.length;
  7653. }
  7654. var minPieces = [],
  7655. shortPieces = [],
  7656. longPieces = [],
  7657. mixedPieces = [],
  7658. i,
  7659. mom,
  7660. minp,
  7661. shortp,
  7662. longp;
  7663. for (i = 0; i < 7; i++) {
  7664. // make the regex if we don't have it already
  7665. mom = createUTC([2000, 1]).day(i);
  7666. minp = regexEscape(this.weekdaysMin(mom, ''));
  7667. shortp = regexEscape(this.weekdaysShort(mom, ''));
  7668. longp = regexEscape(this.weekdays(mom, ''));
  7669. minPieces.push(minp);
  7670. shortPieces.push(shortp);
  7671. longPieces.push(longp);
  7672. mixedPieces.push(minp);
  7673. mixedPieces.push(shortp);
  7674. mixedPieces.push(longp);
  7675. }
  7676. // Sorting makes sure if one weekday (or abbr) is a prefix of another it
  7677. // will match the longer piece.
  7678. minPieces.sort(cmpLenRev);
  7679. shortPieces.sort(cmpLenRev);
  7680. longPieces.sort(cmpLenRev);
  7681. mixedPieces.sort(cmpLenRev);
  7682. this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
  7683. this._weekdaysShortRegex = this._weekdaysRegex;
  7684. this._weekdaysMinRegex = this._weekdaysRegex;
  7685. this._weekdaysStrictRegex = new RegExp(
  7686. '^(' + longPieces.join('|') + ')',
  7687. 'i'
  7688. );
  7689. this._weekdaysShortStrictRegex = new RegExp(
  7690. '^(' + shortPieces.join('|') + ')',
  7691. 'i'
  7692. );
  7693. this._weekdaysMinStrictRegex = new RegExp(
  7694. '^(' + minPieces.join('|') + ')',
  7695. 'i'
  7696. );
  7697. }
  7698. // FORMATTING
  7699. function hFormat() {
  7700. return this.hours() % 12 || 12;
  7701. }
  7702. function kFormat() {
  7703. return this.hours() || 24;
  7704. }
  7705. addFormatToken('H', ['HH', 2], 0, 'hour');
  7706. addFormatToken('h', ['hh', 2], 0, hFormat);
  7707. addFormatToken('k', ['kk', 2], 0, kFormat);
  7708. addFormatToken('hmm', 0, 0, function () {
  7709. return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2);
  7710. });
  7711. addFormatToken('hmmss', 0, 0, function () {
  7712. return (
  7713. '' +
  7714. hFormat.apply(this) +
  7715. zeroFill(this.minutes(), 2) +
  7716. zeroFill(this.seconds(), 2)
  7717. );
  7718. });
  7719. addFormatToken('Hmm', 0, 0, function () {
  7720. return '' + this.hours() + zeroFill(this.minutes(), 2);
  7721. });
  7722. addFormatToken('Hmmss', 0, 0, function () {
  7723. return (
  7724. '' +
  7725. this.hours() +
  7726. zeroFill(this.minutes(), 2) +
  7727. zeroFill(this.seconds(), 2)
  7728. );
  7729. });
  7730. function meridiem(token, lowercase) {
  7731. addFormatToken(token, 0, 0, function () {
  7732. return this.localeData().meridiem(
  7733. this.hours(),
  7734. this.minutes(),
  7735. lowercase
  7736. );
  7737. });
  7738. }
  7739. meridiem('a', true);
  7740. meridiem('A', false);
  7741. // ALIASES
  7742. addUnitAlias('hour', 'h');
  7743. // PRIORITY
  7744. addUnitPriority('hour', 13);
  7745. // PARSING
  7746. function matchMeridiem(isStrict, locale) {
  7747. return locale._meridiemParse;
  7748. }
  7749. addRegexToken('a', matchMeridiem);
  7750. addRegexToken('A', matchMeridiem);
  7751. addRegexToken('H', match1to2);
  7752. addRegexToken('h', match1to2);
  7753. addRegexToken('k', match1to2);
  7754. addRegexToken('HH', match1to2, match2);
  7755. addRegexToken('hh', match1to2, match2);
  7756. addRegexToken('kk', match1to2, match2);
  7757. addRegexToken('hmm', match3to4);
  7758. addRegexToken('hmmss', match5to6);
  7759. addRegexToken('Hmm', match3to4);
  7760. addRegexToken('Hmmss', match5to6);
  7761. addParseToken(['H', 'HH'], HOUR);
  7762. addParseToken(['k', 'kk'], function (input, array, config) {
  7763. var kInput = toInt(input);
  7764. array[HOUR] = kInput === 24 ? 0 : kInput;
  7765. });
  7766. addParseToken(['a', 'A'], function (input, array, config) {
  7767. config._isPm = config._locale.isPM(input);
  7768. config._meridiem = input;
  7769. });
  7770. addParseToken(['h', 'hh'], function (input, array, config) {
  7771. array[HOUR] = toInt(input);
  7772. getParsingFlags(config).bigHour = true;
  7773. });
  7774. addParseToken('hmm', function (input, array, config) {
  7775. var pos = input.length - 2;
  7776. array[HOUR] = toInt(input.substr(0, pos));
  7777. array[MINUTE] = toInt(input.substr(pos));
  7778. getParsingFlags(config).bigHour = true;
  7779. });
  7780. addParseToken('hmmss', function (input, array, config) {
  7781. var pos1 = input.length - 4,
  7782. pos2 = input.length - 2;
  7783. array[HOUR] = toInt(input.substr(0, pos1));
  7784. array[MINUTE] = toInt(input.substr(pos1, 2));
  7785. array[SECOND] = toInt(input.substr(pos2));
  7786. getParsingFlags(config).bigHour = true;
  7787. });
  7788. addParseToken('Hmm', function (input, array, config) {
  7789. var pos = input.length - 2;
  7790. array[HOUR] = toInt(input.substr(0, pos));
  7791. array[MINUTE] = toInt(input.substr(pos));
  7792. });
  7793. addParseToken('Hmmss', function (input, array, config) {
  7794. var pos1 = input.length - 4,
  7795. pos2 = input.length - 2;
  7796. array[HOUR] = toInt(input.substr(0, pos1));
  7797. array[MINUTE] = toInt(input.substr(pos1, 2));
  7798. array[SECOND] = toInt(input.substr(pos2));
  7799. });
  7800. // LOCALES
  7801. function localeIsPM(input) {
  7802. // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
  7803. // Using charAt should be more compatible.
  7804. return (input + '').toLowerCase().charAt(0) === 'p';
  7805. }
  7806. var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i,
  7807. // Setting the hour should keep the time, because the user explicitly
  7808. // specified which hour they want. So trying to maintain the same hour (in
  7809. // a new timezone) makes sense. Adding/subtracting hours does not follow
  7810. // this rule.
  7811. getSetHour = makeGetSet('Hours', true);
  7812. function localeMeridiem(hours, minutes, isLower) {
  7813. if (hours > 11) {
  7814. return isLower ? 'pm' : 'PM';
  7815. } else {
  7816. return isLower ? 'am' : 'AM';
  7817. }
  7818. }
  7819. var baseConfig = {
  7820. calendar: defaultCalendar,
  7821. longDateFormat: defaultLongDateFormat,
  7822. invalidDate: defaultInvalidDate,
  7823. ordinal: defaultOrdinal,
  7824. dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse,
  7825. relativeTime: defaultRelativeTime,
  7826. months: defaultLocaleMonths,
  7827. monthsShort: defaultLocaleMonthsShort,
  7828. week: defaultLocaleWeek,
  7829. weekdays: defaultLocaleWeekdays,
  7830. weekdaysMin: defaultLocaleWeekdaysMin,
  7831. weekdaysShort: defaultLocaleWeekdaysShort,
  7832. meridiemParse: defaultLocaleMeridiemParse,
  7833. };
  7834. // internal storage for locale config files
  7835. var locales = {},
  7836. localeFamilies = {},
  7837. globalLocale;
  7838. function commonPrefix(arr1, arr2) {
  7839. var i,
  7840. minl = Math.min(arr1.length, arr2.length);
  7841. for (i = 0; i < minl; i += 1) {
  7842. if (arr1[i] !== arr2[i]) {
  7843. return i;
  7844. }
  7845. }
  7846. return minl;
  7847. }
  7848. function normalizeLocale(key) {
  7849. return key ? key.toLowerCase().replace('_', '-') : key;
  7850. }
  7851. // pick the locale from the array
  7852. // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
  7853. // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
  7854. function chooseLocale(names) {
  7855. var i = 0,
  7856. j,
  7857. next,
  7858. locale,
  7859. split;
  7860. while (i < names.length) {
  7861. split = normalizeLocale(names[i]).split('-');
  7862. j = split.length;
  7863. next = normalizeLocale(names[i + 1]);
  7864. next = next ? next.split('-') : null;
  7865. while (j > 0) {
  7866. locale = loadLocale(split.slice(0, j).join('-'));
  7867. if (locale) {
  7868. return locale;
  7869. }
  7870. if (
  7871. next &&
  7872. next.length >= j &&
  7873. commonPrefix(split, next) >= j - 1
  7874. ) {
  7875. //the next array item is better than a shallower substring of this one
  7876. break;
  7877. }
  7878. j--;
  7879. }
  7880. i++;
  7881. }
  7882. return globalLocale;
  7883. }
  7884. function loadLocale(name) {
  7885. var oldLocale = null,
  7886. aliasedRequire;
  7887. // TODO: Find a better way to register and load all the locales in Node
  7888. if (
  7889. locales[name] === undefined &&
  7890. 'object' !== 'undefined' &&
  7891. module &&
  7892. module.exports
  7893. ) {
  7894. try {
  7895. oldLocale = globalLocale._abbr;
  7896. aliasedRequire = commonjsRequire;
  7897. aliasedRequire('./locale/' + name);
  7898. getSetGlobalLocale(oldLocale);
  7899. } catch (e) {
  7900. // mark as not found to avoid repeating expensive file require call causing high CPU
  7901. // when trying to find en-US, en_US, en-us for every format call
  7902. locales[name] = null; // null means not found
  7903. }
  7904. }
  7905. return locales[name];
  7906. }
  7907. // This function will load locale and then set the global locale. If
  7908. // no arguments are passed in, it will simply return the current global
  7909. // locale key.
  7910. function getSetGlobalLocale(key, values) {
  7911. var data;
  7912. if (key) {
  7913. if (isUndefined(values)) {
  7914. data = getLocale(key);
  7915. } else {
  7916. data = defineLocale(key, values);
  7917. }
  7918. if (data) {
  7919. // moment.duration._locale = moment._locale = data;
  7920. globalLocale = data;
  7921. } else {
  7922. if (typeof console !== 'undefined' && console.warn) {
  7923. //warn user if arguments are passed but the locale could not be set
  7924. console.warn(
  7925. 'Locale ' + key + ' not found. Did you forget to load it?'
  7926. );
  7927. }
  7928. }
  7929. }
  7930. return globalLocale._abbr;
  7931. }
  7932. function defineLocale(name, config) {
  7933. if (config !== null) {
  7934. var locale,
  7935. parentConfig = baseConfig;
  7936. config.abbr = name;
  7937. if (locales[name] != null) {
  7938. deprecateSimple(
  7939. 'defineLocaleOverride',
  7940. 'use moment.updateLocale(localeName, config) to change ' +
  7941. 'an existing locale. moment.defineLocale(localeName, ' +
  7942. 'config) should only be used for creating a new locale ' +
  7943. 'See http://momentjs.com/guides/#/warnings/define-locale/ for more info.'
  7944. );
  7945. parentConfig = locales[name]._config;
  7946. } else if (config.parentLocale != null) {
  7947. if (locales[config.parentLocale] != null) {
  7948. parentConfig = locales[config.parentLocale]._config;
  7949. } else {
  7950. locale = loadLocale(config.parentLocale);
  7951. if (locale != null) {
  7952. parentConfig = locale._config;
  7953. } else {
  7954. if (!localeFamilies[config.parentLocale]) {
  7955. localeFamilies[config.parentLocale] = [];
  7956. }
  7957. localeFamilies[config.parentLocale].push({
  7958. name: name,
  7959. config: config,
  7960. });
  7961. return null;
  7962. }
  7963. }
  7964. }
  7965. locales[name] = new Locale(mergeConfigs(parentConfig, config));
  7966. if (localeFamilies[name]) {
  7967. localeFamilies[name].forEach(function (x) {
  7968. defineLocale(x.name, x.config);
  7969. });
  7970. }
  7971. // backwards compat for now: also set the locale
  7972. // make sure we set the locale AFTER all child locales have been
  7973. // created, so we won't end up with the child locale set.
  7974. getSetGlobalLocale(name);
  7975. return locales[name];
  7976. } else {
  7977. // useful for testing
  7978. delete locales[name];
  7979. return null;
  7980. }
  7981. }
  7982. function updateLocale(name, config) {
  7983. if (config != null) {
  7984. var locale,
  7985. tmpLocale,
  7986. parentConfig = baseConfig;
  7987. if (locales[name] != null && locales[name].parentLocale != null) {
  7988. // Update existing child locale in-place to avoid memory-leaks
  7989. locales[name].set(mergeConfigs(locales[name]._config, config));
  7990. } else {
  7991. // MERGE
  7992. tmpLocale = loadLocale(name);
  7993. if (tmpLocale != null) {
  7994. parentConfig = tmpLocale._config;
  7995. }
  7996. config = mergeConfigs(parentConfig, config);
  7997. if (tmpLocale == null) {
  7998. // updateLocale is called for creating a new locale
  7999. // Set abbr so it will have a name (getters return
  8000. // undefined otherwise).
  8001. config.abbr = name;
  8002. }
  8003. locale = new Locale(config);
  8004. locale.parentLocale = locales[name];
  8005. locales[name] = locale;
  8006. }
  8007. // backwards compat for now: also set the locale
  8008. getSetGlobalLocale(name);
  8009. } else {
  8010. // pass null for config to unupdate, useful for tests
  8011. if (locales[name] != null) {
  8012. if (locales[name].parentLocale != null) {
  8013. locales[name] = locales[name].parentLocale;
  8014. if (name === getSetGlobalLocale()) {
  8015. getSetGlobalLocale(name);
  8016. }
  8017. } else if (locales[name] != null) {
  8018. delete locales[name];
  8019. }
  8020. }
  8021. }
  8022. return locales[name];
  8023. }
  8024. // returns locale data
  8025. function getLocale(key) {
  8026. var locale;
  8027. if (key && key._locale && key._locale._abbr) {
  8028. key = key._locale._abbr;
  8029. }
  8030. if (!key) {
  8031. return globalLocale;
  8032. }
  8033. if (!isArray(key)) {
  8034. //short-circuit everything else
  8035. locale = loadLocale(key);
  8036. if (locale) {
  8037. return locale;
  8038. }
  8039. key = [key];
  8040. }
  8041. return chooseLocale(key);
  8042. }
  8043. function listLocales() {
  8044. return keys(locales);
  8045. }
  8046. function checkOverflow(m) {
  8047. var overflow,
  8048. a = m._a;
  8049. if (a && getParsingFlags(m).overflow === -2) {
  8050. overflow =
  8051. a[MONTH] < 0 || a[MONTH] > 11
  8052. ? MONTH
  8053. : a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH])
  8054. ? DATE
  8055. : a[HOUR] < 0 ||
  8056. a[HOUR] > 24 ||
  8057. (a[HOUR] === 24 &&
  8058. (a[MINUTE] !== 0 ||
  8059. a[SECOND] !== 0 ||
  8060. a[MILLISECOND] !== 0))
  8061. ? HOUR
  8062. : a[MINUTE] < 0 || a[MINUTE] > 59
  8063. ? MINUTE
  8064. : a[SECOND] < 0 || a[SECOND] > 59
  8065. ? SECOND
  8066. : a[MILLISECOND] < 0 || a[MILLISECOND] > 999
  8067. ? MILLISECOND
  8068. : -1;
  8069. if (
  8070. getParsingFlags(m)._overflowDayOfYear &&
  8071. (overflow < YEAR || overflow > DATE)
  8072. ) {
  8073. overflow = DATE;
  8074. }
  8075. if (getParsingFlags(m)._overflowWeeks && overflow === -1) {
  8076. overflow = WEEK;
  8077. }
  8078. if (getParsingFlags(m)._overflowWeekday && overflow === -1) {
  8079. overflow = WEEKDAY;
  8080. }
  8081. getParsingFlags(m).overflow = overflow;
  8082. }
  8083. return m;
  8084. }
  8085. // iso 8601 regex
  8086. // 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00)
  8087. var extendedIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/,
  8088. basicIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d|))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/,
  8089. tzRegex = /Z|[+-]\d\d(?::?\d\d)?/,
  8090. isoDates = [
  8091. ['YYYYYY-MM-DD', /[+-]\d{6}-\d\d-\d\d/],
  8092. ['YYYY-MM-DD', /\d{4}-\d\d-\d\d/],
  8093. ['GGGG-[W]WW-E', /\d{4}-W\d\d-\d/],
  8094. ['GGGG-[W]WW', /\d{4}-W\d\d/, false],
  8095. ['YYYY-DDD', /\d{4}-\d{3}/],
  8096. ['YYYY-MM', /\d{4}-\d\d/, false],
  8097. ['YYYYYYMMDD', /[+-]\d{10}/],
  8098. ['YYYYMMDD', /\d{8}/],
  8099. ['GGGG[W]WWE', /\d{4}W\d{3}/],
  8100. ['GGGG[W]WW', /\d{4}W\d{2}/, false],
  8101. ['YYYYDDD', /\d{7}/],
  8102. ['YYYYMM', /\d{6}/, false],
  8103. ['YYYY', /\d{4}/, false],
  8104. ],
  8105. // iso time formats and regexes
  8106. isoTimes = [
  8107. ['HH:mm:ss.SSSS', /\d\d:\d\d:\d\d\.\d+/],
  8108. ['HH:mm:ss,SSSS', /\d\d:\d\d:\d\d,\d+/],
  8109. ['HH:mm:ss', /\d\d:\d\d:\d\d/],
  8110. ['HH:mm', /\d\d:\d\d/],
  8111. ['HHmmss.SSSS', /\d\d\d\d\d\d\.\d+/],
  8112. ['HHmmss,SSSS', /\d\d\d\d\d\d,\d+/],
  8113. ['HHmmss', /\d\d\d\d\d\d/],
  8114. ['HHmm', /\d\d\d\d/],
  8115. ['HH', /\d\d/],
  8116. ],
  8117. aspNetJsonRegex = /^\/?Date\((-?\d+)/i,
  8118. // RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3
  8119. rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/,
  8120. obsOffsets = {
  8121. UT: 0,
  8122. GMT: 0,
  8123. EDT: -4 * 60,
  8124. EST: -5 * 60,
  8125. CDT: -5 * 60,
  8126. CST: -6 * 60,
  8127. MDT: -6 * 60,
  8128. MST: -7 * 60,
  8129. PDT: -7 * 60,
  8130. PST: -8 * 60,
  8131. };
  8132. // date from iso format
  8133. function configFromISO(config) {
  8134. var i,
  8135. l,
  8136. string = config._i,
  8137. match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string),
  8138. allowTime,
  8139. dateFormat,
  8140. timeFormat,
  8141. tzFormat;
  8142. if (match) {
  8143. getParsingFlags(config).iso = true;
  8144. for (i = 0, l = isoDates.length; i < l; i++) {
  8145. if (isoDates[i][1].exec(match[1])) {
  8146. dateFormat = isoDates[i][0];
  8147. allowTime = isoDates[i][2] !== false;
  8148. break;
  8149. }
  8150. }
  8151. if (dateFormat == null) {
  8152. config._isValid = false;
  8153. return;
  8154. }
  8155. if (match[3]) {
  8156. for (i = 0, l = isoTimes.length; i < l; i++) {
  8157. if (isoTimes[i][1].exec(match[3])) {
  8158. // match[2] should be 'T' or space
  8159. timeFormat = (match[2] || ' ') + isoTimes[i][0];
  8160. break;
  8161. }
  8162. }
  8163. if (timeFormat == null) {
  8164. config._isValid = false;
  8165. return;
  8166. }
  8167. }
  8168. if (!allowTime && timeFormat != null) {
  8169. config._isValid = false;
  8170. return;
  8171. }
  8172. if (match[4]) {
  8173. if (tzRegex.exec(match[4])) {
  8174. tzFormat = 'Z';
  8175. } else {
  8176. config._isValid = false;
  8177. return;
  8178. }
  8179. }
  8180. config._f = dateFormat + (timeFormat || '') + (tzFormat || '');
  8181. configFromStringAndFormat(config);
  8182. } else {
  8183. config._isValid = false;
  8184. }
  8185. }
  8186. function extractFromRFC2822Strings(
  8187. yearStr,
  8188. monthStr,
  8189. dayStr,
  8190. hourStr,
  8191. minuteStr,
  8192. secondStr
  8193. ) {
  8194. var result = [
  8195. untruncateYear(yearStr),
  8196. defaultLocaleMonthsShort.indexOf(monthStr),
  8197. parseInt(dayStr, 10),
  8198. parseInt(hourStr, 10),
  8199. parseInt(minuteStr, 10),
  8200. ];
  8201. if (secondStr) {
  8202. result.push(parseInt(secondStr, 10));
  8203. }
  8204. return result;
  8205. }
  8206. function untruncateYear(yearStr) {
  8207. var year = parseInt(yearStr, 10);
  8208. if (year <= 49) {
  8209. return 2000 + year;
  8210. } else if (year <= 999) {
  8211. return 1900 + year;
  8212. }
  8213. return year;
  8214. }
  8215. function preprocessRFC2822(s) {
  8216. // Remove comments and folding whitespace and replace multiple-spaces with a single space
  8217. return s
  8218. .replace(/\([^)]*\)|[\n\t]/g, ' ')
  8219. .replace(/(\s\s+)/g, ' ')
  8220. .replace(/^\s\s*/, '')
  8221. .replace(/\s\s*$/, '');
  8222. }
  8223. function checkWeekday(weekdayStr, parsedInput, config) {
  8224. if (weekdayStr) {
  8225. // TODO: Replace the vanilla JS Date object with an independent day-of-week check.
  8226. var weekdayProvided = defaultLocaleWeekdaysShort.indexOf(weekdayStr),
  8227. weekdayActual = new Date(
  8228. parsedInput[0],
  8229. parsedInput[1],
  8230. parsedInput[2]
  8231. ).getDay();
  8232. if (weekdayProvided !== weekdayActual) {
  8233. getParsingFlags(config).weekdayMismatch = true;
  8234. config._isValid = false;
  8235. return false;
  8236. }
  8237. }
  8238. return true;
  8239. }
  8240. function calculateOffset(obsOffset, militaryOffset, numOffset) {
  8241. if (obsOffset) {
  8242. return obsOffsets[obsOffset];
  8243. } else if (militaryOffset) {
  8244. // the only allowed military tz is Z
  8245. return 0;
  8246. } else {
  8247. var hm = parseInt(numOffset, 10),
  8248. m = hm % 100,
  8249. h = (hm - m) / 100;
  8250. return h * 60 + m;
  8251. }
  8252. }
  8253. // date and time from ref 2822 format
  8254. function configFromRFC2822(config) {
  8255. var match = rfc2822.exec(preprocessRFC2822(config._i)),
  8256. parsedArray;
  8257. if (match) {
  8258. parsedArray = extractFromRFC2822Strings(
  8259. match[4],
  8260. match[3],
  8261. match[2],
  8262. match[5],
  8263. match[6],
  8264. match[7]
  8265. );
  8266. if (!checkWeekday(match[1], parsedArray, config)) {
  8267. return;
  8268. }
  8269. config._a = parsedArray;
  8270. config._tzm = calculateOffset(match[8], match[9], match[10]);
  8271. config._d = createUTCDate.apply(null, config._a);
  8272. config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
  8273. getParsingFlags(config).rfc2822 = true;
  8274. } else {
  8275. config._isValid = false;
  8276. }
  8277. }
  8278. // date from 1) ASP.NET, 2) ISO, 3) RFC 2822 formats, or 4) optional fallback if parsing isn't strict
  8279. function configFromString(config) {
  8280. var matched = aspNetJsonRegex.exec(config._i);
  8281. if (matched !== null) {
  8282. config._d = new Date(+matched[1]);
  8283. return;
  8284. }
  8285. configFromISO(config);
  8286. if (config._isValid === false) {
  8287. delete config._isValid;
  8288. } else {
  8289. return;
  8290. }
  8291. configFromRFC2822(config);
  8292. if (config._isValid === false) {
  8293. delete config._isValid;
  8294. } else {
  8295. return;
  8296. }
  8297. if (config._strict) {
  8298. config._isValid = false;
  8299. } else {
  8300. // Final attempt, use Input Fallback
  8301. hooks.createFromInputFallback(config);
  8302. }
  8303. }
  8304. hooks.createFromInputFallback = deprecate(
  8305. 'value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), ' +
  8306. 'which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are ' +
  8307. 'discouraged. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.',
  8308. function (config) {
  8309. config._d = new Date(config._i + (config._useUTC ? ' UTC' : ''));
  8310. }
  8311. );
  8312. // Pick the first defined of two or three arguments.
  8313. function defaults(a, b, c) {
  8314. if (a != null) {
  8315. return a;
  8316. }
  8317. if (b != null) {
  8318. return b;
  8319. }
  8320. return c;
  8321. }
  8322. function currentDateArray(config) {
  8323. // hooks is actually the exported moment object
  8324. var nowValue = new Date(hooks.now());
  8325. if (config._useUTC) {
  8326. return [
  8327. nowValue.getUTCFullYear(),
  8328. nowValue.getUTCMonth(),
  8329. nowValue.getUTCDate(),
  8330. ];
  8331. }
  8332. return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()];
  8333. }
  8334. // convert an array to a date.
  8335. // the array should mirror the parameters below
  8336. // note: all values past the year are optional and will default to the lowest possible value.
  8337. // [year, month, day , hour, minute, second, millisecond]
  8338. function configFromArray(config) {
  8339. var i,
  8340. date,
  8341. input = [],
  8342. currentDate,
  8343. expectedWeekday,
  8344. yearToUse;
  8345. if (config._d) {
  8346. return;
  8347. }
  8348. currentDate = currentDateArray(config);
  8349. //compute day of the year from weeks and weekdays
  8350. if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
  8351. dayOfYearFromWeekInfo(config);
  8352. }
  8353. //if the day of the year is set, figure out what it is
  8354. if (config._dayOfYear != null) {
  8355. yearToUse = defaults(config._a[YEAR], currentDate[YEAR]);
  8356. if (
  8357. config._dayOfYear > daysInYear(yearToUse) ||
  8358. config._dayOfYear === 0
  8359. ) {
  8360. getParsingFlags(config)._overflowDayOfYear = true;
  8361. }
  8362. date = createUTCDate(yearToUse, 0, config._dayOfYear);
  8363. config._a[MONTH] = date.getUTCMonth();
  8364. config._a[DATE] = date.getUTCDate();
  8365. }
  8366. // Default to current date.
  8367. // * if no year, month, day of month are given, default to today
  8368. // * if day of month is given, default month and year
  8369. // * if month is given, default only year
  8370. // * if year is given, don't default anything
  8371. for (i = 0; i < 3 && config._a[i] == null; ++i) {
  8372. config._a[i] = input[i] = currentDate[i];
  8373. }
  8374. // Zero out whatever was not defaulted, including time
  8375. for (; i < 7; i++) {
  8376. config._a[i] = input[i] =
  8377. config._a[i] == null ? (i === 2 ? 1 : 0) : config._a[i];
  8378. }
  8379. // Check for 24:00:00.000
  8380. if (
  8381. config._a[HOUR] === 24 &&
  8382. config._a[MINUTE] === 0 &&
  8383. config._a[SECOND] === 0 &&
  8384. config._a[MILLISECOND] === 0
  8385. ) {
  8386. config._nextDay = true;
  8387. config._a[HOUR] = 0;
  8388. }
  8389. config._d = (config._useUTC ? createUTCDate : createDate).apply(
  8390. null,
  8391. input
  8392. );
  8393. expectedWeekday = config._useUTC
  8394. ? config._d.getUTCDay()
  8395. : config._d.getDay();
  8396. // Apply timezone offset from input. The actual utcOffset can be changed
  8397. // with parseZone.
  8398. if (config._tzm != null) {
  8399. config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
  8400. }
  8401. if (config._nextDay) {
  8402. config._a[HOUR] = 24;
  8403. }
  8404. // check for mismatching day of week
  8405. if (
  8406. config._w &&
  8407. typeof config._w.d !== 'undefined' &&
  8408. config._w.d !== expectedWeekday
  8409. ) {
  8410. getParsingFlags(config).weekdayMismatch = true;
  8411. }
  8412. }
  8413. function dayOfYearFromWeekInfo(config) {
  8414. var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow, curWeek;
  8415. w = config._w;
  8416. if (w.GG != null || w.W != null || w.E != null) {
  8417. dow = 1;
  8418. doy = 4;
  8419. // TODO: We need to take the current isoWeekYear, but that depends on
  8420. // how we interpret now (local, utc, fixed offset). So create
  8421. // a now version of current config (take local/utc/offset flags, and
  8422. // create now).
  8423. weekYear = defaults(
  8424. w.GG,
  8425. config._a[YEAR],
  8426. weekOfYear(createLocal(), 1, 4).year
  8427. );
  8428. week = defaults(w.W, 1);
  8429. weekday = defaults(w.E, 1);
  8430. if (weekday < 1 || weekday > 7) {
  8431. weekdayOverflow = true;
  8432. }
  8433. } else {
  8434. dow = config._locale._week.dow;
  8435. doy = config._locale._week.doy;
  8436. curWeek = weekOfYear(createLocal(), dow, doy);
  8437. weekYear = defaults(w.gg, config._a[YEAR], curWeek.year);
  8438. // Default to current week.
  8439. week = defaults(w.w, curWeek.week);
  8440. if (w.d != null) {
  8441. // weekday -- low day numbers are considered next week
  8442. weekday = w.d;
  8443. if (weekday < 0 || weekday > 6) {
  8444. weekdayOverflow = true;
  8445. }
  8446. } else if (w.e != null) {
  8447. // local weekday -- counting starts from beginning of week
  8448. weekday = w.e + dow;
  8449. if (w.e < 0 || w.e > 6) {
  8450. weekdayOverflow = true;
  8451. }
  8452. } else {
  8453. // default to beginning of week
  8454. weekday = dow;
  8455. }
  8456. }
  8457. if (week < 1 || week > weeksInYear(weekYear, dow, doy)) {
  8458. getParsingFlags(config)._overflowWeeks = true;
  8459. } else if (weekdayOverflow != null) {
  8460. getParsingFlags(config)._overflowWeekday = true;
  8461. } else {
  8462. temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy);
  8463. config._a[YEAR] = temp.year;
  8464. config._dayOfYear = temp.dayOfYear;
  8465. }
  8466. }
  8467. // constant that refers to the ISO standard
  8468. hooks.ISO_8601 = function () {};
  8469. // constant that refers to the RFC 2822 form
  8470. hooks.RFC_2822 = function () {};
  8471. // date from string and format string
  8472. function configFromStringAndFormat(config) {
  8473. // TODO: Move this to another part of the creation flow to prevent circular deps
  8474. if (config._f === hooks.ISO_8601) {
  8475. configFromISO(config);
  8476. return;
  8477. }
  8478. if (config._f === hooks.RFC_2822) {
  8479. configFromRFC2822(config);
  8480. return;
  8481. }
  8482. config._a = [];
  8483. getParsingFlags(config).empty = true;
  8484. // This array is used to make a Date, either with `new Date` or `Date.UTC`
  8485. var string = '' + config._i,
  8486. i,
  8487. parsedInput,
  8488. tokens,
  8489. token,
  8490. skipped,
  8491. stringLength = string.length,
  8492. totalParsedInputLength = 0,
  8493. era;
  8494. tokens =
  8495. expandFormat(config._f, config._locale).match(formattingTokens) || [];
  8496. for (i = 0; i < tokens.length; i++) {
  8497. token = tokens[i];
  8498. parsedInput = (string.match(getParseRegexForToken(token, config)) ||
  8499. [])[0];
  8500. if (parsedInput) {
  8501. skipped = string.substr(0, string.indexOf(parsedInput));
  8502. if (skipped.length > 0) {
  8503. getParsingFlags(config).unusedInput.push(skipped);
  8504. }
  8505. string = string.slice(
  8506. string.indexOf(parsedInput) + parsedInput.length
  8507. );
  8508. totalParsedInputLength += parsedInput.length;
  8509. }
  8510. // don't parse if it's not a known token
  8511. if (formatTokenFunctions[token]) {
  8512. if (parsedInput) {
  8513. getParsingFlags(config).empty = false;
  8514. } else {
  8515. getParsingFlags(config).unusedTokens.push(token);
  8516. }
  8517. addTimeToArrayFromToken(token, parsedInput, config);
  8518. } else if (config._strict && !parsedInput) {
  8519. getParsingFlags(config).unusedTokens.push(token);
  8520. }
  8521. }
  8522. // add remaining unparsed input length to the string
  8523. getParsingFlags(config).charsLeftOver =
  8524. stringLength - totalParsedInputLength;
  8525. if (string.length > 0) {
  8526. getParsingFlags(config).unusedInput.push(string);
  8527. }
  8528. // clear _12h flag if hour is <= 12
  8529. if (
  8530. config._a[HOUR] <= 12 &&
  8531. getParsingFlags(config).bigHour === true &&
  8532. config._a[HOUR] > 0
  8533. ) {
  8534. getParsingFlags(config).bigHour = undefined;
  8535. }
  8536. getParsingFlags(config).parsedDateParts = config._a.slice(0);
  8537. getParsingFlags(config).meridiem = config._meridiem;
  8538. // handle meridiem
  8539. config._a[HOUR] = meridiemFixWrap(
  8540. config._locale,
  8541. config._a[HOUR],
  8542. config._meridiem
  8543. );
  8544. // handle era
  8545. era = getParsingFlags(config).era;
  8546. if (era !== null) {
  8547. config._a[YEAR] = config._locale.erasConvertYear(era, config._a[YEAR]);
  8548. }
  8549. configFromArray(config);
  8550. checkOverflow(config);
  8551. }
  8552. function meridiemFixWrap(locale, hour, meridiem) {
  8553. var isPm;
  8554. if (meridiem == null) {
  8555. // nothing to do
  8556. return hour;
  8557. }
  8558. if (locale.meridiemHour != null) {
  8559. return locale.meridiemHour(hour, meridiem);
  8560. } else if (locale.isPM != null) {
  8561. // Fallback
  8562. isPm = locale.isPM(meridiem);
  8563. if (isPm && hour < 12) {
  8564. hour += 12;
  8565. }
  8566. if (!isPm && hour === 12) {
  8567. hour = 0;
  8568. }
  8569. return hour;
  8570. } else {
  8571. // this is not supposed to happen
  8572. return hour;
  8573. }
  8574. }
  8575. // date from string and array of format strings
  8576. function configFromStringAndArray(config) {
  8577. var tempConfig,
  8578. bestMoment,
  8579. scoreToBeat,
  8580. i,
  8581. currentScore,
  8582. validFormatFound,
  8583. bestFormatIsValid = false;
  8584. if (config._f.length === 0) {
  8585. getParsingFlags(config).invalidFormat = true;
  8586. config._d = new Date(NaN);
  8587. return;
  8588. }
  8589. for (i = 0; i < config._f.length; i++) {
  8590. currentScore = 0;
  8591. validFormatFound = false;
  8592. tempConfig = copyConfig({}, config);
  8593. if (config._useUTC != null) {
  8594. tempConfig._useUTC = config._useUTC;
  8595. }
  8596. tempConfig._f = config._f[i];
  8597. configFromStringAndFormat(tempConfig);
  8598. if (isValid(tempConfig)) {
  8599. validFormatFound = true;
  8600. }
  8601. // if there is any input that was not parsed add a penalty for that format
  8602. currentScore += getParsingFlags(tempConfig).charsLeftOver;
  8603. //or tokens
  8604. currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10;
  8605. getParsingFlags(tempConfig).score = currentScore;
  8606. if (!bestFormatIsValid) {
  8607. if (
  8608. scoreToBeat == null ||
  8609. currentScore < scoreToBeat ||
  8610. validFormatFound
  8611. ) {
  8612. scoreToBeat = currentScore;
  8613. bestMoment = tempConfig;
  8614. if (validFormatFound) {
  8615. bestFormatIsValid = true;
  8616. }
  8617. }
  8618. } else {
  8619. if (currentScore < scoreToBeat) {
  8620. scoreToBeat = currentScore;
  8621. bestMoment = tempConfig;
  8622. }
  8623. }
  8624. }
  8625. extend(config, bestMoment || tempConfig);
  8626. }
  8627. function configFromObject(config) {
  8628. if (config._d) {
  8629. return;
  8630. }
  8631. var i = normalizeObjectUnits(config._i),
  8632. dayOrDate = i.day === undefined ? i.date : i.day;
  8633. config._a = map(
  8634. [i.year, i.month, dayOrDate, i.hour, i.minute, i.second, i.millisecond],
  8635. function (obj) {
  8636. return obj && parseInt(obj, 10);
  8637. }
  8638. );
  8639. configFromArray(config);
  8640. }
  8641. function createFromConfig(config) {
  8642. var res = new Moment(checkOverflow(prepareConfig(config)));
  8643. if (res._nextDay) {
  8644. // Adding is smart enough around DST
  8645. res.add(1, 'd');
  8646. res._nextDay = undefined;
  8647. }
  8648. return res;
  8649. }
  8650. function prepareConfig(config) {
  8651. var input = config._i,
  8652. format = config._f;
  8653. config._locale = config._locale || getLocale(config._l);
  8654. if (input === null || (format === undefined && input === '')) {
  8655. return createInvalid({ nullInput: true });
  8656. }
  8657. if (typeof input === 'string') {
  8658. config._i = input = config._locale.preparse(input);
  8659. }
  8660. if (isMoment(input)) {
  8661. return new Moment(checkOverflow(input));
  8662. } else if (isDate(input)) {
  8663. config._d = input;
  8664. } else if (isArray(format)) {
  8665. configFromStringAndArray(config);
  8666. } else if (format) {
  8667. configFromStringAndFormat(config);
  8668. } else {
  8669. configFromInput(config);
  8670. }
  8671. if (!isValid(config)) {
  8672. config._d = null;
  8673. }
  8674. return config;
  8675. }
  8676. function configFromInput(config) {
  8677. var input = config._i;
  8678. if (isUndefined(input)) {
  8679. config._d = new Date(hooks.now());
  8680. } else if (isDate(input)) {
  8681. config._d = new Date(input.valueOf());
  8682. } else if (typeof input === 'string') {
  8683. configFromString(config);
  8684. } else if (isArray(input)) {
  8685. config._a = map(input.slice(0), function (obj) {
  8686. return parseInt(obj, 10);
  8687. });
  8688. configFromArray(config);
  8689. } else if (isObject(input)) {
  8690. configFromObject(config);
  8691. } else if (isNumber(input)) {
  8692. // from milliseconds
  8693. config._d = new Date(input);
  8694. } else {
  8695. hooks.createFromInputFallback(config);
  8696. }
  8697. }
  8698. function createLocalOrUTC(input, format, locale, strict, isUTC) {
  8699. var c = {};
  8700. if (format === true || format === false) {
  8701. strict = format;
  8702. format = undefined;
  8703. }
  8704. if (locale === true || locale === false) {
  8705. strict = locale;
  8706. locale = undefined;
  8707. }
  8708. if (
  8709. (isObject(input) && isObjectEmpty(input)) ||
  8710. (isArray(input) && input.length === 0)
  8711. ) {
  8712. input = undefined;
  8713. }
  8714. // object construction must be done this way.
  8715. // https://github.com/moment/moment/issues/1423
  8716. c._isAMomentObject = true;
  8717. c._useUTC = c._isUTC = isUTC;
  8718. c._l = locale;
  8719. c._i = input;
  8720. c._f = format;
  8721. c._strict = strict;
  8722. return createFromConfig(c);
  8723. }
  8724. function createLocal(input, format, locale, strict) {
  8725. return createLocalOrUTC(input, format, locale, strict, false);
  8726. }
  8727. var prototypeMin = deprecate(
  8728. 'moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/',
  8729. function () {
  8730. var other = createLocal.apply(null, arguments);
  8731. if (this.isValid() && other.isValid()) {
  8732. return other < this ? this : other;
  8733. } else {
  8734. return createInvalid();
  8735. }
  8736. }
  8737. ),
  8738. prototypeMax = deprecate(
  8739. 'moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/',
  8740. function () {
  8741. var other = createLocal.apply(null, arguments);
  8742. if (this.isValid() && other.isValid()) {
  8743. return other > this ? this : other;
  8744. } else {
  8745. return createInvalid();
  8746. }
  8747. }
  8748. );
  8749. // Pick a moment m from moments so that m[fn](other) is true for all
  8750. // other. This relies on the function fn to be transitive.
  8751. //
  8752. // moments should either be an array of moment objects or an array, whose
  8753. // first element is an array of moment objects.
  8754. function pickBy(fn, moments) {
  8755. var res, i;
  8756. if (moments.length === 1 && isArray(moments[0])) {
  8757. moments = moments[0];
  8758. }
  8759. if (!moments.length) {
  8760. return createLocal();
  8761. }
  8762. res = moments[0];
  8763. for (i = 1; i < moments.length; ++i) {
  8764. if (!moments[i].isValid() || moments[i][fn](res)) {
  8765. res = moments[i];
  8766. }
  8767. }
  8768. return res;
  8769. }
  8770. // TODO: Use [].sort instead?
  8771. function min() {
  8772. var args = [].slice.call(arguments, 0);
  8773. return pickBy('isBefore', args);
  8774. }
  8775. function max() {
  8776. var args = [].slice.call(arguments, 0);
  8777. return pickBy('isAfter', args);
  8778. }
  8779. var now = function () {
  8780. return Date.now ? Date.now() : +new Date();
  8781. };
  8782. var ordering = [
  8783. 'year',
  8784. 'quarter',
  8785. 'month',
  8786. 'week',
  8787. 'day',
  8788. 'hour',
  8789. 'minute',
  8790. 'second',
  8791. 'millisecond',
  8792. ];
  8793. function isDurationValid(m) {
  8794. var key,
  8795. unitHasDecimal = false,
  8796. i;
  8797. for (key in m) {
  8798. if (
  8799. hasOwnProp(m, key) &&
  8800. !(
  8801. indexOf.call(ordering, key) !== -1 &&
  8802. (m[key] == null || !isNaN(m[key]))
  8803. )
  8804. ) {
  8805. return false;
  8806. }
  8807. }
  8808. for (i = 0; i < ordering.length; ++i) {
  8809. if (m[ordering[i]]) {
  8810. if (unitHasDecimal) {
  8811. return false; // only allow non-integers for smallest unit
  8812. }
  8813. if (parseFloat(m[ordering[i]]) !== toInt(m[ordering[i]])) {
  8814. unitHasDecimal = true;
  8815. }
  8816. }
  8817. }
  8818. return true;
  8819. }
  8820. function isValid$1() {
  8821. return this._isValid;
  8822. }
  8823. function createInvalid$1() {
  8824. return createDuration(NaN);
  8825. }
  8826. function Duration(duration) {
  8827. var normalizedInput = normalizeObjectUnits(duration),
  8828. years = normalizedInput.year || 0,
  8829. quarters = normalizedInput.quarter || 0,
  8830. months = normalizedInput.month || 0,
  8831. weeks = normalizedInput.week || normalizedInput.isoWeek || 0,
  8832. days = normalizedInput.day || 0,
  8833. hours = normalizedInput.hour || 0,
  8834. minutes = normalizedInput.minute || 0,
  8835. seconds = normalizedInput.second || 0,
  8836. milliseconds = normalizedInput.millisecond || 0;
  8837. this._isValid = isDurationValid(normalizedInput);
  8838. // representation for dateAddRemove
  8839. this._milliseconds =
  8840. +milliseconds +
  8841. seconds * 1e3 + // 1000
  8842. minutes * 6e4 + // 1000 * 60
  8843. hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978
  8844. // Because of dateAddRemove treats 24 hours as different from a
  8845. // day when working around DST, we need to store them separately
  8846. this._days = +days + weeks * 7;
  8847. // It is impossible to translate months into days without knowing
  8848. // which months you are are talking about, so we have to store
  8849. // it separately.
  8850. this._months = +months + quarters * 3 + years * 12;
  8851. this._data = {};
  8852. this._locale = getLocale();
  8853. this._bubble();
  8854. }
  8855. function isDuration(obj) {
  8856. return obj instanceof Duration;
  8857. }
  8858. function absRound(number) {
  8859. if (number < 0) {
  8860. return Math.round(-1 * number) * -1;
  8861. } else {
  8862. return Math.round(number);
  8863. }
  8864. }
  8865. // compare two arrays, return the number of differences
  8866. function compareArrays(array1, array2, dontConvert) {
  8867. var len = Math.min(array1.length, array2.length),
  8868. lengthDiff = Math.abs(array1.length - array2.length),
  8869. diffs = 0,
  8870. i;
  8871. for (i = 0; i < len; i++) {
  8872. if (
  8873. (dontConvert && array1[i] !== array2[i]) ||
  8874. (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))
  8875. ) {
  8876. diffs++;
  8877. }
  8878. }
  8879. return diffs + lengthDiff;
  8880. }
  8881. // FORMATTING
  8882. function offset(token, separator) {
  8883. addFormatToken(token, 0, 0, function () {
  8884. var offset = this.utcOffset(),
  8885. sign = '+';
  8886. if (offset < 0) {
  8887. offset = -offset;
  8888. sign = '-';
  8889. }
  8890. return (
  8891. sign +
  8892. zeroFill(~~(offset / 60), 2) +
  8893. separator +
  8894. zeroFill(~~offset % 60, 2)
  8895. );
  8896. });
  8897. }
  8898. offset('Z', ':');
  8899. offset('ZZ', '');
  8900. // PARSING
  8901. addRegexToken('Z', matchShortOffset);
  8902. addRegexToken('ZZ', matchShortOffset);
  8903. addParseToken(['Z', 'ZZ'], function (input, array, config) {
  8904. config._useUTC = true;
  8905. config._tzm = offsetFromString(matchShortOffset, input);
  8906. });
  8907. // HELPERS
  8908. // timezone chunker
  8909. // '+10:00' > ['10', '00']
  8910. // '-1530' > ['-15', '30']
  8911. var chunkOffset = /([\+\-]|\d\d)/gi;
  8912. function offsetFromString(matcher, string) {
  8913. var matches = (string || '').match(matcher),
  8914. chunk,
  8915. parts,
  8916. minutes;
  8917. if (matches === null) {
  8918. return null;
  8919. }
  8920. chunk = matches[matches.length - 1] || [];
  8921. parts = (chunk + '').match(chunkOffset) || ['-', 0, 0];
  8922. minutes = +(parts[1] * 60) + toInt(parts[2]);
  8923. return minutes === 0 ? 0 : parts[0] === '+' ? minutes : -minutes;
  8924. }
  8925. // Return a moment from input, that is local/utc/zone equivalent to model.
  8926. function cloneWithOffset(input, model) {
  8927. var res, diff;
  8928. if (model._isUTC) {
  8929. res = model.clone();
  8930. diff =
  8931. (isMoment(input) || isDate(input)
  8932. ? input.valueOf()
  8933. : createLocal(input).valueOf()) - res.valueOf();
  8934. // Use low-level api, because this fn is low-level api.
  8935. res._d.setTime(res._d.valueOf() + diff);
  8936. hooks.updateOffset(res, false);
  8937. return res;
  8938. } else {
  8939. return createLocal(input).local();
  8940. }
  8941. }
  8942. function getDateOffset(m) {
  8943. // On Firefox.24 Date#getTimezoneOffset returns a floating point.
  8944. // https://github.com/moment/moment/pull/1871
  8945. return -Math.round(m._d.getTimezoneOffset());
  8946. }
  8947. // HOOKS
  8948. // This function will be called whenever a moment is mutated.
  8949. // It is intended to keep the offset in sync with the timezone.
  8950. hooks.updateOffset = function () {};
  8951. // MOMENTS
  8952. // keepLocalTime = true means only change the timezone, without
  8953. // affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]-->
  8954. // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset
  8955. // +0200, so we adjust the time as needed, to be valid.
  8956. //
  8957. // Keeping the time actually adds/subtracts (one hour)
  8958. // from the actual represented time. That is why we call updateOffset
  8959. // a second time. In case it wants us to change the offset again
  8960. // _changeInProgress == true case, then we have to adjust, because
  8961. // there is no such time in the given timezone.
  8962. function getSetOffset(input, keepLocalTime, keepMinutes) {
  8963. var offset = this._offset || 0,
  8964. localAdjust;
  8965. if (!this.isValid()) {
  8966. return input != null ? this : NaN;
  8967. }
  8968. if (input != null) {
  8969. if (typeof input === 'string') {
  8970. input = offsetFromString(matchShortOffset, input);
  8971. if (input === null) {
  8972. return this;
  8973. }
  8974. } else if (Math.abs(input) < 16 && !keepMinutes) {
  8975. input = input * 60;
  8976. }
  8977. if (!this._isUTC && keepLocalTime) {
  8978. localAdjust = getDateOffset(this);
  8979. }
  8980. this._offset = input;
  8981. this._isUTC = true;
  8982. if (localAdjust != null) {
  8983. this.add(localAdjust, 'm');
  8984. }
  8985. if (offset !== input) {
  8986. if (!keepLocalTime || this._changeInProgress) {
  8987. addSubtract(
  8988. this,
  8989. createDuration(input - offset, 'm'),
  8990. 1,
  8991. false
  8992. );
  8993. } else if (!this._changeInProgress) {
  8994. this._changeInProgress = true;
  8995. hooks.updateOffset(this, true);
  8996. this._changeInProgress = null;
  8997. }
  8998. }
  8999. return this;
  9000. } else {
  9001. return this._isUTC ? offset : getDateOffset(this);
  9002. }
  9003. }
  9004. function getSetZone(input, keepLocalTime) {
  9005. if (input != null) {
  9006. if (typeof input !== 'string') {
  9007. input = -input;
  9008. }
  9009. this.utcOffset(input, keepLocalTime);
  9010. return this;
  9011. } else {
  9012. return -this.utcOffset();
  9013. }
  9014. }
  9015. function setOffsetToUTC(keepLocalTime) {
  9016. return this.utcOffset(0, keepLocalTime);
  9017. }
  9018. function setOffsetToLocal(keepLocalTime) {
  9019. if (this._isUTC) {
  9020. this.utcOffset(0, keepLocalTime);
  9021. this._isUTC = false;
  9022. if (keepLocalTime) {
  9023. this.subtract(getDateOffset(this), 'm');
  9024. }
  9025. }
  9026. return this;
  9027. }
  9028. function setOffsetToParsedOffset() {
  9029. if (this._tzm != null) {
  9030. this.utcOffset(this._tzm, false, true);
  9031. } else if (typeof this._i === 'string') {
  9032. var tZone = offsetFromString(matchOffset, this._i);
  9033. if (tZone != null) {
  9034. this.utcOffset(tZone);
  9035. } else {
  9036. this.utcOffset(0, true);
  9037. }
  9038. }
  9039. return this;
  9040. }
  9041. function hasAlignedHourOffset(input) {
  9042. if (!this.isValid()) {
  9043. return false;
  9044. }
  9045. input = input ? createLocal(input).utcOffset() : 0;
  9046. return (this.utcOffset() - input) % 60 === 0;
  9047. }
  9048. function isDaylightSavingTime() {
  9049. return (
  9050. this.utcOffset() > this.clone().month(0).utcOffset() ||
  9051. this.utcOffset() > this.clone().month(5).utcOffset()
  9052. );
  9053. }
  9054. function isDaylightSavingTimeShifted() {
  9055. if (!isUndefined(this._isDSTShifted)) {
  9056. return this._isDSTShifted;
  9057. }
  9058. var c = {},
  9059. other;
  9060. copyConfig(c, this);
  9061. c = prepareConfig(c);
  9062. if (c._a) {
  9063. other = c._isUTC ? createUTC(c._a) : createLocal(c._a);
  9064. this._isDSTShifted =
  9065. this.isValid() && compareArrays(c._a, other.toArray()) > 0;
  9066. } else {
  9067. this._isDSTShifted = false;
  9068. }
  9069. return this._isDSTShifted;
  9070. }
  9071. function isLocal() {
  9072. return this.isValid() ? !this._isUTC : false;
  9073. }
  9074. function isUtcOffset() {
  9075. return this.isValid() ? this._isUTC : false;
  9076. }
  9077. function isUtc() {
  9078. return this.isValid() ? this._isUTC && this._offset === 0 : false;
  9079. }
  9080. // ASP.NET json date format regex
  9081. var aspNetRegex = /^(-|\+)?(?:(\d*)[. ])?(\d+):(\d+)(?::(\d+)(\.\d*)?)?$/,
  9082. // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
  9083. // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
  9084. // and further modified to allow for strings containing both week and day
  9085. isoRegex = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;
  9086. function createDuration(input, key) {
  9087. var duration = input,
  9088. // matching against regexp is expensive, do it on demand
  9089. match = null,
  9090. sign,
  9091. ret,
  9092. diffRes;
  9093. if (isDuration(input)) {
  9094. duration = {
  9095. ms: input._milliseconds,
  9096. d: input._days,
  9097. M: input._months,
  9098. };
  9099. } else if (isNumber(input) || !isNaN(+input)) {
  9100. duration = {};
  9101. if (key) {
  9102. duration[key] = +input;
  9103. } else {
  9104. duration.milliseconds = +input;
  9105. }
  9106. } else if ((match = aspNetRegex.exec(input))) {
  9107. sign = match[1] === '-' ? -1 : 1;
  9108. duration = {
  9109. y: 0,
  9110. d: toInt(match[DATE]) * sign,
  9111. h: toInt(match[HOUR]) * sign,
  9112. m: toInt(match[MINUTE]) * sign,
  9113. s: toInt(match[SECOND]) * sign,
  9114. ms: toInt(absRound(match[MILLISECOND] * 1000)) * sign, // the millisecond decimal point is included in the match
  9115. };
  9116. } else if ((match = isoRegex.exec(input))) {
  9117. sign = match[1] === '-' ? -1 : 1;
  9118. duration = {
  9119. y: parseIso(match[2], sign),
  9120. M: parseIso(match[3], sign),
  9121. w: parseIso(match[4], sign),
  9122. d: parseIso(match[5], sign),
  9123. h: parseIso(match[6], sign),
  9124. m: parseIso(match[7], sign),
  9125. s: parseIso(match[8], sign),
  9126. };
  9127. } else if (duration == null) {
  9128. // checks for null or undefined
  9129. duration = {};
  9130. } else if (
  9131. typeof duration === 'object' &&
  9132. ('from' in duration || 'to' in duration)
  9133. ) {
  9134. diffRes = momentsDifference(
  9135. createLocal(duration.from),
  9136. createLocal(duration.to)
  9137. );
  9138. duration = {};
  9139. duration.ms = diffRes.milliseconds;
  9140. duration.M = diffRes.months;
  9141. }
  9142. ret = new Duration(duration);
  9143. if (isDuration(input) && hasOwnProp(input, '_locale')) {
  9144. ret._locale = input._locale;
  9145. }
  9146. if (isDuration(input) && hasOwnProp(input, '_isValid')) {
  9147. ret._isValid = input._isValid;
  9148. }
  9149. return ret;
  9150. }
  9151. createDuration.fn = Duration.prototype;
  9152. createDuration.invalid = createInvalid$1;
  9153. function parseIso(inp, sign) {
  9154. // We'd normally use ~~inp for this, but unfortunately it also
  9155. // converts floats to ints.
  9156. // inp may be undefined, so careful calling replace on it.
  9157. var res = inp && parseFloat(inp.replace(',', '.'));
  9158. // apply sign while we're at it
  9159. return (isNaN(res) ? 0 : res) * sign;
  9160. }
  9161. function positiveMomentsDifference(base, other) {
  9162. var res = {};
  9163. res.months =
  9164. other.month() - base.month() + (other.year() - base.year()) * 12;
  9165. if (base.clone().add(res.months, 'M').isAfter(other)) {
  9166. --res.months;
  9167. }
  9168. res.milliseconds = +other - +base.clone().add(res.months, 'M');
  9169. return res;
  9170. }
  9171. function momentsDifference(base, other) {
  9172. var res;
  9173. if (!(base.isValid() && other.isValid())) {
  9174. return { milliseconds: 0, months: 0 };
  9175. }
  9176. other = cloneWithOffset(other, base);
  9177. if (base.isBefore(other)) {
  9178. res = positiveMomentsDifference(base, other);
  9179. } else {
  9180. res = positiveMomentsDifference(other, base);
  9181. res.milliseconds = -res.milliseconds;
  9182. res.months = -res.months;
  9183. }
  9184. return res;
  9185. }
  9186. // TODO: remove 'name' arg after deprecation is removed
  9187. function createAdder(direction, name) {
  9188. return function (val, period) {
  9189. var dur, tmp;
  9190. //invert the arguments, but complain about it
  9191. if (period !== null && !isNaN(+period)) {
  9192. deprecateSimple(
  9193. name,
  9194. 'moment().' +
  9195. name +
  9196. '(period, number) is deprecated. Please use moment().' +
  9197. name +
  9198. '(number, period). ' +
  9199. 'See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.'
  9200. );
  9201. tmp = val;
  9202. val = period;
  9203. period = tmp;
  9204. }
  9205. dur = createDuration(val, period);
  9206. addSubtract(this, dur, direction);
  9207. return this;
  9208. };
  9209. }
  9210. function addSubtract(mom, duration, isAdding, updateOffset) {
  9211. var milliseconds = duration._milliseconds,
  9212. days = absRound(duration._days),
  9213. months = absRound(duration._months);
  9214. if (!mom.isValid()) {
  9215. // No op
  9216. return;
  9217. }
  9218. updateOffset = updateOffset == null ? true : updateOffset;
  9219. if (months) {
  9220. setMonth(mom, get(mom, 'Month') + months * isAdding);
  9221. }
  9222. if (days) {
  9223. set$1(mom, 'Date', get(mom, 'Date') + days * isAdding);
  9224. }
  9225. if (milliseconds) {
  9226. mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding);
  9227. }
  9228. if (updateOffset) {
  9229. hooks.updateOffset(mom, days || months);
  9230. }
  9231. }
  9232. var add = createAdder(1, 'add'),
  9233. subtract = createAdder(-1, 'subtract');
  9234. function isString(input) {
  9235. return typeof input === 'string' || input instanceof String;
  9236. }
  9237. // type MomentInput = Moment | Date | string | number | (number | string)[] | MomentInputObject | void; // null | undefined
  9238. function isMomentInput(input) {
  9239. return (
  9240. isMoment(input) ||
  9241. isDate(input) ||
  9242. isString(input) ||
  9243. isNumber(input) ||
  9244. isNumberOrStringArray(input) ||
  9245. isMomentInputObject(input) ||
  9246. input === null ||
  9247. input === undefined
  9248. );
  9249. }
  9250. function isMomentInputObject(input) {
  9251. var objectTest = isObject(input) && !isObjectEmpty(input),
  9252. propertyTest = false,
  9253. properties = [
  9254. 'years',
  9255. 'year',
  9256. 'y',
  9257. 'months',
  9258. 'month',
  9259. 'M',
  9260. 'days',
  9261. 'day',
  9262. 'd',
  9263. 'dates',
  9264. 'date',
  9265. 'D',
  9266. 'hours',
  9267. 'hour',
  9268. 'h',
  9269. 'minutes',
  9270. 'minute',
  9271. 'm',
  9272. 'seconds',
  9273. 'second',
  9274. 's',
  9275. 'milliseconds',
  9276. 'millisecond',
  9277. 'ms',
  9278. ],
  9279. i,
  9280. property;
  9281. for (i = 0; i < properties.length; i += 1) {
  9282. property = properties[i];
  9283. propertyTest = propertyTest || hasOwnProp(input, property);
  9284. }
  9285. return objectTest && propertyTest;
  9286. }
  9287. function isNumberOrStringArray(input) {
  9288. var arrayTest = isArray(input),
  9289. dataTypeTest = false;
  9290. if (arrayTest) {
  9291. dataTypeTest =
  9292. input.filter(function (item) {
  9293. return !isNumber(item) && isString(input);
  9294. }).length === 0;
  9295. }
  9296. return arrayTest && dataTypeTest;
  9297. }
  9298. function isCalendarSpec(input) {
  9299. var objectTest = isObject(input) && !isObjectEmpty(input),
  9300. propertyTest = false,
  9301. properties = [
  9302. 'sameDay',
  9303. 'nextDay',
  9304. 'lastDay',
  9305. 'nextWeek',
  9306. 'lastWeek',
  9307. 'sameElse',
  9308. ],
  9309. i,
  9310. property;
  9311. for (i = 0; i < properties.length; i += 1) {
  9312. property = properties[i];
  9313. propertyTest = propertyTest || hasOwnProp(input, property);
  9314. }
  9315. return objectTest && propertyTest;
  9316. }
  9317. function getCalendarFormat(myMoment, now) {
  9318. var diff = myMoment.diff(now, 'days', true);
  9319. return diff < -6
  9320. ? 'sameElse'
  9321. : diff < -1
  9322. ? 'lastWeek'
  9323. : diff < 0
  9324. ? 'lastDay'
  9325. : diff < 1
  9326. ? 'sameDay'
  9327. : diff < 2
  9328. ? 'nextDay'
  9329. : diff < 7
  9330. ? 'nextWeek'
  9331. : 'sameElse';
  9332. }
  9333. function calendar$1(time, formats) {
  9334. // Support for single parameter, formats only overload to the calendar function
  9335. if (arguments.length === 1) {
  9336. if (!arguments[0]) {
  9337. time = undefined;
  9338. formats = undefined;
  9339. } else if (isMomentInput(arguments[0])) {
  9340. time = arguments[0];
  9341. formats = undefined;
  9342. } else if (isCalendarSpec(arguments[0])) {
  9343. formats = arguments[0];
  9344. time = undefined;
  9345. }
  9346. }
  9347. // We want to compare the start of today, vs this.
  9348. // Getting start-of-today depends on whether we're local/utc/offset or not.
  9349. var now = time || createLocal(),
  9350. sod = cloneWithOffset(now, this).startOf('day'),
  9351. format = hooks.calendarFormat(this, sod) || 'sameElse',
  9352. output =
  9353. formats &&
  9354. (isFunction(formats[format])
  9355. ? formats[format].call(this, now)
  9356. : formats[format]);
  9357. return this.format(
  9358. output || this.localeData().calendar(format, this, createLocal(now))
  9359. );
  9360. }
  9361. function clone() {
  9362. return new Moment(this);
  9363. }
  9364. function isAfter(input, units) {
  9365. var localInput = isMoment(input) ? input : createLocal(input);
  9366. if (!(this.isValid() && localInput.isValid())) {
  9367. return false;
  9368. }
  9369. units = normalizeUnits(units) || 'millisecond';
  9370. if (units === 'millisecond') {
  9371. return this.valueOf() > localInput.valueOf();
  9372. } else {
  9373. return localInput.valueOf() < this.clone().startOf(units).valueOf();
  9374. }
  9375. }
  9376. function isBefore(input, units) {
  9377. var localInput = isMoment(input) ? input : createLocal(input);
  9378. if (!(this.isValid() && localInput.isValid())) {
  9379. return false;
  9380. }
  9381. units = normalizeUnits(units) || 'millisecond';
  9382. if (units === 'millisecond') {
  9383. return this.valueOf() < localInput.valueOf();
  9384. } else {
  9385. return this.clone().endOf(units).valueOf() < localInput.valueOf();
  9386. }
  9387. }
  9388. function isBetween(from, to, units, inclusivity) {
  9389. var localFrom = isMoment(from) ? from : createLocal(from),
  9390. localTo = isMoment(to) ? to : createLocal(to);
  9391. if (!(this.isValid() && localFrom.isValid() && localTo.isValid())) {
  9392. return false;
  9393. }
  9394. inclusivity = inclusivity || '()';
  9395. return (
  9396. (inclusivity[0] === '('
  9397. ? this.isAfter(localFrom, units)
  9398. : !this.isBefore(localFrom, units)) &&
  9399. (inclusivity[1] === ')'
  9400. ? this.isBefore(localTo, units)
  9401. : !this.isAfter(localTo, units))
  9402. );
  9403. }
  9404. function isSame(input, units) {
  9405. var localInput = isMoment(input) ? input : createLocal(input),
  9406. inputMs;
  9407. if (!(this.isValid() && localInput.isValid())) {
  9408. return false;
  9409. }
  9410. units = normalizeUnits(units) || 'millisecond';
  9411. if (units === 'millisecond') {
  9412. return this.valueOf() === localInput.valueOf();
  9413. } else {
  9414. inputMs = localInput.valueOf();
  9415. return (
  9416. this.clone().startOf(units).valueOf() <= inputMs &&
  9417. inputMs <= this.clone().endOf(units).valueOf()
  9418. );
  9419. }
  9420. }
  9421. function isSameOrAfter(input, units) {
  9422. return this.isSame(input, units) || this.isAfter(input, units);
  9423. }
  9424. function isSameOrBefore(input, units) {
  9425. return this.isSame(input, units) || this.isBefore(input, units);
  9426. }
  9427. function diff(input, units, asFloat) {
  9428. var that, zoneDelta, output;
  9429. if (!this.isValid()) {
  9430. return NaN;
  9431. }
  9432. that = cloneWithOffset(input, this);
  9433. if (!that.isValid()) {
  9434. return NaN;
  9435. }
  9436. zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4;
  9437. units = normalizeUnits(units);
  9438. switch (units) {
  9439. case 'year':
  9440. output = monthDiff(this, that) / 12;
  9441. break;
  9442. case 'month':
  9443. output = monthDiff(this, that);
  9444. break;
  9445. case 'quarter':
  9446. output = monthDiff(this, that) / 3;
  9447. break;
  9448. case 'second':
  9449. output = (this - that) / 1e3;
  9450. break; // 1000
  9451. case 'minute':
  9452. output = (this - that) / 6e4;
  9453. break; // 1000 * 60
  9454. case 'hour':
  9455. output = (this - that) / 36e5;
  9456. break; // 1000 * 60 * 60
  9457. case 'day':
  9458. output = (this - that - zoneDelta) / 864e5;
  9459. break; // 1000 * 60 * 60 * 24, negate dst
  9460. case 'week':
  9461. output = (this - that - zoneDelta) / 6048e5;
  9462. break; // 1000 * 60 * 60 * 24 * 7, negate dst
  9463. default:
  9464. output = this - that;
  9465. }
  9466. return asFloat ? output : absFloor(output);
  9467. }
  9468. function monthDiff(a, b) {
  9469. if (a.date() < b.date()) {
  9470. // end-of-month calculations work correct when the start month has more
  9471. // days than the end month.
  9472. return -monthDiff(b, a);
  9473. }
  9474. // difference in months
  9475. var wholeMonthDiff = (b.year() - a.year()) * 12 + (b.month() - a.month()),
  9476. // b is in (anchor - 1 month, anchor + 1 month)
  9477. anchor = a.clone().add(wholeMonthDiff, 'months'),
  9478. anchor2,
  9479. adjust;
  9480. if (b - anchor < 0) {
  9481. anchor2 = a.clone().add(wholeMonthDiff - 1, 'months');
  9482. // linear across the month
  9483. adjust = (b - anchor) / (anchor - anchor2);
  9484. } else {
  9485. anchor2 = a.clone().add(wholeMonthDiff + 1, 'months');
  9486. // linear across the month
  9487. adjust = (b - anchor) / (anchor2 - anchor);
  9488. }
  9489. //check for negative zero, return zero if negative zero
  9490. return -(wholeMonthDiff + adjust) || 0;
  9491. }
  9492. hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ';
  9493. hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]';
  9494. function toString() {
  9495. return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ');
  9496. }
  9497. function toISOString(keepOffset) {
  9498. if (!this.isValid()) {
  9499. return null;
  9500. }
  9501. var utc = keepOffset !== true,
  9502. m = utc ? this.clone().utc() : this;
  9503. if (m.year() < 0 || m.year() > 9999) {
  9504. return formatMoment(
  9505. m,
  9506. utc
  9507. ? 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]'
  9508. : 'YYYYYY-MM-DD[T]HH:mm:ss.SSSZ'
  9509. );
  9510. }
  9511. if (isFunction(Date.prototype.toISOString)) {
  9512. // native implementation is ~50x faster, use it when we can
  9513. if (utc) {
  9514. return this.toDate().toISOString();
  9515. } else {
  9516. return new Date(this.valueOf() + this.utcOffset() * 60 * 1000)
  9517. .toISOString()
  9518. .replace('Z', formatMoment(m, 'Z'));
  9519. }
  9520. }
  9521. return formatMoment(
  9522. m,
  9523. utc ? 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYY-MM-DD[T]HH:mm:ss.SSSZ'
  9524. );
  9525. }
  9526. /**
  9527. * Return a human readable representation of a moment that can
  9528. * also be evaluated to get a new moment which is the same
  9529. *
  9530. * @link https://nodejs.org/dist/latest/docs/api/util.html#util_custom_inspect_function_on_objects
  9531. */
  9532. function inspect() {
  9533. if (!this.isValid()) {
  9534. return 'moment.invalid(/* ' + this._i + ' */)';
  9535. }
  9536. var func = 'moment',
  9537. zone = '',
  9538. prefix,
  9539. year,
  9540. datetime,
  9541. suffix;
  9542. if (!this.isLocal()) {
  9543. func = this.utcOffset() === 0 ? 'moment.utc' : 'moment.parseZone';
  9544. zone = 'Z';
  9545. }
  9546. prefix = '[' + func + '("]';
  9547. year = 0 <= this.year() && this.year() <= 9999 ? 'YYYY' : 'YYYYYY';
  9548. datetime = '-MM-DD[T]HH:mm:ss.SSS';
  9549. suffix = zone + '[")]';
  9550. return this.format(prefix + year + datetime + suffix);
  9551. }
  9552. function format(inputString) {
  9553. if (!inputString) {
  9554. inputString = this.isUtc()
  9555. ? hooks.defaultFormatUtc
  9556. : hooks.defaultFormat;
  9557. }
  9558. var output = formatMoment(this, inputString);
  9559. return this.localeData().postformat(output);
  9560. }
  9561. function from(time, withoutSuffix) {
  9562. if (
  9563. this.isValid() &&
  9564. ((isMoment(time) && time.isValid()) || createLocal(time).isValid())
  9565. ) {
  9566. return createDuration({ to: this, from: time })
  9567. .locale(this.locale())
  9568. .humanize(!withoutSuffix);
  9569. } else {
  9570. return this.localeData().invalidDate();
  9571. }
  9572. }
  9573. function fromNow(withoutSuffix) {
  9574. return this.from(createLocal(), withoutSuffix);
  9575. }
  9576. function to(time, withoutSuffix) {
  9577. if (
  9578. this.isValid() &&
  9579. ((isMoment(time) && time.isValid()) || createLocal(time).isValid())
  9580. ) {
  9581. return createDuration({ from: this, to: time })
  9582. .locale(this.locale())
  9583. .humanize(!withoutSuffix);
  9584. } else {
  9585. return this.localeData().invalidDate();
  9586. }
  9587. }
  9588. function toNow(withoutSuffix) {
  9589. return this.to(createLocal(), withoutSuffix);
  9590. }
  9591. // If passed a locale key, it will set the locale for this
  9592. // instance. Otherwise, it will return the locale configuration
  9593. // variables for this instance.
  9594. function locale(key) {
  9595. var newLocaleData;
  9596. if (key === undefined) {
  9597. return this._locale._abbr;
  9598. } else {
  9599. newLocaleData = getLocale(key);
  9600. if (newLocaleData != null) {
  9601. this._locale = newLocaleData;
  9602. }
  9603. return this;
  9604. }
  9605. }
  9606. var lang = deprecate(
  9607. 'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.',
  9608. function (key) {
  9609. if (key === undefined) {
  9610. return this.localeData();
  9611. } else {
  9612. return this.locale(key);
  9613. }
  9614. }
  9615. );
  9616. function localeData() {
  9617. return this._locale;
  9618. }
  9619. var MS_PER_SECOND = 1000,
  9620. MS_PER_MINUTE = 60 * MS_PER_SECOND,
  9621. MS_PER_HOUR = 60 * MS_PER_MINUTE,
  9622. MS_PER_400_YEARS = (365 * 400 + 97) * 24 * MS_PER_HOUR;
  9623. // actual modulo - handles negative numbers (for dates before 1970):
  9624. function mod$1(dividend, divisor) {
  9625. return ((dividend % divisor) + divisor) % divisor;
  9626. }
  9627. function localStartOfDate(y, m, d) {
  9628. // the date constructor remaps years 0-99 to 1900-1999
  9629. if (y < 100 && y >= 0) {
  9630. // preserve leap years using a full 400 year cycle, then reset
  9631. return new Date(y + 400, m, d) - MS_PER_400_YEARS;
  9632. } else {
  9633. return new Date(y, m, d).valueOf();
  9634. }
  9635. }
  9636. function utcStartOfDate(y, m, d) {
  9637. // Date.UTC remaps years 0-99 to 1900-1999
  9638. if (y < 100 && y >= 0) {
  9639. // preserve leap years using a full 400 year cycle, then reset
  9640. return Date.UTC(y + 400, m, d) - MS_PER_400_YEARS;
  9641. } else {
  9642. return Date.UTC(y, m, d);
  9643. }
  9644. }
  9645. function startOf(units) {
  9646. var time, startOfDate;
  9647. units = normalizeUnits(units);
  9648. if (units === undefined || units === 'millisecond' || !this.isValid()) {
  9649. return this;
  9650. }
  9651. startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate;
  9652. switch (units) {
  9653. case 'year':
  9654. time = startOfDate(this.year(), 0, 1);
  9655. break;
  9656. case 'quarter':
  9657. time = startOfDate(
  9658. this.year(),
  9659. this.month() - (this.month() % 3),
  9660. 1
  9661. );
  9662. break;
  9663. case 'month':
  9664. time = startOfDate(this.year(), this.month(), 1);
  9665. break;
  9666. case 'week':
  9667. time = startOfDate(
  9668. this.year(),
  9669. this.month(),
  9670. this.date() - this.weekday()
  9671. );
  9672. break;
  9673. case 'isoWeek':
  9674. time = startOfDate(
  9675. this.year(),
  9676. this.month(),
  9677. this.date() - (this.isoWeekday() - 1)
  9678. );
  9679. break;
  9680. case 'day':
  9681. case 'date':
  9682. time = startOfDate(this.year(), this.month(), this.date());
  9683. break;
  9684. case 'hour':
  9685. time = this._d.valueOf();
  9686. time -= mod$1(
  9687. time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE),
  9688. MS_PER_HOUR
  9689. );
  9690. break;
  9691. case 'minute':
  9692. time = this._d.valueOf();
  9693. time -= mod$1(time, MS_PER_MINUTE);
  9694. break;
  9695. case 'second':
  9696. time = this._d.valueOf();
  9697. time -= mod$1(time, MS_PER_SECOND);
  9698. break;
  9699. }
  9700. this._d.setTime(time);
  9701. hooks.updateOffset(this, true);
  9702. return this;
  9703. }
  9704. function endOf(units) {
  9705. var time, startOfDate;
  9706. units = normalizeUnits(units);
  9707. if (units === undefined || units === 'millisecond' || !this.isValid()) {
  9708. return this;
  9709. }
  9710. startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate;
  9711. switch (units) {
  9712. case 'year':
  9713. time = startOfDate(this.year() + 1, 0, 1) - 1;
  9714. break;
  9715. case 'quarter':
  9716. time =
  9717. startOfDate(
  9718. this.year(),
  9719. this.month() - (this.month() % 3) + 3,
  9720. 1
  9721. ) - 1;
  9722. break;
  9723. case 'month':
  9724. time = startOfDate(this.year(), this.month() + 1, 1) - 1;
  9725. break;
  9726. case 'week':
  9727. time =
  9728. startOfDate(
  9729. this.year(),
  9730. this.month(),
  9731. this.date() - this.weekday() + 7
  9732. ) - 1;
  9733. break;
  9734. case 'isoWeek':
  9735. time =
  9736. startOfDate(
  9737. this.year(),
  9738. this.month(),
  9739. this.date() - (this.isoWeekday() - 1) + 7
  9740. ) - 1;
  9741. break;
  9742. case 'day':
  9743. case 'date':
  9744. time = startOfDate(this.year(), this.month(), this.date() + 1) - 1;
  9745. break;
  9746. case 'hour':
  9747. time = this._d.valueOf();
  9748. time +=
  9749. MS_PER_HOUR -
  9750. mod$1(
  9751. time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE),
  9752. MS_PER_HOUR
  9753. ) -
  9754. 1;
  9755. break;
  9756. case 'minute':
  9757. time = this._d.valueOf();
  9758. time += MS_PER_MINUTE - mod$1(time, MS_PER_MINUTE) - 1;
  9759. break;
  9760. case 'second':
  9761. time = this._d.valueOf();
  9762. time += MS_PER_SECOND - mod$1(time, MS_PER_SECOND) - 1;
  9763. break;
  9764. }
  9765. this._d.setTime(time);
  9766. hooks.updateOffset(this, true);
  9767. return this;
  9768. }
  9769. function valueOf() {
  9770. return this._d.valueOf() - (this._offset || 0) * 60000;
  9771. }
  9772. function unix() {
  9773. return Math.floor(this.valueOf() / 1000);
  9774. }
  9775. function toDate() {
  9776. return new Date(this.valueOf());
  9777. }
  9778. function toArray() {
  9779. var m = this;
  9780. return [
  9781. m.year(),
  9782. m.month(),
  9783. m.date(),
  9784. m.hour(),
  9785. m.minute(),
  9786. m.second(),
  9787. m.millisecond(),
  9788. ];
  9789. }
  9790. function toObject() {
  9791. var m = this;
  9792. return {
  9793. years: m.year(),
  9794. months: m.month(),
  9795. date: m.date(),
  9796. hours: m.hours(),
  9797. minutes: m.minutes(),
  9798. seconds: m.seconds(),
  9799. milliseconds: m.milliseconds(),
  9800. };
  9801. }
  9802. function toJSON() {
  9803. // new Date(NaN).toJSON() === null
  9804. return this.isValid() ? this.toISOString() : null;
  9805. }
  9806. function isValid$2() {
  9807. return isValid(this);
  9808. }
  9809. function parsingFlags() {
  9810. return extend({}, getParsingFlags(this));
  9811. }
  9812. function invalidAt() {
  9813. return getParsingFlags(this).overflow;
  9814. }
  9815. function creationData() {
  9816. return {
  9817. input: this._i,
  9818. format: this._f,
  9819. locale: this._locale,
  9820. isUTC: this._isUTC,
  9821. strict: this._strict,
  9822. };
  9823. }
  9824. addFormatToken('N', 0, 0, 'eraAbbr');
  9825. addFormatToken('NN', 0, 0, 'eraAbbr');
  9826. addFormatToken('NNN', 0, 0, 'eraAbbr');
  9827. addFormatToken('NNNN', 0, 0, 'eraName');
  9828. addFormatToken('NNNNN', 0, 0, 'eraNarrow');
  9829. addFormatToken('y', ['y', 1], 'yo', 'eraYear');
  9830. addFormatToken('y', ['yy', 2], 0, 'eraYear');
  9831. addFormatToken('y', ['yyy', 3], 0, 'eraYear');
  9832. addFormatToken('y', ['yyyy', 4], 0, 'eraYear');
  9833. addRegexToken('N', matchEraAbbr);
  9834. addRegexToken('NN', matchEraAbbr);
  9835. addRegexToken('NNN', matchEraAbbr);
  9836. addRegexToken('NNNN', matchEraName);
  9837. addRegexToken('NNNNN', matchEraNarrow);
  9838. addParseToken(['N', 'NN', 'NNN', 'NNNN', 'NNNNN'], function (
  9839. input,
  9840. array,
  9841. config,
  9842. token
  9843. ) {
  9844. var era = config._locale.erasParse(input, token, config._strict);
  9845. if (era) {
  9846. getParsingFlags(config).era = era;
  9847. } else {
  9848. getParsingFlags(config).invalidEra = input;
  9849. }
  9850. });
  9851. addRegexToken('y', matchUnsigned);
  9852. addRegexToken('yy', matchUnsigned);
  9853. addRegexToken('yyy', matchUnsigned);
  9854. addRegexToken('yyyy', matchUnsigned);
  9855. addRegexToken('yo', matchEraYearOrdinal);
  9856. addParseToken(['y', 'yy', 'yyy', 'yyyy'], YEAR);
  9857. addParseToken(['yo'], function (input, array, config, token) {
  9858. var match;
  9859. if (config._locale._eraYearOrdinalRegex) {
  9860. match = input.match(config._locale._eraYearOrdinalRegex);
  9861. }
  9862. if (config._locale.eraYearOrdinalParse) {
  9863. array[YEAR] = config._locale.eraYearOrdinalParse(input, match);
  9864. } else {
  9865. array[YEAR] = parseInt(input, 10);
  9866. }
  9867. });
  9868. function localeEras(m, format) {
  9869. var i,
  9870. l,
  9871. date,
  9872. eras = this._eras || getLocale('en')._eras;
  9873. for (i = 0, l = eras.length; i < l; ++i) {
  9874. switch (typeof eras[i].since) {
  9875. case 'string':
  9876. // truncate time
  9877. date = hooks(eras[i].since).startOf('day');
  9878. eras[i].since = date.valueOf();
  9879. break;
  9880. }
  9881. switch (typeof eras[i].until) {
  9882. case 'undefined':
  9883. eras[i].until = +Infinity;
  9884. break;
  9885. case 'string':
  9886. // truncate time
  9887. date = hooks(eras[i].until).startOf('day').valueOf();
  9888. eras[i].until = date.valueOf();
  9889. break;
  9890. }
  9891. }
  9892. return eras;
  9893. }
  9894. function localeErasParse(eraName, format, strict) {
  9895. var i,
  9896. l,
  9897. eras = this.eras(),
  9898. name,
  9899. abbr,
  9900. narrow;
  9901. eraName = eraName.toUpperCase();
  9902. for (i = 0, l = eras.length; i < l; ++i) {
  9903. name = eras[i].name.toUpperCase();
  9904. abbr = eras[i].abbr.toUpperCase();
  9905. narrow = eras[i].narrow.toUpperCase();
  9906. if (strict) {
  9907. switch (format) {
  9908. case 'N':
  9909. case 'NN':
  9910. case 'NNN':
  9911. if (abbr === eraName) {
  9912. return eras[i];
  9913. }
  9914. break;
  9915. case 'NNNN':
  9916. if (name === eraName) {
  9917. return eras[i];
  9918. }
  9919. break;
  9920. case 'NNNNN':
  9921. if (narrow === eraName) {
  9922. return eras[i];
  9923. }
  9924. break;
  9925. }
  9926. } else if ([name, abbr, narrow].indexOf(eraName) >= 0) {
  9927. return eras[i];
  9928. }
  9929. }
  9930. }
  9931. function localeErasConvertYear(era, year) {
  9932. var dir = era.since <= era.until ? +1 : -1;
  9933. if (year === undefined) {
  9934. return hooks(era.since).year();
  9935. } else {
  9936. return hooks(era.since).year() + (year - era.offset) * dir;
  9937. }
  9938. }
  9939. function getEraName() {
  9940. var i,
  9941. l,
  9942. val,
  9943. eras = this.localeData().eras();
  9944. for (i = 0, l = eras.length; i < l; ++i) {
  9945. // truncate time
  9946. val = this.clone().startOf('day').valueOf();
  9947. if (eras[i].since <= val && val <= eras[i].until) {
  9948. return eras[i].name;
  9949. }
  9950. if (eras[i].until <= val && val <= eras[i].since) {
  9951. return eras[i].name;
  9952. }
  9953. }
  9954. return '';
  9955. }
  9956. function getEraNarrow() {
  9957. var i,
  9958. l,
  9959. val,
  9960. eras = this.localeData().eras();
  9961. for (i = 0, l = eras.length; i < l; ++i) {
  9962. // truncate time
  9963. val = this.clone().startOf('day').valueOf();
  9964. if (eras[i].since <= val && val <= eras[i].until) {
  9965. return eras[i].narrow;
  9966. }
  9967. if (eras[i].until <= val && val <= eras[i].since) {
  9968. return eras[i].narrow;
  9969. }
  9970. }
  9971. return '';
  9972. }
  9973. function getEraAbbr() {
  9974. var i,
  9975. l,
  9976. val,
  9977. eras = this.localeData().eras();
  9978. for (i = 0, l = eras.length; i < l; ++i) {
  9979. // truncate time
  9980. val = this.clone().startOf('day').valueOf();
  9981. if (eras[i].since <= val && val <= eras[i].until) {
  9982. return eras[i].abbr;
  9983. }
  9984. if (eras[i].until <= val && val <= eras[i].since) {
  9985. return eras[i].abbr;
  9986. }
  9987. }
  9988. return '';
  9989. }
  9990. function getEraYear() {
  9991. var i,
  9992. l,
  9993. dir,
  9994. val,
  9995. eras = this.localeData().eras();
  9996. for (i = 0, l = eras.length; i < l; ++i) {
  9997. dir = eras[i].since <= eras[i].until ? +1 : -1;
  9998. // truncate time
  9999. val = this.clone().startOf('day').valueOf();
  10000. if (
  10001. (eras[i].since <= val && val <= eras[i].until) ||
  10002. (eras[i].until <= val && val <= eras[i].since)
  10003. ) {
  10004. return (
  10005. (this.year() - hooks(eras[i].since).year()) * dir +
  10006. eras[i].offset
  10007. );
  10008. }
  10009. }
  10010. return this.year();
  10011. }
  10012. function erasNameRegex(isStrict) {
  10013. if (!hasOwnProp(this, '_erasNameRegex')) {
  10014. computeErasParse.call(this);
  10015. }
  10016. return isStrict ? this._erasNameRegex : this._erasRegex;
  10017. }
  10018. function erasAbbrRegex(isStrict) {
  10019. if (!hasOwnProp(this, '_erasAbbrRegex')) {
  10020. computeErasParse.call(this);
  10021. }
  10022. return isStrict ? this._erasAbbrRegex : this._erasRegex;
  10023. }
  10024. function erasNarrowRegex(isStrict) {
  10025. if (!hasOwnProp(this, '_erasNarrowRegex')) {
  10026. computeErasParse.call(this);
  10027. }
  10028. return isStrict ? this._erasNarrowRegex : this._erasRegex;
  10029. }
  10030. function matchEraAbbr(isStrict, locale) {
  10031. return locale.erasAbbrRegex(isStrict);
  10032. }
  10033. function matchEraName(isStrict, locale) {
  10034. return locale.erasNameRegex(isStrict);
  10035. }
  10036. function matchEraNarrow(isStrict, locale) {
  10037. return locale.erasNarrowRegex(isStrict);
  10038. }
  10039. function matchEraYearOrdinal(isStrict, locale) {
  10040. return locale._eraYearOrdinalRegex || matchUnsigned;
  10041. }
  10042. function computeErasParse() {
  10043. var abbrPieces = [],
  10044. namePieces = [],
  10045. narrowPieces = [],
  10046. mixedPieces = [],
  10047. i,
  10048. l,
  10049. eras = this.eras();
  10050. for (i = 0, l = eras.length; i < l; ++i) {
  10051. namePieces.push(regexEscape(eras[i].name));
  10052. abbrPieces.push(regexEscape(eras[i].abbr));
  10053. narrowPieces.push(regexEscape(eras[i].narrow));
  10054. mixedPieces.push(regexEscape(eras[i].name));
  10055. mixedPieces.push(regexEscape(eras[i].abbr));
  10056. mixedPieces.push(regexEscape(eras[i].narrow));
  10057. }
  10058. this._erasRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
  10059. this._erasNameRegex = new RegExp('^(' + namePieces.join('|') + ')', 'i');
  10060. this._erasAbbrRegex = new RegExp('^(' + abbrPieces.join('|') + ')', 'i');
  10061. this._erasNarrowRegex = new RegExp(
  10062. '^(' + narrowPieces.join('|') + ')',
  10063. 'i'
  10064. );
  10065. }
  10066. // FORMATTING
  10067. addFormatToken(0, ['gg', 2], 0, function () {
  10068. return this.weekYear() % 100;
  10069. });
  10070. addFormatToken(0, ['GG', 2], 0, function () {
  10071. return this.isoWeekYear() % 100;
  10072. });
  10073. function addWeekYearFormatToken(token, getter) {
  10074. addFormatToken(0, [token, token.length], 0, getter);
  10075. }
  10076. addWeekYearFormatToken('gggg', 'weekYear');
  10077. addWeekYearFormatToken('ggggg', 'weekYear');
  10078. addWeekYearFormatToken('GGGG', 'isoWeekYear');
  10079. addWeekYearFormatToken('GGGGG', 'isoWeekYear');
  10080. // ALIASES
  10081. addUnitAlias('weekYear', 'gg');
  10082. addUnitAlias('isoWeekYear', 'GG');
  10083. // PRIORITY
  10084. addUnitPriority('weekYear', 1);
  10085. addUnitPriority('isoWeekYear', 1);
  10086. // PARSING
  10087. addRegexToken('G', matchSigned);
  10088. addRegexToken('g', matchSigned);
  10089. addRegexToken('GG', match1to2, match2);
  10090. addRegexToken('gg', match1to2, match2);
  10091. addRegexToken('GGGG', match1to4, match4);
  10092. addRegexToken('gggg', match1to4, match4);
  10093. addRegexToken('GGGGG', match1to6, match6);
  10094. addRegexToken('ggggg', match1to6, match6);
  10095. addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function (
  10096. input,
  10097. week,
  10098. config,
  10099. token
  10100. ) {
  10101. week[token.substr(0, 2)] = toInt(input);
  10102. });
  10103. addWeekParseToken(['gg', 'GG'], function (input, week, config, token) {
  10104. week[token] = hooks.parseTwoDigitYear(input);
  10105. });
  10106. // MOMENTS
  10107. function getSetWeekYear(input) {
  10108. return getSetWeekYearHelper.call(
  10109. this,
  10110. input,
  10111. this.week(),
  10112. this.weekday(),
  10113. this.localeData()._week.dow,
  10114. this.localeData()._week.doy
  10115. );
  10116. }
  10117. function getSetISOWeekYear(input) {
  10118. return getSetWeekYearHelper.call(
  10119. this,
  10120. input,
  10121. this.isoWeek(),
  10122. this.isoWeekday(),
  10123. 1,
  10124. 4
  10125. );
  10126. }
  10127. function getISOWeeksInYear() {
  10128. return weeksInYear(this.year(), 1, 4);
  10129. }
  10130. function getISOWeeksInISOWeekYear() {
  10131. return weeksInYear(this.isoWeekYear(), 1, 4);
  10132. }
  10133. function getWeeksInYear() {
  10134. var weekInfo = this.localeData()._week;
  10135. return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
  10136. }
  10137. function getWeeksInWeekYear() {
  10138. var weekInfo = this.localeData()._week;
  10139. return weeksInYear(this.weekYear(), weekInfo.dow, weekInfo.doy);
  10140. }
  10141. function getSetWeekYearHelper(input, week, weekday, dow, doy) {
  10142. var weeksTarget;
  10143. if (input == null) {
  10144. return weekOfYear(this, dow, doy).year;
  10145. } else {
  10146. weeksTarget = weeksInYear(input, dow, doy);
  10147. if (week > weeksTarget) {
  10148. week = weeksTarget;
  10149. }
  10150. return setWeekAll.call(this, input, week, weekday, dow, doy);
  10151. }
  10152. }
  10153. function setWeekAll(weekYear, week, weekday, dow, doy) {
  10154. var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy),
  10155. date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear);
  10156. this.year(date.getUTCFullYear());
  10157. this.month(date.getUTCMonth());
  10158. this.date(date.getUTCDate());
  10159. return this;
  10160. }
  10161. // FORMATTING
  10162. addFormatToken('Q', 0, 'Qo', 'quarter');
  10163. // ALIASES
  10164. addUnitAlias('quarter', 'Q');
  10165. // PRIORITY
  10166. addUnitPriority('quarter', 7);
  10167. // PARSING
  10168. addRegexToken('Q', match1);
  10169. addParseToken('Q', function (input, array) {
  10170. array[MONTH] = (toInt(input) - 1) * 3;
  10171. });
  10172. // MOMENTS
  10173. function getSetQuarter(input) {
  10174. return input == null
  10175. ? Math.ceil((this.month() + 1) / 3)
  10176. : this.month((input - 1) * 3 + (this.month() % 3));
  10177. }
  10178. // FORMATTING
  10179. addFormatToken('D', ['DD', 2], 'Do', 'date');
  10180. // ALIASES
  10181. addUnitAlias('date', 'D');
  10182. // PRIORITY
  10183. addUnitPriority('date', 9);
  10184. // PARSING
  10185. addRegexToken('D', match1to2);
  10186. addRegexToken('DD', match1to2, match2);
  10187. addRegexToken('Do', function (isStrict, locale) {
  10188. // TODO: Remove "ordinalParse" fallback in next major release.
  10189. return isStrict
  10190. ? locale._dayOfMonthOrdinalParse || locale._ordinalParse
  10191. : locale._dayOfMonthOrdinalParseLenient;
  10192. });
  10193. addParseToken(['D', 'DD'], DATE);
  10194. addParseToken('Do', function (input, array) {
  10195. array[DATE] = toInt(input.match(match1to2)[0]);
  10196. });
  10197. // MOMENTS
  10198. var getSetDayOfMonth = makeGetSet('Date', true);
  10199. // FORMATTING
  10200. addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear');
  10201. // ALIASES
  10202. addUnitAlias('dayOfYear', 'DDD');
  10203. // PRIORITY
  10204. addUnitPriority('dayOfYear', 4);
  10205. // PARSING
  10206. addRegexToken('DDD', match1to3);
  10207. addRegexToken('DDDD', match3);
  10208. addParseToken(['DDD', 'DDDD'], function (input, array, config) {
  10209. config._dayOfYear = toInt(input);
  10210. });
  10211. // HELPERS
  10212. // MOMENTS
  10213. function getSetDayOfYear(input) {
  10214. var dayOfYear =
  10215. Math.round(
  10216. (this.clone().startOf('day') - this.clone().startOf('year')) / 864e5
  10217. ) + 1;
  10218. return input == null ? dayOfYear : this.add(input - dayOfYear, 'd');
  10219. }
  10220. // FORMATTING
  10221. addFormatToken('m', ['mm', 2], 0, 'minute');
  10222. // ALIASES
  10223. addUnitAlias('minute', 'm');
  10224. // PRIORITY
  10225. addUnitPriority('minute', 14);
  10226. // PARSING
  10227. addRegexToken('m', match1to2);
  10228. addRegexToken('mm', match1to2, match2);
  10229. addParseToken(['m', 'mm'], MINUTE);
  10230. // MOMENTS
  10231. var getSetMinute = makeGetSet('Minutes', false);
  10232. // FORMATTING
  10233. addFormatToken('s', ['ss', 2], 0, 'second');
  10234. // ALIASES
  10235. addUnitAlias('second', 's');
  10236. // PRIORITY
  10237. addUnitPriority('second', 15);
  10238. // PARSING
  10239. addRegexToken('s', match1to2);
  10240. addRegexToken('ss', match1to2, match2);
  10241. addParseToken(['s', 'ss'], SECOND);
  10242. // MOMENTS
  10243. var getSetSecond = makeGetSet('Seconds', false);
  10244. // FORMATTING
  10245. addFormatToken('S', 0, 0, function () {
  10246. return ~~(this.millisecond() / 100);
  10247. });
  10248. addFormatToken(0, ['SS', 2], 0, function () {
  10249. return ~~(this.millisecond() / 10);
  10250. });
  10251. addFormatToken(0, ['SSS', 3], 0, 'millisecond');
  10252. addFormatToken(0, ['SSSS', 4], 0, function () {
  10253. return this.millisecond() * 10;
  10254. });
  10255. addFormatToken(0, ['SSSSS', 5], 0, function () {
  10256. return this.millisecond() * 100;
  10257. });
  10258. addFormatToken(0, ['SSSSSS', 6], 0, function () {
  10259. return this.millisecond() * 1000;
  10260. });
  10261. addFormatToken(0, ['SSSSSSS', 7], 0, function () {
  10262. return this.millisecond() * 10000;
  10263. });
  10264. addFormatToken(0, ['SSSSSSSS', 8], 0, function () {
  10265. return this.millisecond() * 100000;
  10266. });
  10267. addFormatToken(0, ['SSSSSSSSS', 9], 0, function () {
  10268. return this.millisecond() * 1000000;
  10269. });
  10270. // ALIASES
  10271. addUnitAlias('millisecond', 'ms');
  10272. // PRIORITY
  10273. addUnitPriority('millisecond', 16);
  10274. // PARSING
  10275. addRegexToken('S', match1to3, match1);
  10276. addRegexToken('SS', match1to3, match2);
  10277. addRegexToken('SSS', match1to3, match3);
  10278. var token, getSetMillisecond;
  10279. for (token = 'SSSS'; token.length <= 9; token += 'S') {
  10280. addRegexToken(token, matchUnsigned);
  10281. }
  10282. function parseMs(input, array) {
  10283. array[MILLISECOND] = toInt(('0.' + input) * 1000);
  10284. }
  10285. for (token = 'S'; token.length <= 9; token += 'S') {
  10286. addParseToken(token, parseMs);
  10287. }
  10288. getSetMillisecond = makeGetSet('Milliseconds', false);
  10289. // FORMATTING
  10290. addFormatToken('z', 0, 0, 'zoneAbbr');
  10291. addFormatToken('zz', 0, 0, 'zoneName');
  10292. // MOMENTS
  10293. function getZoneAbbr() {
  10294. return this._isUTC ? 'UTC' : '';
  10295. }
  10296. function getZoneName() {
  10297. return this._isUTC ? 'Coordinated Universal Time' : '';
  10298. }
  10299. var proto = Moment.prototype;
  10300. proto.add = add;
  10301. proto.calendar = calendar$1;
  10302. proto.clone = clone;
  10303. proto.diff = diff;
  10304. proto.endOf = endOf;
  10305. proto.format = format;
  10306. proto.from = from;
  10307. proto.fromNow = fromNow;
  10308. proto.to = to;
  10309. proto.toNow = toNow;
  10310. proto.get = stringGet;
  10311. proto.invalidAt = invalidAt;
  10312. proto.isAfter = isAfter;
  10313. proto.isBefore = isBefore;
  10314. proto.isBetween = isBetween;
  10315. proto.isSame = isSame;
  10316. proto.isSameOrAfter = isSameOrAfter;
  10317. proto.isSameOrBefore = isSameOrBefore;
  10318. proto.isValid = isValid$2;
  10319. proto.lang = lang;
  10320. proto.locale = locale;
  10321. proto.localeData = localeData;
  10322. proto.max = prototypeMax;
  10323. proto.min = prototypeMin;
  10324. proto.parsingFlags = parsingFlags;
  10325. proto.set = stringSet;
  10326. proto.startOf = startOf;
  10327. proto.subtract = subtract;
  10328. proto.toArray = toArray;
  10329. proto.toObject = toObject;
  10330. proto.toDate = toDate;
  10331. proto.toISOString = toISOString;
  10332. proto.inspect = inspect;
  10333. if (typeof Symbol !== 'undefined' && Symbol.for != null) {
  10334. proto[Symbol.for('nodejs.util.inspect.custom')] = function () {
  10335. return 'Moment<' + this.format() + '>';
  10336. };
  10337. }
  10338. proto.toJSON = toJSON;
  10339. proto.toString = toString;
  10340. proto.unix = unix;
  10341. proto.valueOf = valueOf;
  10342. proto.creationData = creationData;
  10343. proto.eraName = getEraName;
  10344. proto.eraNarrow = getEraNarrow;
  10345. proto.eraAbbr = getEraAbbr;
  10346. proto.eraYear = getEraYear;
  10347. proto.year = getSetYear;
  10348. proto.isLeapYear = getIsLeapYear;
  10349. proto.weekYear = getSetWeekYear;
  10350. proto.isoWeekYear = getSetISOWeekYear;
  10351. proto.quarter = proto.quarters = getSetQuarter;
  10352. proto.month = getSetMonth;
  10353. proto.daysInMonth = getDaysInMonth;
  10354. proto.week = proto.weeks = getSetWeek;
  10355. proto.isoWeek = proto.isoWeeks = getSetISOWeek;
  10356. proto.weeksInYear = getWeeksInYear;
  10357. proto.weeksInWeekYear = getWeeksInWeekYear;
  10358. proto.isoWeeksInYear = getISOWeeksInYear;
  10359. proto.isoWeeksInISOWeekYear = getISOWeeksInISOWeekYear;
  10360. proto.date = getSetDayOfMonth;
  10361. proto.day = proto.days = getSetDayOfWeek;
  10362. proto.weekday = getSetLocaleDayOfWeek;
  10363. proto.isoWeekday = getSetISODayOfWeek;
  10364. proto.dayOfYear = getSetDayOfYear;
  10365. proto.hour = proto.hours = getSetHour;
  10366. proto.minute = proto.minutes = getSetMinute;
  10367. proto.second = proto.seconds = getSetSecond;
  10368. proto.millisecond = proto.milliseconds = getSetMillisecond;
  10369. proto.utcOffset = getSetOffset;
  10370. proto.utc = setOffsetToUTC;
  10371. proto.local = setOffsetToLocal;
  10372. proto.parseZone = setOffsetToParsedOffset;
  10373. proto.hasAlignedHourOffset = hasAlignedHourOffset;
  10374. proto.isDST = isDaylightSavingTime;
  10375. proto.isLocal = isLocal;
  10376. proto.isUtcOffset = isUtcOffset;
  10377. proto.isUtc = isUtc;
  10378. proto.isUTC = isUtc;
  10379. proto.zoneAbbr = getZoneAbbr;
  10380. proto.zoneName = getZoneName;
  10381. proto.dates = deprecate(
  10382. 'dates accessor is deprecated. Use date instead.',
  10383. getSetDayOfMonth
  10384. );
  10385. proto.months = deprecate(
  10386. 'months accessor is deprecated. Use month instead',
  10387. getSetMonth
  10388. );
  10389. proto.years = deprecate(
  10390. 'years accessor is deprecated. Use year instead',
  10391. getSetYear
  10392. );
  10393. proto.zone = deprecate(
  10394. 'moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/',
  10395. getSetZone
  10396. );
  10397. proto.isDSTShifted = deprecate(
  10398. 'isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information',
  10399. isDaylightSavingTimeShifted
  10400. );
  10401. function createUnix(input) {
  10402. return createLocal(input * 1000);
  10403. }
  10404. function createInZone() {
  10405. return createLocal.apply(null, arguments).parseZone();
  10406. }
  10407. function preParsePostFormat(string) {
  10408. return string;
  10409. }
  10410. var proto$1 = Locale.prototype;
  10411. proto$1.calendar = calendar;
  10412. proto$1.longDateFormat = longDateFormat;
  10413. proto$1.invalidDate = invalidDate;
  10414. proto$1.ordinal = ordinal;
  10415. proto$1.preparse = preParsePostFormat;
  10416. proto$1.postformat = preParsePostFormat;
  10417. proto$1.relativeTime = relativeTime;
  10418. proto$1.pastFuture = pastFuture;
  10419. proto$1.set = set;
  10420. proto$1.eras = localeEras;
  10421. proto$1.erasParse = localeErasParse;
  10422. proto$1.erasConvertYear = localeErasConvertYear;
  10423. proto$1.erasAbbrRegex = erasAbbrRegex;
  10424. proto$1.erasNameRegex = erasNameRegex;
  10425. proto$1.erasNarrowRegex = erasNarrowRegex;
  10426. proto$1.months = localeMonths;
  10427. proto$1.monthsShort = localeMonthsShort;
  10428. proto$1.monthsParse = localeMonthsParse;
  10429. proto$1.monthsRegex = monthsRegex;
  10430. proto$1.monthsShortRegex = monthsShortRegex;
  10431. proto$1.week = localeWeek;
  10432. proto$1.firstDayOfYear = localeFirstDayOfYear;
  10433. proto$1.firstDayOfWeek = localeFirstDayOfWeek;
  10434. proto$1.weekdays = localeWeekdays;
  10435. proto$1.weekdaysMin = localeWeekdaysMin;
  10436. proto$1.weekdaysShort = localeWeekdaysShort;
  10437. proto$1.weekdaysParse = localeWeekdaysParse;
  10438. proto$1.weekdaysRegex = weekdaysRegex;
  10439. proto$1.weekdaysShortRegex = weekdaysShortRegex;
  10440. proto$1.weekdaysMinRegex = weekdaysMinRegex;
  10441. proto$1.isPM = localeIsPM;
  10442. proto$1.meridiem = localeMeridiem;
  10443. function get$1(format, index, field, setter) {
  10444. var locale = getLocale(),
  10445. utc = createUTC().set(setter, index);
  10446. return locale[field](utc, format);
  10447. }
  10448. function listMonthsImpl(format, index, field) {
  10449. if (isNumber(format)) {
  10450. index = format;
  10451. format = undefined;
  10452. }
  10453. format = format || '';
  10454. if (index != null) {
  10455. return get$1(format, index, field, 'month');
  10456. }
  10457. var i,
  10458. out = [];
  10459. for (i = 0; i < 12; i++) {
  10460. out[i] = get$1(format, i, field, 'month');
  10461. }
  10462. return out;
  10463. }
  10464. // ()
  10465. // (5)
  10466. // (fmt, 5)
  10467. // (fmt)
  10468. // (true)
  10469. // (true, 5)
  10470. // (true, fmt, 5)
  10471. // (true, fmt)
  10472. function listWeekdaysImpl(localeSorted, format, index, field) {
  10473. if (typeof localeSorted === 'boolean') {
  10474. if (isNumber(format)) {
  10475. index = format;
  10476. format = undefined;
  10477. }
  10478. format = format || '';
  10479. } else {
  10480. format = localeSorted;
  10481. index = format;
  10482. localeSorted = false;
  10483. if (isNumber(format)) {
  10484. index = format;
  10485. format = undefined;
  10486. }
  10487. format = format || '';
  10488. }
  10489. var locale = getLocale(),
  10490. shift = localeSorted ? locale._week.dow : 0,
  10491. i,
  10492. out = [];
  10493. if (index != null) {
  10494. return get$1(format, (index + shift) % 7, field, 'day');
  10495. }
  10496. for (i = 0; i < 7; i++) {
  10497. out[i] = get$1(format, (i + shift) % 7, field, 'day');
  10498. }
  10499. return out;
  10500. }
  10501. function listMonths(format, index) {
  10502. return listMonthsImpl(format, index, 'months');
  10503. }
  10504. function listMonthsShort(format, index) {
  10505. return listMonthsImpl(format, index, 'monthsShort');
  10506. }
  10507. function listWeekdays(localeSorted, format, index) {
  10508. return listWeekdaysImpl(localeSorted, format, index, 'weekdays');
  10509. }
  10510. function listWeekdaysShort(localeSorted, format, index) {
  10511. return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort');
  10512. }
  10513. function listWeekdaysMin(localeSorted, format, index) {
  10514. return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin');
  10515. }
  10516. getSetGlobalLocale('en', {
  10517. eras: [
  10518. {
  10519. since: '0001-01-01',
  10520. until: +Infinity,
  10521. offset: 1,
  10522. name: 'Anno Domini',
  10523. narrow: 'AD',
  10524. abbr: 'AD',
  10525. },
  10526. {
  10527. since: '0000-12-31',
  10528. until: -Infinity,
  10529. offset: 1,
  10530. name: 'Before Christ',
  10531. narrow: 'BC',
  10532. abbr: 'BC',
  10533. },
  10534. ],
  10535. dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/,
  10536. ordinal: function (number) {
  10537. var b = number % 10,
  10538. output =
  10539. toInt((number % 100) / 10) === 1
  10540. ? 'th'
  10541. : b === 1
  10542. ? 'st'
  10543. : b === 2
  10544. ? 'nd'
  10545. : b === 3
  10546. ? 'rd'
  10547. : 'th';
  10548. return number + output;
  10549. },
  10550. });
  10551. // Side effect imports
  10552. hooks.lang = deprecate(
  10553. 'moment.lang is deprecated. Use moment.locale instead.',
  10554. getSetGlobalLocale
  10555. );
  10556. hooks.langData = deprecate(
  10557. 'moment.langData is deprecated. Use moment.localeData instead.',
  10558. getLocale
  10559. );
  10560. var mathAbs = Math.abs;
  10561. function abs() {
  10562. var data = this._data;
  10563. this._milliseconds = mathAbs(this._milliseconds);
  10564. this._days = mathAbs(this._days);
  10565. this._months = mathAbs(this._months);
  10566. data.milliseconds = mathAbs(data.milliseconds);
  10567. data.seconds = mathAbs(data.seconds);
  10568. data.minutes = mathAbs(data.minutes);
  10569. data.hours = mathAbs(data.hours);
  10570. data.months = mathAbs(data.months);
  10571. data.years = mathAbs(data.years);
  10572. return this;
  10573. }
  10574. function addSubtract$1(duration, input, value, direction) {
  10575. var other = createDuration(input, value);
  10576. duration._milliseconds += direction * other._milliseconds;
  10577. duration._days += direction * other._days;
  10578. duration._months += direction * other._months;
  10579. return duration._bubble();
  10580. }
  10581. // supports only 2.0-style add(1, 's') or add(duration)
  10582. function add$1(input, value) {
  10583. return addSubtract$1(this, input, value, 1);
  10584. }
  10585. // supports only 2.0-style subtract(1, 's') or subtract(duration)
  10586. function subtract$1(input, value) {
  10587. return addSubtract$1(this, input, value, -1);
  10588. }
  10589. function absCeil(number) {
  10590. if (number < 0) {
  10591. return Math.floor(number);
  10592. } else {
  10593. return Math.ceil(number);
  10594. }
  10595. }
  10596. function bubble() {
  10597. var milliseconds = this._milliseconds,
  10598. days = this._days,
  10599. months = this._months,
  10600. data = this._data,
  10601. seconds,
  10602. minutes,
  10603. hours,
  10604. years,
  10605. monthsFromDays;
  10606. // if we have a mix of positive and negative values, bubble down first
  10607. // check: https://github.com/moment/moment/issues/2166
  10608. if (
  10609. !(
  10610. (milliseconds >= 0 && days >= 0 && months >= 0) ||
  10611. (milliseconds <= 0 && days <= 0 && months <= 0)
  10612. )
  10613. ) {
  10614. milliseconds += absCeil(monthsToDays(months) + days) * 864e5;
  10615. days = 0;
  10616. months = 0;
  10617. }
  10618. // The following code bubbles up values, see the tests for
  10619. // examples of what that means.
  10620. data.milliseconds = milliseconds % 1000;
  10621. seconds = absFloor(milliseconds / 1000);
  10622. data.seconds = seconds % 60;
  10623. minutes = absFloor(seconds / 60);
  10624. data.minutes = minutes % 60;
  10625. hours = absFloor(minutes / 60);
  10626. data.hours = hours % 24;
  10627. days += absFloor(hours / 24);
  10628. // convert days to months
  10629. monthsFromDays = absFloor(daysToMonths(days));
  10630. months += monthsFromDays;
  10631. days -= absCeil(monthsToDays(monthsFromDays));
  10632. // 12 months -> 1 year
  10633. years = absFloor(months / 12);
  10634. months %= 12;
  10635. data.days = days;
  10636. data.months = months;
  10637. data.years = years;
  10638. return this;
  10639. }
  10640. function daysToMonths(days) {
  10641. // 400 years have 146097 days (taking into account leap year rules)
  10642. // 400 years have 12 months === 4800
  10643. return (days * 4800) / 146097;
  10644. }
  10645. function monthsToDays(months) {
  10646. // the reverse of daysToMonths
  10647. return (months * 146097) / 4800;
  10648. }
  10649. function as(units) {
  10650. if (!this.isValid()) {
  10651. return NaN;
  10652. }
  10653. var days,
  10654. months,
  10655. milliseconds = this._milliseconds;
  10656. units = normalizeUnits(units);
  10657. if (units === 'month' || units === 'quarter' || units === 'year') {
  10658. days = this._days + milliseconds / 864e5;
  10659. months = this._months + daysToMonths(days);
  10660. switch (units) {
  10661. case 'month':
  10662. return months;
  10663. case 'quarter':
  10664. return months / 3;
  10665. case 'year':
  10666. return months / 12;
  10667. }
  10668. } else {
  10669. // handle milliseconds separately because of floating point math errors (issue #1867)
  10670. days = this._days + Math.round(monthsToDays(this._months));
  10671. switch (units) {
  10672. case 'week':
  10673. return days / 7 + milliseconds / 6048e5;
  10674. case 'day':
  10675. return days + milliseconds / 864e5;
  10676. case 'hour':
  10677. return days * 24 + milliseconds / 36e5;
  10678. case 'minute':
  10679. return days * 1440 + milliseconds / 6e4;
  10680. case 'second':
  10681. return days * 86400 + milliseconds / 1000;
  10682. // Math.floor prevents floating point math errors here
  10683. case 'millisecond':
  10684. return Math.floor(days * 864e5) + milliseconds;
  10685. default:
  10686. throw new Error('Unknown unit ' + units);
  10687. }
  10688. }
  10689. }
  10690. // TODO: Use this.as('ms')?
  10691. function valueOf$1() {
  10692. if (!this.isValid()) {
  10693. return NaN;
  10694. }
  10695. return (
  10696. this._milliseconds +
  10697. this._days * 864e5 +
  10698. (this._months % 12) * 2592e6 +
  10699. toInt(this._months / 12) * 31536e6
  10700. );
  10701. }
  10702. function makeAs(alias) {
  10703. return function () {
  10704. return this.as(alias);
  10705. };
  10706. }
  10707. var asMilliseconds = makeAs('ms'),
  10708. asSeconds = makeAs('s'),
  10709. asMinutes = makeAs('m'),
  10710. asHours = makeAs('h'),
  10711. asDays = makeAs('d'),
  10712. asWeeks = makeAs('w'),
  10713. asMonths = makeAs('M'),
  10714. asQuarters = makeAs('Q'),
  10715. asYears = makeAs('y');
  10716. function clone$1() {
  10717. return createDuration(this);
  10718. }
  10719. function get$2(units) {
  10720. units = normalizeUnits(units);
  10721. return this.isValid() ? this[units + 's']() : NaN;
  10722. }
  10723. function makeGetter(name) {
  10724. return function () {
  10725. return this.isValid() ? this._data[name] : NaN;
  10726. };
  10727. }
  10728. var milliseconds = makeGetter('milliseconds'),
  10729. seconds = makeGetter('seconds'),
  10730. minutes = makeGetter('minutes'),
  10731. hours = makeGetter('hours'),
  10732. days = makeGetter('days'),
  10733. months = makeGetter('months'),
  10734. years = makeGetter('years');
  10735. function weeks() {
  10736. return absFloor(this.days() / 7);
  10737. }
  10738. var round = Math.round,
  10739. thresholds = {
  10740. ss: 44, // a few seconds to seconds
  10741. s: 45, // seconds to minute
  10742. m: 45, // minutes to hour
  10743. h: 22, // hours to day
  10744. d: 26, // days to month/week
  10745. w: null, // weeks to month
  10746. M: 11, // months to year
  10747. };
  10748. // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
  10749. function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) {
  10750. return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
  10751. }
  10752. function relativeTime$1(posNegDuration, withoutSuffix, thresholds, locale) {
  10753. var duration = createDuration(posNegDuration).abs(),
  10754. seconds = round(duration.as('s')),
  10755. minutes = round(duration.as('m')),
  10756. hours = round(duration.as('h')),
  10757. days = round(duration.as('d')),
  10758. months = round(duration.as('M')),
  10759. weeks = round(duration.as('w')),
  10760. years = round(duration.as('y')),
  10761. a =
  10762. (seconds <= thresholds.ss && ['s', seconds]) ||
  10763. (seconds < thresholds.s && ['ss', seconds]) ||
  10764. (minutes <= 1 && ['m']) ||
  10765. (minutes < thresholds.m && ['mm', minutes]) ||
  10766. (hours <= 1 && ['h']) ||
  10767. (hours < thresholds.h && ['hh', hours]) ||
  10768. (days <= 1 && ['d']) ||
  10769. (days < thresholds.d && ['dd', days]);
  10770. if (thresholds.w != null) {
  10771. a =
  10772. a ||
  10773. (weeks <= 1 && ['w']) ||
  10774. (weeks < thresholds.w && ['ww', weeks]);
  10775. }
  10776. a = a ||
  10777. (months <= 1 && ['M']) ||
  10778. (months < thresholds.M && ['MM', months]) ||
  10779. (years <= 1 && ['y']) || ['yy', years];
  10780. a[2] = withoutSuffix;
  10781. a[3] = +posNegDuration > 0;
  10782. a[4] = locale;
  10783. return substituteTimeAgo.apply(null, a);
  10784. }
  10785. // This function allows you to set the rounding function for relative time strings
  10786. function getSetRelativeTimeRounding(roundingFunction) {
  10787. if (roundingFunction === undefined) {
  10788. return round;
  10789. }
  10790. if (typeof roundingFunction === 'function') {
  10791. round = roundingFunction;
  10792. return true;
  10793. }
  10794. return false;
  10795. }
  10796. // This function allows you to set a threshold for relative time strings
  10797. function getSetRelativeTimeThreshold(threshold, limit) {
  10798. if (thresholds[threshold] === undefined) {
  10799. return false;
  10800. }
  10801. if (limit === undefined) {
  10802. return thresholds[threshold];
  10803. }
  10804. thresholds[threshold] = limit;
  10805. if (threshold === 's') {
  10806. thresholds.ss = limit - 1;
  10807. }
  10808. return true;
  10809. }
  10810. function humanize(argWithSuffix, argThresholds) {
  10811. if (!this.isValid()) {
  10812. return this.localeData().invalidDate();
  10813. }
  10814. var withSuffix = false,
  10815. th = thresholds,
  10816. locale,
  10817. output;
  10818. if (typeof argWithSuffix === 'object') {
  10819. argThresholds = argWithSuffix;
  10820. argWithSuffix = false;
  10821. }
  10822. if (typeof argWithSuffix === 'boolean') {
  10823. withSuffix = argWithSuffix;
  10824. }
  10825. if (typeof argThresholds === 'object') {
  10826. th = Object.assign({}, thresholds, argThresholds);
  10827. if (argThresholds.s != null && argThresholds.ss == null) {
  10828. th.ss = argThresholds.s - 1;
  10829. }
  10830. }
  10831. locale = this.localeData();
  10832. output = relativeTime$1(this, !withSuffix, th, locale);
  10833. if (withSuffix) {
  10834. output = locale.pastFuture(+this, output);
  10835. }
  10836. return locale.postformat(output);
  10837. }
  10838. var abs$1 = Math.abs;
  10839. function sign(x) {
  10840. return (x > 0) - (x < 0) || +x;
  10841. }
  10842. function toISOString$1() {
  10843. // for ISO strings we do not use the normal bubbling rules:
  10844. // * milliseconds bubble up until they become hours
  10845. // * days do not bubble at all
  10846. // * months bubble up until they become years
  10847. // This is because there is no context-free conversion between hours and days
  10848. // (think of clock changes)
  10849. // and also not between days and months (28-31 days per month)
  10850. if (!this.isValid()) {
  10851. return this.localeData().invalidDate();
  10852. }
  10853. var seconds = abs$1(this._milliseconds) / 1000,
  10854. days = abs$1(this._days),
  10855. months = abs$1(this._months),
  10856. minutes,
  10857. hours,
  10858. years,
  10859. s,
  10860. total = this.asSeconds(),
  10861. totalSign,
  10862. ymSign,
  10863. daysSign,
  10864. hmsSign;
  10865. if (!total) {
  10866. // this is the same as C#'s (Noda) and python (isodate)...
  10867. // but not other JS (goog.date)
  10868. return 'P0D';
  10869. }
  10870. // 3600 seconds -> 60 minutes -> 1 hour
  10871. minutes = absFloor(seconds / 60);
  10872. hours = absFloor(minutes / 60);
  10873. seconds %= 60;
  10874. minutes %= 60;
  10875. // 12 months -> 1 year
  10876. years = absFloor(months / 12);
  10877. months %= 12;
  10878. // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
  10879. s = seconds ? seconds.toFixed(3).replace(/\.?0+$/, '') : '';
  10880. totalSign = total < 0 ? '-' : '';
  10881. ymSign = sign(this._months) !== sign(total) ? '-' : '';
  10882. daysSign = sign(this._days) !== sign(total) ? '-' : '';
  10883. hmsSign = sign(this._milliseconds) !== sign(total) ? '-' : '';
  10884. return (
  10885. totalSign +
  10886. 'P' +
  10887. (years ? ymSign + years + 'Y' : '') +
  10888. (months ? ymSign + months + 'M' : '') +
  10889. (days ? daysSign + days + 'D' : '') +
  10890. (hours || minutes || seconds ? 'T' : '') +
  10891. (hours ? hmsSign + hours + 'H' : '') +
  10892. (minutes ? hmsSign + minutes + 'M' : '') +
  10893. (seconds ? hmsSign + s + 'S' : '')
  10894. );
  10895. }
  10896. var proto$2 = Duration.prototype;
  10897. proto$2.isValid = isValid$1;
  10898. proto$2.abs = abs;
  10899. proto$2.add = add$1;
  10900. proto$2.subtract = subtract$1;
  10901. proto$2.as = as;
  10902. proto$2.asMilliseconds = asMilliseconds;
  10903. proto$2.asSeconds = asSeconds;
  10904. proto$2.asMinutes = asMinutes;
  10905. proto$2.asHours = asHours;
  10906. proto$2.asDays = asDays;
  10907. proto$2.asWeeks = asWeeks;
  10908. proto$2.asMonths = asMonths;
  10909. proto$2.asQuarters = asQuarters;
  10910. proto$2.asYears = asYears;
  10911. proto$2.valueOf = valueOf$1;
  10912. proto$2._bubble = bubble;
  10913. proto$2.clone = clone$1;
  10914. proto$2.get = get$2;
  10915. proto$2.milliseconds = milliseconds;
  10916. proto$2.seconds = seconds;
  10917. proto$2.minutes = minutes;
  10918. proto$2.hours = hours;
  10919. proto$2.days = days;
  10920. proto$2.weeks = weeks;
  10921. proto$2.months = months;
  10922. proto$2.years = years;
  10923. proto$2.humanize = humanize;
  10924. proto$2.toISOString = toISOString$1;
  10925. proto$2.toString = toISOString$1;
  10926. proto$2.toJSON = toISOString$1;
  10927. proto$2.locale = locale;
  10928. proto$2.localeData = localeData;
  10929. proto$2.toIsoString = deprecate(
  10930. 'toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)',
  10931. toISOString$1
  10932. );
  10933. proto$2.lang = lang;
  10934. // FORMATTING
  10935. addFormatToken('X', 0, 0, 'unix');
  10936. addFormatToken('x', 0, 0, 'valueOf');
  10937. // PARSING
  10938. addRegexToken('x', matchSigned);
  10939. addRegexToken('X', matchTimestamp);
  10940. addParseToken('X', function (input, array, config) {
  10941. config._d = new Date(parseFloat(input) * 1000);
  10942. });
  10943. addParseToken('x', function (input, array, config) {
  10944. config._d = new Date(toInt(input));
  10945. });
  10946. //! moment.js
  10947. hooks.version = '2.29.1';
  10948. setHookCallback(createLocal);
  10949. hooks.fn = proto;
  10950. hooks.min = min;
  10951. hooks.max = max;
  10952. hooks.now = now;
  10953. hooks.utc = createUTC;
  10954. hooks.unix = createUnix;
  10955. hooks.months = listMonths;
  10956. hooks.isDate = isDate;
  10957. hooks.locale = getSetGlobalLocale;
  10958. hooks.invalid = createInvalid;
  10959. hooks.duration = createDuration;
  10960. hooks.isMoment = isMoment;
  10961. hooks.weekdays = listWeekdays;
  10962. hooks.parseZone = createInZone;
  10963. hooks.localeData = getLocale;
  10964. hooks.isDuration = isDuration;
  10965. hooks.monthsShort = listMonthsShort;
  10966. hooks.weekdaysMin = listWeekdaysMin;
  10967. hooks.defineLocale = defineLocale;
  10968. hooks.updateLocale = updateLocale;
  10969. hooks.locales = listLocales;
  10970. hooks.weekdaysShort = listWeekdaysShort;
  10971. hooks.normalizeUnits = normalizeUnits;
  10972. hooks.relativeTimeRounding = getSetRelativeTimeRounding;
  10973. hooks.relativeTimeThreshold = getSetRelativeTimeThreshold;
  10974. hooks.calendarFormat = getCalendarFormat;
  10975. hooks.prototype = proto;
  10976. // currently HTML5 input type only supports 24-hour formats
  10977. hooks.HTML5_FMT = {
  10978. DATETIME_LOCAL: 'YYYY-MM-DDTHH:mm', // <input type="datetime-local" />
  10979. DATETIME_LOCAL_SECONDS: 'YYYY-MM-DDTHH:mm:ss', // <input type="datetime-local" step="1" />
  10980. DATETIME_LOCAL_MS: 'YYYY-MM-DDTHH:mm:ss.SSS', // <input type="datetime-local" step="0.001" />
  10981. DATE: 'YYYY-MM-DD', // <input type="date" />
  10982. TIME: 'HH:mm', // <input type="time" />
  10983. TIME_SECONDS: 'HH:mm:ss', // <input type="time" step="1" />
  10984. TIME_MS: 'HH:mm:ss.SSS', // <input type="time" step="0.001" />
  10985. WEEK: 'GGGG-[W]WW', // <input type="week" />
  10986. MONTH: 'YYYY-MM', // <input type="month" />
  10987. };
  10988. return hooks;
  10989. })));
  10990. }, "/$$rollup_base$$/node_modules/moment");
  10991. let array8 = arrayUntyped,
  10992. array16 = arrayUntyped,
  10993. array32 = arrayUntyped,
  10994. arrayLengthen = arrayLengthenUntyped,
  10995. arrayWiden = arrayWidenUntyped;
  10996. if (typeof Uint8Array !== "undefined") {
  10997. array8 = function(n) { return new Uint8Array(n); };
  10998. array16 = function(n) { return new Uint16Array(n); };
  10999. array32 = function(n) { return new Uint32Array(n); };
  11000. arrayLengthen = function(array, length) {
  11001. if (array.length >= length) return array;
  11002. var copy = new array.constructor(length);
  11003. copy.set(array);
  11004. return copy;
  11005. };
  11006. arrayWiden = function(array, width) {
  11007. var copy;
  11008. switch (width) {
  11009. case 16: copy = array16(array.length); break;
  11010. case 32: copy = array32(array.length); break;
  11011. default: throw new Error("invalid array width!");
  11012. }
  11013. copy.set(array);
  11014. return copy;
  11015. };
  11016. }
  11017. function arrayUntyped(n) {
  11018. var array = new Array(n), i = -1;
  11019. while (++i < n) array[i] = 0;
  11020. return array;
  11021. }
  11022. function arrayLengthenUntyped(array, length) {
  11023. var n = array.length;
  11024. while (n < length) array[n++] = 0;
  11025. return array;
  11026. }
  11027. function arrayWidenUntyped(array, width) {
  11028. if (width > 32) throw new Error("invalid array width!");
  11029. return array;
  11030. }
  11031. // An arbitrarily-wide array of bitmasks
  11032. function bitarray(n) {
  11033. this.length = n;
  11034. this.subarrays = 1;
  11035. this.width = 8;
  11036. this.masks = {
  11037. 0: 0
  11038. };
  11039. this[0] = array8(n);
  11040. }
  11041. bitarray.prototype.lengthen = function(n) {
  11042. var i, len;
  11043. for (i = 0, len = this.subarrays; i < len; ++i) {
  11044. this[i] = arrayLengthen(this[i], n);
  11045. }
  11046. this.length = n;
  11047. };
  11048. // Reserve a new bit index in the array, returns {offset, one}
  11049. bitarray.prototype.add = function() {
  11050. var m, w, one, i, len;
  11051. for (i = 0, len = this.subarrays; i < len; ++i) {
  11052. m = this.masks[i];
  11053. w = this.width - (32 * i);
  11054. // isolate the rightmost zero bit and return it as an unsigned int of 32 bits, if NaN or -1, return a 0
  11055. one = (~m & (m + 1)) >>> 0;
  11056. if (w >= 32 && !one) {
  11057. continue;
  11058. }
  11059. if (w < 32 && (one & (1 << w))) {
  11060. // widen this subarray
  11061. this[i] = arrayWiden(this[i], w <<= 1);
  11062. this.width = 32 * i + w;
  11063. }
  11064. this.masks[i] |= one;
  11065. return {
  11066. offset: i,
  11067. one: one
  11068. };
  11069. }
  11070. // add a new subarray
  11071. this[this.subarrays] = array8(this.length);
  11072. this.masks[this.subarrays] = 1;
  11073. this.width += 8;
  11074. return {
  11075. offset: this.subarrays++,
  11076. one: 1
  11077. };
  11078. };
  11079. // Copy record from index src to index dest
  11080. bitarray.prototype.copy = function(dest, src) {
  11081. var i, len;
  11082. for (i = 0, len = this.subarrays; i < len; ++i) {
  11083. this[i][dest] = this[i][src];
  11084. }
  11085. };
  11086. // Truncate the array to the given length
  11087. bitarray.prototype.truncate = function(n) {
  11088. var i, len;
  11089. for (i = 0, len = this.subarrays; i < len; ++i) {
  11090. for (var j = this.length - 1; j >= n; j--) {
  11091. this[i][j] = 0;
  11092. }
  11093. }
  11094. this.length = n;
  11095. };
  11096. // Checks that all bits for the given index are 0
  11097. bitarray.prototype.zero = function(n) {
  11098. var i, len;
  11099. for (i = 0, len = this.subarrays; i < len; ++i) {
  11100. if (this[i][n]) {
  11101. return false;
  11102. }
  11103. }
  11104. return true;
  11105. };
  11106. // Checks that all bits for the given index are 0 except for possibly one
  11107. bitarray.prototype.zeroExcept = function(n, offset, zero) {
  11108. var i, len;
  11109. for (i = 0, len = this.subarrays; i < len; ++i) {
  11110. if (i === offset ? this[i][n] & zero : this[i][n]) {
  11111. return false;
  11112. }
  11113. }
  11114. return true;
  11115. };
  11116. // Checks that all bits for the given index are 0 except for the specified mask.
  11117. // The mask should be an array of the same size as the filter subarrays width.
  11118. bitarray.prototype.zeroExceptMask = function(n, mask) {
  11119. var i, len;
  11120. for (i = 0, len = this.subarrays; i < len; ++i) {
  11121. if (this[i][n] & mask[i]) {
  11122. return false;
  11123. }
  11124. }
  11125. return true;
  11126. };
  11127. // Checks that only the specified bit is set for the given index
  11128. bitarray.prototype.only = function(n, offset, one) {
  11129. var i, len;
  11130. for (i = 0, len = this.subarrays; i < len; ++i) {
  11131. if (this[i][n] != (i === offset ? one : 0)) {
  11132. return false;
  11133. }
  11134. }
  11135. return true;
  11136. };
  11137. // Checks that only the specified bit is set for the given index except for possibly one other
  11138. bitarray.prototype.onlyExcept = function(n, offset, zero, onlyOffset, onlyOne) {
  11139. var mask;
  11140. var i, len;
  11141. for (i = 0, len = this.subarrays; i < len; ++i) {
  11142. mask = this[i][n];
  11143. if (i === offset)
  11144. mask = (mask & zero) >>> 0;
  11145. if (mask != (i === onlyOffset ? onlyOne : 0)) {
  11146. return false;
  11147. }
  11148. }
  11149. return true;
  11150. };
  11151. var xfilterArray = {
  11152. array8: arrayUntyped,
  11153. array16: arrayUntyped,
  11154. array32: arrayUntyped,
  11155. arrayLengthen: arrayLengthenUntyped,
  11156. arrayWiden: arrayWidenUntyped,
  11157. bitarray: bitarray
  11158. };
  11159. const filterExact = (bisect, value) => {
  11160. return function(values) {
  11161. var n = values.length;
  11162. return [bisect.left(values, value, 0, n), bisect.right(values, value, 0, n)];
  11163. };
  11164. };
  11165. const filterRange = (bisect, range) => {
  11166. var min = range[0],
  11167. max = range[1];
  11168. return function(values) {
  11169. var n = values.length;
  11170. return [bisect.left(values, min, 0, n), bisect.left(values, max, 0, n)];
  11171. };
  11172. };
  11173. const filterAll = values => {
  11174. return [0, values.length];
  11175. };
  11176. var xfilterFilter = {
  11177. filterExact,
  11178. filterRange,
  11179. filterAll
  11180. };
  11181. var cr_identity = d => {
  11182. return d;
  11183. };
  11184. var cr_null = () => {
  11185. return null;
  11186. };
  11187. var cr_zero = () => {
  11188. return 0;
  11189. };
  11190. function heap_by(f) {
  11191. // Builds a binary heap within the specified array a[lo:hi]. The heap has the
  11192. // property such that the parent a[lo+i] is always less than or equal to its
  11193. // two children: a[lo+2*i+1] and a[lo+2*i+2].
  11194. function heap(a, lo, hi) {
  11195. var n = hi - lo,
  11196. i = (n >>> 1) + 1;
  11197. while (--i > 0) sift(a, i, n, lo);
  11198. return a;
  11199. }
  11200. // Sorts the specified array a[lo:hi] in descending order, assuming it is
  11201. // already a heap.
  11202. function sort(a, lo, hi) {
  11203. var n = hi - lo,
  11204. t;
  11205. while (--n > 0) t = a[lo], a[lo] = a[lo + n], a[lo + n] = t, sift(a, 1, n, lo);
  11206. return a;
  11207. }
  11208. // Sifts the element a[lo+i-1] down the heap, where the heap is the contiguous
  11209. // slice of array a[lo:lo+n]. This method can also be used to update the heap
  11210. // incrementally, without incurring the full cost of reconstructing the heap.
  11211. function sift(a, i, n, lo) {
  11212. var d = a[--lo + i],
  11213. x = f(d),
  11214. child;
  11215. while ((child = i << 1) <= n) {
  11216. if (child < n && f(a[lo + child]) > f(a[lo + child + 1])) child++;
  11217. if (x <= f(a[lo + child])) break;
  11218. a[lo + i] = a[lo + child];
  11219. i = child;
  11220. }
  11221. a[lo + i] = d;
  11222. }
  11223. heap.sort = sort;
  11224. return heap;
  11225. }
  11226. const h$1 = heap_by(cr_identity);
  11227. h$1.by = heap_by;
  11228. function heapselect_by(f) {
  11229. var heap = h$1.by(f);
  11230. // Returns a new array containing the top k elements in the array a[lo:hi].
  11231. // The returned array is not sorted, but maintains the heap property. If k is
  11232. // greater than hi - lo, then fewer than k elements will be returned. The
  11233. // order of elements in a is unchanged by this operation.
  11234. function heapselect(a, lo, hi, k) {
  11235. var queue = new Array(k = Math.min(hi - lo, k)),
  11236. min,
  11237. i,
  11238. d;
  11239. for (i = 0; i < k; ++i) queue[i] = a[lo++];
  11240. heap(queue, 0, k);
  11241. if (lo < hi) {
  11242. min = f(queue[0]);
  11243. do {
  11244. if (f(d = a[lo]) > min) {
  11245. queue[0] = d;
  11246. min = f(heap(queue, 0, k)[0]);
  11247. }
  11248. } while (++lo < hi);
  11249. }
  11250. return queue;
  11251. }
  11252. return heapselect;
  11253. }
  11254. const h = heapselect_by(cr_identity);
  11255. h.by = heapselect_by; // assign the raw function to the export as well
  11256. function bisect_by(f) {
  11257. // Locate the insertion point for x in a to maintain sorted order. The
  11258. // arguments lo and hi may be used to specify a subset of the array which
  11259. // should be considered; by default the entire array is used. If x is already
  11260. // present in a, the insertion point will be before (to the left of) any
  11261. // existing entries. The return value is suitable for use as the first
  11262. // argument to `array.splice` assuming that a is already sorted.
  11263. //
  11264. // The returned insertion point i partitions the array a into two halves so
  11265. // that all v < x for v in a[lo:i] for the left side and all v >= x for v in
  11266. // a[i:hi] for the right side.
  11267. function bisectLeft(a, x, lo, hi) {
  11268. while (lo < hi) {
  11269. var mid = lo + hi >>> 1;
  11270. if (f(a[mid]) < x) lo = mid + 1;
  11271. else hi = mid;
  11272. }
  11273. return lo;
  11274. }
  11275. // Similar to bisectLeft, but returns an insertion point which comes after (to
  11276. // the right of) any existing entries of x in a.
  11277. //
  11278. // The returned insertion point i partitions the array into two halves so that
  11279. // all v <= x for v in a[lo:i] for the left side and all v > x for v in
  11280. // a[i:hi] for the right side.
  11281. function bisectRight(a, x, lo, hi) {
  11282. while (lo < hi) {
  11283. var mid = lo + hi >>> 1;
  11284. if (x < f(a[mid])) hi = mid;
  11285. else lo = mid + 1;
  11286. }
  11287. return lo;
  11288. }
  11289. bisectRight.right = bisectRight;
  11290. bisectRight.left = bisectLeft;
  11291. return bisectRight;
  11292. }
  11293. const bisect = bisect_by(cr_identity);
  11294. bisect.by = bisect_by; // assign the raw function to the export as well
  11295. var permute = (array, index, deep) => {
  11296. for (var i = 0, n = index.length, copy = deep ? JSON.parse(JSON.stringify(array)) : new Array(n); i < n; ++i) {
  11297. copy[i] = array[index[i]];
  11298. }
  11299. return copy;
  11300. };
  11301. const reduceIncrement = p => {
  11302. return p + 1;
  11303. };
  11304. const reduceDecrement = p => {
  11305. return p - 1;
  11306. };
  11307. const reduceAdd = f => {
  11308. return function(p, v) {
  11309. return p + +f(v);
  11310. };
  11311. };
  11312. const reduceSubtract = f => {
  11313. return function(p, v) {
  11314. return p - f(v);
  11315. };
  11316. };
  11317. var xfilterReduce = {
  11318. reduceIncrement,
  11319. reduceDecrement,
  11320. reduceAdd,
  11321. reduceSubtract
  11322. };
  11323. function deep(t,e,i,n,r){for(r in n=(i=i.split(".")).splice(-1,1),i)e=e[i[r]]=e[i[r]]||{};return t(e,n)}
  11324. // Note(cg): result was previsouly using lodash.result, not ESM compatible.
  11325. const get = (obj, prop) => {
  11326. const value = obj[prop];
  11327. return (typeof value === 'function') ? value.call(obj) : value;
  11328. };
  11329. /**
  11330. * get value of object at a deep path.
  11331. * if the resolved value is a function,
  11332. * it's invoked with the `this` binding of
  11333. * its parent object and its result is returned.
  11334. *
  11335. * @param {Object} obj the object (e.g. { 'a': [{ 'b': { 'c1': 3, 'c2': 4} }], 'd': {e:1} }; )
  11336. * @param {String} path deep path (e.g. `d.e`` or `a[0].b.c1`. Dot notation (a.0.b)is also supported)
  11337. * @return {Any} the resolved value
  11338. */
  11339. const reg = /\[([\w\d]+)\]/g;
  11340. var result = (obj, path) => {
  11341. return deep(get, obj, path.replace(reg, '.$1'))
  11342. };
  11343. // constants
  11344. var REMOVED_INDEX = -1;
  11345. crossfilter$1.heap = h$1;
  11346. crossfilter$1.heapselect = h;
  11347. crossfilter$1.bisect = bisect;
  11348. crossfilter$1.permute = permute;
  11349. function crossfilter$1() {
  11350. var crossfilter = {
  11351. add: add,
  11352. remove: removeData,
  11353. dimension: dimension,
  11354. groupAll: groupAll,
  11355. size: size,
  11356. all: all,
  11357. allFiltered: allFiltered,
  11358. onChange: onChange,
  11359. isElementFiltered: isElementFiltered
  11360. };
  11361. var data = [], // the records
  11362. n = 0, // the number of records; data.length
  11363. filters, // 1 is filtered out
  11364. filterListeners = [], // when the filters change
  11365. dataListeners = [], // when data is added
  11366. removeDataListeners = [], // when data is removed
  11367. callbacks = [];
  11368. filters = new xfilterArray.bitarray(0);
  11369. // Adds the specified new records to this crossfilter.
  11370. function add(newData) {
  11371. var n0 = n,
  11372. n1 = newData.length;
  11373. // If there's actually new data to add…
  11374. // Merge the new data into the existing data.
  11375. // Lengthen the filter bitset to handle the new records.
  11376. // Notify listeners (dimensions and groups) that new data is available.
  11377. if (n1) {
  11378. data = data.concat(newData);
  11379. filters.lengthen(n += n1);
  11380. dataListeners.forEach(function(l) { l(newData, n0, n1); });
  11381. triggerOnChange('dataAdded');
  11382. }
  11383. return crossfilter;
  11384. }
  11385. // Removes all records that match the current filters, or if a predicate function is passed,
  11386. // removes all records matching the predicate (ignoring filters).
  11387. function removeData(predicate) {
  11388. var // Mapping from old record indexes to new indexes (after records removed)
  11389. newIndex = new Array(n),
  11390. removed = [],
  11391. usePred = typeof predicate === 'function',
  11392. shouldRemove = function (i) {
  11393. return usePred ? predicate(data[i], i) : filters.zero(i)
  11394. };
  11395. for (var index1 = 0, index2 = 0; index1 < n; ++index1) {
  11396. if ( shouldRemove(index1) ) {
  11397. removed.push(index1);
  11398. newIndex[index1] = REMOVED_INDEX;
  11399. } else {
  11400. newIndex[index1] = index2++;
  11401. }
  11402. }
  11403. // Remove all matching records from groups.
  11404. filterListeners.forEach(function(l) { l(-1, -1, [], removed, true); });
  11405. // Update indexes.
  11406. removeDataListeners.forEach(function(l) { l(newIndex); });
  11407. // Remove old filters and data by overwriting.
  11408. for (var index3 = 0, index4 = 0; index3 < n; ++index3) {
  11409. if ( newIndex[index3] !== REMOVED_INDEX ) {
  11410. if (index3 !== index4) filters.copy(index4, index3), data[index4] = data[index3];
  11411. ++index4;
  11412. }
  11413. }
  11414. data.length = n = index4;
  11415. filters.truncate(index4);
  11416. triggerOnChange('dataRemoved');
  11417. }
  11418. function maskForDimensions(dimensions) {
  11419. var n,
  11420. d,
  11421. len,
  11422. id,
  11423. mask = Array(filters.subarrays);
  11424. for (n = 0; n < filters.subarrays; n++) { mask[n] = ~0; }
  11425. for (d = 0, len = dimensions.length; d < len; d++) {
  11426. // The top bits of the ID are the subarray offset and the lower bits are the bit
  11427. // offset of the "one" mask.
  11428. id = dimensions[d].id();
  11429. mask[id >> 7] &= ~(0x1 << (id & 0x3f));
  11430. }
  11431. return mask;
  11432. }
  11433. // Return true if the data element at index i is filtered IN.
  11434. // Optionally, ignore the filters of any dimensions in the ignore_dimensions list.
  11435. function isElementFiltered(i, ignore_dimensions) {
  11436. var mask = maskForDimensions(ignore_dimensions || []);
  11437. return filters.zeroExceptMask(i,mask);
  11438. }
  11439. // Adds a new dimension with the specified value accessor function.
  11440. function dimension(value, iterable) {
  11441. if (typeof value === 'string') {
  11442. var accessorPath = value;
  11443. value = function(d) { return result(d, accessorPath); };
  11444. }
  11445. var dimension = {
  11446. filter: filter,
  11447. filterExact: filterExact,
  11448. filterRange: filterRange,
  11449. filterFunction: filterFunction,
  11450. filterAll: filterAll,
  11451. currentFilter: currentFilter,
  11452. hasCurrentFilter: hasCurrentFilter,
  11453. top: top,
  11454. bottom: bottom,
  11455. group: group,
  11456. groupAll: groupAll,
  11457. dispose: dispose,
  11458. remove: dispose, // for backwards-compatibility
  11459. accessor: value,
  11460. id: function() { return id; }
  11461. };
  11462. var one, // lowest unset bit as mask, e.g., 00001000
  11463. zero, // inverted one, e.g., 11110111
  11464. offset, // offset into the filters arrays
  11465. id, // unique ID for this dimension (reused when dimensions are disposed)
  11466. values, // sorted, cached array
  11467. index, // maps sorted value index -> record index (in data)
  11468. newValues, // temporary array storing newly-added values
  11469. newIndex, // temporary array storing newly-added index
  11470. iterablesIndexCount,
  11471. iterablesIndexFilterStatus,
  11472. iterablesEmptyRows = [],
  11473. sortRange = function(n) {
  11474. return cr_range(n).sort(function(A, B) {
  11475. var a = newValues[A], b = newValues[B];
  11476. return a < b ? -1 : a > b ? 1 : A - B;
  11477. });
  11478. },
  11479. refilter = xfilterFilter.filterAll, // for recomputing filter
  11480. refilterFunction, // the custom filter function in use
  11481. filterValue, // the value used for filtering (value, array, function or undefined)
  11482. filterValuePresent, // true if filterValue contains something
  11483. indexListeners = [], // when data is added
  11484. dimensionGroups = [],
  11485. lo0 = 0,
  11486. hi0 = 0,
  11487. t = 0,
  11488. k;
  11489. // Updating a dimension is a two-stage process. First, we must update the
  11490. // associated filters for the newly-added records. Once all dimensions have
  11491. // updated their filters, the groups are notified to update.
  11492. dataListeners.unshift(preAdd);
  11493. dataListeners.push(postAdd);
  11494. removeDataListeners.push(removeData);
  11495. // Add a new dimension in the filter bitmap and store the offset and bitmask.
  11496. var tmp = filters.add();
  11497. offset = tmp.offset;
  11498. one = tmp.one;
  11499. zero = ~one;
  11500. // Create a unique ID for the dimension
  11501. // IDs will be re-used if dimensions are disposed.
  11502. // For internal use the ID is the subarray offset shifted left 7 bits or'd with the
  11503. // bit offset of the set bit in the dimension's "one" mask.
  11504. id = (offset << 7) | (Math.log(one) / Math.log(2));
  11505. preAdd(data, 0, n);
  11506. postAdd(data, 0, n);
  11507. // Incorporates the specified new records into this dimension.
  11508. // This function is responsible for updating filters, values, and index.
  11509. function preAdd(newData, n0, n1) {
  11510. var newIterablesIndexCount,
  11511. newIterablesIndexFilterStatus;
  11512. if (iterable){
  11513. // Count all the values
  11514. t = 0;
  11515. j = 0;
  11516. k = [];
  11517. for (var i0 = 0; i0 < newData.length; i0++) {
  11518. for(j = 0, k = value(newData[i0]); j < k.length; j++) {
  11519. t++;
  11520. }
  11521. }
  11522. newValues = [];
  11523. newIterablesIndexCount = cr_range(newData.length);
  11524. newIterablesIndexFilterStatus = cr_index(t,1);
  11525. var unsortedIndex = cr_range(t);
  11526. for (var l = 0, index1 = 0; index1 < newData.length; index1++) {
  11527. k = value(newData[index1]);
  11528. //
  11529. if(!k.length){
  11530. newIterablesIndexCount[index1] = 0;
  11531. iterablesEmptyRows.push(index1 + n0);
  11532. continue;
  11533. }
  11534. newIterablesIndexCount[index1] = k.length;
  11535. for (j = 0; j < k.length; j++) {
  11536. newValues.push(k[j]);
  11537. unsortedIndex[l] = index1;
  11538. l++;
  11539. }
  11540. }
  11541. // Create the Sort map used to sort both the values and the valueToData indices
  11542. var sortMap = sortRange(t);
  11543. // Use the sortMap to sort the newValues
  11544. newValues = permute(newValues, sortMap);
  11545. // Use the sortMap to sort the unsortedIndex map
  11546. // newIndex should be a map of sortedValue -> crossfilterData
  11547. newIndex = permute(unsortedIndex, sortMap);
  11548. } else {
  11549. // Permute new values into natural order using a standard sorted index.
  11550. newValues = newData.map(value);
  11551. newIndex = sortRange(n1);
  11552. newValues = permute(newValues, newIndex);
  11553. }
  11554. // Bisect newValues to determine which new records are selected.
  11555. var bounds = refilter(newValues), lo1 = bounds[0], hi1 = bounds[1];
  11556. var index2, index3, index4;
  11557. if(iterable) {
  11558. n1 = t;
  11559. if (refilterFunction) {
  11560. for (index2 = 0; index2 < n1; ++index2) {
  11561. if (!refilterFunction(newValues[index2], index2)) {
  11562. if(--newIterablesIndexCount[newIndex[index2]] === 0) {
  11563. filters[offset][newIndex[index2] + n0] |= one;
  11564. }
  11565. newIterablesIndexFilterStatus[index2] = 1;
  11566. }
  11567. }
  11568. } else {
  11569. for (index3 = 0; index3 < lo1; ++index3) {
  11570. if(--newIterablesIndexCount[newIndex[index3]] === 0) {
  11571. filters[offset][newIndex[index3] + n0] |= one;
  11572. }
  11573. newIterablesIndexFilterStatus[index3] = 1;
  11574. }
  11575. for (index4 = hi1; index4 < n1; ++index4) {
  11576. if(--newIterablesIndexCount[newIndex[index4]] === 0) {
  11577. filters[offset][newIndex[index4] + n0] |= one;
  11578. }
  11579. newIterablesIndexFilterStatus[index4] = 1;
  11580. }
  11581. }
  11582. } else {
  11583. if (refilterFunction) {
  11584. for (index2 = 0; index2 < n1; ++index2) {
  11585. if (!refilterFunction(newValues[index2], index2)) {
  11586. filters[offset][newIndex[index2] + n0] |= one;
  11587. }
  11588. }
  11589. } else {
  11590. for (index3 = 0; index3 < lo1; ++index3) {
  11591. filters[offset][newIndex[index3] + n0] |= one;
  11592. }
  11593. for (index4 = hi1; index4 < n1; ++index4) {
  11594. filters[offset][newIndex[index4] + n0] |= one;
  11595. }
  11596. }
  11597. }
  11598. // If this dimension previously had no data, then we don't need to do the
  11599. // more expensive merge operation; use the new values and index as-is.
  11600. if (!n0) {
  11601. values = newValues;
  11602. index = newIndex;
  11603. iterablesIndexCount = newIterablesIndexCount;
  11604. iterablesIndexFilterStatus = newIterablesIndexFilterStatus;
  11605. lo0 = lo1;
  11606. hi0 = hi1;
  11607. return;
  11608. }
  11609. var oldValues = values,
  11610. oldIndex = index,
  11611. oldIterablesIndexFilterStatus = iterablesIndexFilterStatus,
  11612. old_n0,
  11613. i1 = 0;
  11614. i0 = 0;
  11615. if(iterable){
  11616. old_n0 = n0;
  11617. n0 = oldValues.length;
  11618. n1 = t;
  11619. }
  11620. // Otherwise, create new arrays into which to merge new and old.
  11621. values = iterable ? new Array(n0 + n1) : new Array(n);
  11622. index = iterable ? new Array(n0 + n1) : cr_index(n, n);
  11623. if(iterable) iterablesIndexFilterStatus = cr_index(n0 + n1, 1);
  11624. // Concatenate the newIterablesIndexCount onto the old one.
  11625. if(iterable) {
  11626. var oldiiclength = iterablesIndexCount.length;
  11627. iterablesIndexCount = xfilterArray.arrayLengthen(iterablesIndexCount, n);
  11628. for(var j=0; j+oldiiclength < n; j++) {
  11629. iterablesIndexCount[j+oldiiclength] = newIterablesIndexCount[j];
  11630. }
  11631. }
  11632. // Merge the old and new sorted values, and old and new index.
  11633. var index5 = 0;
  11634. for (; i0 < n0 && i1 < n1; ++index5) {
  11635. if (oldValues[i0] < newValues[i1]) {
  11636. values[index5] = oldValues[i0];
  11637. if(iterable) iterablesIndexFilterStatus[index5] = oldIterablesIndexFilterStatus[i0];
  11638. index[index5] = oldIndex[i0++];
  11639. } else {
  11640. values[index5] = newValues[i1];
  11641. if(iterable) iterablesIndexFilterStatus[index5] = newIterablesIndexFilterStatus[i1];
  11642. index[index5] = newIndex[i1++] + (iterable ? old_n0 : n0);
  11643. }
  11644. }
  11645. // Add any remaining old values.
  11646. for (; i0 < n0; ++i0, ++index5) {
  11647. values[index5] = oldValues[i0];
  11648. if(iterable) iterablesIndexFilterStatus[index5] = oldIterablesIndexFilterStatus[i0];
  11649. index[index5] = oldIndex[i0];
  11650. }
  11651. // Add any remaining new values.
  11652. for (; i1 < n1; ++i1, ++index5) {
  11653. values[index5] = newValues[i1];
  11654. if(iterable) iterablesIndexFilterStatus[index5] = newIterablesIndexFilterStatus[i1];
  11655. index[index5] = newIndex[i1] + (iterable ? old_n0 : n0);
  11656. }
  11657. // Bisect again to recompute lo0 and hi0.
  11658. bounds = refilter(values), lo0 = bounds[0], hi0 = bounds[1];
  11659. }
  11660. // When all filters have updated, notify index listeners of the new values.
  11661. function postAdd(newData, n0, n1) {
  11662. indexListeners.forEach(function(l) { l(newValues, newIndex, n0, n1); });
  11663. newValues = newIndex = null;
  11664. }
  11665. function removeData(reIndex) {
  11666. if (iterable) {
  11667. for (var i0 = 0, i1 = 0; i0 < iterablesEmptyRows.length; i0++) {
  11668. if (reIndex[iterablesEmptyRows[i0]] !== REMOVED_INDEX) {
  11669. iterablesEmptyRows[i1] = reIndex[iterablesEmptyRows[i0]];
  11670. i1++;
  11671. }
  11672. }
  11673. iterablesEmptyRows.length = i1;
  11674. for (i0 = 0, i1 = 0; i0 < n; i0++) {
  11675. if (reIndex[i0] !== REMOVED_INDEX) {
  11676. if (i1 !== i0) iterablesIndexCount[i1] = iterablesIndexCount[i0];
  11677. i1++;
  11678. }
  11679. }
  11680. iterablesIndexCount = iterablesIndexCount.slice(0, i1);
  11681. }
  11682. // Rewrite our index, overwriting removed values
  11683. var n0 = values.length;
  11684. for (var i = 0, j = 0, oldDataIndex; i < n0; ++i) {
  11685. oldDataIndex = index[i];
  11686. if (reIndex[oldDataIndex] !== REMOVED_INDEX) {
  11687. if (i !== j) values[j] = values[i];
  11688. index[j] = reIndex[oldDataIndex];
  11689. if (iterable) {
  11690. iterablesIndexFilterStatus[j] = iterablesIndexFilterStatus[i];
  11691. }
  11692. ++j;
  11693. }
  11694. }
  11695. values.length = j;
  11696. if (iterable) iterablesIndexFilterStatus = iterablesIndexFilterStatus.slice(0, j);
  11697. while (j < n0) index[j++] = 0;
  11698. // Bisect again to recompute lo0 and hi0.
  11699. var bounds = refilter(values);
  11700. lo0 = bounds[0], hi0 = bounds[1];
  11701. }
  11702. // Updates the selected values based on the specified bounds [lo, hi].
  11703. // This implementation is used by all the public filter methods.
  11704. function filterIndexBounds(bounds) {
  11705. var lo1 = bounds[0],
  11706. hi1 = bounds[1];
  11707. if (refilterFunction) {
  11708. refilterFunction = null;
  11709. filterIndexFunction(function(d, i) { return lo1 <= i && i < hi1; }, bounds[0] === 0 && bounds[1] === values.length);
  11710. lo0 = lo1;
  11711. hi0 = hi1;
  11712. return dimension;
  11713. }
  11714. var i,
  11715. j,
  11716. k,
  11717. added = [],
  11718. removed = [],
  11719. valueIndexAdded = [],
  11720. valueIndexRemoved = [];
  11721. // Fast incremental update based on previous lo index.
  11722. if (lo1 < lo0) {
  11723. for (i = lo1, j = Math.min(lo0, hi1); i < j; ++i) {
  11724. added.push(index[i]);
  11725. valueIndexAdded.push(i);
  11726. }
  11727. } else if (lo1 > lo0) {
  11728. for (i = lo0, j = Math.min(lo1, hi0); i < j; ++i) {
  11729. removed.push(index[i]);
  11730. valueIndexRemoved.push(i);
  11731. }
  11732. }
  11733. // Fast incremental update based on previous hi index.
  11734. if (hi1 > hi0) {
  11735. for (i = Math.max(lo1, hi0), j = hi1; i < j; ++i) {
  11736. added.push(index[i]);
  11737. valueIndexAdded.push(i);
  11738. }
  11739. } else if (hi1 < hi0) {
  11740. for (i = Math.max(lo0, hi1), j = hi0; i < j; ++i) {
  11741. removed.push(index[i]);
  11742. valueIndexRemoved.push(i);
  11743. }
  11744. }
  11745. if(!iterable) {
  11746. // Flip filters normally.
  11747. for(i=0; i<added.length; i++) {
  11748. filters[offset][added[i]] ^= one;
  11749. }
  11750. for(i=0; i<removed.length; i++) {
  11751. filters[offset][removed[i]] ^= one;
  11752. }
  11753. } else {
  11754. // For iterables, we need to figure out if the row has been completely removed vs partially included
  11755. // Only count a row as added if it is not already being aggregated. Only count a row
  11756. // as removed if the last element being aggregated is removed.
  11757. var newAdded = [];
  11758. var newRemoved = [];
  11759. for (i = 0; i < added.length; i++) {
  11760. iterablesIndexCount[added[i]]++;
  11761. iterablesIndexFilterStatus[valueIndexAdded[i]] = 0;
  11762. if(iterablesIndexCount[added[i]] === 1) {
  11763. filters[offset][added[i]] ^= one;
  11764. newAdded.push(added[i]);
  11765. }
  11766. }
  11767. for (i = 0; i < removed.length; i++) {
  11768. iterablesIndexCount[removed[i]]--;
  11769. iterablesIndexFilterStatus[valueIndexRemoved[i]] = 1;
  11770. if(iterablesIndexCount[removed[i]] === 0) {
  11771. filters[offset][removed[i]] ^= one;
  11772. newRemoved.push(removed[i]);
  11773. }
  11774. }
  11775. added = newAdded;
  11776. removed = newRemoved;
  11777. // Now handle empty rows.
  11778. if(refilter === xfilterFilter.filterAll) {
  11779. for(i = 0; i < iterablesEmptyRows.length; i++) {
  11780. if((filters[offset][k = iterablesEmptyRows[i]] & one)) {
  11781. // Was not in the filter, so set the filter and add
  11782. filters[offset][k] ^= one;
  11783. added.push(k);
  11784. }
  11785. }
  11786. } else {
  11787. // filter in place - remove empty rows if necessary
  11788. for(i = 0; i < iterablesEmptyRows.length; i++) {
  11789. if(!(filters[offset][k = iterablesEmptyRows[i]] & one)) {
  11790. // Was in the filter, so set the filter and remove
  11791. filters[offset][k] ^= one;
  11792. removed.push(k);
  11793. }
  11794. }
  11795. }
  11796. }
  11797. lo0 = lo1;
  11798. hi0 = hi1;
  11799. filterListeners.forEach(function(l) { l(one, offset, added, removed); });
  11800. triggerOnChange('filtered');
  11801. return dimension;
  11802. }
  11803. // Filters this dimension using the specified range, value, or null.
  11804. // If the range is null, this is equivalent to filterAll.
  11805. // If the range is an array, this is equivalent to filterRange.
  11806. // Otherwise, this is equivalent to filterExact.
  11807. function filter(range) {
  11808. return range == null
  11809. ? filterAll() : Array.isArray(range)
  11810. ? filterRange(range) : typeof range === "function"
  11811. ? filterFunction(range)
  11812. : filterExact(range);
  11813. }
  11814. // Filters this dimension to select the exact value.
  11815. function filterExact(value) {
  11816. filterValue = value;
  11817. filterValuePresent = true;
  11818. return filterIndexBounds((refilter = xfilterFilter.filterExact(bisect, value))(values));
  11819. }
  11820. // Filters this dimension to select the specified range [lo, hi].
  11821. // The lower bound is inclusive, and the upper bound is exclusive.
  11822. function filterRange(range) {
  11823. filterValue = range;
  11824. filterValuePresent = true;
  11825. return filterIndexBounds((refilter = xfilterFilter.filterRange(bisect, range))(values));
  11826. }
  11827. // Clears any filters on this dimension.
  11828. function filterAll() {
  11829. filterValue = undefined;
  11830. filterValuePresent = false;
  11831. return filterIndexBounds((refilter = xfilterFilter.filterAll)(values));
  11832. }
  11833. // Filters this dimension using an arbitrary function.
  11834. function filterFunction(f) {
  11835. filterValue = f;
  11836. filterValuePresent = true;
  11837. refilterFunction = f;
  11838. refilter = xfilterFilter.filterAll;
  11839. filterIndexFunction(f, false);
  11840. var bounds = refilter(values);
  11841. lo0 = bounds[0], hi0 = bounds[1];
  11842. return dimension;
  11843. }
  11844. function filterIndexFunction(f, filterAll) {
  11845. var i,
  11846. k,
  11847. x,
  11848. added = [],
  11849. removed = [],
  11850. valueIndexAdded = [],
  11851. valueIndexRemoved = [],
  11852. indexLength = values.length;
  11853. if(!iterable) {
  11854. for (i = 0; i < indexLength; ++i) {
  11855. if (!(filters[offset][k = index[i]] & one) ^ !!(x = f(values[i], i))) {
  11856. if (x) added.push(k);
  11857. else removed.push(k);
  11858. }
  11859. }
  11860. }
  11861. if(iterable) {
  11862. for(i=0; i < indexLength; ++i) {
  11863. if(f(values[i], i)) {
  11864. added.push(index[i]);
  11865. valueIndexAdded.push(i);
  11866. } else {
  11867. removed.push(index[i]);
  11868. valueIndexRemoved.push(i);
  11869. }
  11870. }
  11871. }
  11872. if(!iterable) {
  11873. for(i=0; i<added.length; i++) {
  11874. if(filters[offset][added[i]] & one) filters[offset][added[i]] &= zero;
  11875. }
  11876. for(i=0; i<removed.length; i++) {
  11877. if(!(filters[offset][removed[i]] & one)) filters[offset][removed[i]] |= one;
  11878. }
  11879. } else {
  11880. var newAdded = [];
  11881. var newRemoved = [];
  11882. for (i = 0; i < added.length; i++) {
  11883. // First check this particular value needs to be added
  11884. if(iterablesIndexFilterStatus[valueIndexAdded[i]] === 1) {
  11885. iterablesIndexCount[added[i]]++;
  11886. iterablesIndexFilterStatus[valueIndexAdded[i]] = 0;
  11887. if(iterablesIndexCount[added[i]] === 1) {
  11888. filters[offset][added[i]] ^= one;
  11889. newAdded.push(added[i]);
  11890. }
  11891. }
  11892. }
  11893. for (i = 0; i < removed.length; i++) {
  11894. // First check this particular value needs to be removed
  11895. if(iterablesIndexFilterStatus[valueIndexRemoved[i]] === 0) {
  11896. iterablesIndexCount[removed[i]]--;
  11897. iterablesIndexFilterStatus[valueIndexRemoved[i]] = 1;
  11898. if(iterablesIndexCount[removed[i]] === 0) {
  11899. filters[offset][removed[i]] ^= one;
  11900. newRemoved.push(removed[i]);
  11901. }
  11902. }
  11903. }
  11904. added = newAdded;
  11905. removed = newRemoved;
  11906. // Now handle empty rows.
  11907. if(filterAll) {
  11908. for(i = 0; i < iterablesEmptyRows.length; i++) {
  11909. if((filters[offset][k = iterablesEmptyRows[i]] & one)) {
  11910. // Was not in the filter, so set the filter and add
  11911. filters[offset][k] ^= one;
  11912. added.push(k);
  11913. }
  11914. }
  11915. } else {
  11916. // filter in place - remove empty rows if necessary
  11917. for(i = 0; i < iterablesEmptyRows.length; i++) {
  11918. if(!(filters[offset][k = iterablesEmptyRows[i]] & one)) {
  11919. // Was in the filter, so set the filter and remove
  11920. filters[offset][k] ^= one;
  11921. removed.push(k);
  11922. }
  11923. }
  11924. }
  11925. }
  11926. filterListeners.forEach(function(l) { l(one, offset, added, removed); });
  11927. triggerOnChange('filtered');
  11928. }
  11929. function currentFilter() {
  11930. return filterValue;
  11931. }
  11932. function hasCurrentFilter() {
  11933. return filterValuePresent;
  11934. }
  11935. // Returns the top K selected records based on this dimension's order.
  11936. // Note: observes this dimension's filter, unlike group and groupAll.
  11937. function top(k, top_offset) {
  11938. var array = [],
  11939. i = hi0,
  11940. j,
  11941. toSkip = 0;
  11942. if(top_offset && top_offset > 0) toSkip = top_offset;
  11943. while (--i >= lo0 && k > 0) {
  11944. if (filters.zero(j = index[i])) {
  11945. if(toSkip > 0) {
  11946. //skip matching row
  11947. --toSkip;
  11948. } else {
  11949. array.push(data[j]);
  11950. --k;
  11951. }
  11952. }
  11953. }
  11954. if(iterable){
  11955. for(i = 0; i < iterablesEmptyRows.length && k > 0; i++) {
  11956. // Add row with empty iterable column at the end
  11957. if(filters.zero(j = iterablesEmptyRows[i])) {
  11958. if(toSkip > 0) {
  11959. //skip matching row
  11960. --toSkip;
  11961. } else {
  11962. array.push(data[j]);
  11963. --k;
  11964. }
  11965. }
  11966. }
  11967. }
  11968. return array;
  11969. }
  11970. // Returns the bottom K selected records based on this dimension's order.
  11971. // Note: observes this dimension's filter, unlike group and groupAll.
  11972. function bottom(k, bottom_offset) {
  11973. var array = [],
  11974. i,
  11975. j,
  11976. toSkip = 0;
  11977. if(bottom_offset && bottom_offset > 0) toSkip = bottom_offset;
  11978. if(iterable) {
  11979. // Add row with empty iterable column at the top
  11980. for(i = 0; i < iterablesEmptyRows.length && k > 0; i++) {
  11981. if(filters.zero(j = iterablesEmptyRows[i])) {
  11982. if(toSkip > 0) {
  11983. //skip matching row
  11984. --toSkip;
  11985. } else {
  11986. array.push(data[j]);
  11987. --k;
  11988. }
  11989. }
  11990. }
  11991. }
  11992. i = lo0;
  11993. while (i < hi0 && k > 0) {
  11994. if (filters.zero(j = index[i])) {
  11995. if(toSkip > 0) {
  11996. //skip matching row
  11997. --toSkip;
  11998. } else {
  11999. array.push(data[j]);
  12000. --k;
  12001. }
  12002. }
  12003. i++;
  12004. }
  12005. return array;
  12006. }
  12007. // Adds a new group to this dimension, using the specified key function.
  12008. function group(key) {
  12009. var group = {
  12010. top: top,
  12011. all: all,
  12012. reduce: reduce,
  12013. reduceCount: reduceCount,
  12014. reduceSum: reduceSum,
  12015. order: order,
  12016. orderNatural: orderNatural,
  12017. size: size,
  12018. dispose: dispose,
  12019. remove: dispose // for backwards-compatibility
  12020. };
  12021. // Ensure that this group will be removed when the dimension is removed.
  12022. dimensionGroups.push(group);
  12023. var groups, // array of {key, value}
  12024. groupIndex, // object id ↦ group id
  12025. groupWidth = 8,
  12026. groupCapacity = capacity(groupWidth),
  12027. k = 0, // cardinality
  12028. select,
  12029. heap,
  12030. reduceAdd,
  12031. reduceRemove,
  12032. reduceInitial,
  12033. update = cr_null,
  12034. reset = cr_null,
  12035. resetNeeded = true,
  12036. groupAll = key === cr_null,
  12037. n0old;
  12038. if (arguments.length < 1) key = cr_identity;
  12039. // The group listens to the crossfilter for when any dimension changes, so
  12040. // that it can update the associated reduce values. It must also listen to
  12041. // the parent dimension for when data is added, and compute new keys.
  12042. filterListeners.push(update);
  12043. indexListeners.push(add);
  12044. removeDataListeners.push(removeData);
  12045. // Incorporate any existing data into the grouping.
  12046. add(values, index, 0, n);
  12047. // Incorporates the specified new values into this group.
  12048. // This function is responsible for updating groups and groupIndex.
  12049. function add(newValues, newIndex, n0, n1) {
  12050. if(iterable) {
  12051. n0old = n0;
  12052. n0 = values.length - newValues.length;
  12053. n1 = newValues.length;
  12054. }
  12055. var oldGroups = groups,
  12056. reIndex = iterable ? [] : cr_index(k, groupCapacity),
  12057. add = reduceAdd,
  12058. remove = reduceRemove,
  12059. initial = reduceInitial,
  12060. k0 = k, // old cardinality
  12061. i0 = 0, // index of old group
  12062. i1 = 0, // index of new record
  12063. j, // object id
  12064. g0, // old group
  12065. x0, // old key
  12066. x1, // new key
  12067. g, // group to add
  12068. x; // key of group to add
  12069. // If a reset is needed, we don't need to update the reduce values.
  12070. if (resetNeeded) add = initial = cr_null;
  12071. if (resetNeeded) remove = initial = cr_null;
  12072. // Reset the new groups (k is a lower bound).
  12073. // Also, make sure that groupIndex exists and is long enough.
  12074. groups = new Array(k), k = 0;
  12075. if(iterable){
  12076. groupIndex = k0 ? groupIndex : [];
  12077. }
  12078. else {
  12079. groupIndex = k0 > 1 ? xfilterArray.arrayLengthen(groupIndex, n) : cr_index(n, groupCapacity);
  12080. }
  12081. // Get the first old key (x0 of g0), if it exists.
  12082. if (k0) x0 = (g0 = oldGroups[0]).key;
  12083. // Find the first new key (x1), skipping NaN keys.
  12084. while (i1 < n1 && !((x1 = key(newValues[i1])) >= x1)) ++i1;
  12085. // While new keys remain…
  12086. while (i1 < n1) {
  12087. // Determine the lesser of the two current keys; new and old.
  12088. // If there are no old keys remaining, then always add the new key.
  12089. if (g0 && x0 <= x1) {
  12090. g = g0, x = x0;
  12091. // Record the new index of the old group.
  12092. reIndex[i0] = k;
  12093. // Retrieve the next old key.
  12094. g0 = oldGroups[++i0];
  12095. if (g0) x0 = g0.key;
  12096. } else {
  12097. g = {key: x1, value: initial()}, x = x1;
  12098. }
  12099. // Add the lesser group.
  12100. groups[k] = g;
  12101. // Add any selected records belonging to the added group, while
  12102. // advancing the new key and populating the associated group index.
  12103. while (x1 <= x) {
  12104. j = newIndex[i1] + (iterable ? n0old : n0);
  12105. if(iterable){
  12106. if(groupIndex[j]){
  12107. groupIndex[j].push(k);
  12108. }
  12109. else {
  12110. groupIndex[j] = [k];
  12111. }
  12112. }
  12113. else {
  12114. groupIndex[j] = k;
  12115. }
  12116. // Always add new values to groups. Only remove when not in filter.
  12117. // This gives groups full information on data life-cycle.
  12118. g.value = add(g.value, data[j], true);
  12119. if (!filters.zeroExcept(j, offset, zero)) g.value = remove(g.value, data[j], false);
  12120. if (++i1 >= n1) break;
  12121. x1 = key(newValues[i1]);
  12122. }
  12123. groupIncrement();
  12124. }
  12125. // Add any remaining old groups that were greater th1an all new keys.
  12126. // No incremental reduce is needed; these groups have no new records.
  12127. // Also record the new index of the old group.
  12128. while (i0 < k0) {
  12129. groups[reIndex[i0] = k] = oldGroups[i0++];
  12130. groupIncrement();
  12131. }
  12132. // Fill in gaps with empty arrays where there may have been rows with empty iterables
  12133. if(iterable){
  12134. for (var index1 = 0; index1 < n; index1++) {
  12135. if(!groupIndex[index1]){
  12136. groupIndex[index1] = [];
  12137. }
  12138. }
  12139. }
  12140. // If we added any new groups before any old groups,
  12141. // update the group index of all the old records.
  12142. if(k > i0){
  12143. if(iterable){
  12144. for (i0 = 0; i0 < n0old; ++i0) {
  12145. for (index1 = 0; index1 < groupIndex[i0].length; index1++) {
  12146. groupIndex[i0][index1] = reIndex[groupIndex[i0][index1]];
  12147. }
  12148. }
  12149. }
  12150. else {
  12151. for (i0 = 0; i0 < n0; ++i0) {
  12152. groupIndex[i0] = reIndex[groupIndex[i0]];
  12153. }
  12154. }
  12155. }
  12156. // Modify the update and reset behavior based on the cardinality.
  12157. // If the cardinality is less than or equal to one, then the groupIndex
  12158. // is not needed. If the cardinality is zero, then there are no records
  12159. // and therefore no groups to update or reset. Note that we also must
  12160. // change the registered listener to point to the new method.
  12161. j = filterListeners.indexOf(update);
  12162. if (k > 1 || iterable) {
  12163. update = updateMany;
  12164. reset = resetMany;
  12165. } else {
  12166. if (!k && groupAll) {
  12167. k = 1;
  12168. groups = [{key: null, value: initial()}];
  12169. }
  12170. if (k === 1) {
  12171. update = updateOne;
  12172. reset = resetOne;
  12173. } else {
  12174. update = cr_null;
  12175. reset = cr_null;
  12176. }
  12177. groupIndex = null;
  12178. }
  12179. filterListeners[j] = update;
  12180. // Count the number of added groups,
  12181. // and widen the group index as needed.
  12182. function groupIncrement() {
  12183. if(iterable){
  12184. k++;
  12185. return
  12186. }
  12187. if (++k === groupCapacity) {
  12188. reIndex = xfilterArray.arrayWiden(reIndex, groupWidth <<= 1);
  12189. groupIndex = xfilterArray.arrayWiden(groupIndex, groupWidth);
  12190. groupCapacity = capacity(groupWidth);
  12191. }
  12192. }
  12193. }
  12194. function removeData(reIndex) {
  12195. if (k > 1 || iterable) {
  12196. var oldK = k,
  12197. oldGroups = groups,
  12198. seenGroups = cr_index(oldK, oldK),
  12199. i,
  12200. i0,
  12201. j;
  12202. // Filter out non-matches by copying matching group index entries to
  12203. // the beginning of the array.
  12204. if (!iterable) {
  12205. for (i = 0, j = 0; i < n; ++i) {
  12206. if (reIndex[i] !== REMOVED_INDEX) {
  12207. seenGroups[groupIndex[j] = groupIndex[i]] = 1;
  12208. ++j;
  12209. }
  12210. }
  12211. } else {
  12212. for (i = 0, j = 0; i < n; ++i) {
  12213. if (reIndex[i] !== REMOVED_INDEX) {
  12214. groupIndex[j] = groupIndex[i];
  12215. for (i0 = 0; i0 < groupIndex[j].length; i0++) {
  12216. seenGroups[groupIndex[j][i0]] = 1;
  12217. }
  12218. ++j;
  12219. }
  12220. }
  12221. groupIndex = groupIndex.slice(0, j);
  12222. }
  12223. // Reassemble groups including only those groups that were referred
  12224. // to by matching group index entries. Note the new group index in
  12225. // seenGroups.
  12226. groups = [], k = 0;
  12227. for (i = 0; i < oldK; ++i) {
  12228. if (seenGroups[i]) {
  12229. seenGroups[i] = k++;
  12230. groups.push(oldGroups[i]);
  12231. }
  12232. }
  12233. if (k > 1 || iterable) {
  12234. // Reindex the group index using seenGroups to find the new index.
  12235. if (!iterable) {
  12236. for (i = 0; i < j; ++i) groupIndex[i] = seenGroups[groupIndex[i]];
  12237. } else {
  12238. for (i = 0; i < j; ++i) {
  12239. for (i0 = 0; i0 < groupIndex[i].length; ++i0) {
  12240. groupIndex[i][i0] = seenGroups[groupIndex[i][i0]];
  12241. }
  12242. }
  12243. }
  12244. } else {
  12245. groupIndex = null;
  12246. }
  12247. filterListeners[filterListeners.indexOf(update)] = k > 1 || iterable
  12248. ? (reset = resetMany, update = updateMany)
  12249. : k === 1 ? (reset = resetOne, update = updateOne)
  12250. : reset = update = cr_null;
  12251. } else if (k === 1) {
  12252. if (groupAll) return;
  12253. for (var index3 = 0; index3 < n; ++index3) if (reIndex[index3] !== REMOVED_INDEX) return;
  12254. groups = [], k = 0;
  12255. filterListeners[filterListeners.indexOf(update)] =
  12256. update = reset = cr_null;
  12257. }
  12258. }
  12259. // Reduces the specified selected or deselected records.
  12260. // This function is only used when the cardinality is greater than 1.
  12261. // notFilter indicates a crossfilter.add/remove operation.
  12262. function updateMany(filterOne, filterOffset, added, removed, notFilter) {
  12263. if ((filterOne === one && filterOffset === offset) || resetNeeded) return;
  12264. var i,
  12265. j,
  12266. k,
  12267. n,
  12268. g;
  12269. if(iterable){
  12270. // Add the added values.
  12271. for (i = 0, n = added.length; i < n; ++i) {
  12272. if (filters.zeroExcept(k = added[i], offset, zero)) {
  12273. for (j = 0; j < groupIndex[k].length; j++) {
  12274. g = groups[groupIndex[k][j]];
  12275. g.value = reduceAdd(g.value, data[k], false, j);
  12276. }
  12277. }
  12278. }
  12279. // Remove the removed values.
  12280. for (i = 0, n = removed.length; i < n; ++i) {
  12281. if (filters.onlyExcept(k = removed[i], offset, zero, filterOffset, filterOne)) {
  12282. for (j = 0; j < groupIndex[k].length; j++) {
  12283. g = groups[groupIndex[k][j]];
  12284. g.value = reduceRemove(g.value, data[k], notFilter, j);
  12285. }
  12286. }
  12287. }
  12288. return;
  12289. }
  12290. // Add the added values.
  12291. for (i = 0, n = added.length; i < n; ++i) {
  12292. if (filters.zeroExcept(k = added[i], offset, zero)) {
  12293. g = groups[groupIndex[k]];
  12294. g.value = reduceAdd(g.value, data[k], false);
  12295. }
  12296. }
  12297. // Remove the removed values.
  12298. for (i = 0, n = removed.length; i < n; ++i) {
  12299. if (filters.onlyExcept(k = removed[i], offset, zero, filterOffset, filterOne)) {
  12300. g = groups[groupIndex[k]];
  12301. g.value = reduceRemove(g.value, data[k], notFilter);
  12302. }
  12303. }
  12304. }
  12305. // Reduces the specified selected or deselected records.
  12306. // This function is only used when the cardinality is 1.
  12307. // notFilter indicates a crossfilter.add/remove operation.
  12308. function updateOne(filterOne, filterOffset, added, removed, notFilter) {
  12309. if ((filterOne === one && filterOffset === offset) || resetNeeded) return;
  12310. var i,
  12311. k,
  12312. n,
  12313. g = groups[0];
  12314. // Add the added values.
  12315. for (i = 0, n = added.length; i < n; ++i) {
  12316. if (filters.zeroExcept(k = added[i], offset, zero)) {
  12317. g.value = reduceAdd(g.value, data[k], false);
  12318. }
  12319. }
  12320. // Remove the removed values.
  12321. for (i = 0, n = removed.length; i < n; ++i) {
  12322. if (filters.onlyExcept(k = removed[i], offset, zero, filterOffset, filterOne)) {
  12323. g.value = reduceRemove(g.value, data[k], notFilter);
  12324. }
  12325. }
  12326. }
  12327. // Recomputes the group reduce values from scratch.
  12328. // This function is only used when the cardinality is greater than 1.
  12329. function resetMany() {
  12330. var i,
  12331. j,
  12332. g;
  12333. // Reset all group values.
  12334. for (i = 0; i < k; ++i) {
  12335. groups[i].value = reduceInitial();
  12336. }
  12337. // We add all records and then remove filtered records so that reducers
  12338. // can build an 'unfiltered' view even if there are already filters in
  12339. // place on other dimensions.
  12340. if(iterable){
  12341. for (i = 0; i < n; ++i) {
  12342. for (j = 0; j < groupIndex[i].length; j++) {
  12343. g = groups[groupIndex[i][j]];
  12344. g.value = reduceAdd(g.value, data[i], true, j);
  12345. }
  12346. }
  12347. for (i = 0; i < n; ++i) {
  12348. if (!filters.zeroExcept(i, offset, zero)) {
  12349. for (j = 0; j < groupIndex[i].length; j++) {
  12350. g = groups[groupIndex[i][j]];
  12351. g.value = reduceRemove(g.value, data[i], false, j);
  12352. }
  12353. }
  12354. }
  12355. return;
  12356. }
  12357. for (i = 0; i < n; ++i) {
  12358. g = groups[groupIndex[i]];
  12359. g.value = reduceAdd(g.value, data[i], true);
  12360. }
  12361. for (i = 0; i < n; ++i) {
  12362. if (!filters.zeroExcept(i, offset, zero)) {
  12363. g = groups[groupIndex[i]];
  12364. g.value = reduceRemove(g.value, data[i], false);
  12365. }
  12366. }
  12367. }
  12368. // Recomputes the group reduce values from scratch.
  12369. // This function is only used when the cardinality is 1.
  12370. function resetOne() {
  12371. var i,
  12372. g = groups[0];
  12373. // Reset the singleton group values.
  12374. g.value = reduceInitial();
  12375. // We add all records and then remove filtered records so that reducers
  12376. // can build an 'unfiltered' view even if there are already filters in
  12377. // place on other dimensions.
  12378. for (i = 0; i < n; ++i) {
  12379. g.value = reduceAdd(g.value, data[i], true);
  12380. }
  12381. for (i = 0; i < n; ++i) {
  12382. if (!filters.zeroExcept(i, offset, zero)) {
  12383. g.value = reduceRemove(g.value, data[i], false);
  12384. }
  12385. }
  12386. }
  12387. // Returns the array of group values, in the dimension's natural order.
  12388. function all() {
  12389. if (resetNeeded) reset(), resetNeeded = false;
  12390. return groups;
  12391. }
  12392. // Returns a new array containing the top K group values, in reduce order.
  12393. function top(k) {
  12394. var top = select(all(), 0, groups.length, k);
  12395. return heap.sort(top, 0, top.length);
  12396. }
  12397. // Sets the reduce behavior for this group to use the specified functions.
  12398. // This method lazily recomputes the reduce values, waiting until needed.
  12399. function reduce(add, remove, initial) {
  12400. reduceAdd = add;
  12401. reduceRemove = remove;
  12402. reduceInitial = initial;
  12403. resetNeeded = true;
  12404. return group;
  12405. }
  12406. // A convenience method for reducing by count.
  12407. function reduceCount() {
  12408. return reduce(xfilterReduce.reduceIncrement, xfilterReduce.reduceDecrement, cr_zero);
  12409. }
  12410. // A convenience method for reducing by sum(value).
  12411. function reduceSum(value) {
  12412. return reduce(xfilterReduce.reduceAdd(value), xfilterReduce.reduceSubtract(value), cr_zero);
  12413. }
  12414. // Sets the reduce order, using the specified accessor.
  12415. function order(value) {
  12416. select = h.by(valueOf);
  12417. heap = h$1.by(valueOf);
  12418. function valueOf(d) { return value(d.value); }
  12419. return group;
  12420. }
  12421. // A convenience method for natural ordering by reduce value.
  12422. function orderNatural() {
  12423. return order(cr_identity);
  12424. }
  12425. // Returns the cardinality of this group, irrespective of any filters.
  12426. function size() {
  12427. return k;
  12428. }
  12429. // Removes this group and associated event listeners.
  12430. function dispose() {
  12431. var i = filterListeners.indexOf(update);
  12432. if (i >= 0) filterListeners.splice(i, 1);
  12433. i = indexListeners.indexOf(add);
  12434. if (i >= 0) indexListeners.splice(i, 1);
  12435. i = removeDataListeners.indexOf(removeData);
  12436. if (i >= 0) removeDataListeners.splice(i, 1);
  12437. i = dimensionGroups.indexOf(group);
  12438. if (i >= 0) dimensionGroups.splice(i, 1);
  12439. return group;
  12440. }
  12441. return reduceCount().orderNatural();
  12442. }
  12443. // A convenience function for generating a singleton group.
  12444. function groupAll() {
  12445. var g = group(cr_null), all = g.all;
  12446. delete g.all;
  12447. delete g.top;
  12448. delete g.order;
  12449. delete g.orderNatural;
  12450. delete g.size;
  12451. g.value = function() { return all()[0].value; };
  12452. return g;
  12453. }
  12454. // Removes this dimension and associated groups and event listeners.
  12455. function dispose() {
  12456. dimensionGroups.forEach(function(group) { group.dispose(); });
  12457. var i = dataListeners.indexOf(preAdd);
  12458. if (i >= 0) dataListeners.splice(i, 1);
  12459. i = dataListeners.indexOf(postAdd);
  12460. if (i >= 0) dataListeners.splice(i, 1);
  12461. i = removeDataListeners.indexOf(removeData);
  12462. if (i >= 0) removeDataListeners.splice(i, 1);
  12463. filters.masks[offset] &= zero;
  12464. return filterAll();
  12465. }
  12466. return dimension;
  12467. }
  12468. // A convenience method for groupAll on a dummy dimension.
  12469. // This implementation can be optimized since it always has cardinality 1.
  12470. function groupAll() {
  12471. var group = {
  12472. reduce: reduce,
  12473. reduceCount: reduceCount,
  12474. reduceSum: reduceSum,
  12475. value: value,
  12476. dispose: dispose,
  12477. remove: dispose // for backwards-compatibility
  12478. };
  12479. var reduceValue,
  12480. reduceAdd,
  12481. reduceRemove,
  12482. reduceInitial,
  12483. resetNeeded = true;
  12484. // The group listens to the crossfilter for when any dimension changes, so
  12485. // that it can update the reduce value. It must also listen to the parent
  12486. // dimension for when data is added.
  12487. filterListeners.push(update);
  12488. dataListeners.push(add);
  12489. // For consistency; actually a no-op since resetNeeded is true.
  12490. add(data, 0);
  12491. // Incorporates the specified new values into this group.
  12492. function add(newData, n0) {
  12493. var i;
  12494. if (resetNeeded) return;
  12495. // Cycle through all the values.
  12496. for (i = n0; i < n; ++i) {
  12497. // Add all values all the time.
  12498. reduceValue = reduceAdd(reduceValue, data[i], true);
  12499. // Remove the value if filtered.
  12500. if (!filters.zero(i)) {
  12501. reduceValue = reduceRemove(reduceValue, data[i], false);
  12502. }
  12503. }
  12504. }
  12505. // Reduces the specified selected or deselected records.
  12506. function update(filterOne, filterOffset, added, removed, notFilter) {
  12507. var i,
  12508. k,
  12509. n;
  12510. if (resetNeeded) return;
  12511. // Add the added values.
  12512. for (i = 0, n = added.length; i < n; ++i) {
  12513. if (filters.zero(k = added[i])) {
  12514. reduceValue = reduceAdd(reduceValue, data[k], notFilter);
  12515. }
  12516. }
  12517. // Remove the removed values.
  12518. for (i = 0, n = removed.length; i < n; ++i) {
  12519. if (filters.only(k = removed[i], filterOffset, filterOne)) {
  12520. reduceValue = reduceRemove(reduceValue, data[k], notFilter);
  12521. }
  12522. }
  12523. }
  12524. // Recomputes the group reduce value from scratch.
  12525. function reset() {
  12526. var i;
  12527. reduceValue = reduceInitial();
  12528. // Cycle through all the values.
  12529. for (i = 0; i < n; ++i) {
  12530. // Add all values all the time.
  12531. reduceValue = reduceAdd(reduceValue, data[i], true);
  12532. // Remove the value if it is filtered.
  12533. if (!filters.zero(i)) {
  12534. reduceValue = reduceRemove(reduceValue, data[i], false);
  12535. }
  12536. }
  12537. }
  12538. // Sets the reduce behavior for this group to use the specified functions.
  12539. // This method lazily recomputes the reduce value, waiting until needed.
  12540. function reduce(add, remove, initial) {
  12541. reduceAdd = add;
  12542. reduceRemove = remove;
  12543. reduceInitial = initial;
  12544. resetNeeded = true;
  12545. return group;
  12546. }
  12547. // A convenience method for reducing by count.
  12548. function reduceCount() {
  12549. return reduce(xfilterReduce.reduceIncrement, xfilterReduce.reduceDecrement, cr_zero);
  12550. }
  12551. // A convenience method for reducing by sum(value).
  12552. function reduceSum(value) {
  12553. return reduce(xfilterReduce.reduceAdd(value), xfilterReduce.reduceSubtract(value), cr_zero);
  12554. }
  12555. // Returns the computed reduce value.
  12556. function value() {
  12557. if (resetNeeded) reset(), resetNeeded = false;
  12558. return reduceValue;
  12559. }
  12560. // Removes this group and associated event listeners.
  12561. function dispose() {
  12562. var i = filterListeners.indexOf(update);
  12563. if (i >= 0) filterListeners.splice(i, 1);
  12564. i = dataListeners.indexOf(add);
  12565. if (i >= 0) dataListeners.splice(i, 1);
  12566. return group;
  12567. }
  12568. return reduceCount();
  12569. }
  12570. // Returns the number of records in this crossfilter, irrespective of any filters.
  12571. function size() {
  12572. return n;
  12573. }
  12574. // Returns the raw row data contained in this crossfilter
  12575. function all(){
  12576. return data;
  12577. }
  12578. // Returns row data with all dimension filters applied, except for filters in ignore_dimensions
  12579. function allFiltered(ignore_dimensions) {
  12580. var array = [],
  12581. i = 0,
  12582. mask = maskForDimensions(ignore_dimensions || []);
  12583. for (i = 0; i < n; i++) {
  12584. if (filters.zeroExceptMask(i, mask)) {
  12585. array.push(data[i]);
  12586. }
  12587. }
  12588. return array;
  12589. }
  12590. function onChange(cb){
  12591. if(typeof cb !== 'function'){
  12592. /* eslint no-console: 0 */
  12593. console.warn('onChange callback parameter must be a function!');
  12594. return;
  12595. }
  12596. callbacks.push(cb);
  12597. return function(){
  12598. callbacks.splice(callbacks.indexOf(cb), 1);
  12599. };
  12600. }
  12601. function triggerOnChange(eventName){
  12602. for (var i = 0; i < callbacks.length; i++) {
  12603. callbacks[i](eventName);
  12604. }
  12605. }
  12606. return arguments.length
  12607. ? add(arguments[0])
  12608. : crossfilter;
  12609. }
  12610. // Returns an array of size n, big enough to store ids up to m.
  12611. function cr_index(n, m) {
  12612. return (m < 0x101
  12613. ? xfilterArray.array8 : m < 0x10001
  12614. ? xfilterArray.array16
  12615. : xfilterArray.array32)(n);
  12616. }
  12617. // Constructs a new array of size n, with sequential values from 0 to n - 1.
  12618. function cr_range(n) {
  12619. var range = cr_index(n, n);
  12620. for (var i = -1; ++i < n;) range[i] = i;
  12621. return range;
  12622. }
  12623. function capacity(w) {
  12624. return w === 8
  12625. ? 0x100 : w === 16
  12626. ? 0x10000
  12627. : 0x100000000;
  12628. }
  12629. var main = /*#__PURE__*/Object.freeze({
  12630. __proto__: null,
  12631. 'default': crossfilter$1
  12632. });
  12633. var crossfilterreq = /*@__PURE__*/getAugmentedNamespace(main);
  12634. const crossfilter = crossfilterreq.default ? crossfilterreq.default : crossfilterreq;
  12635. // -------------------------------------------------------------------
  12636. // dx = multidimensional Crossfilter = Wrapper for crossfilter
  12637. var dx = {
  12638. indexFns : { id : function (d) { return d.id || "" } }
  12639. , createIndexFn : function(indexFn, dim){
  12640. var indexFns = {
  12641. dim : function(d) { return d[dim] || "" }
  12642. , dimId : function(d) { return d[dim + 'Id'] || "" }
  12643. };
  12644. if(Object.prototype.toString.call(indexFn) === '[object Function]' ) return indexFn;
  12645. if(indexFn) return function(d) { return d[indexFn] || "" } // Assume its the column name on the data.
  12646. indexFn = function(d){
  12647. // First time execution detects key to use. We try [dim] then[{{dim}}Id] then [id]
  12648. // This is though dangerous if first item has missing data i.e. d[dim] is undefined even though other rows have d[dim]
  12649. console.error('default generated indexFn on non existence of model property is dangerous.');
  12650. indexFn = d[dim] ? indexFns['dim'] : d[dim + 'Id'] ? indexFns['dimId'] : dx.indexFns['id'];
  12651. dx.indexFns['id'] === indexFn ? console.error('Warning : dimension name not found. Using id as default is not recommended.') : null;
  12652. // Since we were called after the dimension processing has started we will continue to get called until each item is processed.
  12653. // We therefore switch the function that will get called from next time onwards.
  12654. return indexFn(d); //
  12655. };
  12656. return function(d){ return indexFn(d) }
  12657. }
  12658. , filter : function(filter, dim){
  12659. // Note : Ensure that the filter function that you pass in is the same function object. This is the only way to prevent bloat.
  12660. if(!filter) { console.warn('Useless call to filter without a real filter.'); return;} // All filters should already be in place since we are stateful.
  12661. var filterable = dim ? this.dims[dim] : this;
  12662. // Filters are shared between master and dimension on data.
  12663. if(!filterable.wkFilters.get(filter)) {
  12664. filterable.wkFilters.set(filter, true);
  12665. filterable.filters.push(filter); // PB : Note -- Push unique distinct filters ! This will bloat if duplicates are pushed.
  12666. }
  12667. // PB : TODO -- Check CF may not re-evaluate filters if it detects no change in filter.
  12668. if(filterable.dxFd){
  12669. // This is a master dim with attached fact dimension. this.model should give us the column name on the fact data.
  12670. filterable.dxFd.filter( filterable.__filter );
  12671. }
  12672. filterable.dxF.filter(filterable.__filter);
  12673. // If it does re-evaluate following cascade code is not required.
  12674. // Cascade to all nested dimensions which are implicitly bound.
  12675. // Object.keys(specs.dims).forEach((dim)=>{
  12676. // this.dims[dim].dxF.filter( this.dims[dim].__filter )
  12677. // })
  12678. // Handle other custom bound Dimensions on this dimension.
  12679. // Master and Data crossfilters are implicitly bound.
  12680. // this.dims[dim].dxFm ? this.dims[dim].dxFm.filter( this.dims[dim].__filter ) : null;
  12681. // this.dims[dim].dxFd ? this.dims[dim].dxFd.filter( this.dims[dim].__filter ) : null;
  12682. }
  12683. , filterAll : function(dim){
  12684. var filterable = dim ? this.dims[dim] : this;
  12685. if(filterable.dxFd){
  12686. // This is a master dim with attached fact dimension. this.model should give us the column name on the fact data.
  12687. filterable.dxFd.filterAll();
  12688. }
  12689. filterable.dxF.filterAll( );
  12690. // Cascade to all nested dimensions.
  12691. // Object.keys(specs.dims).forEach((dim)=>{
  12692. // specs[dim][dx] = specs[dim].data ? dx.create( specs[dim] ) : null;
  12693. // dx.__createPairedDx(specs, dim);
  12694. // })
  12695. }
  12696. , addFilter : function(filter, dim) {
  12697. dim = dim || 'id';
  12698. this.dims[dim].filters.push(filter);
  12699. }
  12700. , __initDim : function(oDim){
  12701. var __filter = function(d){
  12702. for(var f=0; f < oDim.filters.length; f++) {
  12703. // Filter function will be called on the dimension.
  12704. // PB : TODO accept any scope instead of only the dimension.
  12705. if(!oDim.filters[f].call(oDim, d)) return false;
  12706. }
  12707. return true;
  12708. };
  12709. return oDim ? (()=>{
  12710. oDim.wkFilters = new(WeakMap);
  12711. oDim.filters = []; oDim.__filter = __filter;
  12712. return oDim
  12713. })()
  12714. : { wkFilters : new(WeakMap), filters : [], __filter : __filter }
  12715. }
  12716. , __createPairedDx : function(specs, dim, idxFn){
  12717. var oDim = dim === 'id' ? specs : specs.dims[dim];
  12718. idxFn = idxFn || dx.createIndexFn(oDim.indexFn, dim);
  12719. oDim.dxU = specs.ndxU.dimension( idxFn );
  12720. oDim.dxF = specs.ndxF.dimension( idxFn );
  12721. }
  12722. , create : function( specs ){
  12723. specs.ndxF = crossfilter(specs.data);
  12724. specs.ndxU = crossfilter(specs.data);
  12725. // specs.dims ? null : specs.dims = { 'id' : null }
  12726. // specs.dims['id'] = dx.__initDim(specs.dims['id'])
  12727. dx.__initDim(specs); // id Dimension is merged with dx itself. Other dimensions will be found in dims.
  12728. dx.__createPairedDx(specs, 'id', dx.indexFns.id);
  12729. specs.dims ? Object.keys(specs.dims).forEach((dim)=>{
  12730. specs.dims[dim].data ? (()=>{
  12731. // We have some master data for this dimension.
  12732. dx.create( specs.dims[dim] );
  12733. // PB : TODO -- We should probably bind the an array dx's ...
  12734. // Eg: An array of master dx's for a fact dx...
  12735. // i.e specs.bound = [ dx1 = practitioner, dx2 = xyz etc...]
  12736. })()
  12737. : dx.__initDim(specs.dims[dim]);
  12738. var idxFn = dx.createIndexFn(specs.dims[dim].indexFn, dim);
  12739. specs.dims[dim].dxFd = specs.ndxF.dimension( idxFn );
  12740. specs.dims[dim].dxUd = specs.ndxU.dimension( idxFn );
  12741. }) : null;
  12742. specs.filter = this.filter;
  12743. specs.filterAll = this.filterAll;
  12744. return specs;
  12745. }
  12746. // , exclude : ( dxU, dxF, filterFn )=>{
  12747. // // Excludes filtered from unfiltered.
  12748. // var filterFn = null;
  12749. // if(this.get('selected_doctor.id')) {
  12750. // }
  12751. // else {
  12752. // var __inclusions = [];
  12753. // var __exclusions = [];
  12754. // practitionersDimUnfiltered.top(Infinity).forEach((availablePractitioner)=>{
  12755. // // Per Doc
  12756. // ndxFiltered.filterAll()
  12757. // practitionersDimFiltered.filter(availablePractitioner.id);
  12758. // var freeTimes = getFreeTimes(tRange, practitionersDimFiltered);
  12759. // if(freeTimes.length > 0) { /*available*/
  12760. // __inclusions.push(availablePractitioner) }
  12761. // else {
  12762. // __exclusions.push(availablePractitioner)
  12763. // }
  12764. // })
  12765. // filterFn = ()=> { return ((inclusions, exclusions)=>{
  12766. // for(var f in filters) {
  12767. // if(!filters[f]) return false;
  12768. // }
  12769. // return true;
  12770. // })(__inclusions, __exclusions) } ;
  12771. // practitionersDimFiltered.filter(filterFn);
  12772. // }
  12773. // return filterFn;
  12774. // }
  12775. };
  12776. var dx_1 = dx;
  12777. var commonmasks = {
  12778. "bed":{
  12779. "wards":{
  12780. "Bone Marrow Transplantation Unit":{
  12781. "title":"Bone Marrow Transplantation Unit",
  12782. "v1wardId":"BMTU",
  12783. "mask":"1"
  12784. },
  12785. "BRB (Birthing Room A-Big)":{
  12786. "title":"BRB (Birthing Room A-Big)",
  12787. "v1wardId":"BRB",
  12788. "mask":"2"
  12789. },
  12790. "BRSP (Birthing Room-Special Private Ward)":{
  12791. "title":"BRSP (Birthing Room-Special Private Ward)",
  12792. "v1wardId":"BRSP",
  12793. "mask":"4"
  12794. },
  12795. "CCU (Coronary Care Unit)":{
  12796. "title":"CCU (Coronary Care Unit)",
  12797. "v1wardId":"CCU",
  12798. "mask":"8"
  12799. },
  12800. "Chemotherapy Unit":{
  12801. "title":"Chemotherapy Unit",
  12802. "v1wardId":"CHEMOTHERAPY",
  12803. "mask":"16"
  12804. },
  12805. "High Intensive Care Unit":{
  12806. "title":"High Intensive Care Unit",
  12807. "v1wardId":"HICU",
  12808. "mask":"32"
  12809. },
  12810. "ICU (Intensive Care Unit )":{
  12811. "title":"ICU (Intensive Care Unit )",
  12812. "v1wardId":"ICU",
  12813. "mask":"64"
  12814. },
  12815. "Labour Room A":{
  12816. "title":"Labour Room A",
  12817. "v1wardId":"LDPRA",
  12818. "mask":"128"
  12819. },
  12820. "Labour Room B":{
  12821. "title":"Labour Room B",
  12822. "v1wardId":"LDPRB",
  12823. "mask":"256"
  12824. },
  12825. "LLC Covid Ward":{
  12826. "title":"LLC Covid Ward",
  12827. "v1wardId":"LLCCOVIDWARD",
  12828. "mask":"512"
  12829. },
  12830. "Mortury":{
  12831. "title":"Mortury",
  12832. "v1wardId":"MORTURY",
  12833. "mask":"1024"
  12834. },
  12835. "NCU (Neonetal Care Unit)":{
  12836. "title":"NCU (Neonetal Care Unit)",
  12837. "v1wardId":"NCU",
  12838. "mask":"2048"
  12839. },
  12840. "Neonatal Intensive Care unit2":{
  12841. "title":"Neonatal Intensive Care unit2",
  12842. "v1wardId":"NICU2",
  12843. "mask":"4096"
  12844. },
  12845. "Operation Theatre":{
  12846. "title":"Operation Theatre",
  12847. "v1wardId":"OT",
  12848. "mask":"8192"
  12849. },
  12850. "Patient Parking Area":{
  12851. "title":"Patient Parking Area",
  12852. "v1wardId":"PARKING",
  12853. "mask":"16384"
  12854. },
  12855. "PCU (Peadiatric Care Unit)":{
  12856. "title":"PCU (Peadiatric Care Unit)",
  12857. "v1wardId":"PCU",
  12858. "mask":"32768"
  12859. },
  12860. "Private Ward":{
  12861. "title":"Private Ward",
  12862. "v1wardId":"PVTWARD",
  12863. "mask":"65536"
  12864. },
  12865. "SPPVT (Special Private)":{
  12866. "title":"SPPVT (Special Private)",
  12867. "v1wardId":"SPLPVT",
  12868. "mask":"131072"
  12869. },
  12870. "Special Private":{
  12871. "title":"Special Private",
  12872. "v1wardId":"SPPVT",
  12873. "mask":"262144"
  12874. },
  12875. "Wing 01-Female":{
  12876. "title":"Wing 01-Female",
  12877. "v1wardId":"W1FEMALE",
  12878. "mask":"524288"
  12879. },
  12880. "Wing 01-Maternity":{
  12881. "title":"Wing 01-Maternity",
  12882. "v1wardId":"W1MATERNITY",
  12883. "mask":"1048576"
  12884. },
  12885. "Wing 01-SP":{
  12886. "title":"Wing 01-SP",
  12887. "v1wardId":"W1SEMIPRIVATE",
  12888. "mask":"2097152"
  12889. },
  12890. "Wing 02-Female":{
  12891. "title":"Wing 02-Female",
  12892. "v1wardId":"WING02",
  12893. "mask":"4194304"
  12894. },
  12895. "Wing 02-Paediatric":{
  12896. "title":"Wing 02-Paediatric",
  12897. "v1wardId":"WING02PED",
  12898. "mask":"8388608"
  12899. },
  12900. "Wing 03":{
  12901. "title":"Wing 03",
  12902. "v1wardId":"WING03",
  12903. "mask":"16777216"
  12904. },
  12905. "Wing 04":{
  12906. "title":"Wing 04",
  12907. "v1wardId":"WING04",
  12908. "mask":"33554432"
  12909. },
  12910. "Wing 05":{
  12911. "title":"Wing 05",
  12912. "v1wardId":"WING05",
  12913. "mask":"67108864"
  12914. },
  12915. "Wing 06":{
  12916. "title":"Wing 06",
  12917. "v1wardId":"WING06",
  12918. "mask":"134217728"
  12919. },
  12920. "PVTWR (Private Wad)":{
  12921. "title":"PVTWR (Private Wad)",
  12922. "v1wardId":"WINGPC",
  12923. "read":4,
  12924. "write":4,
  12925. "mask":"268435456"
  12926. },
  12927. "Inactive":{
  12928. "title":"Inactive",
  12929. "v1wardId":"Inactive",
  12930. "mask":"536870912"
  12931. }
  12932. },
  12933. "bedclassifications":{
  12934. "Bassinet":{
  12935. "v1bedclassificationId":"BNT",
  12936. "title":"Bassinet",
  12937. "category":"Ward Type",
  12938. "read":4,
  12939. "write":4,
  12940. "mask":"1"
  12941. },
  12942. "Birthing Room":{
  12943. "v1bedclassificationId":"BRB",
  12944. "title":"Birthing Room",
  12945. "category":"Ward Type",
  12946. "mask":"2"
  12947. },
  12948. "Casualty":{
  12949. "v1bedclassificationId":"CASUALTY",
  12950. "title":"Casualty",
  12951. "category":"Ward Type",
  12952. "mask":"4"
  12953. },
  12954. "Coronary Care Unit":{
  12955. "v1bedclassificationId":"CCU",
  12956. "title":"Coronary Care Unit",
  12957. "category":"Ward Type",
  12958. "mask":"8"
  12959. },
  12960. "Chemotherapy":{
  12961. "v1bedclassificationId":"CHEMO",
  12962. "title":"Chemotherapy",
  12963. "category":"Ward Type",
  12964. "mask":"16"
  12965. },
  12966. "Day Care":{
  12967. "v1bedclassificationId":"DAYCAR",
  12968. "title":"Day Care",
  12969. "category":"Ward Type",
  12970. "mask":"32"
  12971. },
  12972. "Geriatric":{
  12973. "v1bedclassificationId":"GER",
  12974. "title":"Geriatric",
  12975. "category":"Ward Type",
  12976. "mask":"64"
  12977. },
  12978. "Labour Room":{
  12979. "v1bedclassificationId":"LBR",
  12980. "title":"Labour Room",
  12981. "category":"Ward Type",
  12982. "mask":"128"
  12983. },
  12984. "High Dependency Care Unit":{
  12985. "v1bedclassificationId":"HDU",
  12986. "title":"High Dependency Care Unit",
  12987. "category":"Ward Type",
  12988. "mask":"256"
  12989. },
  12990. "Intensive Care Unit":{
  12991. "v1bedclassificationId":"Intensive Care Unit",
  12992. "title":"Intensive Care Unit",
  12993. "category":"Ward Type",
  12994. "mask":"512"
  12995. },
  12996. "High Risk Labour Room":{
  12997. "v1bedclassificationId":"HRLBR",
  12998. "title":"High Risk Labour Room",
  12999. "category":"Ward Type",
  13000. "mask":"1024"
  13001. },
  13002. "High Intensive Care Unit":{
  13003. "v1bedclassificationId":"HICU",
  13004. "title":"High Intensive Care Unit",
  13005. "category":"Ward Type",
  13006. "mask":"2048"
  13007. },
  13008. "Neonatal Intensive Care Unit":{
  13009. "v1bedclassificationId":"NCU",
  13010. "title":"Neonatal Intensive Care Unit",
  13011. "category":"Ward Type",
  13012. "mask":"4096"
  13013. },
  13014. "Paediatric Intensive Care Unit":{
  13015. "v1bedclassificationId":"PCU",
  13016. "title":"Paediatric Intensive Care Unit",
  13017. "category":"Ward Type",
  13018. "mask":"8192"
  13019. },
  13020. "With TV":{
  13021. "v1bedclassificationId":"WTV",
  13022. "title":"With TV",
  13023. "category":"Amenities",
  13024. "mask":"16384"
  13025. },
  13026. "With AC":{
  13027. "v1bedclassificationId":"WAC",
  13028. "title":"With AC",
  13029. "category":"Amenities",
  13030. "mask":"32768"
  13031. },
  13032. "General Semi Private":{
  13033. "v1bedclassificationId":"GSP",
  13034. "title":"General Semi Private",
  13035. "category":"Bill Category",
  13036. "mask":"65536"
  13037. },
  13038. "General":{
  13039. "v1bedclassificationId":"GEN",
  13040. "title":"General",
  13041. "category":"Bill Category",
  13042. "mask":"131072"
  13043. },
  13044. "Private":{
  13045. "v1bedclassificationId":"PVT",
  13046. "title":"Private",
  13047. "category":"Bill Category",
  13048. "mask":"262144"
  13049. },
  13050. "Delux":{
  13051. "v1bedclassificationId":"DLX",
  13052. "title":"Delux",
  13053. "category":"Bill Category",
  13054. "mask":"524288"
  13055. },
  13056. "VIP":{
  13057. "v1bedclassificationId":"VIP",
  13058. "title":"VIP",
  13059. "category":"Bed Type",
  13060. "read":4,
  13061. "write":4,
  13062. "mask":"1048576"
  13063. },
  13064. "Regular":{
  13065. "v1bedclassificationId":"Regular",
  13066. "title":"Regular",
  13067. "category":"Bed Type",
  13068. "read":4,
  13069. "write":4,
  13070. "mask":"2097152"
  13071. },
  13072. "Premium Economy":{
  13073. "v1bedclassificationId":"Premium Economy",
  13074. "title":"Premium Economy",
  13075. "category":"Bed Type",
  13076. "read":4,
  13077. "write":4,
  13078. "mask":"4194304"
  13079. },
  13080. "Economy":{
  13081. "v1bedclassificationId":"Economy",
  13082. "title":"Economy",
  13083. "category":"Bed Type",
  13084. "read":4,
  13085. "write":4,
  13086. "mask":"8388608"
  13087. },
  13088. "Full room":{
  13089. "v1bedclassificationId":"FULL",
  13090. "title":"Full room",
  13091. "category":"Bed Type",
  13092. "read":4,
  13093. "write":4,
  13094. "mask":"16777216"
  13095. },
  13096. "Triple Share":{
  13097. "v1bedclassificationId":"TIO",
  13098. "title":"Triple Share",
  13099. "category":"Bed Type",
  13100. "read":4,
  13101. "write":4,
  13102. "mask":"33554432"
  13103. },
  13104. "Twin Share":{
  13105. "v1bedclassificationId":"TWIN",
  13106. "title":"Twin Share",
  13107. "category":"Bed Type",
  13108. "read":4,
  13109. "write":4,
  13110. "mask":"67108864"
  13111. },
  13112. "Special Private":{
  13113. "v1bedclassificationId":"SPPVT",
  13114. "title":"Special Private",
  13115. "category":"Bill Category",
  13116. "mask":"134217728"
  13117. },
  13118. "Male":{
  13119. "v1bedclassificationId":"MALE",
  13120. "title":"Male",
  13121. "read":4,
  13122. "category":"Gender Type",
  13123. "mask":"268435456"
  13124. },
  13125. "Female":{
  13126. "v1bedclassificationId":"FEMALE",
  13127. "title":"Female",
  13128. "read":4,
  13129. "category":"Gender Type",
  13130. "mask":"536870912"
  13131. },
  13132. "Other":{
  13133. "v1bedclassificationId":"OTHGEN",
  13134. "title":"Other",
  13135. "read":4,
  13136. "category":"Gender Type",
  13137. "mask":"1073741824"
  13138. },
  13139. "Adult":{
  13140. "v1bedclassificationId":"ADLT",
  13141. "title":"Adult",
  13142. "category":"Age Based",
  13143. "mask":"2147483648"
  13144. },
  13145. "Paediatric":{
  13146. "v1bedclassificationId":"PAD",
  13147. "title":"Paediatric",
  13148. "category":"Age Based",
  13149. "mask":"4294967296"
  13150. },
  13151. "Neonatal":{
  13152. "v1bedclassificationId":"NEO",
  13153. "title":"Neonatal",
  13154. "category":"Age Based",
  13155. "mask":"8589934592"
  13156. },
  13157. "Admissible Bed":{
  13158. "v1bedclassificationId":"ADM",
  13159. "title":"Admissible Bed",
  13160. "category":"Admissible Category",
  13161. "read":4,
  13162. "write":4,
  13163. "mask":"17179869184"
  13164. },
  13165. "Non Admissible Bed":{
  13166. "v1bedclassificationId":"NAADM",
  13167. "title":"Non Admissible Bed",
  13168. "category":"Admissible Category",
  13169. "read":4,
  13170. "write":4,
  13171. "mask":"34359738368"
  13172. },
  13173. "Limited Admissible Bed":{
  13174. "v1bedclassificationId":"LMADM",
  13175. "title":"Limited Admissible Bed",
  13176. "category":"Admissible Category",
  13177. "read":4,
  13178. "write":4,
  13179. "mask":"68719476736"
  13180. },
  13181. "Infected":{
  13182. "v1bedclassificationId":"INFECTED",
  13183. "title":"Infected",
  13184. "category":"Clinical",
  13185. "read":8,
  13186. "write":8,
  13187. "mask":"137438953472"
  13188. },
  13189. "Clean":{
  13190. "v1bedclassificationId":"CLEAN",
  13191. "title":"Clean",
  13192. "category":"Clinical",
  13193. "read":8,
  13194. "write":8,
  13195. "mask":"274877906944"
  13196. },
  13197. "Isolation":{
  13198. "v1bedclassificationId":"ISOLATION",
  13199. "title":"Isolation",
  13200. "category":"Clinical",
  13201. "read":8,
  13202. "write":8,
  13203. "mask":"549755813888"
  13204. },
  13205. "Ward":{
  13206. "v1bedclassificationId":"Ward",
  13207. "title":"Ward",
  13208. "category":"Uncategorized",
  13209. "read":4,
  13210. "write":4,
  13211. "mask":"1099511627776"
  13212. },
  13213. "ICU":{
  13214. "v1bedclassificationId":"ICU",
  13215. "title":"ICU",
  13216. "category":"Uncategorized",
  13217. "read":4,
  13218. "write":4,
  13219. "mask":"2199023255552"
  13220. },
  13221. "Inactive":{
  13222. "title":"Inactive",
  13223. "v1bedclassificationId":"Inactive",
  13224. "read":4,
  13225. "write":4,
  13226. "mask":"4398046511104"
  13227. }
  13228. },
  13229. "bedoccupancyclassifications":{
  13230. "Bassinet":{
  13231. "v1bedclassificationId":"BNT",
  13232. "title":"Bassinet",
  13233. "category":"Ward Type",
  13234. "read":4,
  13235. "write":4,
  13236. "mask":"1"
  13237. },
  13238. "Birthing Room":{
  13239. "v1bedclassificationId":"BRB",
  13240. "title":"Birthing Room",
  13241. "category":"Ward Type",
  13242. "mask":"2"
  13243. },
  13244. "Casualty":{
  13245. "v1bedclassificationId":"CASUALTY",
  13246. "title":"Casualty",
  13247. "category":"Ward Type",
  13248. "mask":"4"
  13249. },
  13250. "Coronary Care Unit":{
  13251. "v1bedclassificationId":"CCU",
  13252. "title":"Coronary Care Unit",
  13253. "category":"Ward Type",
  13254. "mask":"8"
  13255. },
  13256. "Chemotherapy":{
  13257. "v1bedclassificationId":"CHEMO",
  13258. "title":"Chemotherapy",
  13259. "category":"Ward Type",
  13260. "mask":"16"
  13261. },
  13262. "Day Care":{
  13263. "v1bedclassificationId":"DAYCAR",
  13264. "title":"Day Care",
  13265. "category":"Ward Type",
  13266. "mask":"32"
  13267. },
  13268. "Geriatric":{
  13269. "v1bedclassificationId":"GER",
  13270. "title":"Geriatric",
  13271. "category":"Ward Type",
  13272. "mask":"64"
  13273. },
  13274. "Labour Room":{
  13275. "v1bedclassificationId":"LBR",
  13276. "title":"Labour Room",
  13277. "category":"Ward Type",
  13278. "mask":"128"
  13279. },
  13280. "High Dependency Care Unit":{
  13281. "v1bedclassificationId":"HDU",
  13282. "title":"High Dependency Care Unit",
  13283. "category":"Ward Type",
  13284. "mask":"256"
  13285. },
  13286. "Intensive Care Unit":{
  13287. "v1bedclassificationId":"Intensive Care Unit",
  13288. "title":"Intensive Care Unit",
  13289. "category":"Ward Type",
  13290. "mask":"512"
  13291. },
  13292. "High Risk Labour Room":{
  13293. "v1bedclassificationId":"HRLBR",
  13294. "title":"High Risk Labour Room",
  13295. "category":"Ward Type",
  13296. "mask":"1024"
  13297. },
  13298. "High Intensive Care Unit":{
  13299. "v1bedclassificationId":"HICU",
  13300. "title":"High Intensive Care Unit",
  13301. "category":"Ward Type",
  13302. "mask":"2048"
  13303. },
  13304. "Neonatal Intensive Care Unit":{
  13305. "v1bedclassificationId":"NCU",
  13306. "title":"Neonatal Intensive Care Unit",
  13307. "category":"Ward Type",
  13308. "mask":"4096"
  13309. },
  13310. "Paediatric Intensive Care Unit":{
  13311. "v1bedclassificationId":"PCU",
  13312. "title":"Paediatric Intensive Care Unit",
  13313. "category":"Ward Type",
  13314. "mask":"8192"
  13315. },
  13316. "With TV":{
  13317. "v1bedclassificationId":"WTV",
  13318. "title":"With TV",
  13319. "category":"Amenities",
  13320. "mask":"16384"
  13321. },
  13322. "With AC":{
  13323. "v1bedclassificationId":"WAC",
  13324. "title":"With AC",
  13325. "category":"Amenities",
  13326. "mask":"32768"
  13327. },
  13328. "General Semi Private":{
  13329. "v1bedclassificationId":"GSP",
  13330. "title":"General Semi Private",
  13331. "category":"Bill Category",
  13332. "mask":"65536"
  13333. },
  13334. "General":{
  13335. "v1bedclassificationId":"GEN",
  13336. "title":"General",
  13337. "category":"Bill Category",
  13338. "mask":"131072"
  13339. },
  13340. "Private":{
  13341. "v1bedclassificationId":"PVT",
  13342. "title":"Private",
  13343. "category":"Bill Category",
  13344. "mask":"262144"
  13345. },
  13346. "Delux":{
  13347. "v1bedclassificationId":"DLX",
  13348. "title":"Delux",
  13349. "category":"Bill Category",
  13350. "mask":"524288"
  13351. },
  13352. "VIP":{
  13353. "v1bedclassificationId":"VIP",
  13354. "title":"VIP",
  13355. "category":"Bed Type",
  13356. "read":4,
  13357. "write":4,
  13358. "mask":"1048576"
  13359. },
  13360. "Regular":{
  13361. "v1bedclassificationId":"Regular",
  13362. "title":"Regular",
  13363. "category":"Bed Type",
  13364. "read":4,
  13365. "write":4,
  13366. "mask":"2097152"
  13367. },
  13368. "Premium Economy":{
  13369. "v1bedclassificationId":"Premium Economy",
  13370. "title":"Premium Economy",
  13371. "category":"Bed Type",
  13372. "read":4,
  13373. "write":4,
  13374. "mask":"4194304"
  13375. },
  13376. "Economy":{
  13377. "v1bedclassificationId":"Economy",
  13378. "title":"Economy",
  13379. "category":"Bed Type",
  13380. "read":4,
  13381. "write":4,
  13382. "mask":"8388608"
  13383. },
  13384. "Full room":{
  13385. "v1bedclassificationId":"FULL",
  13386. "title":"Full room",
  13387. "category":"Bed Type",
  13388. "read":4,
  13389. "write":4,
  13390. "mask":"16777216"
  13391. },
  13392. "Triple Share":{
  13393. "v1bedclassificationId":"TIO",
  13394. "title":"Triple Share",
  13395. "category":"Bed Type",
  13396. "read":4,
  13397. "write":4,
  13398. "mask":"33554432"
  13399. },
  13400. "Twin Share":{
  13401. "v1bedclassificationId":"TWIN",
  13402. "title":"Twin Share",
  13403. "category":"Bed Type",
  13404. "read":4,
  13405. "write":4,
  13406. "mask":"67108864"
  13407. },
  13408. "Special Private":{
  13409. "v1bedclassificationId":"SPPVT",
  13410. "title":"Special Private",
  13411. "category":"Bill Category",
  13412. "mask":"134217728"
  13413. },
  13414. "Male":{
  13415. "v1bedclassificationId":"MALE",
  13416. "title":"Male",
  13417. "read":4,
  13418. "category":"Gender Type",
  13419. "mask":"268435456"
  13420. },
  13421. "Female":{
  13422. "v1bedclassificationId":"FEMALE",
  13423. "title":"Female",
  13424. "read":4,
  13425. "category":"Gender Type",
  13426. "mask":"536870912"
  13427. },
  13428. "Other":{
  13429. "v1bedclassificationId":"OTHGEN",
  13430. "title":"Other",
  13431. "read":4,
  13432. "category":"Gender Type",
  13433. "mask":"1073741824"
  13434. },
  13435. "Adult":{
  13436. "v1bedclassificationId":"ADLT",
  13437. "title":"Adult",
  13438. "category":"Age Based",
  13439. "mask":"2147483648"
  13440. },
  13441. "Paediatric":{
  13442. "v1bedclassificationId":"PAD",
  13443. "title":"Paediatric",
  13444. "category":"Age Based",
  13445. "mask":"4294967296"
  13446. },
  13447. "Neonatal":{
  13448. "v1bedclassificationId":"NEO",
  13449. "title":"Neonatal",
  13450. "category":"Age Based",
  13451. "mask":"8589934592"
  13452. },
  13453. "Admissible Bed":{
  13454. "v1bedclassificationId":"ADM",
  13455. "title":"Admissible Bed",
  13456. "category":"Admissible Category",
  13457. "read":4,
  13458. "write":4,
  13459. "mask":"17179869184"
  13460. },
  13461. "Non Admissible Bed":{
  13462. "v1bedclassificationId":"NAADM",
  13463. "title":"Non Admissible Bed",
  13464. "category":"Admissible Category",
  13465. "read":4,
  13466. "write":4,
  13467. "mask":"34359738368"
  13468. },
  13469. "Limited Admissible Bed":{
  13470. "v1bedclassificationId":"LMADM",
  13471. "title":"Limited Admissible Bed",
  13472. "category":"Admissible Category",
  13473. "read":4,
  13474. "write":4,
  13475. "mask":"68719476736"
  13476. },
  13477. "Infected":{
  13478. "v1bedclassificationId":"INFECTED",
  13479. "title":"Infected",
  13480. "category":"Clinical",
  13481. "read":8,
  13482. "write":8,
  13483. "mask":"137438953472"
  13484. },
  13485. "Clean":{
  13486. "v1bedclassificationId":"CLEAN",
  13487. "title":"Clean",
  13488. "category":"Clinical",
  13489. "read":8,
  13490. "write":8,
  13491. "mask":"274877906944"
  13492. },
  13493. "Isolation":{
  13494. "v1bedclassificationId":"ISOLATION",
  13495. "title":"Isolation",
  13496. "category":"Clinical",
  13497. "read":8,
  13498. "write":8,
  13499. "mask":"549755813888"
  13500. },
  13501. "Ward":{
  13502. "v1bedclassificationId":"Ward",
  13503. "title":"Ward",
  13504. "category":"Uncategorized",
  13505. "read":4,
  13506. "write":4,
  13507. "mask":"1099511627776"
  13508. },
  13509. "ICU":{
  13510. "v1bedclassificationId":"ICU",
  13511. "title":"ICU",
  13512. "category":"Uncategorized",
  13513. "read":4,
  13514. "write":4,
  13515. "mask":"2199023255552"
  13516. },
  13517. "Inactive":{
  13518. "title":"Inactive",
  13519. "v1bedclassificationId":"Inactive",
  13520. "read":4,
  13521. "write":4,
  13522. "mask":"4398046511104"
  13523. }
  13524. }
  13525. },
  13526. "dentalmr":{
  13527. "habits":{
  13528. "Chewing":{
  13529. "title":"Chewing",
  13530. "mask":"1"
  13531. },
  13532. "Smoking":{
  13533. "title":"Smoking",
  13534. "mask":"2"
  13535. },
  13536. "Alchohol":{
  13537. "title":"Alchohol",
  13538. "mask":"4"
  13539. },
  13540. "Other":{
  13541. "title":"Other",
  13542. "mask":"8"
  13543. }
  13544. },
  13545. "oralhygienestatuses":{
  13546. "Calculus":{
  13547. "title":"Calculus",
  13548. "mask":"1"
  13549. },
  13550. "Strain":{
  13551. "title":"Strain",
  13552. "mask":"2"
  13553. },
  13554. "Debris":{
  13555. "title":"Debris",
  13556. "mask":"4"
  13557. },
  13558. "Sub-gingival-calculus":{
  13559. "title":"Sub-gingival-calculus",
  13560. "mask":"8"
  13561. }
  13562. },
  13563. "periodontiums":{
  13564. "Mobility":{
  13565. "title":"Mobility",
  13566. "mask":"1"
  13567. },
  13568. "GR":{
  13569. "title":"GR",
  13570. "mask":"2"
  13571. },
  13572. "PP":{
  13573. "title":"PP",
  13574. "mask":"4"
  13575. },
  13576. "BOP":{
  13577. "title":"BOP",
  13578. "mask":"8"
  13579. },
  13580. "Gingival-inflamation":{
  13581. "title":"Gingival-inflamation",
  13582. "mask":"16"
  13583. }
  13584. },
  13585. "abbreviations":{
  13586. "AA":{
  13587. "title":"AA",
  13588. "mask":"1"
  13589. },
  13590. "AS#":{
  13591. "title":"AS#",
  13592. "mask":"2"
  13593. },
  13594. "AP#":{
  13595. "title":"AP#",
  13596. "mask":"4"
  13597. },
  13598. "AV":{
  13599. "title":"AV",
  13600. "mask":"8"
  13601. },
  13602. "BoP":{
  13603. "title":"BoP",
  13604. "mask":"16"
  13605. },
  13606. "MA":{
  13607. "title":"MA",
  13608. "mask":"32"
  13609. },
  13610. "DA":{
  13611. "title":"DA",
  13612. "mask":"64"
  13613. },
  13614. "H":{
  13615. "title":"H",
  13616. "mask":"128"
  13617. },
  13618. "V":{
  13619. "title":"V",
  13620. "mask":"256"
  13621. },
  13622. "D1":{
  13623. "title":"D1",
  13624. "mask":"512"
  13625. },
  13626. "D2":{
  13627. "title":"D2",
  13628. "mask":"1024"
  13629. },
  13630. "D3":{
  13631. "title":"D3",
  13632. "mask":"2048"
  13633. },
  13634. "D4":{
  13635. "title":"D4",
  13636. "mask":"4096"
  13637. },
  13638. "C":{
  13639. "title":"C",
  13640. "mask":"8192"
  13641. },
  13642. "DT":{
  13643. "title":"DT",
  13644. "mask":"16384"
  13645. },
  13646. "CRF":{
  13647. "title":"CRF",
  13648. "mask":"32768"
  13649. },
  13650. "EX":{
  13651. "title":"EX",
  13652. "mask":"65536"
  13653. },
  13654. "EF":{
  13655. "title":"EF",
  13656. "mask":"131072"
  13657. },
  13658. "EDF":{
  13659. "title":"EDF",
  13660. "mask":"262144"
  13661. },
  13662. "EDP":{
  13663. "title":"EDP",
  13664. "mask":"524288"
  13665. },
  13666. "#EDP":{
  13667. "title":"#EDP",
  13668. "mask":"1048576"
  13669. },
  13670. "E":{
  13671. "title":"E",
  13672. "mask":"2097152"
  13673. },
  13674. "ED":{
  13675. "title":"ED",
  13676. "mask":"4194304"
  13677. },
  13678. "F1":{
  13679. "title":"F1",
  13680. "mask":"8388608"
  13681. },
  13682. "F2":{
  13683. "title":"F2",
  13684. "mask":"16777216"
  13685. },
  13686. "F3":{
  13687. "title":"F3",
  13688. "mask":"33554432"
  13689. },
  13690. "GH":{
  13691. "title":"GH",
  13692. "mask":"67108864"
  13693. },
  13694. "IMP":{
  13695. "title":"IMP",
  13696. "mask":"134217728"
  13697. },
  13698. "IL":{
  13699. "title":"IL",
  13700. "mask":"268435456"
  13701. },
  13702. "LL":{
  13703. "title":"LL",
  13704. "mask":"536870912"
  13705. },
  13706. "MO&DO":{
  13707. "title":"MO&DO",
  13708. "mask":"1073741824"
  13709. },
  13710. "AC":{
  13711. "title":"AC",
  13712. "mask":"2147483648"
  13713. },
  13714. "AT":{
  13715. "title":"AT",
  13716. "mask":"4294967296"
  13717. },
  13718. "BR":{
  13719. "title":"BR",
  13720. "mask":"8589934592"
  13721. },
  13722. "CR":{
  13723. "title":"CR",
  13724. "mask":"17179869184"
  13725. },
  13726. "#E":{
  13727. "title":"#E",
  13728. "mask":"34359738368"
  13729. },
  13730. "F":{
  13731. "title":"F",
  13732. "mask":"68719476736"
  13733. },
  13734. "#F":{
  13735. "title":"#F",
  13736. "mask":"137438953472"
  13737. },
  13738. "FD":{
  13739. "title":"FD",
  13740. "mask":"274877906944"
  13741. },
  13742. "GR":{
  13743. "title":"GR",
  13744. "mask":"549755813888"
  13745. },
  13746. "X":{
  13747. "title":"X",
  13748. "mask":"1099511627776"
  13749. },
  13750. "M1":{
  13751. "title":"M1",
  13752. "mask":"2199023255552"
  13753. },
  13754. "M2":{
  13755. "title":"M2",
  13756. "mask":"4398046511104"
  13757. },
  13758. "M3":{
  13759. "title":"M3",
  13760. "mask":"8796093022208"
  13761. }
  13762. },
  13763. "teethposition":{
  13764. "upperleft":{
  13765. "title":"upperleft",
  13766. "mask":"1"
  13767. },
  13768. "upperright":{
  13769. "title":"upperright",
  13770. "mask":"2"
  13771. },
  13772. "lowerleft":{
  13773. "title":"lowerleft",
  13774. "mask":"4"
  13775. },
  13776. "lowerright":{
  13777. "title":"lowerright",
  13778. "mask":"8"
  13779. },
  13780. "position1":{
  13781. "title":"position1",
  13782. "mask":"16"
  13783. },
  13784. "position2":{
  13785. "title":"position2",
  13786. "mask":"32"
  13787. },
  13788. "position3":{
  13789. "title":"position3",
  13790. "mask":"64"
  13791. },
  13792. "position4":{
  13793. "title":"position4",
  13794. "mask":"128"
  13795. },
  13796. "position5":{
  13797. "title":"position5",
  13798. "mask":"256"
  13799. },
  13800. "position6":{
  13801. "title":"position6",
  13802. "mask":"512"
  13803. },
  13804. "position7":{
  13805. "title":"position7",
  13806. "mask":"1024"
  13807. },
  13808. "position8":{
  13809. "title":"position8",
  13810. "mask":"2048"
  13811. },
  13812. "ischildteeth":{
  13813. "title":"ischildteeth",
  13814. "mask":"4096"
  13815. }
  13816. }
  13817. },
  13818. "item":{
  13819. "ITEMCLASS":{
  13820. "HIGHRISK":{
  13821. "title":"HIGHRISK",
  13822. "mask":"1"
  13823. },
  13824. "ANTIBIOTICUSAGE":{
  13825. "title":"ANTIBIOTICUSAGE",
  13826. "mask":"2"
  13827. },
  13828. "PURCHASABLE":{
  13829. "title":"PURCHASABLE",
  13830. "mask":"4"
  13831. },
  13832. "SERVICES":{
  13833. "title":"SERVICES",
  13834. "mask":"8"
  13835. },
  13836. "GOODS":{
  13837. "title":"GOODS",
  13838. "mask":"16"
  13839. },
  13840. "SALEABLE":{
  13841. "title":"SALEABLE",
  13842. "mask":"32"
  13843. },
  13844. "CONSUMABLE":{
  13845. "title":"CONSUMABLE",
  13846. "mask":"64"
  13847. },
  13848. "STOCKABLE":{
  13849. "title":"STOCKABLE",
  13850. "mask":"128"
  13851. },
  13852. "PHARMACEUTICALS":{
  13853. "title":"PHARMACEUTICALS",
  13854. "mask":"256"
  13855. },
  13856. "NONSTOCK":{
  13857. "title":"NONSTOCK",
  13858. "mask":"512"
  13859. },
  13860. "DISCOUNTS":{
  13861. "title":"DISCOUNTS",
  13862. "mask":"1024"
  13863. },
  13864. "GENERALITEMS":{
  13865. "title":"GENERALITEMS",
  13866. "mask":"2048"
  13867. },
  13868. "TERMS":{
  13869. "title":"TERMS",
  13870. "mask":"4096"
  13871. },
  13872. "SHEETITEMS":{
  13873. "title":"SHEETITEMS",
  13874. "mask":"8192"
  13875. },
  13876. "CAPITALITEM":{
  13877. "title":"CAPITALITEM",
  13878. "mask":"16384"
  13879. },
  13880. "PURCHASEINACTIVATED":{
  13881. "title":"PURCHASEINACTIVATED",
  13882. "mask":"32768"
  13883. },
  13884. "SALEINACTIVATED":{
  13885. "title":"SALEINACTIVATED",
  13886. "mask":"65536"
  13887. }
  13888. }
  13889. },
  13890. "location":{
  13891. "locationclass":{
  13892. "Main Store":{
  13893. "title":"Main Store",
  13894. "mask":"1"
  13895. },
  13896. "SALEABLE":{
  13897. "title":"SALEABLE",
  13898. "mask":"2"
  13899. },
  13900. "CONSUMABLE":{
  13901. "title":"CONSUMABLE",
  13902. "mask":"4"
  13903. },
  13904. "STOCKABLE":{
  13905. "title":"STOCKABLE",
  13906. "mask":"8"
  13907. },
  13908. "PHARMACEUTICALS":{
  13909. "title":"PHARMACEUTICALS",
  13910. "mask":"256"
  13911. },
  13912. "GENERAL ITEMS":{
  13913. "title":"GENERAL ITEMS",
  13914. "mask":"32"
  13915. },
  13916. "TRANSIT":{
  13917. "title":"TRANSIT",
  13918. "mask":"16"
  13919. }
  13920. }
  13921. },
  13922. "policy":{
  13923. "flags":{
  13924. "defaultpharmacynonconsultationentity":{
  13925. "title":"defaultpharmacynonconsultationentity",
  13926. "mask":"1"
  13927. }
  13928. }
  13929. },
  13930. "umask":{
  13931. "description":{
  13932. "SERVICES":{
  13933. "title":"SERVICES",
  13934. "mask":"1"
  13935. },
  13936. "CATEGORY":{
  13937. "title":"CATEGORY",
  13938. "mask":"2"
  13939. },
  13940. "GROUP":{
  13941. "title":"GROUP",
  13942. "mask":"4"
  13943. },
  13944. "CGST":{
  13945. "title":"CGST",
  13946. "mask":"8"
  13947. },
  13948. "SGST":{
  13949. "title":"SGST",
  13950. "mask":"16"
  13951. },
  13952. "IGST":{
  13953. "title":"IGST",
  13954. "mask":"32"
  13955. },
  13956. "UGST":{
  13957. "title":"UGST",
  13958. "mask":"64"
  13959. },
  13960. "PRINTED":{
  13961. "title":"PRINTED",
  13962. "mask":"128"
  13963. },
  13964. "PHARMACEUTICALS":{
  13965. "title":"PHARMACEUTICALS",
  13966. "mask":"256"
  13967. },
  13968. "UPDATED":{
  13969. "title":"UPDATED",
  13970. "mask":"512"
  13971. },
  13972. "DELETED":{
  13973. "title":"DELETED",
  13974. "mask":"1024"
  13975. }
  13976. }
  13977. },
  13978. "user":{
  13979. "roles":{
  13980. "guest":{
  13981. "title":"guest",
  13982. "mask":"1"
  13983. },
  13984. "superadmin":{
  13985. "title":"superadmin",
  13986. "mask":"2"
  13987. },
  13988. "nurseadmin":{
  13989. "title":"nurseadmin",
  13990. "mask":"4"
  13991. },
  13992. "nurse":{
  13993. "title":"nurse",
  13994. "mask":"8"
  13995. },
  13996. "bedadmin":{
  13997. "title":"bedadmin",
  13998. "mask":"16"
  13999. }
  14000. }
  14001. },
  14002. "vendor":{
  14003. "m01" : {
  14004. "externalstockimport": {
  14005. "title": "externalstockimport",
  14006. "mask":"1"
  14007. }
  14008. }
  14009. },
  14010. "billable":{
  14011. "m01" : {
  14012. "createsubencounter": {
  14013. "title": "createsubencounter",
  14014. "mask":"1"
  14015. }
  14016. }
  14017. },
  14018. "ratecard" : {
  14019. "umask" : {
  14020. "enablecredit": {
  14021. "title": "enablecredit",
  14022. "mask":"1"
  14023. },
  14024. "disablecredit": {
  14025. "title": "disablecredit",
  14026. "mask":"2"
  14027. }
  14028. }
  14029. }
  14030. };
  14031. var m_common = commonmasks ;
  14032. var helpers = {
  14033. islengthgreaterthan : function(value, maxlength){
  14034. if(value && value.length < maxlength){
  14035. return true;
  14036. }
  14037. else {
  14038. return false;
  14039. }
  14040. }
  14041. ,
  14042. isnumbercheck : function (value) {
  14043. if ( typeof(value) === 'string' || typeof(value) === 'number') {
  14044. var re = new RegExp(/^[0-9]+$/);
  14045. if (re.test(value) ) {
  14046. return true;
  14047. }
  14048. else {
  14049. return false;
  14050. }
  14051. }
  14052. else {
  14053. return false
  14054. }
  14055. }
  14056. ,
  14057. isintcheck : function (value) {
  14058. if ( typeof(value) === 'string' || typeof(value) === 'number') {
  14059. var re = new RegExp(/^[1-9]\d*$/);
  14060. if (re.test(value) ) {
  14061. return true;
  14062. }
  14063. else {
  14064. return false;
  14065. }
  14066. }
  14067. else {
  14068. return false
  14069. }
  14070. }
  14071. ,
  14072. isguidcheck : function (value) {
  14073. if ( typeof(value) === 'string' || typeof(value) === 'number') {
  14074. // var re = new RegExp(/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i);
  14075. var re = new RegExp('^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$', 'i');
  14076. if (re.test(value) ) {
  14077. return true;
  14078. }
  14079. else {
  14080. return false;
  14081. }
  14082. }
  14083. else {
  14084. return false
  14085. }
  14086. }
  14087. };
  14088. var validationhelpers = helpers;
  14089. try {
  14090. var x = BigInt(0);
  14091. }
  14092. catch(e){
  14093. console.warn('BigInt check failed. Falling back to Number');
  14094. // PB : TODO -- All Number issues with bitmasks will fail since BigInt is not available.
  14095. // Eg : Older Safari versions will not work
  14096. // PB : TODO -- provide a proper polyfill for older Safari Browsers in the ember build.
  14097. BigInt = Number;
  14098. }
  14099. // -------------------------------
  14100. // Command line option parsing
  14101. // -------------------------------
  14102. function cliargs$1(args, opts) {
  14103. if (!opts) opts = {};
  14104. var flags = { bools : {}, strings : {}, unknownFn: null };
  14105. if (typeof opts['unknown'] === 'function') {
  14106. flags.unknownFn = opts['unknown'];
  14107. }
  14108. if (typeof opts['boolean'] === 'boolean' && opts['boolean']) {
  14109. flags.allBools = true;
  14110. } else {
  14111. [].concat(opts['boolean']).filter(Boolean).forEach(function (key) {
  14112. flags.bools[key] = true;
  14113. });
  14114. }
  14115. var aliases = {};
  14116. Object.keys(opts.alias || {}).forEach(function (key) {
  14117. aliases[key] = [].concat(opts.alias[key]);
  14118. aliases[key].forEach(function (x) {
  14119. aliases[x] = [key].concat(aliases[key].filter(function (y) {
  14120. return x !== y;
  14121. }));
  14122. });
  14123. });
  14124. [].concat(opts.string).filter(Boolean).forEach(function (key) {
  14125. flags.strings[key] = true;
  14126. if (aliases[key]) {
  14127. flags.strings[aliases[key]] = true;
  14128. }
  14129. });
  14130. var defaults = opts['default'] || {};
  14131. var argv = { _ : [] };
  14132. Object.keys(flags.bools).forEach(function (key) {
  14133. setArg(key, defaults[key] === undefined ? false : defaults[key]);
  14134. });
  14135. var notFlags = [];
  14136. if (args.indexOf('--') !== -1) {
  14137. notFlags = args.slice(args.indexOf('--')+1);
  14138. args = args.slice(0, args.indexOf('--'));
  14139. }
  14140. function argDefined(key, arg) {
  14141. return (flags.allBools && /^--[^=]+$/.test(arg)) ||
  14142. flags.strings[key] || flags.bools[key] || aliases[key];
  14143. }
  14144. function setArg (key, val, arg) {
  14145. if (arg && flags.unknownFn && !argDefined(key, arg)) {
  14146. if (flags.unknownFn(arg) === false) return;
  14147. }
  14148. var value = !flags.strings[key] && isNumber(val)
  14149. ? Number(val) : val
  14150. ;
  14151. setKey(argv, key.split('.'), value);
  14152. (aliases[key] || []).forEach(function (x) {
  14153. setKey(argv, x.split('.'), value);
  14154. });
  14155. }
  14156. function setKey (obj, keys, value) {
  14157. var o = obj;
  14158. keys.slice(0,-1).forEach(function (key) {
  14159. if (o[key] === undefined) o[key] = {};
  14160. o = o[key];
  14161. });
  14162. var key = keys[keys.length - 1];
  14163. if (o[key] === undefined || flags.bools[key] || typeof o[key] === 'boolean') {
  14164. o[key] = value;
  14165. }
  14166. else if (Array.isArray(o[key])) {
  14167. o[key].push(value);
  14168. }
  14169. else {
  14170. o[key] = [ o[key], value ];
  14171. }
  14172. }
  14173. function aliasIsBoolean(key) {
  14174. return aliases[key].some(function (x) {
  14175. return flags.bools[x];
  14176. });
  14177. }
  14178. for (var i = 0; i < args.length; i++) {
  14179. var arg = args[i];
  14180. if (/^--.+=/.test(arg)) {
  14181. // Using [\s\S] instead of . because js doesn't support the
  14182. // 'dotall' regex modifier. See:
  14183. // http://stackoverflow.com/a/1068308/13216
  14184. var m = arg.match(/^--([^=]+)=([\s\S]*)$/);
  14185. var key = m[1];
  14186. var value = m[2];
  14187. if (flags.bools[key]) {
  14188. value = value !== 'false';
  14189. }
  14190. setArg(key, value, arg);
  14191. }
  14192. else if (/^--no-.+/.test(arg)) {
  14193. var key = arg.match(/^--no-(.+)/)[1];
  14194. setArg(key, false, arg);
  14195. }
  14196. else if (/^--.+/.test(arg)) {
  14197. var key = arg.match(/^--(.+)/)[1];
  14198. var next = args[i + 1];
  14199. if (next !== undefined && !/^-/.test(next)
  14200. && !flags.bools[key]
  14201. && !flags.allBools
  14202. && (aliases[key] ? !aliasIsBoolean(key) : true)) {
  14203. setArg(key, next, arg);
  14204. i++;
  14205. }
  14206. else if (/^(true|false)$/.test(next)) {
  14207. setArg(key, next === 'true', arg);
  14208. i++;
  14209. }
  14210. else {
  14211. setArg(key, flags.strings[key] ? '' : true, arg);
  14212. }
  14213. }
  14214. else if (/^-[^-]+/.test(arg)) {
  14215. var letters = arg.slice(1,-1).split('');
  14216. var broken = false;
  14217. for (var j = 0; j < letters.length; j++) {
  14218. var next = arg.slice(j+2);
  14219. if (next === '-') {
  14220. setArg(letters[j], next, arg);
  14221. continue;
  14222. }
  14223. if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) {
  14224. setArg(letters[j], next.split('=')[1], arg);
  14225. broken = true;
  14226. break;
  14227. }
  14228. if (/[A-Za-z]/.test(letters[j])
  14229. && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
  14230. setArg(letters[j], next, arg);
  14231. broken = true;
  14232. break;
  14233. }
  14234. if (letters[j+1] && letters[j+1].match(/\W/)) {
  14235. setArg(letters[j], arg.slice(j+2), arg);
  14236. broken = true;
  14237. break;
  14238. }
  14239. else {
  14240. setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg);
  14241. }
  14242. }
  14243. var key = arg.slice(-1)[0];
  14244. if (!broken && key !== '-') {
  14245. if (args[i+1] && !/^(-|--)[^-]/.test(args[i+1])
  14246. && !flags.bools[key]
  14247. && (aliases[key] ? !aliasIsBoolean(key) : true)) {
  14248. setArg(key, args[i+1], arg);
  14249. i++;
  14250. }
  14251. else if (args[i+1] && /true|false/.test(args[i+1])) {
  14252. setArg(key, args[i+1] === 'true', arg);
  14253. i++;
  14254. }
  14255. else {
  14256. setArg(key, flags.strings[key] ? '' : true, arg);
  14257. }
  14258. }
  14259. }
  14260. else {
  14261. if (!flags.unknownFn || flags.unknownFn(arg) !== false) {
  14262. argv._.push(
  14263. flags.strings['_'] || !isNumber(arg) ? arg : Number(arg)
  14264. );
  14265. }
  14266. if (opts.stopEarly) {
  14267. argv._.push.apply(argv._, args.slice(i + 1));
  14268. break;
  14269. }
  14270. }
  14271. }
  14272. Object.keys(defaults).forEach(function (key) {
  14273. if (!hasKey(argv, key.split('.'))) {
  14274. setKey(argv, key.split('.'), defaults[key]);
  14275. (aliases[key] || []).forEach(function (x) {
  14276. setKey(argv, x.split('.'), defaults[key]);
  14277. });
  14278. }
  14279. });
  14280. if (opts['--']) {
  14281. argv['--'] = new Array();
  14282. notFlags.forEach(function(key) {
  14283. argv['--'].push(key);
  14284. });
  14285. }
  14286. else {
  14287. notFlags.forEach(function(key) {
  14288. argv._.push(key);
  14289. });
  14290. }
  14291. return argv;
  14292. }
  14293. /*
  14294. Iterable task should return either truthy or false
  14295. Any fn will return only one value for an array of iterables. If any one iterable fails, the return value would be false.
  14296. If all succeed , the return value will be true.
  14297. If continueOnFailure is false, an execption is raised on any one failure
  14298. */
  14299. var logger = {
  14300. l : function(){}
  14301. };
  14302. var any$3 = function(iterable, continueOnFailure, stopOnFirstSucces, options) {
  14303. options = options || { trace : false };
  14304. var l = logger.l;
  14305. if(options.trace) l = console.log;
  14306. // console.log('-------- ' + l)
  14307. var cancelsignal = Symbol();
  14308. return iterable.reduce(
  14309. function(p, tasq, i ,a) {
  14310. var handleError = function(error, pVal){
  14311. if(error !== cancelsignal) {
  14312. l(`E3 : i = ${i} `);
  14313. console.dir(p);
  14314. if(i>0 && a[i-1].info) console.dir(a[i-1].info);
  14315. console.error(a[i-1]);
  14316. a[i-1] ? l("tasq : " + a[i-1].toString()) : null;
  14317. if(error.result) console.error(error.result);
  14318. console.error('Error : ' + (error.message || error.messages) + ' -- ' + JSON.stringify(pVal));
  14319. console.error('Error : ' + error.stack);
  14320. tasq ? l("tasq : " + tasq.toString()) : null;
  14321. l('debugData 3-------------------------');
  14322. if(!continueOnFailure) {l("Cancelling remaining on any one failure ..."); throw cancelsignal}
  14323. else return { error, pVal}
  14324. }
  14325. else throw cancelsignal;
  14326. };
  14327. if(Promise.resolve(p) === p ) {
  14328. if(i>0 && a[i-1].info) p.info = a[i-1].info;
  14329. var trycall = function(tasq){
  14330. try {
  14331. var result = tasq(); // PB : TODO -- Handle scope for call
  14332. if(tasq.resultHandler) return tasq.resultHandler(result)
  14333. // if(!result) throw result; // Default failure detection for functions is falsy values.
  14334. return result
  14335. } catch (error) {
  14336. console.error(error);
  14337. console.error('Error : ' + error ? error.stack : 'No stack');
  14338. if(!continueOnFailure) throw error; // PB : TODO -- Support array of results for any with or without continueonfailure.
  14339. }
  14340. };
  14341. return p.then( function(pVal){
  14342. // Falsy values are no longer treated as task failure exceptions. Specially for Promises.
  14343. // Even tasq function wrappers are required to return promises that eventually either resolve or reject..
  14344. // Failures are known for promises on reject.
  14345. // In future if we support direct sync function execution with a result examination for failure
  14346. // we could examine the result of the function as falsy's... or a result evaluator handler needs to be passed in...
  14347. // if(!pVal) handleError({ error : true, message : 'Failed without result' }, pVal)
  14348. // Truthy values are failures if obj has error=true.
  14349. var handleNext = function(rVal){
  14350. if(stopOnFirstSucces && i > 0 && Object.prototype.toString.call(rVal) !== '[object Object]') return rVal;
  14351. if(stopOnFirstSucces && i > 0 && !rVal.error) return rVal
  14352. l('Task finished with result : ' + JSON.stringify(rVal));
  14353. if(i>0 && a[i-1].info) console.dir(a[i-1].info);
  14354. if(!tasq && !continueOnFailure) { l('Error : No task specified.'); throw false;}
  14355. else if(!tasq) { l('Error : No task specified.'); return false;}
  14356. return (Promise.resolve(tasq) === tasq ) ? tasq : trycall(tasq) ;
  14357. };
  14358. if(pVal && pVal.error) {
  14359. if(continueOnFailure) return handleNext(pVal)
  14360. else return handleError(pVal.error, pVal)
  14361. }
  14362. if(Promise.resolve(pVal) === pVal) {
  14363. // Passed in function retured a promise. We still need to wait for it.
  14364. return pVal //.then(function(rVal){ return handleNext(rVal); })
  14365. }
  14366. else return handleNext(pVal)
  14367. })['catch'](function(error) {
  14368. return handleError(error, null)
  14369. })
  14370. }
  14371. // else if(!p) {
  14372. // handleError({ error : true, message : 'Failed without result' }, pVal)
  14373. // l("Bypass remaining on prior failure");
  14374. // return false; // All remaining tasks will return false in the any results even if they are promisies still running or functions not initiated.
  14375. // }
  14376. else return p; // A truthy value
  14377. }
  14378. , Promise.resolve(true)
  14379. );
  14380. };
  14381. function hasKey (obj, keys) {
  14382. var o = obj;
  14383. keys.slice(0,-1).forEach(function (key) {
  14384. o = (o[key] || {});
  14385. });
  14386. var key = keys[keys.length - 1];
  14387. return key in o;
  14388. }
  14389. function isNumber (x) {
  14390. if (typeof x === 'number') return true;
  14391. if (/^0x[0-9a-f]+$/i.test(x)) return true;
  14392. return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
  14393. }
  14394. //Rounds down function
  14395. // num - Value to rounddown, value - rounddown by
  14396. function g_round(num, value) {
  14397. num = parseFloat(num);
  14398. if( num % value == 0){ num = Math.ceil(num/value) * value;}
  14399. else { num = Math.ceil(num/value) * value - value; }
  14400. return Math.round(num)
  14401. }
  14402. //Precision rounding function
  14403. // Num - Value to roundoff, value - decimal precision (Ex: 10 - 1 decimal points, 100 - 2 decimal points)
  14404. function p_round(num, value) {
  14405. return Math.round((num + Number.EPSILON) * value) / value
  14406. }
  14407. // {{from}}, {{to}}
  14408. // -- Extraday bounding range limits
  14409. // -- null => no bounds => infinite past for {{from}} and infinite future for {{to}}
  14410. // {{recurring}} === 0 there is no frequency or pattern that repeats within the bounded range.
  14411. // -- Therefore the bounded range is the SINGULAR event
  14412. // -- => {{start}} === {{from}} and {{end}} === {{to}}
  14413. // {{recurring}} = {{pattern}}
  14414. // Many envents either recurring at a regular or irregular extraday frequency specified by bits in {{recurring}}.
  14415. // => pattern defines the frequency. pattern is limited to frequencies >= 1 day.
  14416. // -- A paterrn of all bits daysbits or datesbits turned on is all days.
  14417. // Example: {{from}} === null, {{to}} === null, recurring ==== 0b111111 is all days.
  14418. // Additional Time and frequence information will be found in
  14419. // {{start}}, {{end}}, {{for}} {{every}} {{duration???}}
  14420. // -- Irregular Time Patterns within a day are currently not supported but can be supported
  14421. // by another intraday recurring pattern mask {{recurrence To be appropriately renamed}}.
  14422. // hour(24bits), min(60 bits), sec(60bits), ms(1000bits ???) match.
  14423. // -- ms pattern matches to support irregular patterns like 3rd 20th and 908th ms may not be very useful but can be accomodated in the desgin if required.
  14424. // -- All offsets are datetime offsets from 1st Jan 1900 ( SQL Server )
  14425. // {{repeat}} -- is a repeated offset from an anchor. {{from}}, {{start}} are the only anchors.
  14426. // {{period}} -- if period is specified {{end}} is computed as (n-1)*{{repaat}} + {{period}} <= {{to}} boundary. Where n is the number of occurences.
  14427. // It is preferred for {{end}} to always be computed since we need to explode all events to qualify them wth the pattern anyway.
  14428. // {{start}}, {{end}} offsets defining a window with or without a datetime anchor = {{from}} or queried @from normalized to UTC begining of day.
  14429. // -- {{start}} -- Anchored offset to {{from}} or UTC begining of day > queried @from.
  14430. // -- Eg: +8:00 hours from anchor every 24 hours --- {{start}} = 8:00 {{repeat}} = 24hours.
  14431. // => implicitly a recurring repeating subdivision of {{from}} and {{to}} -- defaults to every day if {{every}} is not specified.
  14432. // -- for which day ? => at a minimum {{from}} should not be null
  14433. // -- If no {{from}} and {{to}} are specifed => unbounded so applicable from current date in a windowed form to past and future.
  14434. // -- We only present a windowed set of events for the range being queried.
  14435. // -- Need not be communicated to the client in exploded form. It is the clients responsibility to explode events for presentation.
  14436. // -- Usually an Intraday bounding range but can span multiple days.
  14437. // -- {{recurring}} => filtered by those extraday patterns bound or unbound.
  14438. // -- IMPORTANT NOTE : {{recurring}} is not essential for a recurring event.
  14439. // A recurring pattern is only one way of defining a recurring event mostly irregular patterns.
  14440. // A recurring event with regular intervals can be defined using {{every}} starting at {{start}} or {{from}} if start is not defined.
  14441. // -- {{recurring}} === 0
  14442. // => no pattern but can be recurring, if subdivisions will not repeat beyond {{start}} and {{end}} at an extraday frequency.
  14443. // -- But could be either a single event or an intraday repeating pattern for longer than a single day.
  14444. // -- Since there is no extraday recurring pattern there is nothing to filter for days dates months.
  14445. // -- {{start}} and {{end}} can span multiple consecutive days with or without an extraday pattern.
  14446. // -- specified by the duration between {{start}} and {{end}} from 1st Jan 1970 to whenever {{end}} is.
  14447. // -- single events are better specified as {{from}} and {{to}}
  14448. // -- instead of {{from}} {start} {{end}} which is interpreted equivalent.
  14449. // -- {{every}} => intraday regular frequency of every
  14450. // -- Eg : 2 hours
  14451. // -- {{for}} => for a period of
  14452. // -- Eg : 75 minutes
  14453. // -- {{for}} !== {{every}} provision for intermediate gaps or pauses in the regular {{every}} frequency
  14454. // -- {{duration}} => with an event duration of
  14455. // -- Eg : 15 minutes
  14456. // -- equally distributed and occupying {{for}} without intermediate gaps
  14457. // -- provides for a 3rd level further subdivision at {{for}} without any intermediate gaps.
  14458. // -- {{for}} === {{every}} => {{every}} subdivision has no gaps
  14459. // -- {{duration}} === null => no subdivision of {{for}} => {{for}} is the event
  14460. // -- {{for}} === null => no subdivision of {{every}} {{every}} is itself the event
  14461. // -- Eg : {{start}} = 8:12am 519ms, {{end}} = 8:00pm, {{every}} = 1 hour 6mins 20ms, {{for}} = 13 minutes 5 ms
  14462. // -- PB : TODO -- Do we need an n {{occurences}} limit ? which possibly makes {{end}} redundant. System will pick whichever is earlier.
  14463. // -- Note : It is not possible for {{for}} to repeat and occupy all of {{for}} with equal subdivision
  14464. // However same effect can achived with {{duration}} which occupieas all of {{for}} with {{for}}==={{every}}
  14465. //
  14466. // -- Irregular intraday time frequencies. See discussion above.
  14467. // {{quota}} -- quota limit at event. PB : TODO -- Is this required?
  14468. // The same effect can be achieved with a subdivision of granular time slots
  14469. // However qty will actually be computationally more efficient and address subdivision issues where fractions don't round up properly...
  14470. // {{available}}
  14471. // -- 0 => Unavialability Pattern
  14472. // -- 1 => Availability Pattern
  14473. // -------------------------------------------------------------------
  14474. // timeUtils
  14475. const daysbits = 7;
  14476. const datesbits = 31;
  14477. const monthsbits = 12;
  14478. // 2**53-1 (+/-) is largest integer precision for 64 bit floating point IEE 754
  14479. // 7 + 31 + 12 = 50 bits which fits.
  14480. const datebitOffset = daysbits;
  14481. const monthbitOffset = datesbits + daysbits; // Months are 0 based. So we need to offeset by 1 more so 31st is not overrwritten.
  14482. const monthsMask = 0b111111111111 * 2** (monthbitOffset);
  14483. const datesMask = 0b1111111111111111111111111111111 * 2 ** (datebitOffset);
  14484. const daysMask = 0b1111111;
  14485. var timeUtils = {
  14486. // PB : TODO -- Currently assuming event e1 is a sub 1 day duration. Which may not be true.
  14487. toRecurringPattern( event ){
  14488. var dayBitToSet = event.from.getDay(); // 0 based Index
  14489. var dateBitToSet = event.from.getDate() + datebitOffset - 1; // Dates are 1 based.
  14490. var monthBitToSet = event.from.getMonth() + monthbitOffset; // 0 based
  14491. var recurring = 2**dayBitToSet + 2**dateBitToSet + 2**monthBitToSet;
  14492. // PB : TODO -- loop through all matching masks until the end.
  14493. return {
  14494. from : event.from, to : event.to, recurring: recurring
  14495. , start: new Date ( event.from - new Date( moment(event.from).startOf('day') ) )
  14496. , end: new Date ( event.to - new Date( moment(event.to).startOf('day') ) )
  14497. }
  14498. }
  14499. , getSkipFunction(r, boundedRange){
  14500. var areMonthsSelected = monthsMask & r.recurring;
  14501. var areDatesSelected = datesMask & r.recurring;
  14502. var areDaysSelected = daysMask & r.recurring;
  14503. if(!areMonthsSelected && !areDatesSelected && !areDaysSelected) {
  14504. console.error("Null patterns are useless for selection. This is probably not a recurring pattern");
  14505. return null;
  14506. }
  14507. var filter = { from : boundedRange && boundedRange.from || new Date(moment().startOf('day')), to : boundedRange && boundedRange.to };
  14508. // Returns how much to skip for next available value for a dimension.
  14509. var reset = Symbol('reset');
  14510. var stop = Symbol('stop');
  14511. var skipFn = {
  14512. create : (options)=>{
  14513. var startFrom = options.startFrom;
  14514. options.nBits;
  14515. return {
  14516. originOffset : null // From the origin.
  14517. , getSkipGenerator : (selected)=>{
  14518. var startOffset = null; // From position to start from.
  14519. // var cycleEntryPoint = null;
  14520. var nextCycleIndex = 0;
  14521. var incrementCycle = [];
  14522. var previous = 0;
  14523. // Discover the cycle from the bitmask.
  14524. for(var b = 0; b < nBits; b++) {
  14525. if(selected & 1) {
  14526. if(utils.js.isNull(originOffset)) this.originOffset = b;
  14527. if(utils.js.isNull(startOffset) && (startFrom - b) <= 0){
  14528. // startOffset cannot be negative. cycleEntryPoint is from the origin and is the entrypoint when there is no fitler.from...
  14529. startOffset = b - startFrom; // As measured from filter.from i.e from startingPoint
  14530. // cycleEntryPoint = b
  14531. nextCycleIndex = incrementCycle.length-1; // The place to enter cycle after startoffset aligns to currentCycleIndex.
  14532. }
  14533. incrementCycle.push(1 + b - previous); // We keep pushing and then splice in the first item as the last item to make this cyclical.
  14534. previous = 1 + b; // Minimum incrment is always 1;
  14535. }
  14536. }
  14537. // Due to the cyclical nature incrementCycle[0] has the increment to the second item
  14538. // and incrementCycle[incrementCycle.length-1] points to first item in cycle.
  14539. incrementCycle.push(incrementCycle.splice(0,1));
  14540. if(nextCycleIndex < 0) nextCycleIndex = 0;
  14541. return function*(){
  14542. var signal = false;
  14543. signal = yield startOffset; // Could be 0. Aligns to the first match in the cycle after from.
  14544. var i = nextCycleIndex;
  14545. for(;;){
  14546. for(; i < incrementCycle.length; i++ ) {
  14547. signal = yield incrementCycle[i];
  14548. if(reset === signal) { signal = yield this.originOffset; break; }
  14549. if(signal === stop || signal.done) return null;
  14550. }
  14551. i = 0;
  14552. }
  14553. }
  14554. }
  14555. // Generator for Irregular boundaries.
  14556. , getNextDateGenerator(selection){
  14557. var iterator = this.getSkipGenerator(selection);
  14558. return function*(){
  14559. var nextPotentialDate = moment(potentialDate).add(iterator.next(), 'd');
  14560. if(nextPotentialDate.month() != potentialDate.getMonth()) {
  14561. // Handle month boundary increments.
  14562. nextPotentialDate.startOf('month').add(dateIterator.next(reset), 'm');
  14563. }
  14564. var potentialDate = nextPotentialDate;
  14565. yield nextPotentialDate;
  14566. }
  14567. }
  14568. // Cyclical Generator.
  14569. , getNextGenerator(options, selection){
  14570. this.getSkipGenerator(selection);
  14571. var next = filter.from;
  14572. return function*(){
  14573. yield next = moment(next).add(dayIterator.next(), 'd');
  14574. }
  14575. }
  14576. }
  14577. }
  14578. };
  14579. var monthSkipper = skipFn.create({ nBits : monthsbits, startFrom : filter.from.getMonth() });
  14580. var daySkipper = skipFn.create({ nBits : daysbits, startFrom : filter.from.getDay() });
  14581. var dateSkipper = skipFn.create({ nBits : datebits, startFrom : filter.from.getDate()-1 }); // Skipfn requires a 0 based startFrom.
  14582. if(!areMonthsSelected && !areDatesSelected) return daySkipper(areDaysSelected)
  14583. else if(!areDatesSelected && !areDaysSelected) return monthSkipper(areMonthsSelected/2**(datesbits + daysbits))
  14584. else if(!areMonthsSelected && !areDaysSelected) return dateSkipper(areDatesSelected/2**(daysbits))
  14585. else {
  14586. if(!areMonthsSelected) {
  14587. // Dates, Days are selected.
  14588. return function*(){
  14589. var dateIterator = dateSkipper.getNextDateGenerator({ nBits : datebits, startFrom : filter.from.getDate()-1 }, areDatesSelected/2**(daysbits));
  14590. var dayIterator = daySkipper.getNextGenerator({ nBits : daysbits, startFrom : filter.from.getDay() }, areDaysSelected);
  14591. var potentialDay = null;
  14592. var potentialDate = dateIterator.next(); // Irregular cycle end...
  14593. if(isAnd) {
  14594. // Both day and date shuld match.
  14595. for(;;){
  14596. for(; (potentialDay = dayIterator.next()) < potentialDate ;);
  14597. // PB : TODO -- If we never hit the equals condition this will be a perpetual loop.
  14598. // If both are integer skips we will have a LCM and therefore hit this condition.
  14599. // In the case of sets of irregular skips we still will have the sum of each set also have an LCM.
  14600. // However for irregular boundaries we cannot predict whether an LCM exists and if a equality condition will ever be met.
  14601. // In such cases we need to protect from an infinite loop that will never yield.
  14602. // For dates though despite the irregular boundaries the pattern is that every date, month combination falls on every day of week.
  14603. if(potentialDay == potentialDate) {
  14604. yield potentialDay;
  14605. potentialDate = dateIterator.next();
  14606. continue;
  14607. }
  14608. for(; (potentialDate = dateIterator.next()) < potentialDay;);
  14609. }
  14610. }
  14611. else {
  14612. for(;;){
  14613. for(; (potentialDay = dayIterator.next()) < potentialDate ;) {
  14614. if(stop === (yield potentialDay)) return null;
  14615. }
  14616. if(potentialDay == potentialDate) {
  14617. potentialDate = dateIterator.next();
  14618. continue; // We need to yield in sorted sequence.
  14619. }
  14620. for(; (potentialDate = dateIterator.next()) < potentialDay;) {
  14621. if(stop === (yield potentialDate)) return null;
  14622. }
  14623. }
  14624. }
  14625. }
  14626. }
  14627. }
  14628. }
  14629. , skipThisRecurrable : Symbol('skipThisRecurrable')
  14630. , stopThisIterator : Symbol('stopThisIterator')
  14631. , toEvents( r, boundedRange){
  14632. if(!boundedRange.to) throw 'toEvents requires a bounded Range with an end to terminate. Use generater for unbounded operations'
  14633. ({ from : boundedRange.from || new Date(moment(new Date()).startOf('day')), to : boundedRange.to });
  14634. }
  14635. , jsstart : function(){
  14636. return new Date(moment(new Date(0)).startOf('day')) //1st Jan 1970 12AM local time
  14637. }
  14638. // Returns the whole event that is qualified even by a partial intersection.
  14639. , getEventGenerator : function* (objOrArray, boundedRange, getEvent) {
  14640. getEvent = getEvent || function(r, startOfDayFrom, start, end) {
  14641. var event = Object.assign( {}, r);
  14642. delete event.recurring;
  14643. event.from = new Date (startOfDayFrom.getTime() + start.getTime() + utils.getTZOffsetMilliseconds() );
  14644. event.to = new Date ( startOfDayFrom.getTime() + end.getTime() + utils.getTZOffsetMilliseconds());
  14645. // { from : new Date ( startOfDayFrom.getTime() + start.getTime() ) , to : new Date ( startOfDayFrom.getTime() + end.getTime()) }
  14646. return event
  14647. };
  14648. var recurrables = utils.js.isObject(objOrArray) ? [objOrArray] : objOrArray;
  14649. // We need to start somewhere. We dont need an end as we keep generating perpetually.
  14650. var filter = { from : boundedRange && boundedRange.from || new Date(moment().startOf('day')), to : boundedRange && boundedRange.to };
  14651. for(var gIdx=0; gIdx < recurrables.length; gIdx++){
  14652. // Explode eachRecurrable to list of qualified events
  14653. var eachRecurrable = recurrables[gIdx]; // eachRecurrable -> Recurrable event (eg)
  14654. if( eachRecurrable.to && eachRecurrable.to <= filter.from ) continue; // Disjoint. No need to generate. Usually a past recurring pattern.
  14655. var startFrom = filter.from;
  14656. if( eachRecurrable.from) {
  14657. if(filter.to && filter.to <= eachRecurrable.from ) continue; // Disjoint.
  14658. if(eachRecurrable.from >= filter.from) startFrom = eachRecurrable.from;
  14659. }
  14660. var startOfDayFrom = new Date( moment(startFrom).startOf('day') ); // PB : TODO -- IMP pattern TZ...
  14661. var next = null;
  14662. var stopAt = eachRecurrable.to ? filter.to ? Math.min(filter.to, eachRecurrable.to) : eachRecurrable.to : filter.to ? filter.to : false;
  14663. var shouldStop = stopAt ? ()=>{ return option === this.skipThisRecurrable || next.from >= stopAt } : ()=>{ return option === this.skipThisRecurrable || false }; // Perpetual callee can stop asking for next()..
  14664. // time recurring patterns are sorted and sequential so there is no chance we will find any more after end.
  14665. // which implies there is no need to test the rest of the recurring patterns until end of the boundary
  14666. if(filter.to && eachRecurrable.to) {
  14667. var stopAt = new Date(Min(filter.to, eachRecurrable.to));
  14668. shouldStop = ()=>{ return option === this.skipThisRecurrable || (stopAt <= next.to ? stopAt : false) };
  14669. }
  14670. var start = eachRecurrable.start || this.jsstart();
  14671. var end = eachRecurrable.end || new Date(moment(start).add(1, "d"));
  14672. var option = true;
  14673. next = getEvent(eachRecurrable, startOfDayFrom, start, end);
  14674. while( !shouldStop() ) {
  14675. // PB : TODO -- If we provide an impossible pattern match we will perpetually not match and end up in an infinite loop.
  14676. var patternMatched = this.__hasPatternIntersection(next, eachRecurrable);
  14677. if(patternMatched) option = yield next;
  14678. if(option === this.stopThisIterator) return null;
  14679. // PB : TODO -- Instead of checking every day skip straightaway to the next sequential pattern match.
  14680. startOfDayFrom = new Date( moment(startOfDayFrom).add(1, 'd') );
  14681. next = getEvent(eachRecurrable, startOfDayFrom, start, end);
  14682. }
  14683. }
  14684. }
  14685. // PB : TODO -- Generator that returns a series of intersections events.
  14686. // , recurringIntersectionsG : ()=>{}
  14687. , isEvent : function(obj){
  14688. return !obj.recurring
  14689. }
  14690. , isRecurringPattern : function(obj){
  14691. return obj.recurring
  14692. }
  14693. , hasEventIntersection( e1Orr1, e2Orr2 ){
  14694. return utils.timeUtils.isEvent(e1Orr1) && utils.timeUtils.isRecurringPattern( e2Orr2 ) ? utils.timeUtils.__recurringHasIntersection( e1Orr1, e2Orr2 )
  14695. : utils.timeUtils.isEvent(e2Orr2 ) && utils.timeUtils.isRecurringPattern( e1Orr1 ) ? utils.timeUtils.__recurringHasIntersection( e2Orr2, e1Orr1 )
  14696. : utils.timeUtils.isEvent(e1Orr1) && utils.timeUtils.isEvent(e2Orr2) ? utils.timeUtils.__hasEventIntersection( e1Orr1, e2Orr2 )
  14697. : utils.timeUtils.__willPatternsIntersect( e1Orr1, e2Orr2 ) //(()=>{throw 'PB : TDOO -- To Be implemented'})()
  14698. }
  14699. , __hasPatternIntersection( e1, p2 ){
  14700. var areMonthsSelected = monthsMask & p2.recurring;
  14701. var areDatesSelected = datesMask & p2.recurring;
  14702. var areDaysSelected = daysMask & p2.recurring;
  14703. // PB : TODO -- Gaurd against impossible patters like 29th Feb, 31st April etc...
  14704. if(!areMonthsSelected && !areDatesSelected && !areDaysSelected) {
  14705. console.error("Null patterns are useless for selection. This is probably not a recurring pattern");
  14706. return null; // Null patterns result in null intersection.
  14707. }
  14708. var isAnd = false;
  14709. if(!areMonthsSelected && !areDatesSelected || !areMonthsSelected && !areDaysSelected || !areDatesSelected && !areDaysSelected ) ;
  14710. else {
  14711. isAnd = p2.isAnd;
  14712. }
  14713. var p1 = this.toRecurringPattern(e1);
  14714. var patternMatched = p1.recurring & p2.recurring;
  14715. // In the and case asserts if p1 is a subset of p2 not the other way around. A recurring pattern should always be a superset of an event.
  14716. // And that is what is being queried... for any degree of usefulness.
  14717. return ( isAnd ? p1.recurring === patternMatched : patternMatched );
  14718. // returns truthy pattern that intersects.
  14719. }
  14720. , __willPatternsIntersect( p1, p2 ){
  14721. if(p1.from && p2.to && p2.to <= p1.from) return false;
  14722. if(p2.from && p1.to && p1.to <= p2.from) return false;
  14723. var areMonthsSelected = monthsMask & p2.recurring;
  14724. var areDatesSelected = datesMask & p2.recurring;
  14725. var areDaysSelected = daysMask & p2.recurring;
  14726. // PB : TODO -- Gaurd against impossible patters like 29th Feb, 31st April etc...
  14727. if(!areMonthsSelected && !areDatesSelected && !areDaysSelected) {
  14728. console.error("Null patterns are useless for selection. This is probably not a recurring pattern");
  14729. return null; // Null patterns result in null intersection.
  14730. }
  14731. var isAnd = false;
  14732. if(!areMonthsSelected && !areDatesSelected || !areMonthsSelected && !areDaysSelected || !areDatesSelected && !areDaysSelected ) ;
  14733. else {
  14734. isAnd = p2.isAnd;
  14735. }
  14736. var areP1MonthsSelected = monthsMask & p1.recurring;
  14737. var areP1DatesSelected = datesMask & p1.recurring;
  14738. var areP1DaysSelected = daysMask & p1.recurring;
  14739. // PB : TODO -- Gaurd against impossible patters like 29th Feb, 31st April etc...
  14740. if(!areP1MonthsSelected && !areP1DatesSelected && !areP1DaysSelected) {
  14741. console.error("Null patterns are useless for selection. This is probably not a recurring pattern");
  14742. return null; // Null patterns result in null intersection.
  14743. }
  14744. var isP1And = false;
  14745. if(!areP1MonthsSelected && !areP1DatesSelected || !areP1MonthsSelected && !areP1DaysSelected || !areP1DatesSelected && !areP1DaysSelected ) ;
  14746. else {
  14747. isP1And = p1.isAnd;
  14748. }
  14749. if(isAnd && isP1And === isAnd ) {
  14750. return p1.recurring === p2.recurring;
  14751. }
  14752. else if(isAnd) {
  14753. matchtarget = p2.recurring ;
  14754. }
  14755. else if(isP1And ) {
  14756. matchtarget = p1.recurring ;
  14757. }
  14758. var patternMatched = p1.recurring & p2.recurring;
  14759. // In the and case asserts if p1 is a subset of p2 not the other way around. A recurring pattern should always be a superset of an event.
  14760. // And that is what is being queried... for any degree of usefulness.
  14761. var __patternMatched = ( isAnd || isP1And ? matchtarget === patternMatched : patternMatched );
  14762. if(__patternMatched) {
  14763. if(p1.start && p2.end && p2.end <= p1.start) return false;
  14764. if(p2.start && p1.end && p1.end <= p2.start) return false;
  14765. return true;
  14766. }
  14767. else {
  14768. return false
  14769. }
  14770. // returns truthy pattern that intersects.
  14771. }
  14772. , __recurringHasIntersection(e1, r1){
  14773. // PB : TODO -- Date patterns UTC or Local ? i.e does a Monday mask match UTC Mondays or Local Mondays ????
  14774. // PB : TODO -- Use recunrence generator insteadof startOf today hack based on simplified same day start end assumptions.
  14775. if(e1.from && r1.to && r1.to <= e1.from) return false;
  14776. if(r1.from && e1.to && e1.to <= r1.from) return false;
  14777. // Returns intersection or false.
  14778. return ( utils.timeUtils.__hasPatternIntersection(e1, r1) ) ? (()=>{
  14779. // new Date ( new Date( this.rdata.get('unavailablefrom') ) - new Date( moment().startOf('day') ) )
  14780. var startOfe1 = new Date( moment(e1.from).startOf('day') );
  14781. var r1E = {
  14782. from: new Date(startOfe1.getTime() + r1.start.getTime() + utils.getTZOffsetMilliseconds() )
  14783. , to: new Date(startOfe1.getTime() + r1.end.getTime() + utils.getTZOffsetMilliseconds() )
  14784. };
  14785. // SAM : TODO -- Verify and enable this code.
  14786. // if(r1.from && r1E.from <= r1.from) r1E.from = r1.from;
  14787. // if(r1.to && r1E.to >= r1.to) r1E.to = r1.to;
  14788. return utils.timeUtils.__hasEventIntersection(e1, r1E)
  14789. })()
  14790. : false
  14791. }
  14792. // Checks if two non recurring i.e singular events intersect and if so returns the actual intersection.
  14793. , __hasEventIntersection(e1, e2){
  14794. // PB : TODO -- No assertions for invalid inputs e.from is expected to be <= e.to
  14795. if(!e1.from && !e1.to) return e2;
  14796. if(!e2.from && !e2.to) return e1;
  14797. var e1FromAnde2To = e1.from && e2.to;
  14798. var e2FromAnde1To = e2.from && e1.to;
  14799. var __aFrombTo = (a, b)=>{
  14800. // boundary value overlap is insufficient for intersection. At least 1 millisecond diff is required.
  14801. return (a.from >= b.to ? false
  14802. : a.to && a.to > b.to || !a.to ?
  14803. { from : b.from && b.from > a.from ? b.from : a.from, to : b.to }
  14804. : b.from && b.from >= a.to ? false : { from : b.from && b.from > a.from ? b.from : a.from, to : a.to }
  14805. )
  14806. };
  14807. var result = e1FromAnde2To ? __aFrombTo(e1, e2)
  14808. :( e2FromAnde1To ? __aFrombTo(e2, e1)
  14809. : /* e1FromAnde2To is false and e2FromAnde1To is false => either both froms or both tos exist */
  14810. e1.from ? { from: new Date(Math.max(e1.from, e2.from)) } : { to: new Date(Math.min(e1.to, e2.to)) });
  14811. return result
  14812. }
  14813. , exludeIntersection(freeTimes, e) {
  14814. // Removal of unavilable times will split and splice into the same freeTimes array.
  14815. for(var i =0; i < freeTimes.length; i++) {
  14816. var intersection = timeUtils.hasEventIntersection(freeTimes[i], e);
  14817. if(intersection) {
  14818. // Edit freetime to correct for current collision.
  14819. if(freeTimes[i].from >= intersection.from && freeTimes[i].to <= intersection.to) {
  14820. freeTimes.splice(i,1); i = i-1;
  14821. }
  14822. else {
  14823. var right = Object.assign({}, freeTimes[i]);
  14824. right.from = intersection.to;
  14825. freeTimes[i].to = intersection.from;
  14826. if( right.from < right.to ) {
  14827. freeTimes.splice(++i,0, right); // Skip this we have already processed it.
  14828. }
  14829. }
  14830. }
  14831. }
  14832. }
  14833. , getFreeTimes( tRange, events, dimensions) {
  14834. var freeTimes = [tRange];
  14835. for(var eIdx = 0; eIdx < events.length; eIdx++) {
  14836. var e = events[eIdx];
  14837. timeUtils.exludeIntersection(freeTimes, e);
  14838. if(freeTimes.length === 0) break;
  14839. }
  14840. // { result : freeTimes.length > 0, freeTimes : freeTimes}
  14841. return freeTimes;
  14842. }
  14843. // PB : TODO -- Timeutils Test cases. Comment in production.
  14844. , testAll(){
  14845. // // Disjoint
  14846. // var expected = false
  14847. // var actual = null;
  14848. expected = 2**4 + 2**(6+21) + 2**(5+31+6);
  14849. actual = this.toRecurringPattern(
  14850. { from : new Date('5/21/2020, 11:45:00 PM'), to : new Date('5/22/2020, 00:15:00 AM') } ).recurring;
  14851. if(expected !== actual ) throw (' TEST FAILED toRecurringPattern : expected = ' + expected + ' actual = ' + actual)
  14852. // actual = this.__hasEventIntersection(
  14853. // { from : new Date('5/21/2020, 11:45:00 PM'), to : new Date('5/22/2020, 00:15:00 AM') }
  14854. // , { from : new Date('5/22/2020, 11:45:00 PM'), to : new Date('5/23/2020, 00:15:00 AM') })
  14855. // if(expected !== actual ) throw (' TEST FAILED Disjoint : expected = ' + expected + ' actual = ' + actual)
  14856. // // Interleaved
  14857. // expected = JSON.stringify({ from : new Date('5/22/2020, 00:00:00 AM'), to : new Date('5/22/2020, 00:15:00 AM') })
  14858. // actual = this.__hasEventIntersection(
  14859. // { from : new Date('5/21/2020, 11:45:00 PM'), to : new Date('5/22/2020, 00:15:00 AM') }
  14860. // , { from : new Date('5/22/2020, 00:00:00 AM'), to : new Date('5/22/2020, 00:30:00 AM') })
  14861. // if(expected !== JSON.stringify(actual) ) throw (' TEST FAILED Interleaved : expected = ' + expected + ' actual = ' + JSON.stringify(actual))
  14862. // // Subset
  14863. // expected = JSON.stringify({ from : new Date('5/22/2020, 00:00:00 AM'), to : new Date('5/22/2020, 00:10:00 AM') })
  14864. // actual = this.__hasEventIntersection(
  14865. // { from : new Date('5/21/2020, 11:45:00 PM'), to : new Date('5/22/2020, 00:15:00 AM') }
  14866. // , { from : new Date('5/22/2020, 00:00:00 AM'), to : new Date('5/22/2020, 00:10:00 AM') })
  14867. // if(expected !== JSON.stringify(actual) ) throw (' TEST FAILED Interleaved : expected = ' + expected + ' actual = ' + JSON.stringify(actual))
  14868. // Null
  14869. // Boundary Test Cases....
  14870. var r1 = {
  14871. end: new Date("1970-01-01T11:00:00.000Z")
  14872. , every: null
  14873. , from: new Date("2020-06-04T06:30:00.000Z")
  14874. , id: "DC664060-A0A8-11EA-8B3D-7771F3D49CC1"
  14875. , migrationstate: 1
  14876. , practitionerId: "5FDF1790-8288-11E9-9044-91D8D8658887"
  14877. , purpose: "Meeting"
  14878. , recurring: 106
  14879. , start: new Date("1970-01-01T06:30:00.000Z")
  14880. , status: "SCHEDULED"
  14881. , to: null
  14882. };
  14883. var e1 = {
  14884. availability: false
  14885. , end: null
  14886. , every: null
  14887. , for: null
  14888. , from: new Date("2020-06-08T11:00:00.000Z")
  14889. , id: "AEC5A7E1-A96D-11EA-8DE7-19E354C126F4"
  14890. , migrationstate: 8
  14891. , patientId: "271F4970-F173-4530-A894-68F520BF7945"
  14892. , patientmob: "9944715969"
  14893. , patientname: "SAMUEL RAJA DURAI J"
  14894. , practitionerId: "5FDF1790-8288-11E9-9044-91D8D8658887"
  14895. , purpose: "Appointment"
  14896. , start: null
  14897. , status: "SCHEDULED"
  14898. , to: new Date("2020-06-08T11:15:00.000Z")
  14899. };
  14900. this.hasEventIntersection(e1, r1);
  14901. debugger
  14902. // Iterators
  14903. var eventIterator = this.getEventGenerator({ recurring : 2**1 }); // All Mondays from today.
  14904. for(var i=0, e; i<10 && !(e=eventIterator.next()).done; i++) {
  14905. console.dir(e);
  14906. }
  14907. }
  14908. };
  14909. function promisify(ctx, operation, arraylikearguments) {
  14910. // operation.isAsync We cant assume the last argument being a function implies the last arg is the callback unless we are told.
  14911. // Currently we default to the assumption that if the last arg is a function it is the callback.
  14912. var noargs = !arraylikearguments;
  14913. var nocb = noargs || utils.js.isFunction(arraylikearguments[arraylikearguments.length-1]); /* && operation.isAsync */
  14914. // We always expect a callback as the last arg.
  14915. arraylikearguments = arraylikearguments || [function(){}];
  14916. var originalcallback = arraylikearguments.splice(arraylikearguments.length-1, 1)[0];
  14917. return new Promise(function(resolve, reject) {
  14918. var r = operation.call(ctx, ...arraylikearguments, function(err, result) {
  14919. if (err) return reject(arguments);
  14920. resolve(arguments);
  14921. });
  14922. if(nocb) return resolve([r])
  14923. }).then((aArr)=>{
  14924. originalcallback(...aArr);
  14925. return aArr[1]
  14926. }).catch(function(aArr){
  14927. originalcallback(...aArr);
  14928. throw aArr[0];
  14929. });
  14930. }
  14931. var Tasq$1 = (function(){
  14932. var __proto__ = {
  14933. };
  14934. var listeners = [];
  14935. function Tasq(first, ...rest){
  14936. first.info = utils.assign({ args : rest }, __proto__);
  14937. return first
  14938. }
  14939. Tasq.create = Tasq;
  14940. Tasq.addlistener = (l)=>{ listeners.push(l); };
  14941. Tasq.catch = (e)=>{ console.error(e); console.error(e.messages.join(' ')); listeners.forEach(l => { l(e); } );};
  14942. Tasq.then = (d)=>{ listeners.forEach(l => { l(null, d); } ); return d};
  14943. return Tasq
  14944. })();
  14945. var Traq$1 = (function(){
  14946. var __proto__ = {};
  14947. var log = {
  14948. SUCCESS : []
  14949. , FAILURE : []
  14950. , SKIPPED : []
  14951. };
  14952. Traq$1 = function(){ return utils.assign({}, __proto__) };
  14953. Traq$1.create = Traq$1;
  14954. Traq$1.statuslog = statuslog;
  14955. function statuslog(err, data){
  14956. if(err) log.FAILURE.push( {err, data} );
  14957. else log.SUCCESS.push(data);
  14958. }
  14959. Traq$1.notify = (event)=>{
  14960. if(event.error) log.FAILURE.push( event );
  14961. else log.SUCCESS.push(event);
  14962. };
  14963. Traq$1.finally = ()=>{
  14964. console.log('Total : ' + (log.SKIPPED.length + log.SUCCESS.length + log.FAILURE.length));
  14965. console.log('Pass : ' + log.SUCCESS.length );
  14966. console.log('Fail : ' + log.FAILURE.length);
  14967. console.log('Skipped : ' + log.SKIPPED.length);
  14968. console.log('FAILURES');
  14969. console.log([JSON.stringify(log.FAILURE)]);
  14970. };
  14971. return Traq$1
  14972. })();
  14973. var tzoffset = 0;
  14974. var utils = {
  14975. commonmasks : m_common,
  14976. p_round: p_round,
  14977. g_round: g_round,
  14978. escapeRegExp(string) {
  14979. return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
  14980. }
  14981. , getTZOffsetMilliseconds : (()=>{
  14982. var d = new Date();
  14983. var t1 = d.toISOString().replace('Z','');
  14984. var t2 = d.toISOString();
  14985. tzoffset = ( new Date(t2) - (new Date(t1))); // /60/60/1000 -- milliseconds.
  14986. return ()=>{ return tzoffset}
  14987. })()
  14988. , getLocalDateYYYYMMDD(date){
  14989. var d = new Date();
  14990. d.setTime(tzoffset + new Date(date).getTime());
  14991. return d.toISOString().slice(0,10).replace(/-/g,"")
  14992. }
  14993. , assign(target /** , ...sources */) {
  14994. return utils.assign_core(false, ...arguments)
  14995. }
  14996. , assign_strict(target /** , ...sources */) {
  14997. return utils.assign_core(true, ...arguments)
  14998. }
  14999. // assign
  15000. , assign_core(keycase, target /** , ...sources */) {
  15001. // Important use this instead of Object.assign.
  15002. // Object.assign has several limitations.
  15003. // 1) It doesn't skip intermediates if the final overriden value is already determined.
  15004. // This implementation address this.
  15005. // 2) It is shallow and doesn't clone object references and therefore risks side effects to original nested objects.
  15006. // This implementation deep clones objects arrays and other types with some limitations.
  15007. // 3) Does not merge but allways overrides.
  15008. // Merges objects and arrays. Overides primitives.
  15009. // Array merge is by default a concatenation.
  15010. // PB : TODO -- If corresponding array indices have objects they can be merged like lodash.
  15011. // 4) Does not retain non writable and configurable attributes.
  15012. // This implementation copies descirptors so clones retain non writability and configurability identical to the source.
  15013. // 5) Recursion can cause infinite recursion. Object.assign doesn't deal with this.
  15014. // Detects and avides ininite recursion.
  15015. var cpi = {}; // Caseless property index of already processed target keys. Since we do not alter the target key we need a lookup that gives the actual key.
  15016. var getNormalizedKey = keycase ?
  15017. keycase === 'lower' ? (key)=> key.toLowerCase() : (key)=>key
  15018. : (key)=> key.toLowerCase(); // returns a normalized equivalent key.
  15019. // We do a right to left iterations!
  15020. // overrideKeys = true;
  15021. // PB : Note -- IMPORTANT alreadyScanned has side effects..
  15022. var alreadyScanned = (key)=>{
  15023. Object.keys(target).forEach(k => {
  15024. cpi[k.toLowerCase()] = k;
  15025. if(cpi[k.toLowerCase()] !== k){
  15026. Object.defineProperty( target, cpi[k.toLowerCase()], Object.getOwnPropertyDescriptor(target, k) ); // Relocate to new overridden key
  15027. delete target[tkeys[tkidx]]; // PB : TODO -- review that accessors are not called during delete !
  15028. }
  15029. });
  15030. alreadyScanned = ()=>{ return true; }; // Dont do anything next time we are called.
  15031. // Its not necessary that we found it.
  15032. cpi[key.toLowerCase()] ? null : cpi[key.toLowerCase()] = key;
  15033. return false;
  15034. };
  15035. // PB : Note -- IMPORTANT findEqualKey has side effects..
  15036. var findEqualKey = (key) => {
  15037. // If equiv key on the target is what the target key should ultimately be we will cache all possible now.
  15038. // However in the overrideKeys case this is not true in which case we postpone until the first one found in the overrider.
  15039. {
  15040. if(alreadyScanned(key)) { cpi[key.toLowerCase()] ? null : cpi[key.toLowerCase()] = key; } }
  15041. var targetKey = cpi[key.toLowerCase()];
  15042. return { targetKey, propertyDescriptor : Object.getOwnPropertyDescriptor(target, targetKey) }
  15043. };
  15044. var hOP = Object.prototype.hasOwnProperty;
  15045. var __assign = function(keycase, target /** , ...sources */) {
  15046. if(utils.js.isUndefined(target)) return; // There is noting to assign to. We just play dumb. Why did the caller even call us ?
  15047. // PB : TODO -- we need a flag to support undefined overrides. Default behavior is to retain as much as possible.
  15048. // if(utils.js.isUndefined(arguments[arguments.length-1])) return undefined;
  15049. var undef = 0;
  15050. for(; undef < arguments.length-1 && utils.js.isUndefined(arguments[arguments.length-undef-1]); undef++); // Skip all undefined overrides.
  15051. if(undef === arguments.length-1) return target;
  15052. if(utils.js.isPrimitive(arguments[arguments.length-1-undef])) return arguments[arguments.length-1-undef];
  15053. else {
  15054. // PB : TODO -- Primitive targets cannot be preserved.
  15055. // Target should be decided on first non primitive discovery.
  15056. // Arrays don't work properly yet...
  15057. // We start with a temporary object and if there is a primitive override it will override this temporary object altogether.
  15058. // PB : TODO -- We could convert primitives to their respective object counterparts... Howeer strings with indexes and arrays will get messy.
  15059. if(utils.js.isPrimitive(target)) {
  15060. target = {};
  15061. } }
  15062. for(var
  15063. finalized = {} // One instance for each structurally corresponding key that has already been overridden. Order need not be guaranteed.
  15064. , overrideOrMerge = function (originalkey) {
  15065. // Decision merge or override default to the following.
  15066. // Primitives are overridden by non Primitives ( arrays or objects )
  15067. // Non Primitives are overridden by Primitives. There is no concept of assigning Primitives as new named attributes of Objects.
  15068. // Objects assigned to Objects will be merged.
  15069. // Arrays assigned to Arrays will be merged i.e concatenated. PB : TOOD -- Order will be ??? target then right to left for sources.
  15070. // PB : TODO -- We should avoid examining or tampering with the value during clone and should find another way to make this decision.
  15071. // We do not want side effects to occur while examining the value. Accessors and proxies can do this.
  15072. // Currently assuming simple use cases at this point...
  15073. // Ideally Accessor Descriptors should be postponed for evaluation when runtime access to value is required.
  15074. var { targetKey, dL } = findEqualKey(originalkey);
  15075. var dR = Object.getOwnPropertyDescriptor(this, originalkey);
  15076. if(!dL) {
  15077. // target did not have what it should be according to what was specifed. Lets check for other possibilities.
  15078. dL = Object.getOwnPropertyDescriptor(target, originalkey);
  15079. if(!dL) { Object.defineProperty( target, targetKey, dR ); finalized[targetKey] = true; return; }
  15080. }
  15081. if(!utils.js.isUndefined( dR.writable )) { // writable attribute is present only in Data Descriptor Case
  15082. var valR = this[originalkey]; // We can examine data descriptors without any side effects. ( PB : TODO -- Proxies ! are expected to be transparent !! )
  15083. if(utils.js.isPrimitive( valR )) {
  15084. finalized[targetKey] = true;
  15085. // Primitive values also are implicitly cloned by Data Descriptors when defineProperty is called.
  15086. // Advantage is writable / configurable permissions are retained instead of simple assignment.
  15087. Object.defineProperty( target, targetKey, dR );
  15088. return
  15089. }
  15090. // If its not primitive it may need to get merged if the Left value is also non primitive and of a compatible type...
  15091. }
  15092. // PB : TODO -- Data descriptor that is not writable needs to be handled !? proper check to handle value etc required.
  15093. if(utils.js.isUndefined( dR.writable ) || utils.js.isUndefined( dL.writable ) ){
  15094. // One or both of them is an accessor descriptor.
  15095. // If either one of them is an accessor we need to postpone the merge to runtime evaluation on access.
  15096. var dChosen = !utils.js.isUndefined( dL.writable ) ? dR : dL; // Figure out which one is the accessor.
  15097. // Accessor Descriptors cannot be examined due to possible side effects and possible differences
  15098. // in the value and its type at the point of execution.
  15099. // Since the accessed value here is meaningless we don't know what type it will eventually be at the point wehre
  15100. // real program code needs the value !!!
  15101. // There are 2 options
  15102. // 1) we could do a decoupling here (at clone time) and capture the value.
  15103. // 2) or we could postpone until run time evaluation.
  15104. // Since in either case We need to examine the value it may be superior to evaluate at runtime and decide then.
  15105. // Although decoupling is important and better done as early as possible the delayed value is more important.
  15106. // PB : TODO -- We should provide a pref to evaluate and decouple at clone time
  15107. // PB : TODO -- The postponing strategy has one more issue where delayed override can clobber target modifications on the left side.
  15108. // -- Causing unexpected values specifically when the delayed override value from the source is expected.
  15109. // Ideally the value that was set intermediately should supercede.
  15110. // -- The preferred behaviour implemented here is to decouple on first set such that the intermediate value set on the clone supercedes.
  15111. // Original getter needs to access value in original context.
  15112. // Setters need to be redirected to "cloned setter" in current context.
  15113. var ctx = this;
  15114. var dRGetter = !utils.js.isUndefined( dR.writable ) ? function(){ return dR.value} : dR.get;
  15115. var dLGetter = !utils.js.isUndefined( dL.writable ) ? function(){ return dL.value} : dL.get;
  15116. var valForSetter = null;
  15117. dR.configurable;
  15118. if(!utils.js.isUndefined( dL.writable )) {
  15119. // Oridinarily since we postpone we need to refrence and reevaluete valL also at access time coz the target val could have been switched.
  15120. // The target is now an accessor which gets decoupled on first set in that case there is no need to re-evaluate.
  15121. // These getters are still valid until such a first set happens until which time the valL remains
  15122. // It is therefore possible to cache the valL and use it instead of target[key] at access time....
  15123. var valL = target[targetKey];
  15124. if(utils.js.isPrimitive(valL)) { dChosen.get = function(){ return dRGetter.call(ctx) }; }
  15125. else { dChosen.get = function(){
  15126. // In this case decoupling could happen on first access instead of first set.
  15127. return utils.assign_core(keycase, valL, dRGetter.call(ctx))
  15128. };
  15129. }
  15130. }
  15131. else {
  15132. // rVal could be an accessor or a nonPrimitive. Either case it needs to be mreged in.
  15133. dChosen.get = function(){ return utils.assign_core(keycase, dLGetter.call(target), dRGetter.call(ctx)) };
  15134. }
  15135. // __setter ! Although this is running in the current context we cant use the dR.set setter like so dL.set = dR.set
  15136. // this is dangerous as we do not know what else the setter does !!!. We don't konw what the getter does either
  15137. // but we need to do a one time read in any case wheter at clone time or at access time.
  15138. dChosen.set = function(val) {
  15139. // First time set on clone decouples
  15140. dChosen.get = function() { return valForSetter};
  15141. dChosen.set = function(val) { return valForSetter = val };
  15142. dChosen.configurable = true;
  15143. Object.defineProperty( target, targetKey, dChosen );
  15144. return valForSetter = val
  15145. };
  15146. dChosen.configurable = true;
  15147. Object.defineProperty( target, targetKey, dChosen );
  15148. finalized[targetKey] = true;
  15149. return
  15150. }
  15151. // Neither is an accessor. valR is nonPrimitive, dL is not an Accessor
  15152. // Target is also a Data Descriptor. We can examine it as well to take a decision.
  15153. var valL = target[targetKey]; // We can examine data descriptors without any side effects. ( Proxies ! are expected to be transparent !! )
  15154. if(utils.js.isPrimitive( valL )) {
  15155. if(!utils.js.isNull( valR ) && !utils.js.isUndefined( valR )) {
  15156. finalized[targetKey] = true;
  15157. Object.defineProperty( target, targetKey, dR );
  15158. }
  15159. return
  15160. }
  15161. else {
  15162. // Neither is Primitive.
  15163. // console.log('Assign Iter...')
  15164. if(valL === valR) { finalized[targetKey] = true; return true;}
  15165. if(utils.js.isObject( valL ) && utils.js.isObject( valR )) { utils.assign_core(keycase, valL, valR ); finalized[targetKey] = true; return;}
  15166. if(utils.js.isArray( valL ) && utils.js.isArray( valR )) { target[targetKey] = valL.concat(valR); finalized[targetKey] = true; return;}
  15167. if(utils.js.isNull( valL ) || utils.js.isNull( valR )) { target[targetKey] = valR; finalized[targetKey] = true; return;}
  15168. if(utils.js.isUndefined( valL ) && utils.js.isUndefined( valR )) { target[targetKey] = valR; finalized[targetKey] = true; return;}
  15169. // Functions are tricky. Closures and bound functinos will continue to refer to source locations and could cause unpredictable behaviour.
  15170. // However if such bound functions are being used the intention must be retention of such linkage.
  15171. // Current behavior is to just override. PB : TODO -- Consider options to have multifunction event handlers... if needed.
  15172. if(utils.js.isFunction( valR )) { target[targetKey] = valR; finalized[targetKey] = true; return;}
  15173. else if (utils.js.isFunction( valL )) { return target[targetKey] = valL; } // target may not be valL scope.
  15174. // Unsupported assign / merge for property datemodified data types Thu Sep 10 2020 15:59:38 GMT+0530 (India Standard Time)
  15175. // , Thu Sep 10 2020 15:54:22 GMT+0530 (India Standard Time)
  15176. // SAM : TODO dates are not getting merged.
  15177. if(utils.js.isDate( valL ) && utils.js.isDate( valR )) { target[targetKey] = valR; return;}
  15178. var msg = `Unsupported assign / merge for property ${targetKey} data types ` + valL + ' , ' + valR;
  15179. console.error(msg);
  15180. throw msg;
  15181. }
  15182. }
  15183. , appendmissing = function (originalkey) {
  15184. var standardizedKey = getNormalizedKey(originalkey);
  15185. if (!hOP.call(finalized, standardizedKey)) overrideOrMerge.call(this, originalkey);
  15186. }
  15187. // Start from the rightmost and override or merge.
  15188. , _junkvar = Object.keys(arguments[arguments.length-1-undef]).forEach(overrideOrMerge, arguments[arguments.length-1-undef])
  15189. , i = arguments.length-1-undef;
  15190. 2 < i--;
  15191. utils.js.isUndefined(arguments[i]) ? null :
  15192. // Intermediate primitives are useless. Skipped coz the target has already been assigned.
  15193. utils.js.isPrimitive(arguments[i]) ? null
  15194. : Object.keys(arguments[i]).forEach(appendmissing, arguments[i])
  15195. ){}
  15196. return target;
  15197. };
  15198. return __assign(...arguments)
  15199. }
  15200. // PB : TODO -- Proper type checking.
  15201. // , __TPL__typeHandlers : {
  15202. // '[object String]' : defaultFn
  15203. // , '[object Array]' : defaultFn
  15204. // , '[object Object]' : defaultFn
  15205. // , '[object Null]' : defaultFn
  15206. // , '[object Undefined]' : defaultFn
  15207. // , '[object Date]' : defaultFn
  15208. // , '[object RegExp]' : defaultFn
  15209. // , '[object Function]' : defaultFn
  15210. // }
  15211. // PB : TODO -- Proper type checking.
  15212. // Javascript language utilities that should have been really in the language itself.
  15213. , js : {
  15214. typeInstances : [
  15215. ""
  15216. , 0
  15217. , true
  15218. , null
  15219. , // undefined
  15220. , []
  15221. , {}
  15222. , Symbol()
  15223. , new Date()
  15224. , /.*/
  15225. , Promise.resolve(true)
  15226. , function() {}
  15227. , BigInt(0)
  15228. ]
  15229. , proxyable : []
  15230. , nonproxyable : []
  15231. , isString(x) {
  15232. return Object.prototype.toString.call(x) === "[object String]"
  15233. }
  15234. , isNumber(x) {
  15235. return Object.prototype.toString.call(x) === '[object Number]'
  15236. }
  15237. , isBoolean(x) {
  15238. return Object.prototype.toString.call(x) === '[object Boolean]'
  15239. }
  15240. , isNull(x) {
  15241. return Object.prototype.toString.call(x) === '[object Null]'
  15242. }
  15243. , isUndefined(x) {
  15244. return Object.prototype.toString.call(x) === '[object Undefined]'
  15245. }
  15246. , isArray(x) {
  15247. return Object.prototype.toString.call(x) === '[object Array]'
  15248. }
  15249. , isObject(x) {
  15250. return Object.prototype.toString.call(x) === '[object Object]'
  15251. }
  15252. , isSymbol(x) {
  15253. return Object.prototype.toString.call(x) === '[object Symbol]'
  15254. }
  15255. , isDate(x) {
  15256. return Object.prototype.toString.call(x) === '[object Date]'
  15257. }
  15258. , isRegExp(x) {
  15259. return Object.prototype.toString.call(x) === '[object RegExp]'
  15260. }
  15261. , isPromise(x) {
  15262. return Promise.resolve(x) === x
  15263. }
  15264. , isPromiseOrFunction(o) {
  15265. if(utils.js.isPromise( o ) || utils.js.isFunction(o)) return true;
  15266. return false;
  15267. }
  15268. , isFunction(x) {
  15269. return Object.prototype.toString.call(x) === '[object Function]'
  15270. }
  15271. , isBigInt(x) {
  15272. return Object.prototype.toString.call(x) === '[object BigInt]'
  15273. }
  15274. , isDataDescriptor(d) { return (utils.js.isUndefined(d.set) && utils.js.isUndefined(d.get)) ? d : false }
  15275. // Grouping JS Types into 4 Groups
  15276. // Primitives
  15277. // -- boolean, String, Number
  15278. // Arrays
  15279. // Objects
  15280. // Special
  15281. // -- date, regexp, function ... and other unkown types
  15282. , typeGroups() {
  15283. return [
  15284. '[Primitive]'
  15285. , '[Null]'
  15286. , '[Undefined]'
  15287. , '[Symbol]'
  15288. , '[Array]'
  15289. , '[Object]'
  15290. , '[Special]'
  15291. ]
  15292. }
  15293. , typeGroup(x) {
  15294. var tgMap = {
  15295. '[object String]' : '[Primitive]'
  15296. , '[object Number]' : '[Primitive]'
  15297. , '[object Boolean]' : '[Primitive]'
  15298. , '[object Null]' : '[Null]'
  15299. , '[object Undefined]' : '[Undefined]'
  15300. , '[object Symbol]' : '[Symbol]'
  15301. , '[object BigInt]' : '[BigInt]'
  15302. , '[object Array]' : '[Array]'
  15303. , '[object Object]' : '[Object]'
  15304. , '[object Date]' : '[Special]'
  15305. , '[object RegExp]' : '[Special]'
  15306. , '[object Function]' : '[Special]'
  15307. , '[object Promise]' : '[Special]'
  15308. };
  15309. return tgMap[Object.prototype.toString.call(x)]
  15310. }
  15311. , getTypeInfo(x) {
  15312. var typeMap = {
  15313. '[object String]' : //__assign(typeInfo,
  15314. { typeGroup : '[Primitive]', isString : true, isPrimitive : true
  15315. , create : ()=>{return ""} }
  15316. //)
  15317. , '[object Number]' : { typeGroup : '[Primitive]', isNumber : true, isNumeric : true, isPrimitive : true
  15318. , create : ()=>{return 1}}
  15319. , '[object Boolean]' : { typeGroup : '[Primitive]', isBoolean : true, isPrimitive : true
  15320. , create : ()=>{return true}}
  15321. , '[object Null]' : { typeGroup : '[Null]', isNull : true
  15322. , create : ()=>{return null}}
  15323. , '[object Undefined]' : { typeGroup : '[Undefined]', isUndefined : true
  15324. , create : ()=>{return }}
  15325. , '[object Symbol]' : { typeGroup : '[Symbol]', isSymbol : true
  15326. , create : ()=>{return new Symbol()}}
  15327. , '[object BigInt]' : { typeGroup : '[BigInt]', isNumeric : true, isPrimitive : true
  15328. , create : ()=>{return new BigInt()}}
  15329. , '[object Array]' : { typeGroup : '[Array]', isArray : true
  15330. , create : ()=>{return []}}
  15331. , '[object Object]' : { typeGroup : '[Object]', isObject : true
  15332. , create : ()=>{return {}}}
  15333. , '[object Date]' : { typeGroup : '[Special]', isDate : true
  15334. , create : ()=>{return new Date}}
  15335. , '[object RegExp]' : { typeGroup : '[Special]', isRegExp : true
  15336. , create : ()=>{return new RegExp}}
  15337. , '[object Function]' : { typeGroup : '[Special]', isFunction : true
  15338. , create : ()=>{return new Function}}
  15339. , '[object Promise]' : { typeGroup : '[Special]', isPromise : true
  15340. , create : ()=>{ throw "Blank promise cannot be created."}}
  15341. };
  15342. return typeMap[Object.prototype.toString.call(x)]
  15343. }
  15344. , isPrimitive(x) {
  15345. var xType = this.nativeType(x);
  15346. return xType === '[object Boolean]' || xType === '[object String]' || xType === '[object Number]' || xType === '[object Symbol]' ||
  15347. xType === '[object BigInt]'
  15348. }
  15349. , isSpecial(x) {
  15350. return !isArray(x) && !isObject(x) && !isPrimitive(x)
  15351. }
  15352. , nativeTypes() {
  15353. return [
  15354. // Primitives
  15355. '[object String]'
  15356. , '[object Number]'
  15357. , '[object Boolean]'
  15358. , '[object Null]'
  15359. , '[object Undefined]'
  15360. , '[object Symbol]'
  15361. , '[object BigInt]'
  15362. // Non Primitives.
  15363. , '[object Array]'
  15364. , '[object Object]'
  15365. , '[object Date]'
  15366. , '[object RegExp]'
  15367. , '[object Function]'
  15368. , '[object Promise]'
  15369. ]
  15370. }
  15371. , nativeType(x) { return Object.prototype.toString.call(x) }
  15372. }
  15373. // Upsert for a hash ??
  15374. , hashupsert : function(oA, oB){
  15375. Object.keys(oA).forEach(( oAKey )=>{
  15376. if(oB[oAKey]) {
  15377. var distinct = new Set(oA[oAKey]);
  15378. oB[oAKey].forEach((each)=>{
  15379. distinct.add(each);
  15380. });
  15381. oA[oAKey] = Array.from(distinct);
  15382. }
  15383. });
  15384. }
  15385. // Upsert for an array.
  15386. // Also the same as pushdistinct. Target is expected to have only one instance.
  15387. , upsert(arr, val) {
  15388. // 0 -- did nothing
  15389. // 2 -- inserted
  15390. // 3 -- updated
  15391. // PB: TODO -- We can use (new Set(arr)).add ???. But is this more expensive ?
  15392. var found = arr.find((element)=>{ return element === val});
  15393. return found ? utils.js.isObject(val) && utils.js.isObject(val) ? (Object.assign( found, val), 3) : 0
  15394. : (arr.push(val), 2) ;
  15395. }
  15396. // accumulate
  15397. // o[toVectorPropName] which is an array
  15398. // and o[propName] which is a string
  15399. // into vectorTarget which is an array
  15400. // already previously accumulated in a similar manner probably already attached as oTarget[toVectorPropName]
  15401. // 0 or undefined or null -- didnt do anything. ( val doesn't exist )
  15402. // 1 -- created target and inserted val
  15403. // 2 -- didn't create target but inserted val
  15404. // 3 -- didn't create target but updated val and also handled o[propName].
  15405. , accumulate : function(val, o, propName, toVectorPropName, vectorTargetCreator,
  15406. identityEvaluator
  15407. ){
  15408. var created = 0;
  15409. if(utils.js.isUndefined(val)) return; // Nothing to do i.e. nothing was provided to accumulate. We don't accumulate undefined.
  15410. if(val === o[propName]) return; // Nothing to do.
  15411. var vectorTargetContainer = o[toVectorPropName] || (o[toVectorPropName] = {});
  15412. if(!vectorTargetCreator) vectorTargetCreator = { create : (val)=>{
  15413. return val ? vectorTargetContainer[o["id"]] = [val] : [] } };
  15414. var vectorTarget = vectorTargetContainer[o["id"]];
  15415. if(!vectorTarget) {
  15416. created = 1;
  15417. vectorTarget = vectorTargetContainer[o["id"]] = vectorTargetCreator.create(o[propName]);
  15418. }
  15419. if(!identityEvaluator) identityEvaluator = (a, b)=>{ return a === b };
  15420. var upsertResult = 0;
  15421. if(!created && !utils.js.isUndefined(o[propName])) {
  15422. if(!vectorTargetContainer[o["id"]].find((element)=>{ return identityEvaluator(element, o[propName]) })) {
  15423. upsertResult = utils.upsert(vectorTarget, o[propName]);
  15424. }
  15425. }
  15426. upsertResult = utils.upsert(vectorTarget, val);
  15427. return created ? created : upsertResult;
  15428. }
  15429. // async Utils
  15430. , async : {
  15431. all(list, task){
  15432. var queueditems=[];
  15433. list.forEach(function(v, i, a) {
  15434. queueditems.push(task(v, i, a));
  15435. });
  15436. return Promise.all(queueditems)
  15437. }
  15438. }
  15439. // PB : TODO -- Remove these.
  15440. // , fsdb : require('./fsdb/fsdb')
  15441. // , xlsx : require('./fsdb/xlsx')
  15442. // , xlsxvalidator : require('./fsdb/xlsxvalidator')
  15443. , timeUtils
  15444. , dx: dx_1
  15445. , cliargs: cliargs$1
  15446. , any: any$3
  15447. , promisify
  15448. , moment
  15449. , Tasq: Tasq$1
  15450. , Traq: Traq$1
  15451. , validationhelpers : validationhelpers
  15452. };
  15453. var utils_1 = utils;
  15454. var naiveFallback = function () {
  15455. if (typeof self === "object" && self) return self;
  15456. if (typeof window === "object" && window) return window;
  15457. throw new Error("Unable to resolve global `this`");
  15458. };
  15459. // https://mathiasbynens.be/notes/globalthis
  15460. var globalThis_1 = (function () {
  15461. if (this) return this;
  15462. // Unexpected strict mode (may happen if e.g. bundled into ESM module)
  15463. // Fallback to standard globalThis if available
  15464. if (typeof globalThis === "object" && globalThis) return globalThis;
  15465. // Thanks @mathiasbynens -> https://mathiasbynens.be/notes/globalthis
  15466. // In all ES5+ engines global object inherits from Object.prototype
  15467. // (if you approached one that doesn't please report)
  15468. try {
  15469. Object.prototype.__defineGetter__('__global__', function() {
  15470. return this;
  15471. });
  15472. __global__.globalThis = __global__; // lolwat
  15473. } catch (error) {
  15474. // Unfortunate case of updates to Object.prototype being restricted
  15475. // via preventExtensions, seal or freeze
  15476. return naiveFallback();
  15477. }
  15478. try {
  15479. // Safari case (window.__global__ works, but __global__ does not)
  15480. if (!__global__) return naiveFallback();
  15481. return __global__;
  15482. } finally {
  15483. delete Object.prototype.__global__;
  15484. }
  15485. })();
  15486. // A selector based channels implementation as compared to a simple array.
  15487. var channelMixin = (function() {
  15488. // get channels that qualify for a selector.
  15489. function getSubscriptions(selector) {
  15490. console.dir(this.__channels);
  15491. var filtered = this.__channels; // start with the world...
  15492. // Selector is a simple list of tags.
  15493. for(var select in selector) {
  15494. if(!filtered[selector[select]]) {
  15495. // If the assumption is that all indexes are properly built it implies this channel doesn't exist.
  15496. return []; // We are looking for all selectors therefore if even one fails we don't have anything.
  15497. }
  15498. filtered = filtered[selector[select]];
  15499. }
  15500. return filtered['__data']; // Flattened array
  15501. }
  15502. function addSubscription(selector, func, context) {
  15503. var unfulfilled = selector.splice(0);
  15504. var filtered = this.__channels; // start with the world...
  15505. console.log(filtered);
  15506. for(var select in unfulfilled) {
  15507. if(!filtered[unfulfilled[select]]) {
  15508. filtered[unfulfilled[select]] = { __data : [] };
  15509. }
  15510. filtered = filtered[unfulfilled[select]];
  15511. unfulfilled = unfulfilled.splice(0,1);
  15512. }
  15513. // PB : TODO -- All accessor paths need to be indexed !
  15514. // Will currently fail if not published and queried in the same order.
  15515. filtered.__data.push({context: context, callback: func});
  15516. }
  15517. return function(){
  15518. this.__channels = {};
  15519. this.getSubscriptions = getSubscriptions;
  15520. this.addSubscription = addSubscription;
  15521. return this;
  15522. }
  15523. })();
  15524. // Mediator pattern.
  15525. var mediator = (function() {
  15526. var __subscribe = function(selector, func, context) {
  15527. var subscriptions = this.channels.getSubscriptions(selector);
  15528. if(subscriptions.length < 1){
  15529. this.channels.addSubscription(selector, func, context);
  15530. }
  15531. return this;
  15532. };
  15533. var __publish = function(selector) {
  15534. console.log('publishing for selector ' + selector);
  15535. var subscriptions = this.channels.getSubscriptions(selector);
  15536. console.log(subscriptions);
  15537. if(subscriptions.length < 1){ return; }
  15538. var args = Array.prototype.slice.call(arguments, 1);
  15539. for(i=0; i < subscriptions.length; i++) {
  15540. subscription = subscriptions[i];
  15541. subscription.callback.apply(subscription.context, args);
  15542. }
  15543. return this;
  15544. };
  15545. return function mediator() {
  15546. var thisObj = this ? this : {};
  15547. Object.defineProperty(thisObj, 'channels', { value : channelMixin.apply({}), writable: false, enumerable : false});
  15548. thisObj.publish = __publish;
  15549. thisObj.subscribe = __subscribe;
  15550. return thisObj;
  15551. };
  15552. })();
  15553. // Unique ID creation requires a high quality random # generator. In the browser we therefore
  15554. // require the crypto API and do not support built-in fallback to lower quality random number
  15555. // generators (like Math.random()).
  15556. var getRandomValues;
  15557. var rnds8 = new Uint8Array(16);
  15558. function rng() {
  15559. // lazy load so that environments that need to polyfill have a chance to do so
  15560. if (!getRandomValues) {
  15561. // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also,
  15562. // find the complete implementation of crypto (msCrypto) on IE11.
  15563. getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto);
  15564. if (!getRandomValues) {
  15565. throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
  15566. }
  15567. }
  15568. return getRandomValues(rnds8);
  15569. }
  15570. var REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
  15571. function validate(uuid) {
  15572. return typeof uuid === 'string' && REGEX.test(uuid);
  15573. }
  15574. /**
  15575. * Convert array of 16 byte values to UUID string format of the form:
  15576. * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
  15577. */
  15578. var byteToHex = [];
  15579. for (var i$2 = 0; i$2 < 256; ++i$2) {
  15580. byteToHex.push((i$2 + 0x100).toString(16).substr(1));
  15581. }
  15582. function stringify(arr) {
  15583. var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  15584. // Note: Be careful editing this code! It's been tuned for performance
  15585. // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
  15586. var uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one
  15587. // of the following:
  15588. // - One or more input array values don't map to a hex octet (leading to
  15589. // "undefined" in the uuid)
  15590. // - Invalid input values for the RFC `version` or `variant` fields
  15591. if (!validate(uuid)) {
  15592. throw TypeError('Stringified UUID is invalid');
  15593. }
  15594. return uuid;
  15595. }
  15596. //
  15597. // Inspired by https://github.com/LiosK/UUID.js
  15598. // and http://docs.python.org/library/uuid.html
  15599. var _nodeId;
  15600. var _clockseq; // Previous uuid creation time
  15601. var _lastMSecs = 0;
  15602. var _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details
  15603. function v1(options, buf, offset) {
  15604. var i = buf && offset || 0;
  15605. var b = buf || new Array(16);
  15606. options = options || {};
  15607. var node = options.node || _nodeId;
  15608. var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not
  15609. // specified. We do this lazily to minimize issues related to insufficient
  15610. // system entropy. See #189
  15611. if (node == null || clockseq == null) {
  15612. var seedBytes = options.random || (options.rng || rng)();
  15613. if (node == null) {
  15614. // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
  15615. node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];
  15616. }
  15617. if (clockseq == null) {
  15618. // Per 4.2.2, randomize (14 bit) clockseq
  15619. clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;
  15620. }
  15621. } // UUID timestamps are 100 nano-second units since the Gregorian epoch,
  15622. // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
  15623. // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
  15624. // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
  15625. var msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock
  15626. // cycle to simulate higher resolution clock
  15627. var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs)
  15628. var dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression
  15629. if (dt < 0 && options.clockseq === undefined) {
  15630. clockseq = clockseq + 1 & 0x3fff;
  15631. } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
  15632. // time interval
  15633. if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
  15634. nsecs = 0;
  15635. } // Per 4.2.1.2 Throw error if too many uuids are requested
  15636. if (nsecs >= 10000) {
  15637. throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");
  15638. }
  15639. _lastMSecs = msecs;
  15640. _lastNSecs = nsecs;
  15641. _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
  15642. msecs += 12219292800000; // `time_low`
  15643. var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
  15644. b[i++] = tl >>> 24 & 0xff;
  15645. b[i++] = tl >>> 16 & 0xff;
  15646. b[i++] = tl >>> 8 & 0xff;
  15647. b[i++] = tl & 0xff; // `time_mid`
  15648. var tmh = msecs / 0x100000000 * 10000 & 0xfffffff;
  15649. b[i++] = tmh >>> 8 & 0xff;
  15650. b[i++] = tmh & 0xff; // `time_high_and_version`
  15651. b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
  15652. b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
  15653. b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low`
  15654. b[i++] = clockseq & 0xff; // `node`
  15655. for (var n = 0; n < 6; ++n) {
  15656. b[i + n] = node[n];
  15657. }
  15658. return buf || stringify(b);
  15659. }
  15660. function parse$1(uuid) {
  15661. if (!validate(uuid)) {
  15662. throw TypeError('Invalid UUID');
  15663. }
  15664. var v;
  15665. var arr = new Uint8Array(16); // Parse ########-....-....-....-............
  15666. arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;
  15667. arr[1] = v >>> 16 & 0xff;
  15668. arr[2] = v >>> 8 & 0xff;
  15669. arr[3] = v & 0xff; // Parse ........-####-....-....-............
  15670. arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;
  15671. arr[5] = v & 0xff; // Parse ........-....-####-....-............
  15672. arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;
  15673. arr[7] = v & 0xff; // Parse ........-....-....-####-............
  15674. arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;
  15675. arr[9] = v & 0xff; // Parse ........-....-....-....-############
  15676. // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes)
  15677. arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;
  15678. arr[11] = v / 0x100000000 & 0xff;
  15679. arr[12] = v >>> 24 & 0xff;
  15680. arr[13] = v >>> 16 & 0xff;
  15681. arr[14] = v >>> 8 & 0xff;
  15682. arr[15] = v & 0xff;
  15683. return arr;
  15684. }
  15685. function stringToBytes(str) {
  15686. str = unescape(encodeURIComponent(str)); // UTF8 escape
  15687. var bytes = [];
  15688. for (var i = 0; i < str.length; ++i) {
  15689. bytes.push(str.charCodeAt(i));
  15690. }
  15691. return bytes;
  15692. }
  15693. var DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
  15694. var URL$1 = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';
  15695. function v35 (name, version, hashfunc) {
  15696. function generateUUID(value, namespace, buf, offset) {
  15697. if (typeof value === 'string') {
  15698. value = stringToBytes(value);
  15699. }
  15700. if (typeof namespace === 'string') {
  15701. namespace = parse$1(namespace);
  15702. }
  15703. if (namespace.length !== 16) {
  15704. throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');
  15705. } // Compute hash of namespace and value, Per 4.3
  15706. // Future: Use spread syntax when supported on all platforms, e.g. `bytes =
  15707. // hashfunc([...namespace, ... value])`
  15708. var bytes = new Uint8Array(16 + value.length);
  15709. bytes.set(namespace);
  15710. bytes.set(value, namespace.length);
  15711. bytes = hashfunc(bytes);
  15712. bytes[6] = bytes[6] & 0x0f | version;
  15713. bytes[8] = bytes[8] & 0x3f | 0x80;
  15714. if (buf) {
  15715. offset = offset || 0;
  15716. for (var i = 0; i < 16; ++i) {
  15717. buf[offset + i] = bytes[i];
  15718. }
  15719. return buf;
  15720. }
  15721. return stringify(bytes);
  15722. } // Function#name is not settable on some platforms (#270)
  15723. try {
  15724. generateUUID.name = name; // eslint-disable-next-line no-empty
  15725. } catch (err) {} // For CommonJS default export support
  15726. generateUUID.DNS = DNS;
  15727. generateUUID.URL = URL$1;
  15728. return generateUUID;
  15729. }
  15730. /*
  15731. * Browser-compatible JavaScript MD5
  15732. *
  15733. * Modification of JavaScript MD5
  15734. * https://github.com/blueimp/JavaScript-MD5
  15735. *
  15736. * Copyright 2011, Sebastian Tschan
  15737. * https://blueimp.net
  15738. *
  15739. * Licensed under the MIT license:
  15740. * https://opensource.org/licenses/MIT
  15741. *
  15742. * Based on
  15743. * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
  15744. * Digest Algorithm, as defined in RFC 1321.
  15745. * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009
  15746. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
  15747. * Distributed under the BSD License
  15748. * See http://pajhome.org.uk/crypt/md5 for more info.
  15749. */
  15750. function md5(bytes) {
  15751. if (typeof bytes === 'string') {
  15752. var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape
  15753. bytes = new Uint8Array(msg.length);
  15754. for (var i = 0; i < msg.length; ++i) {
  15755. bytes[i] = msg.charCodeAt(i);
  15756. }
  15757. }
  15758. return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8));
  15759. }
  15760. /*
  15761. * Convert an array of little-endian words to an array of bytes
  15762. */
  15763. function md5ToHexEncodedArray(input) {
  15764. var output = [];
  15765. var length32 = input.length * 32;
  15766. var hexTab = '0123456789abcdef';
  15767. for (var i = 0; i < length32; i += 8) {
  15768. var x = input[i >> 5] >>> i % 32 & 0xff;
  15769. var hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16);
  15770. output.push(hex);
  15771. }
  15772. return output;
  15773. }
  15774. /**
  15775. * Calculate output length with padding and bit length
  15776. */
  15777. function getOutputLength(inputLength8) {
  15778. return (inputLength8 + 64 >>> 9 << 4) + 14 + 1;
  15779. }
  15780. /*
  15781. * Calculate the MD5 of an array of little-endian words, and a bit length.
  15782. */
  15783. function wordsToMd5(x, len) {
  15784. /* append padding */
  15785. x[len >> 5] |= 0x80 << len % 32;
  15786. x[getOutputLength(len) - 1] = len;
  15787. var a = 1732584193;
  15788. var b = -271733879;
  15789. var c = -1732584194;
  15790. var d = 271733878;
  15791. for (var i = 0; i < x.length; i += 16) {
  15792. var olda = a;
  15793. var oldb = b;
  15794. var oldc = c;
  15795. var oldd = d;
  15796. a = md5ff(a, b, c, d, x[i], 7, -680876936);
  15797. d = md5ff(d, a, b, c, x[i + 1], 12, -389564586);
  15798. c = md5ff(c, d, a, b, x[i + 2], 17, 606105819);
  15799. b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330);
  15800. a = md5ff(a, b, c, d, x[i + 4], 7, -176418897);
  15801. d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426);
  15802. c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341);
  15803. b = md5ff(b, c, d, a, x[i + 7], 22, -45705983);
  15804. a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416);
  15805. d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417);
  15806. c = md5ff(c, d, a, b, x[i + 10], 17, -42063);
  15807. b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162);
  15808. a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682);
  15809. d = md5ff(d, a, b, c, x[i + 13], 12, -40341101);
  15810. c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290);
  15811. b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329);
  15812. a = md5gg(a, b, c, d, x[i + 1], 5, -165796510);
  15813. d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632);
  15814. c = md5gg(c, d, a, b, x[i + 11], 14, 643717713);
  15815. b = md5gg(b, c, d, a, x[i], 20, -373897302);
  15816. a = md5gg(a, b, c, d, x[i + 5], 5, -701558691);
  15817. d = md5gg(d, a, b, c, x[i + 10], 9, 38016083);
  15818. c = md5gg(c, d, a, b, x[i + 15], 14, -660478335);
  15819. b = md5gg(b, c, d, a, x[i + 4], 20, -405537848);
  15820. a = md5gg(a, b, c, d, x[i + 9], 5, 568446438);
  15821. d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690);
  15822. c = md5gg(c, d, a, b, x[i + 3], 14, -187363961);
  15823. b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501);
  15824. a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467);
  15825. d = md5gg(d, a, b, c, x[i + 2], 9, -51403784);
  15826. c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473);
  15827. b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734);
  15828. a = md5hh(a, b, c, d, x[i + 5], 4, -378558);
  15829. d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463);
  15830. c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562);
  15831. b = md5hh(b, c, d, a, x[i + 14], 23, -35309556);
  15832. a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060);
  15833. d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353);
  15834. c = md5hh(c, d, a, b, x[i + 7], 16, -155497632);
  15835. b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640);
  15836. a = md5hh(a, b, c, d, x[i + 13], 4, 681279174);
  15837. d = md5hh(d, a, b, c, x[i], 11, -358537222);
  15838. c = md5hh(c, d, a, b, x[i + 3], 16, -722521979);
  15839. b = md5hh(b, c, d, a, x[i + 6], 23, 76029189);
  15840. a = md5hh(a, b, c, d, x[i + 9], 4, -640364487);
  15841. d = md5hh(d, a, b, c, x[i + 12], 11, -421815835);
  15842. c = md5hh(c, d, a, b, x[i + 15], 16, 530742520);
  15843. b = md5hh(b, c, d, a, x[i + 2], 23, -995338651);
  15844. a = md5ii(a, b, c, d, x[i], 6, -198630844);
  15845. d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415);
  15846. c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905);
  15847. b = md5ii(b, c, d, a, x[i + 5], 21, -57434055);
  15848. a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571);
  15849. d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606);
  15850. c = md5ii(c, d, a, b, x[i + 10], 15, -1051523);
  15851. b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799);
  15852. a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359);
  15853. d = md5ii(d, a, b, c, x[i + 15], 10, -30611744);
  15854. c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380);
  15855. b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649);
  15856. a = md5ii(a, b, c, d, x[i + 4], 6, -145523070);
  15857. d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379);
  15858. c = md5ii(c, d, a, b, x[i + 2], 15, 718787259);
  15859. b = md5ii(b, c, d, a, x[i + 9], 21, -343485551);
  15860. a = safeAdd(a, olda);
  15861. b = safeAdd(b, oldb);
  15862. c = safeAdd(c, oldc);
  15863. d = safeAdd(d, oldd);
  15864. }
  15865. return [a, b, c, d];
  15866. }
  15867. /*
  15868. * Convert an array bytes to an array of little-endian words
  15869. * Characters >255 have their high-byte silently ignored.
  15870. */
  15871. function bytesToWords(input) {
  15872. if (input.length === 0) {
  15873. return [];
  15874. }
  15875. var length8 = input.length * 8;
  15876. var output = new Uint32Array(getOutputLength(length8));
  15877. for (var i = 0; i < length8; i += 8) {
  15878. output[i >> 5] |= (input[i / 8] & 0xff) << i % 32;
  15879. }
  15880. return output;
  15881. }
  15882. /*
  15883. * Add integers, wrapping at 2^32. This uses 16-bit operations internally
  15884. * to work around bugs in some JS interpreters.
  15885. */
  15886. function safeAdd(x, y) {
  15887. var lsw = (x & 0xffff) + (y & 0xffff);
  15888. var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  15889. return msw << 16 | lsw & 0xffff;
  15890. }
  15891. /*
  15892. * Bitwise rotate a 32-bit number to the left.
  15893. */
  15894. function bitRotateLeft(num, cnt) {
  15895. return num << cnt | num >>> 32 - cnt;
  15896. }
  15897. /*
  15898. * These functions implement the four basic operations the algorithm uses.
  15899. */
  15900. function md5cmn(q, a, b, x, s, t) {
  15901. return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b);
  15902. }
  15903. function md5ff(a, b, c, d, x, s, t) {
  15904. return md5cmn(b & c | ~b & d, a, b, x, s, t);
  15905. }
  15906. function md5gg(a, b, c, d, x, s, t) {
  15907. return md5cmn(b & d | c & ~d, a, b, x, s, t);
  15908. }
  15909. function md5hh(a, b, c, d, x, s, t) {
  15910. return md5cmn(b ^ c ^ d, a, b, x, s, t);
  15911. }
  15912. function md5ii(a, b, c, d, x, s, t) {
  15913. return md5cmn(c ^ (b | ~d), a, b, x, s, t);
  15914. }
  15915. var v3 = v35('v3', 0x30, md5);
  15916. var v3$1 = v3;
  15917. function v4(options, buf, offset) {
  15918. options = options || {};
  15919. var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
  15920. rnds[6] = rnds[6] & 0x0f | 0x40;
  15921. rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
  15922. if (buf) {
  15923. offset = offset || 0;
  15924. for (var i = 0; i < 16; ++i) {
  15925. buf[offset + i] = rnds[i];
  15926. }
  15927. return buf;
  15928. }
  15929. return stringify(rnds);
  15930. }
  15931. // Adapted from Chris Veness' SHA1 code at
  15932. // http://www.movable-type.co.uk/scripts/sha1.html
  15933. function f(s, x, y, z) {
  15934. switch (s) {
  15935. case 0:
  15936. return x & y ^ ~x & z;
  15937. case 1:
  15938. return x ^ y ^ z;
  15939. case 2:
  15940. return x & y ^ x & z ^ y & z;
  15941. case 3:
  15942. return x ^ y ^ z;
  15943. }
  15944. }
  15945. function ROTL(x, n) {
  15946. return x << n | x >>> 32 - n;
  15947. }
  15948. function sha1(bytes) {
  15949. var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];
  15950. var H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];
  15951. if (typeof bytes === 'string') {
  15952. var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape
  15953. bytes = [];
  15954. for (var i = 0; i < msg.length; ++i) {
  15955. bytes.push(msg.charCodeAt(i));
  15956. }
  15957. } else if (!Array.isArray(bytes)) {
  15958. // Convert Array-like to Array
  15959. bytes = Array.prototype.slice.call(bytes);
  15960. }
  15961. bytes.push(0x80);
  15962. var l = bytes.length / 4 + 2;
  15963. var N = Math.ceil(l / 16);
  15964. var M = new Array(N);
  15965. for (var _i = 0; _i < N; ++_i) {
  15966. var arr = new Uint32Array(16);
  15967. for (var j = 0; j < 16; ++j) {
  15968. arr[j] = bytes[_i * 64 + j * 4] << 24 | bytes[_i * 64 + j * 4 + 1] << 16 | bytes[_i * 64 + j * 4 + 2] << 8 | bytes[_i * 64 + j * 4 + 3];
  15969. }
  15970. M[_i] = arr;
  15971. }
  15972. M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32);
  15973. M[N - 1][14] = Math.floor(M[N - 1][14]);
  15974. M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff;
  15975. for (var _i2 = 0; _i2 < N; ++_i2) {
  15976. var W = new Uint32Array(80);
  15977. for (var t = 0; t < 16; ++t) {
  15978. W[t] = M[_i2][t];
  15979. }
  15980. for (var _t = 16; _t < 80; ++_t) {
  15981. W[_t] = ROTL(W[_t - 3] ^ W[_t - 8] ^ W[_t - 14] ^ W[_t - 16], 1);
  15982. }
  15983. var a = H[0];
  15984. var b = H[1];
  15985. var c = H[2];
  15986. var d = H[3];
  15987. var e = H[4];
  15988. for (var _t2 = 0; _t2 < 80; ++_t2) {
  15989. var s = Math.floor(_t2 / 20);
  15990. var T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[_t2] >>> 0;
  15991. e = d;
  15992. d = c;
  15993. c = ROTL(b, 30) >>> 0;
  15994. b = a;
  15995. a = T;
  15996. }
  15997. H[0] = H[0] + a >>> 0;
  15998. H[1] = H[1] + b >>> 0;
  15999. H[2] = H[2] + c >>> 0;
  16000. H[3] = H[3] + d >>> 0;
  16001. H[4] = H[4] + e >>> 0;
  16002. }
  16003. return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff];
  16004. }
  16005. var v5 = v35('v5', 0x50, sha1);
  16006. var v5$1 = v5;
  16007. var nil = '00000000-0000-0000-0000-000000000000';
  16008. function version$1(uuid) {
  16009. if (!validate(uuid)) {
  16010. throw TypeError('Invalid UUID');
  16011. }
  16012. return parseInt(uuid.substr(14, 1), 16);
  16013. }
  16014. var esmBrowser = /*#__PURE__*/Object.freeze({
  16015. __proto__: null,
  16016. v1: v1,
  16017. v3: v3$1,
  16018. v4: v4,
  16019. v5: v5$1,
  16020. NIL: nil,
  16021. version: version$1,
  16022. validate: validate,
  16023. stringify: stringify,
  16024. parse: parse$1
  16025. });
  16026. var require$$3$1 = /*@__PURE__*/getAugmentedNamespace(esmBrowser);
  16027. var core = createCommonjsModule(function (module) {
  16028. // var nonStrictThis = function(){ return this; }
  16029. // var strictThis = function(){ 'use strict'; return this; }
  16030. (function(){
  16031. // import jstpl from './jstpl';
  16032. // var jstpl = require('./jstpl');
  16033. var utils = utils_1;
  16034. // var __mEV = function(fnstr) {
  16035. // return eval(fnstr);
  16036. // }
  16037. // In strict mode this in Global Scope is not the real global object but a global current context object.
  16038. // Therefore this === global is false.
  16039. // https://stackoverflow.com/questions/3277182/how-to-get-the-global-object-in-javascript
  16040. // var __G = {
  16041. // // Either the module scope or the global scope. In node this is the module scope.
  16042. // __scope : this
  16043. // // Makes sure the global scope.
  16044. // , __g : (function () {
  16045. // // global || window || WorkerGlobalScope || ???modulescope??? ;
  16046. // return Function('return this')() || (0, eval)('this');
  16047. // }())
  16048. // , __eV : eval
  16049. // , __getMVar(varname) {
  16050. // return eval(varname);
  16051. // }
  16052. // };
  16053. var __g = globalThis_1;
  16054. // var __g = __G.__g;
  16055. __g.mediator = mediator.apply({});
  16056. // __g.mediator = __g.mediator.apply({})
  16057. console.dir(__g.mediator);
  16058. // __g.mediator = __g.mediator.apply({});
  16059. //
  16060. function __is__(t, type){
  16061. if(utils.js.isPrimitive(t)) return false;
  16062. if(!t || !t.mixins) return false;
  16063. return t.__mixins().get(type) ? true : false ; }
  16064. // Clazz so as to not conflict with Class ECMAScript keyword. Note the need for this arizes from mixins not bieng easy with Class !?
  16065. const Clazz = (function(){
  16066. // The class factory.
  16067. const __Clazz = function( clazz /* Your class constructor function or extension object ? */) {
  16068. // If clazz a function defined in its closure we honor that as the constructor.
  16069. return (function(){
  16070. // The actual class constructor
  16071. function __Class() {
  16072. // In strict mode we will get undefined. For Ember transpiled with webpack in the browser we should be fine... ( Check other browsers. )
  16073. if(this === undefined) throw 'Invalid Instance for creation. Cannot be global. Please use Fn.apply or Fn.call with appropriate this scope.'
  16074. if(this === __g) throw 'Invalid Instance for creation. Cannot be global. Please use Fn.apply or Fn.call with appropriate this scope.'
  16075. // new YYYY -- should not be used anywhere.
  16076. // if you use apply or call to invoke
  16077. // we will try to discover whether you called us in such a way to the best extent possible.
  16078. // this === globalthis to not adequate
  16079. // Eg : We could be called as
  16080. // theirclazz.create() && theirclazz() are equivalent
  16081. // theirclazz.create( ...extensions )
  16082. // theirclazz( ...extensions )
  16083. // theirclazz.create.call( otoMorph, ...extensions )
  16084. // If you already have an instance that you want to morph use call or apply
  16085. return utils.assign(this, ...arguments)
  16086. }
  16087. // Pristine overrides. Can never be overridden at construction time. Users can easily overrid later...
  16088. var __cp = {
  16089. createusing( oToMorh, ...extensions ){ return utils.assign(oToMorh, ...extensions) }
  16090. , extend(){
  16091. // All new and old instances should get these extensions !?!#@@$
  16092. // older instances are an issue. They could have already overridden. Will need to shift the base proto of all older instances to achieve this !?
  16093. // Current support is only for new instaces created after extend is called.
  16094. // PB : TODO -- Swtich the __proto__ for proper extend support.
  16095. // Should we retain the original extend, create and createusing. Well if you are interested in overriding we should make a provision.
  16096. if( this === __Class) return utils.assign(__Class, ...arguments /*, { extend : __Class.extend, create : __Class.create, createusing : __Class.createusing }*/ )
  16097. else return utils.assign(this, ...arguments /*, { extend : __Class.extend, create : __Class.create, createusing : __Class.createusing }*/ )
  16098. }
  16099. , create : __Class
  16100. };
  16101. var __createusing = __cp.createusing;
  16102. var __constructor = utils.js.isFunction(clazz) ? clazz : null;
  16103. if( __constructor ){
  16104. // We have to support a call site function passed in. But we cannot replace the function itself. So we wrap it and send a different constructur as the class.
  16105. var originalcr = clazz.create || clazz;
  16106. var originalcu = clazz.createusing || function(){ return originalcr.apply(o, arguments) };
  16107. __cp.create = function(){ var o = __Class(...arguments); return originalcu(o, ...arguments) }; // Your constructor should be your create but we switch it to trap here.
  16108. __cp.createusing = function(oToMorh, ...extensions ){
  16109. // PB : TODO -- __g check may not be enough. We need to see what the this object is in the context of the call site function with strict or nonstrict mode !?
  16110. // coz it is different from __g. The purpose of __g is to have a single object acroos the app...
  16111. oToMorh === __g ? (function() { throw 'Cannot use global object in inheritance' })()
  16112. : function(){ var o = __createusing(oToMorh, ...arguments); return originalcu(o, ...arguments) };
  16113. };
  16114. return utils.assign(__Class, __constructor, ...arguments, __cp)
  16115. }
  16116. else if (clazz) {
  16117. // Should all class static members be public and also accessible by instance members ?
  16118. // Privacy is the implementers concern. Provide your own closures to secure your data.
  16119. // Which means all attached members that are public here should continue to be public. Whether they are shared ( referenced ) or deep copied is a strategy decision...
  16120. // Functions are easy to handle.
  16121. // Shared data could either be overridable (instance) or static at the class level.
  16122. // Its a bad practice to have static attributes set directly on the class. Allways use accessors or static functions with closures for such data.
  16123. // It may be inevitable but to switch the function prototype to properly address instance level shared data until overridden.
  16124. // Prototypal chains are themselves slow but current strategy of copy everithing for every instance is not a good idea either.
  16125. // Best middle ground is to have a squished prototype chain into a single proto for all instances without the chain.
  16126. // Squishing will require accessors with an override so we don't have to walk the prototype chain...
  16127. // utils.assign already handles this well.
  16128. var originalcr = clazz.create || function(){};
  16129. var originalcu = clazz.createusing || function(){ return originalcr.apply(o, ...arguments) };
  16130. __Class.create = function(){ var o = __Class(...arguments); return originalcu(o, ...arguments) };
  16131. __Class.createusing = function(oToMorh, ...extensions ){
  16132. // PB : TODO -- __g check may not be enough. We need to see what the this object is in the context of the call site function with strict or nonstrict mode !?
  16133. // coz it is different from __g. The purpose of __g is to have a single object acroos the app...
  16134. oToMorh === __g ? (function() { throw 'Cannot use global object in inheritance' })()
  16135. : function(){ var o = __createusing(oToMorh, ...arguments); return originalcu(o, ...arguments) };
  16136. };
  16137. return utils.assign(__Class, clazz, ...arguments, __cp)
  16138. }
  16139. else return utils.assign(__Class, ...arguments, __cp)
  16140. })()
  16141. };
  16142. __Clazz.create = __Clazz;
  16143. return __Clazz
  16144. })();
  16145. const Mixin = (function(){
  16146. function __createMixBase(clazz){
  16147. if(clazz.is && clazz.is(Mixin)) return clazz;
  16148. return Object.assign(clazz, {
  16149. __mixins : (()=>{ var _m = new WeakMap(); return _m.set(Mixin, true); })()
  16150. , is(){ return __is__(clazz, Mixin) }
  16151. })
  16152. }
  16153. function __createdMixinClazz(clazz, ...others){
  16154. // !! getMixinFor(arguements) No need. We just create a new one.
  16155. var m = __createMixBase(clazz || {});
  16156. m.extend = function(){
  16157. // Is extend callable on an Instance ? No reason why it shouldn't be callable. The behavior will be that it will return a new class not an instance.
  16158. // Although instances and classes do not need to be distinguished in our context.
  16159. Array.from(arguments).forEach(clazz => { this.__mixins.set(clazz, true); });
  16160. // Extend should alter and evolve the class or instance it is enxtening such that all other instances created after should have the extensions.
  16161. return utils.assign(this, ...arguments)
  16162. };
  16163. // PB : TODO -- Addmixin should require a reopen... already created instances may need a prototype switch !?
  16164. // Currently addmixin should only be called before the first instance create of the real extended type
  16165. m.addMixin = function(clazz){ this.__mixins.set(clazz, true); return utils.assign(this, clazz) };
  16166. // Switch to retain the same base mixin when called second time onwards.
  16167. // __createdMixinClazz = function(){ return this }
  16168. // PB : TODO mixins should not be createable once created.... Only extend should be supprted
  16169. // retain create for backward compatibility to return the same mixin untill all creates are replaced.
  16170. // create is an instance create and should be the create of the most derived clazz in the list of constructors...
  16171. m.create = function(){ return m }; //__createdMixinClazz
  16172. return m.extend.apply(m, others)
  16173. // This is not a mixin instance. This is a class factory that returns a new base mixin class for each
  16174. // type that is extending. Therefore create is meaningless for Mixin... Always use extend.
  16175. // However every successive call to extend once already extended should not keep recreating the base but rather reuse the base.
  16176. }
  16177. function __Mixin(){
  16178. return __createdMixinClazz.apply(null, arguments) }
  16179. __Mixin.create = __Mixin; // Gives you a clazz that you need to reuse. Do not keep calling for each instance !!!
  16180. __Mixin.extend = __Mixin; // Same behavior here
  16181. return __Mixin
  16182. })();
  16183. const indexHelper = (function(){
  16184. var getPermutations = function(array){
  16185. var permutations = {};
  16186. // l(array.splice(0, 1))
  16187. for(var i in array) {
  16188. // l(array[i]);
  16189. var aclone = array.slice(0);
  16190. aclone.splice(i, 1);
  16191. permutations[array[i]] = getPermutations(aclone );
  16192. }
  16193. return permutations
  16194. };
  16195. var getCombinations = function(array){
  16196. // P & C
  16197. // http://www.scielo.br/scielo.php?script=sci_arttext&pid=S0104-65002001000200009
  16198. var set = [];
  16199. var alen = array.length;
  16200. var combinations = 1 << alen; // Math.pow(2, array.length);
  16201. for (var i = 1; i < combinations ; i++){
  16202. var combination= [];
  16203. for (var j=0;j<alen;j++) {
  16204. if ((i & (1 << j))){
  16205. combination.push(array[j]);
  16206. }
  16207. }
  16208. set.push(combination);
  16209. }
  16210. return set;
  16211. };
  16212. return function(obj) {
  16213. obj.getPermutations = getPermutations;
  16214. // obj.getPermutations = getPermutations_HeapsMethod;
  16215. obj.getCombinations = getCombinations;
  16216. return obj;
  16217. };
  16218. })();
  16219. const AnyStore = (function(){
  16220. // A store that can store any type and lookup any type.
  16221. // Weakmaps cannot have primitives as keys and hashs cannot have objects as keys.
  16222. // This wraps hash and a weakmap into an abstract class that routes to the appropriate
  16223. // store based on the type of the object.
  16224. const getForPrimitive = function(primitive, target) { return target.storeForPrmitives[primitive] };
  16225. const getForObject = function(obj, target) { return target.storeForObjects.get(obj) };
  16226. const getForSymbol = function(symbol, target) { return target.storeForObjects.get(target.__symbolToObj[symbol]) };
  16227. const setForPrimitive = function(primitive, content, target) {
  16228. // PB : -- Note : Importatn -- No difference between 100 and "100" due to JS keys all being strings...
  16229. target.storeForPrmitives[primitive] = content;
  16230. return content;
  16231. };
  16232. const setForObject = function(obj, content, target) {
  16233. // PB : TODO -- need to listen to changes in content and its attributes to re-index it.
  16234. target.storeForObjects.set(obj, content);
  16235. return content;
  16236. };
  16237. const setForSymbol = function(symbol, content, target) {
  16238. // PB : TODO -- need to listen to changes in content and its attributes to re-index it.
  16239. target.storeForObjects.set(target.__symbolToObj[symbol], content);
  16240. return content;
  16241. };
  16242. const getFor = {
  16243. '[object String]' : getForPrimitive
  16244. , '[object Object]' : getForObject
  16245. , '[object Date]' : getForObject
  16246. , '[object Symbol]' : getForSymbol
  16247. };
  16248. getFor['[object Number]'] = getFor['[object String]'];
  16249. getFor['[object Array]'] = getFor['[object Object]'];
  16250. const setFor = {
  16251. '[object String]' : setForPrimitive
  16252. , '[object Object]' : setForObject
  16253. , '[object Date]' : setForObject
  16254. , '[object Symbol]' : setForSymbol
  16255. };
  16256. setFor['[object Number]'] = setFor['[object String]'];
  16257. setFor['[object Array]'] = setFor['[object Object]'];
  16258. function AnyStore(){
  16259. // Dispatch based on type of prop.
  16260. var targ = { storeForPrmitives : {}, storeForObjects : new WeakMap(), __symbolToObj : {}, __symbolFromObj : new WeakMap() };
  16261. var p = new Proxy( targ
  16262. , {
  16263. // PB : TODO -- Proxy handler gets hit for Index function prop..
  16264. get: function (target, prop) {
  16265. if(prop === 'get') return (what)=>{ return getFor[utils.js.nativeType(what)](what, target); }
  16266. if(prop === 'set') return (what, content)=>{
  16267. return setFor[utils.js.nativeType(what)](what, content, targ)
  16268. // return p[p.Index(what)] = content
  16269. }
  16270. return getFor[utils.js.nativeType(prop)](prop, target); }
  16271. // , set: function (target, prop, content) { return setFor[utils.js.nativeType(prop)](prop, content, target); }
  16272. });
  16273. // p.Index = IndexFactory(targ.__symbolFromObj, targ.__symbolToObj);
  16274. // p.get = (what)=>{
  16275. // // Supporting this index access method helps with [] operator. Since objects cant be keys to [] operator.
  16276. // // However this is useful when in future we have a valuecompare based access.
  16277. // // Currently consumers will probably find it cumbersome to access using o[o.Index(someobj)]...
  16278. // // We really don't need to support Index access.
  16279. // return getFor[utils.js.nativeType(what)](what, targ)
  16280. // // return p[p.Index(what, true)]
  16281. // }
  16282. // p.set = (what, content)=>{
  16283. // return setFor[utils.js.nativeType(what)](what, content, targ)
  16284. // // return p[p.Index(what)] = content
  16285. // }
  16286. return p
  16287. }
  16288. AnyStore.create = AnyStore;
  16289. return AnyStore
  16290. })();
  16291. const StateStore = (function(){
  16292. // PB : TODO -- Make chosenref optional or even remove from here.
  16293. var scopedsatestore = new WeakMap();
  16294. function __StateStore(){}
  16295. const singleton = __StateStore();
  16296. function StateStore(){ return singleton }
  16297. StateStore.create = StateStore;
  16298. StateStore.getstate = function(choice, scope, statekey, vtrue, vfalse, statecreator){
  16299. var managedstatestore = StateStore.getmanagedstatestore(choice, scope, statecreator);
  16300. if(managedstatestore.get(statekey)) return vtrue || true;
  16301. else return vfalse || false;
  16302. };
  16303. StateStore.getmanagedstatestore = function(entity, scope, statecreator){
  16304. statecreator = statecreator || function(){ return AnyStore.create() };
  16305. var statestore = scopedsatestore.get(scope);
  16306. if(!statestore) { statestore = AnyStore.create(); scopedsatestore.set(scope, statestore);
  16307. var state = statecreator();
  16308. statestore.set(entity, state);
  16309. return state
  16310. }
  16311. return statestore.get(entity) || ( ()=>{
  16312. var state = statecreator();
  16313. statestore.set(entity, state);
  16314. return state
  16315. })()
  16316. };
  16317. StateStore.setstate = function(choice, chosenref, scope, statekey, statevalue, statecreator){
  16318. var managedstatestore = StateStore.getmanagedstatestore(choice, scope, statecreator);
  16319. var crtget = function(){
  16320. return chosenref.target.get ? chosenref.target.get(chosenref.targetattr) : chosenref.target[chosenref.targetattr]
  16321. };
  16322. var crtset = function(v){
  16323. return chosenref.target.set ? chosenref.target.set(chosenref.targetattr, v) : chosenref.target[chosenref.targetattr] = v
  16324. };
  16325. var state = statevalue;
  16326. if (chosenref.multi) {
  16327. crtset( crtget() || Ember.A());
  16328. chosenref.target[chosenref.targetattr].removeObject(choice);
  16329. if(state) chosenref.target[chosenref.targetattr].pushObject(choice);
  16330. } else {
  16331. var prevchoice = crtget();
  16332. if (prevchoice) {
  16333. var prevchoicemanagedstate = StateStore.getmanagedstatestore(prevchoice, scope, statecreator);
  16334. prevchoicemanagedstate.set(statekey, undefined);
  16335. }
  16336. if(state) crtset( choice);
  16337. else crtset(null);
  16338. }
  16339. managedstatestore.set(statekey, state);
  16340. };
  16341. StateStore.togglestate = function(choice, chosenref, scope, statekey, statecreator){
  16342. var managedstatestore = StateStore.getmanagedstatestore(choice, scope, statecreator);
  16343. var statevalue = !managedstatestore.get(statekey || 'checked');
  16344. StateStore.setstate(choice, chosenref, scope, statekey, statevalue, statecreator);
  16345. };
  16346. return StateStore.create
  16347. })();
  16348. var initglobals = function() {
  16349. var logentry = (function() {
  16350. var __logentry = function(){};
  16351. __logentry.create = function(m) { return { ts : new Date(), m : '' + m, callstack : new Error().stack.split("\n") } };
  16352. return __logentry
  16353. })();
  16354. // Console channels ???
  16355. var filters = [ "log", "warn", "dir", "time", "timeEnd", "timeLog", "trace", "assert",
  16356. // "clear", "count", "countReset", "group", "groupEnd", "table",
  16357. "debug",
  16358. "info",
  16359. "dirxml",
  16360. "error",
  16361. // "groupCollapsed", "Console",
  16362. "profile",
  16363. "profileEnd",
  16364. "timeStamp"
  16365. // ,
  16366. // "context"
  16367. ];
  16368. var oconsole = Object.assign({}, console);
  16369. // console.error = function(){ logpublisher().publish('error', ...arguments) };
  16370. // filters.forEach((f)=>{ console[f] = function(){ logpublisher().publish(f, ...arguments) }; })
  16371. var logpublisher = (function() {
  16372. var __channels = {};
  16373. var __productionchannels = {};
  16374. filters.forEach( (filter)=>{ __productionchannels[filter] = __channels[filter] = []; } );
  16375. var __developmentchannels = Object.assign({}, __channels);
  16376. var devc = ['review', 'error', 'all'];
  16377. devc.forEach( (filter)=>{ __developmentchannels[filter] = __channels[filter] = (__channels[filter] || []); } );
  16378. var env = __g.env.NODE_ENV ? __g.env.NODE_ENV : process.NODE_ENV ? process.NODE_ENV : 'development' ;
  16379. var channels = env === 'development' ? __developmentchannels : __productionchannels;
  16380. // PB : TODO -- Publish to a log listener asynchronously.
  16381. // We currently directly call the subscriber function which is synchronous...
  16382. var publishers = {};
  16383. var __publish = function(channels, jsonmessage) { channels.forEach( sub=>{ sub(jsonmessage); }); };
  16384. var publish = function(filter, message, ...rest) {
  16385. var jsonmessage = utils.js.isString(message) ? logentry.create(
  16386. // util.format(message, ...rest)
  16387. message
  16388. ) : message;
  16389. oconsole[filter](message, ...rest); //
  16390. // channels.forEach(enabledChannel => {
  16391. // PB : TODO -- Intersect with sbscribed channels.
  16392. // publishers[enabledChannel]( channels[filter], jsonmessage )
  16393. publishers[filter]( channels[filter], jsonmessage );
  16394. // })
  16395. // PB : TODO -- Enable multi channel publicatoin.
  16396. if(env === 'development') publishers['all']( channels['all'], jsonmessage );
  16397. };
  16398. Object.keys(channels).forEach( (filter)=>{ publishers[filter] = __publish; } );
  16399. var __singleTon = {
  16400. console : oconsole,
  16401. review : publishers.review,
  16402. loggers : [],
  16403. publish : function(){
  16404. // getcallee(arguments);
  16405. publish.apply(this, arguments);
  16406. },
  16407. subscribe(filter, subscribers){
  16408. if(channels[filter]) {
  16409. channels[filter].push.apply( channels[filter], subscribers);
  16410. }
  16411. else {
  16412. oconsole.log('Channel Not enabled ' + filter);
  16413. }
  16414. }
  16415. , register(channel) {
  16416. var self = this;
  16417. var channellogger = function(){ publish.call(self, channel, ...arguments); };
  16418. this.loggers.push( channellogger );
  16419. oconsole[channel] = oconsole['log'];
  16420. publishers[channel] = __publish;
  16421. channels[channel] = [];
  16422. return channellogger;
  16423. }
  16424. };
  16425. if(env === 'development' && publishers.all) __singleTon.all = publishers.all;
  16426. var __logpublisher = function(){ return __singleTon };
  16427. __logpublisher.create = __logpublisher;
  16428. // __logpublisher.addsubscribers = function(subs){ subscribers.push.apply( subscribers, subs)}
  16429. __logpublisher = Mixin.extend(__logpublisher);
  16430. return __logpublisher
  16431. })();
  16432. __g.logpublisher = logpublisher;
  16433. __g.hascore = true;
  16434. };
  16435. if(!__g.hascore) { initglobals(); }
  16436. function expandUint32Array(arr, data) {
  16437. const newArray = new Uint32Array(arr.length + data.length);
  16438. newArray.set(arr); // copy old data
  16439. newArray.set(data, arr.length); // copy new data after end of old data
  16440. return newArray;
  16441. }
  16442. const HEX_FFFFFFFF = 0xFFFFFFFF;
  16443. const HEX_FFFF0000 = 0xFFFF0000;
  16444. const HEX_FF00 = 0xFF00;
  16445. const HEX_F0 = 0xF0;
  16446. const HEX_0C = 0x0C;
  16447. const MAX_32BITS = HEX_FFFFFFFF;
  16448. const MAX_53BITS = Number.MAX_SAFE_INTEGER;
  16449. const BIGINT_HEX_FFFFFFFF = BigInt(HEX_FFFFFFFF);
  16450. BigInt(HEX_FFFF0000);
  16451. BigInt(HEX_FF00);
  16452. BigInt(HEX_F0);
  16453. BigInt(HEX_0C);
  16454. const BIGINT_MAX_32BITS = BIGINT_HEX_FFFFFFFF;
  16455. const BIGINT_0 = BigInt(0);
  16456. const BIGINT_1 = BigInt(1);
  16457. BigInt(2);
  16458. BigInt(4);
  16459. BigInt(8);
  16460. BigInt(16);
  16461. const BIGINT_32 = BigInt(32);
  16462. // Only Positive numbers;
  16463. function *bigIntBufferGenerator(bn){
  16464. // len = len || find32BitArrLen(bn); // Inefficeint to detect. Lets just iterate and see where it ends...
  16465. var signal = {};
  16466. var stop = Symbol();
  16467. var i = 0;
  16468. for(;;){
  16469. var bits32 = new Uint32Array(1);
  16470. if(bn > MAX_32BITS){
  16471. bits32[0]= Number((bn & BIGINT_MAX_32BITS));
  16472. signal = (yield {i, bits32}) || {};
  16473. if(signal === stop || signal.done) return {i, bits32};
  16474. bn >>= BIGINT_32;
  16475. i++;
  16476. }
  16477. else {
  16478. bits32[0] = Number(bn);
  16479. return {i, bits32};
  16480. }
  16481. }
  16482. }
  16483. function bigIntToBuffer(bn) {
  16484. // if(utils.js.isUndefined(bn) || utils.js.isNull(bn)) throw 'bigIntToBuffer suported only for BigInts...'
  16485. if(!utils.js.isBigInt(bn)) throw 'bigIntToBuffer suported only for BigInts...'
  16486. // PB : Note -- bn must be passed in. Callee should validate.
  16487. var buffer = null;
  16488. var iterator = bigIntBufferGenerator(bn);
  16489. var next = iterator.next();
  16490. if(next && !next.done) buffer = next.value.bits32;
  16491. else return next.value.bits32;
  16492. while(!(next = iterator.next()).done) {
  16493. // PB : TODO -- Ineffficient copy in a loop !!
  16494. // It would be really nice to know how much space is needed. In the absence lets do binary expansion.
  16495. buffer = expandUint32Array(buffer, next.value.bits32);
  16496. }
  16497. buffer = expandUint32Array(buffer, next.value.bits32);
  16498. return buffer;
  16499. }
  16500. function bufferToBigInt(buffer) {
  16501. // PB : Note -- buffer must be a Uint32Array. Callee should validate.
  16502. var bn = BIGINT_0;
  16503. for(var i=buffer.length; --i > -1;){ bn <<= BIGINT_32; bn |= BigInt(buffer[i]); }
  16504. return bn;
  16505. }
  16506. // A bitmask can also be specified by a index number of the bit in a BitArray
  16507. // Implemented as a class to distinguish from a mask value.
  16508. // For convenieance mask value is provided the ability to be passed in as a Number althout BitIndexes are more naturally in the Number Space..
  16509. // mask values larger than 32 bits will implicitly need to be converted to BitArrays.
  16510. const BitIndex = (function() { function BitIndex(){ return this } // BitIndex constructor.
  16511. // Should support Numbers, BigInt and Uint32Array.
  16512. function __is__(t){ if(t === BitIndex) return true; }
  16513. function __is(type){ return typeof this === type ? true : __is__(type) }
  16514. function __create(n){
  16515. return BitIndex.apply({
  16516. value : n
  16517. , is : __is
  16518. })
  16519. }
  16520. __create.create = __create;
  16521. return __create
  16522. })();
  16523. // function leftshift(m){ return utils.js.isNumber(m) ? leftshift_Number(m) : leftshift_BigInt(m) } // Universal.
  16524. function leftshift_Number(m){ return m << 1 }
  16525. function leftshift_BigInt(m){ return m << BIGINT_1 }
  16526. // function leftshift_Uint32Array(m) { throw "leftshift_Uint32Array not yet implemented." }
  16527. function indexOfLSB32(x, gptwo){
  16528. // x needs to be a 32 bit number.
  16529. // Private functions don't do validations to avoid overhead of validation.
  16530. // Only public api's need to validate inputs.
  16531. if(x === 0) return null;
  16532. var i = 0;
  16533. x & 0xFFFF0000 && (i += 16, x >>= 16),
  16534. x & 0xFF00 && (i += 8, x >>= 8),
  16535. x & 0xF0 && (i += 4, x >>= 4),
  16536. x & 0x0C && (i += 2, x>>= 2),
  16537. x & 2 && (i += 1);
  16538. // x & 1 && (i = 0);
  16539. return i;
  16540. }
  16541. // PB : TODO -- Not yet implemented... profile to see if this is any more performant.
  16542. // function indexOfLSB_BigInt_DeBruijn(x, gptwo){
  16543. // // x needs to be a BigInt.
  16544. // // gptwo needs to be BigInt
  16545. // // Private functions don't do validations to avoid overhead of validation.
  16546. // // Only public api's need to validate inputs.
  16547. // if(x === 0) return null;
  16548. // gptwo = gptwo || x & -x;
  16549. // // DeBruijn explodes on multiplication and needs to work on BigInts even if the results are containted in 32 bits...
  16550. // // PB : TODO -- Not sure if this is faster. In any case BigInts are slower.
  16551. // var MultiplyDeBruijnBitPosition = [
  16552. // 0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
  16553. // 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
  16554. // ];
  16555. // return MultiplyDeBruijnBitPosition[( ( gptwo * BigInt( 0x077CB531 )) >> BigInt(27) ) % BigInt(32) ];
  16556. // }
  16557. // https://stackoverflow.com/questions/757059/position-of-least-significant-bit-that-is-set
  16558. // http://graphics.stanford.edu/~seander/bithacks.html
  16559. const BitArrayUpto32Bits = (function(){
  16560. function validateBitLength(length){ if(length > 32) throw 'BitArrayUpto32Bits doesnt accept BitLength > 32' }
  16561. function __createA(arr){
  16562. validateBitLength(arr.length);
  16563. var created = __create();
  16564. // PB : TODO -- Changes this to preincrement. Mask need not overflow for 32 bits...
  16565. var iterateUpto = [
  16566. ()=>{for(var i =0 ; i < 1; i++) { console.log(i); created.assignMask(arr[i], { title : arr[i]}); }}
  16567. , ()=>{for(var i =1 ; i < Math.min(31, arr.length); i++) { console.log(i); created.assignMask(arr[i], { title : arr[i]}, leftshift_Number ); }}
  16568. , ()=>{for(var i =31; i < Math.min(32, arr.length); i++) { console.log(i); created.assignMask(arr[i], { title : arr[i]}, (m)=>{ return leftshift_Number(m)>>>0 } ); }}
  16569. ];
  16570. arr.length > 31 ? iterateUpto.forEach(f=>f()) :
  16571. arr.length > 1 ? iterateUpto.slice(0,2).forEach(f=>f()) :
  16572. iterateUpto[0]();
  16573. return created;
  16574. }
  16575. function __createO(o){
  16576. var arr = Object.keys(o);
  16577. validateBitLength(arr.length);
  16578. var created = __create();
  16579. var iterateUpto = [
  16580. ()=>{for(var i =0 ; i < 1; i++) { console.log(i); created.assignMask(arr[i], o[arr[i]]); }}
  16581. , ()=>{for(var i =1 ; i < Math.min(31, arr.length); i++) { console.log(i); created.assignMask(arr[i], o[arr[i]], leftshift_Number ); }}
  16582. , ()=>{for(var i =31; i < Math.min(32, arr.length); i++) { console.log(i); created.assignMask(arr[i], o[arr[i]], (m)=>{ return leftshift_Number(m)>>>0 } ); }}
  16583. ];
  16584. arr.length > 31 ? iterateUpto.forEach(f=>f()) :
  16585. arr.length > 1 ? iterateUpto.slice(0,2).forEach(f=>f()) :
  16586. iterateUpto[0]();
  16587. return created;
  16588. }
  16589. function __create(){
  16590. // var store = ??? new Uint32Array(1)var mxn = Mixin.create()
  16591. // PB : TODO -- Not in use.
  16592. // var created = utils.assign(mxn,
  16593. // {
  16594. // validateMask(m){
  16595. // if(__is(m, BitIndex)) {
  16596. // if(m > 32) throw 'BitArrayUpto32Bits doesnt accept BitIndex > 32'
  16597. // return { BitIndex, labels : [masks[indexToMask(m.value)]]
  16598. // // , indices : m.value
  16599. // }
  16600. // }
  16601. // if(m > MAX_32BITS) throw "BitArrayUpto32Bits only supports numbers upto MAX_32BITS "
  16602. // if(!utils.js.isNumber(+m)) throw "BitArrayUpto32Bits requires Numbers upto MAX_32BITS "
  16603. // return true;
  16604. // }
  16605. // , labelsToMask : (__labels)=>{
  16606. // var result = 0; __labels.forEach(l=>{ result |= labels[l] })
  16607. // return result >>> 0;
  16608. // }
  16609. // , hasMask : function(label) { return labels[label] ? labels[label].mask : null ; }
  16610. // , maskToLabels(m, transformEach){
  16611. // var valid = this.validateMask(m);
  16612. // if(!valid) throw "Invalid Mask"
  16613. // if(valid.BitIndex) return valid.labels;
  16614. // var __labels = [];
  16615. // for(var gptwo;gptwo=m&-m;m^=gptwo) {
  16616. // if(!masks[gptwo]) { console.log('Error : Invalid mask passed in.') }
  16617. // else __labels.push( transformEach(masks[Number(gptwo)], labels[masks[Number(gptwo)]]) )
  16618. // }
  16619. // return __labels;
  16620. // }
  16621. // , labelToMask : (l)=>{ return labels[l] }
  16622. // , bit_or : (a, b)=>a | b
  16623. // , bit_and : (a, b)=>a & b
  16624. // , bit_xor : (a, b)=>a ^ b
  16625. // , bit_not : (a)=> ~a
  16626. // , assignMask : function(label, entity, incrementFn) {
  16627. // var lmask = this.hasMask(label); if(lmask) return lmask; // Already assigned.
  16628. // labels[label] = entity;
  16629. // labels[label].mask = currentMaxMask = incrementFn ? incrementFn(currentMaxMask) : __nextMask(); // Use the next unused mask for this dictionary of labels. Currently random. We should eventually have a sort order.
  16630. // masks[labels[label].mask] = label;
  16631. // return labels[label];
  16632. // }
  16633. // , msbIndex : function(v) { throw "msb Not yet implemented" }
  16634. // , indexToMask : function(index) {
  16635. // if(index > 31) throw 'Not supported beyond 32 bits.'
  16636. // return (1 << index) >>> 0;
  16637. // }
  16638. // , indicesToMask : function(indices){
  16639. // var mask = 0;
  16640. // indices.forEach(index=>{
  16641. // if(index > 31) throw 'Not supported beyond 32 bits.'
  16642. // mask |= (1 << index)
  16643. // })
  16644. // return mask >>> 0;
  16645. // }
  16646. // , maskToIndices : function(m) {
  16647. // var valid = this.validateMask(m);
  16648. // if(!valid) throw "Invalid Mask"
  16649. // if(valid.BitIndex) return [m.value];
  16650. // var indices = [];
  16651. // var gptwo;
  16652. // for (;gptwo=m&-m;m^=gptwo) indices.push(indexOfLSB32(gptwo))
  16653. // return indices;
  16654. // }
  16655. // , bit_shiftl : (a, s)=>{ return a << s }
  16656. // , bit_shiftr : (a, s)=>{ return a >> s }
  16657. // , bit_shiftr_uz : (a)=>{ return a >>> 0} // Unsigned right shift by 0.
  16658. // // , bit_shiftl_1 : ()=>{}
  16659. // , toJSON(radix, eachFn){
  16660. // var transFormed = {};
  16661. // if(!eachFn) return labels;
  16662. // Object.keys(labels).forEach(label =>{
  16663. // transFormed[label] = eachFn(labels[label])
  16664. // })
  16665. // return transFormed;
  16666. // }
  16667. // , test(){
  16668. // Object.keys(masks).forEach((v, i)=> {
  16669. // console.log( v )
  16670. // console.log( i + ' : ' + v.toString(2) )
  16671. // console.log( this.maskToIndices(v))
  16672. // })
  16673. // console.log( (173).toString(2) )
  16674. // this.maskToIndices(173).map( (i)=>{ console.log( i ) })
  16675. // console.log('indicesToMask :' + this.indicesToMask([1,4,31]).toString(2))
  16676. // }
  16677. // })
  16678. }
  16679. var creatorFor = {
  16680. '[object Array]' : __createA
  16681. , '[object Object]' : __createO
  16682. , 'undefined' : function(){ return __create() }
  16683. };
  16684. // PB : TODO -- Constructor is not preserved... But mixing in an external passed in object is what we want to achive.
  16685. function BitArrayUpto32Bits(){
  16686. return arguments.length ? creatorFor[utils.js.nativeType(arguments[0])](...arguments) :
  16687. creatorFor['undefined'](...arguments)}
  16688. BitArrayUpto32Bits.create = BitArrayUpto32Bits;
  16689. return BitArrayUpto32Bits
  16690. })();
  16691. const BitArrayBigInt = (function(){
  16692. function __createA(arr){
  16693. var created = __create();
  16694. for(var i =0 ; i < 1; i++) { created.assignMask(arr[i], { title : arr[i]}); }
  16695. for(var i =1 ; i < arr.length; i++) { created.assignMask(arr[i], { title : arr[i]}, leftshift_BigInt ); }
  16696. return created;
  16697. }
  16698. function __createO(o){
  16699. var arr = Object.keys(o);
  16700. var created = __create();
  16701. for(var i =0 ; i < 1; i++) { created.assignMask(arr[i], o[arr[i]]); }
  16702. for(var i =1 ; i < arr.length; i++) { created.assignMask(arr[i], o[arr[i]], leftshift_BigInt ); }
  16703. return created;
  16704. }
  16705. function __create(){
  16706. var labels = {};
  16707. var masks = {};
  16708. var currentMaxMask;
  16709. function __nextMask(){ __nextMask = leftshift_BigInt;
  16710. return currentMaxMask = BIGINT_1; }
  16711. // var store = ??? new Uint32Array(1)
  16712. // PB : TODO -- This need not be done on each instance. We need to do an extend on the type...
  16713. // -- BitArrayBigInt.extend({ validateMask(m){) ... })
  16714. var mxn = Mixin.create();
  16715. var created = utils.assign(mxn,
  16716. {
  16717. validateMask(m){
  16718. if(mxn.is(m, BitIndex)) {
  16719. return { BitIndex, labels : [masks[indexToMask(m.value)]] }
  16720. }
  16721. if(!utils.js.isBigInt(BigInt(m))) throw "BitArrayBigInt requires BigInt Mask "
  16722. return true;
  16723. }
  16724. , labelsToMask : (__labels)=>{
  16725. var result = BIGINT_0; __labels.forEach(l=>{ result |= labels[l]; });
  16726. return result ;
  16727. }
  16728. , hasMask : function(label) { return labels[label] ? labels[label].mask : null ; }
  16729. , maskToLabels(m, transformEach){
  16730. m = BigInt(m);
  16731. var valid = this.validateMask(m);
  16732. if(!valid) throw "Invalid Mask"
  16733. if(valid.BitIndex) return valid.labels;
  16734. var __labels = [];
  16735. for(var gptwo;gptwo=m&-m;m^=gptwo) {
  16736. if(!masks[gptwo]) { console.log('Error : Invalid mask passed in.'); }
  16737. else __labels.push( transformEach(masks[Number(gptwo)], labels[masks[Number(gptwo)]]) );
  16738. }
  16739. return __labels;
  16740. }
  16741. , labelToMask : (l)=>{ return labels[l] }
  16742. , bit_or : (a, b)=>a | b
  16743. , bit_and : (a, b)=>a & b
  16744. , bit_xor : (a, b)=>a ^ b
  16745. , bit_not : (a)=> ~a
  16746. , assignMask : function(label, entity, incrementFn) {
  16747. var lmask = this.hasMask(label); if(lmask) throw `Duplicate assignment for same label ${label} not allowed : mask (${lmask}) ` // Already assigned.
  16748. labels[label] = entity;
  16749. labels[label].mask = currentMaxMask = incrementFn ? incrementFn(currentMaxMask) : __nextMask(); // Use the next unused mask for this dictionary of labels. Currently random. We should eventually have a sort order.
  16750. masks[labels[label].mask] = label;
  16751. return labels[label];
  16752. }
  16753. , msbIndex : function(v) { throw "msb Not yet implemented" }
  16754. , indexToMask : function(index) {
  16755. return BIGINT_1 << index;
  16756. }
  16757. , indicesToMask : function(indices){
  16758. var mask = 0;
  16759. indices.forEach(index=>{
  16760. mask |= (1 << index);
  16761. });
  16762. return mask;
  16763. }
  16764. , maskToIndices : function(m) {
  16765. var valid = this.validateMask(m);
  16766. if(!valid) throw "Invalid Mask"
  16767. if(valid.BitIndex) return [m.value];
  16768. var indices = [];
  16769. var gptwo;
  16770. var iterator = bigIntBufferGenerator(BigInt(m));
  16771. var next;
  16772. // if(next && !next.done) buffer = next.value.bits32;
  16773. // else return next.value.bits32;
  16774. var i = 0;
  16775. while(!(next = iterator.next()).done) {
  16776. next.value.bits32 > 0 ?
  16777. ( ()=> { for(;gptwo=(next.value.bits32& -next.value.bits32) ;next.value.bits32^=gptwo) indices.push(32 * i + indexOfLSB32(gptwo)); } )
  16778. : null;
  16779. i++;
  16780. }
  16781. for(;gptwo=(next.value.bits32&-next.value.bits32);next.value.bits32^=gptwo) indices.push(32 * i + indexOfLSB32(gptwo));
  16782. return indices;
  16783. }
  16784. , bit_shiftl : (a, s)=>{ return a << s }
  16785. , bit_shiftr : (a, s)=>{ return a >> s }
  16786. , bit_shiftr_uz : (a)=>{ throw "BigInt doesnt suppored unsigned right shift."} // Unsigned right shift by 0.
  16787. // , bit_shiftl_1 : ()=>{}
  16788. , toJSON(radix, eachFn){
  16789. var transFormed = {};
  16790. if(!eachFn) return labels;
  16791. Object.keys(labels).forEach(label =>{
  16792. transFormed[label] = eachFn(labels[label]);
  16793. });
  16794. return transFormed;
  16795. }
  16796. , tosqlcte() {
  16797. var select = '';
  16798. // debugger
  16799. Object.keys(labels).forEach((label, index, array) =>{
  16800. var labelObject = labels[label];
  16801. var rowselect = 'select ';
  16802. Object.keys(labelObject).forEach((key, index, array) =>{
  16803. rowselect = rowselect + ` '${labelObject[key]}' ${key}`;
  16804. if(array.length !== index+1) rowselect = rowselect + ',';
  16805. });
  16806. select = select + rowselect;
  16807. if(array.length !== index+1) select = select + '\n union all \n';
  16808. });
  16809. console.log(select);
  16810. return labels
  16811. }
  16812. , test(){
  16813. Object.keys(masks).forEach((v, i)=> {
  16814. console.log( v );
  16815. console.log( i + ' : ' + v.toString(2) );
  16816. console.log( this.maskToIndices(v));
  16817. });
  16818. console.log( (173).toString(2) );
  16819. this.maskToIndices(173).map( (i)=>{ console.log( i ); });
  16820. console.log('indicesToMask :' + this.indicesToMask([1,4,31]).toString(2));
  16821. console.log(BigInt(2535301200456458802993406410752));
  16822. console.log('bigIntToBuffer : ' + bigIntToBuffer(BigInt(2535301200456458802993406410752) ));
  16823. console.log('bufferToBigInt : ' + bufferToBigInt( bigIntToBuffer(BigInt(2535301200456458802993406410752)) ));
  16824. }
  16825. }
  16826. );
  16827. created.addMixin(BitArrayBigInt);
  16828. return created;
  16829. }
  16830. var creatorFor = {
  16831. '[object Array]' : __createA
  16832. , '[object Object]' : __createO
  16833. , 'undefined' : function(){ return __create() }
  16834. };
  16835. // PB : TODO -- Constructor is not preserved... But mixing in an external passed in object is what we want to achive.
  16836. function BitArrayBigInt(){
  16837. return arguments.length ? creatorFor[utils.js.nativeType(arguments[0])](...arguments) :
  16838. creatorFor['undefined'](...arguments)}
  16839. BitArrayBigInt.create = BitArrayBigInt;
  16840. return BitArrayBigInt
  16841. })();
  16842. // > 32 bits upto 53 bits.
  16843. const BitArrayUpto53Bits = (function(){
  16844. function validateBitLength(length){ if(length > 53) throw 'BitArrayUpto53Bits doesnt accept BitLength > 53' }
  16845. function __createO(o, options){
  16846. var arr = Object.keys(o);
  16847. validateBitLength(arr.length);
  16848. var created = __create();
  16849. var iterateUpto = [
  16850. ()=>{for(var i =0 ; i < 1; i++) { console.log(i); created.assignMask(arr[i], o[arr[i]]); }}
  16851. , ()=>{for(var i =1 ; i < Math.min(31, arr.length); i++) { console.log(i); created.assignMask(arr[i], o[arr[i]], leftshift_Number ); }}
  16852. , ()=>{for(var i =31; i < Math.min(32, arr.length); i++) { console.log(i); created.assignMask(arr[i], o[arr[i]], (m)=>{ return leftshift_Number(m)>>>0 } ); }}
  16853. , ()=>{for(var i =32; i < Math.min(53, arr.length); i++) { console.log(i); created.assignMask(arr[i], o[arr[i]], (m)=>{ return Number(BigInt(m) << BIGINT_1) } ); }}
  16854. ];
  16855. arr.length > 32 ? iterateUpto.forEach(f=>f()) :
  16856. arr.length > 31 ? iterateUpto.slice(0,3).forEach(f=>f()) :
  16857. arr.length > 1 ? iterateUpto.slice(0,2).forEach(f=>f()) :
  16858. iterateUpto[0]();
  16859. return created;
  16860. }
  16861. function __createA(arrInp, options){
  16862. validateBitLength(arrInp.length);
  16863. var created = __create();
  16864. var arr = [];
  16865. var pregencache = [];
  16866. // PB : Changed to preincrement. Mask need not overflow for 53 bits...
  16867. var iterateUpto = [
  16868. (prelen)=>{for(var i =Math.max(0, prelen) ; i < 1; i++) { console.log(i); created.assignMask(arr[i-prelen], pregencache[arr[i-prelen]] || { title : arr[i-prelen]} ); }}
  16869. , (prelen)=>{for(var i =Math.max(1, prelen) ; i < Math.min(31, arr.length + prelen); i++) { console.log(i); created.assignMask(arr[i-prelen], pregencache[arr[i-prelen]] || { title : arr[i-prelen]}, leftshift_Number ); }}
  16870. , (prelen)=>{for(var i =Math.max(31, prelen); i < Math.min(32, arr.length + prelen); i++) { console.log(i); created.assignMask(arr[i-prelen], pregencache[arr[i-prelen]] || { title : arr[i-prelen]}, (m)=>{ return leftshift_Number(m)>>>0 } ); }}
  16871. , (prelen)=>{for(var i =Math.max(32, prelen); i < Math.min(53, arr.length + prelen); i++) { console.log(i); created.assignMask(arr[i-prelen], pregencache[arr[i-prelen]] || { title : arr[i-prelen]}, (m)=>{ return Number(BigInt(m) << BIGINT_1) } ); }}
  16872. ];
  16873. if(options && options.pregenerated) {
  16874. arrInp.forEach((inp=>{
  16875. if(!options.pregenerated[inp] || !options.pregenerated[inp].mask) {
  16876. // Doesn't have a mask so needs generation.
  16877. arr.push(inp);
  16878. pregencache[inp] = options.pregenerated[inp];
  16879. }
  16880. else if(!options.pregenerated[inp]) arr.push(inp);
  16881. }));
  16882. Object.keys(options.pregenerated).forEach(p=>{
  16883. if(pregencache[p]) return;
  16884. created.assignMask(p, options.pregenerated[p], created.assignMaxAsNextIncrement );
  16885. });
  16886. var prelen = Object.keys(created.toJSON()).length;
  16887. prelen > 31 ? iterateUpto.slice(3).forEach(f=>f(prelen)) :
  16888. prelen > 30 ?
  16889. (prelen + arr.length) > 32 ? iterateUpto.slice(2).forEach(f=>f(prelen))
  16890. : iterateUpto.slice(2, 3).forEach(f=>f(prelen))
  16891. :
  16892. prelen > 0 ?
  16893. (prelen + arr.length) > 32 ? iterateUpto.slice(1).forEach(f=>f(prelen))
  16894. : (prelen + arr.length) > 31 ? iterateUpto.slice(1,3).forEach(f=>f(prelen)) :
  16895. iterateUpto.slice(1,2).forEach(f=>f(prelen))
  16896. :
  16897. arr.length > 32 ? iterateUpto.forEach(f=>f(prelen)) :
  16898. arr.length > 31 ? iterateUpto.slice(0,3).forEach(f=>f(prelen)) :
  16899. arr.length > 1 ? iterateUpto.slice(0,2).forEach(f=>f(prelen)) :
  16900. iterateUpto[0](prelen);
  16901. }
  16902. else {
  16903. arr = arrInp;
  16904. arr.length > 32 ? iterateUpto.forEach(f=>f(0)) :
  16905. arr.length > 31 ? iterateUpto.slice(0,3).forEach(f=>f(0)) :
  16906. arr.length > 1 ? iterateUpto.slice(0,2).forEach(f=>f(0)) :
  16907. iterateUpto[0](0);
  16908. }
  16909. return created;
  16910. }
  16911. function __create(){
  16912. var labels = {};
  16913. var masks = {};
  16914. var currentMaxMask;
  16915. function __nextMask(){ __nextMask = leftshift_Number;
  16916. return currentMaxMask = 1; }
  16917. // var store = ??? new Uint32Array(1)
  16918. // PB : TODO -- This need not be done on each instance. We need to do an extend on the type...
  16919. // -- BitArrayBigInt.extend({ validateMask(m){) ... })
  16920. var mxn = Mixin.create();
  16921. var created = utils.assign(mxn,
  16922. {
  16923. assignMaxAsNextIncrement(possibleMax) {
  16924. if(currentMaxMask && currentMaxMask < possibleMax) currentMaxMask = possibleMax;
  16925. else currentMaxMask = possibleMax;
  16926. }
  16927. , validateMask(m){
  16928. if(mxn.is(m, BitIndex)) {
  16929. return { BitIndex, labels : [masks[indexToMask(m.value)]] }
  16930. }
  16931. if(m > MAX_53BITS) throw "BitArrayUpto53Bits only supports numbers upto MAX_53BITS "
  16932. if(!utils.js.isNumber(+m)) throw "BitArrayUpto53Bits requires Numbers upto MAX_53BITS "
  16933. return true;
  16934. }
  16935. , labelsToMask : (__labels)=>{
  16936. var result = 0; __labels.forEach(l=>{ result |= labels[l]; });
  16937. return result >>> 0;
  16938. }
  16939. , hasMask : function(label) { return labels[label] ? labels[label].mask : null ; }
  16940. , maskToLabels(m, transformEach){
  16941. var valid = this.validateMask(m);
  16942. if(!valid) throw "Invalid Mask"
  16943. if(valid.BitIndex) return valid.labels;
  16944. var __labels = [];
  16945. var m = BigInt(m);
  16946. // for(var gptwo;gptwo=this.bit_and(m,-m); gptwo = this.bit_xor(m,gptwo)) {
  16947. for(var gptwo;gptwo=m&-m;m^=gptwo) {
  16948. if(!masks[Number(gptwo)]) { console.log('Error : Invalid mask passed in.'); }
  16949. else __labels.push( transformEach(masks[Number(gptwo)], labels[masks[Number(gptwo)]]) );
  16950. }
  16951. return __labels;
  16952. }
  16953. , labelToMask : (l)=>{ return labels[l] }
  16954. , bit_or : (a, b) => {
  16955. return bit_opFn_Upto53(a,b, (a, b)=>a | b)
  16956. }
  16957. , bit_and : (a, b) => bit_opFn_Upto53(a,b, (a, b)=>a & b)
  16958. , bit_xor : (a, b) => bit_opFn_Upto53(a,b, (a, b)=>a ^ b)
  16959. , bit_not : (a) => Number(~BigInt(a))
  16960. , assignMask : function(label, entity, onassignment) {
  16961. if(entity && entity.mask && masks[entity.mask]) {
  16962. throw 'Mask collision. Cannot assign requested mask. ' + entity
  16963. }
  16964. var pregenerated = labels[label] || entity;
  16965. // var lmask = this.hasMask(label); if(lmask) return lmask; // Already assigned.
  16966. // Everything is overridable except mask.
  16967. if(pregenerated && pregenerated.mask) {
  16968. onassignment = (onassignment || created.assignMaxAsNextIncrement);
  16969. labels[label] = utils.assign(pregenerated, entity, {mask : pregenerated.mask});
  16970. onassignment(pregenerated.mask);
  16971. }
  16972. else {
  16973. onassignment = (onassignment || __nextMask);
  16974. labels[label] = entity;
  16975. labels[label].mask = currentMaxMask = onassignment ? onassignment(currentMaxMask) : __nextMask(); // Use the next unused mask for this dictionary of labels. Currently random. We should eventually have a sort order.
  16976. }
  16977. masks[labels[label].mask] = label;
  16978. return labels[label];
  16979. }
  16980. , msbIndex : function(v) { throw "msb Not yet implemented" }
  16981. , indexToMask : function(index) {
  16982. if(index > 52) throw 'Not supported beyond 53 bits.'
  16983. return Number(BigInt(1) << BigInt(index));
  16984. }
  16985. , indicesToMask : function(indices){
  16986. var mask = BigInt(0);
  16987. indices.forEach(index=>{
  16988. if(index > 52) throw 'Not supported beyond 53 bits.'
  16989. mask |= (BIGINT_1 << BigInt(index));
  16990. });
  16991. return Number(mask);
  16992. }
  16993. , maskToIndices : function(m) {
  16994. var valid = this.validateMask(m);
  16995. if(!valid) throw "Invalid Mask"
  16996. if(valid.BitIndex) return [m.value];
  16997. var indices = [];
  16998. var gptwo;
  16999. if(m > MAX_32BITS) {
  17000. var iterator = bigIntBufferGenerator(BigInt(m));
  17001. var next;
  17002. // if(next && !next.done) buffer = next.value.bits32;
  17003. // else return next.value.bits32;
  17004. var i = 0;
  17005. while(!(next = iterator.next()).done) {
  17006. next.value.bits32 > 0 ?
  17007. ( ()=> { for(;gptwo=(next.value.bits32& -next.value.bits32) ;next.value.bits32^=gptwo) indices.push(32 * i + indexOfLSB32(gptwo)); } )
  17008. : null;
  17009. i++;
  17010. }
  17011. for(;gptwo=(next.value.bits32&-next.value.bits32);next.value.bits32^=gptwo) indices.push(32 * i + indexOfLSB32(gptwo));
  17012. }
  17013. else {
  17014. m = Number(m);
  17015. for (;gptwo=m&-m;m^=gptwo) indices.push(indexOfLSB32(gptwo)); }
  17016. // for (;gptwo=BigInt(m)&BigInt(-m);m^=gptwo) indices.push(indexOfLSB32(m, gptwo))
  17017. return indices;
  17018. }
  17019. , bit_shiftl : (a, s)=>{ return a << s }
  17020. , bit_shiftr : (a, s)=>{ return a >> s }
  17021. , bit_shiftr_uz : (a)=>{ return a >>> 0} // Unsigned right shift by 0.
  17022. // , bit_shiftl_1 : ()=>{}
  17023. , toJSON(radix, eachFn){
  17024. var transFormed = {};
  17025. if(!eachFn) return labels;
  17026. Object.keys(labels).forEach(label =>{
  17027. transFormed[label] = eachFn(labels[label]);
  17028. });
  17029. return transFormed;
  17030. }
  17031. , tosqlcte() {
  17032. var select = '';
  17033. // debugger
  17034. Object.keys(labels).forEach((label, index, array) =>{
  17035. var labelObject = labels[label];
  17036. var rowselect = 'select ';
  17037. Object.keys(labelObject).forEach((key, index, array) =>{
  17038. rowselect = rowselect + ` '${labelObject[key]}' ${key}`;
  17039. if(array.length !== index+1) rowselect = rowselect + ',';
  17040. });
  17041. select = select + rowselect;
  17042. if(array.length !== index+1) select = select + '\n union all \n';
  17043. });
  17044. console.log(select);
  17045. return labels
  17046. }
  17047. , test(){
  17048. Object.keys(masks).forEach((v, i)=> {
  17049. console.log( v );
  17050. console.log( i + ' : ' + v.toString(2) );
  17051. console.log( this.maskToIndices(v));
  17052. });
  17053. console.log( (173).toString(2) );
  17054. this.maskToIndices(173).map( (i)=>{ console.log( i ); });
  17055. console.log('indicesToMask :' + this.indicesToMask([1,4,31]).toString(2));
  17056. }
  17057. });
  17058. return created;
  17059. }
  17060. var creatorFor = {
  17061. '[object Array]' : __createA
  17062. , '[object Object]' : __createO
  17063. , 'undefined' : function(){ return __create() }
  17064. };
  17065. // PB : TODO -- Constructor is not preserved... But mixing in an external passed in object is what we want to achive.
  17066. function BitArrayUpto53Bits(){
  17067. return arguments.length ? creatorFor[utils.js.nativeType(arguments[0])](...arguments) :
  17068. creatorFor['undefined'](...arguments)}
  17069. BitArrayUpto53Bits.create = BitArrayUpto53Bits;
  17070. return BitArrayUpto53Bits
  17071. })();
  17072. function bit_opFn_Upto53(a, b, opFn){
  17073. return Number(opFn(BigInt(a), BigInt(b) ))
  17074. // var result = new Uint32Array(2);
  17075. // result[0] = opFn( (a / POWER32)>>0 , (b / POWER32)>>0 )
  17076. // result[1] = opFn(a % POWER32, b % POWER32)
  17077. // return POWER32 * result[0] + result[1];
  17078. }
  17079. // An arbitrarily-wide array of bits. Can be used for bitmasks longer than 32 bits in JS.
  17080. const BitArray = (function(){
  17081. // const NEEDS_BIT_SPLIT = (b)=> b > Number.MAX_SAFE_INTEGER;
  17082. // const MAX_SAFE_MASK_LENGTH = 32
  17083. // function getMinMax(a, b){
  17084. // return a.length > b.length ? { min : b.length, minX : b, max : a.length, maxX : a }
  17085. // : { min : a.length, minX : a, max : b.length, maxX : b }
  17086. // }
  17087. // function getTypes(a, b){
  17088. // var aIsPrimitive = utils.js.isPrimitive(a);
  17089. // var bIsPrimitive = utils.js.isPrimitive(b);
  17090. // return { a : aIsPrimitive, b : bIsPrimitive }
  17091. // }
  17092. // // Binary oprations
  17093. // function bit_opFn(a, b, opFn){
  17094. // var tt = getTypes(a, b);
  17095. // var mm = {}
  17096. // var getRemaining = function(){ return mm.maxX.subarray(mm.min, mm.max-1)}
  17097. // if(tt.a && tt.b) {
  17098. // // both are primitive
  17099. // mm = { min : 1, minX : [a], max : 1, maxX : [b]}
  17100. // getRemaining = function(){ return []}
  17101. // }
  17102. // else if(tt.a){
  17103. // // b is bitarray
  17104. // mm = { min : 1, minX : [a], max : b.length, maxX : b}
  17105. // }
  17106. // else if(tt.b){
  17107. // mm = { min : 1, minX : [b], max : a.length, maxX : a}
  17108. // }
  17109. // else {
  17110. // var mm = getMinMax(a, b)
  17111. // }
  17112. // var result = new Uint32Array(mm.max);
  17113. // for (var i = 0; i < mm.min; ++i) { result.set( [opFn(mm.minX[i], mm.maxX[i])], i) }
  17114. // // js.utils.isPrimitive(mm.maxX) ?
  17115. // var remaining = getRemaining()
  17116. // remaining.length > 0 ? result.set( remaining, mm.min) : null;
  17117. // return result;
  17118. // }
  17119. // // Unary operations
  17120. // function bit_opFnU(mm, opFn){
  17121. // var result = new Uint32Array(mm.length);
  17122. // for (var i = 0; i < mm.min; ++i) { result.set( opFn(a), i) }
  17123. // result.set( mm.maxX.subarray(mm.min, mm.max-1), mm.min)
  17124. // return result;
  17125. // }
  17126. // function __expand(){
  17127. // }
  17128. function __createA(arr){
  17129. // Create a new BitArray
  17130. // Assign Unique bits to each item in an array of labels.
  17131. arr.length % 32;
  17132. arr.length/32 >>> 0;
  17133. var created = arr.length > 53 ?
  17134. BitArrayBigInt.create(...arguments) : arr.length > 32 ?
  17135. BitArrayUpto53Bits.create(...arguments) :
  17136. BitArrayUpto32Bits.create(...arguments);
  17137. return created;
  17138. }
  17139. function __createO(o){
  17140. // Create a new BitArray
  17141. // Assign Unique bits to each item in an array of labels.
  17142. var arr = Object.keys(o);
  17143. arr.length % 32;
  17144. arr.length/32 >>> 0;
  17145. var created = arr.length > 53 ?
  17146. BitArrayBigInt.create(...arguments) : arr.length > 32 ?
  17147. BitArrayUpto53Bits.create(...arguments) :
  17148. BitArrayUpto32Bits.create(...arguments);
  17149. return created;
  17150. }
  17151. function __create(){
  17152. // var store = new Uint32Array(1)
  17153. // var mxn = Mixin.create()
  17154. var created = BitArrayBigInt.create();
  17155. created.addMixin(BitArray);
  17156. return created;
  17157. }
  17158. var creatorFor = {
  17159. '[object Array]' : __createA
  17160. , '[object Object]' : __createO
  17161. , 'undefined' : function(){ return __create() }
  17162. };
  17163. // PB : TODO -- Constructor for BitArrays read from files that have been generated and saved.
  17164. // PB : TODO -- Constructor is not preserved... But mixing in an external passed in object is what we want to achive.
  17165. function BitArray(){
  17166. return arguments.length ? creatorFor[utils.js.nativeType(arguments[0])](...arguments) :
  17167. creatorFor['undefined'](...arguments)}
  17168. BitArray.create = BitArray;
  17169. return BitArray
  17170. })();
  17171. // var uuidv1 = utils.core.uuidV1;
  17172. const { v1: uuidv1 } = require$$3$1;
  17173. // console.log(uuidv1)
  17174. // Mixins.
  17175. const mixs = {
  17176. // __JSTPL : (function() {
  17177. // function __f() {}
  17178. // return function() {
  17179. // this.f = __f;
  17180. // return this;
  17181. // };
  17182. // })()
  17183. // Return a set of mixins.
  17184. kernelMixin : (function() {
  17185. // Wrapper to generate the currently chosen UUID version
  17186. // In JS UUID v4 vs v1 -> In browsers v1 has the timestamp but uses a random number for the node part.
  17187. function __getuuid() {
  17188. return uuidv1();
  17189. }
  17190. // uuid property Mainstream getter after lazy init
  17191. function __get() {
  17192. return this.kernel.uuidv1;
  17193. }
  17194. // uuid property First Time getter for lazy init.
  17195. function __firstGet() {
  17196. this.kernel.uuidv1 = __getuuid();
  17197. __finalize.apply(this);
  17198. return this.uuid;
  17199. }
  17200. function __finalize(){
  17201. Object.defineProperty(this.kernel, 'uuidv1', { writable : false, configurable : false});
  17202. Object.defineProperty(this, 'uuid', {
  17203. get : __get
  17204. , enumerable : true
  17205. , configurable : false
  17206. });
  17207. Object.defineProperty(this, 'kernel', {
  17208. enumerable : false
  17209. , configurable : false
  17210. , writable : false
  17211. });
  17212. }
  17213. function __defineKernel(){
  17214. // MAC and time. Guaranteed unique unless generated way too fast or parallelly.
  17215. //const uuidv1 = utils.core.uuidV1; // (date-time and MAC address)
  17216. //const uuidv2 = // (date-time and MAC Address, DCE security version)
  17217. // (namespace name-based) ...
  17218. //const uuidv3md5 = require('uuid/v3');
  17219. //const uuidv5sha1 = require('uuid/v3'); // SHA1(v5) is broken
  17220. //const uuidv4 = require('uuid/v4'); //(random)
  17221. // Kernel Properties are promoted onto the object itself without value as getters and setters as
  17222. // configurable = false
  17223. // enumerable = false
  17224. // writable = false
  17225. Object.defineProperty(this, 'kernel', { value :{}, writable : true });
  17226. // Keep it lazy. Only generate on first use. Which could be first time persistence.
  17227. Object.defineProperty(this.kernel, 'uuidv1', { writable : true, configurable : true});
  17228. // PB : TODO -- Note : A hash of the content may need to be computed dynamically.
  17229. // The best place to do this is on persistance. In memory objects undergo a lot of changes so the hash keeps varying.
  17230. // It therefore becomes unnecessary to compute the hash very frequently. We may need to do this lazily when accessed or
  17231. // simply use all attributes for comparison. The value of a hash is useful only when the attributes are not changing
  17232. // and the hash is precomputed and ready to be used. We need to use gits methodology to track changes.
  17233. }
  17234. function __loadKernel() {
  17235. // Reinitialize the kernel for an object that already has a uuid probably loaded from a JSON.
  17236. this.kernel.uuidv1 = this.uuid;
  17237. __finalize.apply(this);
  17238. }
  17239. function __attachKernel() {
  17240. // Dont mess with something that already has a kernel.
  17241. if(this.hasOwnProperty('kernel')) {
  17242. l('Already has kernel');
  17243. return this;
  17244. }
  17245. __defineKernel.apply(this);
  17246. if(this.hasOwnProperty('uuid')) {
  17247. l('Already has uuid');
  17248. __loadKernel.apply(this);
  17249. return this;
  17250. }
  17251. Object.defineProperty(this, 'uuid', { get : __firstGet, configurable : true});
  17252. return this;
  17253. }
  17254. var __kernelInstanceMixin = function() {
  17255. return __attachKernel.apply(this);
  17256. };
  17257. __kernelInstanceMixin.getuuid = __getuuid;
  17258. return __kernelInstanceMixin;
  17259. })()
  17260. // Publishes messages to a message queue broker or mediator.
  17261. , publisherMixin : (function() {
  17262. function __publish() {
  17263. }
  17264. return function() {
  17265. this.publish = __publish;
  17266. return this;
  17267. };
  17268. })()
  17269. };
  17270. // Note : Prophelpers are not mixed into the object and hence need to be applied on some other object.
  17271. const helpers = {
  17272. indexHelper : indexHelper
  17273. , meta : (function() {
  17274. // Mainly to observe changes to object properties.
  17275. // A kernel uuid is a prerequisite.
  17276. function spy(obj, prop, action) {
  17277. action = action || 'set';
  17278. if(action != 'set') {
  17279. throw 'Currently only set actions can be observed on properties';
  17280. }
  17281. // Get the current descriptor
  17282. var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
  17283. var value = obj[prop];
  17284. if(descriptor && descriptor.get && descriptor.get.$meta){
  17285. var originalset = descriptor.set;
  17286. descriptor.set = function(newValue) {
  17287. __g.mediator.publish(obj.uuid + '.' + prop, 'willchange', {from : value, to : newValue});
  17288. originalset(newValue);
  17289. __g.mediator.publish(obj.uuid + '.' + prop, 'haschanged', {from : value, to : newValue});
  17290. };
  17291. return this;
  17292. }
  17293. descriptor = {
  17294. get: function() {
  17295. return value;
  17296. },
  17297. set: function(newValue) {
  17298. __g.mediator.publish([obj.uuid, prop, 'willchange'], {from : value, to : newValue});
  17299. value = newValue;
  17300. __g.mediator.publish([obj.uuid, prop, 'haschanged' ], {from : value, to : newValue});
  17301. }
  17302. };
  17303. descriptor.get.$meta = {};
  17304. Object.defineProperty(obj, prop, descriptor);
  17305. return this;
  17306. }
  17307. function getCustomPropertyDescriptor(obj, prop) {
  17308. var actualDescriptor = Object.getOwnPropertyDescriptor(obj, prop);
  17309. if (actualDescriptor && actualDescriptor.get && actualDescriptor.get.$meta) {
  17310. return actualDescriptor;
  17311. }
  17312. var value = obj[prop];
  17313. var descriptor = {
  17314. get: function() {
  17315. return value;
  17316. },
  17317. set: function(newValue) {
  17318. value = newValue;
  17319. }
  17320. };
  17321. descriptor.get.$meta = {};
  17322. Object.defineProperty(obj, prop, descriptor);
  17323. return Object.getOwnPropertyDescriptor(obj, prop);
  17324. }
  17325. function setPropertyAttribute(obj, propertyName, attributeName, attributeValue) {
  17326. var descriptor = getCustomPropertyDescriptor(obj, propertyName);
  17327. descriptor.get.$meta[attributeName] = attributeValue;
  17328. }
  17329. function getPropertyAttributes(obj, propertyName) {
  17330. var descriptor = getCustomPropertyDescriptor(obj, propertyName);
  17331. return descriptor.get.$meta;
  17332. }
  17333. function getPropertyAttribute(obj, propertyName, attributeName) {
  17334. return getPropertyAttributes(obj, propertyName)[attributeName];
  17335. }
  17336. return function(obj) {
  17337. obj.getPropertyAttribute = getPropertyAttribute;
  17338. obj.getPropertyAttributes = getPropertyAttributes;
  17339. obj.setPropertyAttribute = setPropertyAttribute;
  17340. obj.spy = spy;
  17341. return obj;
  17342. };
  17343. })()
  17344. };
  17345. var core = function(object){
  17346. // We can find call site info here... like this etc.
  17347. // l('in \tFunction core')
  17348. return {
  17349. mixs
  17350. , helpers
  17351. , AnyStore
  17352. , StateStore
  17353. , BitArray
  17354. , BitArrayUpto32Bits
  17355. , BitArrayUpto53Bits
  17356. , BitArrayBigInt
  17357. // core object instances
  17358. , uuidv1
  17359. , Rule
  17360. , uuidv1
  17361. , logpublisher : __g.logpublisher
  17362. , Clazz
  17363. }
  17364. };
  17365. // export default core;
  17366. module.exports = core;
  17367. // console.dir(__g.mediator)
  17368. // try {
  17369. // console.log( '__g === global : ' + (__g === global) )
  17370. // }
  17371. // catch(e){
  17372. // console.log( '__g === global : ' + false )
  17373. // }
  17374. // try {
  17375. // console.log( '__g === globalThis : ' + (__g === globalThis) )
  17376. // }
  17377. // catch(e){
  17378. // console.log( '__g === globalThis : ' + false )
  17379. // }
  17380. function *bigIntBitGenerator(){
  17381. var signal = {};
  17382. var stop = Symbol();
  17383. var iId = 0;
  17384. var bit = BIGINT_1;
  17385. for(;;){
  17386. signal = (yield { iId, bit }) || {};
  17387. if(signal === stop || signal.done) return { iId, bit };
  17388. bit = bit << BIGINT_1;
  17389. iId++;
  17390. }
  17391. }
  17392. var Rule = (function(){
  17393. // Immutable private static.
  17394. var __Rule = {};
  17395. // Overridable public static shared on the instance as well as convenience functions.
  17396. // When the extend method is used the instance methods also correspond.
  17397. // IMP : NOTE -- However instance overrides do not switch the static ones attached to the class.
  17398. // These could also be called statically with call or apply Eg: fn.apply(this)
  17399. var _XRule = { assignbit, getParticipating };
  17400. // Extendable public static
  17401. // _Rule should not be referenced anywhere... as its members can be swithed.
  17402. var _Rule = {
  17403. extend : function(extension){
  17404. function __create(){ return init.call({}) }
  17405. function __createO(o){ return init.call(o) }
  17406. function __createA(a){ a.forEach(r=> __createO(r)); return a }
  17407. var creatorFor = {
  17408. '[object Array]' : __createA
  17409. , '[object Object]' : __createO
  17410. , 'undefined' : function(){ return __create() }
  17411. };
  17412. function Rule(){ return arguments.length ? creatorFor[utils.js.nativeType(arguments[0])](...arguments) : creatorFor['undefined'](...arguments) }
  17413. // All static extensions shall be available on the instance as well.
  17414. var _extension = utils.assign({}, _XRule, extension);
  17415. function init() { return utils.assign(this, rProto, _extension, __newInstance(this), this) } _extension.init = init;
  17416. utils.assign(Rule, _Rule, _extension, __Rule);
  17417. // Immutable public static methods.
  17418. Rule.create = Rule;
  17419. Rule.build = buildRules;
  17420. Rule.match = match;
  17421. Rule.connect = connectRules;
  17422. Rule.branch = function(as, ...rest){
  17423. // PB : TODO -- All lists will be invalidated when we splice rules in...
  17424. // Rule.create()
  17425. // Replace an exisiting rule node with an intermediate rule that connects this rule to another rule.
  17426. console.error('Not yet implemented.');
  17427. };
  17428. // from loopback-connector/lib/sql.js
  17429. // PB : TODO -- a generic multipurpose buildwhere which doesn't enforce model property existence
  17430. // Convert from a natural filter to key val expanded filter.
  17431. // Convert In clauses to one rule for each listed values.
  17432. // Do not output the where clause but inlude the operator in the result assosiated with the respective params.
  17433. // Handle mask overflows gracefully
  17434. /**
  17435. * @param where
  17436. * @returns {ChoppedRules}
  17437. */
  17438. function buildRules(where, data, fullResult, parentRule) {
  17439. let columnValue;
  17440. if (!where) return Promise.resolve(fullResult) ;
  17441. if (typeof where !== 'object' || Array.isArray(where)) {
  17442. debug('Invalid value for where: %j', where);
  17443. return Promise.resolve(fullResult);
  17444. }
  17445. var ruleset = [];
  17446. // var id = Object.keys(where).length > 1 ? null : data ? data.id : null;
  17447. var id = data ? data.id : null;
  17448. fullResult = fullResult || [];
  17449. var createIntermediate = createIntermediateParentLess;
  17450. var immediateParentP = null;
  17451. if(parentRule) {
  17452. immediateParentP = parentRule;
  17453. createIntermediate = createIntermediateWithParent;
  17454. }
  17455. if(Object.keys(where).length > 1) {
  17456. immediateParentP = createIntermediate({operator : AND}, ()=>{ return [] }, parentRule);
  17457. ruleset.push(immediateParentP);
  17458. fullResult.push(immediateParentP);
  17459. createIntermediate = createIntermediateWithParent;
  17460. }
  17461. for (const key in where) {
  17462. // Handle and/or operators
  17463. if (key === AND || key === OR) {
  17464. const clauses = where[key];
  17465. if (Array.isArray(clauses)) {
  17466. if(clauses.length > 1) {
  17467. var rp = createIntermediate({operator : key}, (rParent)=>{
  17468. var list = [];
  17469. for (let i = 0, n = clauses.length; i < n; i++) {
  17470. list.push(buildRules(clauses[i], null, fullResult).then( ruleForClause => {
  17471. connectRules(operators[rParent.operator].bit, ruleForClause, rParent);
  17472. return ruleForClause;
  17473. }));
  17474. }
  17475. return list;
  17476. }, immediateParentP);
  17477. ruleset.push(rp);
  17478. fullResult.push(rp);
  17479. }
  17480. else {
  17481. // An outer 'or' OR 'and' condition is meaningless if we have only 1 clause. At least two are required to make sense.
  17482. // We just drop the wrapped grouped (or or and) condition and promote then inner clause to the same level. =
  17483. var rP = buildRules(clauses[0], null, fullResult, immediateParentP);
  17484. // fullResult.push(rP) // Buildrules should should have already pushed this.
  17485. ruleset.push(rP); // buildRules should have already linked parent and child.
  17486. }
  17487. continue;
  17488. }
  17489. else {
  17490. throw 'Invalid filter '
  17491. }
  17492. }
  17493. // eslint-disable one-var
  17494. let expression = where[key];
  17495. let p = key;
  17496. var op ='eq';
  17497. const columnName = columnEscaped(/* modelinstance || */ where, key);
  17498. // eslint-enable one-var
  17499. if (expression === null || expression === undefined) {
  17500. // If null has been passed in we should match null.
  17501. expression = null;
  17502. var rpromise = assignbit(Rule.create({ key : columnName, value : toColumnValue(p, expression)})).then((rChild)=>{
  17503. if(immediateParentP) {
  17504. return immediateParentP.then((immediateParent)=> {
  17505. connectRules(operators[immediateParent.operator].bit, rChild, immediateParent);
  17506. return rChild
  17507. })
  17508. }
  17509. // PB : TODO -- Unwrapped decendents update on parent!!!
  17510. return rChild
  17511. }).catch(e=>{ console.error('null expression : ' + e); });
  17512. fullResult.push(rpromise);
  17513. ruleset.push(rpromise);
  17514. } else if (expression && expression.constructor === Object) {
  17515. const operator = Object.keys(expression)[0];
  17516. expression = expression[operator];
  17517. if (operator === INQ || operator === NIN || operator === BETWEEN) {
  17518. columnValue = [];
  17519. op = operator === INQ ? (EQ) : operator === NIN ? (NEQ) : (LTE);
  17520. if (Array.isArray(expression)) {
  17521. // Column value is a list
  17522. for (let j = 0, m = expression.length; j < m; j++) {
  17523. columnValue.push(toColumnValue(p, expression[j]));
  17524. }
  17525. } else {
  17526. // Loopback keys arrays with an string key called '[]' for operators with an array value. This is weird.
  17527. columnValue.push(toColumnValue(p, expression['[]'] || expression ));
  17528. }
  17529. if (operator === BETWEEN) {
  17530. var rp = createIntermediate({operator : AND}, (rParent)=>{
  17531. // BETWEEN v1 AND v2
  17532. columnValue[0] === undefined ? null : columnValue[0];
  17533. columnValue[1] === undefined ? null : columnValue[1];
  17534. if(expression.length !== 2) console.error('Invalid between operator parameter length');
  17535. var list = [];
  17536. list.push(assignbit(Rule.create({key : columnName, value : columnValue[0], operator : GTE})).then((rChild)=>{
  17537. connectRules(operators[rParent.operator].bit, rChild, rParent);
  17538. return rChild
  17539. }));
  17540. list.push(assignbit(Rule.create({key : columnName, value : columnValue[1], operator : LTE})).then((rChild)=>{
  17541. connectRules(operators[rParent.operator].bit, rChild, rParent);
  17542. return rChild
  17543. }));
  17544. fullResult.push.apply(fullResult, list);
  17545. return list;
  17546. }, immediateParentP);
  17547. ruleset.push(rp);
  17548. fullResult.push(rp);
  17549. } else {
  17550. var rp = createIntermediate({operator : OR}, (rParent)=>{
  17551. // IN (v1,v2,v3) or NOT IN (v1,v2,v3)
  17552. // PB : TODO -- loopbacks handling of nulls is questionable. Invalid rules match nulls and return data.
  17553. if (columnValue.length === 0) {
  17554. if (operator === INQ) {
  17555. columnValue = [null];
  17556. } else {
  17557. // nin () is true
  17558. // nin : [null] is a world query which is an invalid filter. We don't support yet.
  17559. return [];
  17560. }
  17561. }
  17562. var list = [];
  17563. for (let j = 0, m = columnValue.length; j < m; j++) {
  17564. list.push(
  17565. assignbit(Rule.create({key : columnName, value : toColumnValue(p, columnValue[j]), operator : op})).then((rChild)=>{
  17566. connectRules(operators[rParent.operator].bit, rChild, rParent);
  17567. return rChild
  17568. })
  17569. );
  17570. }
  17571. fullResult.push.apply(fullResult, list);
  17572. return list
  17573. }, immediateParentP);
  17574. ruleset.push(rp);
  17575. fullResult.push(rp);
  17576. }
  17577. } else if (operator === 'regexp' && expression instanceof RegExp) {
  17578. // do not coerce RegExp based on property definitions
  17579. var rpromise = assignbit(Rule.create({key : columnName, value : toColumnValue(p, expression), operator})).then((rChild)=>{
  17580. if(immediateParentP) {
  17581. return immediateParentP.then((immediateParent)=> {
  17582. connectRules(operators[immediateParent.operator].bit, rChild, immediateParent);
  17583. return rChild
  17584. })
  17585. }
  17586. // PB : TODO -- Unwrapped decendents update on parent!!!
  17587. return rChild
  17588. }).catch(e=>{ console.error('Regexp expression : ' + e); });
  17589. fullResult.push(rpromise);
  17590. ruleset.push(rpromise);
  17591. // columnValue = expression;
  17592. } else {
  17593. var rpromise = assignbit(Rule.create({key : columnName, value : toColumnValue(p, expression), operator})).then((rChild)=>{
  17594. if(immediateParentP) {
  17595. return immediateParentP.then((immediateParent)=> {
  17596. connectRules(operators[immediateParent.operator].bit, rChild, immediateParent);
  17597. return rChild
  17598. })
  17599. }
  17600. // PB : TODO -- Unwrapped decendents update on parent!!!
  17601. return rChild
  17602. }).catch(e=>{ console.error('other expression : ' + e); });
  17603. fullResult.push(rpromise);
  17604. ruleset.push(rpromise);
  17605. // columnValue = toColumnValue(p, expression);
  17606. }
  17607. } else {
  17608. if(utils.js.isArray(expression)) throw 'Invalid array value for filter. Implicit INQ not supported. '
  17609. // ruleProcessor[EQ]();
  17610. var rpromise = assignbit(Rule.create({key : columnName, value : toColumnValue(p, expression), operator : EQ})).then((rChild)=>{
  17611. if(immediateParentP) {
  17612. return immediateParentP.then((immediateParent)=> {
  17613. connectRules(operators[immediateParent.operator].bit, rChild, immediateParent);
  17614. return rChild
  17615. })
  17616. }
  17617. // PB : TODO -- Unwrapped decendents update on parent!!!
  17618. return rChild
  17619. }).catch(e=>{ console.error('other expression : ' + e); });
  17620. fullResult.push(rpromise);
  17621. ruleset.push(rpromise);
  17622. }
  17623. }
  17624. return Promise.all(ruleset).then(()=>{
  17625. if(immediateParentP){
  17626. return immediateParentP;
  17627. }
  17628. if(ruleset.length > 1) {
  17629. // If only 1 rule there is no point in having an outer implicit and.
  17630. // If length is > 1 it implies there are a mixture of ands ors and raw rules specified as an outer object
  17631. // and we need to return the grouped rule.
  17632. // var grpromise = Promise.all(ruleset).then( (list)=>{
  17633. // var grouped = Rule.create({ id, operator : AND }).assignbit();
  17634. // return grouped.then(r=>{
  17635. // r.list = list;
  17636. // return r
  17637. // })
  17638. // });
  17639. // fullResult.push(grpromise)
  17640. // return grpromise
  17641. return ruleset[ruleset.length-1].then((r)=>{ r.id = id || r.id; return r});
  17642. }
  17643. else if(ruleset.length > 0) {
  17644. return ruleset[0].then((r)=>{ r.id = id || r.id; return r});
  17645. }
  17646. else {
  17647. if(fullResult.length > 0) return fullResult[fullResult.length-1].then((r)=>{ r.id = id || r.id; return r});
  17648. else return Promise.resolve([])
  17649. }
  17650. })
  17651. }
  17652. return Rule
  17653. }
  17654. };
  17655. var createIntermediateParentLess = (interMediatGroupParent, createChildren)=>{
  17656. var interMediatGroupParentP = assignbit(Rule.create(interMediatGroupParent)).then((rIntermediate)=>{
  17657. return rIntermediate
  17658. });
  17659. var grpromise = interMediatGroupParentP.then((rParent)=>{
  17660. // var rParent = resolved[1]
  17661. // if(immediateParentP) {
  17662. // connectRules( operators[ resolved[0].operator].bit, rParent, resolved[0] )
  17663. // // PB : Note -- we connect right here and after children are properly created we update parent descendents when we unwrap to root parent.
  17664. // rParent.ancestors |= resolved[0].ancestors | resolved[0].bit // PB : TODO -- should ancestors be included in the mask ???
  17665. // }
  17666. // PB : TODO -- When we unwind descendents on ancestors need to be updated.
  17667. // PB : TODO -- Why is this group not getting pushed into the full list.
  17668. // Also what happens when caluse[i] is an array ? Does a group get created and also clause i ?
  17669. return Promise.all(createChildren(rParent)).then( (list)=>{
  17670. // PB : TODO -- We don't know yet whether id needs to be assigned to this rule
  17671. // or an outer grouped rule.
  17672. rParent.list = list;
  17673. return rParent
  17674. });
  17675. });
  17676. return grpromise;
  17677. };
  17678. var createIntermediateWithParent = (interMediatGroupParent, createChildren, immediateParentP)=>{
  17679. var interMediatGroupParentP = assignbit(Rule.create(interMediatGroupParent)).then((rIntermediate)=>{
  17680. return immediateParentP.then((immediateParent)=>{
  17681. connectRules(operators[immediateParent.operator].bit, rIntermediate, immediateParent);
  17682. return rIntermediate
  17683. })
  17684. });
  17685. var grpromise = interMediatGroupParentP.then((rParent)=>{
  17686. // var rParent = resolved[1]
  17687. // if(immediateParentP) {
  17688. // connectRules( operators[ resolved[0].operator].bit, rParent, resolved[0] )
  17689. // // PB : Note -- we connect right here and after children are properly created we update parent descendents when we unwrap to root parent.
  17690. // rParent.ancestors |= resolved[0].ancestors | resolved[0].bit // PB : TODO -- should ancestors be included in the mask ???
  17691. // }
  17692. // PB : TODO -- When we unwind descendents on ancestors need to be updated.
  17693. // PB : TODO -- Why is this group not getting pushed into the full list.
  17694. // Also what happens when caluse[i] is an array ? Does a group get created and also clause i ?
  17695. return Promise.all(createChildren(rParent)).then( (list)=>{
  17696. // PB : TODO -- We don't know yet whether id needs to be assigned to this rule
  17697. // or an outer grouped rule.
  17698. rParent.list = list;
  17699. return rParent
  17700. });
  17701. });
  17702. return grpromise;
  17703. };
  17704. // Literals
  17705. const EQ = 'eq';
  17706. const LTE = 'lte';
  17707. const GTE = 'gte';
  17708. const LT = 'lt';
  17709. const GT = 'gt';
  17710. const AND = 'and';
  17711. const OR = 'or';
  17712. const INQ = 'inq';
  17713. const BETWEEN = 'between';
  17714. const NIN = 'nin';
  17715. const NEQ = 'neq';
  17716. __Rule.EQ = 1;
  17717. __Rule.LTE = 2;
  17718. __Rule.GTE = 4;
  17719. __Rule.LT = 8;
  17720. __Rule.GT = 16;
  17721. __Rule.AND = 32;
  17722. __Rule.OR = 64;
  17723. var operators = {
  17724. eq : { operator : '=', bit : __Rule.EQ}
  17725. , neq : { operator : '!=', bit : __Rule.NEQ}
  17726. , lte : { operator : '<=', bit : __Rule.LTE}
  17727. , gte : { operator : '>=', bit : __Rule.GTE}
  17728. , lt : { operator : '<', bit : __Rule.LT}
  17729. , gt : { operator : '>', bit : __Rule.GT}
  17730. , and : { operator : AND, bit : __Rule.AND}
  17731. , or : { operator : OR, bit : __Rule.OR}
  17732. };
  17733. var operatorsIndex = {};
  17734. Object.keys(operators).forEach(op => operatorsIndex[operators[op].bit] = operators[op] );
  17735. function __newInstance(o){
  17736. var d = new Date();
  17737. var id = o.id || uuidv1();
  17738. return { v1ruleId : id, id, datecreated : d, datemodified : d
  17739. , permissive : BIGINT_0, restrictive : BIGINT_0, descendents : BIGINT_0, ancestors : BIGINT_0, list :[] }
  17740. }
  17741. var globalBitIterator = bigIntBitGenerator();
  17742. function assignbit(rule){ var g = globalBitIterator.next().value; rule.bit = g.bit; rule.ruleiId = g.iId;
  17743. return Promise.resolve(rule); // PB : TODO -- remove backward compatible promisification...
  17744. }
  17745. // Find leaf rules from a set of rules ( in a database of rules ) that match the inputs
  17746. function getParticipating(iRule, rList, cb){
  17747. return Promise.all(iRule.results).then((iRules)=>{
  17748. var SUCCESS = BIGINT_0;
  17749. var FAILURE = BIGINT_0;
  17750. var mask = BIGINT_0;
  17751. var results = rList.filter(rule => {
  17752. var found = iRules.find( iR => {
  17753. if(iR.key && typeof(iR.key)=='string'){iR.key=iR.key.toUpperCase();}
  17754. if(iR === rule || iR.id === rule.id ||
  17755. iR.key === rule.key &&
  17756. ( rule.operator == GT && (
  17757. rule.value <= iR.value && iR.operator == GT
  17758. || rule.value < iR.value && ( iR.operator == GTE || iR.operator == EQ )
  17759. )
  17760. || rule.operator == GTE && (
  17761. rule.value <= iR.value && (iR.operator == GTE || iR.operator == EQ)
  17762. || (iR.value - rule.value) >= 0 && iR.operator == GT
  17763. )
  17764. || rule.operator == LT && (
  17765. rule.value >= iR.value && iR.operator == LT
  17766. || rule.value > iR.value && ( iR.operator == LTE || iR.operator == EQ )
  17767. )
  17768. || rule.operator == LTE && (
  17769. rule.value >= iR.value && (iR.operator == LTE || iR.operator == EQ)
  17770. || (rule.value - iR.value) >= 0 && iR.operator == LT
  17771. )
  17772. || rule.operator == EQ && (
  17773. rule.value == iR.value && iR.operator == EQ
  17774. )
  17775. )
  17776. ) {
  17777. SUCCESS |= bufferToBigInt(rule.bit);
  17778. mask |= bufferToBigInt(rule.mask);
  17779. return true;
  17780. }
  17781. });
  17782. if(!found) {
  17783. if(rule.isleaf) { FAILURE |= rule.bit; }
  17784. else {
  17785. // Composite rule evaluation here is incomplete since we are still iterating and finding leaf level participants.
  17786. // Optimistically computed in case we get lucky here on first pass for result caching efficiency.
  17787. // No point in attempting a full evaluation for composite rule through parts as parts are still being evaluated.
  17788. // A priority evaluation registration of leaf level descendents with a async postponed evaluation task for this rule...
  17789. // may help with evaulation of relevant rules earlier....
  17790. // This specific rules full evaluation may be moot if no asserting participants can be found.
  17791. // Or all its ancestral rules are already true without needing this rule to be evaluated....
  17792. if(rule.permissive && rule.restrictive){
  17793. if(rule.permissive & SUCCESS ) { SUCCESS |= rule.bit; mask |= rule.mask; return true; }
  17794. if(rule.restrictive & FAILURE) {FAILURE |= rule.bit; }
  17795. if(rule.restrictive && (rule.restrictive & SUCCESS) === rule.restrictive) { SUCCESS |= rule.bit; mask |= rule.mask; return true; }
  17796. if(rule.permissive && (rule.permissive & FAILURE) === rule.permissive) {FAILURE |= rule.bit; }
  17797. }
  17798. // if((rule.descendents & SUCCESS) === rule.descendents) {
  17799. // // Implies all intermediate groups are true. We only need to examine direct leaf connections.
  17800. // SUCCESS |= rule.bit;
  17801. // mask |= rule.mask;
  17802. // }
  17803. }
  17804. }
  17805. return found;
  17806. });
  17807. if(utils.js.isFunction(arguments[arguments.length-1])) { return cb(null, { SUCCESS, FAILURE, mask, results} ) }
  17808. else return { mask, list : found};
  17809. });
  17810. }
  17811. function getParticipatingRoots(participating, rList, cb){
  17812. var qualifiedRoots = [];
  17813. rList.forEach((r)=>{
  17814. if(r.isRoot && evaluate(r, participating)){ qualifiedRoots.push(r); }
  17815. });
  17816. cb(null, qualifiedRoots);
  17817. }
  17818. function toColumnValue(p, v) { return v; }
  17819. function columnEscaped(inst, p) { return p; }
  17820. function getsql_cond_group(){
  17821. if(!this.list) { console.warn(`${this.operator} condition without list is moot`); return ''}
  17822. if(this.list.length < 2) {
  17823. this.list.push( this.list[0] ); // PB : TOOD -- We are adding instead of eliminating Redundant groups ...
  17824. }
  17825. var slqexprs = [];
  17826. this.list.forEach(r => slqexprs.push(r.sql) );
  17827. return '( ' + slqexprs.join( ` ${this.operator} `) + ' )'
  17828. }
  17829. function getfilter_cond_group(){
  17830. if(!this.list) { console.warn(`${this.operator} condition without list is moot`); return ''}
  17831. if(this.list.length < 2) {
  17832. this.list.push( this.list[0] ); // PB : TOOD -- We are adding instead of eliminating Redundant groups ...
  17833. }
  17834. var filterexprs = [];
  17835. this.list.forEach(r => filterexprs.push(r.filter) );
  17836. return filterexprs;
  17837. }
  17838. // PB : TODO -- This might be easier done in a stored procedure.
  17839. // It will also help if participating is not the whole list but the filtered list relevant for this rule.
  17840. // Relocation so inline functions don't need to be redefined again and again.
  17841. // Implement __Rule.isRoot
  17842. var evaluate = function(rule, participating){
  17843. if(rule.bit & participating.SUCCESS ) return true;
  17844. if(rule.bit & participating.FAILURE) return false
  17845. if(rule.permissive & participating.SUCCESS ) { participating.SUCCESS |= rule.bit; return true }
  17846. if(rule.restrictive & participating.FAILURE) {participating.FAILURE |= rule.bit; return false;}
  17847. if(rule.restrictive && (rule.restrictive & participating.SUCCESS) === rule.restrictive) { participating.SUCCESS |= rule.bit; return true }
  17848. if(rule.permissive && (rule.permissive & participating.FAILURE) === rule.permissive) {participating.FAILURE |= rule.bit; return false;}
  17849. // PB : TODO -- Truth value of grouped could be driven from the roots so we can limit to those rules that are relevant and avoid evaluation of each one.
  17850. if(rule.isleaf) {
  17851. if(participating.results.find( pp => pp === rule )) { participating.SUCCESS |= rule.bit; return true }
  17852. else { participating.FAILURE |= rule.bit; return false; }
  17853. }
  17854. // else {
  17855. // // If descendents are true we can extract only the ones that are direct connections and
  17856. // // Evaluate...
  17857. // var alldescendentsAreTrue = false;
  17858. // if((rule.descendents & participating.SUCCESS) === rule.descendents) {
  17859. // // Implies all intermediate groups are true. We only need to examine direct leaf connections.
  17860. // alldescendentsAreTrue = true;
  17861. // }
  17862. // }
  17863. // getUnevaluated
  17864. var permissive = rule.permissive & (BigInt(-1)-participating.SUCCESS) & (BigInt(-1)-participating.FAILURE);
  17865. for(var rc in rule.list){
  17866. var r = rule.list[rc];
  17867. if(r.bit & permissive) {
  17868. if(evaluate(r, participating)) { participating.SUCCESS |= r.bit; participating.SUCCESS |= rule.bit; return true }
  17869. else participating.FAILURE |= r.bit;
  17870. }
  17871. }
  17872. if(rule.permissive){ participating.FAILURE |= rule.bit; return false; }
  17873. // getUnevaluated.
  17874. var restrictive = rule.restrictive & (BigInt(-1)-participating.SUCCESS) & (BigInt(-1)-participating.FAILURE);
  17875. for(var rc in rule.list){
  17876. var r = rule.list[rc];
  17877. if(r.bit & restrictive) {
  17878. if(!evaluate(r, participating)) { participating.FAILURE |= r.bit; participating.FAILURE |= rule.bit; return false}
  17879. participating.SUCCESS |= r.bit;
  17880. }
  17881. }
  17882. if(rule.restrictive){ participating.SUCCESS |= rule.bit; return true; }
  17883. throw 'Error : A group rule should either be permissive or restrictive...'
  17884. };
  17885. var match = function (inputs, rList, cb) {
  17886. var results = [];
  17887. if (typeof(clause)==undefined){var clause=null;}
  17888. Rule.build(inputs, clause, results).then((inputRule)=>{
  17889. inputRule.results = results;
  17890. // inputs are usually individual assertions. An and / or condition between individual assertions are usually not useful.
  17891. // Unless the assertion is of the form
  17892. // Eg : this indiviudal's age is between x and y which is kind of rare.
  17893. // A negation is also not how an assertion is typically made. However not from location C or D is a possible assertion.
  17894. // An or assertion is still more rare and is usually an abstraction to not be specific.
  17895. // Eg : The user is from location A or B and uses either a Mac or Ubuntu OS.
  17896. // Although the user has specific characteristics the specificity is not disclosed in the inputs.
  17897. // And is adequate to distinguish the inputs from amongst a superset.
  17898. // In the above example the user cannot be from both locations A and B at the same time but could be using both Mac and Ubuntu probably even at the same time.
  17899. // 1) The simplest and fastest use case is exact matches of input assertions with and exact match of saved rules.
  17900. // 2) exact input values with condition groups in the rules is also supportable.
  17901. // 3) complex input rules as abstract or range assertions matching
  17902. // complex rules that have range or absctract conditions -- How to Implement ??
  17903. // IMPLEMENTATION AS SQL
  17904. // FIND PARTICIPATING rules that evaluate true.
  17905. /* WHERE rule.key = input.key ( rule.operator = '>' AND rule.value <= input.value AND input.operator = '>'
  17906. OR rule.operator = '>' AND rule.value < input.value AND input.operator = '>='
  17907. OR rule.operator = '>=' AND rule.value <= input.value AND (input.operator = '>=' OR input.operator = '=')
  17908. ) AND
  17909. ( rule.operator = '<' AND rule.value <= input.value AND input.operator = '<'
  17910. OR rule.operator = '<' AND rule.value < input.value AND input.operator = '<='
  17911. OR rule.operator = '<=' AND rule.value <= input.value AND (input.operator = '<=' OR input.operator = '=')
  17912. )
  17913. */
  17914. // QUALIFY ALL ( GROUPED and LEAF ) RULES that evaluate true using the assertions from the participating rules.
  17915. /*
  17916. LEFT JOIN rule
  17917. WHERE participating.bit = (participating.bit & rule.mask)
  17918. -- and rule.operator = 'or'
  17919. -- or rule.mask = (allparticipating.mask & rule.mask ) and rule.operator = 'and'
  17920. */
  17921. /* USE THE QUALIFED RULES TO EVALUEATE RESULTS for GROUP LEVELS and ROOT RULES.
  17922. Any grouped rule is associated with 3 kinds evaluation sets composed of rules that are either leaf
  17923. level rules directly or through other promoted grouped rules or groups.
  17924. Evaluation Sets.
  17925. Permissive rules, Restrictive rules, Indeterminant rules
  17926. 1) Permissive bits turn the whole group to true if any one is true.
  17927. Irrespective of all the other participating leaf rules.
  17928. It is therefore not required to evaluate any other types of leaf rules.
  17929. 2) Restrictive rules turn the whole group to false if any one is false.
  17930. If there are no permissive rules it then becomes relevant to evaluate the restrictive rules.
  17931. Other Indeterminant rule evaluation is therefore not relevant.
  17932. 3) Indeterminant rules need to be evaluated at run time.
  17933. -- Are typically unevaluated nested groups
  17934. -- Or can be Individual Evaluated results
  17935. which don't yet determine the overall result and mean anything
  17936. until a complex hierarchy of conditions
  17937. are evaluated and collectively satisifed.
  17938. -- Since we do not (yet) support rule negations
  17939. -- it necessarily implies that if all of the Indeterminant set items are true then the whole group is true.
  17940. -- which then implies we can bypass the Indeterminant group and subgroup structure evaluation for efficiency.
  17941. -- Pre-Evaluated promotion to parent group evaluation sets to parent groups evaluation sets.
  17942. Composition of a subgroup can be promoted directly into the parent groups evaluation sets when certain conditions are met.
  17943. When There are no Permissive rules
  17944. AND ( There are no restrictive rules OR all the restrictive rules are true )
  17945. Then evaluation of the descendents rule set is required until we reach all leaf level nodes.
  17946. Subgroups are recursively evaluated using these same 3 steps.
  17947. Following caching efficiencies can be precomputed and stored with the parents rule sets as rule promotions.
  17948. If the sub group rule participates in parents permissive set.
  17949. All of its permissive rules should be added to the parent groups permissive set.
  17950. -- The sub group has no restrictive and descendents sets sub group bit need not be in the parents permissive set.
  17951. If subgroup has restricitve sets and no descendents sets
  17952. -- and is a subset of the parent groups restrictive set
  17953. -- then subgroup bit can be removed from parents permissive and restrictive groups.
  17954. -- This is good for preventing re-evaluation of the sub group for efficiency.
  17955. -- else subgroup bit should be present in the permissive
  17956. Sub group has descendents sets
  17957. -- the sub group bit must necessarily be added to the parents permissive set.
  17958. If the sub group rule participates in the parents restrictive set
  17959. - Sub Group is Pure Permissive = Has no restrictive set or descendents set
  17960. Runtime Evaluate.
  17961. - Sub Group is Pure Restrictive = Has no permissive or descendents set
  17962. -- Restrictive set of sub group should be promoted into the restrictive set of the parent
  17963. -- sub group bit should be removed from all parent sets for effciency by bypassing subgroup evaluation.
  17964. - All other cases Runtime Evaluate.
  17965. Sub Group participates in descendents set.
  17966. -- Run time evaluation.
  17967. */
  17968. getParticipating(inputRule, rList, (err, participating)=>{
  17969. getParticipatingRoots(participating, rList, (err, participatingRoots)=>{
  17970. cb(null, participatingRoots);
  17971. });
  17972. });
  17973. });
  17974. };
  17975. // PB : TODO -- Creations are easy. Edits and updates for addition of a single rule are expensive due to cascading updates to all relations.
  17976. // Connections can be made in multiple dimensions. For Rules we currlently only implement the child and parent dimensions.
  17977. // PB : TODO -ve dimensions ?? In this implementation there are no negative dimensions...
  17978. // So both -ve and +ve dimensions are independent. But can be marked as opposites.
  17979. // Note : Therefore Child and Parent are different independent dimensions.
  17980. // They may not be exactly oposing in this case ( Rules are networks ) and some circular loops may exist.
  17981. var connectRules = function(as, ...rest){ return branch[as](...rest) };
  17982. var branch = {};
  17983. branch[__Rule.AND] = function(rChild, rParent, refresh){
  17984. rChild.ancestors |= rParent.ancestors | rParent.bit; // This should set the whole ancestral network.
  17985. if(rParent.permissive || rParent.operator === OR) throw 'Error Invalid rule addition to parent'
  17986. if(rParent.restrictive & rChild.bit) return; // Was already connected within this and.
  17987. rParent.list.push(rChild);
  17988. // if(!rParent.permissive && !rParent.restrictive) {
  17989. // if(rParent.operator !== AND && rParent.operator !== OR) {
  17990. // if(!rParent.operator) rParent.operator = AND; // Implicit AND if unspeicified
  17991. // else throw 'Incomplete parent. Invalid operator or no operator specified.'
  17992. // }
  17993. // rParent.operator === AND ? rParent.restrictive |= rChild.bit : rParent.permissive |= rChild.bit ;
  17994. // }
  17995. // Promotions : All child rules are only a bunch of Ands or ors
  17996. // they can be flattened directly into the containing rule.
  17997. // if(!rParent.permissive) { rParent.restrictive |= rChild.restrictive; rParent.restrictive |= rChild.bit; }
  17998. // if(!rParent.restrictive) { rParent.permissive |= rChild.permissive; rParent.permissive |= rChild.bit; }
  17999. rParent.restrictive |= rChild.restrictive | rChild.bit;
  18000. // Descendents should be all non immediate descendents.
  18001. // Immmediate descendents can always be computed as (r.permissive | r.restrictive) & !r.descendents
  18002. // child may be either permissive or restrictive. Since child.restrictive is already added in.
  18003. rParent.descendents |= rChild.descendents | rChild.permissive | rChild.restrictive ;
  18004. // If we add another ancestral network to one of the ancestors we need to cascaded it down to the child network.
  18005. // and vice versa.
  18006. if(refresh){
  18007. // PB : TODO -- Cascading refreshes should avoid circular loops..
  18008. rChild.refreshDescendents(rChild.ancestors);
  18009. rParent.refreshAncestors(rParent.descendents);
  18010. }
  18011. };
  18012. branch[__Rule.OR] = function(rChild, rParent, refresh){
  18013. rChild.ancestors |= rParent.ancestors | rParent.bit;
  18014. if(rParent.restrictive || rParent.operator !== OR) throw 'Error Invalid rule addition to parent'
  18015. if(rParent.permissive & rChild.bit) return
  18016. rParent.list.push(rChild);
  18017. rParent.permissive |= rChild.permissive | rChild.bit;
  18018. rParent.descendents |= rChild.descendents | rChild.permissive | rChild.restrictive ;
  18019. if(refresh){
  18020. rChild.refreshDescendents(rChild.ancestors); // This should set the whole ancestral network.
  18021. rParent.refreshAncestors(rParent.descendents);
  18022. }
  18023. };
  18024. var rProto = { migrationstate : 8, operator : EQ
  18025. , evaluate // PB : TODO -- Enforce preconditions for evaluate on instance. Eg. Assignbit is a precondition for evaluate or match.
  18026. , connect : function(parent){
  18027. connectRules(operators[parent.operator].bit, this, parent);
  18028. }
  18029. // PB : TODO -- Cloning descriptors using assgin is expense. Review and just atttach to each new instance...
  18030. , get sql(){
  18031. var getSql = this.operator === AND ? getsql_cond_group : this.operator === OR ? getsql_cond_group
  18032. : ()=>this.key + ' ' + operators[this.operator].operator +
  18033. (Object.prototype.toString.call(this.value) === '[object Date]' ? ` '${this.value.toISOString()}' ` :` '${this.value}' `);
  18034. return getSql.call(this)
  18035. }
  18036. , get filter(){
  18037. var getFilter = this.operator === AND ? getfilter_cond_group : this.operator === OR ? getfilter_cond_group
  18038. : ()=>{
  18039. var f = {};
  18040. f[this.key] = {};
  18041. f[this.key][this.operator] = this.value; return f;};
  18042. return getFilter.call(this)
  18043. }
  18044. // PB : TODO -- this.siblings will be a nice addition.
  18045. , get mask(){ return this.permissive | this.restrictive | this.descendents | this.ancestors | this.bit }
  18046. , get isIndependent() { return (!this.mask || (this.bit === this.mask)) }
  18047. , get isRoot() { return !this.ancestors }
  18048. , get isChild() { return this.ancestors }
  18049. , get isParent() { return (this.permissive | this.restrictive | this.descendents) }
  18050. , get isleaf() { return !this.bit || !(this.permissive | this.restrictive | this.descendents) }
  18051. , get iscomposite() { return this.list.length > 1 } // PB : TODO -- Non composite parents may be possible to collapse
  18052. };
  18053. return _Rule.extend()
  18054. })();
  18055. // Rule.build(clause, null, fullResults).then((rootRule)=>{
  18056. // // console.dir(rootRule)
  18057. // return Promise.all(fullResults).then((fullResults)=>{
  18058. // console.dir(fullResults)
  18059. // console.log(fullResults.length)
  18060. // console.dir(rootRule.sql)
  18061. // console.dir(Rule.match({ and : [ {"field1" : 'foo'}, {"field2" : 'bar'}] }, fullResults, (err, rootRules)=>{
  18062. // console.dir(rootRules)
  18063. // }))
  18064. // })
  18065. // });
  18066. // clause = {
  18067. // or: [
  18068. // { and : [ {"field1" : 'foo'}, {"field2" : 'bar'}] },
  18069. // { and : [ {"field1" : 'morefoo'}, {or : [{"field2" : 'morefoo2'}, {"field3" : 'morefoo3'}] } ] },
  18070. // {"datacontext" : {inq: [1, 2, 4, 16]}},
  18071. // {"date" : {gt: new Date('2020-10-01T18:30:00.000Z')}},
  18072. // { or : [ { x : 'y'}, {"dob" : {between: [new Date('2010-01-01T18:30:00.000Z'), new Date('2010-06-01T18:30:00.000Z')] }} ] }
  18073. // ]
  18074. // , a : { 'eq' : 'b'}
  18075. // , x : 'y'
  18076. // }
  18077. // Rule.build(clause, null, fullResults).then((rootRule)=>{
  18078. // // console.dir(rootRule)
  18079. // return Promise.all(fullResults).then((fullResults)=>{
  18080. // // console.dir(fullResults)
  18081. // console.log(fullResults.length)
  18082. // console.log(fullResults.length)
  18083. // console.dir(rootRule.sql)
  18084. // Rule.match({ and : [ {"field1" : 'foo'}, {"field2" : 'bar'}] }, fullResults, (err, rootRules)=>{
  18085. // console.dir(rootRules)
  18086. // })
  18087. // })
  18088. // });
  18089. })();
  18090. }, "/$$rollup_base$$/node_modules/bbhverse");
  18091. utils_1.core = core;
  18092. var bbhverse = utils_1;
  18093. const { spawn: spawn$1, spawnSync } = childProcess__default["default"];
  18094. function nodeShellExec$3() {
  18095. var args = Array.from(arguments);
  18096. if(args.length > 1){
  18097. var opts = args[2] = args[2] || {};
  18098. opts.title ? null : opts.title = `${args[0]} ${args[1] }`;
  18099. }
  18100. else {
  18101. var opts = {
  18102. title : `${args[0]}`
  18103. // , inherit: true, shell: true
  18104. };
  18105. }
  18106. opts.stdin = 'pipe';
  18107. // // const spawn = require('child_process').spawn;
  18108. // const s = spawn(
  18109. // 'C:\\Program Files\\Git\\bin\\sh.exe'
  18110. // , ['notepad', 'index'], { cwd: __dirname });
  18111. // var interval = null;
  18112. // var t = setTimeout(function(){
  18113. // interval = setInterval(function(){
  18114. // console.log('Awaiting close : ' + child.spawnargs)
  18115. // }, 1500)
  18116. // // console.log('Awaiting close : ' + child.spawnargs)
  18117. // }, 0)
  18118. // child.on('close', (code) => {
  18119. // console.error('Prematurely closed even before promise...')
  18120. // })
  18121. // D:\chess\instances\elixir_01\elxr/.elxr/run-1630002739610/download.bat https://github.com/git-for-windows/git/releases/download/v2.33.0.windows.2/Git-2.33.0.2-64-bit.exe D:\\chess\\instances\\elixir_01\\elxr/Downloads/Git-2.33.0.2-64-bit.exe
  18122. // D:\\chess\\instances\\elixir_01\\elxr/.elxr/run-1630002923584/download.bat https://github.com/git-for-windows/git/releases/download/v2.33.0.windows.2/Git-2.33.0.2-64-bit.exe D:\\chess\\instances\\elixir_01\\elxr/Downloads/Git-2.33.0.2-64-bit.exe
  18123. // console.dir(args[2])
  18124. console.dir(`${args[0]} ${args[1].join(' ') }`);
  18125. const child = spawn$1(...args);
  18126. var p = new Promise(function(resolve, reject){
  18127. // console.log(...args)
  18128. if(!opts.detached) {
  18129. var messages = []; // PB : TODO -- Explore stream for Task level aggregation to prevent interleaved messages from multiple tasks...
  18130. var success = true;
  18131. if(opts.stdio !== 'ignore') {
  18132. child.stdout.setEncoding('utf8');
  18133. child.stderr.setEncoding('utf8');
  18134. child.stdout.on('data', (chunk) => {
  18135. chunk.trim() === '' ? null : messages.push(chunk); /* console.log('d: ' + chunk) */
  18136. process.stdout.write( chunk );
  18137. });
  18138. child.on('error', (chunk) => { success = false; messages.push(chunk); /* console.error('e: ' + chunk) */
  18139. console.log('Error exit not handled.');
  18140. } );
  18141. child.stderr.on('data', (chunk) => {
  18142. if(messages.join('').indexOf('fatal: not a git repository') > -1) opts.haserrors = true;
  18143. messages.push(chunk);
  18144. // process.stdout.write( chunk )
  18145. // console.error('stderr e: ' + chunk)
  18146. });
  18147. }
  18148. child.on('close', (code) => {
  18149. // console.log('Proper close was fired')
  18150. var logEntry = { code, success };
  18151. if(+code !== 0 || opts.haserrors) {
  18152. success = false; logEntry = { messages, result: `${opts.title} exited with code ${code}`, success, code };
  18153. } if(opts.stdio !== 'ignore') {
  18154. logEntry = { result: `${opts.title} exited with code ${code}`, messages, code };
  18155. logEntry.success = success;
  18156. if(opts.evaluateResult) logEntry = opts.evaluateResult(success, logEntry);
  18157. if(opts.runas){
  18158. // success ? logEntry.success = true : null;
  18159. fs__default["default"].writeFileSync('run.log', ', ' + JSON.stringify(logEntry), {'flag':'a+'} );
  18160. }
  18161. else {
  18162. // console.log( messages.join('') )
  18163. process.stdout.write( messages.join('') );
  18164. }
  18165. }
  18166. else if(opts.evaluateResult) {
  18167. try { logEntry = opts.evaluateResult(false, logEntry); }
  18168. catch(e){ reject(e); }
  18169. }
  18170. // clearInterval(interval)
  18171. if(code !== 0 || opts.haserrors) {
  18172. args[2].benign || args[2].ignorefailures ? (logEntry.benign = true, logEntry.ignorefailures = true) : null;
  18173. return reject(logEntry)
  18174. }
  18175. resolve(logEntry);
  18176. });
  18177. }
  18178. else {
  18179. child.unref();
  18180. // clearInterval(interval)
  18181. resolve(true);
  18182. }
  18183. });
  18184. p.process = child;
  18185. return p;
  18186. }
  18187. var prompt = function(choices, label, defaultchoice, selectedchoice){
  18188. // prompt accepts either an array or an object as choices.
  18189. var choices = choices || [];
  18190. defaultchoice = defaultchoice || choices[0] || selectedchoice || choices[Object.keys(choices)[0]];
  18191. var ci = 0;
  18192. return this.prompter.ask(
  18193. `${label} \n` + Object.keys(choices).map(
  18194. choice => {
  18195. ++ci; var choice_label = isNaN(+choice) ? `${ci}) (${choice})` : ci + ')';
  18196. return ` ${choice_label} ${choices[choice]} `
  18197. }).join('\n')
  18198. + `\n d) default ( <= ${ defaultchoice || choices[0]} ) : `
  18199. + `\n selected ( <= ${ selectedchoice || defaultchoice || choices[0]} ) : `
  18200. ).then(choice => {
  18201. // propName = promptable.interpret(propValue)
  18202. if(!choice && selectedchoice) return selectedchoice;
  18203. if(!choice) return defaultchoice || choices[0];
  18204. if(choice && isNaN(+choice)) {
  18205. if(choice === 'd') return defaultchoice || choices[0];
  18206. try {
  18207. return JSON.parse(choice);
  18208. }
  18209. catch(e) {
  18210. // console.error(e)
  18211. return choice // Treat it as a string if it is not parsable
  18212. }
  18213. }
  18214. return choices[(+choice) - 1];
  18215. })
  18216. };
  18217. var cli = {
  18218. nodeShellExec: nodeShellExec$3
  18219. , get prompter() {
  18220. var prompt_interface = {
  18221. ask : function(q){
  18222. // Needs to be serialized. Parallel asks are not possible.
  18223. const clii = readline__default["default"].createInterface({ input: process.stdin, output: process.stdout });
  18224. return new Promise((resolve, reject)=>{
  18225. clii.question(q, (answer)=>{
  18226. try {
  18227. clii.close();
  18228. console.log("readline.createInterface closed");
  18229. resolve(answer);
  18230. }
  18231. catch(e) {
  18232. reject(e);
  18233. }
  18234. });
  18235. })
  18236. }
  18237. };
  18238. return prompt_interface
  18239. }
  18240. , prompt
  18241. , createTask(task, str){
  18242. var tasks = {
  18243. getTaskCheckExists : (str)=>{
  18244. return (command, options) => {
  18245. options = options || {};
  18246. return () => {
  18247. var p = nodeShellExec$3.apply(null, [str, [command]]);
  18248. if (options.ignorefailures) {
  18249. return p.then(() => { return true }).catch(e => { // Ignore. Not a major error.
  18250. return false;
  18251. })
  18252. }
  18253. else return p.then(() => { return true });
  18254. }
  18255. }
  18256. }
  18257. };
  18258. return tasks[task](str)
  18259. }
  18260. };
  18261. var cliverse = cli;
  18262. const { any: any$2 } = bbhverse;
  18263. var nodeShellExec$2 = cliverse.nodeShellExec;
  18264. var __isElevated$1 = null;
  18265. var shell_verse$2 = {
  18266. // getCommonTask is agnostic of whether we are running in an elevated shell or not. It runs in either case.
  18267. getCommonTask( taskToRun ){ return ()=>{ return shell_verse$2.runTask(taskToRun) }}
  18268. , runTask : ( taskToRun ) => {
  18269. if (__isElevated$1) return shell_verse$2.elevatedRunner( taskToRun )
  18270. else return shell_verse$2.runNonElevated( taskToRun )
  18271. }
  18272. , elevatedRunner( taskToRun, inBatch ){
  18273. // PB : TODO -- Should be called only when we are in an elevated shell that was already requested from an unelevated shell with a batch of tasks.
  18274. try {
  18275. var __runasresult = null;
  18276. return taskToRun().then((r)=>{
  18277. // PB : TODO -- Every elevation should have its own messaging file. Async writes from multiple processes are a problem here...
  18278. fs__default["default"].writeFileSync('run.log', ', ' + JSON.stringify( { info : taskToRun.info, success: true }), { 'flag': 'a+' });
  18279. if(!inBatch) fs__default["default"].writeFileSync('run.done', 'success'); // PB : TODO -- This should be done conditionally if we are running inproc.
  18280. return __runasresult = r;
  18281. })
  18282. .catch((e) => {
  18283. fs__default["default"].writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' });
  18284. if(!inBatch)fs__default["default"].writeFileSync('run.done', 'failure');
  18285. console.error(e);
  18286. })
  18287. .finally(() => {
  18288. // if(__runasresult && !__runasresult.skipped) fs.unlinkSync('run.done')
  18289. })
  18290. }
  18291. catch (e) {
  18292. console.error('Error Invalid command : ' + e);
  18293. if(!inBatch) fs__default["default"].writeFileSync('run.done', 'error');
  18294. }
  18295. finally {
  18296. }
  18297. }
  18298. , getElevatedTask : function( taskToRun ){ return ()=>{ return shell_verse$2.runElevated(taskToRun) }}
  18299. , getElevatedTaskInBatch : function( taskToRun ){ return ()=>{ return shell_verse$2.runElevatedInBatch(taskToRun) }}
  18300. , runElevatedInBatch : ( taskToRun ) => {
  18301. if (__isElevated$1) return shell_verse$2.elevatedRunner(taskToRun, true)
  18302. else return shell_verse$2.requestElevation(shell_verse$2.elevatedRunner, taskToRun)
  18303. }
  18304. , runElevated : ( taskToRun ) => {
  18305. // Let shell_verse decide whether to Elevate Out of Proc or In Proc
  18306. // taskToRun by default is the launched command and args. Specially in windows out of proc.
  18307. // taskToRun = taskToRun || (()=>{ return op[processedArgs.label || processedArgs._[0] || 'undefined'](processedArgs) })
  18308. if(taskToRun.processedArgs.skipelevated) return Promise.resolve({ skipped : true });
  18309. if (__isElevated$1) {
  18310. return shell_verse$2.elevatedRunner(taskToRun)
  18311. }
  18312. else {
  18313. console.log('Requesting Elevated Privileges');
  18314. // requesteElevation is acutally request elevation and run. Both In Proc and Out of Proc.
  18315. // Linux doesnt require elevation for most commands...
  18316. return shell_verse$2.requestElevation(shell_verse$2.elevatedRunner, taskToRun)
  18317. }
  18318. }
  18319. , runElevatedBatch( batchToRun ){
  18320. // In windows we don't need to run each task. We hand over to another shell which in elevated state rebuilds the whole batch and runs.
  18321. // Irrespective of the batch we just call runElevated once.
  18322. if (__isElevated$1) {
  18323. return any$2(batchToRun).then((r)=>{
  18324. // PB : TODO -- Every elevation should have its own messaging file. Async writes from multiple processes are a problem here...
  18325. // fs.writeFileSync('run.log', ', ' + JSON.stringify( { info : taskToRun.info, success: true }), { 'flag': 'a+' })
  18326. fs__default["default"].writeFileSync('run.done', 'success'); // PB : TODO -- This should be done conditionally if we are running inproc.
  18327. return __runasresult = r;
  18328. })
  18329. .catch((e) => {
  18330. // fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' })
  18331. fs__default["default"].writeFileSync('run.done', 'failure');
  18332. console.error(e);
  18333. })
  18334. // .finally(() => {
  18335. // if(__runasresult && !__runasresult.skipped) fs.unlinkSync('run.done')
  18336. // });
  18337. }
  18338. else {
  18339. return this.runElevated(batchToRun[0])
  18340. }
  18341. }
  18342. , getNonElevatedTask : function( taskToRun ){ return ()=>{ return shell_verse$2.runNonElevated(taskToRun) } }
  18343. , runNonElevated : ( taskToRun ) => {
  18344. // Let shell_verse decide whether to Elevate Out of Proc or In Proc
  18345. if(__isElevated$1) {
  18346. return Promise.resolve( 'Skipping regular task in elevated shell.' ) // Regular tasks unless marked as common tasks should not run in elevated shell...
  18347. }
  18348. else {
  18349. // taskToRun by default is the launched command and args.
  18350. // taskToRun = taskToRun || (()=>{ return op[processedArgs.label || processedArgs._[0] || 'undefined'](processedArgs) })
  18351. return taskToRun().then(r=>{
  18352. taskToRun.statuslog.statuslog(null, taskToRun.info /*repo*/ );
  18353. return r;
  18354. }).catch((e) => {
  18355. e.info = taskToRun.info;
  18356. taskToRun.statuslog.statuslog(e);
  18357. if(taskToRun.errHandler) throw taskToRun.errHandler(e)
  18358. // console.error(e)
  18359. throw e;
  18360. }).finally(()=>{})
  18361. }
  18362. }
  18363. , isElevated : ()=>{
  18364. return acquireElevationState().then( ()=>{
  18365. shell_verse$2.isElevated = () => {
  18366. return Promise.resolve(__isElevated$1)
  18367. };
  18368. return shell_verse$2.isElevated()
  18369. })
  18370. }
  18371. // , isElevationOutOfProc : ()=>{ return true }
  18372. , acquireElevationState : () => {
  18373. return nodeShellExec$2("fsutil", ["dirty", "query", "C:"], {
  18374. inherit: true
  18375. // , shell: true
  18376. , stdio: 'ignore'
  18377. , env: process.env
  18378. , title: `check privileged execution mode using "fsutil dirty query C:"`
  18379. }).then((exitcode) => {
  18380. console.log('Elevated');
  18381. __isElevated$1 = true;
  18382. }).catch(() => {
  18383. __isElevated$1 = false;
  18384. console.log('Not Elevated');
  18385. }).finally(()=>{
  18386. shell_verse$2.acquireElevationState = ()=> Promise.resolve(__isElevated$1);
  18387. shell_verse$2.isElevated = () => { return Promise.resolve(__isElevated$1)};
  18388. return __isElevated$1;
  18389. })
  18390. }
  18391. , getTaskCheckExists : cliverse.createTask('getTaskCheckExists', 'where')
  18392. , getbash : ()=>{ return "C:\\Program Files\\Git\\bin\\sh.exe" }
  18393. , createJuntionOrLink : (dirOrFile, target, opts) =>{
  18394. return nodeShellExec$2('mklink', ['/J', dirOrFile, target], opts).catch((e) => { console.error(e); })
  18395. }
  18396. , removeJuncionOrLink : ( junctionOrLink )=>{
  18397. return nodeShellExec$2('rmdir', [junctionOrLink], { inherit: true, shell: true, env: process.env })
  18398. }
  18399. , requestElevation(elevatedRunner, taskToRun) {
  18400. // PB : TODO -- Multiple parallel request elevations should be queued into a promise.
  18401. var processedArgs = taskToRun.processedArgs, selectedinstance = taskToRun.selectedinstance , statuslog = taskToRun.statuslog;
  18402. // Wait for the runas to complete before we read it.
  18403. try {
  18404. fs__default["default"].unlinkSync('run.done');
  18405. fs__default["default"].unlinkSync('run.log');
  18406. }
  18407. catch (e) { } //Ignore
  18408. // Find node path to send to hta.
  18409. return nodeShellExec$2('where', ['node']).then(r => {
  18410. var namedArgs = [];
  18411. console.log('result : ' + JSON.stringify(r));
  18412. Object.keys(processedArgs).forEach((v) => { v != '_' ? namedArgs.push('--' + v + '=' + processedArgs[v]) : null; });
  18413. // PB : TODO -- Convert all the cli args back to string.
  18414. var args = [`${selectedinstance.root}/.elxr/run-${taskToRun.runtimestamp}/windowselevate.hta`].concat(processedArgs._);
  18415. namedArgs.length > 0 ? args = args.concat(namedArgs.join(' ')) : null;
  18416. args.push('--runas=self');
  18417. // args.push('--nodepath=' + r.messages[r.messages.length - 1])
  18418. // if (!processedArgs.node_env) args.push('--node_env=' + ENV.NODE_ENV)
  18419. // if (processedArgs.debug) args.push('--debug=true') // Enable to debug elevated..
  18420. // console.dir(processedArgs._)
  18421. // console.dir(namedArgs.join(' '))
  18422. console.dir(args);
  18423. // throw 'test'
  18424. return nodeShellExec$2('MSHTA', [`"${args.join('" "')}"`]
  18425. , {
  18426. inherit: true
  18427. , shell: true
  18428. , env: taskToRun.ENV
  18429. , runas: 'self'
  18430. , title: `runas`
  18431. }
  18432. ).then(() => {
  18433. // runas returned.
  18434. try {
  18435. // PB : TODO -- Log is comma prefixed. Needs to be proper JSON.
  18436. var runaslog = JSON.parse('[ { "success" : true, "result" : "started"}' + fs__default["default"].readFileSync('run.log', { flags: 'a+' }) + ']');
  18437. runaslog.forEach((logEntry) => {
  18438. statuslog.statuslog(logEntry.success ? null : logEntry, logEntry);
  18439. logEntry.success ? (console.log(['success :' + logEntry.result]), console.log((logEntry.messages || []).join(' '))) : (console.error(['error :' + logEntry.result]), console.error((logEntry.messages || []).join(' ')));
  18440. });
  18441. }
  18442. catch (e) {
  18443. // We must have a runas log
  18444. statuslog.statuslog(e);
  18445. console.error('Run log error probably was not created by runas : ' + e);
  18446. }
  18447. })
  18448. .catch(err => console.error('Elevation failed : ' + err));
  18449. })
  18450. }
  18451. };
  18452. var win_verse$1 = shell_verse$2;
  18453. const { any: any$1 } = bbhverse;
  18454. var nodeShellExec$1 = cliverse.nodeShellExec;
  18455. // PB : TODO -- linux prerequistes.
  18456. // export GIT_SSL_NO_VERIFY=true
  18457. // npm i -g nodemon
  18458. // phantomjs": "^2.1.7
  18459. // "sass": "^1.32.7",
  18460. // "node-sass": "^5.0.0",
  18461. // "ember-cli-sass": "^10.0.1",
  18462. // "gulp-sass": "^4.1.0",
  18463. // ember-searchable-select
  18464. // ember-cli-sass
  18465. // ember-cp-validatations
  18466. // ember-cli-yuidoc
  18467. // yuidoc-ember-theme
  18468. // chess-server-lib/server
  18469. // java
  18470. // client
  18471. // export NODE_OPTIONS=--openssl-legacy-provider
  18472. // elixir-client npmi
  18473. // elixir-client/chess-client-lib npmi
  18474. // crossfilter2
  18475. var __isElevated = null;
  18476. var shell_verse$1 = {
  18477. // getCommonTask is agnostic of whether we are running in an elevated shell or not. It runs in either case.
  18478. getCommonTask( taskToRun ){ return ()=>{ return shell_verse$1.runTask(taskToRun) }}
  18479. , runTask : ( taskToRun ) => {
  18480. if (__isElevated) return shell_verse$1.runElevated( taskToRun )
  18481. else return shell_verse$1.runNonElevated( taskToRun )
  18482. }
  18483. , elevatedRunner( taskToRun ){
  18484. // PB : TODO -- Should be called only when we are in an elevated shell that was already requested from an unelevated shell with a batch of tasks.
  18485. try {
  18486. // PB : We do not need IPC in linux. Until a real sudo elevation is required eveything works in non elevated mode...
  18487. var __runasresult = null;
  18488. return taskToRun().then((r)=>{
  18489. // PB : TODO -- Every elevation should have its own messaging file. Async writes from multiple processes are a problem here...
  18490. // fs.writeFileSync('run.log', ', ' + JSON.stringify( { info : taskToRun.info, success: true }), { 'flag': 'a+' })
  18491. // fs.writeFileSync('run.done', 'success') // PB : TODO -- This should be done conditionally if we are running inproc.
  18492. return __runasresult = r;
  18493. })
  18494. .catch((e) => {
  18495. // fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' })
  18496. // fs.writeFileSync('run.done', 'failure')
  18497. console.error(e);
  18498. })
  18499. .finally(() => {
  18500. // if(__runasresult && !__runasresult.skipped) fs.unlinkSync('run.done')
  18501. })
  18502. }
  18503. catch (e) {
  18504. console.error('Error Invalid command : ' + e);
  18505. // fs.writeFileSync('run.done', 'error')
  18506. }
  18507. finally {
  18508. }
  18509. }
  18510. , getElevatedTask : function( taskToRun ){ return ()=>{ return shell_verse$1.runElevated(taskToRun) }}
  18511. , getElevatedTaskInBatch : function( taskToRun ){ return ()=>{ return shell_verse$1.runElevatedInBatch(taskToRun) }}
  18512. , runElevatedInBatch : ( taskToRun ) => {
  18513. if (__isElevated) return shell_verse$1.elevatedRunner(taskToRun, true)
  18514. else return shell_verse$1.requestElevation(shell_verse$1.elevatedRunner, taskToRun)
  18515. }
  18516. , runElevated : ( taskToRun ) => {
  18517. // Let shell_verse decide whether to Elevate Out of Proc or In Proc
  18518. // taskToRun by default is the launched command and args. Specially in windows out of proc.
  18519. // taskToRun = taskToRun || (()=>{ return op[processedArgs.label || processedArgs._[0] || 'undefined'](processedArgs) })
  18520. if(taskToRun.processedArgs.skipelevated) return Promise.resolve({ skipped : true });
  18521. if(__isElevated) {
  18522. return shell_verse$1.elevatedRunner(taskToRun)
  18523. }
  18524. else {
  18525. console.log('Requesting Elevated Privileges');
  18526. // requesteElevation is acutally request elevation and run. Both In Proc and Out of Proc.
  18527. // Linux doesnt require elevation for most commands...
  18528. return shell_verse$1.requestElevation(shell_verse$1.elevatedRunner, taskToRun)
  18529. }
  18530. }
  18531. , runElevatedBatch( batchToRun ){
  18532. // In windows we don't need to run each task. We hand over to another shell which in elevated state rebuilds the whole batch and runs.
  18533. // Irrespective of the batch we just call runElevated once.
  18534. return any$1(batchToRun.map(shell_verse$1.runElevated))
  18535. }
  18536. , getNonElevatedTask : function( taskToRun ){ return ()=>{ return shell_verse$1.runNonElevated(taskToRun) } }
  18537. , runNonElevated : ( taskToRun ) => {
  18538. // Let shell_verse decide whether to Elevate Out of Proc or In Proc
  18539. if(__isElevated) {
  18540. return Promise.resolve( 'Skipping regular task in elevated shell.' ) // Regular tasks unless marked as common tasks should not run in elevated shell...
  18541. }
  18542. else {
  18543. // taskToRun by default is the launched command and args.
  18544. // taskToRun = taskToRun || (()=>{ return op[processedArgs.label || processedArgs._[0] || 'undefined'](processedArgs) })
  18545. return taskToRun().then(r=>{
  18546. taskToRun.statuslog.statuslog(null, taskToRun.info /*repo*/ );
  18547. return r;
  18548. }).catch((e) => {
  18549. e.info = taskToRun.info;
  18550. if(taskToRun.errHandler) throw taskToRun.errHandler(e)
  18551. taskToRun.statuslog.statuslog(e);
  18552. // console.error(e)
  18553. throw e;
  18554. }).finally(()=>{})
  18555. }
  18556. }
  18557. , isElevated : ()=>{
  18558. return acquireElevationState().then( ()=>{
  18559. shell_verse$1.isElevated = () => {
  18560. return Promise.resolve(__isElevated)
  18561. };
  18562. return shell_verse$1.isElevated()
  18563. })
  18564. }
  18565. // , isElevationOutOfProc : ()=>{ return true }
  18566. , acquireElevationState : () => {
  18567. return Promise.resolve(false).then(( elevationstate ) => {
  18568. __isElevated ? console.log('Elevated') : console.log('Not Elevated');
  18569. __isElevated = elevationstate;
  18570. }).catch(() => {
  18571. __isElevated = false;
  18572. console.log('Not Elevated');
  18573. }).finally(()=>{
  18574. shell_verse$1.acquireElevationState = ()=> Promise.resolve(__isElevated);
  18575. shell_verse$1.isElevated = () => { return Promise.resolve(__isElevated)};
  18576. return __isElevated;
  18577. })
  18578. }
  18579. , getTaskCheckExists : cliverse.createTask('getTaskCheckExists', 'which')
  18580. , getbash : ()=>{ return "sh" }
  18581. , createJuntionOrLink : (dirOrFile, target, opts)=>{
  18582. return nodeShellExec$1('ln', ['-s', target, dirOrFile], opts).catch((e) => { console.error(e); })
  18583. }
  18584. , removeJuncionOrLink : ( junctionOrLink )=>{
  18585. return nodeShellExec$1('rm', [junctionOrLink], { inherit: true, shell: true, env: process.env })
  18586. }
  18587. , requestElevation(elevatedRunner, taskToRun) {
  18588. // PB : TODO -- Most linking cmds in linux may not need elevation like in windows.
  18589. // However returning true here is pseudo and will break cases where real elevation is required in linux. We need to refactor to reimplement
  18590. // this with sudo and change all calles to use ony where required.
  18591. return elevatedRunner(taskToRun);
  18592. }
  18593. };
  18594. var lin_verse$1 = shell_verse$1;
  18595. var colorName = {
  18596. "aliceblue": [240, 248, 255],
  18597. "antiquewhite": [250, 235, 215],
  18598. "aqua": [0, 255, 255],
  18599. "aquamarine": [127, 255, 212],
  18600. "azure": [240, 255, 255],
  18601. "beige": [245, 245, 220],
  18602. "bisque": [255, 228, 196],
  18603. "black": [0, 0, 0],
  18604. "blanchedalmond": [255, 235, 205],
  18605. "blue": [0, 0, 255],
  18606. "blueviolet": [138, 43, 226],
  18607. "brown": [165, 42, 42],
  18608. "burlywood": [222, 184, 135],
  18609. "cadetblue": [95, 158, 160],
  18610. "chartreuse": [127, 255, 0],
  18611. "chocolate": [210, 105, 30],
  18612. "coral": [255, 127, 80],
  18613. "cornflowerblue": [100, 149, 237],
  18614. "cornsilk": [255, 248, 220],
  18615. "crimson": [220, 20, 60],
  18616. "cyan": [0, 255, 255],
  18617. "darkblue": [0, 0, 139],
  18618. "darkcyan": [0, 139, 139],
  18619. "darkgoldenrod": [184, 134, 11],
  18620. "darkgray": [169, 169, 169],
  18621. "darkgreen": [0, 100, 0],
  18622. "darkgrey": [169, 169, 169],
  18623. "darkkhaki": [189, 183, 107],
  18624. "darkmagenta": [139, 0, 139],
  18625. "darkolivegreen": [85, 107, 47],
  18626. "darkorange": [255, 140, 0],
  18627. "darkorchid": [153, 50, 204],
  18628. "darkred": [139, 0, 0],
  18629. "darksalmon": [233, 150, 122],
  18630. "darkseagreen": [143, 188, 143],
  18631. "darkslateblue": [72, 61, 139],
  18632. "darkslategray": [47, 79, 79],
  18633. "darkslategrey": [47, 79, 79],
  18634. "darkturquoise": [0, 206, 209],
  18635. "darkviolet": [148, 0, 211],
  18636. "deeppink": [255, 20, 147],
  18637. "deepskyblue": [0, 191, 255],
  18638. "dimgray": [105, 105, 105],
  18639. "dimgrey": [105, 105, 105],
  18640. "dodgerblue": [30, 144, 255],
  18641. "firebrick": [178, 34, 34],
  18642. "floralwhite": [255, 250, 240],
  18643. "forestgreen": [34, 139, 34],
  18644. "fuchsia": [255, 0, 255],
  18645. "gainsboro": [220, 220, 220],
  18646. "ghostwhite": [248, 248, 255],
  18647. "gold": [255, 215, 0],
  18648. "goldenrod": [218, 165, 32],
  18649. "gray": [128, 128, 128],
  18650. "green": [0, 128, 0],
  18651. "greenyellow": [173, 255, 47],
  18652. "grey": [128, 128, 128],
  18653. "honeydew": [240, 255, 240],
  18654. "hotpink": [255, 105, 180],
  18655. "indianred": [205, 92, 92],
  18656. "indigo": [75, 0, 130],
  18657. "ivory": [255, 255, 240],
  18658. "khaki": [240, 230, 140],
  18659. "lavender": [230, 230, 250],
  18660. "lavenderblush": [255, 240, 245],
  18661. "lawngreen": [124, 252, 0],
  18662. "lemonchiffon": [255, 250, 205],
  18663. "lightblue": [173, 216, 230],
  18664. "lightcoral": [240, 128, 128],
  18665. "lightcyan": [224, 255, 255],
  18666. "lightgoldenrodyellow": [250, 250, 210],
  18667. "lightgray": [211, 211, 211],
  18668. "lightgreen": [144, 238, 144],
  18669. "lightgrey": [211, 211, 211],
  18670. "lightpink": [255, 182, 193],
  18671. "lightsalmon": [255, 160, 122],
  18672. "lightseagreen": [32, 178, 170],
  18673. "lightskyblue": [135, 206, 250],
  18674. "lightslategray": [119, 136, 153],
  18675. "lightslategrey": [119, 136, 153],
  18676. "lightsteelblue": [176, 196, 222],
  18677. "lightyellow": [255, 255, 224],
  18678. "lime": [0, 255, 0],
  18679. "limegreen": [50, 205, 50],
  18680. "linen": [250, 240, 230],
  18681. "magenta": [255, 0, 255],
  18682. "maroon": [128, 0, 0],
  18683. "mediumaquamarine": [102, 205, 170],
  18684. "mediumblue": [0, 0, 205],
  18685. "mediumorchid": [186, 85, 211],
  18686. "mediumpurple": [147, 112, 219],
  18687. "mediumseagreen": [60, 179, 113],
  18688. "mediumslateblue": [123, 104, 238],
  18689. "mediumspringgreen": [0, 250, 154],
  18690. "mediumturquoise": [72, 209, 204],
  18691. "mediumvioletred": [199, 21, 133],
  18692. "midnightblue": [25, 25, 112],
  18693. "mintcream": [245, 255, 250],
  18694. "mistyrose": [255, 228, 225],
  18695. "moccasin": [255, 228, 181],
  18696. "navajowhite": [255, 222, 173],
  18697. "navy": [0, 0, 128],
  18698. "oldlace": [253, 245, 230],
  18699. "olive": [128, 128, 0],
  18700. "olivedrab": [107, 142, 35],
  18701. "orange": [255, 165, 0],
  18702. "orangered": [255, 69, 0],
  18703. "orchid": [218, 112, 214],
  18704. "palegoldenrod": [238, 232, 170],
  18705. "palegreen": [152, 251, 152],
  18706. "paleturquoise": [175, 238, 238],
  18707. "palevioletred": [219, 112, 147],
  18708. "papayawhip": [255, 239, 213],
  18709. "peachpuff": [255, 218, 185],
  18710. "peru": [205, 133, 63],
  18711. "pink": [255, 192, 203],
  18712. "plum": [221, 160, 221],
  18713. "powderblue": [176, 224, 230],
  18714. "purple": [128, 0, 128],
  18715. "rebeccapurple": [102, 51, 153],
  18716. "red": [255, 0, 0],
  18717. "rosybrown": [188, 143, 143],
  18718. "royalblue": [65, 105, 225],
  18719. "saddlebrown": [139, 69, 19],
  18720. "salmon": [250, 128, 114],
  18721. "sandybrown": [244, 164, 96],
  18722. "seagreen": [46, 139, 87],
  18723. "seashell": [255, 245, 238],
  18724. "sienna": [160, 82, 45],
  18725. "silver": [192, 192, 192],
  18726. "skyblue": [135, 206, 235],
  18727. "slateblue": [106, 90, 205],
  18728. "slategray": [112, 128, 144],
  18729. "slategrey": [112, 128, 144],
  18730. "snow": [255, 250, 250],
  18731. "springgreen": [0, 255, 127],
  18732. "steelblue": [70, 130, 180],
  18733. "tan": [210, 180, 140],
  18734. "teal": [0, 128, 128],
  18735. "thistle": [216, 191, 216],
  18736. "tomato": [255, 99, 71],
  18737. "turquoise": [64, 224, 208],
  18738. "violet": [238, 130, 238],
  18739. "wheat": [245, 222, 179],
  18740. "white": [255, 255, 255],
  18741. "whitesmoke": [245, 245, 245],
  18742. "yellow": [255, 255, 0],
  18743. "yellowgreen": [154, 205, 50]
  18744. };
  18745. /* MIT license */
  18746. /* eslint-disable no-mixed-operators */
  18747. // NOTE: conversions should only return primitive values (i.e. arrays, or
  18748. // values that give correct `typeof` results).
  18749. // do not use box values types (i.e. Number(), String(), etc.)
  18750. const reverseKeywords = {};
  18751. for (const key of Object.keys(colorName)) {
  18752. reverseKeywords[colorName[key]] = key;
  18753. }
  18754. const convert$1 = {
  18755. rgb: {channels: 3, labels: 'rgb'},
  18756. hsl: {channels: 3, labels: 'hsl'},
  18757. hsv: {channels: 3, labels: 'hsv'},
  18758. hwb: {channels: 3, labels: 'hwb'},
  18759. cmyk: {channels: 4, labels: 'cmyk'},
  18760. xyz: {channels: 3, labels: 'xyz'},
  18761. lab: {channels: 3, labels: 'lab'},
  18762. lch: {channels: 3, labels: 'lch'},
  18763. hex: {channels: 1, labels: ['hex']},
  18764. keyword: {channels: 1, labels: ['keyword']},
  18765. ansi16: {channels: 1, labels: ['ansi16']},
  18766. ansi256: {channels: 1, labels: ['ansi256']},
  18767. hcg: {channels: 3, labels: ['h', 'c', 'g']},
  18768. apple: {channels: 3, labels: ['r16', 'g16', 'b16']},
  18769. gray: {channels: 1, labels: ['gray']}
  18770. };
  18771. var conversions = convert$1;
  18772. // Hide .channels and .labels properties
  18773. for (const model of Object.keys(convert$1)) {
  18774. if (!('channels' in convert$1[model])) {
  18775. throw new Error('missing channels property: ' + model);
  18776. }
  18777. if (!('labels' in convert$1[model])) {
  18778. throw new Error('missing channel labels property: ' + model);
  18779. }
  18780. if (convert$1[model].labels.length !== convert$1[model].channels) {
  18781. throw new Error('channel and label counts mismatch: ' + model);
  18782. }
  18783. const {channels, labels} = convert$1[model];
  18784. delete convert$1[model].channels;
  18785. delete convert$1[model].labels;
  18786. Object.defineProperty(convert$1[model], 'channels', {value: channels});
  18787. Object.defineProperty(convert$1[model], 'labels', {value: labels});
  18788. }
  18789. convert$1.rgb.hsl = function (rgb) {
  18790. const r = rgb[0] / 255;
  18791. const g = rgb[1] / 255;
  18792. const b = rgb[2] / 255;
  18793. const min = Math.min(r, g, b);
  18794. const max = Math.max(r, g, b);
  18795. const delta = max - min;
  18796. let h;
  18797. let s;
  18798. if (max === min) {
  18799. h = 0;
  18800. } else if (r === max) {
  18801. h = (g - b) / delta;
  18802. } else if (g === max) {
  18803. h = 2 + (b - r) / delta;
  18804. } else if (b === max) {
  18805. h = 4 + (r - g) / delta;
  18806. }
  18807. h = Math.min(h * 60, 360);
  18808. if (h < 0) {
  18809. h += 360;
  18810. }
  18811. const l = (min + max) / 2;
  18812. if (max === min) {
  18813. s = 0;
  18814. } else if (l <= 0.5) {
  18815. s = delta / (max + min);
  18816. } else {
  18817. s = delta / (2 - max - min);
  18818. }
  18819. return [h, s * 100, l * 100];
  18820. };
  18821. convert$1.rgb.hsv = function (rgb) {
  18822. let rdif;
  18823. let gdif;
  18824. let bdif;
  18825. let h;
  18826. let s;
  18827. const r = rgb[0] / 255;
  18828. const g = rgb[1] / 255;
  18829. const b = rgb[2] / 255;
  18830. const v = Math.max(r, g, b);
  18831. const diff = v - Math.min(r, g, b);
  18832. const diffc = function (c) {
  18833. return (v - c) / 6 / diff + 1 / 2;
  18834. };
  18835. if (diff === 0) {
  18836. h = 0;
  18837. s = 0;
  18838. } else {
  18839. s = diff / v;
  18840. rdif = diffc(r);
  18841. gdif = diffc(g);
  18842. bdif = diffc(b);
  18843. if (r === v) {
  18844. h = bdif - gdif;
  18845. } else if (g === v) {
  18846. h = (1 / 3) + rdif - bdif;
  18847. } else if (b === v) {
  18848. h = (2 / 3) + gdif - rdif;
  18849. }
  18850. if (h < 0) {
  18851. h += 1;
  18852. } else if (h > 1) {
  18853. h -= 1;
  18854. }
  18855. }
  18856. return [
  18857. h * 360,
  18858. s * 100,
  18859. v * 100
  18860. ];
  18861. };
  18862. convert$1.rgb.hwb = function (rgb) {
  18863. const r = rgb[0];
  18864. const g = rgb[1];
  18865. let b = rgb[2];
  18866. const h = convert$1.rgb.hsl(rgb)[0];
  18867. const w = 1 / 255 * Math.min(r, Math.min(g, b));
  18868. b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
  18869. return [h, w * 100, b * 100];
  18870. };
  18871. convert$1.rgb.cmyk = function (rgb) {
  18872. const r = rgb[0] / 255;
  18873. const g = rgb[1] / 255;
  18874. const b = rgb[2] / 255;
  18875. const k = Math.min(1 - r, 1 - g, 1 - b);
  18876. const c = (1 - r - k) / (1 - k) || 0;
  18877. const m = (1 - g - k) / (1 - k) || 0;
  18878. const y = (1 - b - k) / (1 - k) || 0;
  18879. return [c * 100, m * 100, y * 100, k * 100];
  18880. };
  18881. function comparativeDistance(x, y) {
  18882. /*
  18883. See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
  18884. */
  18885. return (
  18886. ((x[0] - y[0]) ** 2) +
  18887. ((x[1] - y[1]) ** 2) +
  18888. ((x[2] - y[2]) ** 2)
  18889. );
  18890. }
  18891. convert$1.rgb.keyword = function (rgb) {
  18892. const reversed = reverseKeywords[rgb];
  18893. if (reversed) {
  18894. return reversed;
  18895. }
  18896. let currentClosestDistance = Infinity;
  18897. let currentClosestKeyword;
  18898. for (const keyword of Object.keys(colorName)) {
  18899. const value = colorName[keyword];
  18900. // Compute comparative distance
  18901. const distance = comparativeDistance(rgb, value);
  18902. // Check if its less, if so set as closest
  18903. if (distance < currentClosestDistance) {
  18904. currentClosestDistance = distance;
  18905. currentClosestKeyword = keyword;
  18906. }
  18907. }
  18908. return currentClosestKeyword;
  18909. };
  18910. convert$1.keyword.rgb = function (keyword) {
  18911. return colorName[keyword];
  18912. };
  18913. convert$1.rgb.xyz = function (rgb) {
  18914. let r = rgb[0] / 255;
  18915. let g = rgb[1] / 255;
  18916. let b = rgb[2] / 255;
  18917. // Assume sRGB
  18918. r = r > 0.04045 ? (((r + 0.055) / 1.055) ** 2.4) : (r / 12.92);
  18919. g = g > 0.04045 ? (((g + 0.055) / 1.055) ** 2.4) : (g / 12.92);
  18920. b = b > 0.04045 ? (((b + 0.055) / 1.055) ** 2.4) : (b / 12.92);
  18921. const x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805);
  18922. const y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722);
  18923. const z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505);
  18924. return [x * 100, y * 100, z * 100];
  18925. };
  18926. convert$1.rgb.lab = function (rgb) {
  18927. const xyz = convert$1.rgb.xyz(rgb);
  18928. let x = xyz[0];
  18929. let y = xyz[1];
  18930. let z = xyz[2];
  18931. x /= 95.047;
  18932. y /= 100;
  18933. z /= 108.883;
  18934. x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116);
  18935. y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116);
  18936. z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116);
  18937. const l = (116 * y) - 16;
  18938. const a = 500 * (x - y);
  18939. const b = 200 * (y - z);
  18940. return [l, a, b];
  18941. };
  18942. convert$1.hsl.rgb = function (hsl) {
  18943. const h = hsl[0] / 360;
  18944. const s = hsl[1] / 100;
  18945. const l = hsl[2] / 100;
  18946. let t2;
  18947. let t3;
  18948. let val;
  18949. if (s === 0) {
  18950. val = l * 255;
  18951. return [val, val, val];
  18952. }
  18953. if (l < 0.5) {
  18954. t2 = l * (1 + s);
  18955. } else {
  18956. t2 = l + s - l * s;
  18957. }
  18958. const t1 = 2 * l - t2;
  18959. const rgb = [0, 0, 0];
  18960. for (let i = 0; i < 3; i++) {
  18961. t3 = h + 1 / 3 * -(i - 1);
  18962. if (t3 < 0) {
  18963. t3++;
  18964. }
  18965. if (t3 > 1) {
  18966. t3--;
  18967. }
  18968. if (6 * t3 < 1) {
  18969. val = t1 + (t2 - t1) * 6 * t3;
  18970. } else if (2 * t3 < 1) {
  18971. val = t2;
  18972. } else if (3 * t3 < 2) {
  18973. val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
  18974. } else {
  18975. val = t1;
  18976. }
  18977. rgb[i] = val * 255;
  18978. }
  18979. return rgb;
  18980. };
  18981. convert$1.hsl.hsv = function (hsl) {
  18982. const h = hsl[0];
  18983. let s = hsl[1] / 100;
  18984. let l = hsl[2] / 100;
  18985. let smin = s;
  18986. const lmin = Math.max(l, 0.01);
  18987. l *= 2;
  18988. s *= (l <= 1) ? l : 2 - l;
  18989. smin *= lmin <= 1 ? lmin : 2 - lmin;
  18990. const v = (l + s) / 2;
  18991. const sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s);
  18992. return [h, sv * 100, v * 100];
  18993. };
  18994. convert$1.hsv.rgb = function (hsv) {
  18995. const h = hsv[0] / 60;
  18996. const s = hsv[1] / 100;
  18997. let v = hsv[2] / 100;
  18998. const hi = Math.floor(h) % 6;
  18999. const f = h - Math.floor(h);
  19000. const p = 255 * v * (1 - s);
  19001. const q = 255 * v * (1 - (s * f));
  19002. const t = 255 * v * (1 - (s * (1 - f)));
  19003. v *= 255;
  19004. switch (hi) {
  19005. case 0:
  19006. return [v, t, p];
  19007. case 1:
  19008. return [q, v, p];
  19009. case 2:
  19010. return [p, v, t];
  19011. case 3:
  19012. return [p, q, v];
  19013. case 4:
  19014. return [t, p, v];
  19015. case 5:
  19016. return [v, p, q];
  19017. }
  19018. };
  19019. convert$1.hsv.hsl = function (hsv) {
  19020. const h = hsv[0];
  19021. const s = hsv[1] / 100;
  19022. const v = hsv[2] / 100;
  19023. const vmin = Math.max(v, 0.01);
  19024. let sl;
  19025. let l;
  19026. l = (2 - s) * v;
  19027. const lmin = (2 - s) * vmin;
  19028. sl = s * vmin;
  19029. sl /= (lmin <= 1) ? lmin : 2 - lmin;
  19030. sl = sl || 0;
  19031. l /= 2;
  19032. return [h, sl * 100, l * 100];
  19033. };
  19034. // http://dev.w3.org/csswg/css-color/#hwb-to-rgb
  19035. convert$1.hwb.rgb = function (hwb) {
  19036. const h = hwb[0] / 360;
  19037. let wh = hwb[1] / 100;
  19038. let bl = hwb[2] / 100;
  19039. const ratio = wh + bl;
  19040. let f;
  19041. // Wh + bl cant be > 1
  19042. if (ratio > 1) {
  19043. wh /= ratio;
  19044. bl /= ratio;
  19045. }
  19046. const i = Math.floor(6 * h);
  19047. const v = 1 - bl;
  19048. f = 6 * h - i;
  19049. if ((i & 0x01) !== 0) {
  19050. f = 1 - f;
  19051. }
  19052. const n = wh + f * (v - wh); // Linear interpolation
  19053. let r;
  19054. let g;
  19055. let b;
  19056. /* eslint-disable max-statements-per-line,no-multi-spaces */
  19057. switch (i) {
  19058. default:
  19059. case 6:
  19060. case 0: r = v; g = n; b = wh; break;
  19061. case 1: r = n; g = v; b = wh; break;
  19062. case 2: r = wh; g = v; b = n; break;
  19063. case 3: r = wh; g = n; b = v; break;
  19064. case 4: r = n; g = wh; b = v; break;
  19065. case 5: r = v; g = wh; b = n; break;
  19066. }
  19067. /* eslint-enable max-statements-per-line,no-multi-spaces */
  19068. return [r * 255, g * 255, b * 255];
  19069. };
  19070. convert$1.cmyk.rgb = function (cmyk) {
  19071. const c = cmyk[0] / 100;
  19072. const m = cmyk[1] / 100;
  19073. const y = cmyk[2] / 100;
  19074. const k = cmyk[3] / 100;
  19075. const r = 1 - Math.min(1, c * (1 - k) + k);
  19076. const g = 1 - Math.min(1, m * (1 - k) + k);
  19077. const b = 1 - Math.min(1, y * (1 - k) + k);
  19078. return [r * 255, g * 255, b * 255];
  19079. };
  19080. convert$1.xyz.rgb = function (xyz) {
  19081. const x = xyz[0] / 100;
  19082. const y = xyz[1] / 100;
  19083. const z = xyz[2] / 100;
  19084. let r;
  19085. let g;
  19086. let b;
  19087. r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);
  19088. g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);
  19089. b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570);
  19090. // Assume sRGB
  19091. r = r > 0.0031308
  19092. ? ((1.055 * (r ** (1.0 / 2.4))) - 0.055)
  19093. : r * 12.92;
  19094. g = g > 0.0031308
  19095. ? ((1.055 * (g ** (1.0 / 2.4))) - 0.055)
  19096. : g * 12.92;
  19097. b = b > 0.0031308
  19098. ? ((1.055 * (b ** (1.0 / 2.4))) - 0.055)
  19099. : b * 12.92;
  19100. r = Math.min(Math.max(0, r), 1);
  19101. g = Math.min(Math.max(0, g), 1);
  19102. b = Math.min(Math.max(0, b), 1);
  19103. return [r * 255, g * 255, b * 255];
  19104. };
  19105. convert$1.xyz.lab = function (xyz) {
  19106. let x = xyz[0];
  19107. let y = xyz[1];
  19108. let z = xyz[2];
  19109. x /= 95.047;
  19110. y /= 100;
  19111. z /= 108.883;
  19112. x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116);
  19113. y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116);
  19114. z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116);
  19115. const l = (116 * y) - 16;
  19116. const a = 500 * (x - y);
  19117. const b = 200 * (y - z);
  19118. return [l, a, b];
  19119. };
  19120. convert$1.lab.xyz = function (lab) {
  19121. const l = lab[0];
  19122. const a = lab[1];
  19123. const b = lab[2];
  19124. let x;
  19125. let y;
  19126. let z;
  19127. y = (l + 16) / 116;
  19128. x = a / 500 + y;
  19129. z = y - b / 200;
  19130. const y2 = y ** 3;
  19131. const x2 = x ** 3;
  19132. const z2 = z ** 3;
  19133. y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
  19134. x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
  19135. z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
  19136. x *= 95.047;
  19137. y *= 100;
  19138. z *= 108.883;
  19139. return [x, y, z];
  19140. };
  19141. convert$1.lab.lch = function (lab) {
  19142. const l = lab[0];
  19143. const a = lab[1];
  19144. const b = lab[2];
  19145. let h;
  19146. const hr = Math.atan2(b, a);
  19147. h = hr * 360 / 2 / Math.PI;
  19148. if (h < 0) {
  19149. h += 360;
  19150. }
  19151. const c = Math.sqrt(a * a + b * b);
  19152. return [l, c, h];
  19153. };
  19154. convert$1.lch.lab = function (lch) {
  19155. const l = lch[0];
  19156. const c = lch[1];
  19157. const h = lch[2];
  19158. const hr = h / 360 * 2 * Math.PI;
  19159. const a = c * Math.cos(hr);
  19160. const b = c * Math.sin(hr);
  19161. return [l, a, b];
  19162. };
  19163. convert$1.rgb.ansi16 = function (args, saturation = null) {
  19164. const [r, g, b] = args;
  19165. let value = saturation === null ? convert$1.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization
  19166. value = Math.round(value / 50);
  19167. if (value === 0) {
  19168. return 30;
  19169. }
  19170. let ansi = 30
  19171. + ((Math.round(b / 255) << 2)
  19172. | (Math.round(g / 255) << 1)
  19173. | Math.round(r / 255));
  19174. if (value === 2) {
  19175. ansi += 60;
  19176. }
  19177. return ansi;
  19178. };
  19179. convert$1.hsv.ansi16 = function (args) {
  19180. // Optimization here; we already know the value and don't need to get
  19181. // it converted for us.
  19182. return convert$1.rgb.ansi16(convert$1.hsv.rgb(args), args[2]);
  19183. };
  19184. convert$1.rgb.ansi256 = function (args) {
  19185. const r = args[0];
  19186. const g = args[1];
  19187. const b = args[2];
  19188. // We use the extended greyscale palette here, with the exception of
  19189. // black and white. normal palette only has 4 greyscale shades.
  19190. if (r === g && g === b) {
  19191. if (r < 8) {
  19192. return 16;
  19193. }
  19194. if (r > 248) {
  19195. return 231;
  19196. }
  19197. return Math.round(((r - 8) / 247) * 24) + 232;
  19198. }
  19199. const ansi = 16
  19200. + (36 * Math.round(r / 255 * 5))
  19201. + (6 * Math.round(g / 255 * 5))
  19202. + Math.round(b / 255 * 5);
  19203. return ansi;
  19204. };
  19205. convert$1.ansi16.rgb = function (args) {
  19206. let color = args % 10;
  19207. // Handle greyscale
  19208. if (color === 0 || color === 7) {
  19209. if (args > 50) {
  19210. color += 3.5;
  19211. }
  19212. color = color / 10.5 * 255;
  19213. return [color, color, color];
  19214. }
  19215. const mult = (~~(args > 50) + 1) * 0.5;
  19216. const r = ((color & 1) * mult) * 255;
  19217. const g = (((color >> 1) & 1) * mult) * 255;
  19218. const b = (((color >> 2) & 1) * mult) * 255;
  19219. return [r, g, b];
  19220. };
  19221. convert$1.ansi256.rgb = function (args) {
  19222. // Handle greyscale
  19223. if (args >= 232) {
  19224. const c = (args - 232) * 10 + 8;
  19225. return [c, c, c];
  19226. }
  19227. args -= 16;
  19228. let rem;
  19229. const r = Math.floor(args / 36) / 5 * 255;
  19230. const g = Math.floor((rem = args % 36) / 6) / 5 * 255;
  19231. const b = (rem % 6) / 5 * 255;
  19232. return [r, g, b];
  19233. };
  19234. convert$1.rgb.hex = function (args) {
  19235. const integer = ((Math.round(args[0]) & 0xFF) << 16)
  19236. + ((Math.round(args[1]) & 0xFF) << 8)
  19237. + (Math.round(args[2]) & 0xFF);
  19238. const string = integer.toString(16).toUpperCase();
  19239. return '000000'.substring(string.length) + string;
  19240. };
  19241. convert$1.hex.rgb = function (args) {
  19242. const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
  19243. if (!match) {
  19244. return [0, 0, 0];
  19245. }
  19246. let colorString = match[0];
  19247. if (match[0].length === 3) {
  19248. colorString = colorString.split('').map(char => {
  19249. return char + char;
  19250. }).join('');
  19251. }
  19252. const integer = parseInt(colorString, 16);
  19253. const r = (integer >> 16) & 0xFF;
  19254. const g = (integer >> 8) & 0xFF;
  19255. const b = integer & 0xFF;
  19256. return [r, g, b];
  19257. };
  19258. convert$1.rgb.hcg = function (rgb) {
  19259. const r = rgb[0] / 255;
  19260. const g = rgb[1] / 255;
  19261. const b = rgb[2] / 255;
  19262. const max = Math.max(Math.max(r, g), b);
  19263. const min = Math.min(Math.min(r, g), b);
  19264. const chroma = (max - min);
  19265. let grayscale;
  19266. let hue;
  19267. if (chroma < 1) {
  19268. grayscale = min / (1 - chroma);
  19269. } else {
  19270. grayscale = 0;
  19271. }
  19272. if (chroma <= 0) {
  19273. hue = 0;
  19274. } else
  19275. if (max === r) {
  19276. hue = ((g - b) / chroma) % 6;
  19277. } else
  19278. if (max === g) {
  19279. hue = 2 + (b - r) / chroma;
  19280. } else {
  19281. hue = 4 + (r - g) / chroma;
  19282. }
  19283. hue /= 6;
  19284. hue %= 1;
  19285. return [hue * 360, chroma * 100, grayscale * 100];
  19286. };
  19287. convert$1.hsl.hcg = function (hsl) {
  19288. const s = hsl[1] / 100;
  19289. const l = hsl[2] / 100;
  19290. const c = l < 0.5 ? (2.0 * s * l) : (2.0 * s * (1.0 - l));
  19291. let f = 0;
  19292. if (c < 1.0) {
  19293. f = (l - 0.5 * c) / (1.0 - c);
  19294. }
  19295. return [hsl[0], c * 100, f * 100];
  19296. };
  19297. convert$1.hsv.hcg = function (hsv) {
  19298. const s = hsv[1] / 100;
  19299. const v = hsv[2] / 100;
  19300. const c = s * v;
  19301. let f = 0;
  19302. if (c < 1.0) {
  19303. f = (v - c) / (1 - c);
  19304. }
  19305. return [hsv[0], c * 100, f * 100];
  19306. };
  19307. convert$1.hcg.rgb = function (hcg) {
  19308. const h = hcg[0] / 360;
  19309. const c = hcg[1] / 100;
  19310. const g = hcg[2] / 100;
  19311. if (c === 0.0) {
  19312. return [g * 255, g * 255, g * 255];
  19313. }
  19314. const pure = [0, 0, 0];
  19315. const hi = (h % 1) * 6;
  19316. const v = hi % 1;
  19317. const w = 1 - v;
  19318. let mg = 0;
  19319. /* eslint-disable max-statements-per-line */
  19320. switch (Math.floor(hi)) {
  19321. case 0:
  19322. pure[0] = 1; pure[1] = v; pure[2] = 0; break;
  19323. case 1:
  19324. pure[0] = w; pure[1] = 1; pure[2] = 0; break;
  19325. case 2:
  19326. pure[0] = 0; pure[1] = 1; pure[2] = v; break;
  19327. case 3:
  19328. pure[0] = 0; pure[1] = w; pure[2] = 1; break;
  19329. case 4:
  19330. pure[0] = v; pure[1] = 0; pure[2] = 1; break;
  19331. default:
  19332. pure[0] = 1; pure[1] = 0; pure[2] = w;
  19333. }
  19334. /* eslint-enable max-statements-per-line */
  19335. mg = (1.0 - c) * g;
  19336. return [
  19337. (c * pure[0] + mg) * 255,
  19338. (c * pure[1] + mg) * 255,
  19339. (c * pure[2] + mg) * 255
  19340. ];
  19341. };
  19342. convert$1.hcg.hsv = function (hcg) {
  19343. const c = hcg[1] / 100;
  19344. const g = hcg[2] / 100;
  19345. const v = c + g * (1.0 - c);
  19346. let f = 0;
  19347. if (v > 0.0) {
  19348. f = c / v;
  19349. }
  19350. return [hcg[0], f * 100, v * 100];
  19351. };
  19352. convert$1.hcg.hsl = function (hcg) {
  19353. const c = hcg[1] / 100;
  19354. const g = hcg[2] / 100;
  19355. const l = g * (1.0 - c) + 0.5 * c;
  19356. let s = 0;
  19357. if (l > 0.0 && l < 0.5) {
  19358. s = c / (2 * l);
  19359. } else
  19360. if (l >= 0.5 && l < 1.0) {
  19361. s = c / (2 * (1 - l));
  19362. }
  19363. return [hcg[0], s * 100, l * 100];
  19364. };
  19365. convert$1.hcg.hwb = function (hcg) {
  19366. const c = hcg[1] / 100;
  19367. const g = hcg[2] / 100;
  19368. const v = c + g * (1.0 - c);
  19369. return [hcg[0], (v - c) * 100, (1 - v) * 100];
  19370. };
  19371. convert$1.hwb.hcg = function (hwb) {
  19372. const w = hwb[1] / 100;
  19373. const b = hwb[2] / 100;
  19374. const v = 1 - b;
  19375. const c = v - w;
  19376. let g = 0;
  19377. if (c < 1) {
  19378. g = (v - c) / (1 - c);
  19379. }
  19380. return [hwb[0], c * 100, g * 100];
  19381. };
  19382. convert$1.apple.rgb = function (apple) {
  19383. return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255];
  19384. };
  19385. convert$1.rgb.apple = function (rgb) {
  19386. return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535];
  19387. };
  19388. convert$1.gray.rgb = function (args) {
  19389. return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
  19390. };
  19391. convert$1.gray.hsl = function (args) {
  19392. return [0, 0, args[0]];
  19393. };
  19394. convert$1.gray.hsv = convert$1.gray.hsl;
  19395. convert$1.gray.hwb = function (gray) {
  19396. return [0, 100, gray[0]];
  19397. };
  19398. convert$1.gray.cmyk = function (gray) {
  19399. return [0, 0, 0, gray[0]];
  19400. };
  19401. convert$1.gray.lab = function (gray) {
  19402. return [gray[0], 0, 0];
  19403. };
  19404. convert$1.gray.hex = function (gray) {
  19405. const val = Math.round(gray[0] / 100 * 255) & 0xFF;
  19406. const integer = (val << 16) + (val << 8) + val;
  19407. const string = integer.toString(16).toUpperCase();
  19408. return '000000'.substring(string.length) + string;
  19409. };
  19410. convert$1.rgb.gray = function (rgb) {
  19411. const val = (rgb[0] + rgb[1] + rgb[2]) / 3;
  19412. return [val / 255 * 100];
  19413. };
  19414. /*
  19415. This function routes a model to all other models.
  19416. all functions that are routed have a property `.conversion` attached
  19417. to the returned synthetic function. This property is an array
  19418. of strings, each with the steps in between the 'from' and 'to'
  19419. color models (inclusive).
  19420. conversions that are not possible simply are not included.
  19421. */
  19422. function buildGraph() {
  19423. const graph = {};
  19424. // https://jsperf.com/object-keys-vs-for-in-with-closure/3
  19425. const models = Object.keys(conversions);
  19426. for (let len = models.length, i = 0; i < len; i++) {
  19427. graph[models[i]] = {
  19428. // http://jsperf.com/1-vs-infinity
  19429. // micro-opt, but this is simple.
  19430. distance: -1,
  19431. parent: null
  19432. };
  19433. }
  19434. return graph;
  19435. }
  19436. // https://en.wikipedia.org/wiki/Breadth-first_search
  19437. function deriveBFS(fromModel) {
  19438. const graph = buildGraph();
  19439. const queue = [fromModel]; // Unshift -> queue -> pop
  19440. graph[fromModel].distance = 0;
  19441. while (queue.length) {
  19442. const current = queue.pop();
  19443. const adjacents = Object.keys(conversions[current]);
  19444. for (let len = adjacents.length, i = 0; i < len; i++) {
  19445. const adjacent = adjacents[i];
  19446. const node = graph[adjacent];
  19447. if (node.distance === -1) {
  19448. node.distance = graph[current].distance + 1;
  19449. node.parent = current;
  19450. queue.unshift(adjacent);
  19451. }
  19452. }
  19453. }
  19454. return graph;
  19455. }
  19456. function link(from, to) {
  19457. return function (args) {
  19458. return to(from(args));
  19459. };
  19460. }
  19461. function wrapConversion(toModel, graph) {
  19462. const path = [graph[toModel].parent, toModel];
  19463. let fn = conversions[graph[toModel].parent][toModel];
  19464. let cur = graph[toModel].parent;
  19465. while (graph[cur].parent) {
  19466. path.unshift(graph[cur].parent);
  19467. fn = link(conversions[graph[cur].parent][cur], fn);
  19468. cur = graph[cur].parent;
  19469. }
  19470. fn.conversion = path;
  19471. return fn;
  19472. }
  19473. var route = function (fromModel) {
  19474. const graph = deriveBFS(fromModel);
  19475. const conversion = {};
  19476. const models = Object.keys(graph);
  19477. for (let len = models.length, i = 0; i < len; i++) {
  19478. const toModel = models[i];
  19479. const node = graph[toModel];
  19480. if (node.parent === null) {
  19481. // No possible conversion, or this node is the source model.
  19482. continue;
  19483. }
  19484. conversion[toModel] = wrapConversion(toModel, graph);
  19485. }
  19486. return conversion;
  19487. };
  19488. const convert = {};
  19489. const models = Object.keys(conversions);
  19490. function wrapRaw(fn) {
  19491. const wrappedFn = function (...args) {
  19492. const arg0 = args[0];
  19493. if (arg0 === undefined || arg0 === null) {
  19494. return arg0;
  19495. }
  19496. if (arg0.length > 1) {
  19497. args = arg0;
  19498. }
  19499. return fn(args);
  19500. };
  19501. // Preserve .conversion property if there is one
  19502. if ('conversion' in fn) {
  19503. wrappedFn.conversion = fn.conversion;
  19504. }
  19505. return wrappedFn;
  19506. }
  19507. function wrapRounded(fn) {
  19508. const wrappedFn = function (...args) {
  19509. const arg0 = args[0];
  19510. if (arg0 === undefined || arg0 === null) {
  19511. return arg0;
  19512. }
  19513. if (arg0.length > 1) {
  19514. args = arg0;
  19515. }
  19516. const result = fn(args);
  19517. // We're assuming the result is an array here.
  19518. // see notice in conversions.js; don't use box types
  19519. // in conversion functions.
  19520. if (typeof result === 'object') {
  19521. for (let len = result.length, i = 0; i < len; i++) {
  19522. result[i] = Math.round(result[i]);
  19523. }
  19524. }
  19525. return result;
  19526. };
  19527. // Preserve .conversion property if there is one
  19528. if ('conversion' in fn) {
  19529. wrappedFn.conversion = fn.conversion;
  19530. }
  19531. return wrappedFn;
  19532. }
  19533. models.forEach(fromModel => {
  19534. convert[fromModel] = {};
  19535. Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels});
  19536. Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels});
  19537. const routes = route(fromModel);
  19538. const routeModels = Object.keys(routes);
  19539. routeModels.forEach(toModel => {
  19540. const fn = routes[toModel];
  19541. convert[fromModel][toModel] = wrapRounded(fn);
  19542. convert[fromModel][toModel].raw = wrapRaw(fn);
  19543. });
  19544. });
  19545. var colorConvert = convert;
  19546. var ansiStyles = createCommonjsModule(function (module) {
  19547. const wrapAnsi16 = (fn, offset) => (...args) => {
  19548. const code = fn(...args);
  19549. return `\u001B[${code + offset}m`;
  19550. };
  19551. const wrapAnsi256 = (fn, offset) => (...args) => {
  19552. const code = fn(...args);
  19553. return `\u001B[${38 + offset};5;${code}m`;
  19554. };
  19555. const wrapAnsi16m = (fn, offset) => (...args) => {
  19556. const rgb = fn(...args);
  19557. return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
  19558. };
  19559. const ansi2ansi = n => n;
  19560. const rgb2rgb = (r, g, b) => [r, g, b];
  19561. const setLazyProperty = (object, property, get) => {
  19562. Object.defineProperty(object, property, {
  19563. get: () => {
  19564. const value = get();
  19565. Object.defineProperty(object, property, {
  19566. value,
  19567. enumerable: true,
  19568. configurable: true
  19569. });
  19570. return value;
  19571. },
  19572. enumerable: true,
  19573. configurable: true
  19574. });
  19575. };
  19576. /** @type {typeof import('color-convert')} */
  19577. let colorConvert$1;
  19578. const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => {
  19579. if (colorConvert$1 === undefined) {
  19580. colorConvert$1 = colorConvert;
  19581. }
  19582. const offset = isBackground ? 10 : 0;
  19583. const styles = {};
  19584. for (const [sourceSpace, suite] of Object.entries(colorConvert$1)) {
  19585. const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace;
  19586. if (sourceSpace === targetSpace) {
  19587. styles[name] = wrap(identity, offset);
  19588. } else if (typeof suite === 'object') {
  19589. styles[name] = wrap(suite[targetSpace], offset);
  19590. }
  19591. }
  19592. return styles;
  19593. };
  19594. function assembleStyles() {
  19595. const codes = new Map();
  19596. const styles = {
  19597. modifier: {
  19598. reset: [0, 0],
  19599. // 21 isn't widely supported and 22 does the same thing
  19600. bold: [1, 22],
  19601. dim: [2, 22],
  19602. italic: [3, 23],
  19603. underline: [4, 24],
  19604. inverse: [7, 27],
  19605. hidden: [8, 28],
  19606. strikethrough: [9, 29]
  19607. },
  19608. color: {
  19609. black: [30, 39],
  19610. red: [31, 39],
  19611. green: [32, 39],
  19612. yellow: [33, 39],
  19613. blue: [34, 39],
  19614. magenta: [35, 39],
  19615. cyan: [36, 39],
  19616. white: [37, 39],
  19617. // Bright color
  19618. blackBright: [90, 39],
  19619. redBright: [91, 39],
  19620. greenBright: [92, 39],
  19621. yellowBright: [93, 39],
  19622. blueBright: [94, 39],
  19623. magentaBright: [95, 39],
  19624. cyanBright: [96, 39],
  19625. whiteBright: [97, 39]
  19626. },
  19627. bgColor: {
  19628. bgBlack: [40, 49],
  19629. bgRed: [41, 49],
  19630. bgGreen: [42, 49],
  19631. bgYellow: [43, 49],
  19632. bgBlue: [44, 49],
  19633. bgMagenta: [45, 49],
  19634. bgCyan: [46, 49],
  19635. bgWhite: [47, 49],
  19636. // Bright color
  19637. bgBlackBright: [100, 49],
  19638. bgRedBright: [101, 49],
  19639. bgGreenBright: [102, 49],
  19640. bgYellowBright: [103, 49],
  19641. bgBlueBright: [104, 49],
  19642. bgMagentaBright: [105, 49],
  19643. bgCyanBright: [106, 49],
  19644. bgWhiteBright: [107, 49]
  19645. }
  19646. };
  19647. // Alias bright black as gray (and grey)
  19648. styles.color.gray = styles.color.blackBright;
  19649. styles.bgColor.bgGray = styles.bgColor.bgBlackBright;
  19650. styles.color.grey = styles.color.blackBright;
  19651. styles.bgColor.bgGrey = styles.bgColor.bgBlackBright;
  19652. for (const [groupName, group] of Object.entries(styles)) {
  19653. for (const [styleName, style] of Object.entries(group)) {
  19654. styles[styleName] = {
  19655. open: `\u001B[${style[0]}m`,
  19656. close: `\u001B[${style[1]}m`
  19657. };
  19658. group[styleName] = styles[styleName];
  19659. codes.set(style[0], style[1]);
  19660. }
  19661. Object.defineProperty(styles, groupName, {
  19662. value: group,
  19663. enumerable: false
  19664. });
  19665. }
  19666. Object.defineProperty(styles, 'codes', {
  19667. value: codes,
  19668. enumerable: false
  19669. });
  19670. styles.color.close = '\u001B[39m';
  19671. styles.bgColor.close = '\u001B[49m';
  19672. setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false));
  19673. setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false));
  19674. setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false));
  19675. setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true));
  19676. setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true));
  19677. setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true));
  19678. return styles;
  19679. }
  19680. // Make the export immutable
  19681. Object.defineProperty(module, 'exports', {
  19682. enumerable: true,
  19683. get: assembleStyles
  19684. });
  19685. }, "/$$rollup_base$$/node_modules/ansi-styles");
  19686. var hasFlag = (flag, argv = process.argv) => {
  19687. const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');
  19688. const position = argv.indexOf(prefix + flag);
  19689. const terminatorPosition = argv.indexOf('--');
  19690. return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
  19691. };
  19692. const {env: env$1} = process;
  19693. let forceColor;
  19694. if (hasFlag('no-color') ||
  19695. hasFlag('no-colors') ||
  19696. hasFlag('color=false') ||
  19697. hasFlag('color=never')) {
  19698. forceColor = 0;
  19699. } else if (hasFlag('color') ||
  19700. hasFlag('colors') ||
  19701. hasFlag('color=true') ||
  19702. hasFlag('color=always')) {
  19703. forceColor = 1;
  19704. }
  19705. if ('FORCE_COLOR' in env$1) {
  19706. if (env$1.FORCE_COLOR === 'true') {
  19707. forceColor = 1;
  19708. } else if (env$1.FORCE_COLOR === 'false') {
  19709. forceColor = 0;
  19710. } else {
  19711. forceColor = env$1.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env$1.FORCE_COLOR, 10), 3);
  19712. }
  19713. }
  19714. function translateLevel(level) {
  19715. if (level === 0) {
  19716. return false;
  19717. }
  19718. return {
  19719. level,
  19720. hasBasic: true,
  19721. has256: level >= 2,
  19722. has16m: level >= 3
  19723. };
  19724. }
  19725. function supportsColor(haveStream, streamIsTTY) {
  19726. if (forceColor === 0) {
  19727. return 0;
  19728. }
  19729. if (hasFlag('color=16m') ||
  19730. hasFlag('color=full') ||
  19731. hasFlag('color=truecolor')) {
  19732. return 3;
  19733. }
  19734. if (hasFlag('color=256')) {
  19735. return 2;
  19736. }
  19737. if (haveStream && !streamIsTTY && forceColor === undefined) {
  19738. return 0;
  19739. }
  19740. const min = forceColor || 0;
  19741. if (env$1.TERM === 'dumb') {
  19742. return min;
  19743. }
  19744. if (process.platform === 'win32') {
  19745. // Windows 10 build 10586 is the first Windows release that supports 256 colors.
  19746. // Windows 10 build 14931 is the first release that supports 16m/TrueColor.
  19747. const osRelease = os__default["default"].release().split('.');
  19748. if (
  19749. Number(osRelease[0]) >= 10 &&
  19750. Number(osRelease[2]) >= 10586
  19751. ) {
  19752. return Number(osRelease[2]) >= 14931 ? 3 : 2;
  19753. }
  19754. return 1;
  19755. }
  19756. if ('CI' in env$1) {
  19757. if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env$1) || env$1.CI_NAME === 'codeship') {
  19758. return 1;
  19759. }
  19760. return min;
  19761. }
  19762. if ('TEAMCITY_VERSION' in env$1) {
  19763. return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$1.TEAMCITY_VERSION) ? 1 : 0;
  19764. }
  19765. if (env$1.COLORTERM === 'truecolor') {
  19766. return 3;
  19767. }
  19768. if ('TERM_PROGRAM' in env$1) {
  19769. const version = parseInt((env$1.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
  19770. switch (env$1.TERM_PROGRAM) {
  19771. case 'iTerm.app':
  19772. return version >= 3 ? 3 : 2;
  19773. case 'Apple_Terminal':
  19774. return 2;
  19775. // No default
  19776. }
  19777. }
  19778. if (/-256(color)?$/i.test(env$1.TERM)) {
  19779. return 2;
  19780. }
  19781. if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$1.TERM)) {
  19782. return 1;
  19783. }
  19784. if ('COLORTERM' in env$1) {
  19785. return 1;
  19786. }
  19787. return min;
  19788. }
  19789. function getSupportLevel(stream) {
  19790. const level = supportsColor(stream, stream && stream.isTTY);
  19791. return translateLevel(level);
  19792. }
  19793. var supportsColor_1 = {
  19794. supportsColor: getSupportLevel,
  19795. stdout: translateLevel(supportsColor(true, tty__default["default"].isatty(1))),
  19796. stderr: translateLevel(supportsColor(true, tty__default["default"].isatty(2)))
  19797. };
  19798. const stringReplaceAll$1 = (string, substring, replacer) => {
  19799. let index = string.indexOf(substring);
  19800. if (index === -1) {
  19801. return string;
  19802. }
  19803. const substringLength = substring.length;
  19804. let endIndex = 0;
  19805. let returnValue = '';
  19806. do {
  19807. returnValue += string.substr(endIndex, index - endIndex) + substring + replacer;
  19808. endIndex = index + substringLength;
  19809. index = string.indexOf(substring, endIndex);
  19810. } while (index !== -1);
  19811. returnValue += string.substr(endIndex);
  19812. return returnValue;
  19813. };
  19814. const stringEncaseCRLFWithFirstIndex$1 = (string, prefix, postfix, index) => {
  19815. let endIndex = 0;
  19816. let returnValue = '';
  19817. do {
  19818. const gotCR = string[index - 1] === '\r';
  19819. returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix;
  19820. endIndex = index + 1;
  19821. index = string.indexOf('\n', endIndex);
  19822. } while (index !== -1);
  19823. returnValue += string.substr(endIndex);
  19824. return returnValue;
  19825. };
  19826. var util = {
  19827. stringReplaceAll: stringReplaceAll$1,
  19828. stringEncaseCRLFWithFirstIndex: stringEncaseCRLFWithFirstIndex$1
  19829. };
  19830. const TEMPLATE_REGEX = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
  19831. const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
  19832. const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
  19833. const ESCAPE_REGEX = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi;
  19834. const ESCAPES = new Map([
  19835. ['n', '\n'],
  19836. ['r', '\r'],
  19837. ['t', '\t'],
  19838. ['b', '\b'],
  19839. ['f', '\f'],
  19840. ['v', '\v'],
  19841. ['0', '\0'],
  19842. ['\\', '\\'],
  19843. ['e', '\u001B'],
  19844. ['a', '\u0007']
  19845. ]);
  19846. function unescape$1(c) {
  19847. const u = c[0] === 'u';
  19848. const bracket = c[1] === '{';
  19849. if ((u && !bracket && c.length === 5) || (c[0] === 'x' && c.length === 3)) {
  19850. return String.fromCharCode(parseInt(c.slice(1), 16));
  19851. }
  19852. if (u && bracket) {
  19853. return String.fromCodePoint(parseInt(c.slice(2, -1), 16));
  19854. }
  19855. return ESCAPES.get(c) || c;
  19856. }
  19857. function parseArguments(name, arguments_) {
  19858. const results = [];
  19859. const chunks = arguments_.trim().split(/\s*,\s*/g);
  19860. let matches;
  19861. for (const chunk of chunks) {
  19862. const number = Number(chunk);
  19863. if (!Number.isNaN(number)) {
  19864. results.push(number);
  19865. } else if ((matches = chunk.match(STRING_REGEX))) {
  19866. results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, character) => escape ? unescape$1(escape) : character));
  19867. } else {
  19868. throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
  19869. }
  19870. }
  19871. return results;
  19872. }
  19873. function parseStyle(style) {
  19874. STYLE_REGEX.lastIndex = 0;
  19875. const results = [];
  19876. let matches;
  19877. while ((matches = STYLE_REGEX.exec(style)) !== null) {
  19878. const name = matches[1];
  19879. if (matches[2]) {
  19880. const args = parseArguments(name, matches[2]);
  19881. results.push([name].concat(args));
  19882. } else {
  19883. results.push([name]);
  19884. }
  19885. }
  19886. return results;
  19887. }
  19888. function buildStyle(chalk, styles) {
  19889. const enabled = {};
  19890. for (const layer of styles) {
  19891. for (const style of layer.styles) {
  19892. enabled[style[0]] = layer.inverse ? null : style.slice(1);
  19893. }
  19894. }
  19895. let current = chalk;
  19896. for (const [styleName, styles] of Object.entries(enabled)) {
  19897. if (!Array.isArray(styles)) {
  19898. continue;
  19899. }
  19900. if (!(styleName in current)) {
  19901. throw new Error(`Unknown Chalk style: ${styleName}`);
  19902. }
  19903. current = styles.length > 0 ? current[styleName](...styles) : current[styleName];
  19904. }
  19905. return current;
  19906. }
  19907. var templates = (chalk, temporary) => {
  19908. const styles = [];
  19909. const chunks = [];
  19910. let chunk = [];
  19911. // eslint-disable-next-line max-params
  19912. temporary.replace(TEMPLATE_REGEX, (m, escapeCharacter, inverse, style, close, character) => {
  19913. if (escapeCharacter) {
  19914. chunk.push(unescape$1(escapeCharacter));
  19915. } else if (style) {
  19916. const string = chunk.join('');
  19917. chunk = [];
  19918. chunks.push(styles.length === 0 ? string : buildStyle(chalk, styles)(string));
  19919. styles.push({inverse, styles: parseStyle(style)});
  19920. } else if (close) {
  19921. if (styles.length === 0) {
  19922. throw new Error('Found extraneous } in Chalk template literal');
  19923. }
  19924. chunks.push(buildStyle(chalk, styles)(chunk.join('')));
  19925. chunk = [];
  19926. styles.pop();
  19927. } else {
  19928. chunk.push(character);
  19929. }
  19930. });
  19931. chunks.push(chunk.join(''));
  19932. if (styles.length > 0) {
  19933. const errMessage = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
  19934. throw new Error(errMessage);
  19935. }
  19936. return chunks.join('');
  19937. };
  19938. const {stdout: stdoutColor, stderr: stderrColor} = supportsColor_1;
  19939. const {
  19940. stringReplaceAll,
  19941. stringEncaseCRLFWithFirstIndex
  19942. } = util;
  19943. const {isArray: isArray$2} = Array;
  19944. // `supportsColor.level` → `ansiStyles.color[name]` mapping
  19945. const levelMapping = [
  19946. 'ansi',
  19947. 'ansi',
  19948. 'ansi256',
  19949. 'ansi16m'
  19950. ];
  19951. const styles = Object.create(null);
  19952. const applyOptions = (object, options = {}) => {
  19953. if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
  19954. throw new Error('The `level` option should be an integer from 0 to 3');
  19955. }
  19956. // Detect level if not set manually
  19957. const colorLevel = stdoutColor ? stdoutColor.level : 0;
  19958. object.level = options.level === undefined ? colorLevel : options.level;
  19959. };
  19960. class ChalkClass {
  19961. constructor(options) {
  19962. // eslint-disable-next-line no-constructor-return
  19963. return chalkFactory(options);
  19964. }
  19965. }
  19966. const chalkFactory = options => {
  19967. const chalk = {};
  19968. applyOptions(chalk, options);
  19969. chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_);
  19970. Object.setPrototypeOf(chalk, Chalk.prototype);
  19971. Object.setPrototypeOf(chalk.template, chalk);
  19972. chalk.template.constructor = () => {
  19973. throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.');
  19974. };
  19975. chalk.template.Instance = ChalkClass;
  19976. return chalk.template;
  19977. };
  19978. function Chalk(options) {
  19979. return chalkFactory(options);
  19980. }
  19981. for (const [styleName, style] of Object.entries(ansiStyles)) {
  19982. styles[styleName] = {
  19983. get() {
  19984. const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty);
  19985. Object.defineProperty(this, styleName, {value: builder});
  19986. return builder;
  19987. }
  19988. };
  19989. }
  19990. styles.visible = {
  19991. get() {
  19992. const builder = createBuilder(this, this._styler, true);
  19993. Object.defineProperty(this, 'visible', {value: builder});
  19994. return builder;
  19995. }
  19996. };
  19997. const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256'];
  19998. for (const model of usedModels) {
  19999. styles[model] = {
  20000. get() {
  20001. const {level} = this;
  20002. return function (...arguments_) {
  20003. const styler = createStyler(ansiStyles.color[levelMapping[level]][model](...arguments_), ansiStyles.color.close, this._styler);
  20004. return createBuilder(this, styler, this._isEmpty);
  20005. };
  20006. }
  20007. };
  20008. }
  20009. for (const model of usedModels) {
  20010. const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
  20011. styles[bgModel] = {
  20012. get() {
  20013. const {level} = this;
  20014. return function (...arguments_) {
  20015. const styler = createStyler(ansiStyles.bgColor[levelMapping[level]][model](...arguments_), ansiStyles.bgColor.close, this._styler);
  20016. return createBuilder(this, styler, this._isEmpty);
  20017. };
  20018. }
  20019. };
  20020. }
  20021. const proto = Object.defineProperties(() => {}, {
  20022. ...styles,
  20023. level: {
  20024. enumerable: true,
  20025. get() {
  20026. return this._generator.level;
  20027. },
  20028. set(level) {
  20029. this._generator.level = level;
  20030. }
  20031. }
  20032. });
  20033. const createStyler = (open, close, parent) => {
  20034. let openAll;
  20035. let closeAll;
  20036. if (parent === undefined) {
  20037. openAll = open;
  20038. closeAll = close;
  20039. } else {
  20040. openAll = parent.openAll + open;
  20041. closeAll = close + parent.closeAll;
  20042. }
  20043. return {
  20044. open,
  20045. close,
  20046. openAll,
  20047. closeAll,
  20048. parent
  20049. };
  20050. };
  20051. const createBuilder = (self, _styler, _isEmpty) => {
  20052. const builder = (...arguments_) => {
  20053. if (isArray$2(arguments_[0]) && isArray$2(arguments_[0].raw)) {
  20054. // Called as a template literal, for example: chalk.red`2 + 3 = {bold ${2+3}}`
  20055. return applyStyle(builder, chalkTag(builder, ...arguments_));
  20056. }
  20057. // Single argument is hot path, implicit coercion is faster than anything
  20058. // eslint-disable-next-line no-implicit-coercion
  20059. return applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' '));
  20060. };
  20061. // We alter the prototype because we must return a function, but there is
  20062. // no way to create a function with a different prototype
  20063. Object.setPrototypeOf(builder, proto);
  20064. builder._generator = self;
  20065. builder._styler = _styler;
  20066. builder._isEmpty = _isEmpty;
  20067. return builder;
  20068. };
  20069. const applyStyle = (self, string) => {
  20070. if (self.level <= 0 || !string) {
  20071. return self._isEmpty ? '' : string;
  20072. }
  20073. let styler = self._styler;
  20074. if (styler === undefined) {
  20075. return string;
  20076. }
  20077. const {openAll, closeAll} = styler;
  20078. if (string.indexOf('\u001B') !== -1) {
  20079. while (styler !== undefined) {
  20080. // Replace any instances already present with a re-opening code
  20081. // otherwise only the part of the string until said closing code
  20082. // will be colored, and the rest will simply be 'plain'.
  20083. string = stringReplaceAll(string, styler.close, styler.open);
  20084. styler = styler.parent;
  20085. }
  20086. }
  20087. // We can move both next actions out of loop, because remaining actions in loop won't have
  20088. // any/visible effect on parts we add here. Close the styling before a linebreak and reopen
  20089. // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92
  20090. const lfIndex = string.indexOf('\n');
  20091. if (lfIndex !== -1) {
  20092. string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
  20093. }
  20094. return openAll + string + closeAll;
  20095. };
  20096. let template;
  20097. const chalkTag = (chalk, ...strings) => {
  20098. const [firstString] = strings;
  20099. if (!isArray$2(firstString) || !isArray$2(firstString.raw)) {
  20100. // If chalk() was called by itself or with a string,
  20101. // return the string itself as a string.
  20102. return strings.join(' ');
  20103. }
  20104. const arguments_ = strings.slice(1);
  20105. const parts = [firstString.raw[0]];
  20106. for (let i = 1; i < firstString.length; i++) {
  20107. parts.push(
  20108. String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'),
  20109. String(firstString.raw[i])
  20110. );
  20111. }
  20112. if (template === undefined) {
  20113. template = templates;
  20114. }
  20115. return template(chalk, parts.join(''));
  20116. };
  20117. Object.defineProperties(Chalk.prototype, styles);
  20118. const chalk = Chalk(); // eslint-disable-line new-cap
  20119. chalk.supportsColor = stdoutColor;
  20120. chalk.stderr = Chalk({level: stderrColor ? stderrColor.level : 0}); // eslint-disable-line new-cap
  20121. chalk.stderr.supportsColor = stderrColor;
  20122. var source = chalk;
  20123. // Copyright Joyent, Inc. and other Node contributors.
  20124. //
  20125. // Permission is hereby granted, free of charge, to any person obtaining a
  20126. // copy of this software and associated documentation files (the
  20127. // "Software"), to deal in the Software without restriction, including
  20128. // without limitation the rights to use, copy, modify, merge, publish,
  20129. // distribute, sublicense, and/or sell copies of the Software, and to permit
  20130. // persons to whom the Software is furnished to do so, subject to the
  20131. // following conditions:
  20132. //
  20133. // The above copyright notice and this permission notice shall be included
  20134. // in all copies or substantial portions of the Software.
  20135. //
  20136. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  20137. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  20138. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  20139. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  20140. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  20141. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  20142. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  20143. var isWindows = process.platform === 'win32';
  20144. // JavaScript implementation of realpath, ported from node pre-v6
  20145. var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG);
  20146. function rethrow() {
  20147. // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and
  20148. // is fairly slow to generate.
  20149. var callback;
  20150. if (DEBUG) {
  20151. var backtrace = new Error;
  20152. callback = debugCallback;
  20153. } else
  20154. callback = missingCallback;
  20155. return callback;
  20156. function debugCallback(err) {
  20157. if (err) {
  20158. backtrace.message = err.message;
  20159. err = backtrace;
  20160. missingCallback(err);
  20161. }
  20162. }
  20163. function missingCallback(err) {
  20164. if (err) {
  20165. if (process.throwDeprecation)
  20166. throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs
  20167. else if (!process.noDeprecation) {
  20168. var msg = 'fs: missing callback ' + (err.stack || err.message);
  20169. if (process.traceDeprecation)
  20170. console.trace(msg);
  20171. else
  20172. console.error(msg);
  20173. }
  20174. }
  20175. }
  20176. }
  20177. function maybeCallback(cb) {
  20178. return typeof cb === 'function' ? cb : rethrow();
  20179. }
  20180. path__default["default"].normalize;
  20181. // Regexp that finds the next partion of a (partial) path
  20182. // result is [base_with_slash, base], e.g. ['somedir/', 'somedir']
  20183. if (isWindows) {
  20184. var nextPartRe = /(.*?)(?:[\/\\]+|$)/g;
  20185. } else {
  20186. var nextPartRe = /(.*?)(?:[\/]+|$)/g;
  20187. }
  20188. // Regex to find the device root, including trailing slash. E.g. 'c:\\'.
  20189. if (isWindows) {
  20190. var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/;
  20191. } else {
  20192. var splitRootRe = /^[\/]*/;
  20193. }
  20194. var realpathSync$1 = function realpathSync(p, cache) {
  20195. // make p is absolute
  20196. p = path__default["default"].resolve(p);
  20197. if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
  20198. return cache[p];
  20199. }
  20200. var original = p,
  20201. seenLinks = {},
  20202. knownHard = {};
  20203. // current character position in p
  20204. var pos;
  20205. // the partial path so far, including a trailing slash if any
  20206. var current;
  20207. // the partial path without a trailing slash (except when pointing at a root)
  20208. var base;
  20209. // the partial path scanned in the previous round, with slash
  20210. var previous;
  20211. start();
  20212. function start() {
  20213. // Skip over roots
  20214. var m = splitRootRe.exec(p);
  20215. pos = m[0].length;
  20216. current = m[0];
  20217. base = m[0];
  20218. previous = '';
  20219. // On windows, check that the root exists. On unix there is no need.
  20220. if (isWindows && !knownHard[base]) {
  20221. fs__default["default"].lstatSync(base);
  20222. knownHard[base] = true;
  20223. }
  20224. }
  20225. // walk down the path, swapping out linked pathparts for their real
  20226. // values
  20227. // NB: p.length changes.
  20228. while (pos < p.length) {
  20229. // find the next part
  20230. nextPartRe.lastIndex = pos;
  20231. var result = nextPartRe.exec(p);
  20232. previous = current;
  20233. current += result[0];
  20234. base = previous + result[1];
  20235. pos = nextPartRe.lastIndex;
  20236. // continue if not a symlink
  20237. if (knownHard[base] || (cache && cache[base] === base)) {
  20238. continue;
  20239. }
  20240. var resolvedLink;
  20241. if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
  20242. // some known symbolic link. no need to stat again.
  20243. resolvedLink = cache[base];
  20244. } else {
  20245. var stat = fs__default["default"].lstatSync(base);
  20246. if (!stat.isSymbolicLink()) {
  20247. knownHard[base] = true;
  20248. if (cache) cache[base] = base;
  20249. continue;
  20250. }
  20251. // read the link if it wasn't read before
  20252. // dev/ino always return 0 on windows, so skip the check.
  20253. var linkTarget = null;
  20254. if (!isWindows) {
  20255. var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
  20256. if (seenLinks.hasOwnProperty(id)) {
  20257. linkTarget = seenLinks[id];
  20258. }
  20259. }
  20260. if (linkTarget === null) {
  20261. fs__default["default"].statSync(base);
  20262. linkTarget = fs__default["default"].readlinkSync(base);
  20263. }
  20264. resolvedLink = path__default["default"].resolve(previous, linkTarget);
  20265. // track this, if given a cache.
  20266. if (cache) cache[base] = resolvedLink;
  20267. if (!isWindows) seenLinks[id] = linkTarget;
  20268. }
  20269. // resolve the link, then start over
  20270. p = path__default["default"].resolve(resolvedLink, p.slice(pos));
  20271. start();
  20272. }
  20273. if (cache) cache[original] = p;
  20274. return p;
  20275. };
  20276. var realpath$1 = function realpath(p, cache, cb) {
  20277. if (typeof cb !== 'function') {
  20278. cb = maybeCallback(cache);
  20279. cache = null;
  20280. }
  20281. // make p is absolute
  20282. p = path__default["default"].resolve(p);
  20283. if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
  20284. return process.nextTick(cb.bind(null, null, cache[p]));
  20285. }
  20286. var original = p,
  20287. seenLinks = {},
  20288. knownHard = {};
  20289. // current character position in p
  20290. var pos;
  20291. // the partial path so far, including a trailing slash if any
  20292. var current;
  20293. // the partial path without a trailing slash (except when pointing at a root)
  20294. var base;
  20295. // the partial path scanned in the previous round, with slash
  20296. var previous;
  20297. start();
  20298. function start() {
  20299. // Skip over roots
  20300. var m = splitRootRe.exec(p);
  20301. pos = m[0].length;
  20302. current = m[0];
  20303. base = m[0];
  20304. previous = '';
  20305. // On windows, check that the root exists. On unix there is no need.
  20306. if (isWindows && !knownHard[base]) {
  20307. fs__default["default"].lstat(base, function(err) {
  20308. if (err) return cb(err);
  20309. knownHard[base] = true;
  20310. LOOP();
  20311. });
  20312. } else {
  20313. process.nextTick(LOOP);
  20314. }
  20315. }
  20316. // walk down the path, swapping out linked pathparts for their real
  20317. // values
  20318. function LOOP() {
  20319. // stop if scanned past end of path
  20320. if (pos >= p.length) {
  20321. if (cache) cache[original] = p;
  20322. return cb(null, p);
  20323. }
  20324. // find the next part
  20325. nextPartRe.lastIndex = pos;
  20326. var result = nextPartRe.exec(p);
  20327. previous = current;
  20328. current += result[0];
  20329. base = previous + result[1];
  20330. pos = nextPartRe.lastIndex;
  20331. // continue if not a symlink
  20332. if (knownHard[base] || (cache && cache[base] === base)) {
  20333. return process.nextTick(LOOP);
  20334. }
  20335. if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
  20336. // known symbolic link. no need to stat again.
  20337. return gotResolvedLink(cache[base]);
  20338. }
  20339. return fs__default["default"].lstat(base, gotStat);
  20340. }
  20341. function gotStat(err, stat) {
  20342. if (err) return cb(err);
  20343. // if not a symlink, skip to the next path part
  20344. if (!stat.isSymbolicLink()) {
  20345. knownHard[base] = true;
  20346. if (cache) cache[base] = base;
  20347. return process.nextTick(LOOP);
  20348. }
  20349. // stat & read the link if not read before
  20350. // call gotTarget as soon as the link target is known
  20351. // dev/ino always return 0 on windows, so skip the check.
  20352. if (!isWindows) {
  20353. var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
  20354. if (seenLinks.hasOwnProperty(id)) {
  20355. return gotTarget(null, seenLinks[id], base);
  20356. }
  20357. }
  20358. fs__default["default"].stat(base, function(err) {
  20359. if (err) return cb(err);
  20360. fs__default["default"].readlink(base, function(err, target) {
  20361. if (!isWindows) seenLinks[id] = target;
  20362. gotTarget(err, target);
  20363. });
  20364. });
  20365. }
  20366. function gotTarget(err, target, base) {
  20367. if (err) return cb(err);
  20368. var resolvedLink = path__default["default"].resolve(previous, target);
  20369. if (cache) cache[base] = resolvedLink;
  20370. gotResolvedLink(resolvedLink);
  20371. }
  20372. function gotResolvedLink(resolvedLink) {
  20373. // resolve the link, then start over
  20374. p = path__default["default"].resolve(resolvedLink, p.slice(pos));
  20375. start();
  20376. }
  20377. };
  20378. var old = {
  20379. realpathSync: realpathSync$1,
  20380. realpath: realpath$1
  20381. };
  20382. var fs_realpath = realpath;
  20383. realpath.realpath = realpath;
  20384. realpath.sync = realpathSync;
  20385. realpath.realpathSync = realpathSync;
  20386. realpath.monkeypatch = monkeypatch;
  20387. realpath.unmonkeypatch = unmonkeypatch;
  20388. var origRealpath = fs__default["default"].realpath;
  20389. var origRealpathSync = fs__default["default"].realpathSync;
  20390. var version = process.version;
  20391. var ok = /^v[0-5]\./.test(version);
  20392. function newError (er) {
  20393. return er && er.syscall === 'realpath' && (
  20394. er.code === 'ELOOP' ||
  20395. er.code === 'ENOMEM' ||
  20396. er.code === 'ENAMETOOLONG'
  20397. )
  20398. }
  20399. function realpath (p, cache, cb) {
  20400. if (ok) {
  20401. return origRealpath(p, cache, cb)
  20402. }
  20403. if (typeof cache === 'function') {
  20404. cb = cache;
  20405. cache = null;
  20406. }
  20407. origRealpath(p, cache, function (er, result) {
  20408. if (newError(er)) {
  20409. old.realpath(p, cache, cb);
  20410. } else {
  20411. cb(er, result);
  20412. }
  20413. });
  20414. }
  20415. function realpathSync (p, cache) {
  20416. if (ok) {
  20417. return origRealpathSync(p, cache)
  20418. }
  20419. try {
  20420. return origRealpathSync(p, cache)
  20421. } catch (er) {
  20422. if (newError(er)) {
  20423. return old.realpathSync(p, cache)
  20424. } else {
  20425. throw er
  20426. }
  20427. }
  20428. }
  20429. function monkeypatch () {
  20430. fs__default["default"].realpath = realpath;
  20431. fs__default["default"].realpathSync = realpathSync;
  20432. }
  20433. function unmonkeypatch () {
  20434. fs__default["default"].realpath = origRealpath;
  20435. fs__default["default"].realpathSync = origRealpathSync;
  20436. }
  20437. var concatMap = function (xs, fn) {
  20438. var res = [];
  20439. for (var i = 0; i < xs.length; i++) {
  20440. var x = fn(xs[i], i);
  20441. if (isArray$1(x)) res.push.apply(res, x);
  20442. else res.push(x);
  20443. }
  20444. return res;
  20445. };
  20446. var isArray$1 = Array.isArray || function (xs) {
  20447. return Object.prototype.toString.call(xs) === '[object Array]';
  20448. };
  20449. var balancedMatch = balanced;
  20450. function balanced(a, b, str) {
  20451. if (a instanceof RegExp) a = maybeMatch(a, str);
  20452. if (b instanceof RegExp) b = maybeMatch(b, str);
  20453. var r = range(a, b, str);
  20454. return r && {
  20455. start: r[0],
  20456. end: r[1],
  20457. pre: str.slice(0, r[0]),
  20458. body: str.slice(r[0] + a.length, r[1]),
  20459. post: str.slice(r[1] + b.length)
  20460. };
  20461. }
  20462. function maybeMatch(reg, str) {
  20463. var m = str.match(reg);
  20464. return m ? m[0] : null;
  20465. }
  20466. balanced.range = range;
  20467. function range(a, b, str) {
  20468. var begs, beg, left, right, result;
  20469. var ai = str.indexOf(a);
  20470. var bi = str.indexOf(b, ai + 1);
  20471. var i = ai;
  20472. if (ai >= 0 && bi > 0) {
  20473. if(a===b) {
  20474. return [ai, bi];
  20475. }
  20476. begs = [];
  20477. left = str.length;
  20478. while (i >= 0 && !result) {
  20479. if (i == ai) {
  20480. begs.push(i);
  20481. ai = str.indexOf(a, i + 1);
  20482. } else if (begs.length == 1) {
  20483. result = [ begs.pop(), bi ];
  20484. } else {
  20485. beg = begs.pop();
  20486. if (beg < left) {
  20487. left = beg;
  20488. right = bi;
  20489. }
  20490. bi = str.indexOf(b, i + 1);
  20491. }
  20492. i = ai < bi && ai >= 0 ? ai : bi;
  20493. }
  20494. if (begs.length) {
  20495. result = [ left, right ];
  20496. }
  20497. }
  20498. return result;
  20499. }
  20500. var braceExpansion = expandTop;
  20501. var escSlash = '\0SLASH'+Math.random()+'\0';
  20502. var escOpen = '\0OPEN'+Math.random()+'\0';
  20503. var escClose = '\0CLOSE'+Math.random()+'\0';
  20504. var escComma = '\0COMMA'+Math.random()+'\0';
  20505. var escPeriod = '\0PERIOD'+Math.random()+'\0';
  20506. function numeric(str) {
  20507. return parseInt(str, 10) == str
  20508. ? parseInt(str, 10)
  20509. : str.charCodeAt(0);
  20510. }
  20511. function escapeBraces(str) {
  20512. return str.split('\\\\').join(escSlash)
  20513. .split('\\{').join(escOpen)
  20514. .split('\\}').join(escClose)
  20515. .split('\\,').join(escComma)
  20516. .split('\\.').join(escPeriod);
  20517. }
  20518. function unescapeBraces(str) {
  20519. return str.split(escSlash).join('\\')
  20520. .split(escOpen).join('{')
  20521. .split(escClose).join('}')
  20522. .split(escComma).join(',')
  20523. .split(escPeriod).join('.');
  20524. }
  20525. // Basically just str.split(","), but handling cases
  20526. // where we have nested braced sections, which should be
  20527. // treated as individual members, like {a,{b,c},d}
  20528. function parseCommaParts(str) {
  20529. if (!str)
  20530. return [''];
  20531. var parts = [];
  20532. var m = balancedMatch('{', '}', str);
  20533. if (!m)
  20534. return str.split(',');
  20535. var pre = m.pre;
  20536. var body = m.body;
  20537. var post = m.post;
  20538. var p = pre.split(',');
  20539. p[p.length-1] += '{' + body + '}';
  20540. var postParts = parseCommaParts(post);
  20541. if (post.length) {
  20542. p[p.length-1] += postParts.shift();
  20543. p.push.apply(p, postParts);
  20544. }
  20545. parts.push.apply(parts, p);
  20546. return parts;
  20547. }
  20548. function expandTop(str) {
  20549. if (!str)
  20550. return [];
  20551. // I don't know why Bash 4.3 does this, but it does.
  20552. // Anything starting with {} will have the first two bytes preserved
  20553. // but *only* at the top level, so {},a}b will not expand to anything,
  20554. // but a{},b}c will be expanded to [a}c,abc].
  20555. // One could argue that this is a bug in Bash, but since the goal of
  20556. // this module is to match Bash's rules, we escape a leading {}
  20557. if (str.substr(0, 2) === '{}') {
  20558. str = '\\{\\}' + str.substr(2);
  20559. }
  20560. return expand(escapeBraces(str), true).map(unescapeBraces);
  20561. }
  20562. function embrace(str) {
  20563. return '{' + str + '}';
  20564. }
  20565. function isPadded(el) {
  20566. return /^-?0\d/.test(el);
  20567. }
  20568. function lte(i, y) {
  20569. return i <= y;
  20570. }
  20571. function gte(i, y) {
  20572. return i >= y;
  20573. }
  20574. function expand(str, isTop) {
  20575. var expansions = [];
  20576. var m = balancedMatch('{', '}', str);
  20577. if (!m || /\$$/.test(m.pre)) return [str];
  20578. var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
  20579. var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
  20580. var isSequence = isNumericSequence || isAlphaSequence;
  20581. var isOptions = m.body.indexOf(',') >= 0;
  20582. if (!isSequence && !isOptions) {
  20583. // {a},b}
  20584. if (m.post.match(/,.*\}/)) {
  20585. str = m.pre + '{' + m.body + escClose + m.post;
  20586. return expand(str);
  20587. }
  20588. return [str];
  20589. }
  20590. var n;
  20591. if (isSequence) {
  20592. n = m.body.split(/\.\./);
  20593. } else {
  20594. n = parseCommaParts(m.body);
  20595. if (n.length === 1) {
  20596. // x{{a,b}}y ==> x{a}y x{b}y
  20597. n = expand(n[0], false).map(embrace);
  20598. if (n.length === 1) {
  20599. var post = m.post.length
  20600. ? expand(m.post, false)
  20601. : [''];
  20602. return post.map(function(p) {
  20603. return m.pre + n[0] + p;
  20604. });
  20605. }
  20606. }
  20607. }
  20608. // at this point, n is the parts, and we know it's not a comma set
  20609. // with a single entry.
  20610. // no need to expand pre, since it is guaranteed to be free of brace-sets
  20611. var pre = m.pre;
  20612. var post = m.post.length
  20613. ? expand(m.post, false)
  20614. : [''];
  20615. var N;
  20616. if (isSequence) {
  20617. var x = numeric(n[0]);
  20618. var y = numeric(n[1]);
  20619. var width = Math.max(n[0].length, n[1].length);
  20620. var incr = n.length == 3
  20621. ? Math.abs(numeric(n[2]))
  20622. : 1;
  20623. var test = lte;
  20624. var reverse = y < x;
  20625. if (reverse) {
  20626. incr *= -1;
  20627. test = gte;
  20628. }
  20629. var pad = n.some(isPadded);
  20630. N = [];
  20631. for (var i = x; test(i, y); i += incr) {
  20632. var c;
  20633. if (isAlphaSequence) {
  20634. c = String.fromCharCode(i);
  20635. if (c === '\\')
  20636. c = '';
  20637. } else {
  20638. c = String(i);
  20639. if (pad) {
  20640. var need = width - c.length;
  20641. if (need > 0) {
  20642. var z = new Array(need + 1).join('0');
  20643. if (i < 0)
  20644. c = '-' + z + c.slice(1);
  20645. else
  20646. c = z + c;
  20647. }
  20648. }
  20649. }
  20650. N.push(c);
  20651. }
  20652. } else {
  20653. N = concatMap(n, function(el) { return expand(el, false) });
  20654. }
  20655. for (var j = 0; j < N.length; j++) {
  20656. for (var k = 0; k < post.length; k++) {
  20657. var expansion = pre + N[j] + post[k];
  20658. if (!isTop || isSequence || expansion)
  20659. expansions.push(expansion);
  20660. }
  20661. }
  20662. return expansions;
  20663. }
  20664. var minimatch_1 = minimatch;
  20665. minimatch.Minimatch = Minimatch$1;
  20666. var path = (function () { try { return path__default["default"] } catch (e) {}}()) || {
  20667. sep: '/'
  20668. };
  20669. minimatch.sep = path.sep;
  20670. var GLOBSTAR = minimatch.GLOBSTAR = Minimatch$1.GLOBSTAR = {};
  20671. var plTypes = {
  20672. '!': { open: '(?:(?!(?:', close: '))[^/]*?)'},
  20673. '?': { open: '(?:', close: ')?' },
  20674. '+': { open: '(?:', close: ')+' },
  20675. '*': { open: '(?:', close: ')*' },
  20676. '@': { open: '(?:', close: ')' }
  20677. };
  20678. // any single thing other than /
  20679. // don't need to escape / when using new RegExp()
  20680. var qmark = '[^/]';
  20681. // * => any number of characters
  20682. var star = qmark + '*?';
  20683. // ** when dots are allowed. Anything goes, except .. and .
  20684. // not (^ or / followed by one or two dots followed by $ or /),
  20685. // followed by anything, any number of times.
  20686. var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?';
  20687. // not a ^ or / followed by a dot,
  20688. // followed by anything, any number of times.
  20689. var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?';
  20690. // characters that need to be escaped in RegExp.
  20691. var reSpecials = charSet('().*{}+?[]^$\\!');
  20692. // "abc" -> { a:true, b:true, c:true }
  20693. function charSet (s) {
  20694. return s.split('').reduce(function (set, c) {
  20695. set[c] = true;
  20696. return set
  20697. }, {})
  20698. }
  20699. // normalizes slashes.
  20700. var slashSplit = /\/+/;
  20701. minimatch.filter = filter;
  20702. function filter (pattern, options) {
  20703. options = options || {};
  20704. return function (p, i, list) {
  20705. return minimatch(p, pattern, options)
  20706. }
  20707. }
  20708. function ext (a, b) {
  20709. b = b || {};
  20710. var t = {};
  20711. Object.keys(a).forEach(function (k) {
  20712. t[k] = a[k];
  20713. });
  20714. Object.keys(b).forEach(function (k) {
  20715. t[k] = b[k];
  20716. });
  20717. return t
  20718. }
  20719. minimatch.defaults = function (def) {
  20720. if (!def || typeof def !== 'object' || !Object.keys(def).length) {
  20721. return minimatch
  20722. }
  20723. var orig = minimatch;
  20724. var m = function minimatch (p, pattern, options) {
  20725. return orig(p, pattern, ext(def, options))
  20726. };
  20727. m.Minimatch = function Minimatch (pattern, options) {
  20728. return new orig.Minimatch(pattern, ext(def, options))
  20729. };
  20730. m.Minimatch.defaults = function defaults (options) {
  20731. return orig.defaults(ext(def, options)).Minimatch
  20732. };
  20733. m.filter = function filter (pattern, options) {
  20734. return orig.filter(pattern, ext(def, options))
  20735. };
  20736. m.defaults = function defaults (options) {
  20737. return orig.defaults(ext(def, options))
  20738. };
  20739. m.makeRe = function makeRe (pattern, options) {
  20740. return orig.makeRe(pattern, ext(def, options))
  20741. };
  20742. m.braceExpand = function braceExpand (pattern, options) {
  20743. return orig.braceExpand(pattern, ext(def, options))
  20744. };
  20745. m.match = function (list, pattern, options) {
  20746. return orig.match(list, pattern, ext(def, options))
  20747. };
  20748. return m
  20749. };
  20750. Minimatch$1.defaults = function (def) {
  20751. return minimatch.defaults(def).Minimatch
  20752. };
  20753. function minimatch (p, pattern, options) {
  20754. assertValidPattern(pattern);
  20755. if (!options) options = {};
  20756. // shortcut: comments match nothing.
  20757. if (!options.nocomment && pattern.charAt(0) === '#') {
  20758. return false
  20759. }
  20760. return new Minimatch$1(pattern, options).match(p)
  20761. }
  20762. function Minimatch$1 (pattern, options) {
  20763. if (!(this instanceof Minimatch$1)) {
  20764. return new Minimatch$1(pattern, options)
  20765. }
  20766. assertValidPattern(pattern);
  20767. if (!options) options = {};
  20768. pattern = pattern.trim();
  20769. // windows support: need to use /, not \
  20770. if (!options.allowWindowsEscape && path.sep !== '/') {
  20771. pattern = pattern.split(path.sep).join('/');
  20772. }
  20773. this.options = options;
  20774. this.set = [];
  20775. this.pattern = pattern;
  20776. this.regexp = null;
  20777. this.negate = false;
  20778. this.comment = false;
  20779. this.empty = false;
  20780. this.partial = !!options.partial;
  20781. // make the set of regexps etc.
  20782. this.make();
  20783. }
  20784. Minimatch$1.prototype.debug = function () {};
  20785. Minimatch$1.prototype.make = make;
  20786. function make () {
  20787. var pattern = this.pattern;
  20788. var options = this.options;
  20789. // empty patterns and comments match nothing.
  20790. if (!options.nocomment && pattern.charAt(0) === '#') {
  20791. this.comment = true;
  20792. return
  20793. }
  20794. if (!pattern) {
  20795. this.empty = true;
  20796. return
  20797. }
  20798. // step 1: figure out negation, etc.
  20799. this.parseNegate();
  20800. // step 2: expand braces
  20801. var set = this.globSet = this.braceExpand();
  20802. if (options.debug) this.debug = function debug() { console.error.apply(console, arguments); };
  20803. this.debug(this.pattern, set);
  20804. // step 3: now we have a set, so turn each one into a series of path-portion
  20805. // matching patterns.
  20806. // These will be regexps, except in the case of "**", which is
  20807. // set to the GLOBSTAR object for globstar behavior,
  20808. // and will not contain any / characters
  20809. set = this.globParts = set.map(function (s) {
  20810. return s.split(slashSplit)
  20811. });
  20812. this.debug(this.pattern, set);
  20813. // glob --> regexps
  20814. set = set.map(function (s, si, set) {
  20815. return s.map(this.parse, this)
  20816. }, this);
  20817. this.debug(this.pattern, set);
  20818. // filter out everything that didn't compile properly.
  20819. set = set.filter(function (s) {
  20820. return s.indexOf(false) === -1
  20821. });
  20822. this.debug(this.pattern, set);
  20823. this.set = set;
  20824. }
  20825. Minimatch$1.prototype.parseNegate = parseNegate;
  20826. function parseNegate () {
  20827. var pattern = this.pattern;
  20828. var negate = false;
  20829. var options = this.options;
  20830. var negateOffset = 0;
  20831. if (options.nonegate) return
  20832. for (var i = 0, l = pattern.length
  20833. ; i < l && pattern.charAt(i) === '!'
  20834. ; i++) {
  20835. negate = !negate;
  20836. negateOffset++;
  20837. }
  20838. if (negateOffset) this.pattern = pattern.substr(negateOffset);
  20839. this.negate = negate;
  20840. }
  20841. // Brace expansion:
  20842. // a{b,c}d -> abd acd
  20843. // a{b,}c -> abc ac
  20844. // a{0..3}d -> a0d a1d a2d a3d
  20845. // a{b,c{d,e}f}g -> abg acdfg acefg
  20846. // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
  20847. //
  20848. // Invalid sets are not expanded.
  20849. // a{2..}b -> a{2..}b
  20850. // a{b}c -> a{b}c
  20851. minimatch.braceExpand = function (pattern, options) {
  20852. return braceExpand(pattern, options)
  20853. };
  20854. Minimatch$1.prototype.braceExpand = braceExpand;
  20855. function braceExpand (pattern, options) {
  20856. if (!options) {
  20857. if (this instanceof Minimatch$1) {
  20858. options = this.options;
  20859. } else {
  20860. options = {};
  20861. }
  20862. }
  20863. pattern = typeof pattern === 'undefined'
  20864. ? this.pattern : pattern;
  20865. assertValidPattern(pattern);
  20866. // Thanks to Yeting Li <https://github.com/yetingli> for
  20867. // improving this regexp to avoid a ReDOS vulnerability.
  20868. if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
  20869. // shortcut. no need to expand.
  20870. return [pattern]
  20871. }
  20872. return braceExpansion(pattern)
  20873. }
  20874. var MAX_PATTERN_LENGTH = 1024 * 64;
  20875. var assertValidPattern = function (pattern) {
  20876. if (typeof pattern !== 'string') {
  20877. throw new TypeError('invalid pattern')
  20878. }
  20879. if (pattern.length > MAX_PATTERN_LENGTH) {
  20880. throw new TypeError('pattern is too long')
  20881. }
  20882. };
  20883. // parse a component of the expanded set.
  20884. // At this point, no pattern may contain "/" in it
  20885. // so we're going to return a 2d array, where each entry is the full
  20886. // pattern, split on '/', and then turned into a regular expression.
  20887. // A regexp is made at the end which joins each array with an
  20888. // escaped /, and another full one which joins each regexp with |.
  20889. //
  20890. // Following the lead of Bash 4.1, note that "**" only has special meaning
  20891. // when it is the *only* thing in a path portion. Otherwise, any series
  20892. // of * is equivalent to a single *. Globstar behavior is enabled by
  20893. // default, and can be disabled by setting options.noglobstar.
  20894. Minimatch$1.prototype.parse = parse;
  20895. var SUBPARSE = {};
  20896. function parse (pattern, isSub) {
  20897. assertValidPattern(pattern);
  20898. var options = this.options;
  20899. // shortcuts
  20900. if (pattern === '**') {
  20901. if (!options.noglobstar)
  20902. return GLOBSTAR
  20903. else
  20904. pattern = '*';
  20905. }
  20906. if (pattern === '') return ''
  20907. var re = '';
  20908. var hasMagic = !!options.nocase;
  20909. var escaping = false;
  20910. // ? => one single character
  20911. var patternListStack = [];
  20912. var negativeLists = [];
  20913. var stateChar;
  20914. var inClass = false;
  20915. var reClassStart = -1;
  20916. var classStart = -1;
  20917. // . and .. never match anything that doesn't start with .,
  20918. // even when options.dot is set.
  20919. var patternStart = pattern.charAt(0) === '.' ? '' // anything
  20920. // not (start or / followed by . or .. followed by / or end)
  20921. : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))'
  20922. : '(?!\\.)';
  20923. var self = this;
  20924. function clearStateChar () {
  20925. if (stateChar) {
  20926. // we had some state-tracking character
  20927. // that wasn't consumed by this pass.
  20928. switch (stateChar) {
  20929. case '*':
  20930. re += star;
  20931. hasMagic = true;
  20932. break
  20933. case '?':
  20934. re += qmark;
  20935. hasMagic = true;
  20936. break
  20937. default:
  20938. re += '\\' + stateChar;
  20939. break
  20940. }
  20941. self.debug('clearStateChar %j %j', stateChar, re);
  20942. stateChar = false;
  20943. }
  20944. }
  20945. for (var i = 0, len = pattern.length, c
  20946. ; (i < len) && (c = pattern.charAt(i))
  20947. ; i++) {
  20948. this.debug('%s\t%s %s %j', pattern, i, re, c);
  20949. // skip over any that are escaped.
  20950. if (escaping && reSpecials[c]) {
  20951. re += '\\' + c;
  20952. escaping = false;
  20953. continue
  20954. }
  20955. switch (c) {
  20956. /* istanbul ignore next */
  20957. case '/': {
  20958. // completely not allowed, even escaped.
  20959. // Should already be path-split by now.
  20960. return false
  20961. }
  20962. case '\\':
  20963. clearStateChar();
  20964. escaping = true;
  20965. continue
  20966. // the various stateChar values
  20967. // for the "extglob" stuff.
  20968. case '?':
  20969. case '*':
  20970. case '+':
  20971. case '@':
  20972. case '!':
  20973. this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c);
  20974. // all of those are literals inside a class, except that
  20975. // the glob [!a] means [^a] in regexp
  20976. if (inClass) {
  20977. this.debug(' in class');
  20978. if (c === '!' && i === classStart + 1) c = '^';
  20979. re += c;
  20980. continue
  20981. }
  20982. // if we already have a stateChar, then it means
  20983. // that there was something like ** or +? in there.
  20984. // Handle the stateChar, then proceed with this one.
  20985. self.debug('call clearStateChar %j', stateChar);
  20986. clearStateChar();
  20987. stateChar = c;
  20988. // if extglob is disabled, then +(asdf|foo) isn't a thing.
  20989. // just clear the statechar *now*, rather than even diving into
  20990. // the patternList stuff.
  20991. if (options.noext) clearStateChar();
  20992. continue
  20993. case '(':
  20994. if (inClass) {
  20995. re += '(';
  20996. continue
  20997. }
  20998. if (!stateChar) {
  20999. re += '\\(';
  21000. continue
  21001. }
  21002. patternListStack.push({
  21003. type: stateChar,
  21004. start: i - 1,
  21005. reStart: re.length,
  21006. open: plTypes[stateChar].open,
  21007. close: plTypes[stateChar].close
  21008. });
  21009. // negation is (?:(?!js)[^/]*)
  21010. re += stateChar === '!' ? '(?:(?!(?:' : '(?:';
  21011. this.debug('plType %j %j', stateChar, re);
  21012. stateChar = false;
  21013. continue
  21014. case ')':
  21015. if (inClass || !patternListStack.length) {
  21016. re += '\\)';
  21017. continue
  21018. }
  21019. clearStateChar();
  21020. hasMagic = true;
  21021. var pl = patternListStack.pop();
  21022. // negation is (?:(?!js)[^/]*)
  21023. // The others are (?:<pattern>)<type>
  21024. re += pl.close;
  21025. if (pl.type === '!') {
  21026. negativeLists.push(pl);
  21027. }
  21028. pl.reEnd = re.length;
  21029. continue
  21030. case '|':
  21031. if (inClass || !patternListStack.length || escaping) {
  21032. re += '\\|';
  21033. escaping = false;
  21034. continue
  21035. }
  21036. clearStateChar();
  21037. re += '|';
  21038. continue
  21039. // these are mostly the same in regexp and glob
  21040. case '[':
  21041. // swallow any state-tracking char before the [
  21042. clearStateChar();
  21043. if (inClass) {
  21044. re += '\\' + c;
  21045. continue
  21046. }
  21047. inClass = true;
  21048. classStart = i;
  21049. reClassStart = re.length;
  21050. re += c;
  21051. continue
  21052. case ']':
  21053. // a right bracket shall lose its special
  21054. // meaning and represent itself in
  21055. // a bracket expression if it occurs
  21056. // first in the list. -- POSIX.2 2.8.3.2
  21057. if (i === classStart + 1 || !inClass) {
  21058. re += '\\' + c;
  21059. escaping = false;
  21060. continue
  21061. }
  21062. // handle the case where we left a class open.
  21063. // "[z-a]" is valid, equivalent to "\[z-a\]"
  21064. // split where the last [ was, make sure we don't have
  21065. // an invalid re. if so, re-walk the contents of the
  21066. // would-be class to re-translate any characters that
  21067. // were passed through as-is
  21068. // TODO: It would probably be faster to determine this
  21069. // without a try/catch and a new RegExp, but it's tricky
  21070. // to do safely. For now, this is safe and works.
  21071. var cs = pattern.substring(classStart + 1, i);
  21072. try {
  21073. RegExp('[' + cs + ']');
  21074. } catch (er) {
  21075. // not a valid class!
  21076. var sp = this.parse(cs, SUBPARSE);
  21077. re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]';
  21078. hasMagic = hasMagic || sp[1];
  21079. inClass = false;
  21080. continue
  21081. }
  21082. // finish up the class.
  21083. hasMagic = true;
  21084. inClass = false;
  21085. re += c;
  21086. continue
  21087. default:
  21088. // swallow any state char that wasn't consumed
  21089. clearStateChar();
  21090. if (escaping) {
  21091. // no need
  21092. escaping = false;
  21093. } else if (reSpecials[c]
  21094. && !(c === '^' && inClass)) {
  21095. re += '\\';
  21096. }
  21097. re += c;
  21098. } // switch
  21099. } // for
  21100. // handle the case where we left a class open.
  21101. // "[abc" is valid, equivalent to "\[abc"
  21102. if (inClass) {
  21103. // split where the last [ was, and escape it
  21104. // this is a huge pita. We now have to re-walk
  21105. // the contents of the would-be class to re-translate
  21106. // any characters that were passed through as-is
  21107. cs = pattern.substr(classStart + 1);
  21108. sp = this.parse(cs, SUBPARSE);
  21109. re = re.substr(0, reClassStart) + '\\[' + sp[0];
  21110. hasMagic = hasMagic || sp[1];
  21111. }
  21112. // handle the case where we had a +( thing at the *end*
  21113. // of the pattern.
  21114. // each pattern list stack adds 3 chars, and we need to go through
  21115. // and escape any | chars that were passed through as-is for the regexp.
  21116. // Go through and escape them, taking care not to double-escape any
  21117. // | chars that were already escaped.
  21118. for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
  21119. var tail = re.slice(pl.reStart + pl.open.length);
  21120. this.debug('setting tail', re, pl);
  21121. // maybe some even number of \, then maybe 1 \, followed by a |
  21122. tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) {
  21123. if (!$2) {
  21124. // the | isn't already escaped, so escape it.
  21125. $2 = '\\';
  21126. }
  21127. // need to escape all those slashes *again*, without escaping the
  21128. // one that we need for escaping the | character. As it works out,
  21129. // escaping an even number of slashes can be done by simply repeating
  21130. // it exactly after itself. That's why this trick works.
  21131. //
  21132. // I am sorry that you have to see this.
  21133. return $1 + $1 + $2 + '|'
  21134. });
  21135. this.debug('tail=%j\n %s', tail, tail, pl, re);
  21136. var t = pl.type === '*' ? star
  21137. : pl.type === '?' ? qmark
  21138. : '\\' + pl.type;
  21139. hasMagic = true;
  21140. re = re.slice(0, pl.reStart) + t + '\\(' + tail;
  21141. }
  21142. // handle trailing things that only matter at the very end.
  21143. clearStateChar();
  21144. if (escaping) {
  21145. // trailing \\
  21146. re += '\\\\';
  21147. }
  21148. // only need to apply the nodot start if the re starts with
  21149. // something that could conceivably capture a dot
  21150. var addPatternStart = false;
  21151. switch (re.charAt(0)) {
  21152. case '[': case '.': case '(': addPatternStart = true;
  21153. }
  21154. // Hack to work around lack of negative lookbehind in JS
  21155. // A pattern like: *.!(x).!(y|z) needs to ensure that a name
  21156. // like 'a.xyz.yz' doesn't match. So, the first negative
  21157. // lookahead, has to look ALL the way ahead, to the end of
  21158. // the pattern.
  21159. for (var n = negativeLists.length - 1; n > -1; n--) {
  21160. var nl = negativeLists[n];
  21161. var nlBefore = re.slice(0, nl.reStart);
  21162. var nlFirst = re.slice(nl.reStart, nl.reEnd - 8);
  21163. var nlLast = re.slice(nl.reEnd - 8, nl.reEnd);
  21164. var nlAfter = re.slice(nl.reEnd);
  21165. nlLast += nlAfter;
  21166. // Handle nested stuff like *(*.js|!(*.json)), where open parens
  21167. // mean that we should *not* include the ) in the bit that is considered
  21168. // "after" the negated section.
  21169. var openParensBefore = nlBefore.split('(').length - 1;
  21170. var cleanAfter = nlAfter;
  21171. for (i = 0; i < openParensBefore; i++) {
  21172. cleanAfter = cleanAfter.replace(/\)[+*?]?/, '');
  21173. }
  21174. nlAfter = cleanAfter;
  21175. var dollar = '';
  21176. if (nlAfter === '' && isSub !== SUBPARSE) {
  21177. dollar = '$';
  21178. }
  21179. var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast;
  21180. re = newRe;
  21181. }
  21182. // if the re is not "" at this point, then we need to make sure
  21183. // it doesn't match against an empty path part.
  21184. // Otherwise a/* will match a/, which it should not.
  21185. if (re !== '' && hasMagic) {
  21186. re = '(?=.)' + re;
  21187. }
  21188. if (addPatternStart) {
  21189. re = patternStart + re;
  21190. }
  21191. // parsing just a piece of a larger pattern.
  21192. if (isSub === SUBPARSE) {
  21193. return [re, hasMagic]
  21194. }
  21195. // skip the regexp for non-magical patterns
  21196. // unescape anything in it, though, so that it'll be
  21197. // an exact match against a file etc.
  21198. if (!hasMagic) {
  21199. return globUnescape(pattern)
  21200. }
  21201. var flags = options.nocase ? 'i' : '';
  21202. try {
  21203. var regExp = new RegExp('^' + re + '$', flags);
  21204. } catch (er) /* istanbul ignore next - should be impossible */ {
  21205. // If it was an invalid regular expression, then it can't match
  21206. // anything. This trick looks for a character after the end of
  21207. // the string, which is of course impossible, except in multi-line
  21208. // mode, but it's not a /m regex.
  21209. return new RegExp('$.')
  21210. }
  21211. regExp._glob = pattern;
  21212. regExp._src = re;
  21213. return regExp
  21214. }
  21215. minimatch.makeRe = function (pattern, options) {
  21216. return new Minimatch$1(pattern, options || {}).makeRe()
  21217. };
  21218. Minimatch$1.prototype.makeRe = makeRe;
  21219. function makeRe () {
  21220. if (this.regexp || this.regexp === false) return this.regexp
  21221. // at this point, this.set is a 2d array of partial
  21222. // pattern strings, or "**".
  21223. //
  21224. // It's better to use .match(). This function shouldn't
  21225. // be used, really, but it's pretty convenient sometimes,
  21226. // when you just want to work with a regex.
  21227. var set = this.set;
  21228. if (!set.length) {
  21229. this.regexp = false;
  21230. return this.regexp
  21231. }
  21232. var options = this.options;
  21233. var twoStar = options.noglobstar ? star
  21234. : options.dot ? twoStarDot
  21235. : twoStarNoDot;
  21236. var flags = options.nocase ? 'i' : '';
  21237. var re = set.map(function (pattern) {
  21238. return pattern.map(function (p) {
  21239. return (p === GLOBSTAR) ? twoStar
  21240. : (typeof p === 'string') ? regExpEscape(p)
  21241. : p._src
  21242. }).join('\\\/')
  21243. }).join('|');
  21244. // must match entire pattern
  21245. // ending in a * or ** will make it less strict.
  21246. re = '^(?:' + re + ')$';
  21247. // can match anything, as long as it's not this.
  21248. if (this.negate) re = '^(?!' + re + ').*$';
  21249. try {
  21250. this.regexp = new RegExp(re, flags);
  21251. } catch (ex) /* istanbul ignore next - should be impossible */ {
  21252. this.regexp = false;
  21253. }
  21254. return this.regexp
  21255. }
  21256. minimatch.match = function (list, pattern, options) {
  21257. options = options || {};
  21258. var mm = new Minimatch$1(pattern, options);
  21259. list = list.filter(function (f) {
  21260. return mm.match(f)
  21261. });
  21262. if (mm.options.nonull && !list.length) {
  21263. list.push(pattern);
  21264. }
  21265. return list
  21266. };
  21267. Minimatch$1.prototype.match = function match (f, partial) {
  21268. if (typeof partial === 'undefined') partial = this.partial;
  21269. this.debug('match', f, this.pattern);
  21270. // short-circuit in the case of busted things.
  21271. // comments, etc.
  21272. if (this.comment) return false
  21273. if (this.empty) return f === ''
  21274. if (f === '/' && partial) return true
  21275. var options = this.options;
  21276. // windows: need to use /, not \
  21277. if (path.sep !== '/') {
  21278. f = f.split(path.sep).join('/');
  21279. }
  21280. // treat the test path as a set of pathparts.
  21281. f = f.split(slashSplit);
  21282. this.debug(this.pattern, 'split', f);
  21283. // just ONE of the pattern sets in this.set needs to match
  21284. // in order for it to be valid. If negating, then just one
  21285. // match means that we have failed.
  21286. // Either way, return on the first hit.
  21287. var set = this.set;
  21288. this.debug(this.pattern, 'set', set);
  21289. // Find the basename of the path by looking for the last non-empty segment
  21290. var filename;
  21291. var i;
  21292. for (i = f.length - 1; i >= 0; i--) {
  21293. filename = f[i];
  21294. if (filename) break
  21295. }
  21296. for (i = 0; i < set.length; i++) {
  21297. var pattern = set[i];
  21298. var file = f;
  21299. if (options.matchBase && pattern.length === 1) {
  21300. file = [filename];
  21301. }
  21302. var hit = this.matchOne(file, pattern, partial);
  21303. if (hit) {
  21304. if (options.flipNegate) return true
  21305. return !this.negate
  21306. }
  21307. }
  21308. // didn't get any hits. this is success if it's a negative
  21309. // pattern, failure otherwise.
  21310. if (options.flipNegate) return false
  21311. return this.negate
  21312. };
  21313. // set partial to true to test if, for example,
  21314. // "/a/b" matches the start of "/*/b/*/d"
  21315. // Partial means, if you run out of file before you run
  21316. // out of pattern, then that's fine, as long as all
  21317. // the parts match.
  21318. Minimatch$1.prototype.matchOne = function (file, pattern, partial) {
  21319. var options = this.options;
  21320. this.debug('matchOne',
  21321. { 'this': this, file: file, pattern: pattern });
  21322. this.debug('matchOne', file.length, pattern.length);
  21323. for (var fi = 0,
  21324. pi = 0,
  21325. fl = file.length,
  21326. pl = pattern.length
  21327. ; (fi < fl) && (pi < pl)
  21328. ; fi++, pi++) {
  21329. this.debug('matchOne loop');
  21330. var p = pattern[pi];
  21331. var f = file[fi];
  21332. this.debug(pattern, p, f);
  21333. // should be impossible.
  21334. // some invalid regexp stuff in the set.
  21335. /* istanbul ignore if */
  21336. if (p === false) return false
  21337. if (p === GLOBSTAR) {
  21338. this.debug('GLOBSTAR', [pattern, p, f]);
  21339. // "**"
  21340. // a/**/b/**/c would match the following:
  21341. // a/b/x/y/z/c
  21342. // a/x/y/z/b/c
  21343. // a/b/x/b/x/c
  21344. // a/b/c
  21345. // To do this, take the rest of the pattern after
  21346. // the **, and see if it would match the file remainder.
  21347. // If so, return success.
  21348. // If not, the ** "swallows" a segment, and try again.
  21349. // This is recursively awful.
  21350. //
  21351. // a/**/b/**/c matching a/b/x/y/z/c
  21352. // - a matches a
  21353. // - doublestar
  21354. // - matchOne(b/x/y/z/c, b/**/c)
  21355. // - b matches b
  21356. // - doublestar
  21357. // - matchOne(x/y/z/c, c) -> no
  21358. // - matchOne(y/z/c, c) -> no
  21359. // - matchOne(z/c, c) -> no
  21360. // - matchOne(c, c) yes, hit
  21361. var fr = fi;
  21362. var pr = pi + 1;
  21363. if (pr === pl) {
  21364. this.debug('** at the end');
  21365. // a ** at the end will just swallow the rest.
  21366. // We have found a match.
  21367. // however, it will not swallow /.x, unless
  21368. // options.dot is set.
  21369. // . and .. are *never* matched by **, for explosively
  21370. // exponential reasons.
  21371. for (; fi < fl; fi++) {
  21372. if (file[fi] === '.' || file[fi] === '..' ||
  21373. (!options.dot && file[fi].charAt(0) === '.')) return false
  21374. }
  21375. return true
  21376. }
  21377. // ok, let's see if we can swallow whatever we can.
  21378. while (fr < fl) {
  21379. var swallowee = file[fr];
  21380. this.debug('\nglobstar while', file, fr, pattern, pr, swallowee);
  21381. // XXX remove this slice. Just pass the start index.
  21382. if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
  21383. this.debug('globstar found match!', fr, fl, swallowee);
  21384. // found a match.
  21385. return true
  21386. } else {
  21387. // can't swallow "." or ".." ever.
  21388. // can only swallow ".foo" when explicitly asked.
  21389. if (swallowee === '.' || swallowee === '..' ||
  21390. (!options.dot && swallowee.charAt(0) === '.')) {
  21391. this.debug('dot detected!', file, fr, pattern, pr);
  21392. break
  21393. }
  21394. // ** swallows a segment, and continue.
  21395. this.debug('globstar swallow a segment, and continue');
  21396. fr++;
  21397. }
  21398. }
  21399. // no match was found.
  21400. // However, in partial mode, we can't say this is necessarily over.
  21401. // If there's more *pattern* left, then
  21402. /* istanbul ignore if */
  21403. if (partial) {
  21404. // ran out of file
  21405. this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
  21406. if (fr === fl) return true
  21407. }
  21408. return false
  21409. }
  21410. // something other than **
  21411. // non-magic patterns just have to match exactly
  21412. // patterns with magic have been turned into regexps.
  21413. var hit;
  21414. if (typeof p === 'string') {
  21415. hit = f === p;
  21416. this.debug('string match', p, f, hit);
  21417. } else {
  21418. hit = f.match(p);
  21419. this.debug('pattern match', p, f, hit);
  21420. }
  21421. if (!hit) return false
  21422. }
  21423. // Note: ending in / means that we'll get a final ""
  21424. // at the end of the pattern. This can only match a
  21425. // corresponding "" at the end of the file.
  21426. // If the file ends in /, then it can only match a
  21427. // a pattern that ends in /, unless the pattern just
  21428. // doesn't have any more for it. But, a/b/ should *not*
  21429. // match "a/b/*", even though "" matches against the
  21430. // [^/]*? pattern, except in partial mode, where it might
  21431. // simply not be reached yet.
  21432. // However, a/b/ should still satisfy a/*
  21433. // now either we fell off the end of the pattern, or we're done.
  21434. if (fi === fl && pi === pl) {
  21435. // ran out of pattern and filename at the same time.
  21436. // an exact hit!
  21437. return true
  21438. } else if (fi === fl) {
  21439. // ran out of file, but still had pattern left.
  21440. // this is ok if we're doing the match as part of
  21441. // a glob fs traversal.
  21442. return partial
  21443. } else /* istanbul ignore else */ if (pi === pl) {
  21444. // ran out of pattern, still have file left.
  21445. // this is only acceptable if we're on the very last
  21446. // empty segment of a file with a trailing slash.
  21447. // a/* should match a/b/
  21448. return (fi === fl - 1) && (file[fi] === '')
  21449. }
  21450. // should be unreachable.
  21451. /* istanbul ignore next */
  21452. throw new Error('wtf?')
  21453. };
  21454. // replace stuff like \* with *
  21455. function globUnescape (s) {
  21456. return s.replace(/\\(.)/g, '$1')
  21457. }
  21458. function regExpEscape (s) {
  21459. return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
  21460. }
  21461. var inherits_browser = createCommonjsModule(function (module) {
  21462. if (typeof Object.create === 'function') {
  21463. // implementation from standard node.js 'util' module
  21464. module.exports = function inherits(ctor, superCtor) {
  21465. if (superCtor) {
  21466. ctor.super_ = superCtor;
  21467. ctor.prototype = Object.create(superCtor.prototype, {
  21468. constructor: {
  21469. value: ctor,
  21470. enumerable: false,
  21471. writable: true,
  21472. configurable: true
  21473. }
  21474. });
  21475. }
  21476. };
  21477. } else {
  21478. // old school shim for old browsers
  21479. module.exports = function inherits(ctor, superCtor) {
  21480. if (superCtor) {
  21481. ctor.super_ = superCtor;
  21482. var TempCtor = function () {};
  21483. TempCtor.prototype = superCtor.prototype;
  21484. ctor.prototype = new TempCtor();
  21485. ctor.prototype.constructor = ctor;
  21486. }
  21487. };
  21488. }
  21489. }, "/$$rollup_base$$/node_modules/inherits");
  21490. var inherits = createCommonjsModule(function (module) {
  21491. try {
  21492. var util = require$$0__default["default"];
  21493. /* istanbul ignore next */
  21494. if (typeof util.inherits !== 'function') throw '';
  21495. module.exports = util.inherits;
  21496. } catch (e) {
  21497. /* istanbul ignore next */
  21498. module.exports = inherits_browser;
  21499. }
  21500. }, "/$$rollup_base$$/node_modules/inherits");
  21501. function posix(path) {
  21502. return path.charAt(0) === '/';
  21503. }
  21504. function win32(path) {
  21505. // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56
  21506. var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/;
  21507. var result = splitDeviceRe.exec(path);
  21508. var device = result[1] || '';
  21509. var isUnc = Boolean(device && device.charAt(1) !== ':');
  21510. // UNC paths are always absolute
  21511. return Boolean(result[2] || isUnc);
  21512. }
  21513. var pathIsAbsolute = process.platform === 'win32' ? win32 : posix;
  21514. var posix_1 = posix;
  21515. var win32_1 = win32;
  21516. pathIsAbsolute.posix = posix_1;
  21517. pathIsAbsolute.win32 = win32_1;
  21518. var setopts_1 = setopts$2;
  21519. var ownProp_1 = ownProp$2;
  21520. var makeAbs_1 = makeAbs;
  21521. var finish_1 = finish;
  21522. var mark_1 = mark;
  21523. var isIgnored_1 = isIgnored$2;
  21524. var childrenIgnored_1 = childrenIgnored$2;
  21525. function ownProp$2 (obj, field) {
  21526. return Object.prototype.hasOwnProperty.call(obj, field)
  21527. }
  21528. var Minimatch = minimatch_1.Minimatch;
  21529. function alphasort (a, b) {
  21530. return a.localeCompare(b, 'en')
  21531. }
  21532. function setupIgnores (self, options) {
  21533. self.ignore = options.ignore || [];
  21534. if (!Array.isArray(self.ignore))
  21535. self.ignore = [self.ignore];
  21536. if (self.ignore.length) {
  21537. self.ignore = self.ignore.map(ignoreMap);
  21538. }
  21539. }
  21540. // ignore patterns are always in dot:true mode.
  21541. function ignoreMap (pattern) {
  21542. var gmatcher = null;
  21543. if (pattern.slice(-3) === '/**') {
  21544. var gpattern = pattern.replace(/(\/\*\*)+$/, '');
  21545. gmatcher = new Minimatch(gpattern, { dot: true });
  21546. }
  21547. return {
  21548. matcher: new Minimatch(pattern, { dot: true }),
  21549. gmatcher: gmatcher
  21550. }
  21551. }
  21552. function setopts$2 (self, pattern, options) {
  21553. if (!options)
  21554. options = {};
  21555. // base-matching: just use globstar for that.
  21556. if (options.matchBase && -1 === pattern.indexOf("/")) {
  21557. if (options.noglobstar) {
  21558. throw new Error("base matching requires globstar")
  21559. }
  21560. pattern = "**/" + pattern;
  21561. }
  21562. self.silent = !!options.silent;
  21563. self.pattern = pattern;
  21564. self.strict = options.strict !== false;
  21565. self.realpath = !!options.realpath;
  21566. self.realpathCache = options.realpathCache || Object.create(null);
  21567. self.follow = !!options.follow;
  21568. self.dot = !!options.dot;
  21569. self.mark = !!options.mark;
  21570. self.nodir = !!options.nodir;
  21571. if (self.nodir)
  21572. self.mark = true;
  21573. self.sync = !!options.sync;
  21574. self.nounique = !!options.nounique;
  21575. self.nonull = !!options.nonull;
  21576. self.nosort = !!options.nosort;
  21577. self.nocase = !!options.nocase;
  21578. self.stat = !!options.stat;
  21579. self.noprocess = !!options.noprocess;
  21580. self.absolute = !!options.absolute;
  21581. self.fs = options.fs || fs__default["default"];
  21582. self.maxLength = options.maxLength || Infinity;
  21583. self.cache = options.cache || Object.create(null);
  21584. self.statCache = options.statCache || Object.create(null);
  21585. self.symlinks = options.symlinks || Object.create(null);
  21586. setupIgnores(self, options);
  21587. self.changedCwd = false;
  21588. var cwd = process.cwd();
  21589. if (!ownProp$2(options, "cwd"))
  21590. self.cwd = cwd;
  21591. else {
  21592. self.cwd = path__default["default"].resolve(options.cwd);
  21593. self.changedCwd = self.cwd !== cwd;
  21594. }
  21595. self.root = options.root || path__default["default"].resolve(self.cwd, "/");
  21596. self.root = path__default["default"].resolve(self.root);
  21597. if (process.platform === "win32")
  21598. self.root = self.root.replace(/\\/g, "/");
  21599. // TODO: is an absolute `cwd` supposed to be resolved against `root`?
  21600. // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test')
  21601. self.cwdAbs = pathIsAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd);
  21602. if (process.platform === "win32")
  21603. self.cwdAbs = self.cwdAbs.replace(/\\/g, "/");
  21604. self.nomount = !!options.nomount;
  21605. // disable comments and negation in Minimatch.
  21606. // Note that they are not supported in Glob itself anyway.
  21607. options.nonegate = true;
  21608. options.nocomment = true;
  21609. self.minimatch = new Minimatch(pattern, options);
  21610. self.options = self.minimatch.options;
  21611. }
  21612. function finish (self) {
  21613. var nou = self.nounique;
  21614. var all = nou ? [] : Object.create(null);
  21615. for (var i = 0, l = self.matches.length; i < l; i ++) {
  21616. var matches = self.matches[i];
  21617. if (!matches || Object.keys(matches).length === 0) {
  21618. if (self.nonull) {
  21619. // do like the shell, and spit out the literal glob
  21620. var literal = self.minimatch.globSet[i];
  21621. if (nou)
  21622. all.push(literal);
  21623. else
  21624. all[literal] = true;
  21625. }
  21626. } else {
  21627. // had matches
  21628. var m = Object.keys(matches);
  21629. if (nou)
  21630. all.push.apply(all, m);
  21631. else
  21632. m.forEach(function (m) {
  21633. all[m] = true;
  21634. });
  21635. }
  21636. }
  21637. if (!nou)
  21638. all = Object.keys(all);
  21639. if (!self.nosort)
  21640. all = all.sort(alphasort);
  21641. // at *some* point we statted all of these
  21642. if (self.mark) {
  21643. for (var i = 0; i < all.length; i++) {
  21644. all[i] = self._mark(all[i]);
  21645. }
  21646. if (self.nodir) {
  21647. all = all.filter(function (e) {
  21648. var notDir = !(/\/$/.test(e));
  21649. var c = self.cache[e] || self.cache[makeAbs(self, e)];
  21650. if (notDir && c)
  21651. notDir = c !== 'DIR' && !Array.isArray(c);
  21652. return notDir
  21653. });
  21654. }
  21655. }
  21656. if (self.ignore.length)
  21657. all = all.filter(function(m) {
  21658. return !isIgnored$2(self, m)
  21659. });
  21660. self.found = all;
  21661. }
  21662. function mark (self, p) {
  21663. var abs = makeAbs(self, p);
  21664. var c = self.cache[abs];
  21665. var m = p;
  21666. if (c) {
  21667. var isDir = c === 'DIR' || Array.isArray(c);
  21668. var slash = p.slice(-1) === '/';
  21669. if (isDir && !slash)
  21670. m += '/';
  21671. else if (!isDir && slash)
  21672. m = m.slice(0, -1);
  21673. if (m !== p) {
  21674. var mabs = makeAbs(self, m);
  21675. self.statCache[mabs] = self.statCache[abs];
  21676. self.cache[mabs] = self.cache[abs];
  21677. }
  21678. }
  21679. return m
  21680. }
  21681. // lotta situps...
  21682. function makeAbs (self, f) {
  21683. var abs = f;
  21684. if (f.charAt(0) === '/') {
  21685. abs = path__default["default"].join(self.root, f);
  21686. } else if (pathIsAbsolute(f) || f === '') {
  21687. abs = f;
  21688. } else if (self.changedCwd) {
  21689. abs = path__default["default"].resolve(self.cwd, f);
  21690. } else {
  21691. abs = path__default["default"].resolve(f);
  21692. }
  21693. if (process.platform === 'win32')
  21694. abs = abs.replace(/\\/g, '/');
  21695. return abs
  21696. }
  21697. // Return true, if pattern ends with globstar '**', for the accompanying parent directory.
  21698. // Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents
  21699. function isIgnored$2 (self, path) {
  21700. if (!self.ignore.length)
  21701. return false
  21702. return self.ignore.some(function(item) {
  21703. return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path))
  21704. })
  21705. }
  21706. function childrenIgnored$2 (self, path) {
  21707. if (!self.ignore.length)
  21708. return false
  21709. return self.ignore.some(function(item) {
  21710. return !!(item.gmatcher && item.gmatcher.match(path))
  21711. })
  21712. }
  21713. var common = {
  21714. setopts: setopts_1,
  21715. ownProp: ownProp_1,
  21716. makeAbs: makeAbs_1,
  21717. finish: finish_1,
  21718. mark: mark_1,
  21719. isIgnored: isIgnored_1,
  21720. childrenIgnored: childrenIgnored_1
  21721. };
  21722. var require$$3 = glob_1;
  21723. var sync = globSync;
  21724. globSync.GlobSync = GlobSync$1;
  21725. minimatch_1.Minimatch;
  21726. require$$3.Glob;
  21727. var setopts$1 = common.setopts;
  21728. var ownProp$1 = common.ownProp;
  21729. var childrenIgnored$1 = common.childrenIgnored;
  21730. var isIgnored$1 = common.isIgnored;
  21731. function globSync (pattern, options) {
  21732. if (typeof options === 'function' || arguments.length === 3)
  21733. throw new TypeError('callback provided to sync glob\n'+
  21734. 'See: https://github.com/isaacs/node-glob/issues/167')
  21735. return new GlobSync$1(pattern, options).found
  21736. }
  21737. function GlobSync$1 (pattern, options) {
  21738. if (!pattern)
  21739. throw new Error('must provide pattern')
  21740. if (typeof options === 'function' || arguments.length === 3)
  21741. throw new TypeError('callback provided to sync glob\n'+
  21742. 'See: https://github.com/isaacs/node-glob/issues/167')
  21743. if (!(this instanceof GlobSync$1))
  21744. return new GlobSync$1(pattern, options)
  21745. setopts$1(this, pattern, options);
  21746. if (this.noprocess)
  21747. return this
  21748. var n = this.minimatch.set.length;
  21749. this.matches = new Array(n);
  21750. for (var i = 0; i < n; i ++) {
  21751. this._process(this.minimatch.set[i], i, false);
  21752. }
  21753. this._finish();
  21754. }
  21755. GlobSync$1.prototype._finish = function () {
  21756. assert__default["default"](this instanceof GlobSync$1);
  21757. if (this.realpath) {
  21758. var self = this;
  21759. this.matches.forEach(function (matchset, index) {
  21760. var set = self.matches[index] = Object.create(null);
  21761. for (var p in matchset) {
  21762. try {
  21763. p = self._makeAbs(p);
  21764. var real = fs_realpath.realpathSync(p, self.realpathCache);
  21765. set[real] = true;
  21766. } catch (er) {
  21767. if (er.syscall === 'stat')
  21768. set[self._makeAbs(p)] = true;
  21769. else
  21770. throw er
  21771. }
  21772. }
  21773. });
  21774. }
  21775. common.finish(this);
  21776. };
  21777. GlobSync$1.prototype._process = function (pattern, index, inGlobStar) {
  21778. assert__default["default"](this instanceof GlobSync$1);
  21779. // Get the first [n] parts of pattern that are all strings.
  21780. var n = 0;
  21781. while (typeof pattern[n] === 'string') {
  21782. n ++;
  21783. }
  21784. // now n is the index of the first one that is *not* a string.
  21785. // See if there's anything else
  21786. var prefix;
  21787. switch (n) {
  21788. // if not, then this is rather simple
  21789. case pattern.length:
  21790. this._processSimple(pattern.join('/'), index);
  21791. return
  21792. case 0:
  21793. // pattern *starts* with some non-trivial item.
  21794. // going to readdir(cwd), but not include the prefix in matches.
  21795. prefix = null;
  21796. break
  21797. default:
  21798. // pattern has some string bits in the front.
  21799. // whatever it starts with, whether that's 'absolute' like /foo/bar,
  21800. // or 'relative' like '../baz'
  21801. prefix = pattern.slice(0, n).join('/');
  21802. break
  21803. }
  21804. var remain = pattern.slice(n);
  21805. // get the list of entries.
  21806. var read;
  21807. if (prefix === null)
  21808. read = '.';
  21809. else if (pathIsAbsolute(prefix) || pathIsAbsolute(pattern.join('/'))) {
  21810. if (!prefix || !pathIsAbsolute(prefix))
  21811. prefix = '/' + prefix;
  21812. read = prefix;
  21813. } else
  21814. read = prefix;
  21815. var abs = this._makeAbs(read);
  21816. //if ignored, skip processing
  21817. if (childrenIgnored$1(this, read))
  21818. return
  21819. var isGlobStar = remain[0] === minimatch_1.GLOBSTAR;
  21820. if (isGlobStar)
  21821. this._processGlobStar(prefix, read, abs, remain, index, inGlobStar);
  21822. else
  21823. this._processReaddir(prefix, read, abs, remain, index, inGlobStar);
  21824. };
  21825. GlobSync$1.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) {
  21826. var entries = this._readdir(abs, inGlobStar);
  21827. // if the abs isn't a dir, then nothing can match!
  21828. if (!entries)
  21829. return
  21830. // It will only match dot entries if it starts with a dot, or if
  21831. // dot is set. Stuff like @(.foo|.bar) isn't allowed.
  21832. var pn = remain[0];
  21833. var negate = !!this.minimatch.negate;
  21834. var rawGlob = pn._glob;
  21835. var dotOk = this.dot || rawGlob.charAt(0) === '.';
  21836. var matchedEntries = [];
  21837. for (var i = 0; i < entries.length; i++) {
  21838. var e = entries[i];
  21839. if (e.charAt(0) !== '.' || dotOk) {
  21840. var m;
  21841. if (negate && !prefix) {
  21842. m = !e.match(pn);
  21843. } else {
  21844. m = e.match(pn);
  21845. }
  21846. if (m)
  21847. matchedEntries.push(e);
  21848. }
  21849. }
  21850. var len = matchedEntries.length;
  21851. // If there are no matched entries, then nothing matches.
  21852. if (len === 0)
  21853. return
  21854. // if this is the last remaining pattern bit, then no need for
  21855. // an additional stat *unless* the user has specified mark or
  21856. // stat explicitly. We know they exist, since readdir returned
  21857. // them.
  21858. if (remain.length === 1 && !this.mark && !this.stat) {
  21859. if (!this.matches[index])
  21860. this.matches[index] = Object.create(null);
  21861. for (var i = 0; i < len; i ++) {
  21862. var e = matchedEntries[i];
  21863. if (prefix) {
  21864. if (prefix.slice(-1) !== '/')
  21865. e = prefix + '/' + e;
  21866. else
  21867. e = prefix + e;
  21868. }
  21869. if (e.charAt(0) === '/' && !this.nomount) {
  21870. e = path__default["default"].join(this.root, e);
  21871. }
  21872. this._emitMatch(index, e);
  21873. }
  21874. // This was the last one, and no stats were needed
  21875. return
  21876. }
  21877. // now test all matched entries as stand-ins for that part
  21878. // of the pattern.
  21879. remain.shift();
  21880. for (var i = 0; i < len; i ++) {
  21881. var e = matchedEntries[i];
  21882. var newPattern;
  21883. if (prefix)
  21884. newPattern = [prefix, e];
  21885. else
  21886. newPattern = [e];
  21887. this._process(newPattern.concat(remain), index, inGlobStar);
  21888. }
  21889. };
  21890. GlobSync$1.prototype._emitMatch = function (index, e) {
  21891. if (isIgnored$1(this, e))
  21892. return
  21893. var abs = this._makeAbs(e);
  21894. if (this.mark)
  21895. e = this._mark(e);
  21896. if (this.absolute) {
  21897. e = abs;
  21898. }
  21899. if (this.matches[index][e])
  21900. return
  21901. if (this.nodir) {
  21902. var c = this.cache[abs];
  21903. if (c === 'DIR' || Array.isArray(c))
  21904. return
  21905. }
  21906. this.matches[index][e] = true;
  21907. if (this.stat)
  21908. this._stat(e);
  21909. };
  21910. GlobSync$1.prototype._readdirInGlobStar = function (abs) {
  21911. // follow all symlinked directories forever
  21912. // just proceed as if this is a non-globstar situation
  21913. if (this.follow)
  21914. return this._readdir(abs, false)
  21915. var entries;
  21916. var lstat;
  21917. try {
  21918. lstat = this.fs.lstatSync(abs);
  21919. } catch (er) {
  21920. if (er.code === 'ENOENT') {
  21921. // lstat failed, doesn't exist
  21922. return null
  21923. }
  21924. }
  21925. var isSym = lstat && lstat.isSymbolicLink();
  21926. this.symlinks[abs] = isSym;
  21927. // If it's not a symlink or a dir, then it's definitely a regular file.
  21928. // don't bother doing a readdir in that case.
  21929. if (!isSym && lstat && !lstat.isDirectory())
  21930. this.cache[abs] = 'FILE';
  21931. else
  21932. entries = this._readdir(abs, false);
  21933. return entries
  21934. };
  21935. GlobSync$1.prototype._readdir = function (abs, inGlobStar) {
  21936. if (inGlobStar && !ownProp$1(this.symlinks, abs))
  21937. return this._readdirInGlobStar(abs)
  21938. if (ownProp$1(this.cache, abs)) {
  21939. var c = this.cache[abs];
  21940. if (!c || c === 'FILE')
  21941. return null
  21942. if (Array.isArray(c))
  21943. return c
  21944. }
  21945. try {
  21946. return this._readdirEntries(abs, this.fs.readdirSync(abs))
  21947. } catch (er) {
  21948. this._readdirError(abs, er);
  21949. return null
  21950. }
  21951. };
  21952. GlobSync$1.prototype._readdirEntries = function (abs, entries) {
  21953. // if we haven't asked to stat everything, then just
  21954. // assume that everything in there exists, so we can avoid
  21955. // having to stat it a second time.
  21956. if (!this.mark && !this.stat) {
  21957. for (var i = 0; i < entries.length; i ++) {
  21958. var e = entries[i];
  21959. if (abs === '/')
  21960. e = abs + e;
  21961. else
  21962. e = abs + '/' + e;
  21963. this.cache[e] = true;
  21964. }
  21965. }
  21966. this.cache[abs] = entries;
  21967. // mark and cache dir-ness
  21968. return entries
  21969. };
  21970. GlobSync$1.prototype._readdirError = function (f, er) {
  21971. // handle errors, and cache the information
  21972. switch (er.code) {
  21973. case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
  21974. case 'ENOTDIR': // totally normal. means it *does* exist.
  21975. var abs = this._makeAbs(f);
  21976. this.cache[abs] = 'FILE';
  21977. if (abs === this.cwdAbs) {
  21978. var error = new Error(er.code + ' invalid cwd ' + this.cwd);
  21979. error.path = this.cwd;
  21980. error.code = er.code;
  21981. throw error
  21982. }
  21983. break
  21984. case 'ENOENT': // not terribly unusual
  21985. case 'ELOOP':
  21986. case 'ENAMETOOLONG':
  21987. case 'UNKNOWN':
  21988. this.cache[this._makeAbs(f)] = false;
  21989. break
  21990. default: // some unusual error. Treat as failure.
  21991. this.cache[this._makeAbs(f)] = false;
  21992. if (this.strict)
  21993. throw er
  21994. if (!this.silent)
  21995. console.error('glob error', er);
  21996. break
  21997. }
  21998. };
  21999. GlobSync$1.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) {
  22000. var entries = this._readdir(abs, inGlobStar);
  22001. // no entries means not a dir, so it can never have matches
  22002. // foo.txt/** doesn't match foo.txt
  22003. if (!entries)
  22004. return
  22005. // test without the globstar, and with every child both below
  22006. // and replacing the globstar.
  22007. var remainWithoutGlobStar = remain.slice(1);
  22008. var gspref = prefix ? [ prefix ] : [];
  22009. var noGlobStar = gspref.concat(remainWithoutGlobStar);
  22010. // the noGlobStar pattern exits the inGlobStar state
  22011. this._process(noGlobStar, index, false);
  22012. var len = entries.length;
  22013. var isSym = this.symlinks[abs];
  22014. // If it's a symlink, and we're in a globstar, then stop
  22015. if (isSym && inGlobStar)
  22016. return
  22017. for (var i = 0; i < len; i++) {
  22018. var e = entries[i];
  22019. if (e.charAt(0) === '.' && !this.dot)
  22020. continue
  22021. // these two cases enter the inGlobStar state
  22022. var instead = gspref.concat(entries[i], remainWithoutGlobStar);
  22023. this._process(instead, index, true);
  22024. var below = gspref.concat(entries[i], remain);
  22025. this._process(below, index, true);
  22026. }
  22027. };
  22028. GlobSync$1.prototype._processSimple = function (prefix, index) {
  22029. // XXX review this. Shouldn't it be doing the mounting etc
  22030. // before doing stat? kinda weird?
  22031. var exists = this._stat(prefix);
  22032. if (!this.matches[index])
  22033. this.matches[index] = Object.create(null);
  22034. // If it doesn't exist, then just mark the lack of results
  22035. if (!exists)
  22036. return
  22037. if (prefix && pathIsAbsolute(prefix) && !this.nomount) {
  22038. var trail = /[\/\\]$/.test(prefix);
  22039. if (prefix.charAt(0) === '/') {
  22040. prefix = path__default["default"].join(this.root, prefix);
  22041. } else {
  22042. prefix = path__default["default"].resolve(this.root, prefix);
  22043. if (trail)
  22044. prefix += '/';
  22045. }
  22046. }
  22047. if (process.platform === 'win32')
  22048. prefix = prefix.replace(/\\/g, '/');
  22049. // Mark this as a match
  22050. this._emitMatch(index, prefix);
  22051. };
  22052. // Returns either 'DIR', 'FILE', or false
  22053. GlobSync$1.prototype._stat = function (f) {
  22054. var abs = this._makeAbs(f);
  22055. var needDir = f.slice(-1) === '/';
  22056. if (f.length > this.maxLength)
  22057. return false
  22058. if (!this.stat && ownProp$1(this.cache, abs)) {
  22059. var c = this.cache[abs];
  22060. if (Array.isArray(c))
  22061. c = 'DIR';
  22062. // It exists, but maybe not how we need it
  22063. if (!needDir || c === 'DIR')
  22064. return c
  22065. if (needDir && c === 'FILE')
  22066. return false
  22067. // otherwise we have to stat, because maybe c=true
  22068. // if we know it exists, but not what it is.
  22069. }
  22070. var stat = this.statCache[abs];
  22071. if (!stat) {
  22072. var lstat;
  22073. try {
  22074. lstat = this.fs.lstatSync(abs);
  22075. } catch (er) {
  22076. if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
  22077. this.statCache[abs] = false;
  22078. return false
  22079. }
  22080. }
  22081. if (lstat && lstat.isSymbolicLink()) {
  22082. try {
  22083. stat = this.fs.statSync(abs);
  22084. } catch (er) {
  22085. stat = lstat;
  22086. }
  22087. } else {
  22088. stat = lstat;
  22089. }
  22090. }
  22091. this.statCache[abs] = stat;
  22092. var c = true;
  22093. if (stat)
  22094. c = stat.isDirectory() ? 'DIR' : 'FILE';
  22095. this.cache[abs] = this.cache[abs] || c;
  22096. if (needDir && c === 'FILE')
  22097. return false
  22098. return c
  22099. };
  22100. GlobSync$1.prototype._mark = function (p) {
  22101. return common.mark(this, p)
  22102. };
  22103. GlobSync$1.prototype._makeAbs = function (f) {
  22104. return common.makeAbs(this, f)
  22105. };
  22106. // Returns a wrapper function that returns a wrapped callback
  22107. // The wrapper function should do some stuff, and return a
  22108. // presumably different callback function.
  22109. // This makes sure that own properties are retained, so that
  22110. // decorations and such are not lost along the way.
  22111. var wrappy_1 = wrappy;
  22112. function wrappy (fn, cb) {
  22113. if (fn && cb) return wrappy(fn)(cb)
  22114. if (typeof fn !== 'function')
  22115. throw new TypeError('need wrapper function')
  22116. Object.keys(fn).forEach(function (k) {
  22117. wrapper[k] = fn[k];
  22118. });
  22119. return wrapper
  22120. function wrapper() {
  22121. var args = new Array(arguments.length);
  22122. for (var i = 0; i < args.length; i++) {
  22123. args[i] = arguments[i];
  22124. }
  22125. var ret = fn.apply(this, args);
  22126. var cb = args[args.length-1];
  22127. if (typeof ret === 'function' && ret !== cb) {
  22128. Object.keys(cb).forEach(function (k) {
  22129. ret[k] = cb[k];
  22130. });
  22131. }
  22132. return ret
  22133. }
  22134. }
  22135. var once_1 = wrappy_1(once);
  22136. var strict = wrappy_1(onceStrict);
  22137. once.proto = once(function () {
  22138. Object.defineProperty(Function.prototype, 'once', {
  22139. value: function () {
  22140. return once(this)
  22141. },
  22142. configurable: true
  22143. });
  22144. Object.defineProperty(Function.prototype, 'onceStrict', {
  22145. value: function () {
  22146. return onceStrict(this)
  22147. },
  22148. configurable: true
  22149. });
  22150. });
  22151. function once (fn) {
  22152. var f = function () {
  22153. if (f.called) return f.value
  22154. f.called = true;
  22155. return f.value = fn.apply(this, arguments)
  22156. };
  22157. f.called = false;
  22158. return f
  22159. }
  22160. function onceStrict (fn) {
  22161. var f = function () {
  22162. if (f.called)
  22163. throw new Error(f.onceError)
  22164. f.called = true;
  22165. return f.value = fn.apply(this, arguments)
  22166. };
  22167. var name = fn.name || 'Function wrapped with `once`';
  22168. f.onceError = name + " shouldn't be called more than once";
  22169. f.called = false;
  22170. return f
  22171. }
  22172. once_1.strict = strict;
  22173. var reqs = Object.create(null);
  22174. var inflight_1 = wrappy_1(inflight);
  22175. function inflight (key, cb) {
  22176. if (reqs[key]) {
  22177. reqs[key].push(cb);
  22178. return null
  22179. } else {
  22180. reqs[key] = [cb];
  22181. return makeres(key)
  22182. }
  22183. }
  22184. function makeres (key) {
  22185. return once_1(function RES () {
  22186. var cbs = reqs[key];
  22187. var len = cbs.length;
  22188. var args = slice(arguments);
  22189. // XXX It's somewhat ambiguous whether a new callback added in this
  22190. // pass should be queued for later execution if something in the
  22191. // list of callbacks throws, or if it should just be discarded.
  22192. // However, it's such an edge case that it hardly matters, and either
  22193. // choice is likely as surprising as the other.
  22194. // As it happens, we do go ahead and schedule it for later execution.
  22195. try {
  22196. for (var i = 0; i < len; i++) {
  22197. cbs[i].apply(null, args);
  22198. }
  22199. } finally {
  22200. if (cbs.length > len) {
  22201. // added more in the interim.
  22202. // de-zalgo, just in case, but don't call again.
  22203. cbs.splice(0, len);
  22204. process.nextTick(function () {
  22205. RES.apply(null, args);
  22206. });
  22207. } else {
  22208. delete reqs[key];
  22209. }
  22210. }
  22211. })
  22212. }
  22213. function slice (args) {
  22214. var length = args.length;
  22215. var array = [];
  22216. for (var i = 0; i < length; i++) array[i] = args[i];
  22217. return array
  22218. }
  22219. // Approach:
  22220. //
  22221. // 1. Get the minimatch set
  22222. // 2. For each pattern in the set, PROCESS(pattern, false)
  22223. // 3. Store matches per-set, then uniq them
  22224. //
  22225. // PROCESS(pattern, inGlobStar)
  22226. // Get the first [n] items from pattern that are all strings
  22227. // Join these together. This is PREFIX.
  22228. // If there is no more remaining, then stat(PREFIX) and
  22229. // add to matches if it succeeds. END.
  22230. //
  22231. // If inGlobStar and PREFIX is symlink and points to dir
  22232. // set ENTRIES = []
  22233. // else readdir(PREFIX) as ENTRIES
  22234. // If fail, END
  22235. //
  22236. // with ENTRIES
  22237. // If pattern[n] is GLOBSTAR
  22238. // // handle the case where the globstar match is empty
  22239. // // by pruning it out, and testing the resulting pattern
  22240. // PROCESS(pattern[0..n] + pattern[n+1 .. $], false)
  22241. // // handle other cases.
  22242. // for ENTRY in ENTRIES (not dotfiles)
  22243. // // attach globstar + tail onto the entry
  22244. // // Mark that this entry is a globstar match
  22245. // PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true)
  22246. //
  22247. // else // not globstar
  22248. // for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot)
  22249. // Test ENTRY against pattern[n]
  22250. // If fails, continue
  22251. // If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $])
  22252. //
  22253. // Caveat:
  22254. // Cache all stats and readdirs results to minimize syscall. Since all
  22255. // we ever care about is existence and directory-ness, we can just keep
  22256. // `true` for files, and [children,...] for directories, or `false` for
  22257. // things that don't exist.
  22258. var glob_1 = glob;
  22259. minimatch_1.Minimatch;
  22260. var EE = require$$0__default$1["default"].EventEmitter;
  22261. var setopts = common.setopts;
  22262. var ownProp = common.ownProp;
  22263. var childrenIgnored = common.childrenIgnored;
  22264. var isIgnored = common.isIgnored;
  22265. function glob (pattern, options, cb) {
  22266. if (typeof options === 'function') cb = options, options = {};
  22267. if (!options) options = {};
  22268. if (options.sync) {
  22269. if (cb)
  22270. throw new TypeError('callback provided to sync glob')
  22271. return sync(pattern, options)
  22272. }
  22273. return new Glob(pattern, options, cb)
  22274. }
  22275. glob.sync = sync;
  22276. var GlobSync = glob.GlobSync = sync.GlobSync;
  22277. // old api surface
  22278. glob.glob = glob;
  22279. function extend (origin, add) {
  22280. if (add === null || typeof add !== 'object') {
  22281. return origin
  22282. }
  22283. var keys = Object.keys(add);
  22284. var i = keys.length;
  22285. while (i--) {
  22286. origin[keys[i]] = add[keys[i]];
  22287. }
  22288. return origin
  22289. }
  22290. glob.hasMagic = function (pattern, options_) {
  22291. var options = extend({}, options_);
  22292. options.noprocess = true;
  22293. var g = new Glob(pattern, options);
  22294. var set = g.minimatch.set;
  22295. if (!pattern)
  22296. return false
  22297. if (set.length > 1)
  22298. return true
  22299. for (var j = 0; j < set[0].length; j++) {
  22300. if (typeof set[0][j] !== 'string')
  22301. return true
  22302. }
  22303. return false
  22304. };
  22305. glob.Glob = Glob;
  22306. inherits(Glob, EE);
  22307. function Glob (pattern, options, cb) {
  22308. if (typeof options === 'function') {
  22309. cb = options;
  22310. options = null;
  22311. }
  22312. if (options && options.sync) {
  22313. if (cb)
  22314. throw new TypeError('callback provided to sync glob')
  22315. return new GlobSync(pattern, options)
  22316. }
  22317. if (!(this instanceof Glob))
  22318. return new Glob(pattern, options, cb)
  22319. setopts(this, pattern, options);
  22320. this._didRealPath = false;
  22321. // process each pattern in the minimatch set
  22322. var n = this.minimatch.set.length;
  22323. // The matches are stored as {<filename>: true,...} so that
  22324. // duplicates are automagically pruned.
  22325. // Later, we do an Object.keys() on these.
  22326. // Keep them as a list so we can fill in when nonull is set.
  22327. this.matches = new Array(n);
  22328. if (typeof cb === 'function') {
  22329. cb = once_1(cb);
  22330. this.on('error', cb);
  22331. this.on('end', function (matches) {
  22332. cb(null, matches);
  22333. });
  22334. }
  22335. var self = this;
  22336. this._processing = 0;
  22337. this._emitQueue = [];
  22338. this._processQueue = [];
  22339. this.paused = false;
  22340. if (this.noprocess)
  22341. return this
  22342. if (n === 0)
  22343. return done()
  22344. var sync = true;
  22345. for (var i = 0; i < n; i ++) {
  22346. this._process(this.minimatch.set[i], i, false, done);
  22347. }
  22348. sync = false;
  22349. function done () {
  22350. --self._processing;
  22351. if (self._processing <= 0) {
  22352. if (sync) {
  22353. process.nextTick(function () {
  22354. self._finish();
  22355. });
  22356. } else {
  22357. self._finish();
  22358. }
  22359. }
  22360. }
  22361. }
  22362. Glob.prototype._finish = function () {
  22363. assert__default["default"](this instanceof Glob);
  22364. if (this.aborted)
  22365. return
  22366. if (this.realpath && !this._didRealpath)
  22367. return this._realpath()
  22368. common.finish(this);
  22369. this.emit('end', this.found);
  22370. };
  22371. Glob.prototype._realpath = function () {
  22372. if (this._didRealpath)
  22373. return
  22374. this._didRealpath = true;
  22375. var n = this.matches.length;
  22376. if (n === 0)
  22377. return this._finish()
  22378. var self = this;
  22379. for (var i = 0; i < this.matches.length; i++)
  22380. this._realpathSet(i, next);
  22381. function next () {
  22382. if (--n === 0)
  22383. self._finish();
  22384. }
  22385. };
  22386. Glob.prototype._realpathSet = function (index, cb) {
  22387. var matchset = this.matches[index];
  22388. if (!matchset)
  22389. return cb()
  22390. var found = Object.keys(matchset);
  22391. var self = this;
  22392. var n = found.length;
  22393. if (n === 0)
  22394. return cb()
  22395. var set = this.matches[index] = Object.create(null);
  22396. found.forEach(function (p, i) {
  22397. // If there's a problem with the stat, then it means that
  22398. // one or more of the links in the realpath couldn't be
  22399. // resolved. just return the abs value in that case.
  22400. p = self._makeAbs(p);
  22401. fs_realpath.realpath(p, self.realpathCache, function (er, real) {
  22402. if (!er)
  22403. set[real] = true;
  22404. else if (er.syscall === 'stat')
  22405. set[p] = true;
  22406. else
  22407. self.emit('error', er); // srsly wtf right here
  22408. if (--n === 0) {
  22409. self.matches[index] = set;
  22410. cb();
  22411. }
  22412. });
  22413. });
  22414. };
  22415. Glob.prototype._mark = function (p) {
  22416. return common.mark(this, p)
  22417. };
  22418. Glob.prototype._makeAbs = function (f) {
  22419. return common.makeAbs(this, f)
  22420. };
  22421. Glob.prototype.abort = function () {
  22422. this.aborted = true;
  22423. this.emit('abort');
  22424. };
  22425. Glob.prototype.pause = function () {
  22426. if (!this.paused) {
  22427. this.paused = true;
  22428. this.emit('pause');
  22429. }
  22430. };
  22431. Glob.prototype.resume = function () {
  22432. if (this.paused) {
  22433. this.emit('resume');
  22434. this.paused = false;
  22435. if (this._emitQueue.length) {
  22436. var eq = this._emitQueue.slice(0);
  22437. this._emitQueue.length = 0;
  22438. for (var i = 0; i < eq.length; i ++) {
  22439. var e = eq[i];
  22440. this._emitMatch(e[0], e[1]);
  22441. }
  22442. }
  22443. if (this._processQueue.length) {
  22444. var pq = this._processQueue.slice(0);
  22445. this._processQueue.length = 0;
  22446. for (var i = 0; i < pq.length; i ++) {
  22447. var p = pq[i];
  22448. this._processing--;
  22449. this._process(p[0], p[1], p[2], p[3]);
  22450. }
  22451. }
  22452. }
  22453. };
  22454. Glob.prototype._process = function (pattern, index, inGlobStar, cb) {
  22455. assert__default["default"](this instanceof Glob);
  22456. assert__default["default"](typeof cb === 'function');
  22457. if (this.aborted)
  22458. return
  22459. this._processing++;
  22460. if (this.paused) {
  22461. this._processQueue.push([pattern, index, inGlobStar, cb]);
  22462. return
  22463. }
  22464. //console.error('PROCESS %d', this._processing, pattern)
  22465. // Get the first [n] parts of pattern that are all strings.
  22466. var n = 0;
  22467. while (typeof pattern[n] === 'string') {
  22468. n ++;
  22469. }
  22470. // now n is the index of the first one that is *not* a string.
  22471. // see if there's anything else
  22472. var prefix;
  22473. switch (n) {
  22474. // if not, then this is rather simple
  22475. case pattern.length:
  22476. this._processSimple(pattern.join('/'), index, cb);
  22477. return
  22478. case 0:
  22479. // pattern *starts* with some non-trivial item.
  22480. // going to readdir(cwd), but not include the prefix in matches.
  22481. prefix = null;
  22482. break
  22483. default:
  22484. // pattern has some string bits in the front.
  22485. // whatever it starts with, whether that's 'absolute' like /foo/bar,
  22486. // or 'relative' like '../baz'
  22487. prefix = pattern.slice(0, n).join('/');
  22488. break
  22489. }
  22490. var remain = pattern.slice(n);
  22491. // get the list of entries.
  22492. var read;
  22493. if (prefix === null)
  22494. read = '.';
  22495. else if (pathIsAbsolute(prefix) || pathIsAbsolute(pattern.join('/'))) {
  22496. if (!prefix || !pathIsAbsolute(prefix))
  22497. prefix = '/' + prefix;
  22498. read = prefix;
  22499. } else
  22500. read = prefix;
  22501. var abs = this._makeAbs(read);
  22502. //if ignored, skip _processing
  22503. if (childrenIgnored(this, read))
  22504. return cb()
  22505. var isGlobStar = remain[0] === minimatch_1.GLOBSTAR;
  22506. if (isGlobStar)
  22507. this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb);
  22508. else
  22509. this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb);
  22510. };
  22511. Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) {
  22512. var self = this;
  22513. this._readdir(abs, inGlobStar, function (er, entries) {
  22514. return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb)
  22515. });
  22516. };
  22517. Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
  22518. // if the abs isn't a dir, then nothing can match!
  22519. if (!entries)
  22520. return cb()
  22521. // It will only match dot entries if it starts with a dot, or if
  22522. // dot is set. Stuff like @(.foo|.bar) isn't allowed.
  22523. var pn = remain[0];
  22524. var negate = !!this.minimatch.negate;
  22525. var rawGlob = pn._glob;
  22526. var dotOk = this.dot || rawGlob.charAt(0) === '.';
  22527. var matchedEntries = [];
  22528. for (var i = 0; i < entries.length; i++) {
  22529. var e = entries[i];
  22530. if (e.charAt(0) !== '.' || dotOk) {
  22531. var m;
  22532. if (negate && !prefix) {
  22533. m = !e.match(pn);
  22534. } else {
  22535. m = e.match(pn);
  22536. }
  22537. if (m)
  22538. matchedEntries.push(e);
  22539. }
  22540. }
  22541. //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries)
  22542. var len = matchedEntries.length;
  22543. // If there are no matched entries, then nothing matches.
  22544. if (len === 0)
  22545. return cb()
  22546. // if this is the last remaining pattern bit, then no need for
  22547. // an additional stat *unless* the user has specified mark or
  22548. // stat explicitly. We know they exist, since readdir returned
  22549. // them.
  22550. if (remain.length === 1 && !this.mark && !this.stat) {
  22551. if (!this.matches[index])
  22552. this.matches[index] = Object.create(null);
  22553. for (var i = 0; i < len; i ++) {
  22554. var e = matchedEntries[i];
  22555. if (prefix) {
  22556. if (prefix !== '/')
  22557. e = prefix + '/' + e;
  22558. else
  22559. e = prefix + e;
  22560. }
  22561. if (e.charAt(0) === '/' && !this.nomount) {
  22562. e = path__default["default"].join(this.root, e);
  22563. }
  22564. this._emitMatch(index, e);
  22565. }
  22566. // This was the last one, and no stats were needed
  22567. return cb()
  22568. }
  22569. // now test all matched entries as stand-ins for that part
  22570. // of the pattern.
  22571. remain.shift();
  22572. for (var i = 0; i < len; i ++) {
  22573. var e = matchedEntries[i];
  22574. if (prefix) {
  22575. if (prefix !== '/')
  22576. e = prefix + '/' + e;
  22577. else
  22578. e = prefix + e;
  22579. }
  22580. this._process([e].concat(remain), index, inGlobStar, cb);
  22581. }
  22582. cb();
  22583. };
  22584. Glob.prototype._emitMatch = function (index, e) {
  22585. if (this.aborted)
  22586. return
  22587. if (isIgnored(this, e))
  22588. return
  22589. if (this.paused) {
  22590. this._emitQueue.push([index, e]);
  22591. return
  22592. }
  22593. var abs = pathIsAbsolute(e) ? e : this._makeAbs(e);
  22594. if (this.mark)
  22595. e = this._mark(e);
  22596. if (this.absolute)
  22597. e = abs;
  22598. if (this.matches[index][e])
  22599. return
  22600. if (this.nodir) {
  22601. var c = this.cache[abs];
  22602. if (c === 'DIR' || Array.isArray(c))
  22603. return
  22604. }
  22605. this.matches[index][e] = true;
  22606. var st = this.statCache[abs];
  22607. if (st)
  22608. this.emit('stat', e, st);
  22609. this.emit('match', e);
  22610. };
  22611. Glob.prototype._readdirInGlobStar = function (abs, cb) {
  22612. if (this.aborted)
  22613. return
  22614. // follow all symlinked directories forever
  22615. // just proceed as if this is a non-globstar situation
  22616. if (this.follow)
  22617. return this._readdir(abs, false, cb)
  22618. var lstatkey = 'lstat\0' + abs;
  22619. var self = this;
  22620. var lstatcb = inflight_1(lstatkey, lstatcb_);
  22621. if (lstatcb)
  22622. self.fs.lstat(abs, lstatcb);
  22623. function lstatcb_ (er, lstat) {
  22624. if (er && er.code === 'ENOENT')
  22625. return cb()
  22626. var isSym = lstat && lstat.isSymbolicLink();
  22627. self.symlinks[abs] = isSym;
  22628. // If it's not a symlink or a dir, then it's definitely a regular file.
  22629. // don't bother doing a readdir in that case.
  22630. if (!isSym && lstat && !lstat.isDirectory()) {
  22631. self.cache[abs] = 'FILE';
  22632. cb();
  22633. } else
  22634. self._readdir(abs, false, cb);
  22635. }
  22636. };
  22637. Glob.prototype._readdir = function (abs, inGlobStar, cb) {
  22638. if (this.aborted)
  22639. return
  22640. cb = inflight_1('readdir\0'+abs+'\0'+inGlobStar, cb);
  22641. if (!cb)
  22642. return
  22643. //console.error('RD %j %j', +inGlobStar, abs)
  22644. if (inGlobStar && !ownProp(this.symlinks, abs))
  22645. return this._readdirInGlobStar(abs, cb)
  22646. if (ownProp(this.cache, abs)) {
  22647. var c = this.cache[abs];
  22648. if (!c || c === 'FILE')
  22649. return cb()
  22650. if (Array.isArray(c))
  22651. return cb(null, c)
  22652. }
  22653. var self = this;
  22654. self.fs.readdir(abs, readdirCb(this, abs, cb));
  22655. };
  22656. function readdirCb (self, abs, cb) {
  22657. return function (er, entries) {
  22658. if (er)
  22659. self._readdirError(abs, er, cb);
  22660. else
  22661. self._readdirEntries(abs, entries, cb);
  22662. }
  22663. }
  22664. Glob.prototype._readdirEntries = function (abs, entries, cb) {
  22665. if (this.aborted)
  22666. return
  22667. // if we haven't asked to stat everything, then just
  22668. // assume that everything in there exists, so we can avoid
  22669. // having to stat it a second time.
  22670. if (!this.mark && !this.stat) {
  22671. for (var i = 0; i < entries.length; i ++) {
  22672. var e = entries[i];
  22673. if (abs === '/')
  22674. e = abs + e;
  22675. else
  22676. e = abs + '/' + e;
  22677. this.cache[e] = true;
  22678. }
  22679. }
  22680. this.cache[abs] = entries;
  22681. return cb(null, entries)
  22682. };
  22683. Glob.prototype._readdirError = function (f, er, cb) {
  22684. if (this.aborted)
  22685. return
  22686. // handle errors, and cache the information
  22687. switch (er.code) {
  22688. case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
  22689. case 'ENOTDIR': // totally normal. means it *does* exist.
  22690. var abs = this._makeAbs(f);
  22691. this.cache[abs] = 'FILE';
  22692. if (abs === this.cwdAbs) {
  22693. var error = new Error(er.code + ' invalid cwd ' + this.cwd);
  22694. error.path = this.cwd;
  22695. error.code = er.code;
  22696. this.emit('error', error);
  22697. this.abort();
  22698. }
  22699. break
  22700. case 'ENOENT': // not terribly unusual
  22701. case 'ELOOP':
  22702. case 'ENAMETOOLONG':
  22703. case 'UNKNOWN':
  22704. this.cache[this._makeAbs(f)] = false;
  22705. break
  22706. default: // some unusual error. Treat as failure.
  22707. this.cache[this._makeAbs(f)] = false;
  22708. if (this.strict) {
  22709. this.emit('error', er);
  22710. // If the error is handled, then we abort
  22711. // if not, we threw out of here
  22712. this.abort();
  22713. }
  22714. if (!this.silent)
  22715. console.error('glob error', er);
  22716. break
  22717. }
  22718. return cb()
  22719. };
  22720. Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) {
  22721. var self = this;
  22722. this._readdir(abs, inGlobStar, function (er, entries) {
  22723. self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb);
  22724. });
  22725. };
  22726. Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
  22727. //console.error('pgs2', prefix, remain[0], entries)
  22728. // no entries means not a dir, so it can never have matches
  22729. // foo.txt/** doesn't match foo.txt
  22730. if (!entries)
  22731. return cb()
  22732. // test without the globstar, and with every child both below
  22733. // and replacing the globstar.
  22734. var remainWithoutGlobStar = remain.slice(1);
  22735. var gspref = prefix ? [ prefix ] : [];
  22736. var noGlobStar = gspref.concat(remainWithoutGlobStar);
  22737. // the noGlobStar pattern exits the inGlobStar state
  22738. this._process(noGlobStar, index, false, cb);
  22739. var isSym = this.symlinks[abs];
  22740. var len = entries.length;
  22741. // If it's a symlink, and we're in a globstar, then stop
  22742. if (isSym && inGlobStar)
  22743. return cb()
  22744. for (var i = 0; i < len; i++) {
  22745. var e = entries[i];
  22746. if (e.charAt(0) === '.' && !this.dot)
  22747. continue
  22748. // these two cases enter the inGlobStar state
  22749. var instead = gspref.concat(entries[i], remainWithoutGlobStar);
  22750. this._process(instead, index, true, cb);
  22751. var below = gspref.concat(entries[i], remain);
  22752. this._process(below, index, true, cb);
  22753. }
  22754. cb();
  22755. };
  22756. Glob.prototype._processSimple = function (prefix, index, cb) {
  22757. // XXX review this. Shouldn't it be doing the mounting etc
  22758. // before doing stat? kinda weird?
  22759. var self = this;
  22760. this._stat(prefix, function (er, exists) {
  22761. self._processSimple2(prefix, index, er, exists, cb);
  22762. });
  22763. };
  22764. Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) {
  22765. //console.error('ps2', prefix, exists)
  22766. if (!this.matches[index])
  22767. this.matches[index] = Object.create(null);
  22768. // If it doesn't exist, then just mark the lack of results
  22769. if (!exists)
  22770. return cb()
  22771. if (prefix && pathIsAbsolute(prefix) && !this.nomount) {
  22772. var trail = /[\/\\]$/.test(prefix);
  22773. if (prefix.charAt(0) === '/') {
  22774. prefix = path__default["default"].join(this.root, prefix);
  22775. } else {
  22776. prefix = path__default["default"].resolve(this.root, prefix);
  22777. if (trail)
  22778. prefix += '/';
  22779. }
  22780. }
  22781. if (process.platform === 'win32')
  22782. prefix = prefix.replace(/\\/g, '/');
  22783. // Mark this as a match
  22784. this._emitMatch(index, prefix);
  22785. cb();
  22786. };
  22787. // Returns either 'DIR', 'FILE', or false
  22788. Glob.prototype._stat = function (f, cb) {
  22789. var abs = this._makeAbs(f);
  22790. var needDir = f.slice(-1) === '/';
  22791. if (f.length > this.maxLength)
  22792. return cb()
  22793. if (!this.stat && ownProp(this.cache, abs)) {
  22794. var c = this.cache[abs];
  22795. if (Array.isArray(c))
  22796. c = 'DIR';
  22797. // It exists, but maybe not how we need it
  22798. if (!needDir || c === 'DIR')
  22799. return cb(null, c)
  22800. if (needDir && c === 'FILE')
  22801. return cb()
  22802. // otherwise we have to stat, because maybe c=true
  22803. // if we know it exists, but not what it is.
  22804. }
  22805. var stat = this.statCache[abs];
  22806. if (stat !== undefined) {
  22807. if (stat === false)
  22808. return cb(null, stat)
  22809. else {
  22810. var type = stat.isDirectory() ? 'DIR' : 'FILE';
  22811. if (needDir && type === 'FILE')
  22812. return cb()
  22813. else
  22814. return cb(null, type, stat)
  22815. }
  22816. }
  22817. var self = this;
  22818. var statcb = inflight_1('stat\0' + abs, lstatcb_);
  22819. if (statcb)
  22820. self.fs.lstat(abs, statcb);
  22821. function lstatcb_ (er, lstat) {
  22822. if (lstat && lstat.isSymbolicLink()) {
  22823. // If it's a symlink, then treat it as the target, unless
  22824. // the target does not exist, then treat it as a file.
  22825. return self.fs.stat(abs, function (er, stat) {
  22826. if (er)
  22827. self._stat2(f, abs, null, lstat, cb);
  22828. else
  22829. self._stat2(f, abs, er, stat, cb);
  22830. })
  22831. } else {
  22832. self._stat2(f, abs, er, lstat, cb);
  22833. }
  22834. }
  22835. };
  22836. Glob.prototype._stat2 = function (f, abs, er, stat, cb) {
  22837. if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
  22838. this.statCache[abs] = false;
  22839. return cb()
  22840. }
  22841. var needDir = f.slice(-1) === '/';
  22842. this.statCache[abs] = stat;
  22843. if (abs.slice(-1) === '/' && stat && !stat.isDirectory())
  22844. return cb(null, false, stat)
  22845. var c = true;
  22846. if (stat)
  22847. c = stat.isDirectory() ? 'DIR' : 'FILE';
  22848. this.cache[abs] = this.cache[abs] || c;
  22849. if (needDir && c === 'FILE')
  22850. return cb()
  22851. return cb(null, c, stat)
  22852. };
  22853. var spawn = childProcess__default["default"].spawn;
  22854. var exec = childProcess__default["default"].exec;
  22855. var treeKill = function (pid, signal, callback) {
  22856. if (typeof signal === 'function' && callback === undefined) {
  22857. callback = signal;
  22858. signal = undefined;
  22859. }
  22860. pid = parseInt(pid);
  22861. if (Number.isNaN(pid)) {
  22862. if (callback) {
  22863. return callback(new Error("pid must be a number"));
  22864. } else {
  22865. throw new Error("pid must be a number");
  22866. }
  22867. }
  22868. var tree = {};
  22869. var pidsToProcess = {};
  22870. tree[pid] = [];
  22871. pidsToProcess[pid] = 1;
  22872. switch (process.platform) {
  22873. case 'win32':
  22874. exec('taskkill /pid ' + pid + ' /T /F', callback);
  22875. break;
  22876. case 'darwin':
  22877. buildProcessTree(pid, tree, pidsToProcess, function (parentPid) {
  22878. return spawn('pgrep', ['-P', parentPid]);
  22879. }, function () {
  22880. killAll(tree, signal, callback);
  22881. });
  22882. break;
  22883. // case 'sunos':
  22884. // buildProcessTreeSunOS(pid, tree, pidsToProcess, function () {
  22885. // killAll(tree, signal, callback);
  22886. // });
  22887. // break;
  22888. default: // Linux
  22889. buildProcessTree(pid, tree, pidsToProcess, function (parentPid) {
  22890. return spawn('ps', ['-o', 'pid', '--no-headers', '--ppid', parentPid]);
  22891. }, function () {
  22892. killAll(tree, signal, callback);
  22893. });
  22894. break;
  22895. }
  22896. };
  22897. function killAll (tree, signal, callback) {
  22898. var killed = {};
  22899. try {
  22900. Object.keys(tree).forEach(function (pid) {
  22901. tree[pid].forEach(function (pidpid) {
  22902. if (!killed[pidpid]) {
  22903. killPid(pidpid, signal);
  22904. killed[pidpid] = 1;
  22905. }
  22906. });
  22907. if (!killed[pid]) {
  22908. killPid(pid, signal);
  22909. killed[pid] = 1;
  22910. }
  22911. });
  22912. } catch (err) {
  22913. if (callback) {
  22914. return callback(err);
  22915. } else {
  22916. throw err;
  22917. }
  22918. }
  22919. if (callback) {
  22920. return callback();
  22921. }
  22922. }
  22923. function killPid(pid, signal) {
  22924. try {
  22925. process.kill(parseInt(pid, 10), signal);
  22926. }
  22927. catch (err) {
  22928. if (err.code !== 'ESRCH') throw err;
  22929. }
  22930. }
  22931. function buildProcessTree (parentPid, tree, pidsToProcess, spawnChildProcessesList, cb) {
  22932. var ps = spawnChildProcessesList(parentPid);
  22933. var allData = '';
  22934. ps.stdout.on('data', function (data) {
  22935. var data = data.toString('ascii');
  22936. allData += data;
  22937. });
  22938. var onClose = function (code) {
  22939. delete pidsToProcess[parentPid];
  22940. if (code != 0) {
  22941. // no more parent processes
  22942. if (Object.keys(pidsToProcess).length == 0) {
  22943. cb();
  22944. }
  22945. return;
  22946. }
  22947. allData.match(/\d+/g).forEach(function (pid) {
  22948. pid = parseInt(pid, 10);
  22949. tree[parentPid].push(pid);
  22950. tree[pid] = [];
  22951. pidsToProcess[pid] = 1;
  22952. buildProcessTree(pid, tree, pidsToProcess, spawnChildProcessesList, cb);
  22953. });
  22954. };
  22955. ps.on('close', onClose);
  22956. }
  22957. commonjsGlobal.env = process.env;
  22958. commonjsGlobal.env.NODE_ENV = commonjsGlobal.env.NODE_ENV || 'development';
  22959. const fs = fs__default["default"];
  22960. var any = bbhverse.any;
  22961. var Tasq = bbhverse.Tasq;
  22962. var statuslog = bbhverse.Traq;
  22963. var Traq = bbhverse.Traq;
  22964. Tasq.addlistener(statuslog.statuslog);
  22965. // fs.writeFileSync('run.log', ', ' + JSON.stringify( { m : 'Hello'} ), { 'flag': 'a+' })
  22966. Tasq.addlistener((e)=>{ fs.writeFileSync('run.log', ', ' + JSON.stringify( e ), { 'flag': 'a+' }); });
  22967. function isWin(){ return /^win/.test(process.platform) }
  22968. if(isWin()) {
  22969. var win_verse = win_verse$1;
  22970. var shell_verse = win_verse;
  22971. }
  22972. else {
  22973. var lin_verse = lin_verse$1;
  22974. var shell_verse = lin_verse;
  22975. }
  22976. var nodeShellExec = cliverse.nodeShellExec;
  22977. const homedir = os__default["default"].homedir();
  22978. function sysAddPathVar(addpath){
  22979. // Object.assign({
  22980. // inherit: true, shell: true, env: ENV, title: `${command} ${args}`
  22981. // }, options)
  22982. // powershell $env:Path -split ';'
  22983. var etask = ()=>{
  22984. return nodeShellExec('Powershell.exe', [
  22985. `$path = [Environment]::GetEnvironmentVariable('PATH', 'Machine')
  22986. $newpath = $path + ';${addpath}'
  22987. [Environment]::SetEnvironmentVariable("PATH", $newpath, 'Machine')`
  22988. ]).then(() => {
  22989. fs.writeFileSync('run.done', 'success');
  22990. }).catch(() => {
  22991. fs.writeFileSync('run.done', 'error');
  22992. })
  22993. };
  22994. etask.statuslog = statuslog;
  22995. etask.selectedinstance = selectedinstance;
  22996. etask.processedArgs = processedArgs;
  22997. etask.runtimestamp = runtimestamp;
  22998. etask.ENV = ENV;
  22999. return shell_verse.runElevated(etask)
  23000. // var newpath = addpath.split(';');
  23001. // newpath.push(addpath)
  23002. // newpath = Array.from(new Set(newpath)).join(';')
  23003. // // addpath.split(';').forEach(pel => { var kv = pel.split('='); kv[0] === key ? null : newpath.push(pel); } )
  23004. // // setx /M PATH "%PATH%;<path-to-executable-folder>"
  23005. // // %AppData%\npm
  23006. // return nodeShellExec('setx', ['/m', 'PATH', `%PATH%;${addpath}` ]);
  23007. }
  23008. // singleton one time lazy
  23009. var getCredentials = function(){
  23010. // First call
  23011. var creds = fs.readFileSync(path__default["default"].normalize(`${homedir}/.elxrcredentials`), { encoding: 'utf8' });
  23012. var creds = creds.split('\n').map( c => c.trim() && new URL(c));
  23013. console.log(creds);
  23014. creds.forEach(cred => {console.log( cred.hostname ); console.log( cred.username );} );
  23015. // Subsequent calls
  23016. getCredentials = ()=>{ return creds };
  23017. return getCredentials();
  23018. };
  23019. const __ALIAS__STAMP__ = '9e7bebe0-1f57-11ec-8f88-778ffeea9d1b';
  23020. const BUILD_VERSION = 'Version: 1.0.0 - built on July 25, 2022 18:16:21';
  23021. const runtimestamp = (new Date()).getTime();
  23022. function getVersion() { return BUILD_VERSION; }
  23023. console.log(getVersion());
  23024. // 'use strict';
  23025. // PB : TODO -- make sure folder context is proper coz we can now run elxr from anywhere.
  23026. // PB : TODO --
  23027. // runas bypass non elevated tasks when we request privelege
  23028. // runas message is always error needs to be fixed.
  23029. // runas wait needs to be parallelized.
  23030. // suppress elevation check error messages
  23031. // support runas lauched directly from shell.
  23032. // pass in environment in hta to shellexecute.
  23033. // PB : NOTE -- iife doesnt work if previous statement is not terminated by ;
  23034. (function () {
  23035. if (!Array.prototype.earlyreduce) {
  23036. Array.prototype.earlyreduce = function(eachcallback, initialValue, donecallback){
  23037. var iterable = this;
  23038. var donecallback = donecallback || (a=>a);
  23039. var result = { value : initialValue === undefined ? iterable[0] : initialValue };
  23040. initialValue === undefined ? null : result = eachcallback(result, element, i, iterable);
  23041. // function *earlyReduceGenerator(acc, v, i, a) {
  23042. for(var i = initialValue === undefined ? 0 : 1; i < iterable.length; i++){
  23043. var element = iterable[i];
  23044. result = eachcallback(result, element, i, iterable);
  23045. if(result.done) return donecallback(result)
  23046. }
  23047. // }
  23048. return donecallback(result)
  23049. };
  23050. }
  23051. }());
  23052. const { existsSync } = fs__default["default"];
  23053. const existslink = function(name, cb){
  23054. fs.lstat(name, (error, stats) => {
  23055. if (error) {
  23056. console.log(error);
  23057. cb(error);
  23058. }
  23059. else {
  23060. console.log("Stats object for: example_directory.txt");
  23061. console.log(stats);
  23062. // Using methods of the Stats object
  23063. console.log("Path is file:", stats.isFile());
  23064. console.log("Path is directory:", stats.isDirectory());
  23065. cb(null, true);
  23066. }
  23067. });
  23068. };
  23069. const existsFolderSync = existsSync;
  23070. const cliargs = bbhverse.cliargs;
  23071. const processedArgs = cliargs(process.argv.slice(2));
  23072. if(!processedArgs.wd){
  23073. if(process.env.wd);
  23074. else {
  23075. process.env.wd = process.cwd();
  23076. if(process.cwd() === __dirname) {
  23077. // This script was launched in the same dir.
  23078. // We do not know if it was copied to some random location. Check if we have elxr installed in current location. Or subidr.
  23079. process.env.wd = path__default["default"].dirname( process.env.wd ); // Default to the parent.
  23080. }
  23081. }
  23082. }
  23083. else process.env.wd = processedArgs.wd;
  23084. var ENV = Object.assign({}, process.env); // Shallow clone it.
  23085. console.dir(processedArgs);
  23086. // PB : TODO -- defaults for valuless arguments if passed.
  23087. // Object.keys(processedArgs).forEach(a=>{
  23088. // if(Object.prototype.toString.call(processedArgs[a]) === '[object Undefined]' || !processedArgs[a]) || trim(processedArgs[a])) == '') {
  23089. // }
  23090. // })
  23091. //
  23092. // Object.keys(clioverrides).forEach( prop => { })
  23093. require$$3.sync;
  23094. const { readdir } = fs__default["default"].promises;
  23095. // Directory shallow walk and do perform on each dir.
  23096. const dirs = async (perform, src, target, options) => {
  23097. var rs = [];
  23098. for (const dir of await readdir(src || selectedinstance.root, { withFileTypes: true })) {
  23099. if (dir.isDirectory()) rs.push( perform(dir, src, target, options) );
  23100. }
  23101. return any(rs)
  23102. };
  23103. var fsMove = async function(from, to, options) {
  23104. if(!options?.innernode) {
  23105. var exists = fs.existsSync(from);
  23106. var stats = exists && fs.statSync(from);
  23107. var isDirectory = exists && stats.isDirectory();
  23108. }
  23109. else {
  23110. var isDirectory = options.innernode.isDirectory();
  23111. }
  23112. if(!isDirectory) return fs.renameSync(from, to)
  23113. fs.mkdirSync(to, { recursive : true });
  23114. var rs = [];
  23115. for (const innernode of await readdir(from, { withFileTypes: true })) {
  23116. rs.push( fsMove( path__default["default"].join(from, innernode.name), path__default["default"].join(to, innernode.name), { innernode } ) );
  23117. }
  23118. return any(rs)
  23119. };
  23120. // PB : TODO -- Should return a bunch of promises to wait for...
  23121. var copyrecursive = async function(src, target, options) {
  23122. if(!options?.innernode) {
  23123. var exists = fs.existsSync(src);
  23124. var stats = exists && fs.statSync(src);
  23125. var isDirectory = exists && stats.isDirectory();
  23126. }
  23127. else {
  23128. var isDirectory = options.innernode.isDirectory();
  23129. }
  23130. if(!isDirectory) return fs.copyFileSync(src, target)
  23131. fs.mkdirSync(target, { recursive : true });
  23132. var rs = [];
  23133. for (const innernode of await readdir(src, { withFileTypes: true })) {
  23134. rs.push( copyrecursive( path__default["default"].join(src, innernode.name), path__default["default"].join(target, innernode.name), { innernode } )
  23135. // .then(()=>{
  23136. // return any(actions.map( a => ()=>a(dir, { isDirectory : true}) ))
  23137. // })
  23138. );
  23139. }
  23140. return any(rs)
  23141. // return fswalk( src, {}, [
  23142. // (src, options)=> {
  23143. // if(options.innernode.isDirectory()) fs.mkdirSync(options.target, { recursive : true })
  23144. // else fs.copyFileSync(src, options.target)
  23145. // }
  23146. // ])
  23147. // var exists = fs.existsSync(src);
  23148. // var stats = exists && fs.statSync(src);
  23149. // var isDirectory = exists && stats.isDirectory();
  23150. // if (isDirectory) {
  23151. // fs.mkdirSync(dest, { recursive : true });
  23152. // return dirs( function(childItemName) {
  23153. // return copyrecursive(path.join(src, childItemName.name),
  23154. // path.join(dest, childItemName.name));
  23155. // }, src )
  23156. // } else {
  23157. // fs.copyFileSync(src, dest);
  23158. // }
  23159. };
  23160. // var renamerecursive = function(from, to){
  23161. // var exists = fs.existsSync(from);
  23162. // var stats = exists && fs.statSync(from);
  23163. // var isDirectory = exists && stats.isDirectory();
  23164. // if (isDirectory) {
  23165. // fs.mkdirSync(to);
  23166. // dirs( function(childItemName) {
  23167. // renamerecursive(path.join(from, childItemName),
  23168. // path.join(to, childItemName));
  23169. // }, from )
  23170. // // fs.readdirSync(from).forEach(function(childItemName) {
  23171. // // copyrecursive(path.join(from, childItemName),
  23172. // // path.join(to, childItemName));
  23173. // // });
  23174. // } else {
  23175. // fsrename(from, to);
  23176. // }
  23177. // }
  23178. var regexreplaceall = function(content, ps){
  23179. var repmatches;
  23180. var replaced = content;
  23181. while (repmatches = ps.strOrregexp.exec(content)) {
  23182. if(content.length > 0) {
  23183. var replacement = repmatches[0];
  23184. for(var m = 1; m < repmatches.length; m++) {
  23185. replacement = replacement.replace(repmatches[m], ps.substitutes[m-1]);
  23186. }
  23187. replaced = replaced.replace( repmatches[0], replacement );
  23188. }
  23189. }
  23190. return replaced
  23191. };
  23192. // filesystem walk
  23193. const fswalk = async (pathToWalk, options, actions) => {
  23194. // options = options || { depthfirst : true }
  23195. if(!options.innernode) {
  23196. var exists = fs.existsSync(pathToWalk);
  23197. var stats = exists && fs.statSync(pathToWalk);
  23198. var isDirectory = exists && stats.isDirectory();
  23199. }
  23200. else {
  23201. var isDirectory = options.innernode.isDirectory();
  23202. }
  23203. if(!isDirectory) return any(actions.map( a => ()=>a( pathToWalk, bbhverse.assign({}, options
  23204. , { pathToWalk, innernode : options.innernode || { isDirectory : function(){ return true } } }) ) ))
  23205. var rs = [];
  23206. for (const innernode of await readdir(pathToWalk, { withFileTypes: true })) {
  23207. rs.push( fswalk( path__default["default"].join(pathToWalk, innernode.name), bbhverse.assign({}, options, {pathToWalk, innernode }), actions )
  23208. // .then(()=>{
  23209. // return any(actions.map( a => ()=>a(innernode, { isDirectory : true}) ))
  23210. // })
  23211. );
  23212. }
  23213. // Wait for the walk to complete before renaming directories.
  23214. Array.prototype.push.apply(rs, actions.map( a => ()=>a( pathToWalk, bbhverse.assign({}, options
  23215. , { pathToWalk, innernode : options.innernode || { isDirectory : function(){ return true } } } ) ) ));
  23216. return any(rs)
  23217. };
  23218. // var fslink = function(to, options){ try { fs.linkSync( to, options.from ) } catch(e) { throw e } }
  23219. var fslink = function(to, options){ fs.symlinkSync( to, options.from /*, type = "junction"*/ ); };
  23220. var fsrename = function(target, options){
  23221. // PB : TODO -- streaming and async.. target could be a stream a string or a filesystem item or a tree node...
  23222. var targetname = options.innernode?.name || path__default["default"].parse(target).base;
  23223. var replaced = targetname;
  23224. options.patternsubstitutions.forEach( ps => { replaced = regexreplaceall( replaced, ps ); });
  23225. if(replaced && replaced !== targetname) {
  23226. var tr = target.replace( targetname, replaced );
  23227. fs.renameSync(target, tr);
  23228. return tr;
  23229. }
  23230. else return replaced
  23231. };
  23232. var fscontentreplace = function( target, options ){
  23233. // do many replacements in one shot in the file.
  23234. if(options.processingtype === 'inplace' && options.sourcetype === 'filesystem' && !options.innernode.isDirectory() ) {
  23235. var content = fs.readFileSync(target, { encoding: 'utf8' }); // PB : TODO -- streaming and async..
  23236. options.patternsubstitutions.forEach( ps => { content = regexreplaceall( content, ps ); });
  23237. fs.writeFileSync(target, content);
  23238. }
  23239. };
  23240. var templatelink = function(target, options){
  23241. var targetSubPath = target.replace(options.workingtarget + '/', '' );
  23242. var targetSubPathsplit = targetSubPath.split("/");
  23243. var targetPathBaseDir = `${targetSubPathsplit[0]}/${targetSubPathsplit[1]}`;
  23244. var linkToSubPathReplacement = `${options.base}-server-lib/common`;
  23245. // var rgxp = new RegExp(`(__link__)${options.base}-server-lib`, "g")
  23246. var rgxp = new RegExp(`(__link__${options.base}-server-lib)`, "g");
  23247. var linkToSubPath = targetSubPath;
  23248. var b = target.match(rgxp);
  23249. var linkFromName = regexreplaceall( target, { strOrregexp : rgxp, substitutes : [ '' ] } );
  23250. linkFromName = linkFromName.replace(options.workingtarget, options.destinationroot);
  23251. if( b ) {
  23252. // Only if the pattern matches which is link instruction.
  23253. linkToSubPath = regexreplaceall( linkToSubPath, { strOrregexp : rgxp, substitutes : [ '' ] } );
  23254. }
  23255. options.patternsubstitutions.forEach( ps => { linkToSubPath = regexreplaceall( linkToSubPath, ps ); });
  23256. var linkToName = `${options.destinationroot}/${linkToSubPath}`;
  23257. if(b){
  23258. linkToSubPath = linkToSubPath.replace( targetPathBaseDir, linkToSubPathReplacement);
  23259. // PB : DONT DELETE EVERYTHING ??? Only the linkable ones... Or use an add strategy without deleting...
  23260. fs.unlinkSync( target );
  23261. fslink( `${options.destinationroot}/${linkToSubPath}`, { from : linkFromName } );
  23262. }
  23263. else {
  23264. fsMove( `${options.workingtarget}/${linkToSubPath}`, linkToName );
  23265. // fsMove( `${options.workingtarget}/${linkToSubPath}`, linkFromName )
  23266. }
  23267. };
  23268. var getShellTask = (command, args, options) => {
  23269. options = options || {};
  23270. var callshell = command === 'rm' ? getgitbashtask : getshelltask;
  23271. return () => {
  23272. var p = callshell( [command, args, Object.assign({
  23273. inherit: true, shell: true, env: ENV, title: `${command} ${args}`
  23274. }, options)
  23275. ])();
  23276. if (options.ignorefailures) {
  23277. return p.catch(e => {
  23278. // Ignore. Not a major error.
  23279. })
  23280. }
  23281. else return p;
  23282. }
  23283. };
  23284. var callshelltask = (args) => {
  23285. // console.dir(args)
  23286. if( Object.prototype.toString.call(args) === '[object Function]' ) {
  23287. return args;
  23288. }
  23289. return getshelltask(args)()
  23290. };
  23291. var getCmdString = function(args){ return `"${args[0]} ${args[1].join(' ')}"` };
  23292. var getshelltask = (args) => {
  23293. return args[0] === 'rm' ? getgitbashtask(args) : () => {
  23294. return nodeShellExec.apply(null, args).catch(function(e){
  23295. e.benign = args[2].benign;
  23296. if(!e.benign) { console.error(e); }
  23297. throw e
  23298. })
  23299. }
  23300. };
  23301. var getgitbashtask = (args, onEachError) => { return () => {
  23302. return nodeShellExec( `"${gitbash}"`, ['-c', getCmdString(args)], args[2]).catch( onEachError || function(e){ console.error(e); }) }
  23303. };
  23304. var getnodeshellexectask = (args) => { return () => { return nodeShellExec.apply(null, args) }};
  23305. var perform = function( serailtasks, taskvector ){ return any( serailtasks(taskvector).map(getnodeshellexectask)) };
  23306. var getTaskCheckExists = shell_verse.getTaskCheckExists;
  23307. // var getTaskWithElevation = function(tasdef){ return shell_verse.getElevatedTask( tasdef.elevatedpulltasks ) }
  23308. // var getTaskWithoutElevation = function(tasdef){
  23309. // return ()=>{
  23310. // if(!processedArgs.runas) { return tasdef.regularpulltasks(); }
  23311. // else Promise.resolve(true)
  23312. // }
  23313. // }
  23314. var gitops = {
  23315. getdiscoverbranchcmd : function(repo){
  23316. var parameters = ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;'];
  23317. var cmd = [gitbash
  23318. , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  23319. , { cwd: instanceroot + '/' + repo, title: 'discoverbranch for ' + repo + ' ' + parameters.join(' ') }];
  23320. return cmd
  23321. }
  23322. };
  23323. var getPullCmd = (repodef, branch) => {
  23324. // console.log(useGitPull)var getPullCmd = (repo, branch) => {
  23325. // console.log(useGitPull)
  23326. var repo = repodef.repo;
  23327. var pullCmd = [];
  23328. if(!branch) {
  23329. // console.warn('No branch was specified detecting from working client.')
  23330. // First check if working client exists.
  23331. // if (existsSync(instanceroot + '/' + repo)) {
  23332. pullCmd= gitops.getdiscoverbranchcmd(repo);
  23333. // }
  23334. // else performpull
  23335. }
  23336. // var pullCmd = [gitInstallDir
  23337. // , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  23338. // , { cwd: instanceroot + '/' + repo, title: 'pull all remotes for ' + repo }]
  23339. if(branch) {
  23340. var parameters = ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;'];
  23341. var pullCmd = [ gitbash
  23342. , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  23343. , { cwd: instanceroot + '/' + repo, title : 'pull all remotes for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }];
  23344. }
  23345. // var pullCmd = ['pullall', [], { cwd : repo }]
  23346. if (useGitPull) pullCmd = ['git', ['pull'], {
  23347. inherit: true, shell: true,
  23348. cwd: instanceroot + '/' + repo
  23349. // , env: process.env
  23350. , runas: processedArgs.runas
  23351. , title: `git pull ${repo}`
  23352. }];
  23353. return pullCmd
  23354. };
  23355. // PB : TODO -- Use queueing with async tasks..
  23356. var performPull = (repodef, branch, repoowner, errHandler, elevatedBatch, regularBatch) => {
  23357. var pT = getPullTask(repodef, branch, repoowner, errHandler, elevatedBatch, regularBatch);
  23358. // var waitForBatchAdditions = function(){
  23359. // return pT;
  23360. // }
  23361. // Execute is implied.
  23362. // if(false && (__inelevatedBatch || __inregularBatch) ) return waitForBatchAdditions() // PB : Todo Implemnt a trigger which starts execution.
  23363. // else
  23364. return pT() // Execute it.
  23365. };
  23366. var getPullTask = (repodef, branch, repoowner, errHandler, elevatedBatch, regularBatch) => {
  23367. // PB : TODO -- Handle no branch passed in case.
  23368. // if(!branch) { throw 'No branch specified' }
  23369. var repo = repodef.repo;
  23370. elevatedBatch = elevatedBatch || [];
  23371. regularBatch = regularBatch || [];
  23372. try{
  23373. // PB : TODO -- local repo folder named the same as the remote repository name is not enough to establish existence.
  23374. // This remote repo and branch may have been or may need to be added as a local tracking branch
  23375. // to any other local repo folder (with a different name)
  23376. var exists = existsSync(instanceroot + '/' + repo);
  23377. }
  23378. catch(e){
  23379. exists = false;
  23380. console.log(e);
  23381. }
  23382. function initTask(etask){
  23383. etask.info = { repo };
  23384. etask.errHandler = errHandler;
  23385. etask.statuslog = statuslog;
  23386. etask.processedArgs = processedArgs;
  23387. etask.selectedinstance = selectedinstance;
  23388. etask.runtimestamp = runtimestamp;
  23389. etask.ENV = ENV;
  23390. }
  23391. function initElevatedBatch(){
  23392. elevatedBatch.info = { repo };
  23393. elevatedBatch.errHandler = errHandler;
  23394. elevatedBatch.statuslog = statuslog;
  23395. elevatedBatch.processedArgs = processedArgs;
  23396. elevatedBatch.selectedinstance = selectedinstance;
  23397. elevatedBatch.runtimestamp = runtimestamp;
  23398. elevatedBatch.ENV = ENV;
  23399. }
  23400. if (exists) {
  23401. var tasks = [];
  23402. return (()=>{
  23403. // PB : TODO -- We need a non cacheable set of properties that need to default to something but then need to escplicitly specified in each run.
  23404. if(selectedinstance.addremotes) {
  23405. return op['get-remotes']({repo}).then(( remotes )=>{
  23406. return op['get-upstream']({repo, remotes}).then(( upstream ) => {
  23407. return __addremotesandpull({ upstream, remotes})
  23408. })
  23409. })
  23410. }
  23411. else return __pull();
  23412. })()
  23413. function __pull(){
  23414. var branchprint = branch ? ' branch :' + branch : '';
  23415. var task = ()=>{
  23416. console.log('pulling ' + instanceroot + '/' + repo + branchprint );
  23417. return any(tasks).then( ()=>{
  23418. return nodeShellExec.apply(null, getPullCmd(repodef, branch)).then(() => {
  23419. return true;
  23420. })
  23421. })
  23422. };
  23423. initTask(task);
  23424. if(repodef.requiresElevation) {
  23425. elevatedBatch.push(shell_verse.getElevatedTaskInBatch( task ));
  23426. if(elevatedBatch.length === 1) { initElevatedBatch(); initTask(elevatedBatch[0]); } // PB : TDOO -- Make sure first task also has run context. May need to be moved to win_verse
  23427. else initTask(elevatedBatch[elevatedBatch.length-1]);
  23428. return elevatedBatch[elevatedBatch.length-1]
  23429. }
  23430. else {
  23431. regularBatch.push(shell_verse.getNonElevatedTask( task ));
  23432. return regularBatch[regularBatch.length-1]
  23433. }
  23434. }
  23435. function __addremotesandpull(options){
  23436. // selectedinstance.selectedremotes are optional and need not be enforced to be chosen. The selection for hte selected remotes
  23437. // could also be derived from a crossfilter of remote-type selected for this run and the current chosen and operating reposervers.
  23438. var selectedremotes = Array.from( new Set(selectedinstance.selectedremotes.concat(Object.keys(repodef.remotes || {}))));
  23439. if(selectedremotes.length > 0) ;
  23440. var repoRemotes = Object.assign( {}, selectedinstance.remotes, options.remotes, options.upstream, repodef.remotes );
  23441. // We need a most permissive filtered list to use as an efficient starting point to further reduce to whats actually needed.
  23442. // However if such a cached list is not available we need to build it by scaning and apply all the filters anyway on the whole world.
  23443. Object.keys(repoRemotes).forEach((remotename)=>{
  23444. });
  23445. __pull();
  23446. }
  23447. }
  23448. else {
  23449. // PB : TODO -- detect if a clonable repo exists within the context of currentGitAuthUser on remote reposerver...
  23450. console.log('cloning ' + repo);
  23451. // PB : TODO -- add additional remotes after cloning and pull again...
  23452. var task = ()=>{
  23453. return nodeShellExec('git', ['clone', '-c', 'core.symlinks=true', selectedinstance.reposerver + `/${repoowner || defaultRepoOwner}/` + repo + '.git'],
  23454. {
  23455. inherit: true, shell: true,
  23456. env: process.env
  23457. , cwd : instanceroot
  23458. , runas: processedArgs.runas
  23459. }).then(() => {
  23460. var task = ()=>{
  23461. return nodeShellExec('git', ['config', '--replace-all', 'core.symlinks', true],
  23462. {
  23463. inherit: true, shell: true,
  23464. env: process.env
  23465. , cwd: instanceroot + '/' + repo
  23466. , runas: processedArgs.runas
  23467. , title: `'git', ${['config', '--replace-all', 'core.symlinks', selectedinstance.username].join(' ')}`
  23468. })
  23469. };
  23470. initTask(task);
  23471. if(repodef.requiresElevation) {
  23472. elevatedBatch.push(shell_verse.getElevatedTaskInBatch( task ));
  23473. return elevatedBatch[elevatedBatch.length-1]
  23474. }
  23475. else {
  23476. regularBatch.push(shell_verse.getNonElevatedTask( task ));
  23477. return regularBatch[regularBatch.length-1]
  23478. }
  23479. })
  23480. };
  23481. initTask(task);
  23482. if(repodef.requiresElevation) {
  23483. elevatedBatch.push(shell_verse.getElevatedTaskInBatch( task ));
  23484. return elevatedBatch[elevatedBatch.length-1]
  23485. }
  23486. else {
  23487. regularBatch.push(shell_verse.getNonElevatedTask( task ));
  23488. return regularBatch[regularBatch.length-1]
  23489. }
  23490. }
  23491. };
  23492. var defaultRepoOwner = 'chess';
  23493. var elevatedRunasRepos = null;
  23494. var gitRepos = null;
  23495. // grep -qxF 'alias elxr="node elxr/index.js"' ~/.bash_profile || echo 'alias elxr="node elxr/index.js"' >> ~/.bash_profile
  23496. // nodeShellExec('echo', ['elxr'], { inherit : true}) //, {stdio: "inherit"}
  23497. var dbForLabel = function (label) {
  23498. var dbsForLabel = {
  23499. devmysql: 'mysql'
  23500. , development: 'mssql'
  23501. , production: 'mssql'
  23502. };
  23503. return dbsForLabel[label] || 'mysql'
  23504. };
  23505. // Maps an environment to a branch. Not required if the branch is appropriately named.
  23506. var checkoutMap = { 'development': 'master' };
  23507. // SAM : TODO Use nodeshellexec where to detect git installation dir
  23508. var gitbash = shell_verse.getbash();
  23509. // var gitbash = "G:\\Installed\\Git\\bin\\sh.exe"
  23510. // Relevant git repos
  23511. var exludeMergeRepos = [];
  23512. var useGitPull = processedArgs.useGitPull || false;
  23513. var op = {
  23514. 'h': () => { console.log(elxr.help()); return '-h' }
  23515. , 'clean' : () => {
  23516. // delete all node_module folders and links.
  23517. var tasklist = [];
  23518. dirs( (repodir)=> tasklist.push(getShellTask('rm',['-rf', 'node_modules'], { cwd : instanceroot + '/' + repodir.name })()), instanceroot );
  23519. return Promise.all(tasklist)
  23520. }
  23521. // , 'undefined': () => { return acquireChoices( {} ); }
  23522. , 'reset': () => {
  23523. // Reset NPM packages semver so major versions can be updated.
  23524. const fs = fs__default["default"];
  23525. const wipeDependencies = (__package) => {
  23526. const file = fs.readFileSync(__package + '/package.json');
  23527. const content = JSON.parse(file);
  23528. for (var devDep in content.devDependencies) {
  23529. if (content.devDependencies[devDep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  23530. content.devDependencies[devDep] = '*';
  23531. }
  23532. }
  23533. for (var dep in content.dependencies) {
  23534. if (content.dependencies[dep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  23535. content.dependencies[dep] = '*';
  23536. }
  23537. }
  23538. fs.writeFileSync(__package + '/package.json', JSON.stringify(content));
  23539. };
  23540. var repos = ['client'];
  23541. // repos = gitRepos;
  23542. repos.forEach(wipeDependencies);
  23543. // if (require.main === module) {
  23544. // } else {
  23545. // module.exports = wipeDependencies
  23546. // }
  23547. }
  23548. , 'upgrade': () => {
  23549. console.log('upgrade.......');
  23550. var tasks = [
  23551. () => {
  23552. var p = nodeShellExec('npm', ['i', '-g', 'npm-upgrade'], {
  23553. inherit: true, shell: true
  23554. , env: process.env
  23555. }).catch((e) => { console.error(e); });
  23556. p.position = 1;
  23557. console.log('One');
  23558. return p;
  23559. }
  23560. , () => {
  23561. var p = nodeShellExec('npm', ['cache', 'clean', '-f'], {
  23562. inherit: true, shell: true
  23563. , env: process.env
  23564. }).catch((e) => { console.error(e); });
  23565. p.position = 2;
  23566. console.log('Two');
  23567. return p;
  23568. }
  23569. , () => {
  23570. var p = nodeShellExec('npm', ['install', '-g', 'n'], {
  23571. inherit: true, shell: true
  23572. , env: process.env
  23573. }).catch((e) => { console.error(e); });
  23574. p.position = 3;
  23575. console.log('Three');
  23576. return p;
  23577. }
  23578. , () => {
  23579. var p = nodeShellExec('n', ['latest'], {
  23580. inherit: true, shell: true
  23581. , env: process.env
  23582. }).catch((e) => { console.error(e); });
  23583. p.position = 4;
  23584. console.log('Four');
  23585. return p;
  23586. }
  23587. ];
  23588. any(tasks);
  23589. console.log('.......done');
  23590. console.log('Running exlr upgrade in : ' + path__default["default"].dirname(__dirname));
  23591. console.log('Currently only upgrades ember : ' + path__default["default"].dirname(__dirname));
  23592. console.info('Uninstalling existing ember globally');
  23593. var step1 = nodeShellExec('cmd', ['/c', 'npm', 'uninstall', '-g', 'ember-cli'], {
  23594. stdio: ['pipe', process.stdout, process.stderr],
  23595. inherit: true,
  23596. shell: true,
  23597. cwd: path__default["default"].dirname(__dirname),
  23598. env: env
  23599. });
  23600. step1.on('close', () => {
  23601. console.info('Installing ember globally');
  23602. var step2 = nodeShellExec('cmd', ['/c', 'npm', 'install', '-g', 'ember-cli'], {
  23603. stdio: ['pipe', process.stdout, process.stderr],
  23604. inherit: true,
  23605. shell: true,
  23606. cwd: path__default["default"].dirname(__dirname),
  23607. env: env
  23608. });
  23609. step2.on('close', () => {
  23610. nodeShellExec('cmd', ['/c', 'ember', '--version'], {
  23611. stdio: ['pipe', process.stdout, process.stderr],
  23612. inherit: true,
  23613. shell: true,
  23614. cwd: path__default["default"].dirname(__dirname),
  23615. env: env
  23616. });
  23617. });
  23618. });
  23619. }
  23620. , 'push': () => {
  23621. if (!processedArgs._[1]) { console.error('push all not supported. Specify repo name'); return }
  23622. // init remote bare from local
  23623. // pushandinitremotebare
  23624. // https://www.jeffgeerling.com/blogs/jeff-geerling/push-your-git-repositories
  23625. // connect to repo server -- net use 172.16.0.27
  23626. // cd 172.16.0.27/repos/
  23627. // mkdir repo.git
  23628. // cd repo.git
  23629. // git init --bare
  23630. // cd localrepo
  23631. // git remote rename origin githubclone
  23632. // git remote add origin //172.16.0.27/repos/repo.git
  23633. // git push origin master
  23634. var repo = processedArgs._[1];
  23635. var remote = 'origin';
  23636. var sequentialTaskShellCommands = [];
  23637. if (!existsSync(`Z:/${repo}.git`)) {
  23638. sequentialTaskShellCommands = [
  23639. // ['net', ['use', 'Z:', selectedinstance.reposerver.replace('/','\\')], {
  23640. // inherit : true, shell: true
  23641. // , env: process.env
  23642. // }]
  23643. ['pwd', { cwd: 'Z:', inherit: true }]
  23644. , ['mkdir', [`${repo}.git`], {
  23645. cwd: `Z:`
  23646. , inherit: true, shell: true
  23647. , env: process.env
  23648. }]
  23649. , ['pwd', { cwd: `Z:/${repo}.git`, inherit: true }]
  23650. , ['git', ['init', '--bare'], {
  23651. cwd: `Z:/${repo}.git`
  23652. , inherit: true, shell: true
  23653. , env: process.env
  23654. }]
  23655. // PB : TODO -- Do this conditionally only...
  23656. , ['git', ['remote', 'rename', remote, 'githubclone'], { cwd: `${instanceroot + '/' + repo}` }, (err) => {
  23657. console.log(`Ignoring ${remote} rename error : ` + err); return true; //return true to continue.
  23658. }] // PB ; Todo -- new repositories created locally will not have origin. Handle this failure.
  23659. , ['git', ['remote', 'add', remote, `${selectedinstance.reposerver}/${repo}.git`], { cwd: `${instanceroot + '/' + repo}` }]
  23660. // PB : TODO -- If threre is a gitbubclone origin
  23661. // Set the master to pull from the local repo.
  23662. ];
  23663. if (!existsSync(`Z:`)) {
  23664. sequentialTaskShellCommands.splice(0, 0, ['net', ['use', 'Z:', selectedinstance.reposerver.replace(/\//gm, '\\')], {
  23665. inherit: true, shell: true
  23666. , env: process.env
  23667. }]);
  23668. console.warn('Adding network drive z: for repo server. ' + sequentialTaskShellCommands[0]);
  23669. // throw 'done'
  23670. }
  23671. }
  23672. sequentialTaskShellCommands.push(['git', ['push', remote, 'master'], { cwd: `${instanceroot + '/' + repo}` }]);
  23673. // console.dir(sequentialTaskShellCommands);
  23674. var tasks = [];
  23675. sequentialTaskShellCommands.forEach(shellcmd => {
  23676. // console.log(shellcmd)
  23677. tasks.push(() => {
  23678. var p = nodeShellExec.apply(null, shellcmd.slice(0, 3)).catch((e) => { if (shellcmd[3]) { return shellcmd[3]() } else { console.error(e); } });
  23679. return p;
  23680. });
  23681. });
  23682. any(tasks);
  23683. }
  23684. , 'is-git-repo': (dir) => {
  23685. return nodeShellExec('git', ['-C', dir.name, 'rev-parse'], { stdio: 'ignore' })
  23686. }
  23687. // git remote equivalents...
  23688. // git branch --set-upstream-to=elixir-unc/master master
  23689. // git push --set-upstream elixir-unc branch..
  23690. , 'remote': (args) => {
  23691. // Subcommands!
  23692. // PB : TODO -- we can now pass in hypehnated args...
  23693. if(!processedArgs.v) return false; // Only -v is supported presently..
  23694. var serial_perform = (repo) => {
  23695. var options = { cwd: instanceroot + '/' + repo };
  23696. return [
  23697. ['git', ['remote', '-v'], options]
  23698. ]
  23699. };
  23700. var x = (args) => {
  23701. var tasq = () => {
  23702. // console.log(args)
  23703. return nodeShellExec.apply(null, args).catch(e => {
  23704. // We continue on failure.
  23705. console.error(tasq.toString());
  23706. })
  23707. };
  23708. tasq.toString = function(){
  23709. return JSON.stringify(args)
  23710. };
  23711. return tasq;
  23712. };
  23713. var perform = (dir) => {
  23714. return any(serial_perform(dir.name).map(x))
  23715. };
  23716. dirs(perform);
  23717. }
  23718. , 'remote set-url': (args) => {
  23719. // git remote set-url elixir-unc //10.10.5.60/gitrepo/chess/bbhverse
  23720. var __args = {
  23721. remotename : args.remotename || processedArgs._[2]
  23722. , url : args.url || processedArgs._[3]
  23723. };
  23724. // pushable doesn't mean the remote doesn't support being pushed to.
  23725. // Over here it just means we are disabling pushing to that remote by setting the push portion of the url the a junk remote called no-pushing.
  23726. // PB : TODO -- change this to enablepushing.
  23727. // By default pushing should be disabled. Also developers permissions on the remote is a secondary check for pushing.
  23728. var pushable = processedArgs.pushable || false;
  23729. remotename = __args.remotename;
  23730. url = __args.url;
  23731. var serial_perform_git_seturl = (repo) => {
  23732. // console.log(repo)
  23733. if (pushable) {
  23734. return [
  23735. ['git', ['remote', 'set-url', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  23736. , ['git', ['remote', `set-url`, '--push', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  23737. ]
  23738. }
  23739. else {
  23740. return [
  23741. ['git', ['remote', 'set-url', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  23742. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  23743. ]
  23744. }
  23745. };
  23746. var x = (args) => {
  23747. var tasq = () => {
  23748. // console.log(args)
  23749. return nodeShellExec.apply(null, args).catch(e => {
  23750. // We continue on failure.
  23751. console.error(tasq.toString());
  23752. })
  23753. };
  23754. tasq.toString = function(){
  23755. return JSON.stringify(args)
  23756. };
  23757. return tasq;
  23758. };
  23759. var perform_git_seturl = (dir) => {
  23760. op['is-git-repo'](dir).then((logEntry) => {
  23761. return any(serial_perform_git_seturl(dir.name).map(x))
  23762. }).catch((e) => {
  23763. // console.log('Failed : ' + dir.name)
  23764. });
  23765. };
  23766. dirs(perform_git_seturl);
  23767. }
  23768. // , 'reset' : ()=>{
  23769. // PB : TODO -- Cant have 2 resets !! | There is an npm reset that should be bundled.
  23770. // // Reset the whole installation pertaining to this elxr folder.
  23771. // }
  23772. , 'remote exists': (args) => {
  23773. var __args = {
  23774. remotename : args.remotename|| processedArgs._[2]
  23775. , url : args.url || processedArgs._[3]
  23776. , branch : args.branch || processedArgs._[4]
  23777. };
  23778. var options = args.repo ? { cwd: instanceroot + '/' + args.repo } : {};
  23779. // PB : TODO -- We should evaluate a whole list of remotes passed in from args instead of just one.
  23780. var commands = [
  23781. // git remote -v| while read remote; do "${remote#origin/}" "$remote"; done
  23782. // ['git', ['remote', '-v', '| while read remote; do "${remote#origin/}" "$remote"; done'], utils.assign( {
  23783. [
  23784. // 'git', ['remote', '-v']
  23785. 'git', ['config', `remote.${__args.remotename}.url`]
  23786. , bbhverse.assign_core( { arraymergetype : bbhverse.assign_core.DISTINCT_UNION }
  23787. , {
  23788. benign : args.benign, ignorefailures : args.ignorefailures,
  23789. evaluateResult : function(err, result){
  23790. return [
  23791. +result.code === 0
  23792. , result
  23793. ]
  23794. }
  23795. } , options) ]
  23796. ];
  23797. var mapped = commands.map(getshelltask); //.map( p => p.catch(e => e)) // Handle errors later.
  23798. mapped.push( function(prevserialtaskresult) {
  23799. var pt = [false , null];
  23800. if(prevserialtaskresult.error) {
  23801. // Previous task has failed.
  23802. pt[1] = prevserialtaskresult.error[1];
  23803. }
  23804. else pt = prevserialtaskresult;
  23805. console.dir(prevserialtaskresult);
  23806. return getshelltask(['git', ['ls-remote', `${__args.url}`], bbhverse.assign_core( { arraymergetype : bbhverse.assign_core.DISTINCT_UNION }
  23807. , {
  23808. benign : args.benign, ignorefailures : args.ignorefailures,
  23809. evaluateResult : function(err, result){
  23810. if(+result.code !== 0) return [pt, [ false, result]]
  23811. // var hasfailed = /^fatal: .*/.test(result.messages.join(' '))
  23812. return [pt, [true, result] ]
  23813. }
  23814. } , options) ])().catch( e => {
  23815. console.error(e);
  23816. return [pt, [ false, null]]
  23817. })
  23818. });
  23819. return any(mapped, true, false, { accumulatedresults : [] }).then( allresolved => {
  23820. console.dir(allresolved);
  23821. !allresolved[0][0] && !allresolved[1][0] ? console.log('was not added as a remote and url is currently inaccessible.')
  23822. : allresolved[0][0] && allresolved[1][0] ? console.log('was added as a remote and url is accessible.')
  23823. : allresolved[0][0] && !allresolved[1][0] ? console.log('was added as a remote but url is currently inaccessible.')
  23824. : console.log('was not added as a remote but url is currently accessible.');
  23825. return !allresolved[0][0] && !allresolved[1][0] ? [0, 0]
  23826. : allresolved[0][0] && allresolved[1][0] ? [1, 1] // => was added as a remote and url is accessible.
  23827. : allresolved[0][0] && !allresolved[1][0] ? [1, 0] // => was added as a remote but url is currently inaccessible.
  23828. : [0, 1] // => was not added and remote and url is accessible.
  23829. }).catch(e => {
  23830. console.log(e);
  23831. return [0, 0]
  23832. })
  23833. }
  23834. , 'remote refresh': (args) => {
  23835. var __args = {
  23836. remotename : args.remotename|| processedArgs._[2]
  23837. , url : args.url || processedArgs._[3]
  23838. , branch : args.branch || processedArgs._[4]
  23839. };
  23840. // use the repo manifest to create missing remotes.
  23841. function perform_remote_refresh(dir){
  23842. var repo = dir.name;
  23843. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo);
  23844. try {
  23845. var remotes = commonjsRequire(`${selectedinstance.root}/${dir.name}/repo-manifest.js`,"/$$rollup_base$$")( null
  23846. , { utils: bbhverse, username : selectedinstance.username, instanceName : selectedinstance.instanceName
  23847. , node_env : selectedinstance.node_env, reposerver : 'https://git.bbh.org.in' } // options
  23848. ).remotes || [];
  23849. }
  23850. catch(e){
  23851. var remotes = [];
  23852. }
  23853. // console.log(`${dir.name}/repo-manifest.js` + '---------------------------')
  23854. // console.dir(remotes)
  23855. return nodeShellExec.apply(null, dscoverbranchcmd).then(__branch=>{
  23856. console.log('Processing : ' + dir.name);
  23857. var branch = __branch;
  23858. __args.repo = repo;
  23859. __args.branch = __branch;
  23860. var promises = [];
  23861. remotes.forEach(remote =>{
  23862. Object.keys(remote).forEach(remotename => {
  23863. __args.remotename = remotename;
  23864. __args.url = remote[remotename];
  23865. __args.benign = true;
  23866. __args.ignorefailures = true;
  23867. promises.push( op['remote exists']( __args ).then( exists => {
  23868. if(!exists[0]) {
  23869. if(!exists[1]) { console.error( `Skipping inaccessible remote url ${__args.url}` ); }
  23870. else return op['remote add']( { remotename,
  23871. // PB : TODO -- use the most accessible remote instead of the first available.
  23872. url : (bbhverse.js.isArray(remote[remotename]) ? remote[remotename][0] : remote[remotename]), branch
  23873. } )
  23874. }
  23875. })
  23876. );
  23877. });
  23878. });
  23879. return Promise.all(promises)
  23880. })
  23881. .catch((e) => { console.log('Processing Error : ' + dir.name); console.error(e); return { error: true, message: repo } })
  23882. }
  23883. return dirs(perform_remote_refresh)
  23884. }
  23885. , 'remote add': (args) => {
  23886. // PB : TODO -- set-upstream-to should be chosen and intentionally switched. Coz we can have multiple upstream remotes.
  23887. // Also each upstream remote may need to have is own branch to switch to. We therefore need a branch nomenclature
  23888. // That explicitly has a remote name prefix.
  23889. // git branch branch_name --set-upstream-to your_new_remote/branch_name
  23890. // git branch branch_name -u your_new_remote/branch_name -- older versions
  23891. // git branch -vv -- Detect which branch are we tracking.
  23892. // default upstream should be users own fork.
  23893. // Also need alias branches to
  23894. // define a git alias which would git pull master from one repo, and then git pull master from other remotes.
  23895. // probably git merge from all remotes... and relevant branches...
  23896. // alias pushall='for i in `git remote`; do git push $i; done;'
  23897. // alias pullall='for i in `git remote`; do git pull $i; done;'
  23898. // args === processedArgs ? args = {} : null;
  23899. var __args = {
  23900. remotename : args.remotename|| processedArgs._[2]
  23901. , repo : args.repo
  23902. , url : args.url || processedArgs._[3]
  23903. , branch : args.branch || processedArgs._[4]
  23904. , 'set-upstream' : args['set-upstream'] || processedArgs._[5]
  23905. };
  23906. var remotename = __args.remotename;
  23907. var url = __args.url;
  23908. var branch = __args.branch;
  23909. var pushable = processedArgs.pushable || false;
  23910. var serial_perform_git_add = (repo) => {
  23911. // console.log(repo)
  23912. if (pushable) {
  23913. var gacmds = [
  23914. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  23915. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
  23916. // , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  23917. ];
  23918. }
  23919. else {
  23920. var gacmds = [
  23921. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  23922. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  23923. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
  23924. // When we add a remote it should not automatically become the upstream. The upstream should be a chosen remote else we do not change
  23925. // , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  23926. ];
  23927. }
  23928. if(args['set-upstream']) gacmds.push(['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]);
  23929. return gacmds
  23930. };
  23931. // PB : TODO -- Accumulate using yield... and finally return a set of tasks or promises...
  23932. var perform_git_add = (dir) => {
  23933. op['is-git-repo'](dir).then((logEntry) => {
  23934. // console.log(code)
  23935. if (logEntry.success) {
  23936. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  23937. console.log('skipped : ' + dir.name + ', reason : A remote with same name already exists.');
  23938. })
  23939. .catch((e) => {
  23940. perform( serial_perform_git_add, dir.name );
  23941. });
  23942. }
  23943. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  23944. }).catch((e) => {
  23945. console.log('Failed : ' + dir.name);
  23946. });
  23947. };
  23948. if(args.repo) { perform_git_add( { name : args.repo} ); }
  23949. else return dirs(perform_git_add)
  23950. }
  23951. , 'remote remove': (args) => {
  23952. var __args = {
  23953. remotename : args.remotename|| processedArgs._[2]
  23954. };
  23955. var remotename = __args.remotename;
  23956. var serial_perform_git_remove = (repo) => {
  23957. // console.log(repo)
  23958. return [
  23959. ['git', ['remote', 'remove', remotename], { cwd: instanceroot + '/' + repo }]
  23960. ]
  23961. };
  23962. var perform_git_remove = (dir) => {
  23963. op['is-git-repo'](dir).then((logEntry) => {
  23964. // console.log(code)
  23965. if (logEntry.success) {
  23966. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  23967. any(serial_perform_git_remove(dir.name).map(getnodeshellexectask));
  23968. })
  23969. .catch((e) => {
  23970. console.log('skipped : ' + dir.name + `, reason : No remote named ${remotename}`);
  23971. });
  23972. }
  23973. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  23974. }).catch((e) => {
  23975. // console.log('Failed : ' + dir.name)
  23976. });
  23977. };
  23978. fs__default["default"].promises;
  23979. dirs(perform_git_remove);
  23980. }
  23981. , 'get-remotes' : (args) => {
  23982. // var __args = {
  23983. // repo : args?.repo || processedArgs._[1]
  23984. // }
  23985. var repo = args.repo;
  23986. var serial_perform = (repo) => {
  23987. return [
  23988. ['git', ['remote', '-vvvv'], { cwd: instanceroot + '/' + repo,
  23989. evaluateResult : function( issuccess, result){
  23990. if(!issuccess || +result.code !== 0) throw Object.assign( new Error('git branch -vvvv crashed'), result);
  23991. var lines = result.messages.join('').split('\n');
  23992. var remotes = {};
  23993. lines.forEach(line => {
  23994. // pattern = origin https://git.bbh.org.in/chess/elxr (fetch)
  23995. var match = new RegExp(`(\\S+)\\s(\\S+)/${repo}.git\\s\\((\\S+)\\)`).exec(line);
  23996. if(match) {
  23997. var r = remotes[match[1]] || (remotes[match[1]] = { title : match[1] });
  23998. if(match[3] === 'push') { r.push = match[2]; }
  23999. else r.url = match[2];
  24000. }
  24001. });
  24002. return remotes
  24003. }}]
  24004. ]
  24005. };
  24006. return perform( serial_perform, repo )
  24007. }
  24008. , 'get-remote' : (upstream) => {
  24009. // var __args = {
  24010. // repo : args?.repo || processedArgs._[1]
  24011. // }
  24012. var repo = upstream.repo;
  24013. var serial_perform = (repo) => {
  24014. return [
  24015. ['git', ['remote', '-vvvv'], { cwd: instanceroot + '/' + repo,
  24016. evaluateResult : function( issuccess, result){
  24017. if(!issuccess || +result.code !== 0) throw Object.assign( new Error('git branch -vvvv crashed'), result);
  24018. // origin https://git.bbh.org.in/chess/elxr (fetch)
  24019. var match = new RegExp(`${upstream.remotename}\\\s(\\S+)/${repo}.git\\s\\(fetch\\)`).exec(result.messages.join(' '));
  24020. if(match) { upstream.url = match[1]; }
  24021. else throw Object.assign( new Error('No upstream found for active branch'), result)
  24022. return upstream
  24023. }}]
  24024. ]
  24025. };
  24026. return perform( serial_perform, repo )
  24027. }
  24028. , 'get-upstream' : (args) => {
  24029. var __args = {
  24030. repo : args?.repo || processedArgs._[1]
  24031. };
  24032. var repo = __args.repo;
  24033. var serial_perform = (repo) => {
  24034. return [
  24035. ['git', ['branch', '-vvvv'], { cwd: instanceroot + '/' + repo,
  24036. evaluateResult : function( issuccess, result){
  24037. if(!issuccess || +result.code !== 0) throw Object.assign( new Error('git branch -vvvv crashed'), result);
  24038. var match = /\*\s(\S+)\s\S+\s\[(\S+)\/(\S+).*?\].*?/.exec(result.messages.join(' '));
  24039. if(match) { var upstream = { remotename : match[2], branch : match[1], remotebranch : match[3] }; }
  24040. else throw Object.assign( new Error('No upstream found for active branch'), result)
  24041. if(args?.remotes) {
  24042. var r = args.remotes[upstream.remotename];
  24043. if(!r) return op['get-remote'](upstream)
  24044. r.branch = upstream.branch;
  24045. r.remotebranch = upstream.remotebranch;
  24046. return r
  24047. }
  24048. return op['get-remote'](upstream)
  24049. }}]
  24050. ]
  24051. };
  24052. return perform( serial_perform, repo )
  24053. }
  24054. , 'init-gitea': (user) => {
  24055. user = user || processedArgs._[1];
  24056. if (!user) throw 'User name required'
  24057. var serial_perform_init_gitea = (repo) => {
  24058. // console.log(repo)
  24059. return [
  24060. ['git', ['remote', 'add', 'chess', `${selectedinstance.reposerver}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  24061. , ['git', ['remote', 'set-url', '--push', 'chess', 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  24062. , ['git', ['remote', 'set-url', 'userfork', `${selectedinstance.reposerver}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  24063. ]
  24064. };
  24065. var perform_init_gitea = (dir) => {
  24066. op['is-git-repo'](dir).then((logEntry) => {
  24067. // console.log(code)
  24068. if (logEntry.success) {
  24069. nodeShellExec('git', ['remote', 'get-url', 'chess'], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  24070. console.log('skipped : ' + dir.name + ', reason : Already has remote chess ');
  24071. })
  24072. .catch((e) => {
  24073. perform( serial_perform_init_gitea, dir.name );
  24074. });
  24075. }
  24076. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  24077. }).catch((e) => {
  24078. // console.log('Failed : ' + dir.name)
  24079. });
  24080. };
  24081. dirs(perform_init_gitea);
  24082. }
  24083. , 'syncmaster': (label) => {
  24084. // Usage :
  24085. // elxr pull -- Defaults to run config
  24086. Object.assign({}, process.env); // Shallow clone it.
  24087. // console.dir(env)
  24088. console.log('Running exlr pull : ' + path__default["default"].dirname(__dirname));
  24089. if (!processedArgs.runas) gitRepos.map((def) => performPull(def, def.branch || 'master'));
  24090. var etask = ()=>{
  24091. return any(elevatedRunasRepos.map((def) => performPull(def, def.branch || 'master'))).then(() => {
  24092. fs.writeFileSync('run.done', 'success');
  24093. }).catch(() => {
  24094. fs.writeFileSync('run.done', 'error');
  24095. })
  24096. };
  24097. etask.statuslog = statuslog;
  24098. etask.selectedinstance = selectedinstance;
  24099. etask.processedArgs = processedArgs;
  24100. etask.runtimestamp = runtimestamp;
  24101. etask.ENV = ENV;
  24102. return shell_verse.runElevated(etask)
  24103. }
  24104. , 'repo-relocate' : function(args){
  24105. // relocate a subfolder in source repo to same subfolder in target repo with history.
  24106. var args = args || {
  24107. remotebase : processedArgs._[4] || 'http://git.bbh/chess/'
  24108. , folder : processedArgs._[3] || 'server'
  24109. , sourcerepo : processedArgs._[2] || 'client'
  24110. , targetrepo : processedArgs._[1] || 'elixir-server'
  24111. };
  24112. var sourcerepooptions = { cwd: `${instanceroot}/relocate/${args.sourcerepo}`
  24113. // , stdio: ['pipe', process.stdout, process.stderr]
  24114. , inherit: true,
  24115. shell: true,
  24116. env: process.env
  24117. , runas: processedArgs.runas
  24118. };
  24119. return op['repo-split'](args).then(()=>{
  24120. return op['repo-merge'](args).then(()=>{
  24121. // cleanup folder from source.
  24122. var cmdseq = [
  24123. ['rm', ['-rf', `${args.folder}`], sourcerepooptions ]
  24124. // commits have to intentional...
  24125. // , ['git', ['commit', '-a', '-m', `relocate folder ${args.folder} to ${targetrepo}`], sourcerepooptions ]
  24126. ];
  24127. return any(cmdseq.map(getshelltask))
  24128. })
  24129. }).catch(e=>{console.error(e);})
  24130. }
  24131. , 'repo-split' : function(args) {
  24132. // https://gist.github.com/smdabdoub/17065c348289158277b5
  24133. /**
  24134. * Eg : folder, remotebase, sourcerepo, targetrepo
  24135. * args.folder = 'server'
  24136. * args.remotebase = 'https://git.bbh/chess/'
  24137. * args.sourcerepo = 'client'
  24138. * args.targetrepo = 'elixir-server'
  24139. */
  24140. var args = args || {
  24141. folder : 'server'
  24142. , remotebase : 'http://git.bbh/chess/'
  24143. , sourcerepo : 'client'
  24144. , targetrepo : 'elixir-server'
  24145. };
  24146. var options = { cwd: `${instanceroot}/relocate`
  24147. // , stdio: ['pipe', process.stdout, process.stderr]
  24148. , inherit: true,
  24149. shell: true,
  24150. env: process.env
  24151. , runas: processedArgs.runas
  24152. };
  24153. var cmdseq = [
  24154. // create a temporary working dir in current folder where we started execution.
  24155. ['mkdir', [ '-p', `${instanceroot}/relocate`]]
  24156. , ['git', ['clone', `${args.remotebase}${args.sourcerepo}`], options ]
  24157. , ['git', ['clone', `${args.sourcerepo}`, `relocate-${args.sourcerepo}-${args.folder}`], options]
  24158. , ['git', ['clone', `${args.remotebase}${args.targetrepo}`, `relocate-${args.targetrepo}-${args.folder}`], options]
  24159. ];
  24160. return any(cmdseq.map(getshelltask)).then(() => {
  24161. // , ['git', ['subtree', 'split', '-P', `${args.folder}`, '-b', `relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
  24162. // split doesnt retain folder structure we need to move and commit ourselves through a branch to retain history...
  24163. // , ['git', [`checkout relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
  24164. // , ['mkdir', [`${args.folder}`], sourcerepooptions]
  24165. // , ['git', ['mv', `!(${args.folder})`, `${args.folder}`], sourcerepooptions ] // requires shopt -s extglob
  24166. // , ['git', ['commit', `-m`, 'Moved to same subfolder after subtree split in branch'] , sourcerepooptions]
  24167. // subtree split and filter-branch are options. We currently use repo-filter.
  24168. return op['filter-repo'](args)
  24169. }).catch(e=>{console.error(e); throw 'failed'})
  24170. }
  24171. , 'repo-merge' : function(args) {
  24172. // Merge source repo into target repo
  24173. var args = args || {
  24174. folder : 'server'
  24175. , remotebase : 'http://git.bbh/chess/'
  24176. , sourcerepo : 'client'
  24177. , targetrepo : 'elixir-server'
  24178. };
  24179. ({ cwd: `${instanceroot}/relocate/relocate-${args.sourcerepo}-${args.folder}`
  24180. // , stdio: ['pipe', process.stdout, process.stderr]
  24181. , inherit: true,
  24182. shell: true,
  24183. env: process.env
  24184. , runas: processedArgs.runas
  24185. });
  24186. var targetrepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.targetrepo}-${args.folder}`
  24187. // , stdio: ['pipe', process.stdout, process.stderr]
  24188. , inherit: true,
  24189. shell: true,
  24190. env: process.env
  24191. , runas: processedArgs.runas
  24192. };
  24193. var cmdseq = [
  24194. ['git', ['pull', `../relocate-${args.sourcerepo}-${args.folder}`, `master`, '--allow-unrelated-histories']
  24195. , targetrepooptions ]
  24196. // , ['git', ['push', targetrepooptions ] // manual push for now..
  24197. ];
  24198. return any(cmdseq.map(getshelltask)).catch(e=>{console.error(e);})
  24199. }
  24200. , 'filter-repo' : function(args){
  24201. // Merge source repo into target repo
  24202. var args = args || {
  24203. folder : 'server'
  24204. , remotebase : 'http://git.bbh/chess/'
  24205. , targetrepo : 'elixir-server'
  24206. };
  24207. var targetrepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.sourcerepo}-${args.folder}`
  24208. , inherit: true, shell: true
  24209. , env: process.env
  24210. , runas: processedArgs.runas
  24211. };
  24212. var cmdseq = [
  24213. // git checkout -b feature/merge-old-project
  24214. // git remote add src-project ../src-project
  24215. ['git', ['filter-repo', '--path', `${args.folder}`], targetrepooptions ]
  24216. ];
  24217. return any(cmdseq.map(getshelltask)).catch(e=>{console.error(e); throw 'failed' })
  24218. }
  24219. , 'filter-branch' : function(preservefolder, repo){
  24220. // https://stackoverflow.com/questions/359424/detach-move-subdirectory-into-separate-git-repository
  24221. // git subtree split -P <name-of-folder> -b <name-of-new-branch>
  24222. // Preserve a specific folder.
  24223. // PB : TODO -- filter-branch has known issues. Explore subtree and filter-repo...
  24224. /*
  24225. git clone repo reposplit
  24226. git filter-branch --tag-name-filter cat --prune-empty --subdirectory-filter {{folder}} -- --all
  24227. git remote rm origin
  24228. */
  24229. throw 'filter-repo-history not yet implmented pls refer to manual commands in code.'
  24230. }
  24231. // , 'repo-merge-folder' : function(mergetarget, mergesource, mergefolder){
  24232. // // Merge repo2 into a subfolder in repo1
  24233. // // https://alexharv074.github.io/puppet/2017/10/04/merge-a-git-repository-and-its-history-into-a-subdirectory-of-a-second-git-repository.html
  24234. // // https://thoughts.t37.net/merging-2-different-git-repositories-without-losing-your-history-de7a06bba804
  24235. // /*
  24236. // cd repo1
  24237. // git remote add -f tempmergesource ../{{mergesource}}/.git
  24238. // git merge -s ours --no-commit tempmergesource/master --allow-unrelated-histories
  24239. // git read-tree --prefix={{mergefolder}} -u tempmergesource/master:
  24240. // git commit
  24241. // // Repair History
  24242. // // === git filter-branch --tree-filter '(echo === $GIT_COMMIT:; git ls-tree $GIT_COMMIT) >> /tmp/tree.log'
  24243. // #!/usr/bin/env bash
  24244. // first=ed4f16becc2f03820c164e0617bb98f12ff49ef0
  24245. // last=038e26e21bd60fa265d6637261f3bc918780d2e8
  24246. // subdir=server
  24247. // git filter-branch --tree-filter '
  24248. // first='"$first"'
  24249. // last='"$last"'
  24250. // subdir='"$subdir"'
  24251. // log_file=/tmp/filter.log
  24252. // [ "$GIT_COMMIT" = "$first" ] && seen_first=true
  24253. // if [ "$seen_first" = "true" ] && [ "$seen_last" != "true" ]; then
  24254. // echo "=== $GIT_COMMIT: making changes"
  24255. // files=$(git ls-tree --name-only $GIT_COMMIT)
  24256. // mkdir -p $subdir
  24257. // for i in $files; do
  24258. // mv $i $subdir || echo "ERR: mv $i $subdir failed"
  24259. // done
  24260. // else
  24261. // echo "=== $GIT_COMMIT: ignoring"
  24262. // fi \
  24263. // >> $log_file
  24264. // [ "$GIT_COMMIT" = "$last" ] && seen_last=true
  24265. // status=0 # tell tree-filter never to fail
  24266. // '
  24267. // git remote rm tempmergesource
  24268. // */
  24269. // // better alternative for history
  24270. // /**
  24271. // *
  24272. // git clone git@server.com:old-project.git
  24273. // git clone git@server.com:new-project.git
  24274. // cd old-project
  24275. // mkdir old-project
  24276. // git mv !(old-project) old-project
  24277. // ls -la and gt mv hidden files ....
  24278. // git commit -a -S -m “Moving old project into its own subdirectory”
  24279. // cd ../new-project
  24280. // git remote add old-project ../old-project
  24281. // git fetch old-project
  24282. // git checkout -b feature/merge-old-project
  24283. // git merge -S --allow-unrelated-histories old-project/master
  24284. // git push origin feature/merge-old-project
  24285. // git remote rm old-project
  24286. // */
  24287. // throw 'merge-repos not yet implmented pls refer to manual commands in code.'
  24288. // }
  24289. , 'pull' : (label) => {
  24290. // Usage :
  24291. // elxr pull -- Defaults to run config
  24292. return elxr.getpulltask(selectedinstance)
  24293. }
  24294. , 'isInstalled': () => {
  24295. return nodeShellExec('where', [processedArgs._[1]], { inherit: true }).then(() => {
  24296. console.log(processedArgs._[1] + ' exists.');
  24297. return true;
  24298. });
  24299. }
  24300. , 'c' : ()=>{
  24301. }
  24302. , 'i' : () => {
  24303. var tasks = [];
  24304. // tasks.push(op['pull']);
  24305. tasks.push(getShellTask.apply(null, ['rm', [instanceroot + '/run.js'], { ignorefailures: true }]));
  24306. tasks.push(op['use']); // Will pull repos...
  24307. op['npmi'].statuslog = statuslog;
  24308. tasks.push(shell_verse.getNonElevatedTask(op['npmi'])); // We do not run npm i with elevated privilege for security reasons.
  24309. // var tasksdefs = [
  24310. // ['elxr', ['pull']]
  24311. // , ['elxr', ['use', 'elixir']]
  24312. // , ['elxr', ['npmi']]
  24313. // ]
  24314. // tasksdefs.forEach(tasksdef=>{
  24315. // tasks.push( ()=> nodeShellExec.apply(null, tasksdef) )
  24316. // })
  24317. return any(tasks);
  24318. }
  24319. , 'npmi': () => {
  24320. var tasks = [];
  24321. // Build fails without babel...
  24322. tasks.push(getShellTask(
  24323. 'npm',[ 'i', '-g', 'babel-cli' ]
  24324. ) );
  24325. var npmbuildrepos = ['loopback-jsonapi-model-serializer'];
  24326. // npmbuildrepos = []
  24327. npmbuildrepos.forEach(repo => {
  24328. tasks.push(() => {
  24329. return nodeShellExec('npm', ['i --force'], {
  24330. inherit: true, shell: true
  24331. , cwd: instanceroot + '/' + repo
  24332. , env: process.env
  24333. , title: `npm i for ${repo}`
  24334. }).catch((e) => {
  24335. console.error('Ignoring Benign Error'); console.error(e);
  24336. }).then(() => {
  24337. console.log(`--npm run build for ${repo}--------------------`);
  24338. return nodeShellExec('npm', ['run build'], {
  24339. inherit: true, shell: true
  24340. , cwd: instanceroot + '/' + repo
  24341. , env: process.env
  24342. , title: `npm run build for ${repo}`
  24343. }).then(Tasq.then).catch(Tasq.catch)
  24344. })
  24345. });
  24346. });
  24347. return any(tasks).then(() => {
  24348. gitRepos.push({ repo : 'chess-server-lib/server'});
  24349. gitRepos = gitRepos.concat(elevatedRunasRepos);
  24350. // console.dir(gitRepos)
  24351. // throw ""
  24352. // gitRepos = [
  24353. // // 'bbhverse', 'serververse', 'elixir-server',
  24354. // // 'clientverse',
  24355. // 'client'
  24356. // ];
  24357. var rmtasks = [];
  24358. var repotasks = [];
  24359. var env = Object.assign({}, process.env);
  24360. delete env.NODE_ENV;
  24361. gitRepos.forEach(repodef => {
  24362. rmtasks.push(
  24363. // () => {
  24364. // console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
  24365. // return nodeShellExec(`"${gitbash}"`, ['-c', '"rm package-lock.json"'], {
  24366. callshelltask(['rm', ['package-lock.json'], {
  24367. inherit: true, shell: true
  24368. , cwd: instanceroot + '/' + repodef.repo
  24369. , env: process.env
  24370. , title: `rm 'package-lock.json' for ${repodef.repo}`
  24371. }])
  24372. .then(()=>{
  24373. console.log(`--rm package-lock.json for ${repodef.repo}--------------------`);
  24374. }).catch((e) => { console.error(e); })
  24375. // }
  24376. );
  24377. if (npmbuildrepos.indexOf(repodef.repo) < 0) {
  24378. repotasks.push(
  24379. () => {
  24380. console.log(`--npm i for ${repodef.repo}--------------------`);
  24381. var p = nodeShellExec('npm', ['i', '--force'], {
  24382. inherit: true, shell: true
  24383. , cwd: instanceroot + '/' + repodef.repo
  24384. , env
  24385. , title: `npm i for ${repodef.repo}`
  24386. }).then(Tasq.then).catch(Tasq.catch);
  24387. return p;
  24388. });
  24389. }
  24390. });
  24391. // NODE_ENV=development DEBUG=loopback:connector:mssql node --tls-min-v1.0 --inspect elixir/server.js
  24392. // PB : NOTE -- npm i for client does not complete when NODE_ENV=production
  24393. // therefore bower doesn't get installed !!! which then fails installing the bower dependenciew !!!
  24394. // We work around this by running npm i for client without any NODE_ENV which probably defualts to development.
  24395. // PB : TODO -- Investigate why NODE_ENF has an impact on npm i !??
  24396. // Second time try also doesnt work.
  24397. // repotasks.push(
  24398. // () => {
  24399. // var env = Object.assign({}, process.env)
  24400. // delete env.NODE_ENV
  24401. // console.log(`--------------------second time npm i for client--------------------`)
  24402. // return nodeShellExec(`"${gitbash}"`, ['-c', '"npm i --force"'], {
  24403. // // return nodeShellExec('npm', ['i --force'], {
  24404. // inherit: true, shell: true
  24405. // , cwd: instanceroot + '/' + 'client'
  24406. // , env
  24407. // , title: `npm i for client`
  24408. // }).then(Tasq.then).catch(Tasq.catch)
  24409. // })
  24410. var bowerRepos = [{ repo : 'client'}];
  24411. var bowertasks = [];
  24412. bowerRepos.forEach(repodef => {
  24413. bowertasks.push(() => {
  24414. console.log(instanceroot + '/' + repodef.repo + '/node_modules/bower/bin/bower');
  24415. // var p = nodeShellExec('node_modules/bower/bin/bower', ['install'], {
  24416. var p = nodeShellExec(`"${gitbash}"`, ['-c', '"node_modules/bower/bin/bower i"'], {
  24417. inherit: true, shell: true
  24418. , cwd: instanceroot + '/' + repodef.repo
  24419. , env: process.env
  24420. , title: `bower i for ${repodef.repo}`
  24421. }).then(Tasq.then).catch(Tasq.catch);
  24422. return p;
  24423. });
  24424. });
  24425. // console.log('rmtasks.length : ' + rmtasks.length)
  24426. return Promise.all(rmtasks).then(() => any(repotasks)).then(()=>any(bowertasks));
  24427. }).catch(e => {
  24428. console.error(e);
  24429. }).finally(statuslog.finally)
  24430. }
  24431. , 'start': (args) => {
  24432. var label = clioverrides.cmd;
  24433. var env = Object.assign({}, process.env); // Shallow clone it.
  24434. env.NODE_ENV = clioverrides.node_env || 'development';
  24435. var nodecmd = clioverrides.node_env === 'development' ? 'nodemon' : 'node';
  24436. function startFn( o ){
  24437. var cmd = [nodecmd, [`--inspect=${o.debugport}`, '--preserve-symlinks', o.script]];
  24438. console.log(`Starting ${o.name}.`);
  24439. var childPromise = nodeShellExec('cmd', ['/k', getCmdString(cmd) ], {
  24440. // inherit : true,
  24441. shell: true,
  24442. detached: true,
  24443. stdio: 'ignore',
  24444. cwd: instanceroot + o.path
  24445. , env: env
  24446. });
  24447. var child = childPromise.process;
  24448. var cpid = child.pid;
  24449. if (typeof child.pid !== 'undefined') {
  24450. childPromise.then(()=>{
  24451. console.log(` *** started Elixir Loopback Server PID(${cpid}) : NODE_ENV=${clioverrides.node_env} ${cmd}`);
  24452. fs.writeFileSync('.elixir-server.elixir.server.pid', '' + cpid);
  24453. })
  24454. .catch(e => console.errror(e) );
  24455. }
  24456. }
  24457. if(clioverrides.node_env === 'development') {
  24458. env.DEBUG = 'loopback:connector:' + dbForLabel(label);
  24459. startFn( { debugport : 9228, script : 'elixir/server.js', name : 'Elixir Loopback Server', path : '/' + 'elixir-server' } );
  24460. startFn( { debugport : 9227, script : 'bin/www', name : 'Express Server', path : '/' + 'chess-server-lib/server' } );
  24461. // cmd = 'node'()
  24462. // nodeShellExec('node', ['--inspect=9226', ' bin/www'], {
  24463. // inherit : true,
  24464. // shell: true, detached: true,
  24465. // cwd : 'qms/server',
  24466. // env: env,
  24467. // shell : true
  24468. // })
  24469. // nodeShellExec('ember', ['s'], {
  24470. // // inherit : true,
  24471. // shell: true, detached: true,
  24472. // cwd : 'client/',
  24473. // env: env
  24474. // })
  24475. console.log('Starting Elixir Client Host.');
  24476. var cmd = ['ember', ['s']];
  24477. var childPromise = nodeShellExec(...cmd, {
  24478. // var childPromise = nodeShellExec('node', ['--inspect=9227', './node_modules/.bin/ember', 's'], {
  24479. // PB : TODO -- ember debugging.
  24480. // inherit : true,
  24481. shell: true,
  24482. detached: true,
  24483. stdio: 'ignore',
  24484. cwd: instanceroot + '/' + 'client'
  24485. , env: env
  24486. });
  24487. // .catch(e=>console.error(e))
  24488. child = childPromise.process;
  24489. if (typeof child.pid !== 'undefined') {
  24490. console.log(`started Elixir Client Host PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  24491. fs.writeFileSync('.client.server.pid', child.pid, {
  24492. encoding: 'utf8'
  24493. });
  24494. }
  24495. }
  24496. }
  24497. , 'stop': (label) => {
  24498. const kill = treeKill;
  24499. var serverPid = fs.readFileSync('.elixir-server.elixir.server.pid', {
  24500. encoding: 'utf8'
  24501. });
  24502. fs.unlinkSync('.elixir-server.elixir.server.pid');
  24503. console.log(serverPid);
  24504. kill(serverPid);
  24505. serverPid = fs.readFileSync('.express.server.pid', {
  24506. encoding: 'utf8'
  24507. });
  24508. fs.unlinkSync('.express.server.pid');
  24509. console.log(serverPid);
  24510. kill(serverPid);
  24511. }
  24512. , 'model' : () => {
  24513. var etask = ()=>{
  24514. var tasks = [
  24515. () => {
  24516. var p = nodeShellExec('mklink', [ `${processedArgs._[2]}.json`
  24517. , `..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`], {
  24518. inherit: true, shell: true
  24519. , cwd : instanceroot + `/${selectedinstance.instanceName}-server/${selectedinstance.instanceName}/models`
  24520. , title: `mklink ${processedArgs._[2]}.json ..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`
  24521. , env: process.env
  24522. }).catch((e) => { console.error(e); });
  24523. return p;
  24524. }
  24525. ];
  24526. return any(tasks).then(() => {
  24527. fs.writeFileSync('run.done', 'success');
  24528. }).catch(() => {
  24529. fs.writeFileSync('run.done', 'error');
  24530. })
  24531. };
  24532. etask.statuslog = statuslog;
  24533. etask.selectedinstance = selectedinstance;
  24534. etask.processedArgs = processedArgs;
  24535. etask.runtimestamp = runtimestamp;
  24536. etask.ENV = ENV;
  24537. return shell_verse.runElevated(etask)
  24538. }
  24539. , 'use' : () => {
  24540. // use a certain named instance.
  24541. // Eg :
  24542. // 1) elxr use elixir
  24543. // 2) elxr use cihsr
  24544. // If environment is not specified defaults to development.
  24545. // 1) NODE=test elxr use elixir
  24546. /*// Steps
  24547. 1) Delete Config and Data symlinks
  24548. 2) Make Links for config ({{name}}-config-{{node_env}}) and data with the NODE_ENV specified or default to dev
  24549. 3) Iterates all repos and pull all. 'git', ['pull', '--all'].
  24550. 4) Iterates all repos and checkout to the ENV specified. 'git', ['checkout', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  24551. 5) Iterates all repos and merge from source configured in mergesource. 'git', ['merge', mergesource],
  24552. */
  24553. // We no longer need to check ruans.. ??? if we were initiated from self invoked privileged shell ?
  24554. if (( /*processedArgs.runas && processedArgs.runas !== 'self' &&*/ !processedArgs.force) &&
  24555. runconfig.NODE_ENV && runconfig.NODE_ENV === (selectedinstance.node_env || runconfig.NODE_ENV) &&
  24556. selectedinstance.instanceName && runconfig.use === selectedinstance.instanceName) {
  24557. console.log(`No change detected. Already using requested specs : ${runconfig.NODE_ENV} ${runconfig.use}`);
  24558. if (processedArgs.runas) { fs.writeFileSync('run.done', 'success'); }
  24559. if (existsSync('config') && existsSync('data')){
  24560. return
  24561. }
  24562. }
  24563. var tasks = [
  24564. () => {
  24565. var promise = new Promise((resolve, reject)=>{
  24566. existslink('config', function(err, data){
  24567. if(data) {
  24568. shell_verse.removeJuncionOrLink('config')
  24569. .then(()=>{resolve(true);})
  24570. .catch((err) => { console.log('Ignoring benign error : ' + err); return resolve(true); });
  24571. }
  24572. else resolve(false);
  24573. });
  24574. });
  24575. return promise;
  24576. },
  24577. () => {
  24578. var promise = new Promise((resolve, reject)=>{
  24579. existslink('data', function(err, data){
  24580. if(data) {
  24581. shell_verse.removeJuncionOrLink('data')
  24582. .then(()=>{resolve(true);})
  24583. .catch((err) => { console.log('Ignoring benign error : ' + err); return resolve(true); });
  24584. }
  24585. else resolve(false);
  24586. });
  24587. });
  24588. return promise;
  24589. },
  24590. ];
  24591. runconfig.NODE_ENV = process.env.NODE_ENV = process.env.NODE_ENV || runconfig.NODE_ENV || 'development';
  24592. if (processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1];
  24593. if (!runconfig.use && selectedinstance.instanceName) runconfig.use = selectedinstance.instanceName;
  24594. if (!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' }
  24595. // console.log(process.env.cwd)
  24596. fs.writeFileSync(instanceroot + '/run.js', 'module.exports = ' + JSON.stringify(runconfig));
  24597. var branch = checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV;
  24598. var performPullOrCloneForBranch = (def)=>{
  24599. var promise = Promise.resolve(true);
  24600. if (!branch) {
  24601. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo);
  24602. promise = nodeShellExec.apply(null, dscoverbranchcmd).then(__branch=>{ branch = __branch;})
  24603. .catch((e) => { console.error(e); return { error: true, message: repo } });
  24604. }
  24605. return promise = promise.then(()=>{ return elxr.getpulltask(def)() }).catch(e => { console.error( 'performPullOrCloneForBranch : Failed ' + e );})
  24606. };
  24607. var performCloneAndCheckout = null;
  24608. // cant use git checkout -b it fails when branch already exists.
  24609. var performCheckout = performCloneAndCheckout = (def) => {if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  24610. return performPullOrCloneForBranch(def).then(()=>{
  24611. nodeShellExec('git', ['checkout', def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  24612. // return nodeShellExec('git', ['switch', '-m', '-C', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  24613. // inherit : true, shell: true,
  24614. cwd: instanceroot + '/' + def.repo
  24615. // , stdio : ignore // Use when we want to silence output completely.
  24616. , runas: processedArgs.runas
  24617. , title: `git checkout ${def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${def.repo}`
  24618. }).then(()=>{ console.log( `SUCCESS : git checkout ${def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${def.repo}` ); }).catch((e) => { console.error(e); return { error: true, message: def.repo } });
  24619. })
  24620. };
  24621. var mergeSources = {
  24622. 'development': null,
  24623. 'test': 'master',
  24624. 'production': 'master'
  24625. };
  24626. var mergesource = mergeSources[checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV];
  24627. // Checkout is reduced to pull provided the current branch is the targetbranch
  24628. if(branch === mergesource) performCheckout = (def) => {
  24629. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo);
  24630. return nodeShellExec.apply(null, dscoverbranchcmd).then(__branch=>{
  24631. if(branch === __branch) return performCloneAndCheckout(def)
  24632. return performPullOrCloneForBranch(def)
  24633. })
  24634. .catch((e) => { console.error(e); return { error: true, message: repo } })
  24635. };
  24636. // else performCheckout = (def) => { return performPullOrCloneForBranch(def) }
  24637. var performPullAll = (def) => {
  24638. if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  24639. return nodeShellExec('git', ['pull', '--all'], {
  24640. // inherit : true, shell: true,
  24641. cwd: instanceroot + '/' + def.repo
  24642. , runas: processedArgs.runas
  24643. , title: `git pull -all for ${checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} ${def.repo}`
  24644. }).catch((e) => { console.error(e); return { error: true, message: def.repo } })
  24645. };
  24646. var excludeCheckouts = Object.assign(exludeMergeRepos);
  24647. delete excludeCheckouts[`elixir-config-${runconfig.NODE_ENV}`];
  24648. delete excludeCheckouts[`cihsr-config-${runconfig.NODE_ENV}`];
  24649. var performMerge = (def) => {
  24650. if (exludeMergeRepos[def.repo]) return Promise.resolve({ 'skipped': true })
  24651. return nodeShellExec('git', ['merge', mergesource], {
  24652. inherit: true, shell: true,
  24653. cwd: instanceroot + '/' + def.repo
  24654. , runas: processedArgs.runas
  24655. }).catch((e) => { console.error(e); })
  24656. };
  24657. if(!mergesource || branch === mergesource) performMerge = () => { return Promise.resolve(true) };
  24658. // var performRepoOperation = function(def) {
  24659. // elevatedRunasRepos.map((repo) => enqueueCheckout({ repo, branch: def.branch, requiresElevation : true }))
  24660. // return any(gitRepos.map((repo) => performCheckout({ repo, branch: def.branch})))
  24661. // }
  24662. return any(tasks).then(() => {
  24663. var task = ()=>{
  24664. //target is the env is we specify in elxr use command. Default is dev
  24665. //Switch to target branch
  24666. return any(gitRepos.map((repodef) => { return performCheckout({ repo : repodef.repo, branch}).catch(e=>{ console.log(e); }) } ))
  24667. // pull or clone target branch
  24668. .then(() => {
  24669. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  24670. return any(gitRepos.map((repo) => performPullAll(repo)))
  24671. })
  24672. // switch to source branch
  24673. .then( () => {
  24674. if(!mergesource || branch === mergesource ) return Promise.resolve(true) // Dont do anything if there is no source to merge from.
  24675. return any(gitRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource})))
  24676. })
  24677. //Pull on merge source branch
  24678. .then( () => {
  24679. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  24680. return any(gitRepos.map((repo) => performPullAll(repo)))
  24681. })
  24682. //Switch to target branch
  24683. .then( () => {
  24684. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  24685. return any(gitRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch})))
  24686. })
  24687. .then( //Merge source branch to target branch
  24688. () => {
  24689. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  24690. return any(gitRepos.map((repo) => performMerge( repo ))).catch(err => { console.error('error in performMerge ' + err); })
  24691. })
  24692. };
  24693. task.statuslog = statuslog;
  24694. var netask = shell_verse.getNonElevatedTask(task);
  24695. var eltask = ()=> {
  24696. var opts = {
  24697. inherit: true, shell: true
  24698. , cwd : instanceroot
  24699. , env: process.env
  24700. };
  24701. var tasks = [
  24702. () => {
  24703. // Use junctions to avoid npm package issues
  24704. var target = runconfig.use + '-' + 'config' + '-' + process.env.NODE_ENV;
  24705. var p = shell_verse.createJuntionOrLink('config', target, opts);
  24706. return p;
  24707. }
  24708. ];
  24709. // if (processedArgs._[1]) {
  24710. tasks = tasks.concat( [
  24711. () => {
  24712. var dataToLink = runconfig.use + '-data' + '-' + process.env.NODE_ENV;
  24713. if(!existsSync(dataToLink)) dataToLink = runconfig.use + '-data';
  24714. var p = shell_verse.createJuntionOrLink('data', dataToLink, opts);
  24715. return p;
  24716. }
  24717. ]
  24718. );
  24719. // }
  24720. return any(tasks).then(()=>{
  24721. // checkout target branch
  24722. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  24723. // pull or clone target branch
  24724. .then(() => {
  24725. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  24726. return any(elevatedRunasRepos.map((repo) => performPullAll(repo)))
  24727. })
  24728. // switch to source branch
  24729. .then( () => {
  24730. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  24731. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource, requiresElevation : true})))
  24732. })
  24733. //Pull on merge source branch
  24734. .then( () => {
  24735. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  24736. return any(elevatedRunasRepos.map((repodef) => performPullAll({repo : repodef.repo, requiresElevation : true })))
  24737. })
  24738. //Switch to target branch
  24739. .then( () => {
  24740. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  24741. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  24742. })
  24743. .then( //Merge source branch to target branch
  24744. () => {
  24745. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  24746. return any(elevatedRunasRepos.map((repodef) => performMerge({ repo : repodef.repo, requiresElevation : true }))).catch(err => { console.error('error in performMerge ' + err); })
  24747. })
  24748. .then(() => {
  24749. fs.writeFileSync('run.done', 'success');
  24750. }).catch(() => {
  24751. fs.writeFileSync('run.done', 'error');
  24752. })
  24753. })
  24754. };
  24755. eltask.statuslog = statuslog;
  24756. eltask.selectedinstance = selectedinstance;
  24757. eltask.processedArgs = processedArgs;
  24758. var etask = shell_verse.getElevatedTask(eltask);
  24759. return etask().then( ()=>{ return netask() })
  24760. }).catch((e) => {
  24761. fs.writeFileSync('run.done', 'error : ' + e);
  24762. })
  24763. // Antibiotic stewardship program.
  24764. // 1st use is fine.
  24765. // Max vials dispense
  24766. // 2nd use Pharmacy needs justification Form.
  24767. // Approval after a certain period of time.
  24768. }
  24769. , 'g' : () => {
  24770. if (processedArgs.h) {
  24771. console.log('elxr g model [modelname] => generate a model named [modelname]');
  24772. console.log('elxr g vmodel [modelname] => generate a model named [modelname]');
  24773. console.log('elxr g vmodel [modelname] --server=true => generate only a server model named [modelname]');
  24774. console.log('elxr g vmodel [modelname] --all=true => default generate server and client model named [modelname]');
  24775. console.log('elxr g => regenerate all known models');
  24776. return
  24777. }
  24778. // nodeShellExec('npm', ['init', '-y'], options);
  24779. // nodeShellExec('npm', ['init', '-y'], options);
  24780. // })
  24781. var g = {
  24782. 'client': () => {
  24783. // ember new --skip-bower --no-welcome --skip-git -b {{blueprint}}
  24784. console.info('Creating new ember client named : ' + processedArgs._[2]);
  24785. nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
  24786. stdio: ['pipe', process.stdout, process.stderr],
  24787. inherit: true,
  24788. shell: true,
  24789. cwd: path__default["default"].dirname(__dirname),
  24790. env: env
  24791. });
  24792. },
  24793. 'modelr': () => {
  24794. var tasks = [
  24795. () => {
  24796. var p = nodeShellExec('"ember"', [
  24797. 'g'
  24798. , 'modelr'
  24799. , processedArgs._[2]], {
  24800. inherit: true, shell: true, env: process.env
  24801. }).then(() => {
  24802. console.log('Blueprint generation complete for : ' + processedArgs._[2]);
  24803. return true;
  24804. }).catch((e) => { console.error(e); });
  24805. return p;
  24806. },
  24807. () => {
  24808. var chromePrefsFile = "C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data\\chess\\Preferences";
  24809. var chromeprefs = fs.readFileSync(chromePrefsFile, { encoding: 'utf8' });
  24810. chromeprefs = JSON.parse(chromeprefs);
  24811. var previous = chromeprefs.download.default_directory;
  24812. var parentDir = path__default["default"].dirname(__dirname);
  24813. chromeprefs.download.default_directory = parentDir + "\\client\\app\\templates\\components\\resource";
  24814. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs));
  24815. // PB : TODO -- detect where chrome is installed.
  24816. // PB : TODO -- set the download dir to the place where files are needed.
  24817. var p = nodeShellExec('"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"', [
  24818. '--user-data-dir="C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data"'
  24819. , '--profile-directory="chess"'
  24820. , 'http://localhost:4200/admin/crud/create/' + processedArgs._[2]], {
  24821. inherit: true, shell: true
  24822. , env: process.env
  24823. }).then(() => {
  24824. chromeprefs.download.default_directory = previous;
  24825. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs));
  24826. return true;
  24827. }).catch((e) => { console.error(e); });
  24828. return p;
  24829. }
  24830. ,
  24831. () => {
  24832. console.log('Browser process should have closed here....');
  24833. return true;
  24834. }
  24835. ];
  24836. any(tasks);
  24837. }
  24838. , 'undefined' : ()=>{
  24839. console.warn('Are you sure you want to refresh all the models.');
  24840. throw 'NOT YET IMPLMENTED'
  24841. }
  24842. , 'vmodel' : (options)=>{
  24843. // node --inspect-brk elxr/index.js g vmodel qlabresults --server=true
  24844. options = options || {
  24845. generate : processedArgs['all'] ? 'all' : processedArgs['server'] ? 'server' : processedArgs['client'] ? 'client' : null
  24846. };
  24847. if(!options.generate) return 'Nothing specified for generation'
  24848. var name = processedArgs._[2];
  24849. if(!name) return 'No name specified for generation'
  24850. var templateverse = `${selectedinstance.root}/bbhverse/__universe__/vmodel`;
  24851. // var templateverse = `${selectedinstance.root}/bbhverse/__universe__/vmodel/__base__-server-lib/common/lib`
  24852. var workingtarget = `${selectedinstance.root}/.elxr/run-${runtimestamp}/temp/vmodelworkingdir`;
  24853. var destination = `${selectedinstance.root}`;
  24854. // Create a tmp working copy for staging the changes.
  24855. return copyrecursive(templateverse, workingtarget).then( r => {
  24856. var base = 'chess'; // -- The server base from where this instance was dervied from.
  24857. var patternsubstitutions = [
  24858. { strOrregexp : /(__name__)/g, substitutes : [name]}
  24859. , { strOrregexp : /(__instance__)/g, substitutes : [selectedinstance.instanceName]}
  24860. , { strOrregexp : /(__base__)/g, substitutes : [base]}
  24861. , { strOrregexp : /(__microservice__)/g, substitutes : [selectedinstance.microservice || selectedinstance.instanceName]}
  24862. , { strOrregexp : /(__microclient__)/g, substitutes : [selectedinstance.microclient || `${selectedinstance.instanceName}-client` || 'client']} // PB : TODO -- elixir-client etc... use a config to find the microclient..
  24863. ];
  24864. var options = { source : templateverse, target : workingtarget
  24865. , base , destinationroot : destination, workingtarget
  24866. , processingtype : 'inplace', sourcetype : 'filesystem', patternsubstitutions };
  24867. var actions = [
  24868. fswalk( workingtarget, options
  24869. , [ function(t, o){
  24870. // A series of tasks to be executed on each pattern in patternsubstitutions.
  24871. return any([
  24872. // PB : TODO -- Contentreplace is better addressed in memory instead of file IO so do all regexps in sequence in one shot and then rename.
  24873. ()=>{ return fscontentreplace( t, o ) }
  24874. , ()=>{ return fsrename( t, o ) }
  24875. ])
  24876. }] )
  24877. // Post process links in place.
  24878. , () => dirs((innernode, s, t, o ) => fswalk( path__default["default"].join(workingtarget, innernode.name), bbhverse.assign({}, o, { innernode }), [ templatelink ] )
  24879. , workingtarget, null, options)
  24880. // Move to the final destination. Whole tree should move only top level folders are required.
  24881. // , () => fswalk( workingtarget, options, [ fsrename ])
  24882. // , () => dirs( ( child, src, target, options )=>{ return fs.renameSync(path.join(src, child.name), path.join(target, child.name) ) }
  24883. // , workingtarget, destination )
  24884. ];
  24885. return any(actions);
  24886. })
  24887. }
  24888. };
  24889. g[processedArgs._[1]]();
  24890. }
  24891. , 'create' : () => { return createInstance(selectedinstance) }
  24892. , 'httpget' : () => {
  24893. // RESTAPI.get({
  24894. // hostname: 'git.bbh',
  24895. // // port: 443,
  24896. // protocol : 'http:',
  24897. // path: '/',
  24898. // method: 'GET'
  24899. // }, function(data){ console.log(data)}, function(error){ console.log(error)} )
  24900. return createInstance(selectedinstance)
  24901. }
  24902. , 'getuser' : ()=>{ return prerequisites.git.getuser().then(u=>{ console.log(u);}) }
  24903. , 'switch user' : (tousername)=>{ return GIT['switch user'](tousername) }
  24904. };
  24905. // independent elxr cli operations
  24906. var noprerequisites = {
  24907. add : true, 'set-url' : true, 'repo-relocate' : true
  24908. , remote : true, 'c' : true, 'h' : true
  24909. , httpget : true, getuser : true
  24910. , 'switch user' : true
  24911. , 'switch' : true
  24912. // , 'undefined' : true
  24913. };
  24914. var reconfirmcmds = { create : true };
  24915. var subcommandlabels = {
  24916. remote : (`remote ${processedArgs._[1] || ''}`).trim()
  24917. , switch : (`switch ${processedArgs._[1] || ''}`).trim()
  24918. };
  24919. var cmds = {
  24920. remote : {
  24921. // return a interpreted set of arguments for this comd run context.
  24922. interpret() {
  24923. return { cmd : subcommandlabels['remote'], runchoice : 'c' }
  24924. }
  24925. }
  24926. , resetgitconfig : {
  24927. // return a interpreted set of arguments for this comd run context.
  24928. cmdFn : resetgitconfig
  24929. , interpret() { return { cmd : 'resetgitconfig' } }
  24930. , getPossiblePrompts(){ return {} }
  24931. , noprerequisites : true
  24932. , independentcmd : true
  24933. }
  24934. , reinit : {
  24935. // return a interpreted set of arguments for this comd run context.
  24936. cmdFn : reinit
  24937. , interpret() { return { cmd : 'reinit' } }
  24938. , getPossiblePrompts(){ return {} }
  24939. , noprerequisites : true
  24940. , independentcmd : true
  24941. , requiresElevation : true
  24942. , requires : [ generateDependencies ]
  24943. }
  24944. , init : {
  24945. // return a interpreted set of arguments for this comd run context.
  24946. cmdFn : init
  24947. , interpret() { return { cmd : 'init' } }
  24948. , getPossiblePrompts(){ return {} }
  24949. , noprerequisites : true
  24950. , independentcmd : true
  24951. , requiresElevation : true
  24952. , requires : [ generateDependencies ]
  24953. }
  24954. , switch : {
  24955. interpret() {
  24956. return { cmd : subcommandlabels['switch'], runchoice : 'c', username : processedArgs._[2]
  24957. , reposerver : __default.reposerver
  24958. }
  24959. }
  24960. , getPossiblePrompts(){ return { username : true, reposerver : 'http://git.bbh' } } // Requires only one argument...
  24961. }
  24962. , 'switch user' : {
  24963. interpret() {
  24964. return { cmd : subcommandlabels['switch'], runchoice : 'c', username : processedArgs._[2] }
  24965. }
  24966. , getPossiblePrompts(){ return { username : true } } // Requires only one argument...
  24967. }
  24968. // Flat linear structure. Every subcommand should have a top level 'label'
  24969. , 'users' : {
  24970. // default to the users list
  24971. subcommands : { list : {} }
  24972. , cmdFn : ()=>getCredentials() // default
  24973. , cmd : 'users'
  24974. , noprerequisites : true
  24975. }
  24976. , 'users list' : {
  24977. cmdFn : ()=>getCredentials()
  24978. , cmd : 'users list'
  24979. , noprerequisites : true
  24980. }
  24981. , 'get-upstream' :{
  24982. cmdFn : op['get-upstream'] // default
  24983. , cmd : 'get-upstream'
  24984. , noprerequisites : true
  24985. , independentcmd : true
  24986. , interpret() { return { cmd : 'get-upstream' } }
  24987. , getPossiblePrompts(){ return {} }
  24988. }
  24989. , 'g' : {
  24990. cmdFn : op['g'] // default
  24991. , cmd : 'g'
  24992. , noprerequisites : true
  24993. , getPossiblePrompts(){ return {} }
  24994. }
  24995. , 'link' : {
  24996. 'cmd' : 'link'
  24997. // , cmdFn : function( sourecpath, filename, dir ){
  24998. // var afterTargetPath = (dir)=>{
  24999. // console.dir(dir);
  25000. // // var tasks = [
  25001. // // () => {
  25002. // // // Use junctions to avoid npm package issues
  25003. // // var p = nodeShellExec('mklink', ['/J', filename, sourecpath], {
  25004. // // inherit: true, shell: true
  25005. // // , cwd : dir || instanceroot
  25006. // // , env: process.env
  25007. // // }).catch((e) => { console.error(e) })
  25008. // // return p;
  25009. // // }
  25010. // // ];
  25011. // }
  25012. // // console.dir(process.env)
  25013. // if(!dir) getCurrentFolder().then(afterTargetPath);
  25014. // else afterTargetPath(dir)
  25015. // }
  25016. , cmdFn : function( cmdopts ){
  25017. // sourecpathandfile should include name of file name
  25018. targetfilename = cmdopts.targetfilename || processedArgs._[1];
  25019. // console.log(processedArgs)
  25020. if(!targetfilename) return Promise.reject('error no file provided for linking')
  25021. targetdir = cmdopts.targetdir || process.env.wd;
  25022. sourecpathandfile = cmdopts.sourecpathandfile || path__default["default"].normalize(`../../node_modules/chess-server-lib/common/models/${targetfilename}`);
  25023. var tasks = [
  25024. () => {
  25025. // Use junctions to avoid npm package issues
  25026. var p = nodeShellExec('mklink', [path__default["default"].normalize(`${targetdir + '/' + targetfilename}`), sourecpathandfile], {
  25027. inherit: true, shell: true
  25028. , cwd : targetdir
  25029. , env: process.env
  25030. }).catch((e) => { console.error(e); });
  25031. return p;
  25032. }
  25033. ];
  25034. var etask = ()=>{
  25035. return any(tasks).then(() => {
  25036. fs.writeFileSync('run.done', 'success');
  25037. }).catch(() => {
  25038. fs.writeFileSync('run.done', 'error');
  25039. })
  25040. };
  25041. etask.statuslog = statuslog;
  25042. etask.selectedinstance = selectedinstance;
  25043. etask.processedArgs = processedArgs;
  25044. etask.runtimestamp = runtimestamp;
  25045. etask.ENV = ENV;
  25046. return shell_verse.runElevated(etask)
  25047. }
  25048. , noprerequisites : true
  25049. , privileged : true
  25050. }
  25051. };
  25052. var elxrcmd = (function(){
  25053. var __cmdprototype = function(){};
  25054. function subcommandlabelFor(cmd, sub){ return (`${cmd} ${sub || ''}`).trim() }
  25055. var __cmd = {
  25056. interpret() { return { cmd : this.cmd } }
  25057. , getPossiblePrompts(){ return {} } // Requires only one argument...
  25058. , cmdFn : ()=>{ throw "Elxr Unknown command."}
  25059. , finalized : true
  25060. };
  25061. function __createO(o){
  25062. if(o.finalized) return o;
  25063. var subs = Object.keys(cmds[o.cmd].subcommands || {});
  25064. // console.log(subs)
  25065. // console.log(o)
  25066. subs.forEach(sub=>elxrcmd.create( cmds[subcommandlabelFor(o.cmd, sub)] ));
  25067. var created = bbhverse.assign_core( { keycase: true, arraymergetype : bbhverse.assign_core.DISTINCT_UNION }
  25068. , {}, __cmd, cmds[o.cmd], o);
  25069. cmds[o.cmd] = created;
  25070. op[o.cmd] = created.cmdFn;
  25071. noprerequisites[o.cmd] = created.noprerequisites;
  25072. return created.cmdFn;
  25073. }
  25074. function create(o){ return __createO(o) }
  25075. __cmdprototype.create = create;
  25076. return __cmdprototype;
  25077. })();
  25078. elxrcmd.create(cmds['users']);
  25079. elxrcmd.create(cmds['g']);
  25080. elxrcmd.create(cmds['link']);
  25081. var interpretrun = function(){
  25082. var cmd = processedArgs._[0];
  25083. var clioverrides = { cmd };
  25084. processedArgs.node_env ? clioverrides.node_env = processedArgs.node_env
  25085. : (process.env.NODE_ENV && process.env.NODE_ENV.trim())
  25086. ? clioverrides.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) : null;
  25087. return cmds[cmd] ? cmds[cmd].interpret() : (function(){
  25088. processedArgs._[1] ? clioverrides.instanceName = processedArgs._[1]: null;
  25089. // return clioverrides
  25090. cmds[cmd] = {
  25091. interpret() {
  25092. return Object.assign(clioverrides, { cmd, runchoice : 'c' })
  25093. }
  25094. , getPossiblePrompts(){ return { cmd, username : true, password : true,
  25095. instanceName : true, instanceType : true, reposerver : true } }
  25096. };
  25097. return cmds[cmd].interpret()
  25098. })()
  25099. };
  25100. var clioverrides = interpretrun();
  25101. console.dir(clioverrides);
  25102. var cliname = 'elxr';
  25103. var ver = '1.1';
  25104. var readme = `
  25105. Command syntax examples
  25106. elxr
  25107. Displays help. Same as elxr h
  25108. elxr i
  25109. Runs interactive propmts to help choose installation options.
  25110. NODE_ENV={{yourenvironment}} elxr {{cmd}} {{instancename}} {{otheroptions}}
  25111. General command syntax.
  25112. Eg: NODE_ENV=development elxr pull elixir
  25113. Note : Although {{instancename}} is generally a positional parameter supplied immediately after the cmd for most cmd's.
  25114. The specific cmd defines what the value is interpreted as.
  25115. There are several cmds that do not require an {{instancename}} parameter.
  25116. Eg: elxr remote remove origin
  25117. Git operations or passthrough external commands on all repository folders in you working directory.
  25118. Main objectives.
  25119. elxr cli is a wrapper around other shell commands and api based operations.
  25120. One of the main objetives it achives is ease of use of repeating an individual cmd multiple times on all targets.
  25121. Eg: A git operation like pull can be repeated consistently on a set of git repositories.
  25122. `;
  25123. var help = `
  25124. ${readme}
  25125. # list of commands... please refer dveloper documentation for ${cliname}
  25126. \r\n\t${
  25127. Object.keys(op).join('\r\n\t')
  25128. }
  25129. `;
  25130. var elxr = {
  25131. help() {
  25132. return source.cyanBright(`
  25133. -------------------------------------------------------------------------------
  25134. *** BBH Elixir ***
  25135. -------------------------------------------------------------------------------
  25136. elxr ${ver}
  25137. A cli tool for chess
  25138. ${help}
  25139. -------------------------------------------------------------------------------
  25140. `)
  25141. }
  25142. , info() {
  25143. return source.cyanBright(`
  25144. -------------------------------------------------------------------------------
  25145. *** BBH Elixir ***
  25146. -------------------------------------------------------------------------------
  25147. elxr ${ver}
  25148. A cli tool for chess
  25149. -------------------------------------------------------------------------------
  25150. `)
  25151. }
  25152. , getpulltask(args){
  25153. // def can be an instance config
  25154. // Or an object with many repos and elevated repos
  25155. // Or a single repo ( Either Elevated or normal. )
  25156. // USAGE
  25157. // elxr pull elixir origin master
  25158. // elxr pull
  25159. // not all remote branches are setup to be tracked locally (respective remotes and branches).
  25160. // pull --all is useless. As it fetches all remotes and branches but only merges current branch.
  25161. // apart from remote tracking branches We are interested in pulling from all remotes and relavant branches.
  25162. // The branch pipline should feed back to master
  25163. // master -> test -> stage -> release[nnnn] -> production
  25164. // (master) <= git merge [all remotes] production && git merge [all remotes] release[nnnn]
  25165. // git merge [all remotes] stage && git merge [all remotes] test && git merge [all remotes] master
  25166. ({
  25167. remotename : args.remotename|| processedArgs._[2]
  25168. , url : args.url || processedArgs._[3]
  25169. , branch : args.branch || processedArgs._[4] // If branch not specified opearte on the current branch of each working directorys
  25170. });
  25171. // var commands = [
  25172. // // ['git', ['checkout', __args.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]]
  25173. // ,
  25174. // ]
  25175. // var parameters = ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  25176. // var pullCmd = [ gitbash
  25177. // , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  25178. // , { cwd: instanceroot + '/' + repo, title : 'pull all remotes for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }]
  25179. var def = args || {
  25180. repos : selectedinstance.repos,
  25181. elevated : selectedinstance.elevated
  25182. };
  25183. var elevatedpulltasks = null;
  25184. if(def.repo) {
  25185. // Single repo case.
  25186. if(def.repo.requiresElevation) {
  25187. var t1 = function() {
  25188. return performPull(def).then(() => {
  25189. return true;
  25190. }).catch((e) => {
  25191. console.error(e);
  25192. }).finally(Traq.finally)
  25193. };
  25194. t1.statuslog = statuslog;
  25195. t1.selectedinstance = selectedinstance;
  25196. t1.processedArgs = processedArgs;
  25197. elevatedpulltasks = shell_verse.getElevatedTask( t1 );
  25198. }
  25199. else {
  25200. var t2 = function(){
  25201. return performPull(def).then(() => {
  25202. console.log('pulled ' + JSON.stringify(def.repo));
  25203. return true;
  25204. }).catch((e) => {
  25205. console.error(e);
  25206. }).finally(Traq.finally)
  25207. };
  25208. t2.statuslog = statuslog;
  25209. var regularpulltasks = shell_verse.getNonElevatedTask( t2 );
  25210. }
  25211. if(elevatedpulltasks) return elevatedpulltasks //getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  25212. else return regularpulltasks // getTaskWithoutElevation({ regularpulltasks})
  25213. }
  25214. // console.log(`-------------------Processing pull for : ${def.repo} ${def.branch}`)
  25215. console.dir(def);
  25216. Object.assign({}, process.env); // Shallow clone it.
  25217. console.log('Running exlr pull : ' + path__default["default"].dirname(__dirname));
  25218. processedArgs.useGitPull || false;
  25219. if(def.elevated || def.repos) {
  25220. if(def.elevated) def.requiresElevation = true;
  25221. else delete def.requiresElevation;
  25222. }
  25223. else {
  25224. if(def.requiresElevation) def.elevated = [def];
  25225. else def.repos = [def];
  25226. }
  25227. var regularpulltasks = function(){ return Promise.resolve(true) };
  25228. if(def.elevated){
  25229. elevatedpulltasks = function() {
  25230. var eBatch = [];
  25231. def.elevated.map((def) => getPullTask(def, null, null, null, eBatch));
  25232. return shell_verse.runElevatedBatch(eBatch).then(() => {
  25233. return true;
  25234. }).catch((e) => {
  25235. console.error(e);
  25236. })
  25237. };
  25238. elevatedpulltasks.statuslog = statuslog;
  25239. }
  25240. if(def.repos) {
  25241. var regularpulltasks = function(){
  25242. var pendingpulls = [];
  25243. def.repos.forEach((def) => {
  25244. pendingpulls.push(
  25245. performPull(def).then(()=>{ console.log('pulled ' + JSON.stringify(def.repo)); })
  25246. .catch(e => { console.log(e); throw e })
  25247. );
  25248. });
  25249. return any(pendingpulls).finally(Traq.finally)
  25250. };
  25251. regularpulltasks.statuslog = statuslog;
  25252. }
  25253. // if(elevatedpulltasks) return getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  25254. // else return getTaskWithoutElevation({ regularpulltasks})
  25255. return any([ elevatedpulltasks, regularpulltasks ])
  25256. }
  25257. };
  25258. function preworkerconfig(){
  25259. // Everything runs after this check is completed. Elevation occurs out of process when needed.
  25260. gitRepos = selectedinstance.repos;
  25261. // gitRepos = ['chess-server-lib'];
  25262. // Repositiories that have symlinks that require elevated priviletes in windows to create symlinks
  25263. elevatedRunasRepos = selectedinstance.elevated;
  25264. // Repos that should excluded from merge for releases...
  25265. exludeMergeRepos = selectedinstance.exludeMergeRepos;
  25266. }
  25267. // The main elxr cli process
  25268. function elxrworker() {
  25269. var __runcmd = function (label) {
  25270. var distinquishedlabel = subcommandlabels[label] || label;
  25271. return op[distinquishedlabel] ? op[distinquishedlabel](processedArgs) : null;
  25272. };
  25273. // --runas
  25274. if (processedArgs.runas) {
  25275. // Weve been asked to run in priviledged mode. Check if we already are privileged.
  25276. // return __runcmd('runas')
  25277. // we no longer have a runas function. This has been moved to shellverse.requestElevation...
  25278. // Each task has knowledge of requiring elevation and will handle elevation requests as needed. Preferably the task will participate in a batch and queue itself.
  25279. //
  25280. return __runcmd(processedArgs.label || processedArgs._[0] || 'undefined');
  25281. }
  25282. else return __runcmd(processedArgs.label || processedArgs._[0] || 'undefined');
  25283. }
  25284. // function acquireChoices(selectedinstance) {
  25285. // var hasconfig = false;
  25286. // console.warn(chalk.cyan(`
  25287. // -------------------------------------------------------------------------------
  25288. // Could not locate your preferred configuration (you may not specified it)
  25289. // You should fork the default chess configuration to customize and make it
  25290. // your own instance with a named config as
  25291. // {{yourowninstancename}}-config-{{yourchosenenvironment}}
  25292. // And then run this tool as follows
  25293. // NODE_ENV={{yourchosenenvironment}} elxr i {{yourowninstancename}}
  25294. // OR
  25295. // Run this tool with the following command to use a quick start default.
  25296. // elxr --default
  25297. // OR
  25298. // Choose one of the options below to run interactively.
  25299. // We will run your choice at the next prompt.
  25300. // -------------------------------------------------------------------------------
  25301. // `))
  25302. // var choices = getInteractionPoints(detectedinstanceoptions, __interactive_prompts)
  25303. // var todo = any( __interactive_prompts(selectedinstance, choices) ).then(()=>{
  25304. // return initinstances(selectedinstance)
  25305. // })
  25306. // // var prompt = cli.prompter;
  25307. // // return prompt.ask(`Choose an option :
  25308. // // d) Install the default chess instance.
  25309. // // => elxr i chess node_env=development --default
  25310. // // n) Create your custom new instance interactively
  25311. // // => elxr i {{instanceName}} node_env={{environment}}
  25312. // // i) Choose an instance and environment to install
  25313. // // => elxr i {{instanceName}} node_env={{environment}}
  25314. // // c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  25315. // // => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  25316. // // h) Help
  25317. // // q) Quit
  25318. // // Default <= d
  25319. // // : `).then((choice) => {
  25320. // // if (choice && choice === 'd' || !choice) {
  25321. // // processedArgs._[0] = 'i'
  25322. // // selectedinstance.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess'
  25323. // // selectedinstance.node_env = processedArgs.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env || 'development'
  25324. // // selectedinstance.reposerver = 'https://git.bbh.org.in'
  25325. // // }
  25326. // // else if (choice === 'h') {
  25327. // // processedArgs._[0] = 'h'
  25328. // // fs.writeFileSync('run.done', 'noop help');
  25329. // // console.log(elxr.help()); process.exit()
  25330. // // }
  25331. // // else if (choice === 'n' || choice === 'i') {
  25332. // // var p1 = cli.prompter;
  25333. // // return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  25334. // // processedArgs._[0] = 'i'
  25335. // // selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName;
  25336. // // return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  25337. // // selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  25338. // // if (choice === 'n') {
  25339. // // selectedinstance.reposerver = 'https://git.bbh.org.in'
  25340. // // console.warn(
  25341. // // chalk.magenta('No Option Available. Your account may not have privileges. You can request here http://git.bbh.org.in/chess'))
  25342. // // process.exit();
  25343. // // }
  25344. // // return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  25345. // // selectedinstance.reposerver = reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  25346. // // })
  25347. // // })
  25348. // // })
  25349. // // } else if (choice === 'c') {
  25350. // // var p1 = cli.prompter;
  25351. // // return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  25352. // // selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName
  25353. // // return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  25354. // // selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  25355. // // return p1.ask(`Enter cmd :
  25356. // // p) pull
  25357. // // Default <= p
  25358. // // : `).then(function (cmd) {
  25359. // // if (!cmd || cmd === 'p') {
  25360. // // processedArgs._[0] = 'pull'
  25361. // // }
  25362. // // else processedArgs._[0] = cmd
  25363. // // return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  25364. // // selectedinstance.reposerver = reposerver || selectedinstance.reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  25365. // // })
  25366. // // })
  25367. // // })
  25368. // // })
  25369. // // } else {
  25370. // // console.log(chalk.gray(`Default option not exercised. Please follow manual instructions to customize your instance here http://git.bbh.org.in/chess and try again.`));
  25371. // // fs.writeFileSync('run.log', ', ' + JSON.stringify({ success: 'quit without execution' }), { 'flag': 'a+' })
  25372. // // fs.writeFileSync('run.done', 'noop quit');
  25373. // // process.exit()
  25374. // // }
  25375. // // })
  25376. // }
  25377. // PB : TODO -- Move this to utils assign... as an array merge option.
  25378. var mergeObjByKey = function(arrOfObjs, keyName) {
  25379. var keyedDistinct = {};
  25380. var distinctArrOfObjs = [];
  25381. arrOfObjs.forEach( o => {
  25382. if(o) (keyedDistinct[o[keyName]] || (keyedDistinct[o[keyName]] = []) ).push(o);
  25383. });
  25384. Object.keys(keyedDistinct).forEach(key => {
  25385. distinctArrOfObjs.push( bbhverse.assign_core( { arraymergetype : bbhverse.assign_core.DISTINCT_UNION }
  25386. , ...keyedDistinct[key] ) ); // PB : TODO -- Shallow use utils.assign
  25387. });
  25388. return distinctArrOfObjs;
  25389. };
  25390. var cacheWriteInstanceConfig = function(chessinstances){
  25391. var instanceName = chessinstances['current_run'].instanceName;
  25392. var node_env = chessinstances['current_run'].node_env;
  25393. // PB : TODO -- We should be able to do simply merge at a higher level using assign
  25394. chessinstances[instanceName][node_env].repos = mergeObjByKey(chessinstances[instanceName][node_env].repos || [], 'repo') ;
  25395. chessinstances[instanceName][node_env].elevated = mergeObjByKey(chessinstances[instanceName][node_env].elevated || [], 'repo') ;
  25396. fs.writeFileSync(instanceroot + '/chessinstances.js', 'module.exports = ' + JSON.stringify(chessinstances, null, 2) + '', { 'flag': 'w' });
  25397. };
  25398. var hostname = os__default["default"].hostname();
  25399. var clustername = null; // PB : TODO -- Prompt to acquire.
  25400. var configs = (function(){
  25401. // We need to discover and use the most specialized config available.
  25402. // Two passes are required as the config currently cloned may be switched by the discovery.
  25403. // If the repo name is the same but has different remotes the newly acquired config from multiple remotes may
  25404. // iteself redefine the remotes, repos and servers for the config which we need to honor..
  25405. return {
  25406. ownerClusterNodeConfig(selected) {
  25407. // Hostname and therefore clusternodename can be anything and can participate in many clusters.
  25408. // Also many cluster node instance can be running as a set of services on the same host on the same port with ( specific domain names )
  25409. var clusternodename = hostname || `CHESS0001${selected.username}`; // Cluster node names need to be unique accross all clusters to avoid collitions.
  25410. clustername = clustername || `${selected.username}-CHESS-${selected.node_env}`;
  25411. return __acquireConfig(selected, { remote : 'userfork' } // PB : TODO -- accessiblity state should switch to public etc..
  25412. , selected.instanceName + '-config-' + selected.node_env + `-${clusternodename}`
  25413. , function(e){ console.info('Customized node level config not found. This is not an Error. Will attempt with owner level config.');
  25414. return e; }
  25415. )
  25416. }
  25417. , ownerInstnace(selected) { return __acquireConfig(selected, { remote : 'userfork' }
  25418. , selected.instanceName + '-config-' + selected.node_env
  25419. , function(e){ console.info('Customized user level config not found. This is not an Error. Will attempt global common instance config.');
  25420. return e }
  25421. )
  25422. }
  25423. // PB : TODO -- Use the ORG level instance before falling back to common Instance coz common instance may not exist for certain orgs.
  25424. , commonInstance(selected) { return __acquireConfig(selected, { defaultRepoOwner }
  25425. , undefined
  25426. , function(e){
  25427. // PB : TODO -- console.info('This is probably an error unless the user is asking to create a new instance with this name.')
  25428. statuslog.statuslog(e, e);
  25429. var manifestpath = path__default["default"].normalize(selected.root + '/' + selected.instanceName + '-config-' + selected.node_env + '/repo-manifest');
  25430. bbhverse.assign_core( { keycase : true, arraymergetype : bbhverse.assign_core.DISTINCT_UNION }
  25431. , selectedinstance, commonjsRequire(manifestpath,"/$$rollup_base$$")( null, { utils: bbhverse, username : selectedinstance.username, instanceName : selectedinstance.instanceName
  25432. , node_env : selectedinstance.node_env, reposerver : 'https://git.bbh.org.in' } ));
  25433. console.dir(selectedinstance.repos);
  25434. // Config from server always override merges into selection except for the current selection.
  25435. // PB : TODO -- utils.assign Array merges are non-distinct...
  25436. if(selectedinstance?.repos && !selectedinstance.repos[0].repo) {
  25437. console.warn('repo manifest has obsolete format. Attempting upgrade.');
  25438. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } });
  25439. }
  25440. if(selectedinstance?.elevated && !selectedinstance.elevated[0]?.repo) {
  25441. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.');
  25442. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } });
  25443. }
  25444. chessinstances[selected.instanceName][selected.node_env] = selectedinstance = bbhverse.assign_core( { arraymergetype : bbhverse.assign_core.DISTINCT_UNION }
  25445. , selected, selectedinstance);
  25446. chessinstances[selected.instanceName][selected.node_env].reposervers = Array.from(new Set(chessinstances[selected.instanceName][selected.node_env].reposervers));
  25447. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0]; // PB : TODO -- Attempt first one that is available and online...
  25448. cacheWriteInstanceConfig(chessinstances);
  25449. // ENV.NODE_ENV = selectedinstance.node_env;
  25450. throw e
  25451. }
  25452. ) }
  25453. // , genericChessInstance(selected) { return __acquireConfig(selected) }
  25454. }
  25455. })();
  25456. var eNotImplemented = function(){
  25457. console.error('Not yet implemented');
  25458. process.exit();
  25459. };
  25460. // PB : TODO -- accept additional arg - an array specifying custom configPriority.
  25461. var acquireConfig = function(slections){
  25462. var configPriority = [ 'ownerClusterNodeConfig', 'ownerInstnace', 'commonInstance' /*, 'genericChessInstance'*/ ];
  25463. return any(configPriority.map(cfg => { return function() { return configs[cfg](slections) } } ), true, true).then(()=>{
  25464. return acquireData(slections)
  25465. })
  25466. };
  25467. var instanceData = (function(){
  25468. return {
  25469. ownerClusterNodeData(selected) {
  25470. var clusternodename = hostname || `CHESS0001${selected.username}`; // Cluster node names need to be unique accross all clusters to avoid collitions.
  25471. clustername = clustername || `${selected.username}-CHESS-${selected.node_env}`;
  25472. return __acquireData(selected, { remote : 'userfork' }
  25473. , selected.instanceName + '-data-' + selected.node_env + `-${clusternodename}`
  25474. , function(e){ console.info('Customized node level data not found. This is not an Error. Will attempt with owner level config.');
  25475. return e; }
  25476. )
  25477. }
  25478. , ownerInstnace(selected) { return __acquireData(selected, { remote : 'userfork' }
  25479. , selected.instanceName + '-data-' + selected.node_env
  25480. , function(e){ console.info('Customized user level data not found. This is not an Error. Will attempt global common instance config.');
  25481. return e }
  25482. )
  25483. }
  25484. // PB : TODO -- Use the ORG level instance before falling back to common Instance coz common instance may not exist for certain orgs.
  25485. , commonInstance(selected) { return __acquireData(selected, { defaultRepoOwner }
  25486. // , function(e){ console.info('This is probably an error unless the user is asking to create a new instance with this name.') }
  25487. ) }
  25488. , genericChessInstance(selected) { return __acquireData(selected) }
  25489. }
  25490. })();
  25491. var acquireData = function(slections){
  25492. var configPriority = [ 'ownerClusterNodeData', 'ownerInstnace', 'commonInstance' /*, 'genericChessInstance'*/ ];
  25493. return any(configPriority.map(cfg => { return function() { return instanceData[cfg](slections) } } ), true, true)
  25494. };
  25495. function reinit(){
  25496. sysAddPathVar('%AppData%\\npm');
  25497. resetgitconfig();
  25498. }
  25499. function init(){
  25500. sysAddPathVar('%AppData%\\npm');
  25501. resetgitconfig();
  25502. }
  25503. function resetgitconfig(){
  25504. // https://git-scm.com/book/en/v2/Git-Tools-Credential-Storage
  25505. // Git Credential storage...
  25506. // git config --global credential.helper 'store --file ~/.gitcredentials'
  25507. // git credential-store --file ~/.gitcredentials store
  25508. // // notepad C:/Program Files/Git/etc/gitconfig
  25509. // git config --global --unset credential
  25510. // git config --edit --system
  25511. // git config --global credential.helper "store --file ~/gitcredentials"
  25512. // git credential fill
  25513. // git credential-store --file ~/git.store store
  25514. // Find system git config
  25515. // git config --global --edit
  25516. // git config --list --show-origin
  25517. // git config --list --show-origin --show-scope
  25518. // https://stackoverflow.com/questions/35942754/how-can-i-save-username-and-password-in-git
  25519. // Recipie
  25520. // git config --global --unset credentials.helper
  25521. // cd /path/to/my/repo
  25522. // git config --unset credential.helper
  25523. // git config credential.helper 'store --file ~/.git_repo_credentials'
  25524. // git config credential.*.username my_user_name
  25525. // git config credential.https://gitlab.com.username my_user_name
  25526. // git credential fill
  25527. // git config --global credential.modalprompt false // doesnst work.
  25528. // core askpass = ;;; https://stackoverflow.com/questions/37182847/how-do-i-disable-git-credential-manager-for-windows
  25529. var options = {
  25530. inherit: true, shell: true //, env: process.env
  25531. , cwd: instanceroot
  25532. , runas: processedArgs.runas
  25533. };
  25534. var task = ['git', ['config'], options];
  25535. var tasklist = [
  25536. // ['--global', '--unset credentials.helper']
  25537. // ['--unset', 'credentials.helper']
  25538. // ,
  25539. // ['credential.helper', `'store --file git_repo_credentials'`]
  25540. ['--global', 'credential.helper', "'store --file ~/.git_repo_credentials'"]
  25541. , ['--global', '--replace-all', 'user.name', 'pb']
  25542. , ['--global', '--replace-all', 'user.email', 'pradeep@bbh.org.in']
  25543. // , ['--list']
  25544. // , ['credential', 'fill']
  25545. ];
  25546. var onEachError = e => console.error( e.messages.join('\n') + e.result + '\n' + require$$0__default["default"].inspect(e) + '\n');
  25547. var shellT = (args) => { return getgitbashtask(args, onEachError)
  25548. // .catch(e => console.error( e.messages.join('\n') + e.result + '\n' + util.inspect(e) + '\n' + tasq.toString()) )
  25549. };
  25550. execserial(tasklist, task, shellT);
  25551. }
  25552. var createTasq = (args, shellT, onEachError) => {
  25553. var tasq = shellT ? shellT(args) : (() => { return nodeShellExec.apply(null, args).catch( onEachError || function(e){ console.error(e); } ) });
  25554. tasq.toString = function(){ return JSON.stringify(args)};
  25555. return tasq;
  25556. };
  25557. var execserial = function(tasklist, task, shellT){
  25558. var exec = (taskArgs)=>{
  25559. var thistask = task.concat();
  25560. thistask[1] = thistask[1].concat();
  25561. thistask[1].push.apply(thistask[1], taskArgs);
  25562. return createTasq(thistask, shellT)
  25563. };
  25564. return any(tasklist.map(exec))
  25565. };
  25566. var __acquireConfig = function (selected, options, configrepo, errHandler) {
  25567. configrepo = configrepo || selected.instanceName + '-config-' + selected.node_env;
  25568. var errorHandler = (e) => {
  25569. if(e.messages.join(' ').match(new RegExp (`fatal: unable to access '${selectedinstance.reposerver}/${selected.username || options.defaultRepoOwner}/${configrepo}.git/': Failed to connect to .*? port .*? after .*? ms: Timed out`))){
  25570. // console.error('Could not connect to repo server. Timed Out')
  25571. return cliverse.prompt( ['(y)es', '(n)o', '(r)etry'], 'Could not connect to repo server. Timed Out. Would you like to switch server ? (y/n) ', 'y' ).then(propValue => {
  25572. if(propValue === 'y') {
  25573. reconfirm = getReconfirmAll();
  25574. return startElxr()
  25575. }
  25576. else if(propValue === 'r'){
  25577. return acquireConfig(selected)
  25578. }
  25579. else process.exit();
  25580. })
  25581. }
  25582. if(e.messages.join(' ').match(new RegExp (`fatal: repository '${selectedinstance.reposerver}/${selected.username || options.defaultRepoOwner}/${configrepo}.git/' not found`))){
  25583. var choices = {
  25584. t : `install a new temporary local instance with this name ( will not persist ).
  25585. Use your own username for additional options. You can request for a username at chess@bbh.org.in )`
  25586. , e : 'exit' };
  25587. if(selectedinstance.username !== 'guest' && selectedinstance.username !== 'demo') {
  25588. choices = bbhverse.assign_core( { arraymergetype : bbhverse.assign_core.DISTINCT_UNION }
  25589. , {
  25590. i : 'create a new instance with this name => will fork the default config under your username'
  25591. , f : 'fork a new instance with this name for yourself for this node from another instance'
  25592. , o : 'fork a new instance with this name for your organization from another instance' // prompt organization name...
  25593. , c : 'create a custom config for yourself for this node' // prompt hostname as nodename
  25594. , p : 'create a custom config for yourself '
  25595. }, choices);
  25596. }
  25597. return cliverse.prompt( choices
  25598. , 'Config for instance not found. Would you like to ', 'e' ).then(propValue => {
  25599. if(propValue === 't') {
  25600. selectedinstance.local = true; return createInstance(selectedinstance)
  25601. }
  25602. if(propValue === 'i') return eNotImplemented()
  25603. if(propValue === 'f') return eNotImplemented()
  25604. if(propValue === 'o') return eNotImplemented()
  25605. if(propValue === 'c') return eNotImplemented() // return createLocalChessInsance(selectedinstance)
  25606. if(propValue === 'p') return eNotImplemented() // return createChessInstance(selectedinstance)
  25607. // if(propValue === 'o') createChessInstance(selectedinstance, orgname)
  25608. else process.exit();
  25609. })
  25610. }
  25611. console.warn(e);
  25612. throw e; //('Config acquisition failed.')
  25613. };
  25614. var successHandler = () => {
  25615. var manifestpath = path__default["default"].normalize(selected.root + '/' + selected.instanceName + '-config-' + selected.node_env + '/repo-manifest');
  25616. bbhverse.assign_core( { keycase : true, arraymergetype : bbhverse.assign_core.DISTINCT_UNION }
  25617. , selectedinstance, commonjsRequire(manifestpath,"/$$rollup_base$$")( null, { utils: bbhverse, username : selectedinstance.username, instanceName : selectedinstance.instanceName
  25618. , node_env : selectedinstance.node_env, reposerver : 'https://git.bbh.org.in' }));
  25619. console.dir(selectedinstance.repos);
  25620. // Config from server always override merges into selection except for the current selection.
  25621. // PB : TODO -- utils.assign Array merges are non-distinct...
  25622. if(!selectedinstance.repos[0].repo) {
  25623. console.warn('repo manifest has obsolete format. Attempting upgrade.');
  25624. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } });
  25625. }
  25626. if(selectedinstance.elevated[0] && !selectedinstance.elevated[0].repo) {
  25627. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.');
  25628. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } });
  25629. }
  25630. chessinstances[selected.instanceName][selected.node_env] = selectedinstance = bbhverse.assign_core( { arraymergetype : bbhverse.assign_core.DISTINCT_UNION }
  25631. , selected, selectedinstance);
  25632. chessinstances[selected.instanceName][selected.node_env].reposervers = Array.from(new Set(chessinstances[selected.instanceName][selected.node_env].reposervers));
  25633. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0]; // PB : TODO -- Attempt first one that is available and online...
  25634. cacheWriteInstanceConfig(chessinstances);
  25635. ENV.NODE_ENV = selectedinstance.node_env;
  25636. };
  25637. return performPull( selected.reposindexed[configrepo] || { repo : configrepo }
  25638. , null, selected.username || options.defaultRepoOwner, errHandler || errorHandler || ((e)=>{ throw e })).then( successHandler )
  25639. .catch( (e)=>{
  25640. // if(e){
  25641. if(Promise.resolve(e) === e) return e;
  25642. // console.error(e)
  25643. e.benign = true;
  25644. throw e; // Not a hard error but we need this for bcontinueonfailure as we still want to stop on firstsuccess.
  25645. // }
  25646. })
  25647. };
  25648. var __acquireData = function (selected, options, datarepo, errHandler) {
  25649. datarepo = datarepo || selected.instanceName + '-data';
  25650. var errorHandler = (e) => {
  25651. if(e.messages.join(' ').match(new RegExp (`fatal: unable to access '${selectedinstance.reposerver}/${selected.username || options.defaultRepoOwner}/${datarepo}.git/': Failed to connect to .*? port .*? after .*? ms: Timed out`))){
  25652. // console.error('Could not connect to repo server. Timed Out')
  25653. return cliverse.prompt( ['(y)es', '(n)o', '(r)etry'], 'Could not connect to repo server. Timed Out. Would you like to switch server ? (y/n) ', 'y' ).then(propValue => {
  25654. if(propValue === 'y') {
  25655. reconfirm = getReconfirmAll();
  25656. return startElxr()
  25657. }
  25658. else if(propValue === 'r'){
  25659. return acquireConfig(selected)
  25660. }
  25661. else process.exit();
  25662. })
  25663. }
  25664. if(e.messages.join(' ').match(new RegExp (`fatal: repository '${selectedinstance.reposerver}/${selected.username || options.defaultRepoOwner}/${datarepo}.git/' not found`))){
  25665. var choices = {
  25666. t : `install a temporary local data folder.
  25667. For more options. Request and use a personal username at chess@bbh.org.in )`
  25668. , e : 'exit' };
  25669. if(selectedinstance.username !== 'guest' && selectedinstance.username !== 'demo') {
  25670. choices = bbhverse.assign_core( { arraymergetype : bbhverse.assign_core.DISTINCT_UNION }
  25671. , {
  25672. i : 'create a new instance with this name => will fork the default config under your username'
  25673. , f : 'fork a new instance with this name for yourself for this node from another instance'
  25674. , o : 'fork a new instance with this name for your organization from another instance' // prompt organization name...
  25675. , c : 'create a custom config for yourself for this node' // prompt hostname as nodename
  25676. , p : 'create a custom config for yourself '
  25677. }, choices);
  25678. }
  25679. return cliverse.prompt( choices
  25680. , 'Data repo for instance not found. Would you like to ', 'e' ).then(propValue => {
  25681. if(propValue === 't') {
  25682. selectedinstance.local = true; return createInstanceData(selectedinstance)
  25683. }
  25684. if(propValue === 'i') return eNotImplemented()
  25685. if(propValue === 'f') return eNotImplemented()
  25686. if(propValue === 'o') return eNotImplemented()
  25687. if(propValue === 'c') return eNotImplemented() // return createLocalChessInsance(selectedinstance)
  25688. if(propValue === 'p') return eNotImplemented() // return createChessInstance(selectedinstance)
  25689. // if(propValue === 'o') createChessInstance(selectedinstance, orgname)
  25690. else process.exit();
  25691. })
  25692. }
  25693. console.warn(e);
  25694. throw e; //('Config acquisition failed.')
  25695. };
  25696. var successHandler = () => {
  25697. };
  25698. return performPull( selected.reposindexed[datarepo] || { repo : datarepo }
  25699. , null, selected.username || options.defaultRepoOwner, errHandler || errorHandler || ((e)=>{ throw e })).then( successHandler )
  25700. .catch( (e)=>{
  25701. // if(e){
  25702. if(Promise.resolve(e) === e) return e;
  25703. // console.error(e)
  25704. e.benign = true;
  25705. throw e; // Not a hard error but we need this for bcontinueonfailure
  25706. // }
  25707. })
  25708. };
  25709. var launchpath = path__default["default"].resolve(path__default["default"].normalize(process.env.wd));
  25710. var thisscriptdir = path__default["default"].normalize(__dirname); // PB : TODO -- Thisscriptdir could be dislocated when run as a standalone file... We need to detect this where and how we were run.
  25711. // The easisest would be to ask for a target directory and default to current dir....
  25712. // path.dirname(launchpath).split(path.sep).pop()
  25713. var parent = path__default["default"].dirname(launchpath);
  25714. var pp = launchpath;
  25715. var instancediscoverytasks = [];
  25716. while(parent !== pp){
  25717. instancediscoverytasks.push(
  25718. ((pa)=>{
  25719. var p = pa;
  25720. return function(){
  25721. return hasElxr(p).then((value)=>{
  25722. if(value) return p
  25723. // PB : TODO -- Using throw like this is not friendly with any...
  25724. throw Object.assign( new Error('Benign Failure in Batch')
  25725. , { value : false, benign : true });
  25726. })
  25727. }
  25728. })(pp)
  25729. );
  25730. pp = parent;
  25731. parent = path__default["default"].dirname(parent);
  25732. }
  25733. var instanceroot = null;
  25734. var detectInstanceRoot = any(instancediscoverytasks, true, true).then( ir => {
  25735. if(ir.error) { instanceroot = path__default["default"].normalize(thisscriptdir) === path__default["default"].normalize(launchpath) ? path__default["default"].normalize(thisscriptdir + '/..') : launchpath ; }
  25736. else instanceroot = ir.pVal;
  25737. return instanceroot
  25738. }).catch(()=>{
  25739. instanceroot = path__default["default"].normalize(thisscriptdir) === path__default["default"].normalize(launchpath) ? path__default["default"].normalize(thisscriptdir + '/..') : launchpath ;
  25740. });
  25741. // We first load the default and then override with a runconfig if it exists else we override with the interactive prompts.
  25742. // Then acquire and reload and replace this default.
  25743. var hasElxr = function(path, options, cb) {
  25744. // PB : TOOD -- Navigate up the folder chain to discover the relevant .elxr directory.
  25745. options = options || {};
  25746. var tasks = [
  25747. '/elxr' // Is there a subfolder named elxr
  25748. , '/elxr/.git' // which is self git repository
  25749. // , '/elxr/.elxr' // and has .elxr subfolder we now store this in the instanceroot.
  25750. , '/elxr/' + __ALIAS__STAMP__ // Which has our stamp.
  25751. ];
  25752. if(options.sync) { return tasks.earlyreduce((acc, tpath)=>{
  25753. var value = existsFolderSync(path + tpath);
  25754. return { value, done : acc && !value };
  25755. }).value }
  25756. if(cb) return cb(null, tasks.earlyreduce((acc, tpath)=>{
  25757. var value = existsFolderSync(path + tpath);
  25758. return { value, done : acc && !value };
  25759. }).value );
  25760. return Promise.resolve(tasks.earlyreduce((acc, tpath)=>{
  25761. var value = existsFolderSync(path + tpath);
  25762. return { value, done : acc && !value };
  25763. }).value);
  25764. };
  25765. var hasElxrSync = function(path){ return hasElxr(path, { sync :true}); };
  25766. var detectfromroot = function(root){
  25767. return { root, node_env : path__default["default"].basename(root), instanceName : path__default["default"].basename( path__default["default"].dirname(root) ) }
  25768. };
  25769. var detectLocalInstances = function () {
  25770. console.log(`launchpath = ${launchpath}`);
  25771. console.log(`thisscriptdir = ${thisscriptdir}`);
  25772. // PB : TODO -- !Postpone this.
  25773. console.log(`instanceroot = ${instanceroot}`); // Not yet confirmed...
  25774. // Note : Paths should already be normalized fefore this.
  25775. var root = instanceroot;
  25776. var detected = { root };
  25777. var instanceoptions = [clioverrides];
  25778. return hasElxr(launchpath).then( (elxrCliExists) => {
  25779. // We need a reference to the root director for elxr cli to be properly oriented.
  25780. if (( elxrCliExists && path__default["default"].normalize(launchpath + '/elxr')) === thisscriptdir) {
  25781. // We were run from the proper root with elxr cli in the subfolder.
  25782. instanceroot = root = launchpath;
  25783. instanceoptions.splice( 0, 0, detected = { root });
  25784. instanceoptions.splice( 0, 0, detectfromroot(root));
  25785. }
  25786. else {
  25787. if(path__default["default"].normalize(launchpath + '/elxr') === thisscriptdir) {
  25788. // elxrCliExists is false -- and yet thiscriptdir is still proper.
  25789. // PB : TODO -- Maybe a warning / abort if for some reason this scriptdir should not be taken over...
  25790. console.error('Warning : detected thisscriptdir as elxr subfolder but not recognized as elixir. git updates might fail.');
  25791. instanceroot = root = launchpath;
  25792. instanceoptions.splice( 0, 0, detected = { root });
  25793. instanceoptions.splice( 0, 0, detectfromroot(root));
  25794. }
  25795. else if (launchpath === thisscriptdir) {
  25796. var parentHasElxr = hasElxrSync(launchpath + '/..');
  25797. // PB : TODO -- verify if we have .elxr folder in the parent...
  25798. if(!parentHasElxr) {
  25799. // ! thisscriptdir is not elxr.
  25800. console.error('Invalid run location in subfolder that looks like elxr. We should probably abort as elxr will not sync.');
  25801. }
  25802. // Same directory doesn't mean we are being run from elxr sub directory.
  25803. // In standalone build script we may or not be in the same location.
  25804. if (BUILD_VERSION.indexOf('Version: {version} - built on {date}') > -1) {
  25805. // Unbuilt therefore we are in the elxr sub directory.
  25806. instanceroot = root = path__default["default"].normalize(launchpath + '/..');
  25807. instanceoptions.splice( 0, 0, detected = { root });
  25808. instanceoptions.splice( 0, 0, detectfromroot(root));
  25809. }
  25810. else {
  25811. // Built version.
  25812. // We could have been run from the elxr subfolder. Highly likely that the built version isn't the full elxr.
  25813. if(parentHasElxr) {
  25814. // Built version was run from the full elxr subfolder. Should work
  25815. // PB : TODO -- but we should switch to the full version...
  25816. instanceroot = root = path__default["default"].normalize(launchpath + '/..');
  25817. instanceoptions.splice( 0, 0, detected = { root });
  25818. instanceoptions.splice( 0, 0, detectfromroot(root));
  25819. }
  25820. else {
  25821. instanceroot = root = launchpath;
  25822. instanceoptions.splice( 0, 0, detected = { root });
  25823. instanceoptions.splice( 0, 0, detectfromroot(root));
  25824. // Assume current launchpath is a new instance and create.
  25825. // Figure out the instnace name and environment from parent folders as an alternative option with confirmation if not provided in the arguments.
  25826. // if(clioverrides.instanceName) {
  25827. // if(clioverrides.node_env) {
  25828. // instanceroot = root = path.normalize(launchpath + '/' + clioverrides.instanceName + '/' + clioverrides.node_env)
  25829. // instanceoptions.splice( 0, 0, detected = { root, instanceName : clioverrides.instanceName, node_env : clioverrides.node_env })
  25830. // // instanceoptions.splice( 0, 0, detectfromroot(root)) // This can be an option but is unnecessary unless a confirmation is provided.
  25831. // // also folder names may have no relation to the actual instanceName and instanceType coz we need to have many
  25832. // // eg : floder name can be elixir01 but instance name is elixr
  25833. // }
  25834. // else {
  25835. // instanceroot = root = path.normalize(launchpath + '/' + clioverrides.instanceName + '/' + 'development')
  25836. // instanceoptions.splice( 0, 0, detected = { root, instanceName : clioverrides.instanceName, node_env : 'development' })
  25837. // instanceoptions.splice( 0, 0, detectfromroot(root)) // A recessive option only.
  25838. // }
  25839. // }
  25840. // else {
  25841. // instanceroot = root = launchpath;
  25842. // if(clioverrides.node_env) {
  25843. // instanceoptions.splice( 0, 0, detected = { root, node_env : clioverrides.node_env })
  25844. // instanceoptions.splice( 0, 0, detectfromroot(root))
  25845. // }
  25846. // else {
  25847. // // Nothing was specified... We only have one option from root.
  25848. // instanceoptions.splice( 0, 0, detected = detectfromroot(launcpath))
  25849. // }
  25850. // }
  25851. }
  25852. }
  25853. }
  25854. else {
  25855. if(elxrCliExists) {
  25856. instanceroot = root = launchpath;
  25857. instanceoptions.splice( 0, 0, detected = { root });
  25858. instanceoptions.splice( 0, 0, detectfromroot(root));
  25859. }
  25860. }
  25861. }
  25862. instanceroot = detected.root;
  25863. __default.root = root;
  25864. clioverrides.root = clioverrides.root || root;
  25865. // Resolves empty array when No known instances detected.
  25866. return Promise.resolve(instanceoptions)
  25867. })
  25868. };
  25869. var getReconfirmAll = ()=>{return { instanceName : true, instanceType : true, reposerver : true, username : true, password : true } };
  25870. if(clioverrides.reconfirm) {
  25871. var reconfirm = getReconfirmAll();
  25872. }
  25873. else { var reconfirm = {}; }
  25874. var shouldPrompt = function(k, possiblePrompts, target){
  25875. return ((possiblePrompts[k] !== undefined && possiblePrompts[k] !== null) && target[k] !== possiblePrompts[k]
  25876. || (possiblePrompts[k] === undefined || possiblePrompts[k] === null) && (target[k] === undefined || target[k] === null)
  25877. || reconfirm[k])
  25878. };
  25879. var getBoundEachPrompt = function(target, possiblePrompts, promptables, choices, promptsfilter) {
  25880. return function(prompts, k, i, a){
  25881. // Reducer for all prompts on targets.
  25882. // No local instances config found. We use a default initialized instance available in selectedinstance
  25883. // Confirm those that were not supplied as user choices in runtime args and proceed to reattempt.
  25884. // PB : TODO -- selectedinstance === __default check to prompt everything...
  25885. if( shouldPrompt(k, possiblePrompts, target) ) {
  25886. delete reconfirm[k];
  25887. // console.log(k)
  25888. // console.dir(possiblePrompts); //console.dir(target)
  25889. prompts.push(async ()=>{
  25890. // PB : NOTE -- Important in async cases when this {{target}} needs to be in the same state as when it was invoked.
  25891. // We need to take a snapshot... Shallow.. !! If required deep should be used based on use case.
  25892. // var asyncthis = Object.assign(this);
  25893. // By default Latest altered state is provided which is an implicit reference directly.
  25894. promptables[k].choices = choices[k];
  25895. Object.defineProperty(target, k, getPromptableAsyncPropDescriptor(k, promptables[k]));
  25896. return await target[k]
  25897. });
  25898. }
  25899. delete possiblePrompts[k]; // PB : TODO We should keep this around instead of deleting so we can do a second pass if required.
  25900. return prompts
  25901. }
  25902. };
  25903. var __interactive_prompts = function( target, choices, promptsfilter ){
  25904. Object.defineProperty(target, 'node_env', { get : function(){ return this.instanceType } });
  25905. var interactionpoints = {
  25906. runchoice : {
  25907. label :
  25908. `Choose an option :
  25909. d) Install the default chess instance.
  25910. => elxr i chess node_env=development --default
  25911. n) Create your custom new instance interactively
  25912. => elxr i {{instanceName}} node_env={{environment}}
  25913. i) Choose an instance and environment to install
  25914. => elxr i {{instanceName}} node_env={{environment}}
  25915. c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  25916. => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  25917. h) Help
  25918. q) Quit
  25919. : `
  25920. , choices : []
  25921. , defaultchoice : 'c'
  25922. , selectedchoice : target.runchoice
  25923. , interpret : function(choice){
  25924. var interpret_map = {
  25925. d : function(){
  25926. processedArgs._[0] = 'i';
  25927. target.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess';
  25928. target.node_env = processedArgs.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env || 'development';
  25929. target.reposerver = 'https://git.bbh.org.in';
  25930. }
  25931. , n : function() { processedArgs._[0] = 'i'; }
  25932. , i : function() {
  25933. processedArgs._[0] = 'i';
  25934. // processedArgs._[1] = target.instanceName || processedArgs._[1] || 'chess';
  25935. }
  25936. , c : async function() {
  25937. // this here will always be the target.
  25938. Object.defineProperty(this, 'cmd', getPromptableAsyncPropDescriptor('cmd', {
  25939. label : `Enter cmd :
  25940. p) pull
  25941. Default <= p
  25942. : `
  25943. , defaultchoice : 'pull'
  25944. }
  25945. ));
  25946. var cmd = await target['cmd'];
  25947. if (!cmd || cmd === 'p') { target['cmd'] = processedArgs._[0] = 'pull'; }
  25948. else target['cmd'] = processedArgs._[0] = cmd;
  25949. return cmd;
  25950. }
  25951. , h : function() { console.log(elxr.help()); process.exit(); } // PB : TODO -- Why do we need log.
  25952. , q : function() { process.exit(); }
  25953. };
  25954. if(Promise.resolve(choice) === choice){
  25955. return choice.then( resolvedchoice => {
  25956. return (interpret_map[choice] || interpret_map['c']).call(target)
  25957. })
  25958. }
  25959. else return Promise.resolve( (interpret_map[choice] || interpret_map['c']).call(target) )
  25960. // var __interpreter = interpret_map[choice] || interpret_map['c']
  25961. // if(!choice) return interpret_map['c']() // This should not happen prompter should always give us a default choice.
  25962. // if(interpret_map[choice]) __interpreter = interpret_map[choice];
  25963. // return __interpreter.call(target)
  25964. }
  25965. }
  25966. , instanceName : { label : `Enter Instance Name ( <= ${target.instanceName || 'chess'} ) : `
  25967. , choices : choices['instanceName'], defaultchoice : 'chess'
  25968. , selectedchoice : target.instanceName
  25969. }
  25970. , instanceType : { label : `Enter Instance Type ( <= ${target.instanceType || 'development'} ) : `
  25971. , choices : choices['instanceType'], defaultchoice : 'development'
  25972. , selectedchoice : target.instanceType || 'development'
  25973. }
  25974. , reposerver : { label : `Enter Repo Server Base Url ( <= ${target.reposerver || 'https://git.bbh.org.in'} ) : `
  25975. , get choices() {
  25976. choices['reposerver'].forEach( rs => {
  25977. var __rs = new URL(rs);
  25978. __rs.hostname = __rs.host;
  25979. __rs.path = '/';
  25980. __rs.method = 'GET';
  25981. RESTAPI.get(__rs, function(data){ rs.accessibility = 'unaccessible'; }
  25982. , function(error){ rs.accessibility = 'unaccessible'; } );
  25983. });
  25984. return choices['reposerver']
  25985. }
  25986. , defaultchoice : 'https://git.bbh.org.in'
  25987. , selectedchoice : target.reposerver
  25988. }
  25989. , 'upstream-remote' : { label : `Enter Remote Name ( <= ${target['upstream-remote'] || 'chess'} ) : `
  25990. , get choices() {
  25991. var reposerver = target['reposerver'];
  25992. var remotes = [];
  25993. var trs = target.reposervers || [];
  25994. trs.forEach(rs => {
  25995. if(rs.server === reposerver){
  25996. remotes.push(remote);
  25997. // PB : TODO -- Sort and display highest priority target.remotes.sort( )
  25998. }
  25999. });
  26000. return remotes
  26001. }
  26002. , defaultchoice : 'userfork'
  26003. , selectedchoice : target['upstream-remote'] || 'userfork'
  26004. // Just using getters resolves dependencies..., dependencies : [ ()=>{ return target['reposerver'] } ]
  26005. }
  26006. , 'remote-type' : { label : `Enter Remote Type ( <= ${target['remote-type'] || 'public'} ) : `
  26007. , get choices() {
  26008. return ['public', 'private', 'github', 'unc']
  26009. }
  26010. , defaultchoice : 'public'
  26011. , selectedchoice : target['remote-type'] || 'public'
  26012. // Just using getters resolves dependencies..., dependencies : [ ()=>{ return target['reposerver'] } ]
  26013. }
  26014. , 'selectedremotes' : { label : `Chose Remote Names ( <= ${target['selectedremotes'] || 'chess'} ) : `
  26015. , get choices() {
  26016. var reposerver = target['reposerver']; // PB : TODO -- We need options to work with multiple selected reposervers at the same time..
  26017. var remotenames = [];
  26018. Object.entries(target.remotes || []).forEach( ([rname, r]) => {
  26019. if(r.server === reposerver && r.accessibility.find( target[ 'remote-type' ] )){
  26020. remotes.push(rname);
  26021. // PB : TODO -- Sort and display highest priority target.remotes.sort( )
  26022. }
  26023. });
  26024. // PB : TODO -- Need to generate all possible permuted choices nP( 1 -> n )
  26025. // Currenty handles all combinations without any priority order.
  26026. var _remotechoices = []; // Array of arrays of choices.
  26027. remotenames.forEach( r => {
  26028. var __rcs = [];
  26029. _remotechoices.forEach(rc => {
  26030. __rcs.push( rc.concat(r) );
  26031. });
  26032. Array.prototype.push.apply( _remotechoices, __rcs);
  26033. _remotechoices.push(r);
  26034. });
  26035. return _remotechoices
  26036. }
  26037. , defaultchoice : ['userfork-public', 'chess-public']
  26038. , selectedchoice : target['selectedremotes'] || ['userfork-public', 'chess-public']
  26039. // , defaultchoice : { 'userfork-public' : target.remotes['userfork-public'] , 'chess-public' : target.remotes['chess-public'] }
  26040. // , selectedchoice : target['selectedremotes'] || { 'userfork-public' : target.remotes['userfork-public'] , 'chess-public' : target.remotes['chess-public'] }
  26041. // Info : Just using getters resolves dependencies..., dependencies : [ ()=>{ return target['reposerver'] } ]
  26042. }
  26043. , get username() { return { label : `Enter User Id for ${target.reposerver} ( <= ${target.username || 'chess'} ) : `
  26044. , choices : choices['username'], defaultchoice : 'chess', selectedchoice : target.username } }
  26045. , get password() { return { label : `Enter Password for ${target.username} @ ${target.reposerver} ( <= ${target.password || ''} ) : `
  26046. , choices : choices['password'], defaultchoice : '***', selectedchoice : target.password } }
  26047. , get email() { return { label : `Enter Email for ${target.username} @ ${target.reposerver} ( <= ${target.email || ''} ) : `
  26048. , choices : choices['email'], defaultchoice : 'guest@bbh.org.in', selectedchoice : target.email } }
  26049. };
  26050. function getPromptKeys() {
  26051. if(! (processedArgs.label || processedArgs._[0]) ) return Object.assign({}, interactionpoints);
  26052. return promptkeys
  26053. }
  26054. var eachPrompt = getBoundEachPrompt( target, getPromptKeys() , interactionpoints, choices);
  26055. return Object.keys(promptsfilter || interactionpoints).reduce(eachPrompt, [])
  26056. };
  26057. var downloadsdir = '../Downloads';
  26058. var prerequisites = [
  26059. {
  26060. shellcmd: 'git',
  26061. name : 'git',
  26062. url: 'https://github.com/git-for-windows/git/releases/download/v2.31.0.windows.1/Git-2.31.0-64-bit.exe'
  26063. , installer: 'Git-2.31.0-64-bit.exe'
  26064. , installcmd: ['cmd', ['/c', 'start',
  26065. '/WAIT', path__default["default"].resolve(downloadsdir + '/' + 'Git-2.31.0-64-bit.exe')
  26066. , '/VERYSILENT'
  26067. // , '/MERGETASKS=!runcode' // This is required only for vscode...
  26068. ]]
  26069. , preinstallsteps: function() {
  26070. var steps = [
  26071. () => {
  26072. if (!existsSync(downloadsdir + '/' + this.installer)) {
  26073. return nodeShellExec(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, [this.url, downloadsdir + '/' + this.installer])
  26074. }
  26075. else return Promise.resolve(true)
  26076. }
  26077. ];
  26078. var prompts = this.getuser(null, ()=>{
  26079. // console.log('preinstallsteps')
  26080. // var gitUser = 'guest';
  26081. // var gitEmail = 'guest@bbh.org.in';
  26082. // var prompts = [];
  26083. // prompts.push( ()=>{ return cli.prompt(choices['username'], 'git user name').then(gituser => gitUser = gituser) } )
  26084. // prompts.push( ()=>{ return cli.prompt(choices['useremail'], 'git user email').then(gitemail => gitEmail = gitemail) } )
  26085. // console.log('prompting in preinstallsteps')
  26086. // return any(prompts).then(()=>{
  26087. // var steps = [
  26088. // ['git', ['config', '--global', '--add', 'user.name', `${gitUser}`]]
  26089. // , ['git', ['config', '--global', '--add', 'user.email', `${gitEmail}`]]
  26090. // ]
  26091. // return any(steps.map(getshelltask)).then(() => {
  26092. // })
  26093. // });
  26094. return Promise.resolve(true)
  26095. });
  26096. return any([any(steps), prompts])
  26097. }
  26098. , installsteps: function () {
  26099. return any([this.installcmd].map(getshelltask))
  26100. }
  26101. , postinstallsteps: function(err, users){
  26102. return this.getuser(null, (err, data)=>{
  26103. // ignore err and proceed with data as guest.
  26104. console.dir(data);
  26105. if(data && data.length === 1 && !shouldPrompt('username', promptkeys, selectedinstance) ) {
  26106. return username = data[0];
  26107. }
  26108. data = data || ['guest'];
  26109. choices['username'] = Array.from( new Set( data.concat( (choices['username'] || []) )) );
  26110. console.log('prompting in postinstallsteps');
  26111. var username = 'guest';
  26112. var email = 'guest@bbh.org.in';
  26113. var password = '***';
  26114. return any( getInteractionPoints(selectedinstance, promptkeys, { username, password, email}) ).then(()=>{
  26115. if(!data.find(e => e === selectedinstance.username)) {
  26116. var steps = [
  26117. ['git', ['config', '--global', '--add', 'user.name', `${username}`]]
  26118. , ['git', ['config', '--global', '--add', 'user.email', `${email}`]]
  26119. ];
  26120. return any(steps.map(getshelltask)).then(() => {
  26121. })
  26122. }
  26123. else {
  26124. return Promise.resolve(true)
  26125. }
  26126. });
  26127. })
  26128. }
  26129. , install: function () {
  26130. return any([ /*this.preinstallsteps,*/ this.installsteps.bind(this), this.postinstallsteps.bind(this)])
  26131. }
  26132. , verifyAndInstall : function(){
  26133. return getTaskCheckExists(this.shellcmd, { ignorefailures: true })().then((exists) => {
  26134. if(exists) {
  26135. // return any(['git', ['config', '--global', '-l']].map(getshelltask))
  26136. return this.postinstallsteps.bind(this)()
  26137. }
  26138. return this.install();
  26139. });
  26140. }
  26141. , getuser : function(repo, onResult){
  26142. var __onResult = onResult || function(e, data){
  26143. data = data || [];
  26144. choices['username'] = Array.from( new Set( data.concat( (choices['username'] || []) )) );
  26145. // console.dir(choices)
  26146. return data[0]
  26147. };
  26148. var globalOrLocal = '--global';
  26149. if(repo) globalOrLocal = '--local';
  26150. return any([['git', ['config', globalOrLocal, '--get-all', 'user.name']]].map(getshelltask)).then((result)=>{
  26151. // not yet configured.
  26152. if(!result.success) return __onResult(result)
  26153. else {
  26154. var users = result.messages[0].trim().split('\n');
  26155. if(users.length === 0 ||
  26156. users.length === 1 && users[0] === 'guest') {
  26157. return __onResult(result)
  26158. }
  26159. else {
  26160. return __onResult(null, Array.from( new Set( users ) ) ); }// PB : TODO == We should probably prompt with all the users available for selection !
  26161. }
  26162. })
  26163. .catch((e)=>{
  26164. console.log(e);
  26165. return __onResult(e)
  26166. })
  26167. }
  26168. }
  26169. ,
  26170. {
  26171. shellcmd: 'node',
  26172. name : 'node',
  26173. url: 'https://nodejs.org/dist/v14.16.0/node-v14.16.0-x64.msi'
  26174. , installer: 'node-v14.16.0-x64.msi'
  26175. , installcmd: ['MSIEXEC.exe', ['/i'
  26176. , path__default["default"].resolve(downloadsdir + '/' + 'node-v14.16.0-x64.msi')
  26177. , 'ACCEPT=YES', '/passive']]
  26178. , install : function() { return any([this.installcmd].map(getshelltask)).then(() => { }) }
  26179. }
  26180. ];
  26181. for(var i$1=0; i$1<prerequisites.length; i$1++) {
  26182. prerequisites[prerequisites[i$1].name] = prerequisites[i$1];
  26183. }
  26184. prerequisites.forEach(p=>{ prerequisites[p.shellcmd] = p; });
  26185. function ensureDirectoryExistence(filePath) {
  26186. var dirname = path__default["default"].dirname(filePath);
  26187. if (fs.existsSync(dirname)) {
  26188. return filePath;
  26189. }
  26190. ensureDirectoryExistence(dirname);
  26191. fs.mkdirSync(dirname);
  26192. return filePath;
  26193. }
  26194. var mainTasks = [];
  26195. function verifyAndInstallPrerequisites() {
  26196. var downloadtasks = [];
  26197. var installtasks = [];
  26198. prerequisites.forEach(preq => {
  26199. downloadtasks.push(getTaskCheckExists(preq.shellcmd, { ignorefailures: true })().then((exists) => {
  26200. if (exists) console.log(`${preq.shellcmd} exists`);
  26201. else {
  26202. console.log(`${preq.shellcmd} is not installed`);
  26203. return preq.preinstallsteps.call(preq).then(() => {
  26204. installtasks.push(preq.install.bind(preq));
  26205. })
  26206. }
  26207. }));
  26208. });
  26209. return Promise.all(downloadtasks).then(() => { return any(installtasks) })
  26210. }
  26211. var getPromptableAsyncPropDescriptor = function(propName, promptable){
  26212. return {
  26213. get (){
  26214. return any( promptable.dependencies || [] ).then(()=>{
  26215. return cliverse.prompt( promptable.choices, promptable.label, promptable.defaultchoice, promptable.selectedchoice ).then(propValue => {
  26216. var asyncprop = Promise.resolve(propValue);
  26217. if(promptable.interpret){
  26218. asyncprop = promptable.interpret(propValue);
  26219. }
  26220. return asyncprop.then(
  26221. ()=>{
  26222. Object.defineProperty(this, propName, {
  26223. value: propValue,
  26224. writable: true,
  26225. configurable : true,
  26226. enumerable : true
  26227. });
  26228. return propValue
  26229. }
  26230. )
  26231. })
  26232. } )
  26233. }
  26234. // , set (propValue){
  26235. // Object.defineProperty(this, propName, {
  26236. // value: propValue,
  26237. // writable: true, // PB : TODO -- Use this to fix value permanently until run is over.
  26238. // configurable : true,
  26239. // enumerable : true
  26240. // })
  26241. // return propValue;
  26242. // }
  26243. , configurable : true
  26244. , enumerable : true
  26245. }
  26246. };
  26247. function acquirelocalinstances(selected){
  26248. // utils.assign is used to cleanup duplicates... assuming chessinstances.js is probably not clean.
  26249. var chessinstances = bbhverse.assign_core( { arraymergetype : bbhverse.assign_core.DISTINCT_UNION }
  26250. , commonjsRequire(path__default["default"].normalize(selected.root + '/chessinstances.js'),"/$$rollup_base$$"));
  26251. return chessinstances
  26252. }
  26253. function findlocalinstances(chessinstances, instanceoptions){
  26254. // We can expect a .elxr at each level.
  26255. ['' /* instanceroot */, '../' /* instanceTypes or node_env */, '../..' /* instanceNames */].
  26256. earlyreduce( ( value, p, i, a )=>{
  26257. var localinstancesPath = `${instanceroot}/${p}.elxr`;
  26258. if(existsSync( localinstancesPath )) {
  26259. try {
  26260. var chessinstances = acquirelocalinstances( { localinstancesPath } );
  26261. return Object.keys(chessinstances).earlyreduce( ( value, instanceName) => {
  26262. return Object.keys(chessinstances[instanceName]).earlyreduce( (value, instanceType) => {
  26263. if( path__default["default"].normalize(chessinstances[instanceName][instanceType].root) === path__default["default"].normalize( instanceroot) ) {
  26264. instanceoptions.splice( 0, 0, chessinstances[instanceName][instanceType]);
  26265. return {
  26266. value : chessinstances[instanceName][instanceType]
  26267. , done : true
  26268. };
  26269. }
  26270. })
  26271. })
  26272. }
  26273. catch(e){
  26274. return { }
  26275. }
  26276. }
  26277. else return { }
  26278. }
  26279. );
  26280. }
  26281. // function updateselection(selected) { selectedinstance = utils.assign(selectedinstance, selected) }
  26282. var selectedinstance = { root : process.env.wd };
  26283. var runconfig = null;
  26284. var chessinstances = { current_run : {} };
  26285. var promptkeys = {
  26286. cmd : processedArgs._[0] || 'pull'
  26287. // Try not to prompt anything unless absolutely necessary or reconfirm is forced.
  26288. // 'instanceName' : true
  26289. // , 'node_env' : true
  26290. // , username : ''
  26291. // , runchoice : 'c'
  26292. };
  26293. // promptkeys.runchoice = promptkeys.cmd ? 'c' : undefined
  26294. function createLocalChessInstance( cfg ){
  26295. // return createInstance(cfg)
  26296. reconfirm = getReconfirmAll();
  26297. var inst = {};
  26298. var __new = Object.assign({}, __default, cfg);
  26299. inst[cfg.node_env] = __new; return inst;
  26300. }
  26301. var choices = {
  26302. 'instanceName' : []
  26303. , 'reposerver' : []
  26304. , 'upstream-remote' : []
  26305. , 'instanceType' : []
  26306. , username : ['guest', 'chessdemo', 'demo']
  26307. };
  26308. var getInteractionPoints = function(detectedinstanceoptions, possiblePrompts, promptsfilter){
  26309. var instances = [];
  26310. var reposervers = [];
  26311. var remotes = [];
  26312. var instanceNames = [];
  26313. var instanceTypes = ['development', 'production'];
  26314. Object.keys( chessinstances).forEach(instanceName => {
  26315. if(instanceName === 'current_run') return;
  26316. Object.keys( chessinstances[instanceName] ).forEach(node_env=>{
  26317. var instance = chessinstances[instanceName][node_env];
  26318. reposervers = reposervers.concat(instance.reposervers);
  26319. if(instance.reposerver) reposervers.push(instance.reposerver);
  26320. instances.push(instance);
  26321. instanceTypes.push(instance.node_env);
  26322. instanceNames.push(instance.instanceName);
  26323. Array.prototype.push.apply(remotes, Object.keys(instance.reposerverinstances[instance.reposerver].remotes));
  26324. });
  26325. });
  26326. instances = instances.concat(detectedinstanceoptions);
  26327. if(selectedinstance['instanceName']) instanceNames.push(selectedinstance['instanceName']);
  26328. if(possiblePrompts['instanceName']) instanceNames.push(possiblePrompts['instanceName']);
  26329. if(selectedinstance['reposervers']) reposervers = reposervers.concat(selectedinstance['reposervers']);
  26330. choices['instanceName'] = Array.from( new Set(instanceNames.concat(choices['instanceName'])) );
  26331. choices['reposerver'] = Array.from( new Set(reposervers.concat(choices['reposerver'])) );
  26332. // choices['upstream-remote'] = Array.from( new Set(remotes.concat(choices['upstream-remote'])) )
  26333. choices['instanceType'] = Array.from( new Set(instanceTypes.concat(choices['instanceType'])) );
  26334. return __interactive_prompts(selectedinstance, choices, promptsfilter)
  26335. };
  26336. var detection_state = {
  26337. localInstanceDetected : false
  26338. };
  26339. const RESTAPI = (function(){
  26340. // Singleton
  26341. function RESTAPI(){}
  26342. // RESTAPI.create = RESTAPI; // Returns the one singe instance which is the class itself
  26343. // const options = {
  26344. // hostname: 'whatever.com',
  26345. // port: 443,
  26346. // path: '/todos',
  26347. // method: 'POST',
  26348. // headers: {
  26349. // 'Content-Type': 'application/json',
  26350. // 'Content-Length': data.length
  26351. // }
  26352. // }
  26353. RESTAPI.method = function(options, resolve, reject){
  26354. var __method = function() {
  26355. options.headers = options.headers || { 'Content-Type': 'application/json' };
  26356. if(options.payload) {
  26357. const data = new TextEncoder().encode( JSON.stringify(options.payload) );
  26358. options.headers = options.headers || {
  26359. 'Content-Type': 'application/json',
  26360. 'Content-Length': data.length
  26361. };
  26362. }
  26363. if(!options.authenticatepost) options.headers.Authorization = `token ${usertokens[options.username]}`;
  26364. var acquirer = getHTTPorS(options);
  26365. const req = acquirer.request(options, res => {
  26366. if (res.statusCode < 200 || res.statusCode >= 300) {
  26367. return reject(new Error('statusCode=' + res.statusCode));
  26368. }
  26369. var body = [];
  26370. // res.setEncoding('utf8');
  26371. res.on('data', function(chunk) {
  26372. body.push(chunk);
  26373. });
  26374. res.on('end', function() {
  26375. try {
  26376. body = JSON.parse(Buffer.concat(body).toString());
  26377. } catch(e) {
  26378. reject(e);
  26379. }
  26380. resolve(body);
  26381. });
  26382. });
  26383. req.on('error', error => {
  26384. console.error(error);
  26385. reject(error);
  26386. });
  26387. if(options.payload) req.write(data);
  26388. req.end();
  26389. };
  26390. if(!options.authenticatepost && !usertokens[options.username]) {
  26391. RESTAPI.authenticate(options, function(tokenresp){
  26392. usertokens[options.username] = tokenresp.sha1;
  26393. __method();
  26394. },
  26395. function(err){ throw err}
  26396. );
  26397. }
  26398. else __method();
  26399. };
  26400. RESTAPI.post = RESTAPI.method;
  26401. var usertokens = {};
  26402. RESTAPI.authenticate = function(options, resolve, reject){
  26403. options.headers = options.headers || { 'Content-Type': 'application/json' };
  26404. if(!usertokens[options.username]) {
  26405. // Authenticate and acquire token.
  26406. // https://git.bbh/api/v1/users/<username>/tokens
  26407. // curl -XPOST -H "Content-Type: application/json" -k -d '{"name":"demo"}' -u demo:demo123 http://git.bbh/api/v1/users/demo/tokens
  26408. var _options = Object.assign({}, options);
  26409. // _options.username = 'demo'
  26410. // _options.password = 'demo123'
  26411. _options.method = 'POST';
  26412. _options.headers.Authorization = `Basic ${Buffer.from(`${_options.username}:${_options.password}`).toString('base64')}`;
  26413. _options.path = `/api/v1/users/${_options.username}/tokens`;
  26414. _options.authenticatepost = true;
  26415. var postoptions = { name : _options.username };
  26416. delete _options.username;
  26417. delete _options.password;
  26418. _options.payload = postoptions;
  26419. RESTAPI.post( _options, function(tokenresp){
  26420. // tokenresp = JSON.parse(tokenresp)
  26421. usertokens[options.username] = tokenresp.sha1;
  26422. resolve(tokenresp);
  26423. },
  26424. function(err){ reject(err); }
  26425. );
  26426. }
  26427. else resolve(tokenresp.sha1);
  26428. };
  26429. RESTAPI.get = RESTAPI.post = RESTAPI.method;
  26430. return RESTAPI
  26431. })();
  26432. var getHTTPorS = function(options){ return options.protocol.startsWith('https') ? https__default["default"] : http__default["default"]; };
  26433. const GITEA = (function(){
  26434. function GITEA(){}
  26435. GITEA.repository = {
  26436. fork( httpoptions, cmdoptions, giteaoptions, resolve, reject ){
  26437. // forkoptions = { owner : httpoptions.username, repo : {{reoptoFork}} }
  26438. // giteaoptions = {
  26439. // organization string
  26440. // --- organization name, if forking into an organization
  26441. // }
  26442. // http://try.gitea.io/api/v1/repos/{owner}/{repo}/forks
  26443. httpoptions.path = `/api/v1/repos/${cmdoptions.owner}/${cmdoptions.repo}/forks`;
  26444. httpoptions.method = 'POST';
  26445. httpoptions.payload = giteaoptions;
  26446. return RESTAPI.post(httpoptions, resolve || function(){}, reject || function(){} )
  26447. }
  26448. , updateattributes( httpoptions, cmdoptions, giteaoptions, resolve, reject ){
  26449. httpoptions.path = `/api/v1/repos/${cmdoptions.owner}/${cmdoptions.repo}`;
  26450. httpoptions.method = 'PATCH';
  26451. httpoptions.payload = giteaoptions;
  26452. return RESTAPI.post(httpoptions, resolve || function(){}, reject || function(){} )
  26453. }
  26454. };
  26455. GITEA.user = {
  26456. getuser( httpoptions, cmdoptions, giteaoptions, resolve, reject ){
  26457. // ​/users​/{username} // Get a user
  26458. httpoptions.path = `/api/v1/users/${httpoptions.username}`;
  26459. httpoptions.method = 'GET';
  26460. return RESTAPI.get(httpoptions, giteaoptions, resolve || function(){}, reject || function(){} )
  26461. }
  26462. };
  26463. return GITEA
  26464. })();
  26465. // Wrapper for Git shell operations. Some meta operations will map to a bunch of GIT commands.
  26466. const GIT = (function(){
  26467. function GIT(){}
  26468. Object.assign(GIT, {
  26469. 'switch user'(username){
  26470. var server = new URL(selectedinstance.reposerver);
  26471. return GITEA.user.getuser({ hostname : server.host, protocol : server.protocol
  26472. , username : selectedinstance.username, password : selectedinstance.password
  26473. }).then(()=>{
  26474. return nodeShellExec('git', ['config', '--replace-all', 'user.name', username],
  26475. {
  26476. inherit: true, shell: true,
  26477. env: process.env
  26478. , cwd: instanceroot + '/' + repo
  26479. , runas: processedArgs.runas
  26480. , title: `'git', ${['config', '--replace-all', 'user.name', username].join(' ')}`
  26481. })
  26482. }
  26483. )
  26484. .catch(e => {
  26485. console.error(e + 'Could not switch. Probably no such user.');
  26486. })
  26487. }
  26488. });
  26489. return GIT
  26490. })();
  26491. function createInstanceData(target, source) {
  26492. var sourceinstance = source || target;
  26493. console.dir(sourceinstance);
  26494. var args = {
  26495. remotebase : sourceinstance.reposerver + '/chess/'
  26496. , sourcerepo : sourceinstance.repo || 'chess-data'
  26497. , targetrepo : `${target.instanceName}-data-${target.instanceType}${target.nodeName ? ('-' + target.nodeName) : ''}`
  26498. };
  26499. if(sourceinstance.local) {
  26500. var options = {
  26501. inherit: true, shell: true,
  26502. env: process.env
  26503. , cwd : instanceroot
  26504. , runas: processedArgs.runas
  26505. };
  26506. var cmdseq = [
  26507. ['git', ['clone', `${args.remotebase}${args.sourcerepo}`, `${args.targetrepo}`], options]
  26508. ];
  26509. return any(cmdseq.map(getshelltask)).then(() => { return true })
  26510. }
  26511. else {
  26512. // http://try.gitea.io/api/v1/org/{org}/repos
  26513. if(source.reposerver !== target.reposerver && source.username !== target.username) {
  26514. throw 'createInstanceData is possible only within the same repository server.'
  26515. }
  26516. var server = new URL(target.reposerver);
  26517. return GITEA.repository.fork( { hostname : server.host, protocol : server.protocol
  26518. , username : target.username, password : target.password
  26519. }
  26520. // , { repo : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}`}
  26521. , { repo : `${args.sourcerepo}`, owner : `${target.username}` }, {}, function( repository ){
  26522. return GITEA.repository.updateattributes( {
  26523. hostname : server.host, protocol : server.protocol
  26524. , username : target.username, password : target.password
  26525. }
  26526. , { repo : `${args.sourcerepo}`, owner : `${target.username}` }
  26527. , { name : `${args.targetrepo}`}
  26528. )
  26529. }
  26530. )
  26531. }
  26532. // GITEA.repository.updateattributes( {
  26533. // hostname : server.host, protocol : server.protocol
  26534. // , username : selectedinstance.username, password : selectedinstance.password
  26535. // }
  26536. // , { repo : `chess-config`, owner : selectedinstance.username }
  26537. // , { name : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}${selectedinstance.nodeName ? '-' + selectedinstance.nodeName : ''}`}
  26538. // )
  26539. // return selectedinstance
  26540. }
  26541. function createInstance(target, source) {
  26542. var sourceinstance = source || target;
  26543. console.dir(sourceinstance);
  26544. var args = {
  26545. remotebase : sourceinstance.reposerver + '/chess/'
  26546. , sourcerepo : sourceinstance.repo || 'chess-config'
  26547. , targetrepo : `${target.instanceName}-config-${target.instanceType}${target.nodeName ? ('-' + target.nodeName) : ''}`
  26548. };
  26549. if(sourceinstance.local) {
  26550. var options = {
  26551. inherit: true, shell: true,
  26552. env: process.env
  26553. , cwd : instanceroot
  26554. , runas: processedArgs.runas
  26555. };
  26556. var cmdseq = [
  26557. ['git', ['clone', `${args.remotebase}${args.sourcerepo}`, `${args.targetrepo}`], options]
  26558. ];
  26559. return any(cmdseq.map(getshelltask)).then(() => { return true })
  26560. }
  26561. else {
  26562. // http://try.gitea.io/api/v1/org/{org}/repos
  26563. if(source.reposerver !== target.reposerver && source.username !== target.username) {
  26564. throw 'createInstance is possible only within the same repository server.'
  26565. }
  26566. var server = new URL(target.reposerver);
  26567. return GITEA.repository.fork( { hostname : server.host, protocol : server.protocol
  26568. , username : target.username, password : target.password
  26569. }
  26570. // , { repo : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}`}
  26571. , { repo : `${args.sourcerepo}`, owner : `${target.username}` }, {}, function( repository ){
  26572. return GITEA.repository.updateattributes( {
  26573. hostname : server.host, protocol : server.protocol
  26574. , username : target.username, password : target.password
  26575. }
  26576. , { repo : `${args.sourcerepo}`, owner : `${target.username}` }
  26577. , { name : `${args.targetrepo}`}
  26578. )
  26579. }
  26580. )
  26581. }
  26582. // GITEA.repository.updateattributes( {
  26583. // hostname : server.host, protocol : server.protocol
  26584. // , username : selectedinstance.username, password : selectedinstance.password
  26585. // }
  26586. // , { repo : `chess-config`, owner : selectedinstance.username }
  26587. // , { name : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}${selectedinstance.nodeName ? '-' + selectedinstance.nodeName : ''}`}
  26588. // )
  26589. // return selectedinstance
  26590. }
  26591. function initinstances(selected_overrides) {
  26592. var root = selected_overrides.root; // We should always have this coz we are running at some place which is fixed by detectLocalInstances.
  26593. var instanceName = selected_overrides.instanceName
  26594. || clioverrides.instanceName
  26595. // || processedArgs._[1]
  26596. || chessinstances.current_run.instanceName;
  26597. var node_env = selected_overrides.node_env
  26598. || clioverrides.node_env
  26599. // || processedArgs.node_env
  26600. || chessinstances.current_run.node_env;
  26601. var reposerver = selected_overrides.reposerver
  26602. || clioverrides.reposerver
  26603. // || processedArgs.node_env
  26604. || chessinstances.current_run.reposerver;
  26605. if(!instanceName) {
  26606. promptkeys['instanceName'] = instanceName = chessinstances.current_run.instanceName = promptkeys['instanceName'] || __default.instanceName;
  26607. promptkeys['node_env'] = node_env = chessinstances.current_run.node_env = promptkeys['node_env'] || __default.node_env;
  26608. promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  26609. }
  26610. if(!node_env) {
  26611. promptkeys['node_env'] = node_env = chessinstances.current_run.node_env = promptkeys['node_env'] || __default.node_env;
  26612. promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  26613. }
  26614. if(!reposerver) {
  26615. promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  26616. }
  26617. chessinstances[instanceName] = chessinstances[instanceName] || createLocalChessInstance( {
  26618. instanceName, node_env, root : selected_overrides.root, reposerver : selected_overrides.reposerver /* promptkeys['reposerver'] */ } );
  26619. chessinstances['current_run'] = { instanceName: instanceName, node_env, reposerver, root };
  26620. if(path__default["default"].normalize(selected_overrides.root) !== path__default["default"].normalize(chessinstances[instanceName][node_env].root)) {
  26621. throw "instanceName and instanceType specified doesn't match whats already present do you want to continue " + chessinstances[instanceName][node_env].root + ' does not match ' + selected_overrides.root
  26622. }
  26623. // Override sequence.
  26624. // __default, chessinstances[current_run], instanceName-config-development, cliargs, interactve_promts
  26625. // PB : TODO -- Undefined keys are overriding and deleting values. We should not allow that.
  26626. // This is ordinary utils.assign behavior. The key should not exist as undefined in the override.
  26627. // PB : TODO -- We now have options that can be passed into assign_core to control this behavior.
  26628. if(selected_overrides.node_env === undefined) delete selected_overrides.node_env;
  26629. selectedinstance = bbhverse.assign_core( { arraymergetype : bbhverse.assign_core.DISTINCT_UNION }
  26630. , __default
  26631. , chessinstances[instanceName][node_env]
  26632. , clioverrides
  26633. , selected_overrides
  26634. // , __interactive_prompts -- Cant just override. Also need selectedinstance to be ready...
  26635. );
  26636. // chessinstances[instanceName] = chessinstances[instanceName] || {}
  26637. // chessinstances[instanceName][node_env] = chessinstances[instanceName][node_env] || {}
  26638. // if(!selectedinstance.repos || selectedinstance.instanceName) {
  26639. // // Brand New.
  26640. // selectedinstance = Object.assign( __default, selectedinstance )
  26641. // }
  26642. if(selectedinstance?.repos && !selectedinstance?.repos[0]?.repo) {
  26643. console.warn('repo manifest has obsolete format. Attempting upgrade.');
  26644. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } });
  26645. }
  26646. if(selectedinstance?.elevated && !selectedinstance?.elevated[0]?.repo) {
  26647. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.');
  26648. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } });
  26649. }
  26650. // Config from server always override merges into selection except for the current selection.
  26651. // PB : TODO -- utils.assign Array merges are non-distinct...
  26652. chessinstances[instanceName][node_env] = selectedinstance;
  26653. // chessinstances[selectedinstance.instanceName][selectedinstance.node_env] = selectedinstance;
  26654. cacheWriteInstanceConfig(chessinstances);
  26655. // PB : TODO -- We should probably write the new server config also...
  26656. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0]; // PB : TODO -- Attempt first one that is available and online...
  26657. return chessinstances
  26658. }
  26659. var skipprereqs = {};
  26660. var maintask = () => {
  26661. // Default cmd to run !
  26662. processedArgs._[0] === processedArgs._[0] || 'pull';
  26663. // selectedinstance.reposerver = selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online from all that are available.
  26664. if(!noprerequisites[processedArgs._[0]]
  26665. && !skipprereqs[processedArgs._[0]]
  26666. ) {
  26667. return prerequisites.git.verifyAndInstall().then(()=>{
  26668. var inittasks = [];
  26669. var commontask = () => { preworkerconfig(); return elxrworker() };
  26670. if(!detection_state.localInstanceDetected) {
  26671. var t1 = ()=>{ return createInstance(selectedinstance) };
  26672. t1.statuslog = statuslog;
  26673. var specifictask = shell_verse.getNonElevatedTask(t1);
  26674. }
  26675. else {
  26676. var t2 = ()=>{ return acquireConfig(selectedinstance) };
  26677. t2.statuslog = statuslog;
  26678. var specifictask = shell_verse.getNonElevatedTask(t2);
  26679. }
  26680. inittasks.push( specifictask().catch((err) => {
  26681. console.error('Chosen cofiguraton failed or not found. Fix config and rerun or chose another.');
  26682. console.error(err);
  26683. }).then( commontask )
  26684. // .finally(()=>{
  26685. // fs.writeFileSync('run.log', ', ' + JSON.stringify({ error: e.message }), { 'flag': 'a+' })
  26686. // if(!e.success) fs.writeFileSync('run.done', 'error');
  26687. // // return process.exit()
  26688. // }))
  26689. );
  26690. return any(inittasks)
  26691. })
  26692. }
  26693. else {
  26694. console.log('cmd has no preqs or has been configured to skip preqs');
  26695. preworkerconfig();
  26696. return elxrworker()
  26697. }
  26698. };
  26699. function generateDependencies(){
  26700. // PB : TODO -- Keep only the last n runs...
  26701. // Currently it retains 2*n when proc needs to be relaunched in elevated mode !!!
  26702. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`);
  26703. fs.writeFileSync(ensureDirectoryExistence(path__default["default"].normalize(`${selectedinstance.root}/${downloadsdir}/readme.txt`)), `${getVersion()} Your local downloads for this instance`);
  26704. // PB : TODO include and build from files... using rollup..
  26705. var downloadbatch =
  26706. `::**************************************************************************
  26707. :Download_ <url> <File>
  26708. Powershell.exe ^
  26709. $AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'; ^
  26710. [System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols; ^
  26711. (New-Object System.Net.WebClient).DownloadFile('%1','%2')
  26712. exit /b
  26713. ::**************************************************************************`;
  26714. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, downloadbatch);
  26715. var windowselevate =
  26716. `
  26717. <html><HTA:APPLICATION ID="windowselevate" icon="#"/>
  26718. <script language="vbscript">
  26719. document.title = "elxr control panel"
  26720. self.ResizeTo 200,600
  26721. Sub Window_Onload
  26722. self.MoveTo (screen.availWidth - (document.body.clientWidth + 40)),10
  26723. End Sub
  26724. Set objShell = CreateObject("WScript.Shell")
  26725. Set objENV = objShell.Environment("Process")
  26726. dim NODE_ENV
  26727. NODE_ENV = objENV("NODE_ENV")
  26728. </script>
  26729. <script language="javascript">
  26730. //WINDOWSTATE="minimize" SHOWINTASKBAR="no" SYSMENU="no" CAPTION="no"
  26731. // https://devblogs.microsoft.com/scripting/how-can-i-pass-command-line-variables-to-an-hta-when-it-starts/
  26732. // alert(windowselevate.commandLine)
  26733. var args = windowselevate.commandLine.split('"').slice(3);
  26734. // alert(args)
  26735. var processedArgs = { _ : [] }
  26736. var namedArgs = [];
  26737. namedArgs.push('--wd=' + objENV('wd'))
  26738. // alert(namedArgs)
  26739. for(var item in args){
  26740. if(args[item].charAt(0) === '-'){
  26741. namedArgs.push(args[item])
  26742. var split = args[item].split('=');
  26743. processedArgs[split[0].slice(2)] = split[1] || true;
  26744. }
  26745. else processedArgs._.push(args[item]);
  26746. }
  26747. // args = args.forEach(function(item){ })
  26748. // alert('processedArgs._ : ' + processedArgs._);
  26749. // alert(processedArgs.runas);
  26750. // alert(objENV('wd'))
  26751. // PB : TODO -- Convert all the cli args back to string.
  26752. // __filename will sure we are launhed using the same entry point.
  26753. var cargs = (processedArgs.debug ? '--inspect-brk=9228' : '') + ' ${__filename.replace(/\\/g, '\\\\')} ' + processedArgs._.join(' ') + ' ' + namedArgs.join(' ');
  26754. var shell = new ActiveXObject('shell.application');
  26755. // alert('launching node privilged. ' + processedArgs['nodepath'])
  26756. // shell.ShellExecute('cmd.exe', '/k where node', '', '', 10);
  26757. // shell.ShellExecute('cmd.exe', '/k notepad.exe', '', 'runas', 1);
  26758. // shell.ShellExecute('cmd.exe ', '/k node ', '', 'runas', 1);
  26759. // shell.ShellExecute('cmd.exe ', '/k node ' + cargs + '', '', 'runas', 1);
  26760. shell.ShellExecute('node', cargs, '', 'runas', 1);
  26761. // alert('/k node ' + cargs + '')
  26762. // shell.ShellExecute(processedArgs['nodepath'], cargs, '', 'runas', 1);
  26763. var fso = new ActiveXObject('Scripting.FileSystemObject');
  26764. window.onload = function() {
  26765. document.body.style.backgroundColor = 'black';
  26766. document.body.style.fontFamily = 'arial';
  26767. var log = document.createElement('div');
  26768. log.innerHTML='Please Wait';
  26769. function l(msg){ log.innerHTML+= msg; };
  26770. log.style.color = 'blue';
  26771. log.style.width = '95%';
  26772. log.id = 'log';
  26773. document.body.appendChild(log);
  26774. l('<Br/>Current config : ')
  26775. l('<Br/>NODE_ENV = ' + NODE_ENV)
  26776. l('<Br/>cmd = ' + processedArgs._[0])
  26777. processedArgs._[1] === 'use' ? l('<Br/>using = ' + processedArgs._[2]) : null;
  26778. l('<Br/><Br/>')
  26779. // alert(fso.GetAbsolutePathName("."))
  26780. var timer = function(){
  26781. l('.');
  26782. if(fso.FileExists("run.done")) {
  26783. fso.DeleteFile('run.done')
  26784. close();
  26785. }
  26786. else window.setTimeout(timer, 1000);
  26787. };
  26788. window.setTimeout(timer, 3000);
  26789. };
  26790. </script>
  26791. </html>
  26792. `;
  26793. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`, windowselevate);
  26794. }
  26795. var startElxr = function() {
  26796. const retaincount = 2;
  26797. var min = runtimestamp;
  26798. var collect = [];
  26799. if(reconfirmcmds[processedArgs.label || processedArgs._[0]]) {
  26800. reconfirm = getReconfirmAll();
  26801. }
  26802. return detectLocalInstances().then((detectedinstanceoptions)=>{
  26803. detectedinstanceoptions.splice(0,0, __default);
  26804. var cmdinstance = cmds[clioverrides.cmd];
  26805. cmdinstance.getPossiblePrompts();
  26806. selectedinstance.node_env ? selectedinstance.node_env : selectedinstance.node_env = clioverrides.node_env;
  26807. // PB : TODO -- Most recent should be at the tip ! at index 0 so utils.reverseassign is required !!!
  26808. selectedinstance = bbhverse.assign_core( { arraymergetype : bbhverse.assign_core.DISTINCT_UNION }
  26809. , ...detectedinstanceoptions.slice(-2), promptkeys );
  26810. // promptkeys = utils.assign(promptkeys, clioverrides)
  26811. // startElxr requires instance // Independent cmds should have already been bypassed.
  26812. // if(cmdprompts.instanceName) {
  26813. // not an instanceless cmd.
  26814. console.dir(selectedinstance);
  26815. try {
  26816. chessinstances = acquirelocalinstances(selectedinstance);
  26817. findlocalinstances(chessinstances, detectedinstanceoptions);
  26818. initinstances(selectedinstance); // use the local instances for defaults if at all possible.
  26819. var todo = any( getInteractionPoints(detectedinstanceoptions, promptkeys) ).then(()=>{
  26820. var inst = initinstances(selectedinstance);
  26821. detection_state.localInstanceDetected = true;
  26822. return inst;
  26823. });
  26824. }
  26825. catch (e) {
  26826. // PB : TODO -- verbose mode warning.. console.warn(e) // Missing chessinstances is not an error...
  26827. var todo = any( getInteractionPoints(detectedinstanceoptions, promptkeys) ).then(()=>{
  26828. return initinstances(selectedinstance)
  26829. });
  26830. // if(!processedArgs._[0] || !selectedinstance.node_env || !selectedinstance.instanceName){
  26831. // // Weve not been told what to do.
  26832. // todo = todo.then(() => { return acquireChoices(selectedinstance) })
  26833. // }
  26834. todo = todo.then(() => {
  26835. try {
  26836. chessinstances = acquirelocalinstances(selectedinstance);
  26837. findlocalinstances(chessinstances, detectedinstanceoptions);
  26838. detectedinstanceoptions.splice(0,0, __default);
  26839. initinstances(selectedinstance);
  26840. detection_state.localInstanceDetected = true;
  26841. }
  26842. catch (e) {
  26843. // console.error(e)
  26844. console.log('No local instances config found in current root = ' + selectedinstance.root);
  26845. console.log('A config will be createed with the instance and environment chosen...');
  26846. // return (async ()=>{return await __default.reposerver})().then(()=>{
  26847. // // selectedinstance = Object.assign(detectedInstance, clioverrides);
  26848. // return selectedinstance = Object.assign(__default, selectedinstance);
  26849. // })
  26850. detection_state.localInstanceDetected = false;
  26851. return selectedinstance
  26852. }
  26853. });
  26854. }
  26855. return todo.then( ()=>{
  26856. // PB : TODO -- Embed this in the build instead of inlining it.
  26857. // Also attepmt to load from ../chess-config/...
  26858. var __repo_manifest = (commonjsRequire(path__default["default"].normalize(instanceroot + '/elxr/repo-manifest.js'),"/$$rollup_base$$"))(
  26859. 'defaultmanifest' // name
  26860. , { utils: bbhverse, username : selectedinstance.username, instanceName : selectedinstance.instanceName
  26861. , node_env : selectedinstance.node_env, reposerver : 'https://git.bbh.org.in' } // options
  26862. );
  26863. __default = Object.assign(__default, __repo_manifest, {
  26864. // Common baseline repos for all chess instances.
  26865. repos : (()=> {
  26866. var __repos = [
  26867. { repo : 'ember-masonry-grid' /*, branch : master*/ } // Default need not be specified.
  26868. , { repo : 'bbhverse' }
  26869. , { repo : 'clientverse' }
  26870. , { repo : 'serververse' }
  26871. , { repo : 'elxr' }
  26872. , { repo : 'ember-searchable-select' }
  26873. , { repo : 'loopback-component-jsonapi' }
  26874. , { repo : 'loopback-jsonapi-model-serializer' }
  26875. , { repo : 'loopback-connector-mysql' }
  26876. , { repo : 'loopback-connector-ds' }
  26877. , { repo : 'ember-service-worker' }
  26878. , { repo : 'ember-service-worker-asset-cache' }
  26879. , { repo : 'ember-service-worker-cache-fallback' }
  26880. , { repo : 'ember-service-worker-index' }
  26881. , { repo : 'ember-sw-client-route' }
  26882. , { repo : 'global-this' }
  26883. ];
  26884. Array.prototype.push.apply( __repos, __repo_manifest.repos);
  26885. return __repos;
  26886. })()
  26887. // Requires elevation only in windows
  26888. , elevated : [ { repo : 'chess-server-lib', requiresElevation : true } ]
  26889. , exludeMergeRepos : { }
  26890. });
  26891. initinstances(selectedinstance);
  26892. return selectedinstance
  26893. })
  26894. // }
  26895. // else return Promise.resolve(true)
  26896. })
  26897. .then(()=>{
  26898. runconfig = { NODE_ENV: selectedinstance.node_env };
  26899. try { runconfig = Object.assign(runconfig, commonjsRequire(instanceroot + '/run.js',"/$$rollup_base$$")); } catch (e) { }
  26900. generateDependencies();
  26901. if(noprerequisites[processedArgs._[0]]
  26902. || skipprereqs[processedArgs._[0]]
  26903. ) {
  26904. return elxrworker()
  26905. }
  26906. var neTask = ()=>{
  26907. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/${__ALIAS__STAMP__}`);
  26908. // collect garbage
  26909. return dirs( (dir)=>{
  26910. var matches = /run-(.*)/gm.exec(dir.name);
  26911. if(matches) {
  26912. if(+(matches[1]) < min) {
  26913. min = matches[1];
  26914. collect.splice( 0, 0, matches[1] );
  26915. }
  26916. else collect.push(matches[1]);
  26917. }
  26918. return Promise.resolve(collect);
  26919. }, `${selectedinstance.root}/.elxr` )
  26920. .then(()=>{
  26921. // delete garbage
  26922. if(collect.length > retaincount) {
  26923. var asyncs = [];
  26924. while((collect.length - asyncs.length) > retaincount) {
  26925. asyncs.push(getShellTask('rm',['-rf', `run-${collect[asyncs.length]}`], { cwd : `${selectedinstance.root}/.elxr` })());
  26926. }
  26927. return Promise.all(asyncs)
  26928. }
  26929. else return true
  26930. })
  26931. .catch(e => {
  26932. })
  26933. };
  26934. neTask.statuslog = statuslog;
  26935. shell_verse.getNonElevatedTask( neTask )();
  26936. var commonTask = ()=>{
  26937. verifyAndInstallPrerequisites.statuslog = statuslog;
  26938. mainTasks.push(verifyAndInstallPrerequisites);
  26939. mainTasks.push(maintask);
  26940. return any(mainTasks);
  26941. };
  26942. return commonTask()
  26943. })
  26944. };
  26945. var __default = {}; // PB : TODO -- Use initialized instance instead of default everywhere.
  26946. // PB : TODO -- In windows if we are run from an elevated shell we never move forward and simply exits !?.
  26947. // -- Currently workaround in windows is to always run from a non-elevated shell.
  26948. shell_verse.acquireElevationState().then((elevationstate) => {
  26949. return detectInstanceRoot.then(()=>{
  26950. var cmdobj = cmds[clioverrides.cmd];
  26951. return Promise.all((cmdobj.requires || []).map( (r) => bbhverse.promisify(null, r) ) ).then(()=>{
  26952. if(cmdobj.independentcmd) {
  26953. if(cmdobj.requiresElevation) {
  26954. return cmdobj.cmdFn()
  26955. }
  26956. else return cmdobj.cmdFn()
  26957. }
  26958. else return startElxr()
  26959. })
  26960. .catch(e => {
  26961. if(typeof e === 'symbol') console.log('error : ' + 'symbol');
  26962. else console.log('error : ' + e);
  26963. })
  26964. })
  26965. });
  26966. // Sample instances config.
  26967. // var instances = {
  26968. // "elixir": {
  26969. // "production": {
  26970. // "reposervers": ["http://git.bbh", "https://git.bbh.org.in"]
  26971. // , "repos": ["ember-masonry-grid", "client", "elixir-client"]
  26972. // , "exludeMergeRepos": {
  26973. // "elixir-config-development": true, "elixir-config-test": true
  26974. // , "elixir-config-production": true, "elixir-data": true
  26975. // }
  26976. // , "instanceName": "elixir", "node_env": "production"
  26977. // }
  26978. // },
  26979. // "current_run": { "instanceName": "elixir", "node_env": "production" }
  26980. // }
  26981. // ,([^\}^\S\r]*?\}) // Regexp to eliminate extra comma at the end of an array or an object...
  26982. var elxr_1 = {
  26983. };
  26984. module.exports = elxr_1;