i.js 836KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799
  1. /* Version: 1.0.0 - August 23, 2021 14:13:43 */
  2. 'use strict';
  3. var path$1 = require('path');
  4. var childProcess = require('child_process');
  5. var fs$1 = require('fs');
  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. function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
  13. var path__default = /*#__PURE__*/_interopDefaultLegacy(path$1);
  14. var childProcess__default = /*#__PURE__*/_interopDefaultLegacy(childProcess);
  15. var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs$1);
  16. var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);
  17. var os__default = /*#__PURE__*/_interopDefaultLegacy(os);
  18. var tty__default = /*#__PURE__*/_interopDefaultLegacy(tty);
  19. var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0);
  20. var require$$0__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$0$1);
  21. var assert__default = /*#__PURE__*/_interopDefaultLegacy(assert);
  22. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  23. function getAugmentedNamespace(n) {
  24. if (n.__esModule) return n;
  25. var a = Object.defineProperty({}, '__esModule', {value: true});
  26. Object.keys(n).forEach(function (k) {
  27. var d = Object.getOwnPropertyDescriptor(n, k);
  28. Object.defineProperty(a, k, d.get ? d : {
  29. enumerable: true,
  30. get: function () {
  31. return n[k];
  32. }
  33. });
  34. });
  35. return a;
  36. }
  37. function createCommonjsModule(fn, basedir, module) {
  38. return module = {
  39. path: basedir,
  40. exports: {},
  41. require: function (path, base) {
  42. return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
  43. }
  44. }, fn(module, module.exports), module.exports;
  45. }
  46. function commonjsRegister (path, loader) {
  47. DYNAMIC_REQUIRE_LOADERS[path] = loader;
  48. }
  49. const DYNAMIC_REQUIRE_LOADERS = Object.create(null);
  50. const DYNAMIC_REQUIRE_CACHE = Object.create(null);
  51. const DEFAULT_PARENT_MODULE = {
  52. id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []
  53. };
  54. const CHECKED_EXTENSIONS = ['', '.js', '.json'];
  55. function normalize (path) {
  56. path = path.replace(/\\/g, '/');
  57. const parts = path.split('/');
  58. const slashed = parts[0] === '';
  59. for (let i = 1; i < parts.length; i++) {
  60. if (parts[i] === '.' || parts[i] === '') {
  61. parts.splice(i--, 1);
  62. }
  63. }
  64. for (let i = 1; i < parts.length; i++) {
  65. if (parts[i] !== '..') continue;
  66. if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {
  67. parts.splice(--i, 2);
  68. i--;
  69. }
  70. }
  71. path = parts.join('/');
  72. if (slashed && path[0] !== '/')
  73. path = '/' + path;
  74. else if (path.length === 0)
  75. path = '.';
  76. return path;
  77. }
  78. function join () {
  79. if (arguments.length === 0)
  80. return '.';
  81. let joined;
  82. for (let i = 0; i < arguments.length; ++i) {
  83. let arg = arguments[i];
  84. if (arg.length > 0) {
  85. if (joined === undefined)
  86. joined = arg;
  87. else
  88. joined += '/' + arg;
  89. }
  90. }
  91. if (joined === undefined)
  92. return '.';
  93. return joined;
  94. }
  95. function isPossibleNodeModulesPath (modulePath) {
  96. let c0 = modulePath[0];
  97. if (c0 === '/' || c0 === '\\') return false;
  98. let c1 = modulePath[1], c2 = modulePath[2];
  99. if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\')) ||
  100. (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\'))) return false;
  101. if (c1 === ':' && (c2 === '/' || c2 === '\\'))
  102. return false;
  103. return true;
  104. }
  105. function dirname (path) {
  106. if (path.length === 0)
  107. return '.';
  108. let i = path.length - 1;
  109. while (i > 0) {
  110. const c = path.charCodeAt(i);
  111. if ((c === 47 || c === 92) && i !== path.length - 1)
  112. break;
  113. i--;
  114. }
  115. if (i > 0)
  116. return path.substr(0, i);
  117. if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)
  118. return path.charAt(0);
  119. return '.';
  120. }
  121. function commonjsResolveImpl (path, originalModuleDir, testCache) {
  122. const shouldTryNodeModules = isPossibleNodeModulesPath(path);
  123. path = normalize(path);
  124. let relPath;
  125. if (path[0] === '/') {
  126. originalModuleDir = '/';
  127. }
  128. while (true) {
  129. if (!shouldTryNodeModules) {
  130. relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;
  131. } else if (originalModuleDir) {
  132. relPath = normalize(originalModuleDir + '/node_modules/' + path);
  133. } else {
  134. relPath = normalize(join('node_modules', path));
  135. }
  136. if (relPath.endsWith('/..')) {
  137. break; // Travelled too far up, avoid infinite loop
  138. }
  139. for (let extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {
  140. const resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];
  141. if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {
  142. return resolvedPath;
  143. } if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {
  144. return resolvedPath;
  145. } }
  146. if (!shouldTryNodeModules) break;
  147. const nextDir = normalize(originalModuleDir + '/..');
  148. if (nextDir === originalModuleDir) break;
  149. originalModuleDir = nextDir;
  150. }
  151. return null;
  152. }
  153. function commonjsResolve (path, originalModuleDir) {
  154. const resolvedPath = commonjsResolveImpl(path, originalModuleDir);
  155. if (resolvedPath !== null) {
  156. return resolvedPath;
  157. }
  158. return require.resolve(path);
  159. }
  160. function commonjsRequire (path, originalModuleDir) {
  161. const resolvedPath = commonjsResolveImpl(path, originalModuleDir);
  162. if (resolvedPath !== null) {
  163. let cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];
  164. if (cachedModule) return cachedModule.exports;
  165. const loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];
  166. if (loader) {
  167. DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {
  168. id: resolvedPath,
  169. filename: resolvedPath,
  170. path: dirname(resolvedPath),
  171. exports: {},
  172. parent: DEFAULT_PARENT_MODULE,
  173. loaded: false,
  174. children: [],
  175. paths: [],
  176. require: function (path, base) {
  177. return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);
  178. }
  179. };
  180. try {
  181. loader.call(commonjsGlobal, cachedModule, cachedModule.exports);
  182. } catch (error) {
  183. delete DYNAMIC_REQUIRE_CACHE[resolvedPath];
  184. throw error;
  185. }
  186. cachedModule.loaded = true;
  187. return cachedModule.exports;
  188. } }
  189. return require(path);
  190. }
  191. commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;
  192. commonjsRequire.resolve = commonjsResolve;
  193. /**
  194. * This method returns the first argument it receives.
  195. *
  196. * @static
  197. * @since 0.1.0
  198. * @memberOf _
  199. * @category Util
  200. * @param {*} value Any value.
  201. * @returns {*} Returns `value`.
  202. * @example
  203. *
  204. * var object = { 'a': 1 };
  205. *
  206. * console.log(_.identity(object) === object);
  207. * // => true
  208. */
  209. function identity(value) {
  210. return value;
  211. }
  212. var identity_1 = identity;
  213. /** Detect free variable `global` from Node.js. */
  214. var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
  215. var _freeGlobal = freeGlobal;
  216. /** Detect free variable `self`. */
  217. var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
  218. /** Used as a reference to the global object. */
  219. var root = _freeGlobal || freeSelf || Function('return this')();
  220. var _root = root;
  221. /** Built-in value references. */
  222. var Symbol$1 = _root.Symbol;
  223. var _Symbol = Symbol$1;
  224. /** Used for built-in method references. */
  225. var objectProto$h = Object.prototype;
  226. /** Used to check objects for own properties. */
  227. var hasOwnProperty$e = objectProto$h.hasOwnProperty;
  228. /**
  229. * Used to resolve the
  230. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  231. * of values.
  232. */
  233. var nativeObjectToString$1 = objectProto$h.toString;
  234. /** Built-in value references. */
  235. var symToStringTag$1 = _Symbol ? _Symbol.toStringTag : undefined;
  236. /**
  237. * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
  238. *
  239. * @private
  240. * @param {*} value The value to query.
  241. * @returns {string} Returns the raw `toStringTag`.
  242. */
  243. function getRawTag(value) {
  244. var isOwn = hasOwnProperty$e.call(value, symToStringTag$1),
  245. tag = value[symToStringTag$1];
  246. try {
  247. value[symToStringTag$1] = undefined;
  248. var unmasked = true;
  249. } catch (e) {}
  250. var result = nativeObjectToString$1.call(value);
  251. if (unmasked) {
  252. if (isOwn) {
  253. value[symToStringTag$1] = tag;
  254. } else {
  255. delete value[symToStringTag$1];
  256. }
  257. }
  258. return result;
  259. }
  260. var _getRawTag = getRawTag;
  261. /** Used for built-in method references. */
  262. var objectProto$g = Object.prototype;
  263. /**
  264. * Used to resolve the
  265. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  266. * of values.
  267. */
  268. var nativeObjectToString = objectProto$g.toString;
  269. /**
  270. * Converts `value` to a string using `Object.prototype.toString`.
  271. *
  272. * @private
  273. * @param {*} value The value to convert.
  274. * @returns {string} Returns the converted string.
  275. */
  276. function objectToString(value) {
  277. return nativeObjectToString.call(value);
  278. }
  279. var _objectToString = objectToString;
  280. /** `Object#toString` result references. */
  281. var nullTag = '[object Null]',
  282. undefinedTag = '[object Undefined]';
  283. /** Built-in value references. */
  284. var symToStringTag = _Symbol ? _Symbol.toStringTag : undefined;
  285. /**
  286. * The base implementation of `getTag` without fallbacks for buggy environments.
  287. *
  288. * @private
  289. * @param {*} value The value to query.
  290. * @returns {string} Returns the `toStringTag`.
  291. */
  292. function baseGetTag(value) {
  293. if (value == null) {
  294. return value === undefined ? undefinedTag : nullTag;
  295. }
  296. return (symToStringTag && symToStringTag in Object(value))
  297. ? _getRawTag(value)
  298. : _objectToString(value);
  299. }
  300. var _baseGetTag = baseGetTag;
  301. /**
  302. * Checks if `value` is the
  303. * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
  304. * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
  305. *
  306. * @static
  307. * @memberOf _
  308. * @since 0.1.0
  309. * @category Lang
  310. * @param {*} value The value to check.
  311. * @returns {boolean} Returns `true` if `value` is an object, else `false`.
  312. * @example
  313. *
  314. * _.isObject({});
  315. * // => true
  316. *
  317. * _.isObject([1, 2, 3]);
  318. * // => true
  319. *
  320. * _.isObject(_.noop);
  321. * // => true
  322. *
  323. * _.isObject(null);
  324. * // => false
  325. */
  326. function isObject$1(value) {
  327. var type = typeof value;
  328. return value != null && (type == 'object' || type == 'function');
  329. }
  330. var isObject_1 = isObject$1;
  331. /** `Object#toString` result references. */
  332. var asyncTag = '[object AsyncFunction]',
  333. funcTag$2 = '[object Function]',
  334. genTag$1 = '[object GeneratorFunction]',
  335. proxyTag = '[object Proxy]';
  336. /**
  337. * Checks if `value` is classified as a `Function` object.
  338. *
  339. * @static
  340. * @memberOf _
  341. * @since 0.1.0
  342. * @category Lang
  343. * @param {*} value The value to check.
  344. * @returns {boolean} Returns `true` if `value` is a function, else `false`.
  345. * @example
  346. *
  347. * _.isFunction(_);
  348. * // => true
  349. *
  350. * _.isFunction(/abc/);
  351. * // => false
  352. */
  353. function isFunction(value) {
  354. if (!isObject_1(value)) {
  355. return false;
  356. }
  357. // The use of `Object#toString` avoids issues with the `typeof` operator
  358. // in Safari 9 which returns 'object' for typed arrays and other constructors.
  359. var tag = _baseGetTag(value);
  360. return tag == funcTag$2 || tag == genTag$1 || tag == asyncTag || tag == proxyTag;
  361. }
  362. var isFunction_1 = isFunction;
  363. /** Used to detect overreaching core-js shims. */
  364. var coreJsData = _root['__core-js_shared__'];
  365. var _coreJsData = coreJsData;
  366. /** Used to detect methods masquerading as native. */
  367. var maskSrcKey = (function() {
  368. var uid = /[^.]+$/.exec(_coreJsData && _coreJsData.keys && _coreJsData.keys.IE_PROTO || '');
  369. return uid ? ('Symbol(src)_1.' + uid) : '';
  370. }());
  371. /**
  372. * Checks if `func` has its source masked.
  373. *
  374. * @private
  375. * @param {Function} func The function to check.
  376. * @returns {boolean} Returns `true` if `func` is masked, else `false`.
  377. */
  378. function isMasked(func) {
  379. return !!maskSrcKey && (maskSrcKey in func);
  380. }
  381. var _isMasked = isMasked;
  382. /** Used for built-in method references. */
  383. var funcProto$2 = Function.prototype;
  384. /** Used to resolve the decompiled source of functions. */
  385. var funcToString$2 = funcProto$2.toString;
  386. /**
  387. * Converts `func` to its source code.
  388. *
  389. * @private
  390. * @param {Function} func The function to convert.
  391. * @returns {string} Returns the source code.
  392. */
  393. function toSource(func) {
  394. if (func != null) {
  395. try {
  396. return funcToString$2.call(func);
  397. } catch (e) {}
  398. try {
  399. return (func + '');
  400. } catch (e) {}
  401. }
  402. return '';
  403. }
  404. var _toSource = toSource;
  405. /**
  406. * Used to match `RegExp`
  407. * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
  408. */
  409. var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
  410. /** Used to detect host constructors (Safari). */
  411. var reIsHostCtor = /^\[object .+?Constructor\]$/;
  412. /** Used for built-in method references. */
  413. var funcProto$1 = Function.prototype,
  414. objectProto$f = Object.prototype;
  415. /** Used to resolve the decompiled source of functions. */
  416. var funcToString$1 = funcProto$1.toString;
  417. /** Used to check objects for own properties. */
  418. var hasOwnProperty$d = objectProto$f.hasOwnProperty;
  419. /** Used to detect if a method is native. */
  420. var reIsNative = RegExp('^' +
  421. funcToString$1.call(hasOwnProperty$d).replace(reRegExpChar, '\\$&')
  422. .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
  423. );
  424. /**
  425. * The base implementation of `_.isNative` without bad shim checks.
  426. *
  427. * @private
  428. * @param {*} value The value to check.
  429. * @returns {boolean} Returns `true` if `value` is a native function,
  430. * else `false`.
  431. */
  432. function baseIsNative(value) {
  433. if (!isObject_1(value) || _isMasked(value)) {
  434. return false;
  435. }
  436. var pattern = isFunction_1(value) ? reIsNative : reIsHostCtor;
  437. return pattern.test(_toSource(value));
  438. }
  439. var _baseIsNative = baseIsNative;
  440. /**
  441. * Gets the value at `key` of `object`.
  442. *
  443. * @private
  444. * @param {Object} [object] The object to query.
  445. * @param {string} key The key of the property to get.
  446. * @returns {*} Returns the property value.
  447. */
  448. function getValue(object, key) {
  449. return object == null ? undefined : object[key];
  450. }
  451. var _getValue = getValue;
  452. /**
  453. * Gets the native function at `key` of `object`.
  454. *
  455. * @private
  456. * @param {Object} object The object to query.
  457. * @param {string} key The key of the method to get.
  458. * @returns {*} Returns the function if it's native, else `undefined`.
  459. */
  460. function getNative(object, key) {
  461. var value = _getValue(object, key);
  462. return _baseIsNative(value) ? value : undefined;
  463. }
  464. var _getNative = getNative;
  465. /* Built-in method references that are verified to be native. */
  466. var WeakMap$1 = _getNative(_root, 'WeakMap');
  467. var _WeakMap = WeakMap$1;
  468. /** Used to store function metadata. */
  469. var metaMap = _WeakMap && new _WeakMap;
  470. var _metaMap = metaMap;
  471. /**
  472. * The base implementation of `setData` without support for hot loop shorting.
  473. *
  474. * @private
  475. * @param {Function} func The function to associate metadata with.
  476. * @param {*} data The metadata.
  477. * @returns {Function} Returns `func`.
  478. */
  479. var baseSetData = !_metaMap ? identity_1 : function(func, data) {
  480. _metaMap.set(func, data);
  481. return func;
  482. };
  483. var _baseSetData = baseSetData;
  484. /** Built-in value references. */
  485. var objectCreate = Object.create;
  486. /**
  487. * The base implementation of `_.create` without support for assigning
  488. * properties to the created object.
  489. *
  490. * @private
  491. * @param {Object} proto The object to inherit from.
  492. * @returns {Object} Returns the new object.
  493. */
  494. var baseCreate = (function() {
  495. function object() {}
  496. return function(proto) {
  497. if (!isObject_1(proto)) {
  498. return {};
  499. }
  500. if (objectCreate) {
  501. return objectCreate(proto);
  502. }
  503. object.prototype = proto;
  504. var result = new object;
  505. object.prototype = undefined;
  506. return result;
  507. };
  508. }());
  509. var _baseCreate = baseCreate;
  510. /**
  511. * Creates a function that produces an instance of `Ctor` regardless of
  512. * whether it was invoked as part of a `new` expression or by `call` or `apply`.
  513. *
  514. * @private
  515. * @param {Function} Ctor The constructor to wrap.
  516. * @returns {Function} Returns the new wrapped function.
  517. */
  518. function createCtor(Ctor) {
  519. return function() {
  520. // Use a `switch` statement to work with class constructors. See
  521. // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist
  522. // for more details.
  523. var args = arguments;
  524. switch (args.length) {
  525. case 0: return new Ctor;
  526. case 1: return new Ctor(args[0]);
  527. case 2: return new Ctor(args[0], args[1]);
  528. case 3: return new Ctor(args[0], args[1], args[2]);
  529. case 4: return new Ctor(args[0], args[1], args[2], args[3]);
  530. case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]);
  531. case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);
  532. case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
  533. }
  534. var thisBinding = _baseCreate(Ctor.prototype),
  535. result = Ctor.apply(thisBinding, args);
  536. // Mimic the constructor's `return` behavior.
  537. // See https://es5.github.io/#x13.2.2 for more details.
  538. return isObject_1(result) ? result : thisBinding;
  539. };
  540. }
  541. var _createCtor = createCtor;
  542. /** Used to compose bitmasks for function metadata. */
  543. var WRAP_BIND_FLAG$6 = 1;
  544. /**
  545. * Creates a function that wraps `func` to invoke it with the optional `this`
  546. * binding of `thisArg`.
  547. *
  548. * @private
  549. * @param {Function} func The function to wrap.
  550. * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
  551. * @param {*} [thisArg] The `this` binding of `func`.
  552. * @returns {Function} Returns the new wrapped function.
  553. */
  554. function createBind(func, bitmask, thisArg) {
  555. var isBind = bitmask & WRAP_BIND_FLAG$6,
  556. Ctor = _createCtor(func);
  557. function wrapper() {
  558. var fn = (this && this !== _root && this instanceof wrapper) ? Ctor : func;
  559. return fn.apply(isBind ? thisArg : this, arguments);
  560. }
  561. return wrapper;
  562. }
  563. var _createBind = createBind;
  564. /**
  565. * A faster alternative to `Function#apply`, this function invokes `func`
  566. * with the `this` binding of `thisArg` and the arguments of `args`.
  567. *
  568. * @private
  569. * @param {Function} func The function to invoke.
  570. * @param {*} thisArg The `this` binding of `func`.
  571. * @param {Array} args The arguments to invoke `func` with.
  572. * @returns {*} Returns the result of `func`.
  573. */
  574. function apply(func, thisArg, args) {
  575. switch (args.length) {
  576. case 0: return func.call(thisArg);
  577. case 1: return func.call(thisArg, args[0]);
  578. case 2: return func.call(thisArg, args[0], args[1]);
  579. case 3: return func.call(thisArg, args[0], args[1], args[2]);
  580. }
  581. return func.apply(thisArg, args);
  582. }
  583. var _apply = apply;
  584. /* Built-in method references for those with the same name as other `lodash` methods. */
  585. var nativeMax$3 = Math.max;
  586. /**
  587. * Creates an array that is the composition of partially applied arguments,
  588. * placeholders, and provided arguments into a single array of arguments.
  589. *
  590. * @private
  591. * @param {Array} args The provided arguments.
  592. * @param {Array} partials The arguments to prepend to those provided.
  593. * @param {Array} holders The `partials` placeholder indexes.
  594. * @params {boolean} [isCurried] Specify composing for a curried function.
  595. * @returns {Array} Returns the new array of composed arguments.
  596. */
  597. function composeArgs(args, partials, holders, isCurried) {
  598. var argsIndex = -1,
  599. argsLength = args.length,
  600. holdersLength = holders.length,
  601. leftIndex = -1,
  602. leftLength = partials.length,
  603. rangeLength = nativeMax$3(argsLength - holdersLength, 0),
  604. result = Array(leftLength + rangeLength),
  605. isUncurried = !isCurried;
  606. while (++leftIndex < leftLength) {
  607. result[leftIndex] = partials[leftIndex];
  608. }
  609. while (++argsIndex < holdersLength) {
  610. if (isUncurried || argsIndex < argsLength) {
  611. result[holders[argsIndex]] = args[argsIndex];
  612. }
  613. }
  614. while (rangeLength--) {
  615. result[leftIndex++] = args[argsIndex++];
  616. }
  617. return result;
  618. }
  619. var _composeArgs = composeArgs;
  620. /* Built-in method references for those with the same name as other `lodash` methods. */
  621. var nativeMax$2 = Math.max;
  622. /**
  623. * This function is like `composeArgs` except that the arguments composition
  624. * is tailored for `_.partialRight`.
  625. *
  626. * @private
  627. * @param {Array} args The provided arguments.
  628. * @param {Array} partials The arguments to append to those provided.
  629. * @param {Array} holders The `partials` placeholder indexes.
  630. * @params {boolean} [isCurried] Specify composing for a curried function.
  631. * @returns {Array} Returns the new array of composed arguments.
  632. */
  633. function composeArgsRight(args, partials, holders, isCurried) {
  634. var argsIndex = -1,
  635. argsLength = args.length,
  636. holdersIndex = -1,
  637. holdersLength = holders.length,
  638. rightIndex = -1,
  639. rightLength = partials.length,
  640. rangeLength = nativeMax$2(argsLength - holdersLength, 0),
  641. result = Array(rangeLength + rightLength),
  642. isUncurried = !isCurried;
  643. while (++argsIndex < rangeLength) {
  644. result[argsIndex] = args[argsIndex];
  645. }
  646. var offset = argsIndex;
  647. while (++rightIndex < rightLength) {
  648. result[offset + rightIndex] = partials[rightIndex];
  649. }
  650. while (++holdersIndex < holdersLength) {
  651. if (isUncurried || argsIndex < argsLength) {
  652. result[offset + holders[holdersIndex]] = args[argsIndex++];
  653. }
  654. }
  655. return result;
  656. }
  657. var _composeArgsRight = composeArgsRight;
  658. /**
  659. * Gets the number of `placeholder` occurrences in `array`.
  660. *
  661. * @private
  662. * @param {Array} array The array to inspect.
  663. * @param {*} placeholder The placeholder to search for.
  664. * @returns {number} Returns the placeholder count.
  665. */
  666. function countHolders(array, placeholder) {
  667. var length = array.length,
  668. result = 0;
  669. while (length--) {
  670. if (array[length] === placeholder) {
  671. ++result;
  672. }
  673. }
  674. return result;
  675. }
  676. var _countHolders = countHolders;
  677. /**
  678. * The function whose prototype chain sequence wrappers inherit from.
  679. *
  680. * @private
  681. */
  682. function baseLodash() {
  683. // No operation performed.
  684. }
  685. var _baseLodash = baseLodash;
  686. /** Used as references for the maximum length and index of an array. */
  687. var MAX_ARRAY_LENGTH = 4294967295;
  688. /**
  689. * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.
  690. *
  691. * @private
  692. * @constructor
  693. * @param {*} value The value to wrap.
  694. */
  695. function LazyWrapper(value) {
  696. this.__wrapped__ = value;
  697. this.__actions__ = [];
  698. this.__dir__ = 1;
  699. this.__filtered__ = false;
  700. this.__iteratees__ = [];
  701. this.__takeCount__ = MAX_ARRAY_LENGTH;
  702. this.__views__ = [];
  703. }
  704. // Ensure `LazyWrapper` is an instance of `baseLodash`.
  705. LazyWrapper.prototype = _baseCreate(_baseLodash.prototype);
  706. LazyWrapper.prototype.constructor = LazyWrapper;
  707. var _LazyWrapper = LazyWrapper;
  708. /**
  709. * This method returns `undefined`.
  710. *
  711. * @static
  712. * @memberOf _
  713. * @since 2.3.0
  714. * @category Util
  715. * @example
  716. *
  717. * _.times(2, _.noop);
  718. * // => [undefined, undefined]
  719. */
  720. function noop() {
  721. // No operation performed.
  722. }
  723. var noop_1 = noop;
  724. /**
  725. * Gets metadata for `func`.
  726. *
  727. * @private
  728. * @param {Function} func The function to query.
  729. * @returns {*} Returns the metadata for `func`.
  730. */
  731. var getData = !_metaMap ? noop_1 : function(func) {
  732. return _metaMap.get(func);
  733. };
  734. var _getData = getData;
  735. /** Used to lookup unminified function names. */
  736. var realNames = {};
  737. var _realNames = realNames;
  738. /** Used for built-in method references. */
  739. var objectProto$e = Object.prototype;
  740. /** Used to check objects for own properties. */
  741. var hasOwnProperty$c = objectProto$e.hasOwnProperty;
  742. /**
  743. * Gets the name of `func`.
  744. *
  745. * @private
  746. * @param {Function} func The function to query.
  747. * @returns {string} Returns the function name.
  748. */
  749. function getFuncName(func) {
  750. var result = (func.name + ''),
  751. array = _realNames[result],
  752. length = hasOwnProperty$c.call(_realNames, result) ? array.length : 0;
  753. while (length--) {
  754. var data = array[length],
  755. otherFunc = data.func;
  756. if (otherFunc == null || otherFunc == func) {
  757. return data.name;
  758. }
  759. }
  760. return result;
  761. }
  762. var _getFuncName = getFuncName;
  763. /**
  764. * The base constructor for creating `lodash` wrapper objects.
  765. *
  766. * @private
  767. * @param {*} value The value to wrap.
  768. * @param {boolean} [chainAll] Enable explicit method chain sequences.
  769. */
  770. function LodashWrapper(value, chainAll) {
  771. this.__wrapped__ = value;
  772. this.__actions__ = [];
  773. this.__chain__ = !!chainAll;
  774. this.__index__ = 0;
  775. this.__values__ = undefined;
  776. }
  777. LodashWrapper.prototype = _baseCreate(_baseLodash.prototype);
  778. LodashWrapper.prototype.constructor = LodashWrapper;
  779. var _LodashWrapper = LodashWrapper;
  780. /**
  781. * Checks if `value` is classified as an `Array` object.
  782. *
  783. * @static
  784. * @memberOf _
  785. * @since 0.1.0
  786. * @category Lang
  787. * @param {*} value The value to check.
  788. * @returns {boolean} Returns `true` if `value` is an array, else `false`.
  789. * @example
  790. *
  791. * _.isArray([1, 2, 3]);
  792. * // => true
  793. *
  794. * _.isArray(document.body.children);
  795. * // => false
  796. *
  797. * _.isArray('abc');
  798. * // => false
  799. *
  800. * _.isArray(_.noop);
  801. * // => false
  802. */
  803. var isArray$3 = Array.isArray;
  804. var isArray_1 = isArray$3;
  805. /**
  806. * Checks if `value` is object-like. A value is object-like if it's not `null`
  807. * and has a `typeof` result of "object".
  808. *
  809. * @static
  810. * @memberOf _
  811. * @since 4.0.0
  812. * @category Lang
  813. * @param {*} value The value to check.
  814. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  815. * @example
  816. *
  817. * _.isObjectLike({});
  818. * // => true
  819. *
  820. * _.isObjectLike([1, 2, 3]);
  821. * // => true
  822. *
  823. * _.isObjectLike(_.noop);
  824. * // => false
  825. *
  826. * _.isObjectLike(null);
  827. * // => false
  828. */
  829. function isObjectLike(value) {
  830. return value != null && typeof value == 'object';
  831. }
  832. var isObjectLike_1 = isObjectLike;
  833. /**
  834. * Copies the values of `source` to `array`.
  835. *
  836. * @private
  837. * @param {Array} source The array to copy values from.
  838. * @param {Array} [array=[]] The array to copy values to.
  839. * @returns {Array} Returns `array`.
  840. */
  841. function copyArray(source, array) {
  842. var index = -1,
  843. length = source.length;
  844. array || (array = Array(length));
  845. while (++index < length) {
  846. array[index] = source[index];
  847. }
  848. return array;
  849. }
  850. var _copyArray = copyArray;
  851. /**
  852. * Creates a clone of `wrapper`.
  853. *
  854. * @private
  855. * @param {Object} wrapper The wrapper to clone.
  856. * @returns {Object} Returns the cloned wrapper.
  857. */
  858. function wrapperClone(wrapper) {
  859. if (wrapper instanceof _LazyWrapper) {
  860. return wrapper.clone();
  861. }
  862. var result = new _LodashWrapper(wrapper.__wrapped__, wrapper.__chain__);
  863. result.__actions__ = _copyArray(wrapper.__actions__);
  864. result.__index__ = wrapper.__index__;
  865. result.__values__ = wrapper.__values__;
  866. return result;
  867. }
  868. var _wrapperClone = wrapperClone;
  869. /** Used for built-in method references. */
  870. var objectProto$d = Object.prototype;
  871. /** Used to check objects for own properties. */
  872. var hasOwnProperty$b = objectProto$d.hasOwnProperty;
  873. /**
  874. * Creates a `lodash` object which wraps `value` to enable implicit method
  875. * chain sequences. Methods that operate on and return arrays, collections,
  876. * and functions can be chained together. Methods that retrieve a single value
  877. * or may return a primitive value will automatically end the chain sequence
  878. * and return the unwrapped value. Otherwise, the value must be unwrapped
  879. * with `_#value`.
  880. *
  881. * Explicit chain sequences, which must be unwrapped with `_#value`, may be
  882. * enabled using `_.chain`.
  883. *
  884. * The execution of chained methods is lazy, that is, it's deferred until
  885. * `_#value` is implicitly or explicitly called.
  886. *
  887. * Lazy evaluation allows several methods to support shortcut fusion.
  888. * Shortcut fusion is an optimization to merge iteratee calls; this avoids
  889. * the creation of intermediate arrays and can greatly reduce the number of
  890. * iteratee executions. Sections of a chain sequence qualify for shortcut
  891. * fusion if the section is applied to an array and iteratees accept only
  892. * one argument. The heuristic for whether a section qualifies for shortcut
  893. * fusion is subject to change.
  894. *
  895. * Chaining is supported in custom builds as long as the `_#value` method is
  896. * directly or indirectly included in the build.
  897. *
  898. * In addition to lodash methods, wrappers have `Array` and `String` methods.
  899. *
  900. * The wrapper `Array` methods are:
  901. * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift`
  902. *
  903. * The wrapper `String` methods are:
  904. * `replace` and `split`
  905. *
  906. * The wrapper methods that support shortcut fusion are:
  907. * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`,
  908. * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`,
  909. * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray`
  910. *
  911. * The chainable wrapper methods are:
  912. * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`,
  913. * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`,
  914. * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`,
  915. * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`,
  916. * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`,
  917. * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`,
  918. * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`,
  919. * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`,
  920. * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`,
  921. * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`,
  922. * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`,
  923. * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`,
  924. * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`,
  925. * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`,
  926. * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`,
  927. * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`,
  928. * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`,
  929. * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`,
  930. * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`,
  931. * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`,
  932. * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`,
  933. * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`,
  934. * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`,
  935. * `zipObject`, `zipObjectDeep`, and `zipWith`
  936. *
  937. * The wrapper methods that are **not** chainable by default are:
  938. * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`,
  939. * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`,
  940. * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`,
  941. * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`,
  942. * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`,
  943. * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`,
  944. * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`,
  945. * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`,
  946. * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`,
  947. * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`,
  948. * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`,
  949. * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`,
  950. * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`,
  951. * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`,
  952. * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`,
  953. * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`,
  954. * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`,
  955. * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`,
  956. * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`,
  957. * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`,
  958. * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`,
  959. * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`,
  960. * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`,
  961. * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`,
  962. * `upperFirst`, `value`, and `words`
  963. *
  964. * @name _
  965. * @constructor
  966. * @category Seq
  967. * @param {*} value The value to wrap in a `lodash` instance.
  968. * @returns {Object} Returns the new `lodash` wrapper instance.
  969. * @example
  970. *
  971. * function square(n) {
  972. * return n * n;
  973. * }
  974. *
  975. * var wrapped = _([1, 2, 3]);
  976. *
  977. * // Returns an unwrapped value.
  978. * wrapped.reduce(_.add);
  979. * // => 6
  980. *
  981. * // Returns a wrapped value.
  982. * var squares = wrapped.map(square);
  983. *
  984. * _.isArray(squares);
  985. * // => false
  986. *
  987. * _.isArray(squares.value());
  988. * // => true
  989. */
  990. function lodash(value) {
  991. if (isObjectLike_1(value) && !isArray_1(value) && !(value instanceof _LazyWrapper)) {
  992. if (value instanceof _LodashWrapper) {
  993. return value;
  994. }
  995. if (hasOwnProperty$b.call(value, '__wrapped__')) {
  996. return _wrapperClone(value);
  997. }
  998. }
  999. return new _LodashWrapper(value);
  1000. }
  1001. // Ensure wrappers are instances of `baseLodash`.
  1002. lodash.prototype = _baseLodash.prototype;
  1003. lodash.prototype.constructor = lodash;
  1004. var wrapperLodash = lodash;
  1005. /**
  1006. * Checks if `func` has a lazy counterpart.
  1007. *
  1008. * @private
  1009. * @param {Function} func The function to check.
  1010. * @returns {boolean} Returns `true` if `func` has a lazy counterpart,
  1011. * else `false`.
  1012. */
  1013. function isLaziable(func) {
  1014. var funcName = _getFuncName(func),
  1015. other = wrapperLodash[funcName];
  1016. if (typeof other != 'function' || !(funcName in _LazyWrapper.prototype)) {
  1017. return false;
  1018. }
  1019. if (func === other) {
  1020. return true;
  1021. }
  1022. var data = _getData(other);
  1023. return !!data && func === data[0];
  1024. }
  1025. var _isLaziable = isLaziable;
  1026. /** Used to detect hot functions by number of calls within a span of milliseconds. */
  1027. var HOT_COUNT = 800,
  1028. HOT_SPAN = 16;
  1029. /* Built-in method references for those with the same name as other `lodash` methods. */
  1030. var nativeNow = Date.now;
  1031. /**
  1032. * Creates a function that'll short out and invoke `identity` instead
  1033. * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
  1034. * milliseconds.
  1035. *
  1036. * @private
  1037. * @param {Function} func The function to restrict.
  1038. * @returns {Function} Returns the new shortable function.
  1039. */
  1040. function shortOut(func) {
  1041. var count = 0,
  1042. lastCalled = 0;
  1043. return function() {
  1044. var stamp = nativeNow(),
  1045. remaining = HOT_SPAN - (stamp - lastCalled);
  1046. lastCalled = stamp;
  1047. if (remaining > 0) {
  1048. if (++count >= HOT_COUNT) {
  1049. return arguments[0];
  1050. }
  1051. } else {
  1052. count = 0;
  1053. }
  1054. return func.apply(undefined, arguments);
  1055. };
  1056. }
  1057. var _shortOut = shortOut;
  1058. /**
  1059. * Sets metadata for `func`.
  1060. *
  1061. * **Note:** If this function becomes hot, i.e. is invoked a lot in a short
  1062. * period of time, it will trip its breaker and transition to an identity
  1063. * function to avoid garbage collection pauses in V8. See
  1064. * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070)
  1065. * for more details.
  1066. *
  1067. * @private
  1068. * @param {Function} func The function to associate metadata with.
  1069. * @param {*} data The metadata.
  1070. * @returns {Function} Returns `func`.
  1071. */
  1072. var setData = _shortOut(_baseSetData);
  1073. var _setData = setData;
  1074. /** Used to match wrap detail comments. */
  1075. var reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/,
  1076. reSplitDetails = /,? & /;
  1077. /**
  1078. * Extracts wrapper details from the `source` body comment.
  1079. *
  1080. * @private
  1081. * @param {string} source The source to inspect.
  1082. * @returns {Array} Returns the wrapper details.
  1083. */
  1084. function getWrapDetails(source) {
  1085. var match = source.match(reWrapDetails);
  1086. return match ? match[1].split(reSplitDetails) : [];
  1087. }
  1088. var _getWrapDetails = getWrapDetails;
  1089. /** Used to match wrap detail comments. */
  1090. var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/;
  1091. /**
  1092. * Inserts wrapper `details` in a comment at the top of the `source` body.
  1093. *
  1094. * @private
  1095. * @param {string} source The source to modify.
  1096. * @returns {Array} details The details to insert.
  1097. * @returns {string} Returns the modified source.
  1098. */
  1099. function insertWrapDetails(source, details) {
  1100. var length = details.length;
  1101. if (!length) {
  1102. return source;
  1103. }
  1104. var lastIndex = length - 1;
  1105. details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex];
  1106. details = details.join(length > 2 ? ', ' : ' ');
  1107. return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n');
  1108. }
  1109. var _insertWrapDetails = insertWrapDetails;
  1110. /**
  1111. * Creates a function that returns `value`.
  1112. *
  1113. * @static
  1114. * @memberOf _
  1115. * @since 2.4.0
  1116. * @category Util
  1117. * @param {*} value The value to return from the new function.
  1118. * @returns {Function} Returns the new constant function.
  1119. * @example
  1120. *
  1121. * var objects = _.times(2, _.constant({ 'a': 1 }));
  1122. *
  1123. * console.log(objects);
  1124. * // => [{ 'a': 1 }, { 'a': 1 }]
  1125. *
  1126. * console.log(objects[0] === objects[1]);
  1127. * // => true
  1128. */
  1129. function constant(value) {
  1130. return function() {
  1131. return value;
  1132. };
  1133. }
  1134. var constant_1 = constant;
  1135. var defineProperty = (function() {
  1136. try {
  1137. var func = _getNative(Object, 'defineProperty');
  1138. func({}, '', {});
  1139. return func;
  1140. } catch (e) {}
  1141. }());
  1142. var _defineProperty = defineProperty;
  1143. /**
  1144. * The base implementation of `setToString` without support for hot loop shorting.
  1145. *
  1146. * @private
  1147. * @param {Function} func The function to modify.
  1148. * @param {Function} string The `toString` result.
  1149. * @returns {Function} Returns `func`.
  1150. */
  1151. var baseSetToString = !_defineProperty ? identity_1 : function(func, string) {
  1152. return _defineProperty(func, 'toString', {
  1153. 'configurable': true,
  1154. 'enumerable': false,
  1155. 'value': constant_1(string),
  1156. 'writable': true
  1157. });
  1158. };
  1159. var _baseSetToString = baseSetToString;
  1160. /**
  1161. * Sets the `toString` method of `func` to return `string`.
  1162. *
  1163. * @private
  1164. * @param {Function} func The function to modify.
  1165. * @param {Function} string The `toString` result.
  1166. * @returns {Function} Returns `func`.
  1167. */
  1168. var setToString = _shortOut(_baseSetToString);
  1169. var _setToString = setToString;
  1170. /**
  1171. * A specialized version of `_.forEach` for arrays without support for
  1172. * iteratee shorthands.
  1173. *
  1174. * @private
  1175. * @param {Array} [array] The array to iterate over.
  1176. * @param {Function} iteratee The function invoked per iteration.
  1177. * @returns {Array} Returns `array`.
  1178. */
  1179. function arrayEach(array, iteratee) {
  1180. var index = -1,
  1181. length = array == null ? 0 : array.length;
  1182. while (++index < length) {
  1183. if (iteratee(array[index], index, array) === false) {
  1184. break;
  1185. }
  1186. }
  1187. return array;
  1188. }
  1189. var _arrayEach = arrayEach;
  1190. /**
  1191. * The base implementation of `_.findIndex` and `_.findLastIndex` without
  1192. * support for iteratee shorthands.
  1193. *
  1194. * @private
  1195. * @param {Array} array The array to inspect.
  1196. * @param {Function} predicate The function invoked per iteration.
  1197. * @param {number} fromIndex The index to search from.
  1198. * @param {boolean} [fromRight] Specify iterating from right to left.
  1199. * @returns {number} Returns the index of the matched value, else `-1`.
  1200. */
  1201. function baseFindIndex(array, predicate, fromIndex, fromRight) {
  1202. var length = array.length,
  1203. index = fromIndex + (fromRight ? 1 : -1);
  1204. while ((fromRight ? index-- : ++index < length)) {
  1205. if (predicate(array[index], index, array)) {
  1206. return index;
  1207. }
  1208. }
  1209. return -1;
  1210. }
  1211. var _baseFindIndex = baseFindIndex;
  1212. /**
  1213. * The base implementation of `_.isNaN` without support for number objects.
  1214. *
  1215. * @private
  1216. * @param {*} value The value to check.
  1217. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
  1218. */
  1219. function baseIsNaN(value) {
  1220. return value !== value;
  1221. }
  1222. var _baseIsNaN = baseIsNaN;
  1223. /**
  1224. * A specialized version of `_.indexOf` which performs strict equality
  1225. * comparisons of values, i.e. `===`.
  1226. *
  1227. * @private
  1228. * @param {Array} array The array to inspect.
  1229. * @param {*} value The value to search for.
  1230. * @param {number} fromIndex The index to search from.
  1231. * @returns {number} Returns the index of the matched value, else `-1`.
  1232. */
  1233. function strictIndexOf(array, value, fromIndex) {
  1234. var index = fromIndex - 1,
  1235. length = array.length;
  1236. while (++index < length) {
  1237. if (array[index] === value) {
  1238. return index;
  1239. }
  1240. }
  1241. return -1;
  1242. }
  1243. var _strictIndexOf = strictIndexOf;
  1244. /**
  1245. * The base implementation of `_.indexOf` without `fromIndex` bounds checks.
  1246. *
  1247. * @private
  1248. * @param {Array} array The array to inspect.
  1249. * @param {*} value The value to search for.
  1250. * @param {number} fromIndex The index to search from.
  1251. * @returns {number} Returns the index of the matched value, else `-1`.
  1252. */
  1253. function baseIndexOf(array, value, fromIndex) {
  1254. return value === value
  1255. ? _strictIndexOf(array, value, fromIndex)
  1256. : _baseFindIndex(array, _baseIsNaN, fromIndex);
  1257. }
  1258. var _baseIndexOf = baseIndexOf;
  1259. /**
  1260. * A specialized version of `_.includes` for arrays without support for
  1261. * specifying an index to search from.
  1262. *
  1263. * @private
  1264. * @param {Array} [array] The array to inspect.
  1265. * @param {*} target The value to search for.
  1266. * @returns {boolean} Returns `true` if `target` is found, else `false`.
  1267. */
  1268. function arrayIncludes(array, value) {
  1269. var length = array == null ? 0 : array.length;
  1270. return !!length && _baseIndexOf(array, value, 0) > -1;
  1271. }
  1272. var _arrayIncludes = arrayIncludes;
  1273. /** Used to compose bitmasks for function metadata. */
  1274. var WRAP_BIND_FLAG$5 = 1,
  1275. WRAP_BIND_KEY_FLAG$4 = 2,
  1276. WRAP_CURRY_FLAG$4 = 8,
  1277. WRAP_CURRY_RIGHT_FLAG$2 = 16,
  1278. WRAP_PARTIAL_FLAG$2 = 32,
  1279. WRAP_PARTIAL_RIGHT_FLAG$2 = 64,
  1280. WRAP_ARY_FLAG$3 = 128,
  1281. WRAP_REARG_FLAG$2 = 256,
  1282. WRAP_FLIP_FLAG$1 = 512;
  1283. /** Used to associate wrap methods with their bit flags. */
  1284. var wrapFlags = [
  1285. ['ary', WRAP_ARY_FLAG$3],
  1286. ['bind', WRAP_BIND_FLAG$5],
  1287. ['bindKey', WRAP_BIND_KEY_FLAG$4],
  1288. ['curry', WRAP_CURRY_FLAG$4],
  1289. ['curryRight', WRAP_CURRY_RIGHT_FLAG$2],
  1290. ['flip', WRAP_FLIP_FLAG$1],
  1291. ['partial', WRAP_PARTIAL_FLAG$2],
  1292. ['partialRight', WRAP_PARTIAL_RIGHT_FLAG$2],
  1293. ['rearg', WRAP_REARG_FLAG$2]
  1294. ];
  1295. /**
  1296. * Updates wrapper `details` based on `bitmask` flags.
  1297. *
  1298. * @private
  1299. * @returns {Array} details The details to modify.
  1300. * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
  1301. * @returns {Array} Returns `details`.
  1302. */
  1303. function updateWrapDetails(details, bitmask) {
  1304. _arrayEach(wrapFlags, function(pair) {
  1305. var value = '_.' + pair[0];
  1306. if ((bitmask & pair[1]) && !_arrayIncludes(details, value)) {
  1307. details.push(value);
  1308. }
  1309. });
  1310. return details.sort();
  1311. }
  1312. var _updateWrapDetails = updateWrapDetails;
  1313. /**
  1314. * Sets the `toString` method of `wrapper` to mimic the source of `reference`
  1315. * with wrapper details in a comment at the top of the source body.
  1316. *
  1317. * @private
  1318. * @param {Function} wrapper The function to modify.
  1319. * @param {Function} reference The reference function.
  1320. * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
  1321. * @returns {Function} Returns `wrapper`.
  1322. */
  1323. function setWrapToString(wrapper, reference, bitmask) {
  1324. var source = (reference + '');
  1325. return _setToString(wrapper, _insertWrapDetails(source, _updateWrapDetails(_getWrapDetails(source), bitmask)));
  1326. }
  1327. var _setWrapToString = setWrapToString;
  1328. /** Used to compose bitmasks for function metadata. */
  1329. var WRAP_BIND_FLAG$4 = 1,
  1330. WRAP_BIND_KEY_FLAG$3 = 2,
  1331. WRAP_CURRY_BOUND_FLAG$1 = 4,
  1332. WRAP_CURRY_FLAG$3 = 8,
  1333. WRAP_PARTIAL_FLAG$1 = 32,
  1334. WRAP_PARTIAL_RIGHT_FLAG$1 = 64;
  1335. /**
  1336. * Creates a function that wraps `func` to continue currying.
  1337. *
  1338. * @private
  1339. * @param {Function} func The function to wrap.
  1340. * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
  1341. * @param {Function} wrapFunc The function to create the `func` wrapper.
  1342. * @param {*} placeholder The placeholder value.
  1343. * @param {*} [thisArg] The `this` binding of `func`.
  1344. * @param {Array} [partials] The arguments to prepend to those provided to
  1345. * the new function.
  1346. * @param {Array} [holders] The `partials` placeholder indexes.
  1347. * @param {Array} [argPos] The argument positions of the new function.
  1348. * @param {number} [ary] The arity cap of `func`.
  1349. * @param {number} [arity] The arity of `func`.
  1350. * @returns {Function} Returns the new wrapped function.
  1351. */
  1352. function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) {
  1353. var isCurry = bitmask & WRAP_CURRY_FLAG$3,
  1354. newHolders = isCurry ? holders : undefined,
  1355. newHoldersRight = isCurry ? undefined : holders,
  1356. newPartials = isCurry ? partials : undefined,
  1357. newPartialsRight = isCurry ? undefined : partials;
  1358. bitmask |= (isCurry ? WRAP_PARTIAL_FLAG$1 : WRAP_PARTIAL_RIGHT_FLAG$1);
  1359. bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG$1 : WRAP_PARTIAL_FLAG$1);
  1360. if (!(bitmask & WRAP_CURRY_BOUND_FLAG$1)) {
  1361. bitmask &= ~(WRAP_BIND_FLAG$4 | WRAP_BIND_KEY_FLAG$3);
  1362. }
  1363. var newData = [
  1364. func, bitmask, thisArg, newPartials, newHolders, newPartialsRight,
  1365. newHoldersRight, argPos, ary, arity
  1366. ];
  1367. var result = wrapFunc.apply(undefined, newData);
  1368. if (_isLaziable(func)) {
  1369. _setData(result, newData);
  1370. }
  1371. result.placeholder = placeholder;
  1372. return _setWrapToString(result, func, bitmask);
  1373. }
  1374. var _createRecurry = createRecurry;
  1375. /**
  1376. * Gets the argument placeholder value for `func`.
  1377. *
  1378. * @private
  1379. * @param {Function} func The function to inspect.
  1380. * @returns {*} Returns the placeholder value.
  1381. */
  1382. function getHolder(func) {
  1383. var object = func;
  1384. return object.placeholder;
  1385. }
  1386. var _getHolder = getHolder;
  1387. /** Used as references for various `Number` constants. */
  1388. var MAX_SAFE_INTEGER$1 = 9007199254740991;
  1389. /** Used to detect unsigned integer values. */
  1390. var reIsUint = /^(?:0|[1-9]\d*)$/;
  1391. /**
  1392. * Checks if `value` is a valid array-like index.
  1393. *
  1394. * @private
  1395. * @param {*} value The value to check.
  1396. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
  1397. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
  1398. */
  1399. function isIndex(value, length) {
  1400. var type = typeof value;
  1401. length = length == null ? MAX_SAFE_INTEGER$1 : length;
  1402. return !!length &&
  1403. (type == 'number' ||
  1404. (type != 'symbol' && reIsUint.test(value))) &&
  1405. (value > -1 && value % 1 == 0 && value < length);
  1406. }
  1407. var _isIndex = isIndex;
  1408. /* Built-in method references for those with the same name as other `lodash` methods. */
  1409. var nativeMin$1 = Math.min;
  1410. /**
  1411. * Reorder `array` according to the specified indexes where the element at
  1412. * the first index is assigned as the first element, the element at
  1413. * the second index is assigned as the second element, and so on.
  1414. *
  1415. * @private
  1416. * @param {Array} array The array to reorder.
  1417. * @param {Array} indexes The arranged array indexes.
  1418. * @returns {Array} Returns `array`.
  1419. */
  1420. function reorder(array, indexes) {
  1421. var arrLength = array.length,
  1422. length = nativeMin$1(indexes.length, arrLength),
  1423. oldArray = _copyArray(array);
  1424. while (length--) {
  1425. var index = indexes[length];
  1426. array[length] = _isIndex(index, arrLength) ? oldArray[index] : undefined;
  1427. }
  1428. return array;
  1429. }
  1430. var _reorder = reorder;
  1431. /** Used as the internal argument placeholder. */
  1432. var PLACEHOLDER$1 = '__lodash_placeholder__';
  1433. /**
  1434. * Replaces all `placeholder` elements in `array` with an internal placeholder
  1435. * and returns an array of their indexes.
  1436. *
  1437. * @private
  1438. * @param {Array} array The array to modify.
  1439. * @param {*} placeholder The placeholder to replace.
  1440. * @returns {Array} Returns the new array of placeholder indexes.
  1441. */
  1442. function replaceHolders(array, placeholder) {
  1443. var index = -1,
  1444. length = array.length,
  1445. resIndex = 0,
  1446. result = [];
  1447. while (++index < length) {
  1448. var value = array[index];
  1449. if (value === placeholder || value === PLACEHOLDER$1) {
  1450. array[index] = PLACEHOLDER$1;
  1451. result[resIndex++] = index;
  1452. }
  1453. }
  1454. return result;
  1455. }
  1456. var _replaceHolders = replaceHolders;
  1457. /** Used to compose bitmasks for function metadata. */
  1458. var WRAP_BIND_FLAG$3 = 1,
  1459. WRAP_BIND_KEY_FLAG$2 = 2,
  1460. WRAP_CURRY_FLAG$2 = 8,
  1461. WRAP_CURRY_RIGHT_FLAG$1 = 16,
  1462. WRAP_ARY_FLAG$2 = 128,
  1463. WRAP_FLIP_FLAG = 512;
  1464. /**
  1465. * Creates a function that wraps `func` to invoke it with optional `this`
  1466. * binding of `thisArg`, partial application, and currying.
  1467. *
  1468. * @private
  1469. * @param {Function|string} func The function or method name to wrap.
  1470. * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
  1471. * @param {*} [thisArg] The `this` binding of `func`.
  1472. * @param {Array} [partials] The arguments to prepend to those provided to
  1473. * the new function.
  1474. * @param {Array} [holders] The `partials` placeholder indexes.
  1475. * @param {Array} [partialsRight] The arguments to append to those provided
  1476. * to the new function.
  1477. * @param {Array} [holdersRight] The `partialsRight` placeholder indexes.
  1478. * @param {Array} [argPos] The argument positions of the new function.
  1479. * @param {number} [ary] The arity cap of `func`.
  1480. * @param {number} [arity] The arity of `func`.
  1481. * @returns {Function} Returns the new wrapped function.
  1482. */
  1483. function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {
  1484. var isAry = bitmask & WRAP_ARY_FLAG$2,
  1485. isBind = bitmask & WRAP_BIND_FLAG$3,
  1486. isBindKey = bitmask & WRAP_BIND_KEY_FLAG$2,
  1487. isCurried = bitmask & (WRAP_CURRY_FLAG$2 | WRAP_CURRY_RIGHT_FLAG$1),
  1488. isFlip = bitmask & WRAP_FLIP_FLAG,
  1489. Ctor = isBindKey ? undefined : _createCtor(func);
  1490. function wrapper() {
  1491. var length = arguments.length,
  1492. args = Array(length),
  1493. index = length;
  1494. while (index--) {
  1495. args[index] = arguments[index];
  1496. }
  1497. if (isCurried) {
  1498. var placeholder = _getHolder(wrapper),
  1499. holdersCount = _countHolders(args, placeholder);
  1500. }
  1501. if (partials) {
  1502. args = _composeArgs(args, partials, holders, isCurried);
  1503. }
  1504. if (partialsRight) {
  1505. args = _composeArgsRight(args, partialsRight, holdersRight, isCurried);
  1506. }
  1507. length -= holdersCount;
  1508. if (isCurried && length < arity) {
  1509. var newHolders = _replaceHolders(args, placeholder);
  1510. return _createRecurry(
  1511. func, bitmask, createHybrid, wrapper.placeholder, thisArg,
  1512. args, newHolders, argPos, ary, arity - length
  1513. );
  1514. }
  1515. var thisBinding = isBind ? thisArg : this,
  1516. fn = isBindKey ? thisBinding[func] : func;
  1517. length = args.length;
  1518. if (argPos) {
  1519. args = _reorder(args, argPos);
  1520. } else if (isFlip && length > 1) {
  1521. args.reverse();
  1522. }
  1523. if (isAry && ary < length) {
  1524. args.length = ary;
  1525. }
  1526. if (this && this !== _root && this instanceof wrapper) {
  1527. fn = Ctor || _createCtor(fn);
  1528. }
  1529. return fn.apply(thisBinding, args);
  1530. }
  1531. return wrapper;
  1532. }
  1533. var _createHybrid = createHybrid;
  1534. /**
  1535. * Creates a function that wraps `func` to enable currying.
  1536. *
  1537. * @private
  1538. * @param {Function} func The function to wrap.
  1539. * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
  1540. * @param {number} arity The arity of `func`.
  1541. * @returns {Function} Returns the new wrapped function.
  1542. */
  1543. function createCurry(func, bitmask, arity) {
  1544. var Ctor = _createCtor(func);
  1545. function wrapper() {
  1546. var length = arguments.length,
  1547. args = Array(length),
  1548. index = length,
  1549. placeholder = _getHolder(wrapper);
  1550. while (index--) {
  1551. args[index] = arguments[index];
  1552. }
  1553. var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder)
  1554. ? []
  1555. : _replaceHolders(args, placeholder);
  1556. length -= holders.length;
  1557. if (length < arity) {
  1558. return _createRecurry(
  1559. func, bitmask, _createHybrid, wrapper.placeholder, undefined,
  1560. args, holders, undefined, undefined, arity - length);
  1561. }
  1562. var fn = (this && this !== _root && this instanceof wrapper) ? Ctor : func;
  1563. return _apply(fn, this, args);
  1564. }
  1565. return wrapper;
  1566. }
  1567. var _createCurry = createCurry;
  1568. /** Used to compose bitmasks for function metadata. */
  1569. var WRAP_BIND_FLAG$2 = 1;
  1570. /**
  1571. * Creates a function that wraps `func` to invoke it with the `this` binding
  1572. * of `thisArg` and `partials` prepended to the arguments it receives.
  1573. *
  1574. * @private
  1575. * @param {Function} func The function to wrap.
  1576. * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
  1577. * @param {*} thisArg The `this` binding of `func`.
  1578. * @param {Array} partials The arguments to prepend to those provided to
  1579. * the new function.
  1580. * @returns {Function} Returns the new wrapped function.
  1581. */
  1582. function createPartial(func, bitmask, thisArg, partials) {
  1583. var isBind = bitmask & WRAP_BIND_FLAG$2,
  1584. Ctor = _createCtor(func);
  1585. function wrapper() {
  1586. var argsIndex = -1,
  1587. argsLength = arguments.length,
  1588. leftIndex = -1,
  1589. leftLength = partials.length,
  1590. args = Array(leftLength + argsLength),
  1591. fn = (this && this !== _root && this instanceof wrapper) ? Ctor : func;
  1592. while (++leftIndex < leftLength) {
  1593. args[leftIndex] = partials[leftIndex];
  1594. }
  1595. while (argsLength--) {
  1596. args[leftIndex++] = arguments[++argsIndex];
  1597. }
  1598. return _apply(fn, isBind ? thisArg : this, args);
  1599. }
  1600. return wrapper;
  1601. }
  1602. var _createPartial = createPartial;
  1603. /** Used as the internal argument placeholder. */
  1604. var PLACEHOLDER = '__lodash_placeholder__';
  1605. /** Used to compose bitmasks for function metadata. */
  1606. var WRAP_BIND_FLAG$1 = 1,
  1607. WRAP_BIND_KEY_FLAG$1 = 2,
  1608. WRAP_CURRY_BOUND_FLAG = 4,
  1609. WRAP_CURRY_FLAG$1 = 8,
  1610. WRAP_ARY_FLAG$1 = 128,
  1611. WRAP_REARG_FLAG$1 = 256;
  1612. /* Built-in method references for those with the same name as other `lodash` methods. */
  1613. var nativeMin = Math.min;
  1614. /**
  1615. * Merges the function metadata of `source` into `data`.
  1616. *
  1617. * Merging metadata reduces the number of wrappers used to invoke a function.
  1618. * This is possible because methods like `_.bind`, `_.curry`, and `_.partial`
  1619. * may be applied regardless of execution order. Methods like `_.ary` and
  1620. * `_.rearg` modify function arguments, making the order in which they are
  1621. * executed important, preventing the merging of metadata. However, we make
  1622. * an exception for a safe combined case where curried functions have `_.ary`
  1623. * and or `_.rearg` applied.
  1624. *
  1625. * @private
  1626. * @param {Array} data The destination metadata.
  1627. * @param {Array} source The source metadata.
  1628. * @returns {Array} Returns `data`.
  1629. */
  1630. function mergeData(data, source) {
  1631. var bitmask = data[1],
  1632. srcBitmask = source[1],
  1633. newBitmask = bitmask | srcBitmask,
  1634. isCommon = newBitmask < (WRAP_BIND_FLAG$1 | WRAP_BIND_KEY_FLAG$1 | WRAP_ARY_FLAG$1);
  1635. var isCombo =
  1636. ((srcBitmask == WRAP_ARY_FLAG$1) && (bitmask == WRAP_CURRY_FLAG$1)) ||
  1637. ((srcBitmask == WRAP_ARY_FLAG$1) && (bitmask == WRAP_REARG_FLAG$1) && (data[7].length <= source[8])) ||
  1638. ((srcBitmask == (WRAP_ARY_FLAG$1 | WRAP_REARG_FLAG$1)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG$1));
  1639. // Exit early if metadata can't be merged.
  1640. if (!(isCommon || isCombo)) {
  1641. return data;
  1642. }
  1643. // Use source `thisArg` if available.
  1644. if (srcBitmask & WRAP_BIND_FLAG$1) {
  1645. data[2] = source[2];
  1646. // Set when currying a bound function.
  1647. newBitmask |= bitmask & WRAP_BIND_FLAG$1 ? 0 : WRAP_CURRY_BOUND_FLAG;
  1648. }
  1649. // Compose partial arguments.
  1650. var value = source[3];
  1651. if (value) {
  1652. var partials = data[3];
  1653. data[3] = partials ? _composeArgs(partials, value, source[4]) : value;
  1654. data[4] = partials ? _replaceHolders(data[3], PLACEHOLDER) : source[4];
  1655. }
  1656. // Compose partial right arguments.
  1657. value = source[5];
  1658. if (value) {
  1659. partials = data[5];
  1660. data[5] = partials ? _composeArgsRight(partials, value, source[6]) : value;
  1661. data[6] = partials ? _replaceHolders(data[5], PLACEHOLDER) : source[6];
  1662. }
  1663. // Use source `argPos` if available.
  1664. value = source[7];
  1665. if (value) {
  1666. data[7] = value;
  1667. }
  1668. // Use source `ary` if it's smaller.
  1669. if (srcBitmask & WRAP_ARY_FLAG$1) {
  1670. data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]);
  1671. }
  1672. // Use source `arity` if one is not provided.
  1673. if (data[9] == null) {
  1674. data[9] = source[9];
  1675. }
  1676. // Use source `func` and merge bitmasks.
  1677. data[0] = source[0];
  1678. data[1] = newBitmask;
  1679. return data;
  1680. }
  1681. var _mergeData = mergeData;
  1682. /** Used to match a single whitespace character. */
  1683. var reWhitespace = /\s/;
  1684. /**
  1685. * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace
  1686. * character of `string`.
  1687. *
  1688. * @private
  1689. * @param {string} string The string to inspect.
  1690. * @returns {number} Returns the index of the last non-whitespace character.
  1691. */
  1692. function trimmedEndIndex(string) {
  1693. var index = string.length;
  1694. while (index-- && reWhitespace.test(string.charAt(index))) {}
  1695. return index;
  1696. }
  1697. var _trimmedEndIndex = trimmedEndIndex;
  1698. /** Used to match leading whitespace. */
  1699. var reTrimStart = /^\s+/;
  1700. /**
  1701. * The base implementation of `_.trim`.
  1702. *
  1703. * @private
  1704. * @param {string} string The string to trim.
  1705. * @returns {string} Returns the trimmed string.
  1706. */
  1707. function baseTrim(string) {
  1708. return string
  1709. ? string.slice(0, _trimmedEndIndex(string) + 1).replace(reTrimStart, '')
  1710. : string;
  1711. }
  1712. var _baseTrim = baseTrim;
  1713. /** `Object#toString` result references. */
  1714. var symbolTag$3 = '[object Symbol]';
  1715. /**
  1716. * Checks if `value` is classified as a `Symbol` primitive or object.
  1717. *
  1718. * @static
  1719. * @memberOf _
  1720. * @since 4.0.0
  1721. * @category Lang
  1722. * @param {*} value The value to check.
  1723. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
  1724. * @example
  1725. *
  1726. * _.isSymbol(Symbol.iterator);
  1727. * // => true
  1728. *
  1729. * _.isSymbol('abc');
  1730. * // => false
  1731. */
  1732. function isSymbol(value) {
  1733. return typeof value == 'symbol' ||
  1734. (isObjectLike_1(value) && _baseGetTag(value) == symbolTag$3);
  1735. }
  1736. var isSymbol_1 = isSymbol;
  1737. /** Used as references for various `Number` constants. */
  1738. var NAN = 0 / 0;
  1739. /** Used to detect bad signed hexadecimal string values. */
  1740. var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
  1741. /** Used to detect binary string values. */
  1742. var reIsBinary = /^0b[01]+$/i;
  1743. /** Used to detect octal string values. */
  1744. var reIsOctal = /^0o[0-7]+$/i;
  1745. /** Built-in method references without a dependency on `root`. */
  1746. var freeParseInt = parseInt;
  1747. /**
  1748. * Converts `value` to a number.
  1749. *
  1750. * @static
  1751. * @memberOf _
  1752. * @since 4.0.0
  1753. * @category Lang
  1754. * @param {*} value The value to process.
  1755. * @returns {number} Returns the number.
  1756. * @example
  1757. *
  1758. * _.toNumber(3.2);
  1759. * // => 3.2
  1760. *
  1761. * _.toNumber(Number.MIN_VALUE);
  1762. * // => 5e-324
  1763. *
  1764. * _.toNumber(Infinity);
  1765. * // => Infinity
  1766. *
  1767. * _.toNumber('3.2');
  1768. * // => 3.2
  1769. */
  1770. function toNumber(value) {
  1771. if (typeof value == 'number') {
  1772. return value;
  1773. }
  1774. if (isSymbol_1(value)) {
  1775. return NAN;
  1776. }
  1777. if (isObject_1(value)) {
  1778. var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
  1779. value = isObject_1(other) ? (other + '') : other;
  1780. }
  1781. if (typeof value != 'string') {
  1782. return value === 0 ? value : +value;
  1783. }
  1784. value = _baseTrim(value);
  1785. var isBinary = reIsBinary.test(value);
  1786. return (isBinary || reIsOctal.test(value))
  1787. ? freeParseInt(value.slice(2), isBinary ? 2 : 8)
  1788. : (reIsBadHex.test(value) ? NAN : +value);
  1789. }
  1790. var toNumber_1 = toNumber;
  1791. /** Used as references for various `Number` constants. */
  1792. var INFINITY$2 = 1 / 0,
  1793. MAX_INTEGER = 1.7976931348623157e+308;
  1794. /**
  1795. * Converts `value` to a finite number.
  1796. *
  1797. * @static
  1798. * @memberOf _
  1799. * @since 4.12.0
  1800. * @category Lang
  1801. * @param {*} value The value to convert.
  1802. * @returns {number} Returns the converted number.
  1803. * @example
  1804. *
  1805. * _.toFinite(3.2);
  1806. * // => 3.2
  1807. *
  1808. * _.toFinite(Number.MIN_VALUE);
  1809. * // => 5e-324
  1810. *
  1811. * _.toFinite(Infinity);
  1812. * // => 1.7976931348623157e+308
  1813. *
  1814. * _.toFinite('3.2');
  1815. * // => 3.2
  1816. */
  1817. function toFinite(value) {
  1818. if (!value) {
  1819. return value === 0 ? value : 0;
  1820. }
  1821. value = toNumber_1(value);
  1822. if (value === INFINITY$2 || value === -INFINITY$2) {
  1823. var sign = (value < 0 ? -1 : 1);
  1824. return sign * MAX_INTEGER;
  1825. }
  1826. return value === value ? value : 0;
  1827. }
  1828. var toFinite_1 = toFinite;
  1829. /**
  1830. * Converts `value` to an integer.
  1831. *
  1832. * **Note:** This method is loosely based on
  1833. * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).
  1834. *
  1835. * @static
  1836. * @memberOf _
  1837. * @since 4.0.0
  1838. * @category Lang
  1839. * @param {*} value The value to convert.
  1840. * @returns {number} Returns the converted integer.
  1841. * @example
  1842. *
  1843. * _.toInteger(3.2);
  1844. * // => 3
  1845. *
  1846. * _.toInteger(Number.MIN_VALUE);
  1847. * // => 0
  1848. *
  1849. * _.toInteger(Infinity);
  1850. * // => 1.7976931348623157e+308
  1851. *
  1852. * _.toInteger('3.2');
  1853. * // => 3
  1854. */
  1855. function toInteger(value) {
  1856. var result = toFinite_1(value),
  1857. remainder = result % 1;
  1858. return result === result ? (remainder ? result - remainder : result) : 0;
  1859. }
  1860. var toInteger_1 = toInteger;
  1861. /** Error message constants. */
  1862. var FUNC_ERROR_TEXT$1 = 'Expected a function';
  1863. /** Used to compose bitmasks for function metadata. */
  1864. var WRAP_BIND_FLAG = 1,
  1865. WRAP_BIND_KEY_FLAG = 2,
  1866. WRAP_CURRY_FLAG = 8,
  1867. WRAP_CURRY_RIGHT_FLAG = 16,
  1868. WRAP_PARTIAL_FLAG = 32,
  1869. WRAP_PARTIAL_RIGHT_FLAG = 64;
  1870. /* Built-in method references for those with the same name as other `lodash` methods. */
  1871. var nativeMax$1 = Math.max;
  1872. /**
  1873. * Creates a function that either curries or invokes `func` with optional
  1874. * `this` binding and partially applied arguments.
  1875. *
  1876. * @private
  1877. * @param {Function|string} func The function or method name to wrap.
  1878. * @param {number} bitmask The bitmask flags.
  1879. * 1 - `_.bind`
  1880. * 2 - `_.bindKey`
  1881. * 4 - `_.curry` or `_.curryRight` of a bound function
  1882. * 8 - `_.curry`
  1883. * 16 - `_.curryRight`
  1884. * 32 - `_.partial`
  1885. * 64 - `_.partialRight`
  1886. * 128 - `_.rearg`
  1887. * 256 - `_.ary`
  1888. * 512 - `_.flip`
  1889. * @param {*} [thisArg] The `this` binding of `func`.
  1890. * @param {Array} [partials] The arguments to be partially applied.
  1891. * @param {Array} [holders] The `partials` placeholder indexes.
  1892. * @param {Array} [argPos] The argument positions of the new function.
  1893. * @param {number} [ary] The arity cap of `func`.
  1894. * @param {number} [arity] The arity of `func`.
  1895. * @returns {Function} Returns the new wrapped function.
  1896. */
  1897. function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {
  1898. var isBindKey = bitmask & WRAP_BIND_KEY_FLAG;
  1899. if (!isBindKey && typeof func != 'function') {
  1900. throw new TypeError(FUNC_ERROR_TEXT$1);
  1901. }
  1902. var length = partials ? partials.length : 0;
  1903. if (!length) {
  1904. bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG);
  1905. partials = holders = undefined;
  1906. }
  1907. ary = ary === undefined ? ary : nativeMax$1(toInteger_1(ary), 0);
  1908. arity = arity === undefined ? arity : toInteger_1(arity);
  1909. length -= holders ? holders.length : 0;
  1910. if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) {
  1911. var partialsRight = partials,
  1912. holdersRight = holders;
  1913. partials = holders = undefined;
  1914. }
  1915. var data = isBindKey ? undefined : _getData(func);
  1916. var newData = [
  1917. func, bitmask, thisArg, partials, holders, partialsRight, holdersRight,
  1918. argPos, ary, arity
  1919. ];
  1920. if (data) {
  1921. _mergeData(newData, data);
  1922. }
  1923. func = newData[0];
  1924. bitmask = newData[1];
  1925. thisArg = newData[2];
  1926. partials = newData[3];
  1927. holders = newData[4];
  1928. arity = newData[9] = newData[9] === undefined
  1929. ? (isBindKey ? 0 : func.length)
  1930. : nativeMax$1(newData[9] - length, 0);
  1931. if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) {
  1932. bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG);
  1933. }
  1934. if (!bitmask || bitmask == WRAP_BIND_FLAG) {
  1935. var result = _createBind(func, bitmask, thisArg);
  1936. } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) {
  1937. result = _createCurry(func, bitmask, arity);
  1938. } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) {
  1939. result = _createPartial(func, bitmask, thisArg, partials);
  1940. } else {
  1941. result = _createHybrid.apply(undefined, newData);
  1942. }
  1943. var setter = data ? _baseSetData : _setData;
  1944. return _setWrapToString(setter(result, newData), func, bitmask);
  1945. }
  1946. var _createWrap = createWrap;
  1947. commonjsRegister("/$$rollup_base$$/node_modules/lodash/curry.js", function (module, exports) {
  1948. var createWrap = _createWrap;
  1949. /** Used to compose bitmasks for function metadata. */
  1950. var WRAP_CURRY_FLAG = 8;
  1951. /**
  1952. * Creates a function that accepts arguments of `func` and either invokes
  1953. * `func` returning its result, if at least `arity` number of arguments have
  1954. * been provided, or returns a function that accepts the remaining `func`
  1955. * arguments, and so on. The arity of `func` may be specified if `func.length`
  1956. * is not sufficient.
  1957. *
  1958. * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds,
  1959. * may be used as a placeholder for provided arguments.
  1960. *
  1961. * **Note:** This method doesn't set the "length" property of curried functions.
  1962. *
  1963. * @static
  1964. * @memberOf _
  1965. * @since 2.0.0
  1966. * @category Function
  1967. * @param {Function} func The function to curry.
  1968. * @param {number} [arity=func.length] The arity of `func`.
  1969. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  1970. * @returns {Function} Returns the new curried function.
  1971. * @example
  1972. *
  1973. * var abc = function(a, b, c) {
  1974. * return [a, b, c];
  1975. * };
  1976. *
  1977. * var curried = _.curry(abc);
  1978. *
  1979. * curried(1)(2)(3);
  1980. * // => [1, 2, 3]
  1981. *
  1982. * curried(1, 2)(3);
  1983. * // => [1, 2, 3]
  1984. *
  1985. * curried(1, 2, 3);
  1986. * // => [1, 2, 3]
  1987. *
  1988. * // Curried with placeholders.
  1989. * curried(1)(_, 3)(2);
  1990. * // => [1, 2, 3]
  1991. */
  1992. function curry(func, arity, guard) {
  1993. arity = guard ? undefined : arity;
  1994. var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity);
  1995. result.placeholder = curry.placeholder;
  1996. return result;
  1997. }
  1998. // Assign default placeholders.
  1999. curry.placeholder = {};
  2000. module.exports = curry;
  2001. });
  2002. commonjsRegister("/$$rollup_base$$/node_modules/lodash/curryRight.js", function (module, exports) {
  2003. var createWrap = _createWrap;
  2004. /** Used to compose bitmasks for function metadata. */
  2005. var WRAP_CURRY_RIGHT_FLAG = 16;
  2006. /**
  2007. * This method is like `_.curry` except that arguments are applied to `func`
  2008. * in the manner of `_.partialRight` instead of `_.partial`.
  2009. *
  2010. * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic
  2011. * builds, may be used as a placeholder for provided arguments.
  2012. *
  2013. * **Note:** This method doesn't set the "length" property of curried functions.
  2014. *
  2015. * @static
  2016. * @memberOf _
  2017. * @since 3.0.0
  2018. * @category Function
  2019. * @param {Function} func The function to curry.
  2020. * @param {number} [arity=func.length] The arity of `func`.
  2021. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  2022. * @returns {Function} Returns the new curried function.
  2023. * @example
  2024. *
  2025. * var abc = function(a, b, c) {
  2026. * return [a, b, c];
  2027. * };
  2028. *
  2029. * var curried = _.curryRight(abc);
  2030. *
  2031. * curried(3)(2)(1);
  2032. * // => [1, 2, 3]
  2033. *
  2034. * curried(2, 3)(1);
  2035. * // => [1, 2, 3]
  2036. *
  2037. * curried(1, 2, 3);
  2038. * // => [1, 2, 3]
  2039. *
  2040. * // Curried with placeholders.
  2041. * curried(3)(1, _)(2);
  2042. * // => [1, 2, 3]
  2043. */
  2044. function curryRight(func, arity, guard) {
  2045. arity = guard ? undefined : arity;
  2046. var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity);
  2047. result.placeholder = curryRight.placeholder;
  2048. return result;
  2049. }
  2050. // Assign default placeholders.
  2051. curryRight.placeholder = {};
  2052. module.exports = curryRight;
  2053. });
  2054. /** Used to map aliases to their real names. */
  2055. var _mapping = createCommonjsModule(function (module, exports) {
  2056. exports.aliasToReal = {
  2057. // Lodash aliases.
  2058. 'each': 'forEach',
  2059. 'eachRight': 'forEachRight',
  2060. 'entries': 'toPairs',
  2061. 'entriesIn': 'toPairsIn',
  2062. 'extend': 'assignIn',
  2063. 'extendAll': 'assignInAll',
  2064. 'extendAllWith': 'assignInAllWith',
  2065. 'extendWith': 'assignInWith',
  2066. 'first': 'head',
  2067. // Methods that are curried variants of others.
  2068. 'conforms': 'conformsTo',
  2069. 'matches': 'isMatch',
  2070. 'property': 'get',
  2071. // Ramda aliases.
  2072. '__': 'placeholder',
  2073. 'F': 'stubFalse',
  2074. 'T': 'stubTrue',
  2075. 'all': 'every',
  2076. 'allPass': 'overEvery',
  2077. 'always': 'constant',
  2078. 'any': 'some',
  2079. 'anyPass': 'overSome',
  2080. 'apply': 'spread',
  2081. 'assoc': 'set',
  2082. 'assocPath': 'set',
  2083. 'complement': 'negate',
  2084. 'compose': 'flowRight',
  2085. 'contains': 'includes',
  2086. 'dissoc': 'unset',
  2087. 'dissocPath': 'unset',
  2088. 'dropLast': 'dropRight',
  2089. 'dropLastWhile': 'dropRightWhile',
  2090. 'equals': 'isEqual',
  2091. 'identical': 'eq',
  2092. 'indexBy': 'keyBy',
  2093. 'init': 'initial',
  2094. 'invertObj': 'invert',
  2095. 'juxt': 'over',
  2096. 'omitAll': 'omit',
  2097. 'nAry': 'ary',
  2098. 'path': 'get',
  2099. 'pathEq': 'matchesProperty',
  2100. 'pathOr': 'getOr',
  2101. 'paths': 'at',
  2102. 'pickAll': 'pick',
  2103. 'pipe': 'flow',
  2104. 'pluck': 'map',
  2105. 'prop': 'get',
  2106. 'propEq': 'matchesProperty',
  2107. 'propOr': 'getOr',
  2108. 'props': 'at',
  2109. 'symmetricDifference': 'xor',
  2110. 'symmetricDifferenceBy': 'xorBy',
  2111. 'symmetricDifferenceWith': 'xorWith',
  2112. 'takeLast': 'takeRight',
  2113. 'takeLastWhile': 'takeRightWhile',
  2114. 'unapply': 'rest',
  2115. 'unnest': 'flatten',
  2116. 'useWith': 'overArgs',
  2117. 'where': 'conformsTo',
  2118. 'whereEq': 'isMatch',
  2119. 'zipObj': 'zipObject'
  2120. };
  2121. /** Used to map ary to method names. */
  2122. exports.aryMethod = {
  2123. '1': [
  2124. 'assignAll', 'assignInAll', 'attempt', 'castArray', 'ceil', 'create',
  2125. 'curry', 'curryRight', 'defaultsAll', 'defaultsDeepAll', 'floor', 'flow',
  2126. 'flowRight', 'fromPairs', 'invert', 'iteratee', 'memoize', 'method', 'mergeAll',
  2127. 'methodOf', 'mixin', 'nthArg', 'over', 'overEvery', 'overSome','rest', 'reverse',
  2128. 'round', 'runInContext', 'spread', 'template', 'trim', 'trimEnd', 'trimStart',
  2129. 'uniqueId', 'words', 'zipAll'
  2130. ],
  2131. '2': [
  2132. 'add', 'after', 'ary', 'assign', 'assignAllWith', 'assignIn', 'assignInAllWith',
  2133. 'at', 'before', 'bind', 'bindAll', 'bindKey', 'chunk', 'cloneDeepWith',
  2134. 'cloneWith', 'concat', 'conformsTo', 'countBy', 'curryN', 'curryRightN',
  2135. 'debounce', 'defaults', 'defaultsDeep', 'defaultTo', 'delay', 'difference',
  2136. 'divide', 'drop', 'dropRight', 'dropRightWhile', 'dropWhile', 'endsWith', 'eq',
  2137. 'every', 'filter', 'find', 'findIndex', 'findKey', 'findLast', 'findLastIndex',
  2138. 'findLastKey', 'flatMap', 'flatMapDeep', 'flattenDepth', 'forEach',
  2139. 'forEachRight', 'forIn', 'forInRight', 'forOwn', 'forOwnRight', 'get',
  2140. 'groupBy', 'gt', 'gte', 'has', 'hasIn', 'includes', 'indexOf', 'intersection',
  2141. 'invertBy', 'invoke', 'invokeMap', 'isEqual', 'isMatch', 'join', 'keyBy',
  2142. 'lastIndexOf', 'lt', 'lte', 'map', 'mapKeys', 'mapValues', 'matchesProperty',
  2143. 'maxBy', 'meanBy', 'merge', 'mergeAllWith', 'minBy', 'multiply', 'nth', 'omit',
  2144. 'omitBy', 'overArgs', 'pad', 'padEnd', 'padStart', 'parseInt', 'partial',
  2145. 'partialRight', 'partition', 'pick', 'pickBy', 'propertyOf', 'pull', 'pullAll',
  2146. 'pullAt', 'random', 'range', 'rangeRight', 'rearg', 'reject', 'remove',
  2147. 'repeat', 'restFrom', 'result', 'sampleSize', 'some', 'sortBy', 'sortedIndex',
  2148. 'sortedIndexOf', 'sortedLastIndex', 'sortedLastIndexOf', 'sortedUniqBy',
  2149. 'split', 'spreadFrom', 'startsWith', 'subtract', 'sumBy', 'take', 'takeRight',
  2150. 'takeRightWhile', 'takeWhile', 'tap', 'throttle', 'thru', 'times', 'trimChars',
  2151. 'trimCharsEnd', 'trimCharsStart', 'truncate', 'union', 'uniqBy', 'uniqWith',
  2152. 'unset', 'unzipWith', 'without', 'wrap', 'xor', 'zip', 'zipObject',
  2153. 'zipObjectDeep'
  2154. ],
  2155. '3': [
  2156. 'assignInWith', 'assignWith', 'clamp', 'differenceBy', 'differenceWith',
  2157. 'findFrom', 'findIndexFrom', 'findLastFrom', 'findLastIndexFrom', 'getOr',
  2158. 'includesFrom', 'indexOfFrom', 'inRange', 'intersectionBy', 'intersectionWith',
  2159. 'invokeArgs', 'invokeArgsMap', 'isEqualWith', 'isMatchWith', 'flatMapDepth',
  2160. 'lastIndexOfFrom', 'mergeWith', 'orderBy', 'padChars', 'padCharsEnd',
  2161. 'padCharsStart', 'pullAllBy', 'pullAllWith', 'rangeStep', 'rangeStepRight',
  2162. 'reduce', 'reduceRight', 'replace', 'set', 'slice', 'sortedIndexBy',
  2163. 'sortedLastIndexBy', 'transform', 'unionBy', 'unionWith', 'update', 'xorBy',
  2164. 'xorWith', 'zipWith'
  2165. ],
  2166. '4': [
  2167. 'fill', 'setWith', 'updateWith'
  2168. ]
  2169. };
  2170. /** Used to map ary to rearg configs. */
  2171. exports.aryRearg = {
  2172. '2': [1, 0],
  2173. '3': [2, 0, 1],
  2174. '4': [3, 2, 0, 1]
  2175. };
  2176. /** Used to map method names to their iteratee ary. */
  2177. exports.iterateeAry = {
  2178. 'dropRightWhile': 1,
  2179. 'dropWhile': 1,
  2180. 'every': 1,
  2181. 'filter': 1,
  2182. 'find': 1,
  2183. 'findFrom': 1,
  2184. 'findIndex': 1,
  2185. 'findIndexFrom': 1,
  2186. 'findKey': 1,
  2187. 'findLast': 1,
  2188. 'findLastFrom': 1,
  2189. 'findLastIndex': 1,
  2190. 'findLastIndexFrom': 1,
  2191. 'findLastKey': 1,
  2192. 'flatMap': 1,
  2193. 'flatMapDeep': 1,
  2194. 'flatMapDepth': 1,
  2195. 'forEach': 1,
  2196. 'forEachRight': 1,
  2197. 'forIn': 1,
  2198. 'forInRight': 1,
  2199. 'forOwn': 1,
  2200. 'forOwnRight': 1,
  2201. 'map': 1,
  2202. 'mapKeys': 1,
  2203. 'mapValues': 1,
  2204. 'partition': 1,
  2205. 'reduce': 2,
  2206. 'reduceRight': 2,
  2207. 'reject': 1,
  2208. 'remove': 1,
  2209. 'some': 1,
  2210. 'takeRightWhile': 1,
  2211. 'takeWhile': 1,
  2212. 'times': 1,
  2213. 'transform': 2
  2214. };
  2215. /** Used to map method names to iteratee rearg configs. */
  2216. exports.iterateeRearg = {
  2217. 'mapKeys': [1],
  2218. 'reduceRight': [1, 0]
  2219. };
  2220. /** Used to map method names to rearg configs. */
  2221. exports.methodRearg = {
  2222. 'assignInAllWith': [1, 0],
  2223. 'assignInWith': [1, 2, 0],
  2224. 'assignAllWith': [1, 0],
  2225. 'assignWith': [1, 2, 0],
  2226. 'differenceBy': [1, 2, 0],
  2227. 'differenceWith': [1, 2, 0],
  2228. 'getOr': [2, 1, 0],
  2229. 'intersectionBy': [1, 2, 0],
  2230. 'intersectionWith': [1, 2, 0],
  2231. 'isEqualWith': [1, 2, 0],
  2232. 'isMatchWith': [2, 1, 0],
  2233. 'mergeAllWith': [1, 0],
  2234. 'mergeWith': [1, 2, 0],
  2235. 'padChars': [2, 1, 0],
  2236. 'padCharsEnd': [2, 1, 0],
  2237. 'padCharsStart': [2, 1, 0],
  2238. 'pullAllBy': [2, 1, 0],
  2239. 'pullAllWith': [2, 1, 0],
  2240. 'rangeStep': [1, 2, 0],
  2241. 'rangeStepRight': [1, 2, 0],
  2242. 'setWith': [3, 1, 2, 0],
  2243. 'sortedIndexBy': [2, 1, 0],
  2244. 'sortedLastIndexBy': [2, 1, 0],
  2245. 'unionBy': [1, 2, 0],
  2246. 'unionWith': [1, 2, 0],
  2247. 'updateWith': [3, 1, 2, 0],
  2248. 'xorBy': [1, 2, 0],
  2249. 'xorWith': [1, 2, 0],
  2250. 'zipWith': [1, 2, 0]
  2251. };
  2252. /** Used to map method names to spread configs. */
  2253. exports.methodSpread = {
  2254. 'assignAll': { 'start': 0 },
  2255. 'assignAllWith': { 'start': 0 },
  2256. 'assignInAll': { 'start': 0 },
  2257. 'assignInAllWith': { 'start': 0 },
  2258. 'defaultsAll': { 'start': 0 },
  2259. 'defaultsDeepAll': { 'start': 0 },
  2260. 'invokeArgs': { 'start': 2 },
  2261. 'invokeArgsMap': { 'start': 2 },
  2262. 'mergeAll': { 'start': 0 },
  2263. 'mergeAllWith': { 'start': 0 },
  2264. 'partial': { 'start': 1 },
  2265. 'partialRight': { 'start': 1 },
  2266. 'without': { 'start': 1 },
  2267. 'zipAll': { 'start': 0 }
  2268. };
  2269. /** Used to identify methods which mutate arrays or objects. */
  2270. exports.mutate = {
  2271. 'array': {
  2272. 'fill': true,
  2273. 'pull': true,
  2274. 'pullAll': true,
  2275. 'pullAllBy': true,
  2276. 'pullAllWith': true,
  2277. 'pullAt': true,
  2278. 'remove': true,
  2279. 'reverse': true
  2280. },
  2281. 'object': {
  2282. 'assign': true,
  2283. 'assignAll': true,
  2284. 'assignAllWith': true,
  2285. 'assignIn': true,
  2286. 'assignInAll': true,
  2287. 'assignInAllWith': true,
  2288. 'assignInWith': true,
  2289. 'assignWith': true,
  2290. 'defaults': true,
  2291. 'defaultsAll': true,
  2292. 'defaultsDeep': true,
  2293. 'defaultsDeepAll': true,
  2294. 'merge': true,
  2295. 'mergeAll': true,
  2296. 'mergeAllWith': true,
  2297. 'mergeWith': true,
  2298. },
  2299. 'set': {
  2300. 'set': true,
  2301. 'setWith': true,
  2302. 'unset': true,
  2303. 'update': true,
  2304. 'updateWith': true
  2305. }
  2306. };
  2307. /** Used to map real names to their aliases. */
  2308. exports.realToAlias = (function() {
  2309. var hasOwnProperty = Object.prototype.hasOwnProperty,
  2310. object = exports.aliasToReal,
  2311. result = {};
  2312. for (var key in object) {
  2313. var value = object[key];
  2314. if (hasOwnProperty.call(result, value)) {
  2315. result[value].push(key);
  2316. } else {
  2317. result[value] = [key];
  2318. }
  2319. }
  2320. return result;
  2321. }());
  2322. /** Used to map method names to other names. */
  2323. exports.remap = {
  2324. 'assignAll': 'assign',
  2325. 'assignAllWith': 'assignWith',
  2326. 'assignInAll': 'assignIn',
  2327. 'assignInAllWith': 'assignInWith',
  2328. 'curryN': 'curry',
  2329. 'curryRightN': 'curryRight',
  2330. 'defaultsAll': 'defaults',
  2331. 'defaultsDeepAll': 'defaultsDeep',
  2332. 'findFrom': 'find',
  2333. 'findIndexFrom': 'findIndex',
  2334. 'findLastFrom': 'findLast',
  2335. 'findLastIndexFrom': 'findLastIndex',
  2336. 'getOr': 'get',
  2337. 'includesFrom': 'includes',
  2338. 'indexOfFrom': 'indexOf',
  2339. 'invokeArgs': 'invoke',
  2340. 'invokeArgsMap': 'invokeMap',
  2341. 'lastIndexOfFrom': 'lastIndexOf',
  2342. 'mergeAll': 'merge',
  2343. 'mergeAllWith': 'mergeWith',
  2344. 'padChars': 'pad',
  2345. 'padCharsEnd': 'padEnd',
  2346. 'padCharsStart': 'padStart',
  2347. 'propertyOf': 'get',
  2348. 'rangeStep': 'range',
  2349. 'rangeStepRight': 'rangeRight',
  2350. 'restFrom': 'rest',
  2351. 'spreadFrom': 'spread',
  2352. 'trimChars': 'trim',
  2353. 'trimCharsEnd': 'trimEnd',
  2354. 'trimCharsStart': 'trimStart',
  2355. 'zipAll': 'zip'
  2356. };
  2357. /** Used to track methods that skip fixing their arity. */
  2358. exports.skipFixed = {
  2359. 'castArray': true,
  2360. 'flow': true,
  2361. 'flowRight': true,
  2362. 'iteratee': true,
  2363. 'mixin': true,
  2364. 'rearg': true,
  2365. 'runInContext': true
  2366. };
  2367. /** Used to track methods that skip rearranging arguments. */
  2368. exports.skipRearg = {
  2369. 'add': true,
  2370. 'assign': true,
  2371. 'assignIn': true,
  2372. 'bind': true,
  2373. 'bindKey': true,
  2374. 'concat': true,
  2375. 'difference': true,
  2376. 'divide': true,
  2377. 'eq': true,
  2378. 'gt': true,
  2379. 'gte': true,
  2380. 'isEqual': true,
  2381. 'lt': true,
  2382. 'lte': true,
  2383. 'matchesProperty': true,
  2384. 'merge': true,
  2385. 'multiply': true,
  2386. 'overArgs': true,
  2387. 'partial': true,
  2388. 'partialRight': true,
  2389. 'propertyOf': true,
  2390. 'random': true,
  2391. 'range': true,
  2392. 'rangeRight': true,
  2393. 'subtract': true,
  2394. 'zip': true,
  2395. 'zipObject': true,
  2396. 'zipObjectDeep': true
  2397. };
  2398. }, "/$$rollup_base$$/node_modules/lodash/fp");
  2399. /**
  2400. * The default argument placeholder value for methods.
  2401. *
  2402. * @type {Object}
  2403. */
  2404. var placeholder = {};
  2405. /** Built-in value reference. */
  2406. var push = Array.prototype.push;
  2407. /**
  2408. * Creates a function, with an arity of `n`, that invokes `func` with the
  2409. * arguments it receives.
  2410. *
  2411. * @private
  2412. * @param {Function} func The function to wrap.
  2413. * @param {number} n The arity of the new function.
  2414. * @returns {Function} Returns the new function.
  2415. */
  2416. function baseArity(func, n) {
  2417. return n == 2
  2418. ? function(a, b) { return func.apply(undefined, arguments); }
  2419. : function(a) { return func.apply(undefined, arguments); };
  2420. }
  2421. /**
  2422. * Creates a function that invokes `func`, with up to `n` arguments, ignoring
  2423. * any additional arguments.
  2424. *
  2425. * @private
  2426. * @param {Function} func The function to cap arguments for.
  2427. * @param {number} n The arity cap.
  2428. * @returns {Function} Returns the new function.
  2429. */
  2430. function baseAry(func, n) {
  2431. return n == 2
  2432. ? function(a, b) { return func(a, b); }
  2433. : function(a) { return func(a); };
  2434. }
  2435. /**
  2436. * Creates a clone of `array`.
  2437. *
  2438. * @private
  2439. * @param {Array} array The array to clone.
  2440. * @returns {Array} Returns the cloned array.
  2441. */
  2442. function cloneArray(array) {
  2443. var length = array ? array.length : 0,
  2444. result = Array(length);
  2445. while (length--) {
  2446. result[length] = array[length];
  2447. }
  2448. return result;
  2449. }
  2450. /**
  2451. * Creates a function that clones a given object using the assignment `func`.
  2452. *
  2453. * @private
  2454. * @param {Function} func The assignment function.
  2455. * @returns {Function} Returns the new cloner function.
  2456. */
  2457. function createCloner(func) {
  2458. return function(object) {
  2459. return func({}, object);
  2460. };
  2461. }
  2462. /**
  2463. * A specialized version of `_.spread` which flattens the spread array into
  2464. * the arguments of the invoked `func`.
  2465. *
  2466. * @private
  2467. * @param {Function} func The function to spread arguments over.
  2468. * @param {number} start The start position of the spread.
  2469. * @returns {Function} Returns the new function.
  2470. */
  2471. function flatSpread(func, start) {
  2472. return function() {
  2473. var length = arguments.length,
  2474. lastIndex = length - 1,
  2475. args = Array(length);
  2476. while (length--) {
  2477. args[length] = arguments[length];
  2478. }
  2479. var array = args[start],
  2480. otherArgs = args.slice(0, start);
  2481. if (array) {
  2482. push.apply(otherArgs, array);
  2483. }
  2484. if (start != lastIndex) {
  2485. push.apply(otherArgs, args.slice(start + 1));
  2486. }
  2487. return func.apply(this, otherArgs);
  2488. };
  2489. }
  2490. /**
  2491. * Creates a function that wraps `func` and uses `cloner` to clone the first
  2492. * argument it receives.
  2493. *
  2494. * @private
  2495. * @param {Function} func The function to wrap.
  2496. * @param {Function} cloner The function to clone arguments.
  2497. * @returns {Function} Returns the new immutable function.
  2498. */
  2499. function wrapImmutable(func, cloner) {
  2500. return function() {
  2501. var length = arguments.length;
  2502. if (!length) {
  2503. return;
  2504. }
  2505. var args = Array(length);
  2506. while (length--) {
  2507. args[length] = arguments[length];
  2508. }
  2509. var result = args[0] = cloner.apply(undefined, args);
  2510. func.apply(undefined, args);
  2511. return result;
  2512. };
  2513. }
  2514. /**
  2515. * The base implementation of `convert` which accepts a `util` object of methods
  2516. * required to perform conversions.
  2517. *
  2518. * @param {Object} util The util object.
  2519. * @param {string} name The name of the function to convert.
  2520. * @param {Function} func The function to convert.
  2521. * @param {Object} [options] The options object.
  2522. * @param {boolean} [options.cap=true] Specify capping iteratee arguments.
  2523. * @param {boolean} [options.curry=true] Specify currying.
  2524. * @param {boolean} [options.fixed=true] Specify fixed arity.
  2525. * @param {boolean} [options.immutable=true] Specify immutable operations.
  2526. * @param {boolean} [options.rearg=true] Specify rearranging arguments.
  2527. * @returns {Function|Object} Returns the converted function or object.
  2528. */
  2529. function baseConvert(util, name, func, options) {
  2530. var isLib = typeof name == 'function',
  2531. isObj = name === Object(name);
  2532. if (isObj) {
  2533. options = func;
  2534. func = name;
  2535. name = undefined;
  2536. }
  2537. if (func == null) {
  2538. throw new TypeError;
  2539. }
  2540. options || (options = {});
  2541. var config = {
  2542. 'cap': 'cap' in options ? options.cap : true,
  2543. 'curry': 'curry' in options ? options.curry : true,
  2544. 'fixed': 'fixed' in options ? options.fixed : true,
  2545. 'immutable': 'immutable' in options ? options.immutable : true,
  2546. 'rearg': 'rearg' in options ? options.rearg : true
  2547. };
  2548. var defaultHolder = isLib ? func : placeholder,
  2549. forceCurry = ('curry' in options) && options.curry,
  2550. forceFixed = ('fixed' in options) && options.fixed,
  2551. forceRearg = ('rearg' in options) && options.rearg,
  2552. pristine = isLib ? func.runInContext() : undefined;
  2553. var helpers = isLib ? func : {
  2554. 'ary': util.ary,
  2555. 'assign': util.assign,
  2556. 'clone': util.clone,
  2557. 'curry': util.curry,
  2558. 'forEach': util.forEach,
  2559. 'isArray': util.isArray,
  2560. 'isError': util.isError,
  2561. 'isFunction': util.isFunction,
  2562. 'isWeakMap': util.isWeakMap,
  2563. 'iteratee': util.iteratee,
  2564. 'keys': util.keys,
  2565. 'rearg': util.rearg,
  2566. 'toInteger': util.toInteger,
  2567. 'toPath': util.toPath
  2568. };
  2569. var ary = helpers.ary,
  2570. assign = helpers.assign,
  2571. clone = helpers.clone,
  2572. curry = helpers.curry,
  2573. each = helpers.forEach,
  2574. isArray = helpers.isArray,
  2575. isError = helpers.isError,
  2576. isFunction = helpers.isFunction,
  2577. isWeakMap = helpers.isWeakMap,
  2578. keys = helpers.keys,
  2579. rearg = helpers.rearg,
  2580. toInteger = helpers.toInteger,
  2581. toPath = helpers.toPath;
  2582. var aryMethodKeys = keys(_mapping.aryMethod);
  2583. var wrappers = {
  2584. 'castArray': function(castArray) {
  2585. return function() {
  2586. var value = arguments[0];
  2587. return isArray(value)
  2588. ? castArray(cloneArray(value))
  2589. : castArray.apply(undefined, arguments);
  2590. };
  2591. },
  2592. 'iteratee': function(iteratee) {
  2593. return function() {
  2594. var func = arguments[0],
  2595. arity = arguments[1],
  2596. result = iteratee(func, arity),
  2597. length = result.length;
  2598. if (config.cap && typeof arity == 'number') {
  2599. arity = arity > 2 ? (arity - 2) : 1;
  2600. return (length && length <= arity) ? result : baseAry(result, arity);
  2601. }
  2602. return result;
  2603. };
  2604. },
  2605. 'mixin': function(mixin) {
  2606. return function(source) {
  2607. var func = this;
  2608. if (!isFunction(func)) {
  2609. return mixin(func, Object(source));
  2610. }
  2611. var pairs = [];
  2612. each(keys(source), function(key) {
  2613. if (isFunction(source[key])) {
  2614. pairs.push([key, func.prototype[key]]);
  2615. }
  2616. });
  2617. mixin(func, Object(source));
  2618. each(pairs, function(pair) {
  2619. var value = pair[1];
  2620. if (isFunction(value)) {
  2621. func.prototype[pair[0]] = value;
  2622. } else {
  2623. delete func.prototype[pair[0]];
  2624. }
  2625. });
  2626. return func;
  2627. };
  2628. },
  2629. 'nthArg': function(nthArg) {
  2630. return function(n) {
  2631. var arity = n < 0 ? 1 : (toInteger(n) + 1);
  2632. return curry(nthArg(n), arity);
  2633. };
  2634. },
  2635. 'rearg': function(rearg) {
  2636. return function(func, indexes) {
  2637. var arity = indexes ? indexes.length : 0;
  2638. return curry(rearg(func, indexes), arity);
  2639. };
  2640. },
  2641. 'runInContext': function(runInContext) {
  2642. return function(context) {
  2643. return baseConvert(util, runInContext(context), options);
  2644. };
  2645. }
  2646. };
  2647. /*--------------------------------------------------------------------------*/
  2648. /**
  2649. * Casts `func` to a function with an arity capped iteratee if needed.
  2650. *
  2651. * @private
  2652. * @param {string} name The name of the function to inspect.
  2653. * @param {Function} func The function to inspect.
  2654. * @returns {Function} Returns the cast function.
  2655. */
  2656. function castCap(name, func) {
  2657. if (config.cap) {
  2658. var indexes = _mapping.iterateeRearg[name];
  2659. if (indexes) {
  2660. return iterateeRearg(func, indexes);
  2661. }
  2662. var n = !isLib && _mapping.iterateeAry[name];
  2663. if (n) {
  2664. return iterateeAry(func, n);
  2665. }
  2666. }
  2667. return func;
  2668. }
  2669. /**
  2670. * Casts `func` to a curried function if needed.
  2671. *
  2672. * @private
  2673. * @param {string} name The name of the function to inspect.
  2674. * @param {Function} func The function to inspect.
  2675. * @param {number} n The arity of `func`.
  2676. * @returns {Function} Returns the cast function.
  2677. */
  2678. function castCurry(name, func, n) {
  2679. return (forceCurry || (config.curry && n > 1))
  2680. ? curry(func, n)
  2681. : func;
  2682. }
  2683. /**
  2684. * Casts `func` to a fixed arity function if needed.
  2685. *
  2686. * @private
  2687. * @param {string} name The name of the function to inspect.
  2688. * @param {Function} func The function to inspect.
  2689. * @param {number} n The arity cap.
  2690. * @returns {Function} Returns the cast function.
  2691. */
  2692. function castFixed(name, func, n) {
  2693. if (config.fixed && (forceFixed || !_mapping.skipFixed[name])) {
  2694. var data = _mapping.methodSpread[name],
  2695. start = data && data.start;
  2696. return start === undefined ? ary(func, n) : flatSpread(func, start);
  2697. }
  2698. return func;
  2699. }
  2700. /**
  2701. * Casts `func` to an rearged function if needed.
  2702. *
  2703. * @private
  2704. * @param {string} name The name of the function to inspect.
  2705. * @param {Function} func The function to inspect.
  2706. * @param {number} n The arity of `func`.
  2707. * @returns {Function} Returns the cast function.
  2708. */
  2709. function castRearg(name, func, n) {
  2710. return (config.rearg && n > 1 && (forceRearg || !_mapping.skipRearg[name]))
  2711. ? rearg(func, _mapping.methodRearg[name] || _mapping.aryRearg[n])
  2712. : func;
  2713. }
  2714. /**
  2715. * Creates a clone of `object` by `path`.
  2716. *
  2717. * @private
  2718. * @param {Object} object The object to clone.
  2719. * @param {Array|string} path The path to clone by.
  2720. * @returns {Object} Returns the cloned object.
  2721. */
  2722. function cloneByPath(object, path) {
  2723. path = toPath(path);
  2724. var index = -1,
  2725. length = path.length,
  2726. lastIndex = length - 1,
  2727. result = clone(Object(object)),
  2728. nested = result;
  2729. while (nested != null && ++index < length) {
  2730. var key = path[index],
  2731. value = nested[key];
  2732. if (value != null &&
  2733. !(isFunction(value) || isError(value) || isWeakMap(value))) {
  2734. nested[key] = clone(index == lastIndex ? value : Object(value));
  2735. }
  2736. nested = nested[key];
  2737. }
  2738. return result;
  2739. }
  2740. /**
  2741. * Converts `lodash` to an immutable auto-curried iteratee-first data-last
  2742. * version with conversion `options` applied.
  2743. *
  2744. * @param {Object} [options] The options object. See `baseConvert` for more details.
  2745. * @returns {Function} Returns the converted `lodash`.
  2746. */
  2747. function convertLib(options) {
  2748. return _.runInContext.convert(options)(undefined);
  2749. }
  2750. /**
  2751. * Create a converter function for `func` of `name`.
  2752. *
  2753. * @param {string} name The name of the function to convert.
  2754. * @param {Function} func The function to convert.
  2755. * @returns {Function} Returns the new converter function.
  2756. */
  2757. function createConverter(name, func) {
  2758. var realName = _mapping.aliasToReal[name] || name,
  2759. methodName = _mapping.remap[realName] || realName,
  2760. oldOptions = options;
  2761. return function(options) {
  2762. var newUtil = isLib ? pristine : helpers,
  2763. newFunc = isLib ? pristine[methodName] : func,
  2764. newOptions = assign(assign({}, oldOptions), options);
  2765. return baseConvert(newUtil, realName, newFunc, newOptions);
  2766. };
  2767. }
  2768. /**
  2769. * Creates a function that wraps `func` to invoke its iteratee, with up to `n`
  2770. * arguments, ignoring any additional arguments.
  2771. *
  2772. * @private
  2773. * @param {Function} func The function to cap iteratee arguments for.
  2774. * @param {number} n The arity cap.
  2775. * @returns {Function} Returns the new function.
  2776. */
  2777. function iterateeAry(func, n) {
  2778. return overArg(func, function(func) {
  2779. return typeof func == 'function' ? baseAry(func, n) : func;
  2780. });
  2781. }
  2782. /**
  2783. * Creates a function that wraps `func` to invoke its iteratee with arguments
  2784. * arranged according to the specified `indexes` where the argument value at
  2785. * the first index is provided as the first argument, the argument value at
  2786. * the second index is provided as the second argument, and so on.
  2787. *
  2788. * @private
  2789. * @param {Function} func The function to rearrange iteratee arguments for.
  2790. * @param {number[]} indexes The arranged argument indexes.
  2791. * @returns {Function} Returns the new function.
  2792. */
  2793. function iterateeRearg(func, indexes) {
  2794. return overArg(func, function(func) {
  2795. var n = indexes.length;
  2796. return baseArity(rearg(baseAry(func, n), indexes), n);
  2797. });
  2798. }
  2799. /**
  2800. * Creates a function that invokes `func` with its first argument transformed.
  2801. *
  2802. * @private
  2803. * @param {Function} func The function to wrap.
  2804. * @param {Function} transform The argument transform.
  2805. * @returns {Function} Returns the new function.
  2806. */
  2807. function overArg(func, transform) {
  2808. return function() {
  2809. var length = arguments.length;
  2810. if (!length) {
  2811. return func();
  2812. }
  2813. var args = Array(length);
  2814. while (length--) {
  2815. args[length] = arguments[length];
  2816. }
  2817. var index = config.rearg ? 0 : (length - 1);
  2818. args[index] = transform(args[index]);
  2819. return func.apply(undefined, args);
  2820. };
  2821. }
  2822. /**
  2823. * Creates a function that wraps `func` and applys the conversions
  2824. * rules by `name`.
  2825. *
  2826. * @private
  2827. * @param {string} name The name of the function to wrap.
  2828. * @param {Function} func The function to wrap.
  2829. * @returns {Function} Returns the converted function.
  2830. */
  2831. function wrap(name, func, placeholder) {
  2832. var result,
  2833. realName = _mapping.aliasToReal[name] || name,
  2834. wrapped = func,
  2835. wrapper = wrappers[realName];
  2836. if (wrapper) {
  2837. wrapped = wrapper(func);
  2838. }
  2839. else if (config.immutable) {
  2840. if (_mapping.mutate.array[realName]) {
  2841. wrapped = wrapImmutable(func, cloneArray);
  2842. }
  2843. else if (_mapping.mutate.object[realName]) {
  2844. wrapped = wrapImmutable(func, createCloner(func));
  2845. }
  2846. else if (_mapping.mutate.set[realName]) {
  2847. wrapped = wrapImmutable(func, cloneByPath);
  2848. }
  2849. }
  2850. each(aryMethodKeys, function(aryKey) {
  2851. each(_mapping.aryMethod[aryKey], function(otherName) {
  2852. if (realName == otherName) {
  2853. var data = _mapping.methodSpread[realName],
  2854. afterRearg = data && data.afterRearg;
  2855. result = afterRearg
  2856. ? castFixed(realName, castRearg(realName, wrapped, aryKey), aryKey)
  2857. : castRearg(realName, castFixed(realName, wrapped, aryKey), aryKey);
  2858. result = castCap(realName, result);
  2859. result = castCurry(realName, result, aryKey);
  2860. return false;
  2861. }
  2862. });
  2863. return !result;
  2864. });
  2865. result || (result = wrapped);
  2866. if (result == func) {
  2867. result = forceCurry ? curry(result, 1) : function() {
  2868. return func.apply(this, arguments);
  2869. };
  2870. }
  2871. result.convert = createConverter(realName, func);
  2872. result.placeholder = func.placeholder = placeholder;
  2873. return result;
  2874. }
  2875. /*--------------------------------------------------------------------------*/
  2876. if (!isObj) {
  2877. return wrap(name, func, defaultHolder);
  2878. }
  2879. var _ = func;
  2880. // Convert methods by ary cap.
  2881. var pairs = [];
  2882. each(aryMethodKeys, function(aryKey) {
  2883. each(_mapping.aryMethod[aryKey], function(key) {
  2884. var func = _[_mapping.remap[key] || key];
  2885. if (func) {
  2886. pairs.push([key, wrap(key, func, _)]);
  2887. }
  2888. });
  2889. });
  2890. // Convert remaining methods.
  2891. each(keys(_), function(key) {
  2892. var func = _[key];
  2893. if (typeof func == 'function') {
  2894. var length = pairs.length;
  2895. while (length--) {
  2896. if (pairs[length][0] == key) {
  2897. return;
  2898. }
  2899. }
  2900. func.convert = createConverter(key, func);
  2901. pairs.push([key, func]);
  2902. }
  2903. });
  2904. // Assign to `_` leaving `_.prototype` unchanged to allow chaining.
  2905. each(pairs, function(pair) {
  2906. _[pair[0]] = pair[1];
  2907. });
  2908. _.convert = convertLib;
  2909. _.placeholder = _;
  2910. // Assign aliases.
  2911. each(keys(_), function(key) {
  2912. each(_mapping.realToAlias[key] || [], function(alias) {
  2913. _[alias] = _[key];
  2914. });
  2915. });
  2916. return _;
  2917. }
  2918. var _baseConvert = baseConvert;
  2919. /** Used to compose bitmasks for function metadata. */
  2920. var WRAP_ARY_FLAG = 128;
  2921. /**
  2922. * Creates a function that invokes `func`, with up to `n` arguments,
  2923. * ignoring any additional arguments.
  2924. *
  2925. * @static
  2926. * @memberOf _
  2927. * @since 3.0.0
  2928. * @category Function
  2929. * @param {Function} func The function to cap arguments for.
  2930. * @param {number} [n=func.length] The arity cap.
  2931. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  2932. * @returns {Function} Returns the new capped function.
  2933. * @example
  2934. *
  2935. * _.map(['6', '8', '10'], _.ary(parseInt, 1));
  2936. * // => [6, 8, 10]
  2937. */
  2938. function ary(func, n, guard) {
  2939. n = guard ? undefined : n;
  2940. n = (func && n == null) ? func.length : n;
  2941. return _createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n);
  2942. }
  2943. var ary_1 = ary;
  2944. /**
  2945. * The base implementation of `assignValue` and `assignMergeValue` without
  2946. * value checks.
  2947. *
  2948. * @private
  2949. * @param {Object} object The object to modify.
  2950. * @param {string} key The key of the property to assign.
  2951. * @param {*} value The value to assign.
  2952. */
  2953. function baseAssignValue(object, key, value) {
  2954. if (key == '__proto__' && _defineProperty) {
  2955. _defineProperty(object, key, {
  2956. 'configurable': true,
  2957. 'enumerable': true,
  2958. 'value': value,
  2959. 'writable': true
  2960. });
  2961. } else {
  2962. object[key] = value;
  2963. }
  2964. }
  2965. var _baseAssignValue = baseAssignValue;
  2966. /**
  2967. * Performs a
  2968. * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
  2969. * comparison between two values to determine if they are equivalent.
  2970. *
  2971. * @static
  2972. * @memberOf _
  2973. * @since 4.0.0
  2974. * @category Lang
  2975. * @param {*} value The value to compare.
  2976. * @param {*} other The other value to compare.
  2977. * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
  2978. * @example
  2979. *
  2980. * var object = { 'a': 1 };
  2981. * var other = { 'a': 1 };
  2982. *
  2983. * _.eq(object, object);
  2984. * // => true
  2985. *
  2986. * _.eq(object, other);
  2987. * // => false
  2988. *
  2989. * _.eq('a', 'a');
  2990. * // => true
  2991. *
  2992. * _.eq('a', Object('a'));
  2993. * // => false
  2994. *
  2995. * _.eq(NaN, NaN);
  2996. * // => true
  2997. */
  2998. function eq(value, other) {
  2999. return value === other || (value !== value && other !== other);
  3000. }
  3001. var eq_1 = eq;
  3002. /** Used for built-in method references. */
  3003. var objectProto$c = Object.prototype;
  3004. /** Used to check objects for own properties. */
  3005. var hasOwnProperty$a = objectProto$c.hasOwnProperty;
  3006. /**
  3007. * Assigns `value` to `key` of `object` if the existing value is not equivalent
  3008. * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
  3009. * for equality comparisons.
  3010. *
  3011. * @private
  3012. * @param {Object} object The object to modify.
  3013. * @param {string} key The key of the property to assign.
  3014. * @param {*} value The value to assign.
  3015. */
  3016. function assignValue(object, key, value) {
  3017. var objValue = object[key];
  3018. if (!(hasOwnProperty$a.call(object, key) && eq_1(objValue, value)) ||
  3019. (value === undefined && !(key in object))) {
  3020. _baseAssignValue(object, key, value);
  3021. }
  3022. }
  3023. var _assignValue = assignValue;
  3024. /**
  3025. * Copies properties of `source` to `object`.
  3026. *
  3027. * @private
  3028. * @param {Object} source The object to copy properties from.
  3029. * @param {Array} props The property identifiers to copy.
  3030. * @param {Object} [object={}] The object to copy properties to.
  3031. * @param {Function} [customizer] The function to customize copied values.
  3032. * @returns {Object} Returns `object`.
  3033. */
  3034. function copyObject(source, props, object, customizer) {
  3035. var isNew = !object;
  3036. object || (object = {});
  3037. var index = -1,
  3038. length = props.length;
  3039. while (++index < length) {
  3040. var key = props[index];
  3041. var newValue = customizer
  3042. ? customizer(object[key], source[key], key, object, source)
  3043. : undefined;
  3044. if (newValue === undefined) {
  3045. newValue = source[key];
  3046. }
  3047. if (isNew) {
  3048. _baseAssignValue(object, key, newValue);
  3049. } else {
  3050. _assignValue(object, key, newValue);
  3051. }
  3052. }
  3053. return object;
  3054. }
  3055. var _copyObject = copyObject;
  3056. /**
  3057. * The base implementation of `_.times` without support for iteratee shorthands
  3058. * or max array length checks.
  3059. *
  3060. * @private
  3061. * @param {number} n The number of times to invoke `iteratee`.
  3062. * @param {Function} iteratee The function invoked per iteration.
  3063. * @returns {Array} Returns the array of results.
  3064. */
  3065. function baseTimes(n, iteratee) {
  3066. var index = -1,
  3067. result = Array(n);
  3068. while (++index < n) {
  3069. result[index] = iteratee(index);
  3070. }
  3071. return result;
  3072. }
  3073. var _baseTimes = baseTimes;
  3074. /** `Object#toString` result references. */
  3075. var argsTag$3 = '[object Arguments]';
  3076. /**
  3077. * The base implementation of `_.isArguments`.
  3078. *
  3079. * @private
  3080. * @param {*} value The value to check.
  3081. * @returns {boolean} Returns `true` if `value` is an `arguments` object,
  3082. */
  3083. function baseIsArguments(value) {
  3084. return isObjectLike_1(value) && _baseGetTag(value) == argsTag$3;
  3085. }
  3086. var _baseIsArguments = baseIsArguments;
  3087. /** Used for built-in method references. */
  3088. var objectProto$b = Object.prototype;
  3089. /** Used to check objects for own properties. */
  3090. var hasOwnProperty$9 = objectProto$b.hasOwnProperty;
  3091. /** Built-in value references. */
  3092. var propertyIsEnumerable$1 = objectProto$b.propertyIsEnumerable;
  3093. /**
  3094. * Checks if `value` is likely an `arguments` object.
  3095. *
  3096. * @static
  3097. * @memberOf _
  3098. * @since 0.1.0
  3099. * @category Lang
  3100. * @param {*} value The value to check.
  3101. * @returns {boolean} Returns `true` if `value` is an `arguments` object,
  3102. * else `false`.
  3103. * @example
  3104. *
  3105. * _.isArguments(function() { return arguments; }());
  3106. * // => true
  3107. *
  3108. * _.isArguments([1, 2, 3]);
  3109. * // => false
  3110. */
  3111. var isArguments = _baseIsArguments(function() { return arguments; }()) ? _baseIsArguments : function(value) {
  3112. return isObjectLike_1(value) && hasOwnProperty$9.call(value, 'callee') &&
  3113. !propertyIsEnumerable$1.call(value, 'callee');
  3114. };
  3115. var isArguments_1 = isArguments;
  3116. /**
  3117. * This method returns `false`.
  3118. *
  3119. * @static
  3120. * @memberOf _
  3121. * @since 4.13.0
  3122. * @category Util
  3123. * @returns {boolean} Returns `false`.
  3124. * @example
  3125. *
  3126. * _.times(2, _.stubFalse);
  3127. * // => [false, false]
  3128. */
  3129. function stubFalse() {
  3130. return false;
  3131. }
  3132. var stubFalse_1 = stubFalse;
  3133. var isBuffer_1 = createCommonjsModule(function (module, exports) {
  3134. /** Detect free variable `exports`. */
  3135. var freeExports = exports && !exports.nodeType && exports;
  3136. /** Detect free variable `module`. */
  3137. var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
  3138. /** Detect the popular CommonJS extension `module.exports`. */
  3139. var moduleExports = freeModule && freeModule.exports === freeExports;
  3140. /** Built-in value references. */
  3141. var Buffer = moduleExports ? _root.Buffer : undefined;
  3142. /* Built-in method references for those with the same name as other `lodash` methods. */
  3143. var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
  3144. /**
  3145. * Checks if `value` is a buffer.
  3146. *
  3147. * @static
  3148. * @memberOf _
  3149. * @since 4.3.0
  3150. * @category Lang
  3151. * @param {*} value The value to check.
  3152. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
  3153. * @example
  3154. *
  3155. * _.isBuffer(new Buffer(2));
  3156. * // => true
  3157. *
  3158. * _.isBuffer(new Uint8Array(2));
  3159. * // => false
  3160. */
  3161. var isBuffer = nativeIsBuffer || stubFalse_1;
  3162. module.exports = isBuffer;
  3163. }, "/$$rollup_base$$/node_modules/lodash");
  3164. /** Used as references for various `Number` constants. */
  3165. var MAX_SAFE_INTEGER = 9007199254740991;
  3166. /**
  3167. * Checks if `value` is a valid array-like length.
  3168. *
  3169. * **Note:** This method is loosely based on
  3170. * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
  3171. *
  3172. * @static
  3173. * @memberOf _
  3174. * @since 4.0.0
  3175. * @category Lang
  3176. * @param {*} value The value to check.
  3177. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
  3178. * @example
  3179. *
  3180. * _.isLength(3);
  3181. * // => true
  3182. *
  3183. * _.isLength(Number.MIN_VALUE);
  3184. * // => false
  3185. *
  3186. * _.isLength(Infinity);
  3187. * // => false
  3188. *
  3189. * _.isLength('3');
  3190. * // => false
  3191. */
  3192. function isLength(value) {
  3193. return typeof value == 'number' &&
  3194. value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
  3195. }
  3196. var isLength_1 = isLength;
  3197. /** `Object#toString` result references. */
  3198. var argsTag$2 = '[object Arguments]',
  3199. arrayTag$2 = '[object Array]',
  3200. boolTag$3 = '[object Boolean]',
  3201. dateTag$3 = '[object Date]',
  3202. errorTag$3 = '[object Error]',
  3203. funcTag$1 = '[object Function]',
  3204. mapTag$5 = '[object Map]',
  3205. numberTag$3 = '[object Number]',
  3206. objectTag$4 = '[object Object]',
  3207. regexpTag$3 = '[object RegExp]',
  3208. setTag$5 = '[object Set]',
  3209. stringTag$3 = '[object String]',
  3210. weakMapTag$3 = '[object WeakMap]';
  3211. var arrayBufferTag$3 = '[object ArrayBuffer]',
  3212. dataViewTag$4 = '[object DataView]',
  3213. float32Tag$2 = '[object Float32Array]',
  3214. float64Tag$2 = '[object Float64Array]',
  3215. int8Tag$2 = '[object Int8Array]',
  3216. int16Tag$2 = '[object Int16Array]',
  3217. int32Tag$2 = '[object Int32Array]',
  3218. uint8Tag$2 = '[object Uint8Array]',
  3219. uint8ClampedTag$2 = '[object Uint8ClampedArray]',
  3220. uint16Tag$2 = '[object Uint16Array]',
  3221. uint32Tag$2 = '[object Uint32Array]';
  3222. /** Used to identify `toStringTag` values of typed arrays. */
  3223. var typedArrayTags = {};
  3224. typedArrayTags[float32Tag$2] = typedArrayTags[float64Tag$2] =
  3225. typedArrayTags[int8Tag$2] = typedArrayTags[int16Tag$2] =
  3226. typedArrayTags[int32Tag$2] = typedArrayTags[uint8Tag$2] =
  3227. typedArrayTags[uint8ClampedTag$2] = typedArrayTags[uint16Tag$2] =
  3228. typedArrayTags[uint32Tag$2] = true;
  3229. typedArrayTags[argsTag$2] = typedArrayTags[arrayTag$2] =
  3230. typedArrayTags[arrayBufferTag$3] = typedArrayTags[boolTag$3] =
  3231. typedArrayTags[dataViewTag$4] = typedArrayTags[dateTag$3] =
  3232. typedArrayTags[errorTag$3] = typedArrayTags[funcTag$1] =
  3233. typedArrayTags[mapTag$5] = typedArrayTags[numberTag$3] =
  3234. typedArrayTags[objectTag$4] = typedArrayTags[regexpTag$3] =
  3235. typedArrayTags[setTag$5] = typedArrayTags[stringTag$3] =
  3236. typedArrayTags[weakMapTag$3] = false;
  3237. /**
  3238. * The base implementation of `_.isTypedArray` without Node.js optimizations.
  3239. *
  3240. * @private
  3241. * @param {*} value The value to check.
  3242. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
  3243. */
  3244. function baseIsTypedArray(value) {
  3245. return isObjectLike_1(value) &&
  3246. isLength_1(value.length) && !!typedArrayTags[_baseGetTag(value)];
  3247. }
  3248. var _baseIsTypedArray = baseIsTypedArray;
  3249. /**
  3250. * The base implementation of `_.unary` without support for storing metadata.
  3251. *
  3252. * @private
  3253. * @param {Function} func The function to cap arguments for.
  3254. * @returns {Function} Returns the new capped function.
  3255. */
  3256. function baseUnary(func) {
  3257. return function(value) {
  3258. return func(value);
  3259. };
  3260. }
  3261. var _baseUnary = baseUnary;
  3262. var _nodeUtil = createCommonjsModule(function (module, exports) {
  3263. /** Detect free variable `exports`. */
  3264. var freeExports = exports && !exports.nodeType && exports;
  3265. /** Detect free variable `module`. */
  3266. var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
  3267. /** Detect the popular CommonJS extension `module.exports`. */
  3268. var moduleExports = freeModule && freeModule.exports === freeExports;
  3269. /** Detect free variable `process` from Node.js. */
  3270. var freeProcess = moduleExports && _freeGlobal.process;
  3271. /** Used to access faster Node.js helpers. */
  3272. var nodeUtil = (function() {
  3273. try {
  3274. // Use `util.types` for Node.js 10+.
  3275. var types = freeModule && freeModule.require && freeModule.require('util').types;
  3276. if (types) {
  3277. return types;
  3278. }
  3279. // Legacy `process.binding('util')` for Node.js < 10.
  3280. return freeProcess && freeProcess.binding && freeProcess.binding('util');
  3281. } catch (e) {}
  3282. }());
  3283. module.exports = nodeUtil;
  3284. }, "/$$rollup_base$$/node_modules/lodash");
  3285. /* Node.js helper references. */
  3286. var nodeIsTypedArray = _nodeUtil && _nodeUtil.isTypedArray;
  3287. /**
  3288. * Checks if `value` is classified as a typed array.
  3289. *
  3290. * @static
  3291. * @memberOf _
  3292. * @since 3.0.0
  3293. * @category Lang
  3294. * @param {*} value The value to check.
  3295. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
  3296. * @example
  3297. *
  3298. * _.isTypedArray(new Uint8Array);
  3299. * // => true
  3300. *
  3301. * _.isTypedArray([]);
  3302. * // => false
  3303. */
  3304. var isTypedArray = nodeIsTypedArray ? _baseUnary(nodeIsTypedArray) : _baseIsTypedArray;
  3305. var isTypedArray_1 = isTypedArray;
  3306. /** Used for built-in method references. */
  3307. var objectProto$a = Object.prototype;
  3308. /** Used to check objects for own properties. */
  3309. var hasOwnProperty$8 = objectProto$a.hasOwnProperty;
  3310. /**
  3311. * Creates an array of the enumerable property names of the array-like `value`.
  3312. *
  3313. * @private
  3314. * @param {*} value The value to query.
  3315. * @param {boolean} inherited Specify returning inherited property names.
  3316. * @returns {Array} Returns the array of property names.
  3317. */
  3318. function arrayLikeKeys(value, inherited) {
  3319. var isArr = isArray_1(value),
  3320. isArg = !isArr && isArguments_1(value),
  3321. isBuff = !isArr && !isArg && isBuffer_1(value),
  3322. isType = !isArr && !isArg && !isBuff && isTypedArray_1(value),
  3323. skipIndexes = isArr || isArg || isBuff || isType,
  3324. result = skipIndexes ? _baseTimes(value.length, String) : [],
  3325. length = result.length;
  3326. for (var key in value) {
  3327. if ((inherited || hasOwnProperty$8.call(value, key)) &&
  3328. !(skipIndexes && (
  3329. // Safari 9 has enumerable `arguments.length` in strict mode.
  3330. key == 'length' ||
  3331. // Node.js 0.10 has enumerable non-index properties on buffers.
  3332. (isBuff && (key == 'offset' || key == 'parent')) ||
  3333. // PhantomJS 2 has enumerable non-index properties on typed arrays.
  3334. (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
  3335. // Skip index properties.
  3336. _isIndex(key, length)
  3337. ))) {
  3338. result.push(key);
  3339. }
  3340. }
  3341. return result;
  3342. }
  3343. var _arrayLikeKeys = arrayLikeKeys;
  3344. /** Used for built-in method references. */
  3345. var objectProto$9 = Object.prototype;
  3346. /**
  3347. * Checks if `value` is likely a prototype object.
  3348. *
  3349. * @private
  3350. * @param {*} value The value to check.
  3351. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
  3352. */
  3353. function isPrototype(value) {
  3354. var Ctor = value && value.constructor,
  3355. proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$9;
  3356. return value === proto;
  3357. }
  3358. var _isPrototype = isPrototype;
  3359. /**
  3360. * Creates a unary function that invokes `func` with its argument transformed.
  3361. *
  3362. * @private
  3363. * @param {Function} func The function to wrap.
  3364. * @param {Function} transform The argument transform.
  3365. * @returns {Function} Returns the new function.
  3366. */
  3367. function overArg(func, transform) {
  3368. return function(arg) {
  3369. return func(transform(arg));
  3370. };
  3371. }
  3372. var _overArg = overArg;
  3373. /* Built-in method references for those with the same name as other `lodash` methods. */
  3374. var nativeKeys = _overArg(Object.keys, Object);
  3375. var _nativeKeys = nativeKeys;
  3376. /** Used for built-in method references. */
  3377. var objectProto$8 = Object.prototype;
  3378. /** Used to check objects for own properties. */
  3379. var hasOwnProperty$7 = objectProto$8.hasOwnProperty;
  3380. /**
  3381. * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
  3382. *
  3383. * @private
  3384. * @param {Object} object The object to query.
  3385. * @returns {Array} Returns the array of property names.
  3386. */
  3387. function baseKeys(object) {
  3388. if (!_isPrototype(object)) {
  3389. return _nativeKeys(object);
  3390. }
  3391. var result = [];
  3392. for (var key in Object(object)) {
  3393. if (hasOwnProperty$7.call(object, key) && key != 'constructor') {
  3394. result.push(key);
  3395. }
  3396. }
  3397. return result;
  3398. }
  3399. var _baseKeys = baseKeys;
  3400. /**
  3401. * Checks if `value` is array-like. A value is considered array-like if it's
  3402. * not a function and has a `value.length` that's an integer greater than or
  3403. * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
  3404. *
  3405. * @static
  3406. * @memberOf _
  3407. * @since 4.0.0
  3408. * @category Lang
  3409. * @param {*} value The value to check.
  3410. * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
  3411. * @example
  3412. *
  3413. * _.isArrayLike([1, 2, 3]);
  3414. * // => true
  3415. *
  3416. * _.isArrayLike(document.body.children);
  3417. * // => true
  3418. *
  3419. * _.isArrayLike('abc');
  3420. * // => true
  3421. *
  3422. * _.isArrayLike(_.noop);
  3423. * // => false
  3424. */
  3425. function isArrayLike(value) {
  3426. return value != null && isLength_1(value.length) && !isFunction_1(value);
  3427. }
  3428. var isArrayLike_1 = isArrayLike;
  3429. /**
  3430. * Creates an array of the own enumerable property names of `object`.
  3431. *
  3432. * **Note:** Non-object values are coerced to objects. See the
  3433. * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
  3434. * for more details.
  3435. *
  3436. * @static
  3437. * @since 0.1.0
  3438. * @memberOf _
  3439. * @category Object
  3440. * @param {Object} object The object to query.
  3441. * @returns {Array} Returns the array of property names.
  3442. * @example
  3443. *
  3444. * function Foo() {
  3445. * this.a = 1;
  3446. * this.b = 2;
  3447. * }
  3448. *
  3449. * Foo.prototype.c = 3;
  3450. *
  3451. * _.keys(new Foo);
  3452. * // => ['a', 'b'] (iteration order is not guaranteed)
  3453. *
  3454. * _.keys('hi');
  3455. * // => ['0', '1']
  3456. */
  3457. function keys(object) {
  3458. return isArrayLike_1(object) ? _arrayLikeKeys(object) : _baseKeys(object);
  3459. }
  3460. var keys_1 = keys;
  3461. /**
  3462. * The base implementation of `_.assign` without support for multiple sources
  3463. * or `customizer` functions.
  3464. *
  3465. * @private
  3466. * @param {Object} object The destination object.
  3467. * @param {Object} source The source object.
  3468. * @returns {Object} Returns `object`.
  3469. */
  3470. function baseAssign(object, source) {
  3471. return object && _copyObject(source, keys_1(source), object);
  3472. }
  3473. var _baseAssign = baseAssign;
  3474. /**
  3475. * Removes all key-value entries from the list cache.
  3476. *
  3477. * @private
  3478. * @name clear
  3479. * @memberOf ListCache
  3480. */
  3481. function listCacheClear() {
  3482. this.__data__ = [];
  3483. this.size = 0;
  3484. }
  3485. var _listCacheClear = listCacheClear;
  3486. /**
  3487. * Gets the index at which the `key` is found in `array` of key-value pairs.
  3488. *
  3489. * @private
  3490. * @param {Array} array The array to inspect.
  3491. * @param {*} key The key to search for.
  3492. * @returns {number} Returns the index of the matched value, else `-1`.
  3493. */
  3494. function assocIndexOf(array, key) {
  3495. var length = array.length;
  3496. while (length--) {
  3497. if (eq_1(array[length][0], key)) {
  3498. return length;
  3499. }
  3500. }
  3501. return -1;
  3502. }
  3503. var _assocIndexOf = assocIndexOf;
  3504. /** Used for built-in method references. */
  3505. var arrayProto = Array.prototype;
  3506. /** Built-in value references. */
  3507. var splice = arrayProto.splice;
  3508. /**
  3509. * Removes `key` and its value from the list cache.
  3510. *
  3511. * @private
  3512. * @name delete
  3513. * @memberOf ListCache
  3514. * @param {string} key The key of the value to remove.
  3515. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  3516. */
  3517. function listCacheDelete(key) {
  3518. var data = this.__data__,
  3519. index = _assocIndexOf(data, key);
  3520. if (index < 0) {
  3521. return false;
  3522. }
  3523. var lastIndex = data.length - 1;
  3524. if (index == lastIndex) {
  3525. data.pop();
  3526. } else {
  3527. splice.call(data, index, 1);
  3528. }
  3529. --this.size;
  3530. return true;
  3531. }
  3532. var _listCacheDelete = listCacheDelete;
  3533. /**
  3534. * Gets the list cache value for `key`.
  3535. *
  3536. * @private
  3537. * @name get
  3538. * @memberOf ListCache
  3539. * @param {string} key The key of the value to get.
  3540. * @returns {*} Returns the entry value.
  3541. */
  3542. function listCacheGet(key) {
  3543. var data = this.__data__,
  3544. index = _assocIndexOf(data, key);
  3545. return index < 0 ? undefined : data[index][1];
  3546. }
  3547. var _listCacheGet = listCacheGet;
  3548. /**
  3549. * Checks if a list cache value for `key` exists.
  3550. *
  3551. * @private
  3552. * @name has
  3553. * @memberOf ListCache
  3554. * @param {string} key The key of the entry to check.
  3555. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  3556. */
  3557. function listCacheHas(key) {
  3558. return _assocIndexOf(this.__data__, key) > -1;
  3559. }
  3560. var _listCacheHas = listCacheHas;
  3561. /**
  3562. * Sets the list cache `key` to `value`.
  3563. *
  3564. * @private
  3565. * @name set
  3566. * @memberOf ListCache
  3567. * @param {string} key The key of the value to set.
  3568. * @param {*} value The value to set.
  3569. * @returns {Object} Returns the list cache instance.
  3570. */
  3571. function listCacheSet(key, value) {
  3572. var data = this.__data__,
  3573. index = _assocIndexOf(data, key);
  3574. if (index < 0) {
  3575. ++this.size;
  3576. data.push([key, value]);
  3577. } else {
  3578. data[index][1] = value;
  3579. }
  3580. return this;
  3581. }
  3582. var _listCacheSet = listCacheSet;
  3583. /**
  3584. * Creates an list cache object.
  3585. *
  3586. * @private
  3587. * @constructor
  3588. * @param {Array} [entries] The key-value pairs to cache.
  3589. */
  3590. function ListCache(entries) {
  3591. var index = -1,
  3592. length = entries == null ? 0 : entries.length;
  3593. this.clear();
  3594. while (++index < length) {
  3595. var entry = entries[index];
  3596. this.set(entry[0], entry[1]);
  3597. }
  3598. }
  3599. // Add methods to `ListCache`.
  3600. ListCache.prototype.clear = _listCacheClear;
  3601. ListCache.prototype['delete'] = _listCacheDelete;
  3602. ListCache.prototype.get = _listCacheGet;
  3603. ListCache.prototype.has = _listCacheHas;
  3604. ListCache.prototype.set = _listCacheSet;
  3605. var _ListCache = ListCache;
  3606. /**
  3607. * Removes all key-value entries from the stack.
  3608. *
  3609. * @private
  3610. * @name clear
  3611. * @memberOf Stack
  3612. */
  3613. function stackClear() {
  3614. this.__data__ = new _ListCache;
  3615. this.size = 0;
  3616. }
  3617. var _stackClear = stackClear;
  3618. /**
  3619. * Removes `key` and its value from the stack.
  3620. *
  3621. * @private
  3622. * @name delete
  3623. * @memberOf Stack
  3624. * @param {string} key The key of the value to remove.
  3625. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  3626. */
  3627. function stackDelete(key) {
  3628. var data = this.__data__,
  3629. result = data['delete'](key);
  3630. this.size = data.size;
  3631. return result;
  3632. }
  3633. var _stackDelete = stackDelete;
  3634. /**
  3635. * Gets the stack value for `key`.
  3636. *
  3637. * @private
  3638. * @name get
  3639. * @memberOf Stack
  3640. * @param {string} key The key of the value to get.
  3641. * @returns {*} Returns the entry value.
  3642. */
  3643. function stackGet(key) {
  3644. return this.__data__.get(key);
  3645. }
  3646. var _stackGet = stackGet;
  3647. /**
  3648. * Checks if a stack value for `key` exists.
  3649. *
  3650. * @private
  3651. * @name has
  3652. * @memberOf Stack
  3653. * @param {string} key The key of the entry to check.
  3654. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  3655. */
  3656. function stackHas(key) {
  3657. return this.__data__.has(key);
  3658. }
  3659. var _stackHas = stackHas;
  3660. /* Built-in method references that are verified to be native. */
  3661. var Map$1 = _getNative(_root, 'Map');
  3662. var _Map = Map$1;
  3663. /* Built-in method references that are verified to be native. */
  3664. var nativeCreate = _getNative(Object, 'create');
  3665. var _nativeCreate = nativeCreate;
  3666. /**
  3667. * Removes all key-value entries from the hash.
  3668. *
  3669. * @private
  3670. * @name clear
  3671. * @memberOf Hash
  3672. */
  3673. function hashClear() {
  3674. this.__data__ = _nativeCreate ? _nativeCreate(null) : {};
  3675. this.size = 0;
  3676. }
  3677. var _hashClear = hashClear;
  3678. /**
  3679. * Removes `key` and its value from the hash.
  3680. *
  3681. * @private
  3682. * @name delete
  3683. * @memberOf Hash
  3684. * @param {Object} hash The hash to modify.
  3685. * @param {string} key The key of the value to remove.
  3686. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  3687. */
  3688. function hashDelete(key) {
  3689. var result = this.has(key) && delete this.__data__[key];
  3690. this.size -= result ? 1 : 0;
  3691. return result;
  3692. }
  3693. var _hashDelete = hashDelete;
  3694. /** Used to stand-in for `undefined` hash values. */
  3695. var HASH_UNDEFINED$2 = '__lodash_hash_undefined__';
  3696. /** Used for built-in method references. */
  3697. var objectProto$7 = Object.prototype;
  3698. /** Used to check objects for own properties. */
  3699. var hasOwnProperty$6 = objectProto$7.hasOwnProperty;
  3700. /**
  3701. * Gets the hash value for `key`.
  3702. *
  3703. * @private
  3704. * @name get
  3705. * @memberOf Hash
  3706. * @param {string} key The key of the value to get.
  3707. * @returns {*} Returns the entry value.
  3708. */
  3709. function hashGet(key) {
  3710. var data = this.__data__;
  3711. if (_nativeCreate) {
  3712. var result = data[key];
  3713. return result === HASH_UNDEFINED$2 ? undefined : result;
  3714. }
  3715. return hasOwnProperty$6.call(data, key) ? data[key] : undefined;
  3716. }
  3717. var _hashGet = hashGet;
  3718. /** Used for built-in method references. */
  3719. var objectProto$6 = Object.prototype;
  3720. /** Used to check objects for own properties. */
  3721. var hasOwnProperty$5 = objectProto$6.hasOwnProperty;
  3722. /**
  3723. * Checks if a hash value for `key` exists.
  3724. *
  3725. * @private
  3726. * @name has
  3727. * @memberOf Hash
  3728. * @param {string} key The key of the entry to check.
  3729. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  3730. */
  3731. function hashHas(key) {
  3732. var data = this.__data__;
  3733. return _nativeCreate ? (data[key] !== undefined) : hasOwnProperty$5.call(data, key);
  3734. }
  3735. var _hashHas = hashHas;
  3736. /** Used to stand-in for `undefined` hash values. */
  3737. var HASH_UNDEFINED$1 = '__lodash_hash_undefined__';
  3738. /**
  3739. * Sets the hash `key` to `value`.
  3740. *
  3741. * @private
  3742. * @name set
  3743. * @memberOf Hash
  3744. * @param {string} key The key of the value to set.
  3745. * @param {*} value The value to set.
  3746. * @returns {Object} Returns the hash instance.
  3747. */
  3748. function hashSet(key, value) {
  3749. var data = this.__data__;
  3750. this.size += this.has(key) ? 0 : 1;
  3751. data[key] = (_nativeCreate && value === undefined) ? HASH_UNDEFINED$1 : value;
  3752. return this;
  3753. }
  3754. var _hashSet = hashSet;
  3755. /**
  3756. * Creates a hash object.
  3757. *
  3758. * @private
  3759. * @constructor
  3760. * @param {Array} [entries] The key-value pairs to cache.
  3761. */
  3762. function Hash(entries) {
  3763. var index = -1,
  3764. length = entries == null ? 0 : entries.length;
  3765. this.clear();
  3766. while (++index < length) {
  3767. var entry = entries[index];
  3768. this.set(entry[0], entry[1]);
  3769. }
  3770. }
  3771. // Add methods to `Hash`.
  3772. Hash.prototype.clear = _hashClear;
  3773. Hash.prototype['delete'] = _hashDelete;
  3774. Hash.prototype.get = _hashGet;
  3775. Hash.prototype.has = _hashHas;
  3776. Hash.prototype.set = _hashSet;
  3777. var _Hash = Hash;
  3778. /**
  3779. * Removes all key-value entries from the map.
  3780. *
  3781. * @private
  3782. * @name clear
  3783. * @memberOf MapCache
  3784. */
  3785. function mapCacheClear() {
  3786. this.size = 0;
  3787. this.__data__ = {
  3788. 'hash': new _Hash,
  3789. 'map': new (_Map || _ListCache),
  3790. 'string': new _Hash
  3791. };
  3792. }
  3793. var _mapCacheClear = mapCacheClear;
  3794. /**
  3795. * Checks if `value` is suitable for use as unique object key.
  3796. *
  3797. * @private
  3798. * @param {*} value The value to check.
  3799. * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
  3800. */
  3801. function isKeyable(value) {
  3802. var type = typeof value;
  3803. return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
  3804. ? (value !== '__proto__')
  3805. : (value === null);
  3806. }
  3807. var _isKeyable = isKeyable;
  3808. /**
  3809. * Gets the data for `map`.
  3810. *
  3811. * @private
  3812. * @param {Object} map The map to query.
  3813. * @param {string} key The reference key.
  3814. * @returns {*} Returns the map data.
  3815. */
  3816. function getMapData(map, key) {
  3817. var data = map.__data__;
  3818. return _isKeyable(key)
  3819. ? data[typeof key == 'string' ? 'string' : 'hash']
  3820. : data.map;
  3821. }
  3822. var _getMapData = getMapData;
  3823. /**
  3824. * Removes `key` and its value from the map.
  3825. *
  3826. * @private
  3827. * @name delete
  3828. * @memberOf MapCache
  3829. * @param {string} key The key of the value to remove.
  3830. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  3831. */
  3832. function mapCacheDelete(key) {
  3833. var result = _getMapData(this, key)['delete'](key);
  3834. this.size -= result ? 1 : 0;
  3835. return result;
  3836. }
  3837. var _mapCacheDelete = mapCacheDelete;
  3838. /**
  3839. * Gets the map value for `key`.
  3840. *
  3841. * @private
  3842. * @name get
  3843. * @memberOf MapCache
  3844. * @param {string} key The key of the value to get.
  3845. * @returns {*} Returns the entry value.
  3846. */
  3847. function mapCacheGet(key) {
  3848. return _getMapData(this, key).get(key);
  3849. }
  3850. var _mapCacheGet = mapCacheGet;
  3851. /**
  3852. * Checks if a map value for `key` exists.
  3853. *
  3854. * @private
  3855. * @name has
  3856. * @memberOf MapCache
  3857. * @param {string} key The key of the entry to check.
  3858. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  3859. */
  3860. function mapCacheHas(key) {
  3861. return _getMapData(this, key).has(key);
  3862. }
  3863. var _mapCacheHas = mapCacheHas;
  3864. /**
  3865. * Sets the map `key` to `value`.
  3866. *
  3867. * @private
  3868. * @name set
  3869. * @memberOf MapCache
  3870. * @param {string} key The key of the value to set.
  3871. * @param {*} value The value to set.
  3872. * @returns {Object} Returns the map cache instance.
  3873. */
  3874. function mapCacheSet(key, value) {
  3875. var data = _getMapData(this, key),
  3876. size = data.size;
  3877. data.set(key, value);
  3878. this.size += data.size == size ? 0 : 1;
  3879. return this;
  3880. }
  3881. var _mapCacheSet = mapCacheSet;
  3882. /**
  3883. * Creates a map cache object to store key-value pairs.
  3884. *
  3885. * @private
  3886. * @constructor
  3887. * @param {Array} [entries] The key-value pairs to cache.
  3888. */
  3889. function MapCache(entries) {
  3890. var index = -1,
  3891. length = entries == null ? 0 : entries.length;
  3892. this.clear();
  3893. while (++index < length) {
  3894. var entry = entries[index];
  3895. this.set(entry[0], entry[1]);
  3896. }
  3897. }
  3898. // Add methods to `MapCache`.
  3899. MapCache.prototype.clear = _mapCacheClear;
  3900. MapCache.prototype['delete'] = _mapCacheDelete;
  3901. MapCache.prototype.get = _mapCacheGet;
  3902. MapCache.prototype.has = _mapCacheHas;
  3903. MapCache.prototype.set = _mapCacheSet;
  3904. var _MapCache = MapCache;
  3905. /** Used as the size to enable large array optimizations. */
  3906. var LARGE_ARRAY_SIZE = 200;
  3907. /**
  3908. * Sets the stack `key` to `value`.
  3909. *
  3910. * @private
  3911. * @name set
  3912. * @memberOf Stack
  3913. * @param {string} key The key of the value to set.
  3914. * @param {*} value The value to set.
  3915. * @returns {Object} Returns the stack cache instance.
  3916. */
  3917. function stackSet(key, value) {
  3918. var data = this.__data__;
  3919. if (data instanceof _ListCache) {
  3920. var pairs = data.__data__;
  3921. if (!_Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
  3922. pairs.push([key, value]);
  3923. this.size = ++data.size;
  3924. return this;
  3925. }
  3926. data = this.__data__ = new _MapCache(pairs);
  3927. }
  3928. data.set(key, value);
  3929. this.size = data.size;
  3930. return this;
  3931. }
  3932. var _stackSet = stackSet;
  3933. /**
  3934. * Creates a stack cache object to store key-value pairs.
  3935. *
  3936. * @private
  3937. * @constructor
  3938. * @param {Array} [entries] The key-value pairs to cache.
  3939. */
  3940. function Stack(entries) {
  3941. var data = this.__data__ = new _ListCache(entries);
  3942. this.size = data.size;
  3943. }
  3944. // Add methods to `Stack`.
  3945. Stack.prototype.clear = _stackClear;
  3946. Stack.prototype['delete'] = _stackDelete;
  3947. Stack.prototype.get = _stackGet;
  3948. Stack.prototype.has = _stackHas;
  3949. Stack.prototype.set = _stackSet;
  3950. var _Stack = Stack;
  3951. /**
  3952. * This function is like
  3953. * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
  3954. * except that it includes inherited enumerable properties.
  3955. *
  3956. * @private
  3957. * @param {Object} object The object to query.
  3958. * @returns {Array} Returns the array of property names.
  3959. */
  3960. function nativeKeysIn(object) {
  3961. var result = [];
  3962. if (object != null) {
  3963. for (var key in Object(object)) {
  3964. result.push(key);
  3965. }
  3966. }
  3967. return result;
  3968. }
  3969. var _nativeKeysIn = nativeKeysIn;
  3970. /** Used for built-in method references. */
  3971. var objectProto$5 = Object.prototype;
  3972. /** Used to check objects for own properties. */
  3973. var hasOwnProperty$4 = objectProto$5.hasOwnProperty;
  3974. /**
  3975. * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
  3976. *
  3977. * @private
  3978. * @param {Object} object The object to query.
  3979. * @returns {Array} Returns the array of property names.
  3980. */
  3981. function baseKeysIn(object) {
  3982. if (!isObject_1(object)) {
  3983. return _nativeKeysIn(object);
  3984. }
  3985. var isProto = _isPrototype(object),
  3986. result = [];
  3987. for (var key in object) {
  3988. if (!(key == 'constructor' && (isProto || !hasOwnProperty$4.call(object, key)))) {
  3989. result.push(key);
  3990. }
  3991. }
  3992. return result;
  3993. }
  3994. var _baseKeysIn = baseKeysIn;
  3995. /**
  3996. * Creates an array of the own and inherited enumerable property names of `object`.
  3997. *
  3998. * **Note:** Non-object values are coerced to objects.
  3999. *
  4000. * @static
  4001. * @memberOf _
  4002. * @since 3.0.0
  4003. * @category Object
  4004. * @param {Object} object The object to query.
  4005. * @returns {Array} Returns the array of property names.
  4006. * @example
  4007. *
  4008. * function Foo() {
  4009. * this.a = 1;
  4010. * this.b = 2;
  4011. * }
  4012. *
  4013. * Foo.prototype.c = 3;
  4014. *
  4015. * _.keysIn(new Foo);
  4016. * // => ['a', 'b', 'c'] (iteration order is not guaranteed)
  4017. */
  4018. function keysIn(object) {
  4019. return isArrayLike_1(object) ? _arrayLikeKeys(object, true) : _baseKeysIn(object);
  4020. }
  4021. var keysIn_1 = keysIn;
  4022. /**
  4023. * The base implementation of `_.assignIn` without support for multiple sources
  4024. * or `customizer` functions.
  4025. *
  4026. * @private
  4027. * @param {Object} object The destination object.
  4028. * @param {Object} source The source object.
  4029. * @returns {Object} Returns `object`.
  4030. */
  4031. function baseAssignIn(object, source) {
  4032. return object && _copyObject(source, keysIn_1(source), object);
  4033. }
  4034. var _baseAssignIn = baseAssignIn;
  4035. var _cloneBuffer = createCommonjsModule(function (module, exports) {
  4036. /** Detect free variable `exports`. */
  4037. var freeExports = exports && !exports.nodeType && exports;
  4038. /** Detect free variable `module`. */
  4039. var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
  4040. /** Detect the popular CommonJS extension `module.exports`. */
  4041. var moduleExports = freeModule && freeModule.exports === freeExports;
  4042. /** Built-in value references. */
  4043. var Buffer = moduleExports ? _root.Buffer : undefined,
  4044. allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined;
  4045. /**
  4046. * Creates a clone of `buffer`.
  4047. *
  4048. * @private
  4049. * @param {Buffer} buffer The buffer to clone.
  4050. * @param {boolean} [isDeep] Specify a deep clone.
  4051. * @returns {Buffer} Returns the cloned buffer.
  4052. */
  4053. function cloneBuffer(buffer, isDeep) {
  4054. if (isDeep) {
  4055. return buffer.slice();
  4056. }
  4057. var length = buffer.length,
  4058. result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
  4059. buffer.copy(result);
  4060. return result;
  4061. }
  4062. module.exports = cloneBuffer;
  4063. }, "/$$rollup_base$$/node_modules/lodash");
  4064. /**
  4065. * A specialized version of `_.filter` for arrays without support for
  4066. * iteratee shorthands.
  4067. *
  4068. * @private
  4069. * @param {Array} [array] The array to iterate over.
  4070. * @param {Function} predicate The function invoked per iteration.
  4071. * @returns {Array} Returns the new filtered array.
  4072. */
  4073. function arrayFilter(array, predicate) {
  4074. var index = -1,
  4075. length = array == null ? 0 : array.length,
  4076. resIndex = 0,
  4077. result = [];
  4078. while (++index < length) {
  4079. var value = array[index];
  4080. if (predicate(value, index, array)) {
  4081. result[resIndex++] = value;
  4082. }
  4083. }
  4084. return result;
  4085. }
  4086. var _arrayFilter = arrayFilter;
  4087. /**
  4088. * This method returns a new empty array.
  4089. *
  4090. * @static
  4091. * @memberOf _
  4092. * @since 4.13.0
  4093. * @category Util
  4094. * @returns {Array} Returns the new empty array.
  4095. * @example
  4096. *
  4097. * var arrays = _.times(2, _.stubArray);
  4098. *
  4099. * console.log(arrays);
  4100. * // => [[], []]
  4101. *
  4102. * console.log(arrays[0] === arrays[1]);
  4103. * // => false
  4104. */
  4105. function stubArray() {
  4106. return [];
  4107. }
  4108. var stubArray_1 = stubArray;
  4109. /** Used for built-in method references. */
  4110. var objectProto$4 = Object.prototype;
  4111. /** Built-in value references. */
  4112. var propertyIsEnumerable = objectProto$4.propertyIsEnumerable;
  4113. /* Built-in method references for those with the same name as other `lodash` methods. */
  4114. var nativeGetSymbols$1 = Object.getOwnPropertySymbols;
  4115. /**
  4116. * Creates an array of the own enumerable symbols of `object`.
  4117. *
  4118. * @private
  4119. * @param {Object} object The object to query.
  4120. * @returns {Array} Returns the array of symbols.
  4121. */
  4122. var getSymbols = !nativeGetSymbols$1 ? stubArray_1 : function(object) {
  4123. if (object == null) {
  4124. return [];
  4125. }
  4126. object = Object(object);
  4127. return _arrayFilter(nativeGetSymbols$1(object), function(symbol) {
  4128. return propertyIsEnumerable.call(object, symbol);
  4129. });
  4130. };
  4131. var _getSymbols = getSymbols;
  4132. /**
  4133. * Copies own symbols of `source` to `object`.
  4134. *
  4135. * @private
  4136. * @param {Object} source The object to copy symbols from.
  4137. * @param {Object} [object={}] The object to copy symbols to.
  4138. * @returns {Object} Returns `object`.
  4139. */
  4140. function copySymbols(source, object) {
  4141. return _copyObject(source, _getSymbols(source), object);
  4142. }
  4143. var _copySymbols = copySymbols;
  4144. /**
  4145. * Appends the elements of `values` to `array`.
  4146. *
  4147. * @private
  4148. * @param {Array} array The array to modify.
  4149. * @param {Array} values The values to append.
  4150. * @returns {Array} Returns `array`.
  4151. */
  4152. function arrayPush(array, values) {
  4153. var index = -1,
  4154. length = values.length,
  4155. offset = array.length;
  4156. while (++index < length) {
  4157. array[offset + index] = values[index];
  4158. }
  4159. return array;
  4160. }
  4161. var _arrayPush = arrayPush;
  4162. /** Built-in value references. */
  4163. var getPrototype = _overArg(Object.getPrototypeOf, Object);
  4164. var _getPrototype = getPrototype;
  4165. /* Built-in method references for those with the same name as other `lodash` methods. */
  4166. var nativeGetSymbols = Object.getOwnPropertySymbols;
  4167. /**
  4168. * Creates an array of the own and inherited enumerable symbols of `object`.
  4169. *
  4170. * @private
  4171. * @param {Object} object The object to query.
  4172. * @returns {Array} Returns the array of symbols.
  4173. */
  4174. var getSymbolsIn = !nativeGetSymbols ? stubArray_1 : function(object) {
  4175. var result = [];
  4176. while (object) {
  4177. _arrayPush(result, _getSymbols(object));
  4178. object = _getPrototype(object);
  4179. }
  4180. return result;
  4181. };
  4182. var _getSymbolsIn = getSymbolsIn;
  4183. /**
  4184. * Copies own and inherited symbols of `source` to `object`.
  4185. *
  4186. * @private
  4187. * @param {Object} source The object to copy symbols from.
  4188. * @param {Object} [object={}] The object to copy symbols to.
  4189. * @returns {Object} Returns `object`.
  4190. */
  4191. function copySymbolsIn(source, object) {
  4192. return _copyObject(source, _getSymbolsIn(source), object);
  4193. }
  4194. var _copySymbolsIn = copySymbolsIn;
  4195. /**
  4196. * The base implementation of `getAllKeys` and `getAllKeysIn` which uses
  4197. * `keysFunc` and `symbolsFunc` to get the enumerable property names and
  4198. * symbols of `object`.
  4199. *
  4200. * @private
  4201. * @param {Object} object The object to query.
  4202. * @param {Function} keysFunc The function to get the keys of `object`.
  4203. * @param {Function} symbolsFunc The function to get the symbols of `object`.
  4204. * @returns {Array} Returns the array of property names and symbols.
  4205. */
  4206. function baseGetAllKeys(object, keysFunc, symbolsFunc) {
  4207. var result = keysFunc(object);
  4208. return isArray_1(object) ? result : _arrayPush(result, symbolsFunc(object));
  4209. }
  4210. var _baseGetAllKeys = baseGetAllKeys;
  4211. /**
  4212. * Creates an array of own enumerable property names and symbols of `object`.
  4213. *
  4214. * @private
  4215. * @param {Object} object The object to query.
  4216. * @returns {Array} Returns the array of property names and symbols.
  4217. */
  4218. function getAllKeys(object) {
  4219. return _baseGetAllKeys(object, keys_1, _getSymbols);
  4220. }
  4221. var _getAllKeys = getAllKeys;
  4222. /**
  4223. * Creates an array of own and inherited enumerable property names and
  4224. * symbols of `object`.
  4225. *
  4226. * @private
  4227. * @param {Object} object The object to query.
  4228. * @returns {Array} Returns the array of property names and symbols.
  4229. */
  4230. function getAllKeysIn(object) {
  4231. return _baseGetAllKeys(object, keysIn_1, _getSymbolsIn);
  4232. }
  4233. var _getAllKeysIn = getAllKeysIn;
  4234. /* Built-in method references that are verified to be native. */
  4235. var DataView = _getNative(_root, 'DataView');
  4236. var _DataView = DataView;
  4237. /* Built-in method references that are verified to be native. */
  4238. var Promise$1 = _getNative(_root, 'Promise');
  4239. var _Promise = Promise$1;
  4240. /* Built-in method references that are verified to be native. */
  4241. var Set$1 = _getNative(_root, 'Set');
  4242. var _Set = Set$1;
  4243. /** `Object#toString` result references. */
  4244. var mapTag$4 = '[object Map]',
  4245. objectTag$3 = '[object Object]',
  4246. promiseTag = '[object Promise]',
  4247. setTag$4 = '[object Set]',
  4248. weakMapTag$2 = '[object WeakMap]';
  4249. var dataViewTag$3 = '[object DataView]';
  4250. /** Used to detect maps, sets, and weakmaps. */
  4251. var dataViewCtorString = _toSource(_DataView),
  4252. mapCtorString = _toSource(_Map),
  4253. promiseCtorString = _toSource(_Promise),
  4254. setCtorString = _toSource(_Set),
  4255. weakMapCtorString = _toSource(_WeakMap);
  4256. /**
  4257. * Gets the `toStringTag` of `value`.
  4258. *
  4259. * @private
  4260. * @param {*} value The value to query.
  4261. * @returns {string} Returns the `toStringTag`.
  4262. */
  4263. var getTag = _baseGetTag;
  4264. // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
  4265. if ((_DataView && getTag(new _DataView(new ArrayBuffer(1))) != dataViewTag$3) ||
  4266. (_Map && getTag(new _Map) != mapTag$4) ||
  4267. (_Promise && getTag(_Promise.resolve()) != promiseTag) ||
  4268. (_Set && getTag(new _Set) != setTag$4) ||
  4269. (_WeakMap && getTag(new _WeakMap) != weakMapTag$2)) {
  4270. getTag = function(value) {
  4271. var result = _baseGetTag(value),
  4272. Ctor = result == objectTag$3 ? value.constructor : undefined,
  4273. ctorString = Ctor ? _toSource(Ctor) : '';
  4274. if (ctorString) {
  4275. switch (ctorString) {
  4276. case dataViewCtorString: return dataViewTag$3;
  4277. case mapCtorString: return mapTag$4;
  4278. case promiseCtorString: return promiseTag;
  4279. case setCtorString: return setTag$4;
  4280. case weakMapCtorString: return weakMapTag$2;
  4281. }
  4282. }
  4283. return result;
  4284. };
  4285. }
  4286. var _getTag = getTag;
  4287. /** Used for built-in method references. */
  4288. var objectProto$3 = Object.prototype;
  4289. /** Used to check objects for own properties. */
  4290. var hasOwnProperty$3 = objectProto$3.hasOwnProperty;
  4291. /**
  4292. * Initializes an array clone.
  4293. *
  4294. * @private
  4295. * @param {Array} array The array to clone.
  4296. * @returns {Array} Returns the initialized clone.
  4297. */
  4298. function initCloneArray(array) {
  4299. var length = array.length,
  4300. result = new array.constructor(length);
  4301. // Add properties assigned by `RegExp#exec`.
  4302. if (length && typeof array[0] == 'string' && hasOwnProperty$3.call(array, 'index')) {
  4303. result.index = array.index;
  4304. result.input = array.input;
  4305. }
  4306. return result;
  4307. }
  4308. var _initCloneArray = initCloneArray;
  4309. /** Built-in value references. */
  4310. var Uint8Array$1 = _root.Uint8Array;
  4311. var _Uint8Array = Uint8Array$1;
  4312. /**
  4313. * Creates a clone of `arrayBuffer`.
  4314. *
  4315. * @private
  4316. * @param {ArrayBuffer} arrayBuffer The array buffer to clone.
  4317. * @returns {ArrayBuffer} Returns the cloned array buffer.
  4318. */
  4319. function cloneArrayBuffer(arrayBuffer) {
  4320. var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
  4321. new _Uint8Array(result).set(new _Uint8Array(arrayBuffer));
  4322. return result;
  4323. }
  4324. var _cloneArrayBuffer = cloneArrayBuffer;
  4325. /**
  4326. * Creates a clone of `dataView`.
  4327. *
  4328. * @private
  4329. * @param {Object} dataView The data view to clone.
  4330. * @param {boolean} [isDeep] Specify a deep clone.
  4331. * @returns {Object} Returns the cloned data view.
  4332. */
  4333. function cloneDataView(dataView, isDeep) {
  4334. var buffer = isDeep ? _cloneArrayBuffer(dataView.buffer) : dataView.buffer;
  4335. return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
  4336. }
  4337. var _cloneDataView = cloneDataView;
  4338. /** Used to match `RegExp` flags from their coerced string values. */
  4339. var reFlags = /\w*$/;
  4340. /**
  4341. * Creates a clone of `regexp`.
  4342. *
  4343. * @private
  4344. * @param {Object} regexp The regexp to clone.
  4345. * @returns {Object} Returns the cloned regexp.
  4346. */
  4347. function cloneRegExp(regexp) {
  4348. var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
  4349. result.lastIndex = regexp.lastIndex;
  4350. return result;
  4351. }
  4352. var _cloneRegExp = cloneRegExp;
  4353. /** Used to convert symbols to primitives and strings. */
  4354. var symbolProto$2 = _Symbol ? _Symbol.prototype : undefined,
  4355. symbolValueOf$1 = symbolProto$2 ? symbolProto$2.valueOf : undefined;
  4356. /**
  4357. * Creates a clone of the `symbol` object.
  4358. *
  4359. * @private
  4360. * @param {Object} symbol The symbol object to clone.
  4361. * @returns {Object} Returns the cloned symbol object.
  4362. */
  4363. function cloneSymbol(symbol) {
  4364. return symbolValueOf$1 ? Object(symbolValueOf$1.call(symbol)) : {};
  4365. }
  4366. var _cloneSymbol = cloneSymbol;
  4367. /**
  4368. * Creates a clone of `typedArray`.
  4369. *
  4370. * @private
  4371. * @param {Object} typedArray The typed array to clone.
  4372. * @param {boolean} [isDeep] Specify a deep clone.
  4373. * @returns {Object} Returns the cloned typed array.
  4374. */
  4375. function cloneTypedArray(typedArray, isDeep) {
  4376. var buffer = isDeep ? _cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
  4377. return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
  4378. }
  4379. var _cloneTypedArray = cloneTypedArray;
  4380. /** `Object#toString` result references. */
  4381. var boolTag$2 = '[object Boolean]',
  4382. dateTag$2 = '[object Date]',
  4383. mapTag$3 = '[object Map]',
  4384. numberTag$2 = '[object Number]',
  4385. regexpTag$2 = '[object RegExp]',
  4386. setTag$3 = '[object Set]',
  4387. stringTag$2 = '[object String]',
  4388. symbolTag$2 = '[object Symbol]';
  4389. var arrayBufferTag$2 = '[object ArrayBuffer]',
  4390. dataViewTag$2 = '[object DataView]',
  4391. float32Tag$1 = '[object Float32Array]',
  4392. float64Tag$1 = '[object Float64Array]',
  4393. int8Tag$1 = '[object Int8Array]',
  4394. int16Tag$1 = '[object Int16Array]',
  4395. int32Tag$1 = '[object Int32Array]',
  4396. uint8Tag$1 = '[object Uint8Array]',
  4397. uint8ClampedTag$1 = '[object Uint8ClampedArray]',
  4398. uint16Tag$1 = '[object Uint16Array]',
  4399. uint32Tag$1 = '[object Uint32Array]';
  4400. /**
  4401. * Initializes an object clone based on its `toStringTag`.
  4402. *
  4403. * **Note:** This function only supports cloning values with tags of
  4404. * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.
  4405. *
  4406. * @private
  4407. * @param {Object} object The object to clone.
  4408. * @param {string} tag The `toStringTag` of the object to clone.
  4409. * @param {boolean} [isDeep] Specify a deep clone.
  4410. * @returns {Object} Returns the initialized clone.
  4411. */
  4412. function initCloneByTag(object, tag, isDeep) {
  4413. var Ctor = object.constructor;
  4414. switch (tag) {
  4415. case arrayBufferTag$2:
  4416. return _cloneArrayBuffer(object);
  4417. case boolTag$2:
  4418. case dateTag$2:
  4419. return new Ctor(+object);
  4420. case dataViewTag$2:
  4421. return _cloneDataView(object, isDeep);
  4422. case float32Tag$1: case float64Tag$1:
  4423. case int8Tag$1: case int16Tag$1: case int32Tag$1:
  4424. case uint8Tag$1: case uint8ClampedTag$1: case uint16Tag$1: case uint32Tag$1:
  4425. return _cloneTypedArray(object, isDeep);
  4426. case mapTag$3:
  4427. return new Ctor;
  4428. case numberTag$2:
  4429. case stringTag$2:
  4430. return new Ctor(object);
  4431. case regexpTag$2:
  4432. return _cloneRegExp(object);
  4433. case setTag$3:
  4434. return new Ctor;
  4435. case symbolTag$2:
  4436. return _cloneSymbol(object);
  4437. }
  4438. }
  4439. var _initCloneByTag = initCloneByTag;
  4440. /**
  4441. * Initializes an object clone.
  4442. *
  4443. * @private
  4444. * @param {Object} object The object to clone.
  4445. * @returns {Object} Returns the initialized clone.
  4446. */
  4447. function initCloneObject(object) {
  4448. return (typeof object.constructor == 'function' && !_isPrototype(object))
  4449. ? _baseCreate(_getPrototype(object))
  4450. : {};
  4451. }
  4452. var _initCloneObject = initCloneObject;
  4453. /** `Object#toString` result references. */
  4454. var mapTag$2 = '[object Map]';
  4455. /**
  4456. * The base implementation of `_.isMap` without Node.js optimizations.
  4457. *
  4458. * @private
  4459. * @param {*} value The value to check.
  4460. * @returns {boolean} Returns `true` if `value` is a map, else `false`.
  4461. */
  4462. function baseIsMap(value) {
  4463. return isObjectLike_1(value) && _getTag(value) == mapTag$2;
  4464. }
  4465. var _baseIsMap = baseIsMap;
  4466. /* Node.js helper references. */
  4467. var nodeIsMap = _nodeUtil && _nodeUtil.isMap;
  4468. /**
  4469. * Checks if `value` is classified as a `Map` object.
  4470. *
  4471. * @static
  4472. * @memberOf _
  4473. * @since 4.3.0
  4474. * @category Lang
  4475. * @param {*} value The value to check.
  4476. * @returns {boolean} Returns `true` if `value` is a map, else `false`.
  4477. * @example
  4478. *
  4479. * _.isMap(new Map);
  4480. * // => true
  4481. *
  4482. * _.isMap(new WeakMap);
  4483. * // => false
  4484. */
  4485. var isMap = nodeIsMap ? _baseUnary(nodeIsMap) : _baseIsMap;
  4486. var isMap_1 = isMap;
  4487. /** `Object#toString` result references. */
  4488. var setTag$2 = '[object Set]';
  4489. /**
  4490. * The base implementation of `_.isSet` without Node.js optimizations.
  4491. *
  4492. * @private
  4493. * @param {*} value The value to check.
  4494. * @returns {boolean} Returns `true` if `value` is a set, else `false`.
  4495. */
  4496. function baseIsSet(value) {
  4497. return isObjectLike_1(value) && _getTag(value) == setTag$2;
  4498. }
  4499. var _baseIsSet = baseIsSet;
  4500. /* Node.js helper references. */
  4501. var nodeIsSet = _nodeUtil && _nodeUtil.isSet;
  4502. /**
  4503. * Checks if `value` is classified as a `Set` object.
  4504. *
  4505. * @static
  4506. * @memberOf _
  4507. * @since 4.3.0
  4508. * @category Lang
  4509. * @param {*} value The value to check.
  4510. * @returns {boolean} Returns `true` if `value` is a set, else `false`.
  4511. * @example
  4512. *
  4513. * _.isSet(new Set);
  4514. * // => true
  4515. *
  4516. * _.isSet(new WeakSet);
  4517. * // => false
  4518. */
  4519. var isSet = nodeIsSet ? _baseUnary(nodeIsSet) : _baseIsSet;
  4520. var isSet_1 = isSet;
  4521. /** Used to compose bitmasks for cloning. */
  4522. var CLONE_DEEP_FLAG$1 = 1,
  4523. CLONE_FLAT_FLAG = 2,
  4524. CLONE_SYMBOLS_FLAG$1 = 4;
  4525. /** `Object#toString` result references. */
  4526. var argsTag$1 = '[object Arguments]',
  4527. arrayTag$1 = '[object Array]',
  4528. boolTag$1 = '[object Boolean]',
  4529. dateTag$1 = '[object Date]',
  4530. errorTag$2 = '[object Error]',
  4531. funcTag = '[object Function]',
  4532. genTag = '[object GeneratorFunction]',
  4533. mapTag$1 = '[object Map]',
  4534. numberTag$1 = '[object Number]',
  4535. objectTag$2 = '[object Object]',
  4536. regexpTag$1 = '[object RegExp]',
  4537. setTag$1 = '[object Set]',
  4538. stringTag$1 = '[object String]',
  4539. symbolTag$1 = '[object Symbol]',
  4540. weakMapTag$1 = '[object WeakMap]';
  4541. var arrayBufferTag$1 = '[object ArrayBuffer]',
  4542. dataViewTag$1 = '[object DataView]',
  4543. float32Tag = '[object Float32Array]',
  4544. float64Tag = '[object Float64Array]',
  4545. int8Tag = '[object Int8Array]',
  4546. int16Tag = '[object Int16Array]',
  4547. int32Tag = '[object Int32Array]',
  4548. uint8Tag = '[object Uint8Array]',
  4549. uint8ClampedTag = '[object Uint8ClampedArray]',
  4550. uint16Tag = '[object Uint16Array]',
  4551. uint32Tag = '[object Uint32Array]';
  4552. /** Used to identify `toStringTag` values supported by `_.clone`. */
  4553. var cloneableTags = {};
  4554. cloneableTags[argsTag$1] = cloneableTags[arrayTag$1] =
  4555. cloneableTags[arrayBufferTag$1] = cloneableTags[dataViewTag$1] =
  4556. cloneableTags[boolTag$1] = cloneableTags[dateTag$1] =
  4557. cloneableTags[float32Tag] = cloneableTags[float64Tag] =
  4558. cloneableTags[int8Tag] = cloneableTags[int16Tag] =
  4559. cloneableTags[int32Tag] = cloneableTags[mapTag$1] =
  4560. cloneableTags[numberTag$1] = cloneableTags[objectTag$2] =
  4561. cloneableTags[regexpTag$1] = cloneableTags[setTag$1] =
  4562. cloneableTags[stringTag$1] = cloneableTags[symbolTag$1] =
  4563. cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =
  4564. cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
  4565. cloneableTags[errorTag$2] = cloneableTags[funcTag] =
  4566. cloneableTags[weakMapTag$1] = false;
  4567. /**
  4568. * The base implementation of `_.clone` and `_.cloneDeep` which tracks
  4569. * traversed objects.
  4570. *
  4571. * @private
  4572. * @param {*} value The value to clone.
  4573. * @param {boolean} bitmask The bitmask flags.
  4574. * 1 - Deep clone
  4575. * 2 - Flatten inherited properties
  4576. * 4 - Clone symbols
  4577. * @param {Function} [customizer] The function to customize cloning.
  4578. * @param {string} [key] The key of `value`.
  4579. * @param {Object} [object] The parent object of `value`.
  4580. * @param {Object} [stack] Tracks traversed objects and their clone counterparts.
  4581. * @returns {*} Returns the cloned value.
  4582. */
  4583. function baseClone(value, bitmask, customizer, key, object, stack) {
  4584. var result,
  4585. isDeep = bitmask & CLONE_DEEP_FLAG$1,
  4586. isFlat = bitmask & CLONE_FLAT_FLAG,
  4587. isFull = bitmask & CLONE_SYMBOLS_FLAG$1;
  4588. if (customizer) {
  4589. result = object ? customizer(value, key, object, stack) : customizer(value);
  4590. }
  4591. if (result !== undefined) {
  4592. return result;
  4593. }
  4594. if (!isObject_1(value)) {
  4595. return value;
  4596. }
  4597. var isArr = isArray_1(value);
  4598. if (isArr) {
  4599. result = _initCloneArray(value);
  4600. if (!isDeep) {
  4601. return _copyArray(value, result);
  4602. }
  4603. } else {
  4604. var tag = _getTag(value),
  4605. isFunc = tag == funcTag || tag == genTag;
  4606. if (isBuffer_1(value)) {
  4607. return _cloneBuffer(value, isDeep);
  4608. }
  4609. if (tag == objectTag$2 || tag == argsTag$1 || (isFunc && !object)) {
  4610. result = (isFlat || isFunc) ? {} : _initCloneObject(value);
  4611. if (!isDeep) {
  4612. return isFlat
  4613. ? _copySymbolsIn(value, _baseAssignIn(result, value))
  4614. : _copySymbols(value, _baseAssign(result, value));
  4615. }
  4616. } else {
  4617. if (!cloneableTags[tag]) {
  4618. return object ? value : {};
  4619. }
  4620. result = _initCloneByTag(value, tag, isDeep);
  4621. }
  4622. }
  4623. // Check for circular references and return its corresponding clone.
  4624. stack || (stack = new _Stack);
  4625. var stacked = stack.get(value);
  4626. if (stacked) {
  4627. return stacked;
  4628. }
  4629. stack.set(value, result);
  4630. if (isSet_1(value)) {
  4631. value.forEach(function(subValue) {
  4632. result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));
  4633. });
  4634. } else if (isMap_1(value)) {
  4635. value.forEach(function(subValue, key) {
  4636. result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));
  4637. });
  4638. }
  4639. var keysFunc = isFull
  4640. ? (isFlat ? _getAllKeysIn : _getAllKeys)
  4641. : (isFlat ? keysIn_1 : keys_1);
  4642. var props = isArr ? undefined : keysFunc(value);
  4643. _arrayEach(props || value, function(subValue, key) {
  4644. if (props) {
  4645. key = subValue;
  4646. subValue = value[key];
  4647. }
  4648. // Recursively populate clone (susceptible to call stack limits).
  4649. _assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));
  4650. });
  4651. return result;
  4652. }
  4653. var _baseClone = baseClone;
  4654. /** Used to compose bitmasks for cloning. */
  4655. var CLONE_SYMBOLS_FLAG = 4;
  4656. /**
  4657. * Creates a shallow clone of `value`.
  4658. *
  4659. * **Note:** This method is loosely based on the
  4660. * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm)
  4661. * and supports cloning arrays, array buffers, booleans, date objects, maps,
  4662. * numbers, `Object` objects, regexes, sets, strings, symbols, and typed
  4663. * arrays. The own enumerable properties of `arguments` objects are cloned
  4664. * as plain objects. An empty object is returned for uncloneable values such
  4665. * as error objects, functions, DOM nodes, and WeakMaps.
  4666. *
  4667. * @static
  4668. * @memberOf _
  4669. * @since 0.1.0
  4670. * @category Lang
  4671. * @param {*} value The value to clone.
  4672. * @returns {*} Returns the cloned value.
  4673. * @see _.cloneDeep
  4674. * @example
  4675. *
  4676. * var objects = [{ 'a': 1 }, { 'b': 2 }];
  4677. *
  4678. * var shallow = _.clone(objects);
  4679. * console.log(shallow[0] === objects[0]);
  4680. * // => true
  4681. */
  4682. function clone(value) {
  4683. return _baseClone(value, CLONE_SYMBOLS_FLAG);
  4684. }
  4685. var clone_1 = clone;
  4686. /** `Object#toString` result references. */
  4687. var objectTag$1 = '[object Object]';
  4688. /** Used for built-in method references. */
  4689. var funcProto = Function.prototype,
  4690. objectProto$2 = Object.prototype;
  4691. /** Used to resolve the decompiled source of functions. */
  4692. var funcToString = funcProto.toString;
  4693. /** Used to check objects for own properties. */
  4694. var hasOwnProperty$2 = objectProto$2.hasOwnProperty;
  4695. /** Used to infer the `Object` constructor. */
  4696. var objectCtorString = funcToString.call(Object);
  4697. /**
  4698. * Checks if `value` is a plain object, that is, an object created by the
  4699. * `Object` constructor or one with a `[[Prototype]]` of `null`.
  4700. *
  4701. * @static
  4702. * @memberOf _
  4703. * @since 0.8.0
  4704. * @category Lang
  4705. * @param {*} value The value to check.
  4706. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
  4707. * @example
  4708. *
  4709. * function Foo() {
  4710. * this.a = 1;
  4711. * }
  4712. *
  4713. * _.isPlainObject(new Foo);
  4714. * // => false
  4715. *
  4716. * _.isPlainObject([1, 2, 3]);
  4717. * // => false
  4718. *
  4719. * _.isPlainObject({ 'x': 0, 'y': 0 });
  4720. * // => true
  4721. *
  4722. * _.isPlainObject(Object.create(null));
  4723. * // => true
  4724. */
  4725. function isPlainObject(value) {
  4726. if (!isObjectLike_1(value) || _baseGetTag(value) != objectTag$1) {
  4727. return false;
  4728. }
  4729. var proto = _getPrototype(value);
  4730. if (proto === null) {
  4731. return true;
  4732. }
  4733. var Ctor = hasOwnProperty$2.call(proto, 'constructor') && proto.constructor;
  4734. return typeof Ctor == 'function' && Ctor instanceof Ctor &&
  4735. funcToString.call(Ctor) == objectCtorString;
  4736. }
  4737. var isPlainObject_1 = isPlainObject;
  4738. /** `Object#toString` result references. */
  4739. var domExcTag = '[object DOMException]',
  4740. errorTag$1 = '[object Error]';
  4741. /**
  4742. * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`,
  4743. * `SyntaxError`, `TypeError`, or `URIError` object.
  4744. *
  4745. * @static
  4746. * @memberOf _
  4747. * @since 3.0.0
  4748. * @category Lang
  4749. * @param {*} value The value to check.
  4750. * @returns {boolean} Returns `true` if `value` is an error object, else `false`.
  4751. * @example
  4752. *
  4753. * _.isError(new Error);
  4754. * // => true
  4755. *
  4756. * _.isError(Error);
  4757. * // => false
  4758. */
  4759. function isError(value) {
  4760. if (!isObjectLike_1(value)) {
  4761. return false;
  4762. }
  4763. var tag = _baseGetTag(value);
  4764. return tag == errorTag$1 || tag == domExcTag ||
  4765. (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject_1(value));
  4766. }
  4767. var isError_1 = isError;
  4768. /** `Object#toString` result references. */
  4769. var weakMapTag = '[object WeakMap]';
  4770. /**
  4771. * Checks if `value` is classified as a `WeakMap` object.
  4772. *
  4773. * @static
  4774. * @memberOf _
  4775. * @since 4.3.0
  4776. * @category Lang
  4777. * @param {*} value The value to check.
  4778. * @returns {boolean} Returns `true` if `value` is a weak map, else `false`.
  4779. * @example
  4780. *
  4781. * _.isWeakMap(new WeakMap);
  4782. * // => true
  4783. *
  4784. * _.isWeakMap(new Map);
  4785. * // => false
  4786. */
  4787. function isWeakMap(value) {
  4788. return isObjectLike_1(value) && _getTag(value) == weakMapTag;
  4789. }
  4790. var isWeakMap_1 = isWeakMap;
  4791. /** Used to stand-in for `undefined` hash values. */
  4792. var HASH_UNDEFINED = '__lodash_hash_undefined__';
  4793. /**
  4794. * Adds `value` to the array cache.
  4795. *
  4796. * @private
  4797. * @name add
  4798. * @memberOf SetCache
  4799. * @alias push
  4800. * @param {*} value The value to cache.
  4801. * @returns {Object} Returns the cache instance.
  4802. */
  4803. function setCacheAdd(value) {
  4804. this.__data__.set(value, HASH_UNDEFINED);
  4805. return this;
  4806. }
  4807. var _setCacheAdd = setCacheAdd;
  4808. /**
  4809. * Checks if `value` is in the array cache.
  4810. *
  4811. * @private
  4812. * @name has
  4813. * @memberOf SetCache
  4814. * @param {*} value The value to search for.
  4815. * @returns {number} Returns `true` if `value` is found, else `false`.
  4816. */
  4817. function setCacheHas(value) {
  4818. return this.__data__.has(value);
  4819. }
  4820. var _setCacheHas = setCacheHas;
  4821. /**
  4822. *
  4823. * Creates an array cache object to store unique values.
  4824. *
  4825. * @private
  4826. * @constructor
  4827. * @param {Array} [values] The values to cache.
  4828. */
  4829. function SetCache(values) {
  4830. var index = -1,
  4831. length = values == null ? 0 : values.length;
  4832. this.__data__ = new _MapCache;
  4833. while (++index < length) {
  4834. this.add(values[index]);
  4835. }
  4836. }
  4837. // Add methods to `SetCache`.
  4838. SetCache.prototype.add = SetCache.prototype.push = _setCacheAdd;
  4839. SetCache.prototype.has = _setCacheHas;
  4840. var _SetCache = SetCache;
  4841. /**
  4842. * A specialized version of `_.some` for arrays without support for iteratee
  4843. * shorthands.
  4844. *
  4845. * @private
  4846. * @param {Array} [array] The array to iterate over.
  4847. * @param {Function} predicate The function invoked per iteration.
  4848. * @returns {boolean} Returns `true` if any element passes the predicate check,
  4849. * else `false`.
  4850. */
  4851. function arraySome(array, predicate) {
  4852. var index = -1,
  4853. length = array == null ? 0 : array.length;
  4854. while (++index < length) {
  4855. if (predicate(array[index], index, array)) {
  4856. return true;
  4857. }
  4858. }
  4859. return false;
  4860. }
  4861. var _arraySome = arraySome;
  4862. /**
  4863. * Checks if a `cache` value for `key` exists.
  4864. *
  4865. * @private
  4866. * @param {Object} cache The cache to query.
  4867. * @param {string} key The key of the entry to check.
  4868. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  4869. */
  4870. function cacheHas(cache, key) {
  4871. return cache.has(key);
  4872. }
  4873. var _cacheHas = cacheHas;
  4874. /** Used to compose bitmasks for value comparisons. */
  4875. var COMPARE_PARTIAL_FLAG$5 = 1,
  4876. COMPARE_UNORDERED_FLAG$3 = 2;
  4877. /**
  4878. * A specialized version of `baseIsEqualDeep` for arrays with support for
  4879. * partial deep comparisons.
  4880. *
  4881. * @private
  4882. * @param {Array} array The array to compare.
  4883. * @param {Array} other The other array to compare.
  4884. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
  4885. * @param {Function} customizer The function to customize comparisons.
  4886. * @param {Function} equalFunc The function to determine equivalents of values.
  4887. * @param {Object} stack Tracks traversed `array` and `other` objects.
  4888. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
  4889. */
  4890. function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
  4891. var isPartial = bitmask & COMPARE_PARTIAL_FLAG$5,
  4892. arrLength = array.length,
  4893. othLength = other.length;
  4894. if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
  4895. return false;
  4896. }
  4897. // Check that cyclic values are equal.
  4898. var arrStacked = stack.get(array);
  4899. var othStacked = stack.get(other);
  4900. if (arrStacked && othStacked) {
  4901. return arrStacked == other && othStacked == array;
  4902. }
  4903. var index = -1,
  4904. result = true,
  4905. seen = (bitmask & COMPARE_UNORDERED_FLAG$3) ? new _SetCache : undefined;
  4906. stack.set(array, other);
  4907. stack.set(other, array);
  4908. // Ignore non-index properties.
  4909. while (++index < arrLength) {
  4910. var arrValue = array[index],
  4911. othValue = other[index];
  4912. if (customizer) {
  4913. var compared = isPartial
  4914. ? customizer(othValue, arrValue, index, other, array, stack)
  4915. : customizer(arrValue, othValue, index, array, other, stack);
  4916. }
  4917. if (compared !== undefined) {
  4918. if (compared) {
  4919. continue;
  4920. }
  4921. result = false;
  4922. break;
  4923. }
  4924. // Recursively compare arrays (susceptible to call stack limits).
  4925. if (seen) {
  4926. if (!_arraySome(other, function(othValue, othIndex) {
  4927. if (!_cacheHas(seen, othIndex) &&
  4928. (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
  4929. return seen.push(othIndex);
  4930. }
  4931. })) {
  4932. result = false;
  4933. break;
  4934. }
  4935. } else if (!(
  4936. arrValue === othValue ||
  4937. equalFunc(arrValue, othValue, bitmask, customizer, stack)
  4938. )) {
  4939. result = false;
  4940. break;
  4941. }
  4942. }
  4943. stack['delete'](array);
  4944. stack['delete'](other);
  4945. return result;
  4946. }
  4947. var _equalArrays = equalArrays;
  4948. /**
  4949. * Converts `map` to its key-value pairs.
  4950. *
  4951. * @private
  4952. * @param {Object} map The map to convert.
  4953. * @returns {Array} Returns the key-value pairs.
  4954. */
  4955. function mapToArray(map) {
  4956. var index = -1,
  4957. result = Array(map.size);
  4958. map.forEach(function(value, key) {
  4959. result[++index] = [key, value];
  4960. });
  4961. return result;
  4962. }
  4963. var _mapToArray = mapToArray;
  4964. /**
  4965. * Converts `set` to an array of its values.
  4966. *
  4967. * @private
  4968. * @param {Object} set The set to convert.
  4969. * @returns {Array} Returns the values.
  4970. */
  4971. function setToArray(set) {
  4972. var index = -1,
  4973. result = Array(set.size);
  4974. set.forEach(function(value) {
  4975. result[++index] = value;
  4976. });
  4977. return result;
  4978. }
  4979. var _setToArray = setToArray;
  4980. /** Used to compose bitmasks for value comparisons. */
  4981. var COMPARE_PARTIAL_FLAG$4 = 1,
  4982. COMPARE_UNORDERED_FLAG$2 = 2;
  4983. /** `Object#toString` result references. */
  4984. var boolTag = '[object Boolean]',
  4985. dateTag = '[object Date]',
  4986. errorTag = '[object Error]',
  4987. mapTag = '[object Map]',
  4988. numberTag = '[object Number]',
  4989. regexpTag = '[object RegExp]',
  4990. setTag = '[object Set]',
  4991. stringTag = '[object String]',
  4992. symbolTag = '[object Symbol]';
  4993. var arrayBufferTag = '[object ArrayBuffer]',
  4994. dataViewTag = '[object DataView]';
  4995. /** Used to convert symbols to primitives and strings. */
  4996. var symbolProto$1 = _Symbol ? _Symbol.prototype : undefined,
  4997. symbolValueOf = symbolProto$1 ? symbolProto$1.valueOf : undefined;
  4998. /**
  4999. * A specialized version of `baseIsEqualDeep` for comparing objects of
  5000. * the same `toStringTag`.
  5001. *
  5002. * **Note:** This function only supports comparing values with tags of
  5003. * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
  5004. *
  5005. * @private
  5006. * @param {Object} object The object to compare.
  5007. * @param {Object} other The other object to compare.
  5008. * @param {string} tag The `toStringTag` of the objects to compare.
  5009. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
  5010. * @param {Function} customizer The function to customize comparisons.
  5011. * @param {Function} equalFunc The function to determine equivalents of values.
  5012. * @param {Object} stack Tracks traversed `object` and `other` objects.
  5013. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
  5014. */
  5015. function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
  5016. switch (tag) {
  5017. case dataViewTag:
  5018. if ((object.byteLength != other.byteLength) ||
  5019. (object.byteOffset != other.byteOffset)) {
  5020. return false;
  5021. }
  5022. object = object.buffer;
  5023. other = other.buffer;
  5024. case arrayBufferTag:
  5025. if ((object.byteLength != other.byteLength) ||
  5026. !equalFunc(new _Uint8Array(object), new _Uint8Array(other))) {
  5027. return false;
  5028. }
  5029. return true;
  5030. case boolTag:
  5031. case dateTag:
  5032. case numberTag:
  5033. // Coerce booleans to `1` or `0` and dates to milliseconds.
  5034. // Invalid dates are coerced to `NaN`.
  5035. return eq_1(+object, +other);
  5036. case errorTag:
  5037. return object.name == other.name && object.message == other.message;
  5038. case regexpTag:
  5039. case stringTag:
  5040. // Coerce regexes to strings and treat strings, primitives and objects,
  5041. // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
  5042. // for more details.
  5043. return object == (other + '');
  5044. case mapTag:
  5045. var convert = _mapToArray;
  5046. case setTag:
  5047. var isPartial = bitmask & COMPARE_PARTIAL_FLAG$4;
  5048. convert || (convert = _setToArray);
  5049. if (object.size != other.size && !isPartial) {
  5050. return false;
  5051. }
  5052. // Assume cyclic values are equal.
  5053. var stacked = stack.get(object);
  5054. if (stacked) {
  5055. return stacked == other;
  5056. }
  5057. bitmask |= COMPARE_UNORDERED_FLAG$2;
  5058. // Recursively compare objects (susceptible to call stack limits).
  5059. stack.set(object, other);
  5060. var result = _equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
  5061. stack['delete'](object);
  5062. return result;
  5063. case symbolTag:
  5064. if (symbolValueOf) {
  5065. return symbolValueOf.call(object) == symbolValueOf.call(other);
  5066. }
  5067. }
  5068. return false;
  5069. }
  5070. var _equalByTag = equalByTag;
  5071. /** Used to compose bitmasks for value comparisons. */
  5072. var COMPARE_PARTIAL_FLAG$3 = 1;
  5073. /** Used for built-in method references. */
  5074. var objectProto$1 = Object.prototype;
  5075. /** Used to check objects for own properties. */
  5076. var hasOwnProperty$1 = objectProto$1.hasOwnProperty;
  5077. /**
  5078. * A specialized version of `baseIsEqualDeep` for objects with support for
  5079. * partial deep comparisons.
  5080. *
  5081. * @private
  5082. * @param {Object} object The object to compare.
  5083. * @param {Object} other The other object to compare.
  5084. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
  5085. * @param {Function} customizer The function to customize comparisons.
  5086. * @param {Function} equalFunc The function to determine equivalents of values.
  5087. * @param {Object} stack Tracks traversed `object` and `other` objects.
  5088. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
  5089. */
  5090. function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
  5091. var isPartial = bitmask & COMPARE_PARTIAL_FLAG$3,
  5092. objProps = _getAllKeys(object),
  5093. objLength = objProps.length,
  5094. othProps = _getAllKeys(other),
  5095. othLength = othProps.length;
  5096. if (objLength != othLength && !isPartial) {
  5097. return false;
  5098. }
  5099. var index = objLength;
  5100. while (index--) {
  5101. var key = objProps[index];
  5102. if (!(isPartial ? key in other : hasOwnProperty$1.call(other, key))) {
  5103. return false;
  5104. }
  5105. }
  5106. // Check that cyclic values are equal.
  5107. var objStacked = stack.get(object);
  5108. var othStacked = stack.get(other);
  5109. if (objStacked && othStacked) {
  5110. return objStacked == other && othStacked == object;
  5111. }
  5112. var result = true;
  5113. stack.set(object, other);
  5114. stack.set(other, object);
  5115. var skipCtor = isPartial;
  5116. while (++index < objLength) {
  5117. key = objProps[index];
  5118. var objValue = object[key],
  5119. othValue = other[key];
  5120. if (customizer) {
  5121. var compared = isPartial
  5122. ? customizer(othValue, objValue, key, other, object, stack)
  5123. : customizer(objValue, othValue, key, object, other, stack);
  5124. }
  5125. // Recursively compare objects (susceptible to call stack limits).
  5126. if (!(compared === undefined
  5127. ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))
  5128. : compared
  5129. )) {
  5130. result = false;
  5131. break;
  5132. }
  5133. skipCtor || (skipCtor = key == 'constructor');
  5134. }
  5135. if (result && !skipCtor) {
  5136. var objCtor = object.constructor,
  5137. othCtor = other.constructor;
  5138. // Non `Object` object instances with different constructors are not equal.
  5139. if (objCtor != othCtor &&
  5140. ('constructor' in object && 'constructor' in other) &&
  5141. !(typeof objCtor == 'function' && objCtor instanceof objCtor &&
  5142. typeof othCtor == 'function' && othCtor instanceof othCtor)) {
  5143. result = false;
  5144. }
  5145. }
  5146. stack['delete'](object);
  5147. stack['delete'](other);
  5148. return result;
  5149. }
  5150. var _equalObjects = equalObjects;
  5151. /** Used to compose bitmasks for value comparisons. */
  5152. var COMPARE_PARTIAL_FLAG$2 = 1;
  5153. /** `Object#toString` result references. */
  5154. var argsTag = '[object Arguments]',
  5155. arrayTag = '[object Array]',
  5156. objectTag = '[object Object]';
  5157. /** Used for built-in method references. */
  5158. var objectProto = Object.prototype;
  5159. /** Used to check objects for own properties. */
  5160. var hasOwnProperty = objectProto.hasOwnProperty;
  5161. /**
  5162. * A specialized version of `baseIsEqual` for arrays and objects which performs
  5163. * deep comparisons and tracks traversed objects enabling objects with circular
  5164. * references to be compared.
  5165. *
  5166. * @private
  5167. * @param {Object} object The object to compare.
  5168. * @param {Object} other The other object to compare.
  5169. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
  5170. * @param {Function} customizer The function to customize comparisons.
  5171. * @param {Function} equalFunc The function to determine equivalents of values.
  5172. * @param {Object} [stack] Tracks traversed `object` and `other` objects.
  5173. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
  5174. */
  5175. function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
  5176. var objIsArr = isArray_1(object),
  5177. othIsArr = isArray_1(other),
  5178. objTag = objIsArr ? arrayTag : _getTag(object),
  5179. othTag = othIsArr ? arrayTag : _getTag(other);
  5180. objTag = objTag == argsTag ? objectTag : objTag;
  5181. othTag = othTag == argsTag ? objectTag : othTag;
  5182. var objIsObj = objTag == objectTag,
  5183. othIsObj = othTag == objectTag,
  5184. isSameTag = objTag == othTag;
  5185. if (isSameTag && isBuffer_1(object)) {
  5186. if (!isBuffer_1(other)) {
  5187. return false;
  5188. }
  5189. objIsArr = true;
  5190. objIsObj = false;
  5191. }
  5192. if (isSameTag && !objIsObj) {
  5193. stack || (stack = new _Stack);
  5194. return (objIsArr || isTypedArray_1(object))
  5195. ? _equalArrays(object, other, bitmask, customizer, equalFunc, stack)
  5196. : _equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
  5197. }
  5198. if (!(bitmask & COMPARE_PARTIAL_FLAG$2)) {
  5199. var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
  5200. othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
  5201. if (objIsWrapped || othIsWrapped) {
  5202. var objUnwrapped = objIsWrapped ? object.value() : object,
  5203. othUnwrapped = othIsWrapped ? other.value() : other;
  5204. stack || (stack = new _Stack);
  5205. return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
  5206. }
  5207. }
  5208. if (!isSameTag) {
  5209. return false;
  5210. }
  5211. stack || (stack = new _Stack);
  5212. return _equalObjects(object, other, bitmask, customizer, equalFunc, stack);
  5213. }
  5214. var _baseIsEqualDeep = baseIsEqualDeep;
  5215. /**
  5216. * The base implementation of `_.isEqual` which supports partial comparisons
  5217. * and tracks traversed objects.
  5218. *
  5219. * @private
  5220. * @param {*} value The value to compare.
  5221. * @param {*} other The other value to compare.
  5222. * @param {boolean} bitmask The bitmask flags.
  5223. * 1 - Unordered comparison
  5224. * 2 - Partial comparison
  5225. * @param {Function} [customizer] The function to customize comparisons.
  5226. * @param {Object} [stack] Tracks traversed `value` and `other` objects.
  5227. * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
  5228. */
  5229. function baseIsEqual(value, other, bitmask, customizer, stack) {
  5230. if (value === other) {
  5231. return true;
  5232. }
  5233. if (value == null || other == null || (!isObjectLike_1(value) && !isObjectLike_1(other))) {
  5234. return value !== value && other !== other;
  5235. }
  5236. return _baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
  5237. }
  5238. var _baseIsEqual = baseIsEqual;
  5239. /** Used to compose bitmasks for value comparisons. */
  5240. var COMPARE_PARTIAL_FLAG$1 = 1,
  5241. COMPARE_UNORDERED_FLAG$1 = 2;
  5242. /**
  5243. * The base implementation of `_.isMatch` without support for iteratee shorthands.
  5244. *
  5245. * @private
  5246. * @param {Object} object The object to inspect.
  5247. * @param {Object} source The object of property values to match.
  5248. * @param {Array} matchData The property names, values, and compare flags to match.
  5249. * @param {Function} [customizer] The function to customize comparisons.
  5250. * @returns {boolean} Returns `true` if `object` is a match, else `false`.
  5251. */
  5252. function baseIsMatch(object, source, matchData, customizer) {
  5253. var index = matchData.length,
  5254. length = index,
  5255. noCustomizer = !customizer;
  5256. if (object == null) {
  5257. return !length;
  5258. }
  5259. object = Object(object);
  5260. while (index--) {
  5261. var data = matchData[index];
  5262. if ((noCustomizer && data[2])
  5263. ? data[1] !== object[data[0]]
  5264. : !(data[0] in object)
  5265. ) {
  5266. return false;
  5267. }
  5268. }
  5269. while (++index < length) {
  5270. data = matchData[index];
  5271. var key = data[0],
  5272. objValue = object[key],
  5273. srcValue = data[1];
  5274. if (noCustomizer && data[2]) {
  5275. if (objValue === undefined && !(key in object)) {
  5276. return false;
  5277. }
  5278. } else {
  5279. var stack = new _Stack;
  5280. if (customizer) {
  5281. var result = customizer(objValue, srcValue, key, object, source, stack);
  5282. }
  5283. if (!(result === undefined
  5284. ? _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$1 | COMPARE_UNORDERED_FLAG$1, customizer, stack)
  5285. : result
  5286. )) {
  5287. return false;
  5288. }
  5289. }
  5290. }
  5291. return true;
  5292. }
  5293. var _baseIsMatch = baseIsMatch;
  5294. /**
  5295. * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
  5296. *
  5297. * @private
  5298. * @param {*} value The value to check.
  5299. * @returns {boolean} Returns `true` if `value` if suitable for strict
  5300. * equality comparisons, else `false`.
  5301. */
  5302. function isStrictComparable(value) {
  5303. return value === value && !isObject_1(value);
  5304. }
  5305. var _isStrictComparable = isStrictComparable;
  5306. /**
  5307. * Gets the property names, values, and compare flags of `object`.
  5308. *
  5309. * @private
  5310. * @param {Object} object The object to query.
  5311. * @returns {Array} Returns the match data of `object`.
  5312. */
  5313. function getMatchData(object) {
  5314. var result = keys_1(object),
  5315. length = result.length;
  5316. while (length--) {
  5317. var key = result[length],
  5318. value = object[key];
  5319. result[length] = [key, value, _isStrictComparable(value)];
  5320. }
  5321. return result;
  5322. }
  5323. var _getMatchData = getMatchData;
  5324. /**
  5325. * A specialized version of `matchesProperty` for source values suitable
  5326. * for strict equality comparisons, i.e. `===`.
  5327. *
  5328. * @private
  5329. * @param {string} key The key of the property to get.
  5330. * @param {*} srcValue The value to match.
  5331. * @returns {Function} Returns the new spec function.
  5332. */
  5333. function matchesStrictComparable(key, srcValue) {
  5334. return function(object) {
  5335. if (object == null) {
  5336. return false;
  5337. }
  5338. return object[key] === srcValue &&
  5339. (srcValue !== undefined || (key in Object(object)));
  5340. };
  5341. }
  5342. var _matchesStrictComparable = matchesStrictComparable;
  5343. /**
  5344. * The base implementation of `_.matches` which doesn't clone `source`.
  5345. *
  5346. * @private
  5347. * @param {Object} source The object of property values to match.
  5348. * @returns {Function} Returns the new spec function.
  5349. */
  5350. function baseMatches(source) {
  5351. var matchData = _getMatchData(source);
  5352. if (matchData.length == 1 && matchData[0][2]) {
  5353. return _matchesStrictComparable(matchData[0][0], matchData[0][1]);
  5354. }
  5355. return function(object) {
  5356. return object === source || _baseIsMatch(object, source, matchData);
  5357. };
  5358. }
  5359. var _baseMatches = baseMatches;
  5360. /** Used to match property names within property paths. */
  5361. var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
  5362. reIsPlainProp = /^\w*$/;
  5363. /**
  5364. * Checks if `value` is a property name and not a property path.
  5365. *
  5366. * @private
  5367. * @param {*} value The value to check.
  5368. * @param {Object} [object] The object to query keys on.
  5369. * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
  5370. */
  5371. function isKey(value, object) {
  5372. if (isArray_1(value)) {
  5373. return false;
  5374. }
  5375. var type = typeof value;
  5376. if (type == 'number' || type == 'symbol' || type == 'boolean' ||
  5377. value == null || isSymbol_1(value)) {
  5378. return true;
  5379. }
  5380. return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
  5381. (object != null && value in Object(object));
  5382. }
  5383. var _isKey = isKey;
  5384. /** Error message constants. */
  5385. var FUNC_ERROR_TEXT = 'Expected a function';
  5386. /**
  5387. * Creates a function that memoizes the result of `func`. If `resolver` is
  5388. * provided, it determines the cache key for storing the result based on the
  5389. * arguments provided to the memoized function. By default, the first argument
  5390. * provided to the memoized function is used as the map cache key. The `func`
  5391. * is invoked with the `this` binding of the memoized function.
  5392. *
  5393. * **Note:** The cache is exposed as the `cache` property on the memoized
  5394. * function. Its creation may be customized by replacing the `_.memoize.Cache`
  5395. * constructor with one whose instances implement the
  5396. * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
  5397. * method interface of `clear`, `delete`, `get`, `has`, and `set`.
  5398. *
  5399. * @static
  5400. * @memberOf _
  5401. * @since 0.1.0
  5402. * @category Function
  5403. * @param {Function} func The function to have its output memoized.
  5404. * @param {Function} [resolver] The function to resolve the cache key.
  5405. * @returns {Function} Returns the new memoized function.
  5406. * @example
  5407. *
  5408. * var object = { 'a': 1, 'b': 2 };
  5409. * var other = { 'c': 3, 'd': 4 };
  5410. *
  5411. * var values = _.memoize(_.values);
  5412. * values(object);
  5413. * // => [1, 2]
  5414. *
  5415. * values(other);
  5416. * // => [3, 4]
  5417. *
  5418. * object.a = 2;
  5419. * values(object);
  5420. * // => [1, 2]
  5421. *
  5422. * // Modify the result cache.
  5423. * values.cache.set(object, ['a', 'b']);
  5424. * values(object);
  5425. * // => ['a', 'b']
  5426. *
  5427. * // Replace `_.memoize.Cache`.
  5428. * _.memoize.Cache = WeakMap;
  5429. */
  5430. function memoize(func, resolver) {
  5431. if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {
  5432. throw new TypeError(FUNC_ERROR_TEXT);
  5433. }
  5434. var memoized = function() {
  5435. var args = arguments,
  5436. key = resolver ? resolver.apply(this, args) : args[0],
  5437. cache = memoized.cache;
  5438. if (cache.has(key)) {
  5439. return cache.get(key);
  5440. }
  5441. var result = func.apply(this, args);
  5442. memoized.cache = cache.set(key, result) || cache;
  5443. return result;
  5444. };
  5445. memoized.cache = new (memoize.Cache || _MapCache);
  5446. return memoized;
  5447. }
  5448. // Expose `MapCache`.
  5449. memoize.Cache = _MapCache;
  5450. var memoize_1 = memoize;
  5451. /** Used as the maximum memoize cache size. */
  5452. var MAX_MEMOIZE_SIZE = 500;
  5453. /**
  5454. * A specialized version of `_.memoize` which clears the memoized function's
  5455. * cache when it exceeds `MAX_MEMOIZE_SIZE`.
  5456. *
  5457. * @private
  5458. * @param {Function} func The function to have its output memoized.
  5459. * @returns {Function} Returns the new memoized function.
  5460. */
  5461. function memoizeCapped(func) {
  5462. var result = memoize_1(func, function(key) {
  5463. if (cache.size === MAX_MEMOIZE_SIZE) {
  5464. cache.clear();
  5465. }
  5466. return key;
  5467. });
  5468. var cache = result.cache;
  5469. return result;
  5470. }
  5471. var _memoizeCapped = memoizeCapped;
  5472. /** Used to match property names within property paths. */
  5473. var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
  5474. /** Used to match backslashes in property paths. */
  5475. var reEscapeChar = /\\(\\)?/g;
  5476. /**
  5477. * Converts `string` to a property path array.
  5478. *
  5479. * @private
  5480. * @param {string} string The string to convert.
  5481. * @returns {Array} Returns the property path array.
  5482. */
  5483. var stringToPath = _memoizeCapped(function(string) {
  5484. var result = [];
  5485. if (string.charCodeAt(0) === 46 /* . */) {
  5486. result.push('');
  5487. }
  5488. string.replace(rePropName, function(match, number, quote, subString) {
  5489. result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));
  5490. });
  5491. return result;
  5492. });
  5493. var _stringToPath = stringToPath;
  5494. /**
  5495. * A specialized version of `_.map` for arrays without support for iteratee
  5496. * shorthands.
  5497. *
  5498. * @private
  5499. * @param {Array} [array] The array to iterate over.
  5500. * @param {Function} iteratee The function invoked per iteration.
  5501. * @returns {Array} Returns the new mapped array.
  5502. */
  5503. function arrayMap(array, iteratee) {
  5504. var index = -1,
  5505. length = array == null ? 0 : array.length,
  5506. result = Array(length);
  5507. while (++index < length) {
  5508. result[index] = iteratee(array[index], index, array);
  5509. }
  5510. return result;
  5511. }
  5512. var _arrayMap = arrayMap;
  5513. /** Used as references for various `Number` constants. */
  5514. var INFINITY$1 = 1 / 0;
  5515. /** Used to convert symbols to primitives and strings. */
  5516. var symbolProto = _Symbol ? _Symbol.prototype : undefined,
  5517. symbolToString = symbolProto ? symbolProto.toString : undefined;
  5518. /**
  5519. * The base implementation of `_.toString` which doesn't convert nullish
  5520. * values to empty strings.
  5521. *
  5522. * @private
  5523. * @param {*} value The value to process.
  5524. * @returns {string} Returns the string.
  5525. */
  5526. function baseToString(value) {
  5527. // Exit early for strings to avoid a performance hit in some environments.
  5528. if (typeof value == 'string') {
  5529. return value;
  5530. }
  5531. if (isArray_1(value)) {
  5532. // Recursively convert values (susceptible to call stack limits).
  5533. return _arrayMap(value, baseToString) + '';
  5534. }
  5535. if (isSymbol_1(value)) {
  5536. return symbolToString ? symbolToString.call(value) : '';
  5537. }
  5538. var result = (value + '');
  5539. return (result == '0' && (1 / value) == -INFINITY$1) ? '-0' : result;
  5540. }
  5541. var _baseToString = baseToString;
  5542. /**
  5543. * Converts `value` to a string. An empty string is returned for `null`
  5544. * and `undefined` values. The sign of `-0` is preserved.
  5545. *
  5546. * @static
  5547. * @memberOf _
  5548. * @since 4.0.0
  5549. * @category Lang
  5550. * @param {*} value The value to convert.
  5551. * @returns {string} Returns the converted string.
  5552. * @example
  5553. *
  5554. * _.toString(null);
  5555. * // => ''
  5556. *
  5557. * _.toString(-0);
  5558. * // => '-0'
  5559. *
  5560. * _.toString([1, 2, 3]);
  5561. * // => '1,2,3'
  5562. */
  5563. function toString(value) {
  5564. return value == null ? '' : _baseToString(value);
  5565. }
  5566. var toString_1 = toString;
  5567. /**
  5568. * Casts `value` to a path array if it's not one.
  5569. *
  5570. * @private
  5571. * @param {*} value The value to inspect.
  5572. * @param {Object} [object] The object to query keys on.
  5573. * @returns {Array} Returns the cast property path array.
  5574. */
  5575. function castPath(value, object) {
  5576. if (isArray_1(value)) {
  5577. return value;
  5578. }
  5579. return _isKey(value, object) ? [value] : _stringToPath(toString_1(value));
  5580. }
  5581. var _castPath = castPath;
  5582. /** Used as references for various `Number` constants. */
  5583. var INFINITY = 1 / 0;
  5584. /**
  5585. * Converts `value` to a string key if it's not a string or symbol.
  5586. *
  5587. * @private
  5588. * @param {*} value The value to inspect.
  5589. * @returns {string|symbol} Returns the key.
  5590. */
  5591. function toKey(value) {
  5592. if (typeof value == 'string' || isSymbol_1(value)) {
  5593. return value;
  5594. }
  5595. var result = (value + '');
  5596. return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
  5597. }
  5598. var _toKey = toKey;
  5599. /**
  5600. * The base implementation of `_.get` without support for default values.
  5601. *
  5602. * @private
  5603. * @param {Object} object The object to query.
  5604. * @param {Array|string} path The path of the property to get.
  5605. * @returns {*} Returns the resolved value.
  5606. */
  5607. function baseGet(object, path) {
  5608. path = _castPath(path, object);
  5609. var index = 0,
  5610. length = path.length;
  5611. while (object != null && index < length) {
  5612. object = object[_toKey(path[index++])];
  5613. }
  5614. return (index && index == length) ? object : undefined;
  5615. }
  5616. var _baseGet = baseGet;
  5617. /**
  5618. * Gets the value at `path` of `object`. If the resolved value is
  5619. * `undefined`, the `defaultValue` is returned in its place.
  5620. *
  5621. * @static
  5622. * @memberOf _
  5623. * @since 3.7.0
  5624. * @category Object
  5625. * @param {Object} object The object to query.
  5626. * @param {Array|string} path The path of the property to get.
  5627. * @param {*} [defaultValue] The value returned for `undefined` resolved values.
  5628. * @returns {*} Returns the resolved value.
  5629. * @example
  5630. *
  5631. * var object = { 'a': [{ 'b': { 'c': 3 } }] };
  5632. *
  5633. * _.get(object, 'a[0].b.c');
  5634. * // => 3
  5635. *
  5636. * _.get(object, ['a', '0', 'b', 'c']);
  5637. * // => 3
  5638. *
  5639. * _.get(object, 'a.b.c', 'default');
  5640. * // => 'default'
  5641. */
  5642. function get$1(object, path, defaultValue) {
  5643. var result = object == null ? undefined : _baseGet(object, path);
  5644. return result === undefined ? defaultValue : result;
  5645. }
  5646. var get_1 = get$1;
  5647. /**
  5648. * The base implementation of `_.hasIn` without support for deep paths.
  5649. *
  5650. * @private
  5651. * @param {Object} [object] The object to query.
  5652. * @param {Array|string} key The key to check.
  5653. * @returns {boolean} Returns `true` if `key` exists, else `false`.
  5654. */
  5655. function baseHasIn(object, key) {
  5656. return object != null && key in Object(object);
  5657. }
  5658. var _baseHasIn = baseHasIn;
  5659. /**
  5660. * Checks if `path` exists on `object`.
  5661. *
  5662. * @private
  5663. * @param {Object} object The object to query.
  5664. * @param {Array|string} path The path to check.
  5665. * @param {Function} hasFunc The function to check properties.
  5666. * @returns {boolean} Returns `true` if `path` exists, else `false`.
  5667. */
  5668. function hasPath(object, path, hasFunc) {
  5669. path = _castPath(path, object);
  5670. var index = -1,
  5671. length = path.length,
  5672. result = false;
  5673. while (++index < length) {
  5674. var key = _toKey(path[index]);
  5675. if (!(result = object != null && hasFunc(object, key))) {
  5676. break;
  5677. }
  5678. object = object[key];
  5679. }
  5680. if (result || ++index != length) {
  5681. return result;
  5682. }
  5683. length = object == null ? 0 : object.length;
  5684. return !!length && isLength_1(length) && _isIndex(key, length) &&
  5685. (isArray_1(object) || isArguments_1(object));
  5686. }
  5687. var _hasPath = hasPath;
  5688. /**
  5689. * Checks if `path` is a direct or inherited property of `object`.
  5690. *
  5691. * @static
  5692. * @memberOf _
  5693. * @since 4.0.0
  5694. * @category Object
  5695. * @param {Object} object The object to query.
  5696. * @param {Array|string} path The path to check.
  5697. * @returns {boolean} Returns `true` if `path` exists, else `false`.
  5698. * @example
  5699. *
  5700. * var object = _.create({ 'a': _.create({ 'b': 2 }) });
  5701. *
  5702. * _.hasIn(object, 'a');
  5703. * // => true
  5704. *
  5705. * _.hasIn(object, 'a.b');
  5706. * // => true
  5707. *
  5708. * _.hasIn(object, ['a', 'b']);
  5709. * // => true
  5710. *
  5711. * _.hasIn(object, 'b');
  5712. * // => false
  5713. */
  5714. function hasIn(object, path) {
  5715. return object != null && _hasPath(object, path, _baseHasIn);
  5716. }
  5717. var hasIn_1 = hasIn;
  5718. /** Used to compose bitmasks for value comparisons. */
  5719. var COMPARE_PARTIAL_FLAG = 1,
  5720. COMPARE_UNORDERED_FLAG = 2;
  5721. /**
  5722. * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
  5723. *
  5724. * @private
  5725. * @param {string} path The path of the property to get.
  5726. * @param {*} srcValue The value to match.
  5727. * @returns {Function} Returns the new spec function.
  5728. */
  5729. function baseMatchesProperty(path, srcValue) {
  5730. if (_isKey(path) && _isStrictComparable(srcValue)) {
  5731. return _matchesStrictComparable(_toKey(path), srcValue);
  5732. }
  5733. return function(object) {
  5734. var objValue = get_1(object, path);
  5735. return (objValue === undefined && objValue === srcValue)
  5736. ? hasIn_1(object, path)
  5737. : _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);
  5738. };
  5739. }
  5740. var _baseMatchesProperty = baseMatchesProperty;
  5741. /**
  5742. * The base implementation of `_.property` without support for deep paths.
  5743. *
  5744. * @private
  5745. * @param {string} key The key of the property to get.
  5746. * @returns {Function} Returns the new accessor function.
  5747. */
  5748. function baseProperty(key) {
  5749. return function(object) {
  5750. return object == null ? undefined : object[key];
  5751. };
  5752. }
  5753. var _baseProperty = baseProperty;
  5754. /**
  5755. * A specialized version of `baseProperty` which supports deep paths.
  5756. *
  5757. * @private
  5758. * @param {Array|string} path The path of the property to get.
  5759. * @returns {Function} Returns the new accessor function.
  5760. */
  5761. function basePropertyDeep(path) {
  5762. return function(object) {
  5763. return _baseGet(object, path);
  5764. };
  5765. }
  5766. var _basePropertyDeep = basePropertyDeep;
  5767. /**
  5768. * Creates a function that returns the value at `path` of a given object.
  5769. *
  5770. * @static
  5771. * @memberOf _
  5772. * @since 2.4.0
  5773. * @category Util
  5774. * @param {Array|string} path The path of the property to get.
  5775. * @returns {Function} Returns the new accessor function.
  5776. * @example
  5777. *
  5778. * var objects = [
  5779. * { 'a': { 'b': 2 } },
  5780. * { 'a': { 'b': 1 } }
  5781. * ];
  5782. *
  5783. * _.map(objects, _.property('a.b'));
  5784. * // => [2, 1]
  5785. *
  5786. * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
  5787. * // => [1, 2]
  5788. */
  5789. function property(path) {
  5790. return _isKey(path) ? _baseProperty(_toKey(path)) : _basePropertyDeep(path);
  5791. }
  5792. var property_1 = property;
  5793. /**
  5794. * The base implementation of `_.iteratee`.
  5795. *
  5796. * @private
  5797. * @param {*} [value=_.identity] The value to convert to an iteratee.
  5798. * @returns {Function} Returns the iteratee.
  5799. */
  5800. function baseIteratee(value) {
  5801. // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
  5802. // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
  5803. if (typeof value == 'function') {
  5804. return value;
  5805. }
  5806. if (value == null) {
  5807. return identity_1;
  5808. }
  5809. if (typeof value == 'object') {
  5810. return isArray_1(value)
  5811. ? _baseMatchesProperty(value[0], value[1])
  5812. : _baseMatches(value);
  5813. }
  5814. return property_1(value);
  5815. }
  5816. var _baseIteratee = baseIteratee;
  5817. /** Used to compose bitmasks for cloning. */
  5818. var CLONE_DEEP_FLAG = 1;
  5819. /**
  5820. * Creates a function that invokes `func` with the arguments of the created
  5821. * function. If `func` is a property name, the created function returns the
  5822. * property value for a given element. If `func` is an array or object, the
  5823. * created function returns `true` for elements that contain the equivalent
  5824. * source properties, otherwise it returns `false`.
  5825. *
  5826. * @static
  5827. * @since 4.0.0
  5828. * @memberOf _
  5829. * @category Util
  5830. * @param {*} [func=_.identity] The value to convert to a callback.
  5831. * @returns {Function} Returns the callback.
  5832. * @example
  5833. *
  5834. * var users = [
  5835. * { 'user': 'barney', 'age': 36, 'active': true },
  5836. * { 'user': 'fred', 'age': 40, 'active': false }
  5837. * ];
  5838. *
  5839. * // The `_.matches` iteratee shorthand.
  5840. * _.filter(users, _.iteratee({ 'user': 'barney', 'active': true }));
  5841. * // => [{ 'user': 'barney', 'age': 36, 'active': true }]
  5842. *
  5843. * // The `_.matchesProperty` iteratee shorthand.
  5844. * _.filter(users, _.iteratee(['user', 'fred']));
  5845. * // => [{ 'user': 'fred', 'age': 40 }]
  5846. *
  5847. * // The `_.property` iteratee shorthand.
  5848. * _.map(users, _.iteratee('user'));
  5849. * // => ['barney', 'fred']
  5850. *
  5851. * // Create custom iteratee shorthands.
  5852. * _.iteratee = _.wrap(_.iteratee, function(iteratee, func) {
  5853. * return !_.isRegExp(func) ? iteratee(func) : function(string) {
  5854. * return func.test(string);
  5855. * };
  5856. * });
  5857. *
  5858. * _.filter(['abc', 'def'], /ef/);
  5859. * // => ['def']
  5860. */
  5861. function iteratee(func) {
  5862. return _baseIteratee(typeof func == 'function' ? func : _baseClone(func, CLONE_DEEP_FLAG));
  5863. }
  5864. var iteratee_1 = iteratee;
  5865. /** Built-in value references. */
  5866. var spreadableSymbol = _Symbol ? _Symbol.isConcatSpreadable : undefined;
  5867. /**
  5868. * Checks if `value` is a flattenable `arguments` object or array.
  5869. *
  5870. * @private
  5871. * @param {*} value The value to check.
  5872. * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
  5873. */
  5874. function isFlattenable(value) {
  5875. return isArray_1(value) || isArguments_1(value) ||
  5876. !!(spreadableSymbol && value && value[spreadableSymbol]);
  5877. }
  5878. var _isFlattenable = isFlattenable;
  5879. /**
  5880. * The base implementation of `_.flatten` with support for restricting flattening.
  5881. *
  5882. * @private
  5883. * @param {Array} array The array to flatten.
  5884. * @param {number} depth The maximum recursion depth.
  5885. * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
  5886. * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
  5887. * @param {Array} [result=[]] The initial result value.
  5888. * @returns {Array} Returns the new flattened array.
  5889. */
  5890. function baseFlatten(array, depth, predicate, isStrict, result) {
  5891. var index = -1,
  5892. length = array.length;
  5893. predicate || (predicate = _isFlattenable);
  5894. result || (result = []);
  5895. while (++index < length) {
  5896. var value = array[index];
  5897. if (depth > 0 && predicate(value)) {
  5898. if (depth > 1) {
  5899. // Recursively flatten arrays (susceptible to call stack limits).
  5900. baseFlatten(value, depth - 1, predicate, isStrict, result);
  5901. } else {
  5902. _arrayPush(result, value);
  5903. }
  5904. } else if (!isStrict) {
  5905. result[result.length] = value;
  5906. }
  5907. }
  5908. return result;
  5909. }
  5910. var _baseFlatten = baseFlatten;
  5911. /**
  5912. * Flattens `array` a single level deep.
  5913. *
  5914. * @static
  5915. * @memberOf _
  5916. * @since 0.1.0
  5917. * @category Array
  5918. * @param {Array} array The array to flatten.
  5919. * @returns {Array} Returns the new flattened array.
  5920. * @example
  5921. *
  5922. * _.flatten([1, [2, [3, [4]], 5]]);
  5923. * // => [1, 2, [3, [4]], 5]
  5924. */
  5925. function flatten(array) {
  5926. var length = array == null ? 0 : array.length;
  5927. return length ? _baseFlatten(array, 1) : [];
  5928. }
  5929. var flatten_1 = flatten;
  5930. /* Built-in method references for those with the same name as other `lodash` methods. */
  5931. var nativeMax = Math.max;
  5932. /**
  5933. * A specialized version of `baseRest` which transforms the rest array.
  5934. *
  5935. * @private
  5936. * @param {Function} func The function to apply a rest parameter to.
  5937. * @param {number} [start=func.length-1] The start position of the rest parameter.
  5938. * @param {Function} transform The rest array transform.
  5939. * @returns {Function} Returns the new function.
  5940. */
  5941. function overRest(func, start, transform) {
  5942. start = nativeMax(start === undefined ? (func.length - 1) : start, 0);
  5943. return function() {
  5944. var args = arguments,
  5945. index = -1,
  5946. length = nativeMax(args.length - start, 0),
  5947. array = Array(length);
  5948. while (++index < length) {
  5949. array[index] = args[start + index];
  5950. }
  5951. index = -1;
  5952. var otherArgs = Array(start + 1);
  5953. while (++index < start) {
  5954. otherArgs[index] = args[index];
  5955. }
  5956. otherArgs[start] = transform(array);
  5957. return _apply(func, this, otherArgs);
  5958. };
  5959. }
  5960. var _overRest = overRest;
  5961. /**
  5962. * A specialized version of `baseRest` which flattens the rest array.
  5963. *
  5964. * @private
  5965. * @param {Function} func The function to apply a rest parameter to.
  5966. * @returns {Function} Returns the new function.
  5967. */
  5968. function flatRest(func) {
  5969. return _setToString(_overRest(func, undefined, flatten_1), func + '');
  5970. }
  5971. var _flatRest = flatRest;
  5972. /** Used to compose bitmasks for function metadata. */
  5973. var WRAP_REARG_FLAG = 256;
  5974. /**
  5975. * Creates a function that invokes `func` with arguments arranged according
  5976. * to the specified `indexes` where the argument value at the first index is
  5977. * provided as the first argument, the argument value at the second index is
  5978. * provided as the second argument, and so on.
  5979. *
  5980. * @static
  5981. * @memberOf _
  5982. * @since 3.0.0
  5983. * @category Function
  5984. * @param {Function} func The function to rearrange arguments for.
  5985. * @param {...(number|number[])} indexes The arranged argument indexes.
  5986. * @returns {Function} Returns the new function.
  5987. * @example
  5988. *
  5989. * var rearged = _.rearg(function(a, b, c) {
  5990. * return [a, b, c];
  5991. * }, [2, 0, 1]);
  5992. *
  5993. * rearged('b', 'c', 'a')
  5994. * // => ['a', 'b', 'c']
  5995. */
  5996. var rearg = _flatRest(function(func, indexes) {
  5997. return _createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes);
  5998. });
  5999. var rearg_1 = rearg;
  6000. /**
  6001. * Converts `value` to a property path array.
  6002. *
  6003. * @static
  6004. * @memberOf _
  6005. * @since 4.0.0
  6006. * @category Util
  6007. * @param {*} value The value to convert.
  6008. * @returns {Array} Returns the new property path array.
  6009. * @example
  6010. *
  6011. * _.toPath('a.b.c');
  6012. * // => ['a', 'b', 'c']
  6013. *
  6014. * _.toPath('a[0].b.c');
  6015. * // => ['a', '0', 'b', 'c']
  6016. */
  6017. function toPath(value) {
  6018. if (isArray_1(value)) {
  6019. return _arrayMap(value, _toKey);
  6020. }
  6021. return isSymbol_1(value) ? [value] : _copyArray(_stringToPath(toString_1(value)));
  6022. }
  6023. var toPath_1 = toPath;
  6024. var _util = {
  6025. 'ary': ary_1,
  6026. 'assign': _baseAssign,
  6027. 'clone': clone_1,
  6028. 'curry': commonjsRequire("../curry", "/$$rollup_base$$/node_modules/lodash/fp"),
  6029. 'forEach': _arrayEach,
  6030. 'isArray': isArray_1,
  6031. 'isError': isError_1,
  6032. 'isFunction': isFunction_1,
  6033. 'isWeakMap': isWeakMap_1,
  6034. 'iteratee': iteratee_1,
  6035. 'keys': _baseKeys,
  6036. 'rearg': rearg_1,
  6037. 'toInteger': toInteger_1,
  6038. 'toPath': toPath_1
  6039. };
  6040. /**
  6041. * Converts `func` of `name` to an immutable auto-curried iteratee-first data-last
  6042. * version with conversion `options` applied. If `name` is an object its methods
  6043. * will be converted.
  6044. *
  6045. * @param {string} name The name of the function to wrap.
  6046. * @param {Function} [func] The function to wrap.
  6047. * @param {Object} [options] The options object. See `baseConvert` for more details.
  6048. * @returns {Function|Object} Returns the converted function or object.
  6049. */
  6050. function convert$2(name, func, options) {
  6051. return _baseConvert(_util, name, func, options);
  6052. }
  6053. var convert_1 = convert$2;
  6054. commonjsRegister("/$$rollup_base$$/node_modules/lodash/fp/curry.js", function (module, exports) {
  6055. var convert = convert_1,
  6056. func = convert('curry', commonjsRequire("../curry", "/$$rollup_base$$/node_modules/lodash/fp"));
  6057. func.placeholder = placeholder;
  6058. module.exports = func;
  6059. });
  6060. commonjsRegister("/$$rollup_base$$/node_modules/lodash/fp/curryN.js", function (module, exports) {
  6061. var convert = convert_1,
  6062. func = convert('curryN', commonjsRequire("../curry", "/$$rollup_base$$/node_modules/lodash/fp"));
  6063. func.placeholder = placeholder;
  6064. module.exports = func;
  6065. });
  6066. commonjsRegister("/$$rollup_base$$/node_modules/lodash/fp/curryRight.js", function (module, exports) {
  6067. var convert = convert_1,
  6068. func = convert('curryRight', commonjsRequire("../curryRight", "/$$rollup_base$$/node_modules/lodash/fp"));
  6069. func.placeholder = placeholder;
  6070. module.exports = func;
  6071. });
  6072. commonjsRegister("/$$rollup_base$$/node_modules/lodash/fp/curryRightN.js", function (module, exports) {
  6073. var convert = convert_1,
  6074. func = convert('curryRightN', commonjsRequire("../curryRight", "/$$rollup_base$$/node_modules/lodash/fp"));
  6075. func.placeholder = placeholder;
  6076. module.exports = func;
  6077. });
  6078. var moment = createCommonjsModule(function (module, exports) {
  6079. (function (global, factory) {
  6080. module.exports = factory() ;
  6081. }(commonjsGlobal, (function () {
  6082. var hookCallback;
  6083. function hooks() {
  6084. return hookCallback.apply(null, arguments);
  6085. }
  6086. // This is done to register the method called with moment()
  6087. // without creating circular dependencies.
  6088. function setHookCallback(callback) {
  6089. hookCallback = callback;
  6090. }
  6091. function isArray(input) {
  6092. return (
  6093. input instanceof Array ||
  6094. Object.prototype.toString.call(input) === '[object Array]'
  6095. );
  6096. }
  6097. function isObject(input) {
  6098. // IE8 will treat undefined and null as object if it wasn't for
  6099. // input != null
  6100. return (
  6101. input != null &&
  6102. Object.prototype.toString.call(input) === '[object Object]'
  6103. );
  6104. }
  6105. function hasOwnProp(a, b) {
  6106. return Object.prototype.hasOwnProperty.call(a, b);
  6107. }
  6108. function isObjectEmpty(obj) {
  6109. if (Object.getOwnPropertyNames) {
  6110. return Object.getOwnPropertyNames(obj).length === 0;
  6111. } else {
  6112. var k;
  6113. for (k in obj) {
  6114. if (hasOwnProp(obj, k)) {
  6115. return false;
  6116. }
  6117. }
  6118. return true;
  6119. }
  6120. }
  6121. function isUndefined(input) {
  6122. return input === void 0;
  6123. }
  6124. function isNumber(input) {
  6125. return (
  6126. typeof input === 'number' ||
  6127. Object.prototype.toString.call(input) === '[object Number]'
  6128. );
  6129. }
  6130. function isDate(input) {
  6131. return (
  6132. input instanceof Date ||
  6133. Object.prototype.toString.call(input) === '[object Date]'
  6134. );
  6135. }
  6136. function map(arr, fn) {
  6137. var res = [],
  6138. i;
  6139. for (i = 0; i < arr.length; ++i) {
  6140. res.push(fn(arr[i], i));
  6141. }
  6142. return res;
  6143. }
  6144. function extend(a, b) {
  6145. for (var i in b) {
  6146. if (hasOwnProp(b, i)) {
  6147. a[i] = b[i];
  6148. }
  6149. }
  6150. if (hasOwnProp(b, 'toString')) {
  6151. a.toString = b.toString;
  6152. }
  6153. if (hasOwnProp(b, 'valueOf')) {
  6154. a.valueOf = b.valueOf;
  6155. }
  6156. return a;
  6157. }
  6158. function createUTC(input, format, locale, strict) {
  6159. return createLocalOrUTC(input, format, locale, strict, true).utc();
  6160. }
  6161. function defaultParsingFlags() {
  6162. // We need to deep clone this object.
  6163. return {
  6164. empty: false,
  6165. unusedTokens: [],
  6166. unusedInput: [],
  6167. overflow: -2,
  6168. charsLeftOver: 0,
  6169. nullInput: false,
  6170. invalidEra: null,
  6171. invalidMonth: null,
  6172. invalidFormat: false,
  6173. userInvalidated: false,
  6174. iso: false,
  6175. parsedDateParts: [],
  6176. era: null,
  6177. meridiem: null,
  6178. rfc2822: false,
  6179. weekdayMismatch: false,
  6180. };
  6181. }
  6182. function getParsingFlags(m) {
  6183. if (m._pf == null) {
  6184. m._pf = defaultParsingFlags();
  6185. }
  6186. return m._pf;
  6187. }
  6188. var some;
  6189. if (Array.prototype.some) {
  6190. some = Array.prototype.some;
  6191. } else {
  6192. some = function (fun) {
  6193. var t = Object(this),
  6194. len = t.length >>> 0,
  6195. i;
  6196. for (i = 0; i < len; i++) {
  6197. if (i in t && fun.call(this, t[i], i, t)) {
  6198. return true;
  6199. }
  6200. }
  6201. return false;
  6202. };
  6203. }
  6204. function isValid(m) {
  6205. if (m._isValid == null) {
  6206. var flags = getParsingFlags(m),
  6207. parsedParts = some.call(flags.parsedDateParts, function (i) {
  6208. return i != null;
  6209. }),
  6210. isNowValid =
  6211. !isNaN(m._d.getTime()) &&
  6212. flags.overflow < 0 &&
  6213. !flags.empty &&
  6214. !flags.invalidEra &&
  6215. !flags.invalidMonth &&
  6216. !flags.invalidWeekday &&
  6217. !flags.weekdayMismatch &&
  6218. !flags.nullInput &&
  6219. !flags.invalidFormat &&
  6220. !flags.userInvalidated &&
  6221. (!flags.meridiem || (flags.meridiem && parsedParts));
  6222. if (m._strict) {
  6223. isNowValid =
  6224. isNowValid &&
  6225. flags.charsLeftOver === 0 &&
  6226. flags.unusedTokens.length === 0 &&
  6227. flags.bigHour === undefined;
  6228. }
  6229. if (Object.isFrozen == null || !Object.isFrozen(m)) {
  6230. m._isValid = isNowValid;
  6231. } else {
  6232. return isNowValid;
  6233. }
  6234. }
  6235. return m._isValid;
  6236. }
  6237. function createInvalid(flags) {
  6238. var m = createUTC(NaN);
  6239. if (flags != null) {
  6240. extend(getParsingFlags(m), flags);
  6241. } else {
  6242. getParsingFlags(m).userInvalidated = true;
  6243. }
  6244. return m;
  6245. }
  6246. // Plugins that add properties should also add the key here (null value),
  6247. // so we can properly clone ourselves.
  6248. var momentProperties = (hooks.momentProperties = []),
  6249. updateInProgress = false;
  6250. function copyConfig(to, from) {
  6251. var i, prop, val;
  6252. if (!isUndefined(from._isAMomentObject)) {
  6253. to._isAMomentObject = from._isAMomentObject;
  6254. }
  6255. if (!isUndefined(from._i)) {
  6256. to._i = from._i;
  6257. }
  6258. if (!isUndefined(from._f)) {
  6259. to._f = from._f;
  6260. }
  6261. if (!isUndefined(from._l)) {
  6262. to._l = from._l;
  6263. }
  6264. if (!isUndefined(from._strict)) {
  6265. to._strict = from._strict;
  6266. }
  6267. if (!isUndefined(from._tzm)) {
  6268. to._tzm = from._tzm;
  6269. }
  6270. if (!isUndefined(from._isUTC)) {
  6271. to._isUTC = from._isUTC;
  6272. }
  6273. if (!isUndefined(from._offset)) {
  6274. to._offset = from._offset;
  6275. }
  6276. if (!isUndefined(from._pf)) {
  6277. to._pf = getParsingFlags(from);
  6278. }
  6279. if (!isUndefined(from._locale)) {
  6280. to._locale = from._locale;
  6281. }
  6282. if (momentProperties.length > 0) {
  6283. for (i = 0; i < momentProperties.length; i++) {
  6284. prop = momentProperties[i];
  6285. val = from[prop];
  6286. if (!isUndefined(val)) {
  6287. to[prop] = val;
  6288. }
  6289. }
  6290. }
  6291. return to;
  6292. }
  6293. // Moment prototype object
  6294. function Moment(config) {
  6295. copyConfig(this, config);
  6296. this._d = new Date(config._d != null ? config._d.getTime() : NaN);
  6297. if (!this.isValid()) {
  6298. this._d = new Date(NaN);
  6299. }
  6300. // Prevent infinite loop in case updateOffset creates new moment
  6301. // objects.
  6302. if (updateInProgress === false) {
  6303. updateInProgress = true;
  6304. hooks.updateOffset(this);
  6305. updateInProgress = false;
  6306. }
  6307. }
  6308. function isMoment(obj) {
  6309. return (
  6310. obj instanceof Moment || (obj != null && obj._isAMomentObject != null)
  6311. );
  6312. }
  6313. function warn(msg) {
  6314. if (
  6315. hooks.suppressDeprecationWarnings === false &&
  6316. typeof console !== 'undefined' &&
  6317. console.warn
  6318. ) {
  6319. console.warn('Deprecation warning: ' + msg);
  6320. }
  6321. }
  6322. function deprecate(msg, fn) {
  6323. var firstTime = true;
  6324. return extend(function () {
  6325. if (hooks.deprecationHandler != null) {
  6326. hooks.deprecationHandler(null, msg);
  6327. }
  6328. if (firstTime) {
  6329. var args = [],
  6330. arg,
  6331. i,
  6332. key;
  6333. for (i = 0; i < arguments.length; i++) {
  6334. arg = '';
  6335. if (typeof arguments[i] === 'object') {
  6336. arg += '\n[' + i + '] ';
  6337. for (key in arguments[0]) {
  6338. if (hasOwnProp(arguments[0], key)) {
  6339. arg += key + ': ' + arguments[0][key] + ', ';
  6340. }
  6341. }
  6342. arg = arg.slice(0, -2); // Remove trailing comma and space
  6343. } else {
  6344. arg = arguments[i];
  6345. }
  6346. args.push(arg);
  6347. }
  6348. warn(
  6349. msg +
  6350. '\nArguments: ' +
  6351. Array.prototype.slice.call(args).join('') +
  6352. '\n' +
  6353. new Error().stack
  6354. );
  6355. firstTime = false;
  6356. }
  6357. return fn.apply(this, arguments);
  6358. }, fn);
  6359. }
  6360. var deprecations = {};
  6361. function deprecateSimple(name, msg) {
  6362. if (hooks.deprecationHandler != null) {
  6363. hooks.deprecationHandler(name, msg);
  6364. }
  6365. if (!deprecations[name]) {
  6366. warn(msg);
  6367. deprecations[name] = true;
  6368. }
  6369. }
  6370. hooks.suppressDeprecationWarnings = false;
  6371. hooks.deprecationHandler = null;
  6372. function isFunction(input) {
  6373. return (
  6374. (typeof Function !== 'undefined' && input instanceof Function) ||
  6375. Object.prototype.toString.call(input) === '[object Function]'
  6376. );
  6377. }
  6378. function set(config) {
  6379. var prop, i;
  6380. for (i in config) {
  6381. if (hasOwnProp(config, i)) {
  6382. prop = config[i];
  6383. if (isFunction(prop)) {
  6384. this[i] = prop;
  6385. } else {
  6386. this['_' + i] = prop;
  6387. }
  6388. }
  6389. }
  6390. this._config = config;
  6391. // Lenient ordinal parsing accepts just a number in addition to
  6392. // number + (possibly) stuff coming from _dayOfMonthOrdinalParse.
  6393. // TODO: Remove "ordinalParse" fallback in next major release.
  6394. this._dayOfMonthOrdinalParseLenient = new RegExp(
  6395. (this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) +
  6396. '|' +
  6397. /\d{1,2}/.source
  6398. );
  6399. }
  6400. function mergeConfigs(parentConfig, childConfig) {
  6401. var res = extend({}, parentConfig),
  6402. prop;
  6403. for (prop in childConfig) {
  6404. if (hasOwnProp(childConfig, prop)) {
  6405. if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) {
  6406. res[prop] = {};
  6407. extend(res[prop], parentConfig[prop]);
  6408. extend(res[prop], childConfig[prop]);
  6409. } else if (childConfig[prop] != null) {
  6410. res[prop] = childConfig[prop];
  6411. } else {
  6412. delete res[prop];
  6413. }
  6414. }
  6415. }
  6416. for (prop in parentConfig) {
  6417. if (
  6418. hasOwnProp(parentConfig, prop) &&
  6419. !hasOwnProp(childConfig, prop) &&
  6420. isObject(parentConfig[prop])
  6421. ) {
  6422. // make sure changes to properties don't modify parent config
  6423. res[prop] = extend({}, res[prop]);
  6424. }
  6425. }
  6426. return res;
  6427. }
  6428. function Locale(config) {
  6429. if (config != null) {
  6430. this.set(config);
  6431. }
  6432. }
  6433. var keys;
  6434. if (Object.keys) {
  6435. keys = Object.keys;
  6436. } else {
  6437. keys = function (obj) {
  6438. var i,
  6439. res = [];
  6440. for (i in obj) {
  6441. if (hasOwnProp(obj, i)) {
  6442. res.push(i);
  6443. }
  6444. }
  6445. return res;
  6446. };
  6447. }
  6448. var defaultCalendar = {
  6449. sameDay: '[Today at] LT',
  6450. nextDay: '[Tomorrow at] LT',
  6451. nextWeek: 'dddd [at] LT',
  6452. lastDay: '[Yesterday at] LT',
  6453. lastWeek: '[Last] dddd [at] LT',
  6454. sameElse: 'L',
  6455. };
  6456. function calendar(key, mom, now) {
  6457. var output = this._calendar[key] || this._calendar['sameElse'];
  6458. return isFunction(output) ? output.call(mom, now) : output;
  6459. }
  6460. function zeroFill(number, targetLength, forceSign) {
  6461. var absNumber = '' + Math.abs(number),
  6462. zerosToFill = targetLength - absNumber.length,
  6463. sign = number >= 0;
  6464. return (
  6465. (sign ? (forceSign ? '+' : '') : '-') +
  6466. Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) +
  6467. absNumber
  6468. );
  6469. }
  6470. 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,
  6471. localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,
  6472. formatFunctions = {},
  6473. formatTokenFunctions = {};
  6474. // token: 'M'
  6475. // padded: ['MM', 2]
  6476. // ordinal: 'Mo'
  6477. // callback: function () { this.month() + 1 }
  6478. function addFormatToken(token, padded, ordinal, callback) {
  6479. var func = callback;
  6480. if (typeof callback === 'string') {
  6481. func = function () {
  6482. return this[callback]();
  6483. };
  6484. }
  6485. if (token) {
  6486. formatTokenFunctions[token] = func;
  6487. }
  6488. if (padded) {
  6489. formatTokenFunctions[padded[0]] = function () {
  6490. return zeroFill(func.apply(this, arguments), padded[1], padded[2]);
  6491. };
  6492. }
  6493. if (ordinal) {
  6494. formatTokenFunctions[ordinal] = function () {
  6495. return this.localeData().ordinal(
  6496. func.apply(this, arguments),
  6497. token
  6498. );
  6499. };
  6500. }
  6501. }
  6502. function removeFormattingTokens(input) {
  6503. if (input.match(/\[[\s\S]/)) {
  6504. return input.replace(/^\[|\]$/g, '');
  6505. }
  6506. return input.replace(/\\/g, '');
  6507. }
  6508. function makeFormatFunction(format) {
  6509. var array = format.match(formattingTokens),
  6510. i,
  6511. length;
  6512. for (i = 0, length = array.length; i < length; i++) {
  6513. if (formatTokenFunctions[array[i]]) {
  6514. array[i] = formatTokenFunctions[array[i]];
  6515. } else {
  6516. array[i] = removeFormattingTokens(array[i]);
  6517. }
  6518. }
  6519. return function (mom) {
  6520. var output = '',
  6521. i;
  6522. for (i = 0; i < length; i++) {
  6523. output += isFunction(array[i])
  6524. ? array[i].call(mom, format)
  6525. : array[i];
  6526. }
  6527. return output;
  6528. };
  6529. }
  6530. // format date using native date object
  6531. function formatMoment(m, format) {
  6532. if (!m.isValid()) {
  6533. return m.localeData().invalidDate();
  6534. }
  6535. format = expandFormat(format, m.localeData());
  6536. formatFunctions[format] =
  6537. formatFunctions[format] || makeFormatFunction(format);
  6538. return formatFunctions[format](m);
  6539. }
  6540. function expandFormat(format, locale) {
  6541. var i = 5;
  6542. function replaceLongDateFormatTokens(input) {
  6543. return locale.longDateFormat(input) || input;
  6544. }
  6545. localFormattingTokens.lastIndex = 0;
  6546. while (i >= 0 && localFormattingTokens.test(format)) {
  6547. format = format.replace(
  6548. localFormattingTokens,
  6549. replaceLongDateFormatTokens
  6550. );
  6551. localFormattingTokens.lastIndex = 0;
  6552. i -= 1;
  6553. }
  6554. return format;
  6555. }
  6556. var defaultLongDateFormat = {
  6557. LTS: 'h:mm:ss A',
  6558. LT: 'h:mm A',
  6559. L: 'MM/DD/YYYY',
  6560. LL: 'MMMM D, YYYY',
  6561. LLL: 'MMMM D, YYYY h:mm A',
  6562. LLLL: 'dddd, MMMM D, YYYY h:mm A',
  6563. };
  6564. function longDateFormat(key) {
  6565. var format = this._longDateFormat[key],
  6566. formatUpper = this._longDateFormat[key.toUpperCase()];
  6567. if (format || !formatUpper) {
  6568. return format;
  6569. }
  6570. this._longDateFormat[key] = formatUpper
  6571. .match(formattingTokens)
  6572. .map(function (tok) {
  6573. if (
  6574. tok === 'MMMM' ||
  6575. tok === 'MM' ||
  6576. tok === 'DD' ||
  6577. tok === 'dddd'
  6578. ) {
  6579. return tok.slice(1);
  6580. }
  6581. return tok;
  6582. })
  6583. .join('');
  6584. return this._longDateFormat[key];
  6585. }
  6586. var defaultInvalidDate = 'Invalid date';
  6587. function invalidDate() {
  6588. return this._invalidDate;
  6589. }
  6590. var defaultOrdinal = '%d',
  6591. defaultDayOfMonthOrdinalParse = /\d{1,2}/;
  6592. function ordinal(number) {
  6593. return this._ordinal.replace('%d', number);
  6594. }
  6595. var defaultRelativeTime = {
  6596. future: 'in %s',
  6597. past: '%s ago',
  6598. s: 'a few seconds',
  6599. ss: '%d seconds',
  6600. m: 'a minute',
  6601. mm: '%d minutes',
  6602. h: 'an hour',
  6603. hh: '%d hours',
  6604. d: 'a day',
  6605. dd: '%d days',
  6606. w: 'a week',
  6607. ww: '%d weeks',
  6608. M: 'a month',
  6609. MM: '%d months',
  6610. y: 'a year',
  6611. yy: '%d years',
  6612. };
  6613. function relativeTime(number, withoutSuffix, string, isFuture) {
  6614. var output = this._relativeTime[string];
  6615. return isFunction(output)
  6616. ? output(number, withoutSuffix, string, isFuture)
  6617. : output.replace(/%d/i, number);
  6618. }
  6619. function pastFuture(diff, output) {
  6620. var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
  6621. return isFunction(format) ? format(output) : format.replace(/%s/i, output);
  6622. }
  6623. var aliases = {};
  6624. function addUnitAlias(unit, shorthand) {
  6625. var lowerCase = unit.toLowerCase();
  6626. aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit;
  6627. }
  6628. function normalizeUnits(units) {
  6629. return typeof units === 'string'
  6630. ? aliases[units] || aliases[units.toLowerCase()]
  6631. : undefined;
  6632. }
  6633. function normalizeObjectUnits(inputObject) {
  6634. var normalizedInput = {},
  6635. normalizedProp,
  6636. prop;
  6637. for (prop in inputObject) {
  6638. if (hasOwnProp(inputObject, prop)) {
  6639. normalizedProp = normalizeUnits(prop);
  6640. if (normalizedProp) {
  6641. normalizedInput[normalizedProp] = inputObject[prop];
  6642. }
  6643. }
  6644. }
  6645. return normalizedInput;
  6646. }
  6647. var priorities = {};
  6648. function addUnitPriority(unit, priority) {
  6649. priorities[unit] = priority;
  6650. }
  6651. function getPrioritizedUnits(unitsObj) {
  6652. var units = [],
  6653. u;
  6654. for (u in unitsObj) {
  6655. if (hasOwnProp(unitsObj, u)) {
  6656. units.push({ unit: u, priority: priorities[u] });
  6657. }
  6658. }
  6659. units.sort(function (a, b) {
  6660. return a.priority - b.priority;
  6661. });
  6662. return units;
  6663. }
  6664. function isLeapYear(year) {
  6665. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  6666. }
  6667. function absFloor(number) {
  6668. if (number < 0) {
  6669. // -0 -> 0
  6670. return Math.ceil(number) || 0;
  6671. } else {
  6672. return Math.floor(number);
  6673. }
  6674. }
  6675. function toInt(argumentForCoercion) {
  6676. var coercedNumber = +argumentForCoercion,
  6677. value = 0;
  6678. if (coercedNumber !== 0 && isFinite(coercedNumber)) {
  6679. value = absFloor(coercedNumber);
  6680. }
  6681. return value;
  6682. }
  6683. function makeGetSet(unit, keepTime) {
  6684. return function (value) {
  6685. if (value != null) {
  6686. set$1(this, unit, value);
  6687. hooks.updateOffset(this, keepTime);
  6688. return this;
  6689. } else {
  6690. return get(this, unit);
  6691. }
  6692. };
  6693. }
  6694. function get(mom, unit) {
  6695. return mom.isValid()
  6696. ? mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]()
  6697. : NaN;
  6698. }
  6699. function set$1(mom, unit, value) {
  6700. if (mom.isValid() && !isNaN(value)) {
  6701. if (
  6702. unit === 'FullYear' &&
  6703. isLeapYear(mom.year()) &&
  6704. mom.month() === 1 &&
  6705. mom.date() === 29
  6706. ) {
  6707. value = toInt(value);
  6708. mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](
  6709. value,
  6710. mom.month(),
  6711. daysInMonth(value, mom.month())
  6712. );
  6713. } else {
  6714. mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
  6715. }
  6716. }
  6717. }
  6718. // MOMENTS
  6719. function stringGet(units) {
  6720. units = normalizeUnits(units);
  6721. if (isFunction(this[units])) {
  6722. return this[units]();
  6723. }
  6724. return this;
  6725. }
  6726. function stringSet(units, value) {
  6727. if (typeof units === 'object') {
  6728. units = normalizeObjectUnits(units);
  6729. var prioritized = getPrioritizedUnits(units),
  6730. i;
  6731. for (i = 0; i < prioritized.length; i++) {
  6732. this[prioritized[i].unit](units[prioritized[i].unit]);
  6733. }
  6734. } else {
  6735. units = normalizeUnits(units);
  6736. if (isFunction(this[units])) {
  6737. return this[units](value);
  6738. }
  6739. }
  6740. return this;
  6741. }
  6742. var match1 = /\d/, // 0 - 9
  6743. match2 = /\d\d/, // 00 - 99
  6744. match3 = /\d{3}/, // 000 - 999
  6745. match4 = /\d{4}/, // 0000 - 9999
  6746. match6 = /[+-]?\d{6}/, // -999999 - 999999
  6747. match1to2 = /\d\d?/, // 0 - 99
  6748. match3to4 = /\d\d\d\d?/, // 999 - 9999
  6749. match5to6 = /\d\d\d\d\d\d?/, // 99999 - 999999
  6750. match1to3 = /\d{1,3}/, // 0 - 999
  6751. match1to4 = /\d{1,4}/, // 0 - 9999
  6752. match1to6 = /[+-]?\d{1,6}/, // -999999 - 999999
  6753. matchUnsigned = /\d+/, // 0 - inf
  6754. matchSigned = /[+-]?\d+/, // -inf - inf
  6755. matchOffset = /Z|[+-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z
  6756. matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi, // +00 -00 +00:00 -00:00 +0000 -0000 or Z
  6757. matchTimestamp = /[+-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123
  6758. // any word (or two) characters or numbers including two/three word month in arabic.
  6759. // includes scottish gaelic two word and hyphenated months
  6760. 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,
  6761. regexes;
  6762. regexes = {};
  6763. function addRegexToken(token, regex, strictRegex) {
  6764. regexes[token] = isFunction(regex)
  6765. ? regex
  6766. : function (isStrict, localeData) {
  6767. return isStrict && strictRegex ? strictRegex : regex;
  6768. };
  6769. }
  6770. function getParseRegexForToken(token, config) {
  6771. if (!hasOwnProp(regexes, token)) {
  6772. return new RegExp(unescapeFormat(token));
  6773. }
  6774. return regexes[token](config._strict, config._locale);
  6775. }
  6776. // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
  6777. function unescapeFormat(s) {
  6778. return regexEscape(
  6779. s
  6780. .replace('\\', '')
  6781. .replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (
  6782. matched,
  6783. p1,
  6784. p2,
  6785. p3,
  6786. p4
  6787. ) {
  6788. return p1 || p2 || p3 || p4;
  6789. })
  6790. );
  6791. }
  6792. function regexEscape(s) {
  6793. return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  6794. }
  6795. var tokens = {};
  6796. function addParseToken(token, callback) {
  6797. var i,
  6798. func = callback;
  6799. if (typeof token === 'string') {
  6800. token = [token];
  6801. }
  6802. if (isNumber(callback)) {
  6803. func = function (input, array) {
  6804. array[callback] = toInt(input);
  6805. };
  6806. }
  6807. for (i = 0; i < token.length; i++) {
  6808. tokens[token[i]] = func;
  6809. }
  6810. }
  6811. function addWeekParseToken(token, callback) {
  6812. addParseToken(token, function (input, array, config, token) {
  6813. config._w = config._w || {};
  6814. callback(input, config._w, config, token);
  6815. });
  6816. }
  6817. function addTimeToArrayFromToken(token, input, config) {
  6818. if (input != null && hasOwnProp(tokens, token)) {
  6819. tokens[token](input, config._a, config, token);
  6820. }
  6821. }
  6822. var YEAR = 0,
  6823. MONTH = 1,
  6824. DATE = 2,
  6825. HOUR = 3,
  6826. MINUTE = 4,
  6827. SECOND = 5,
  6828. MILLISECOND = 6,
  6829. WEEK = 7,
  6830. WEEKDAY = 8;
  6831. function mod(n, x) {
  6832. return ((n % x) + x) % x;
  6833. }
  6834. var indexOf;
  6835. if (Array.prototype.indexOf) {
  6836. indexOf = Array.prototype.indexOf;
  6837. } else {
  6838. indexOf = function (o) {
  6839. // I know
  6840. var i;
  6841. for (i = 0; i < this.length; ++i) {
  6842. if (this[i] === o) {
  6843. return i;
  6844. }
  6845. }
  6846. return -1;
  6847. };
  6848. }
  6849. function daysInMonth(year, month) {
  6850. if (isNaN(year) || isNaN(month)) {
  6851. return NaN;
  6852. }
  6853. var modMonth = mod(month, 12);
  6854. year += (month - modMonth) / 12;
  6855. return modMonth === 1
  6856. ? isLeapYear(year)
  6857. ? 29
  6858. : 28
  6859. : 31 - ((modMonth % 7) % 2);
  6860. }
  6861. // FORMATTING
  6862. addFormatToken('M', ['MM', 2], 'Mo', function () {
  6863. return this.month() + 1;
  6864. });
  6865. addFormatToken('MMM', 0, 0, function (format) {
  6866. return this.localeData().monthsShort(this, format);
  6867. });
  6868. addFormatToken('MMMM', 0, 0, function (format) {
  6869. return this.localeData().months(this, format);
  6870. });
  6871. // ALIASES
  6872. addUnitAlias('month', 'M');
  6873. // PRIORITY
  6874. addUnitPriority('month', 8);
  6875. // PARSING
  6876. addRegexToken('M', match1to2);
  6877. addRegexToken('MM', match1to2, match2);
  6878. addRegexToken('MMM', function (isStrict, locale) {
  6879. return locale.monthsShortRegex(isStrict);
  6880. });
  6881. addRegexToken('MMMM', function (isStrict, locale) {
  6882. return locale.monthsRegex(isStrict);
  6883. });
  6884. addParseToken(['M', 'MM'], function (input, array) {
  6885. array[MONTH] = toInt(input) - 1;
  6886. });
  6887. addParseToken(['MMM', 'MMMM'], function (input, array, config, token) {
  6888. var month = config._locale.monthsParse(input, token, config._strict);
  6889. // if we didn't find a month name, mark the date as invalid.
  6890. if (month != null) {
  6891. array[MONTH] = month;
  6892. } else {
  6893. getParsingFlags(config).invalidMonth = input;
  6894. }
  6895. });
  6896. // LOCALES
  6897. var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split(
  6898. '_'
  6899. ),
  6900. defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split(
  6901. '_'
  6902. ),
  6903. MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/,
  6904. defaultMonthsShortRegex = matchWord,
  6905. defaultMonthsRegex = matchWord;
  6906. function localeMonths(m, format) {
  6907. if (!m) {
  6908. return isArray(this._months)
  6909. ? this._months
  6910. : this._months['standalone'];
  6911. }
  6912. return isArray(this._months)
  6913. ? this._months[m.month()]
  6914. : this._months[
  6915. (this._months.isFormat || MONTHS_IN_FORMAT).test(format)
  6916. ? 'format'
  6917. : 'standalone'
  6918. ][m.month()];
  6919. }
  6920. function localeMonthsShort(m, format) {
  6921. if (!m) {
  6922. return isArray(this._monthsShort)
  6923. ? this._monthsShort
  6924. : this._monthsShort['standalone'];
  6925. }
  6926. return isArray(this._monthsShort)
  6927. ? this._monthsShort[m.month()]
  6928. : this._monthsShort[
  6929. MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone'
  6930. ][m.month()];
  6931. }
  6932. function handleStrictParse(monthName, format, strict) {
  6933. var i,
  6934. ii,
  6935. mom,
  6936. llc = monthName.toLocaleLowerCase();
  6937. if (!this._monthsParse) {
  6938. // this is not used
  6939. this._monthsParse = [];
  6940. this._longMonthsParse = [];
  6941. this._shortMonthsParse = [];
  6942. for (i = 0; i < 12; ++i) {
  6943. mom = createUTC([2000, i]);
  6944. this._shortMonthsParse[i] = this.monthsShort(
  6945. mom,
  6946. ''
  6947. ).toLocaleLowerCase();
  6948. this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase();
  6949. }
  6950. }
  6951. if (strict) {
  6952. if (format === 'MMM') {
  6953. ii = indexOf.call(this._shortMonthsParse, llc);
  6954. return ii !== -1 ? ii : null;
  6955. } else {
  6956. ii = indexOf.call(this._longMonthsParse, llc);
  6957. return ii !== -1 ? ii : null;
  6958. }
  6959. } else {
  6960. if (format === 'MMM') {
  6961. ii = indexOf.call(this._shortMonthsParse, llc);
  6962. if (ii !== -1) {
  6963. return ii;
  6964. }
  6965. ii = indexOf.call(this._longMonthsParse, llc);
  6966. return ii !== -1 ? ii : null;
  6967. } else {
  6968. ii = indexOf.call(this._longMonthsParse, llc);
  6969. if (ii !== -1) {
  6970. return ii;
  6971. }
  6972. ii = indexOf.call(this._shortMonthsParse, llc);
  6973. return ii !== -1 ? ii : null;
  6974. }
  6975. }
  6976. }
  6977. function localeMonthsParse(monthName, format, strict) {
  6978. var i, mom, regex;
  6979. if (this._monthsParseExact) {
  6980. return handleStrictParse.call(this, monthName, format, strict);
  6981. }
  6982. if (!this._monthsParse) {
  6983. this._monthsParse = [];
  6984. this._longMonthsParse = [];
  6985. this._shortMonthsParse = [];
  6986. }
  6987. // TODO: add sorting
  6988. // Sorting makes sure if one month (or abbr) is a prefix of another
  6989. // see sorting in computeMonthsParse
  6990. for (i = 0; i < 12; i++) {
  6991. // make the regex if we don't have it already
  6992. mom = createUTC([2000, i]);
  6993. if (strict && !this._longMonthsParse[i]) {
  6994. this._longMonthsParse[i] = new RegExp(
  6995. '^' + this.months(mom, '').replace('.', '') + '$',
  6996. 'i'
  6997. );
  6998. this._shortMonthsParse[i] = new RegExp(
  6999. '^' + this.monthsShort(mom, '').replace('.', '') + '$',
  7000. 'i'
  7001. );
  7002. }
  7003. if (!strict && !this._monthsParse[i]) {
  7004. regex =
  7005. '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
  7006. this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
  7007. }
  7008. // test the regex
  7009. if (
  7010. strict &&
  7011. format === 'MMMM' &&
  7012. this._longMonthsParse[i].test(monthName)
  7013. ) {
  7014. return i;
  7015. } else if (
  7016. strict &&
  7017. format === 'MMM' &&
  7018. this._shortMonthsParse[i].test(monthName)
  7019. ) {
  7020. return i;
  7021. } else if (!strict && this._monthsParse[i].test(monthName)) {
  7022. return i;
  7023. }
  7024. }
  7025. }
  7026. // MOMENTS
  7027. function setMonth(mom, value) {
  7028. var dayOfMonth;
  7029. if (!mom.isValid()) {
  7030. // No op
  7031. return mom;
  7032. }
  7033. if (typeof value === 'string') {
  7034. if (/^\d+$/.test(value)) {
  7035. value = toInt(value);
  7036. } else {
  7037. value = mom.localeData().monthsParse(value);
  7038. // TODO: Another silent failure?
  7039. if (!isNumber(value)) {
  7040. return mom;
  7041. }
  7042. }
  7043. }
  7044. dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value));
  7045. mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
  7046. return mom;
  7047. }
  7048. function getSetMonth(value) {
  7049. if (value != null) {
  7050. setMonth(this, value);
  7051. hooks.updateOffset(this, true);
  7052. return this;
  7053. } else {
  7054. return get(this, 'Month');
  7055. }
  7056. }
  7057. function getDaysInMonth() {
  7058. return daysInMonth(this.year(), this.month());
  7059. }
  7060. function monthsShortRegex(isStrict) {
  7061. if (this._monthsParseExact) {
  7062. if (!hasOwnProp(this, '_monthsRegex')) {
  7063. computeMonthsParse.call(this);
  7064. }
  7065. if (isStrict) {
  7066. return this._monthsShortStrictRegex;
  7067. } else {
  7068. return this._monthsShortRegex;
  7069. }
  7070. } else {
  7071. if (!hasOwnProp(this, '_monthsShortRegex')) {
  7072. this._monthsShortRegex = defaultMonthsShortRegex;
  7073. }
  7074. return this._monthsShortStrictRegex && isStrict
  7075. ? this._monthsShortStrictRegex
  7076. : this._monthsShortRegex;
  7077. }
  7078. }
  7079. function monthsRegex(isStrict) {
  7080. if (this._monthsParseExact) {
  7081. if (!hasOwnProp(this, '_monthsRegex')) {
  7082. computeMonthsParse.call(this);
  7083. }
  7084. if (isStrict) {
  7085. return this._monthsStrictRegex;
  7086. } else {
  7087. return this._monthsRegex;
  7088. }
  7089. } else {
  7090. if (!hasOwnProp(this, '_monthsRegex')) {
  7091. this._monthsRegex = defaultMonthsRegex;
  7092. }
  7093. return this._monthsStrictRegex && isStrict
  7094. ? this._monthsStrictRegex
  7095. : this._monthsRegex;
  7096. }
  7097. }
  7098. function computeMonthsParse() {
  7099. function cmpLenRev(a, b) {
  7100. return b.length - a.length;
  7101. }
  7102. var shortPieces = [],
  7103. longPieces = [],
  7104. mixedPieces = [],
  7105. i,
  7106. mom;
  7107. for (i = 0; i < 12; i++) {
  7108. // make the regex if we don't have it already
  7109. mom = createUTC([2000, i]);
  7110. shortPieces.push(this.monthsShort(mom, ''));
  7111. longPieces.push(this.months(mom, ''));
  7112. mixedPieces.push(this.months(mom, ''));
  7113. mixedPieces.push(this.monthsShort(mom, ''));
  7114. }
  7115. // Sorting makes sure if one month (or abbr) is a prefix of another it
  7116. // will match the longer piece.
  7117. shortPieces.sort(cmpLenRev);
  7118. longPieces.sort(cmpLenRev);
  7119. mixedPieces.sort(cmpLenRev);
  7120. for (i = 0; i < 12; i++) {
  7121. shortPieces[i] = regexEscape(shortPieces[i]);
  7122. longPieces[i] = regexEscape(longPieces[i]);
  7123. }
  7124. for (i = 0; i < 24; i++) {
  7125. mixedPieces[i] = regexEscape(mixedPieces[i]);
  7126. }
  7127. this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
  7128. this._monthsShortRegex = this._monthsRegex;
  7129. this._monthsStrictRegex = new RegExp(
  7130. '^(' + longPieces.join('|') + ')',
  7131. 'i'
  7132. );
  7133. this._monthsShortStrictRegex = new RegExp(
  7134. '^(' + shortPieces.join('|') + ')',
  7135. 'i'
  7136. );
  7137. }
  7138. // FORMATTING
  7139. addFormatToken('Y', 0, 0, function () {
  7140. var y = this.year();
  7141. return y <= 9999 ? zeroFill(y, 4) : '+' + y;
  7142. });
  7143. addFormatToken(0, ['YY', 2], 0, function () {
  7144. return this.year() % 100;
  7145. });
  7146. addFormatToken(0, ['YYYY', 4], 0, 'year');
  7147. addFormatToken(0, ['YYYYY', 5], 0, 'year');
  7148. addFormatToken(0, ['YYYYYY', 6, true], 0, 'year');
  7149. // ALIASES
  7150. addUnitAlias('year', 'y');
  7151. // PRIORITIES
  7152. addUnitPriority('year', 1);
  7153. // PARSING
  7154. addRegexToken('Y', matchSigned);
  7155. addRegexToken('YY', match1to2, match2);
  7156. addRegexToken('YYYY', match1to4, match4);
  7157. addRegexToken('YYYYY', match1to6, match6);
  7158. addRegexToken('YYYYYY', match1to6, match6);
  7159. addParseToken(['YYYYY', 'YYYYYY'], YEAR);
  7160. addParseToken('YYYY', function (input, array) {
  7161. array[YEAR] =
  7162. input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input);
  7163. });
  7164. addParseToken('YY', function (input, array) {
  7165. array[YEAR] = hooks.parseTwoDigitYear(input);
  7166. });
  7167. addParseToken('Y', function (input, array) {
  7168. array[YEAR] = parseInt(input, 10);
  7169. });
  7170. // HELPERS
  7171. function daysInYear(year) {
  7172. return isLeapYear(year) ? 366 : 365;
  7173. }
  7174. // HOOKS
  7175. hooks.parseTwoDigitYear = function (input) {
  7176. return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
  7177. };
  7178. // MOMENTS
  7179. var getSetYear = makeGetSet('FullYear', true);
  7180. function getIsLeapYear() {
  7181. return isLeapYear(this.year());
  7182. }
  7183. function createDate(y, m, d, h, M, s, ms) {
  7184. // can't just apply() to create a date:
  7185. // https://stackoverflow.com/q/181348
  7186. var date;
  7187. // the date constructor remaps years 0-99 to 1900-1999
  7188. if (y < 100 && y >= 0) {
  7189. // preserve leap years using a full 400 year cycle, then reset
  7190. date = new Date(y + 400, m, d, h, M, s, ms);
  7191. if (isFinite(date.getFullYear())) {
  7192. date.setFullYear(y);
  7193. }
  7194. } else {
  7195. date = new Date(y, m, d, h, M, s, ms);
  7196. }
  7197. return date;
  7198. }
  7199. function createUTCDate(y) {
  7200. var date, args;
  7201. // the Date.UTC function remaps years 0-99 to 1900-1999
  7202. if (y < 100 && y >= 0) {
  7203. args = Array.prototype.slice.call(arguments);
  7204. // preserve leap years using a full 400 year cycle, then reset
  7205. args[0] = y + 400;
  7206. date = new Date(Date.UTC.apply(null, args));
  7207. if (isFinite(date.getUTCFullYear())) {
  7208. date.setUTCFullYear(y);
  7209. }
  7210. } else {
  7211. date = new Date(Date.UTC.apply(null, arguments));
  7212. }
  7213. return date;
  7214. }
  7215. // start-of-first-week - start-of-year
  7216. function firstWeekOffset(year, dow, doy) {
  7217. var // first-week day -- which january is always in the first week (4 for iso, 1 for other)
  7218. fwd = 7 + dow - doy,
  7219. // first-week day local weekday -- which local weekday is fwd
  7220. fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7;
  7221. return -fwdlw + fwd - 1;
  7222. }
  7223. // https://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
  7224. function dayOfYearFromWeeks(year, week, weekday, dow, doy) {
  7225. var localWeekday = (7 + weekday - dow) % 7,
  7226. weekOffset = firstWeekOffset(year, dow, doy),
  7227. dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset,
  7228. resYear,
  7229. resDayOfYear;
  7230. if (dayOfYear <= 0) {
  7231. resYear = year - 1;
  7232. resDayOfYear = daysInYear(resYear) + dayOfYear;
  7233. } else if (dayOfYear > daysInYear(year)) {
  7234. resYear = year + 1;
  7235. resDayOfYear = dayOfYear - daysInYear(year);
  7236. } else {
  7237. resYear = year;
  7238. resDayOfYear = dayOfYear;
  7239. }
  7240. return {
  7241. year: resYear,
  7242. dayOfYear: resDayOfYear,
  7243. };
  7244. }
  7245. function weekOfYear(mom, dow, doy) {
  7246. var weekOffset = firstWeekOffset(mom.year(), dow, doy),
  7247. week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1,
  7248. resWeek,
  7249. resYear;
  7250. if (week < 1) {
  7251. resYear = mom.year() - 1;
  7252. resWeek = week + weeksInYear(resYear, dow, doy);
  7253. } else if (week > weeksInYear(mom.year(), dow, doy)) {
  7254. resWeek = week - weeksInYear(mom.year(), dow, doy);
  7255. resYear = mom.year() + 1;
  7256. } else {
  7257. resYear = mom.year();
  7258. resWeek = week;
  7259. }
  7260. return {
  7261. week: resWeek,
  7262. year: resYear,
  7263. };
  7264. }
  7265. function weeksInYear(year, dow, doy) {
  7266. var weekOffset = firstWeekOffset(year, dow, doy),
  7267. weekOffsetNext = firstWeekOffset(year + 1, dow, doy);
  7268. return (daysInYear(year) - weekOffset + weekOffsetNext) / 7;
  7269. }
  7270. // FORMATTING
  7271. addFormatToken('w', ['ww', 2], 'wo', 'week');
  7272. addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek');
  7273. // ALIASES
  7274. addUnitAlias('week', 'w');
  7275. addUnitAlias('isoWeek', 'W');
  7276. // PRIORITIES
  7277. addUnitPriority('week', 5);
  7278. addUnitPriority('isoWeek', 5);
  7279. // PARSING
  7280. addRegexToken('w', match1to2);
  7281. addRegexToken('ww', match1to2, match2);
  7282. addRegexToken('W', match1to2);
  7283. addRegexToken('WW', match1to2, match2);
  7284. addWeekParseToken(['w', 'ww', 'W', 'WW'], function (
  7285. input,
  7286. week,
  7287. config,
  7288. token
  7289. ) {
  7290. week[token.substr(0, 1)] = toInt(input);
  7291. });
  7292. // HELPERS
  7293. // LOCALES
  7294. function localeWeek(mom) {
  7295. return weekOfYear(mom, this._week.dow, this._week.doy).week;
  7296. }
  7297. var defaultLocaleWeek = {
  7298. dow: 0, // Sunday is the first day of the week.
  7299. doy: 6, // The week that contains Jan 6th is the first week of the year.
  7300. };
  7301. function localeFirstDayOfWeek() {
  7302. return this._week.dow;
  7303. }
  7304. function localeFirstDayOfYear() {
  7305. return this._week.doy;
  7306. }
  7307. // MOMENTS
  7308. function getSetWeek(input) {
  7309. var week = this.localeData().week(this);
  7310. return input == null ? week : this.add((input - week) * 7, 'd');
  7311. }
  7312. function getSetISOWeek(input) {
  7313. var week = weekOfYear(this, 1, 4).week;
  7314. return input == null ? week : this.add((input - week) * 7, 'd');
  7315. }
  7316. // FORMATTING
  7317. addFormatToken('d', 0, 'do', 'day');
  7318. addFormatToken('dd', 0, 0, function (format) {
  7319. return this.localeData().weekdaysMin(this, format);
  7320. });
  7321. addFormatToken('ddd', 0, 0, function (format) {
  7322. return this.localeData().weekdaysShort(this, format);
  7323. });
  7324. addFormatToken('dddd', 0, 0, function (format) {
  7325. return this.localeData().weekdays(this, format);
  7326. });
  7327. addFormatToken('e', 0, 0, 'weekday');
  7328. addFormatToken('E', 0, 0, 'isoWeekday');
  7329. // ALIASES
  7330. addUnitAlias('day', 'd');
  7331. addUnitAlias('weekday', 'e');
  7332. addUnitAlias('isoWeekday', 'E');
  7333. // PRIORITY
  7334. addUnitPriority('day', 11);
  7335. addUnitPriority('weekday', 11);
  7336. addUnitPriority('isoWeekday', 11);
  7337. // PARSING
  7338. addRegexToken('d', match1to2);
  7339. addRegexToken('e', match1to2);
  7340. addRegexToken('E', match1to2);
  7341. addRegexToken('dd', function (isStrict, locale) {
  7342. return locale.weekdaysMinRegex(isStrict);
  7343. });
  7344. addRegexToken('ddd', function (isStrict, locale) {
  7345. return locale.weekdaysShortRegex(isStrict);
  7346. });
  7347. addRegexToken('dddd', function (isStrict, locale) {
  7348. return locale.weekdaysRegex(isStrict);
  7349. });
  7350. addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) {
  7351. var weekday = config._locale.weekdaysParse(input, token, config._strict);
  7352. // if we didn't get a weekday name, mark the date as invalid
  7353. if (weekday != null) {
  7354. week.d = weekday;
  7355. } else {
  7356. getParsingFlags(config).invalidWeekday = input;
  7357. }
  7358. });
  7359. addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) {
  7360. week[token] = toInt(input);
  7361. });
  7362. // HELPERS
  7363. function parseWeekday(input, locale) {
  7364. if (typeof input !== 'string') {
  7365. return input;
  7366. }
  7367. if (!isNaN(input)) {
  7368. return parseInt(input, 10);
  7369. }
  7370. input = locale.weekdaysParse(input);
  7371. if (typeof input === 'number') {
  7372. return input;
  7373. }
  7374. return null;
  7375. }
  7376. function parseIsoWeekday(input, locale) {
  7377. if (typeof input === 'string') {
  7378. return locale.weekdaysParse(input) % 7 || 7;
  7379. }
  7380. return isNaN(input) ? null : input;
  7381. }
  7382. // LOCALES
  7383. function shiftWeekdays(ws, n) {
  7384. return ws.slice(n, 7).concat(ws.slice(0, n));
  7385. }
  7386. var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split(
  7387. '_'
  7388. ),
  7389. defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),
  7390. defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),
  7391. defaultWeekdaysRegex = matchWord,
  7392. defaultWeekdaysShortRegex = matchWord,
  7393. defaultWeekdaysMinRegex = matchWord;
  7394. function localeWeekdays(m, format) {
  7395. var weekdays = isArray(this._weekdays)
  7396. ? this._weekdays
  7397. : this._weekdays[
  7398. m && m !== true && this._weekdays.isFormat.test(format)
  7399. ? 'format'
  7400. : 'standalone'
  7401. ];
  7402. return m === true
  7403. ? shiftWeekdays(weekdays, this._week.dow)
  7404. : m
  7405. ? weekdays[m.day()]
  7406. : weekdays;
  7407. }
  7408. function localeWeekdaysShort(m) {
  7409. return m === true
  7410. ? shiftWeekdays(this._weekdaysShort, this._week.dow)
  7411. : m
  7412. ? this._weekdaysShort[m.day()]
  7413. : this._weekdaysShort;
  7414. }
  7415. function localeWeekdaysMin(m) {
  7416. return m === true
  7417. ? shiftWeekdays(this._weekdaysMin, this._week.dow)
  7418. : m
  7419. ? this._weekdaysMin[m.day()]
  7420. : this._weekdaysMin;
  7421. }
  7422. function handleStrictParse$1(weekdayName, format, strict) {
  7423. var i,
  7424. ii,
  7425. mom,
  7426. llc = weekdayName.toLocaleLowerCase();
  7427. if (!this._weekdaysParse) {
  7428. this._weekdaysParse = [];
  7429. this._shortWeekdaysParse = [];
  7430. this._minWeekdaysParse = [];
  7431. for (i = 0; i < 7; ++i) {
  7432. mom = createUTC([2000, 1]).day(i);
  7433. this._minWeekdaysParse[i] = this.weekdaysMin(
  7434. mom,
  7435. ''
  7436. ).toLocaleLowerCase();
  7437. this._shortWeekdaysParse[i] = this.weekdaysShort(
  7438. mom,
  7439. ''
  7440. ).toLocaleLowerCase();
  7441. this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase();
  7442. }
  7443. }
  7444. if (strict) {
  7445. if (format === 'dddd') {
  7446. ii = indexOf.call(this._weekdaysParse, llc);
  7447. return ii !== -1 ? ii : null;
  7448. } else if (format === 'ddd') {
  7449. ii = indexOf.call(this._shortWeekdaysParse, llc);
  7450. return ii !== -1 ? ii : null;
  7451. } else {
  7452. ii = indexOf.call(this._minWeekdaysParse, llc);
  7453. return ii !== -1 ? ii : null;
  7454. }
  7455. } else {
  7456. if (format === 'dddd') {
  7457. ii = indexOf.call(this._weekdaysParse, llc);
  7458. if (ii !== -1) {
  7459. return ii;
  7460. }
  7461. ii = indexOf.call(this._shortWeekdaysParse, llc);
  7462. if (ii !== -1) {
  7463. return ii;
  7464. }
  7465. ii = indexOf.call(this._minWeekdaysParse, llc);
  7466. return ii !== -1 ? ii : null;
  7467. } else if (format === 'ddd') {
  7468. ii = indexOf.call(this._shortWeekdaysParse, llc);
  7469. if (ii !== -1) {
  7470. return ii;
  7471. }
  7472. ii = indexOf.call(this._weekdaysParse, llc);
  7473. if (ii !== -1) {
  7474. return ii;
  7475. }
  7476. ii = indexOf.call(this._minWeekdaysParse, llc);
  7477. return ii !== -1 ? ii : null;
  7478. } else {
  7479. ii = indexOf.call(this._minWeekdaysParse, llc);
  7480. if (ii !== -1) {
  7481. return ii;
  7482. }
  7483. ii = indexOf.call(this._weekdaysParse, llc);
  7484. if (ii !== -1) {
  7485. return ii;
  7486. }
  7487. ii = indexOf.call(this._shortWeekdaysParse, llc);
  7488. return ii !== -1 ? ii : null;
  7489. }
  7490. }
  7491. }
  7492. function localeWeekdaysParse(weekdayName, format, strict) {
  7493. var i, mom, regex;
  7494. if (this._weekdaysParseExact) {
  7495. return handleStrictParse$1.call(this, weekdayName, format, strict);
  7496. }
  7497. if (!this._weekdaysParse) {
  7498. this._weekdaysParse = [];
  7499. this._minWeekdaysParse = [];
  7500. this._shortWeekdaysParse = [];
  7501. this._fullWeekdaysParse = [];
  7502. }
  7503. for (i = 0; i < 7; i++) {
  7504. // make the regex if we don't have it already
  7505. mom = createUTC([2000, 1]).day(i);
  7506. if (strict && !this._fullWeekdaysParse[i]) {
  7507. this._fullWeekdaysParse[i] = new RegExp(
  7508. '^' + this.weekdays(mom, '').replace('.', '\\.?') + '$',
  7509. 'i'
  7510. );
  7511. this._shortWeekdaysParse[i] = new RegExp(
  7512. '^' + this.weekdaysShort(mom, '').replace('.', '\\.?') + '$',
  7513. 'i'
  7514. );
  7515. this._minWeekdaysParse[i] = new RegExp(
  7516. '^' + this.weekdaysMin(mom, '').replace('.', '\\.?') + '$',
  7517. 'i'
  7518. );
  7519. }
  7520. if (!this._weekdaysParse[i]) {
  7521. regex =
  7522. '^' +
  7523. this.weekdays(mom, '') +
  7524. '|^' +
  7525. this.weekdaysShort(mom, '') +
  7526. '|^' +
  7527. this.weekdaysMin(mom, '');
  7528. this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
  7529. }
  7530. // test the regex
  7531. if (
  7532. strict &&
  7533. format === 'dddd' &&
  7534. this._fullWeekdaysParse[i].test(weekdayName)
  7535. ) {
  7536. return i;
  7537. } else if (
  7538. strict &&
  7539. format === 'ddd' &&
  7540. this._shortWeekdaysParse[i].test(weekdayName)
  7541. ) {
  7542. return i;
  7543. } else if (
  7544. strict &&
  7545. format === 'dd' &&
  7546. this._minWeekdaysParse[i].test(weekdayName)
  7547. ) {
  7548. return i;
  7549. } else if (!strict && this._weekdaysParse[i].test(weekdayName)) {
  7550. return i;
  7551. }
  7552. }
  7553. }
  7554. // MOMENTS
  7555. function getSetDayOfWeek(input) {
  7556. if (!this.isValid()) {
  7557. return input != null ? this : NaN;
  7558. }
  7559. var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
  7560. if (input != null) {
  7561. input = parseWeekday(input, this.localeData());
  7562. return this.add(input - day, 'd');
  7563. } else {
  7564. return day;
  7565. }
  7566. }
  7567. function getSetLocaleDayOfWeek(input) {
  7568. if (!this.isValid()) {
  7569. return input != null ? this : NaN;
  7570. }
  7571. var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7;
  7572. return input == null ? weekday : this.add(input - weekday, 'd');
  7573. }
  7574. function getSetISODayOfWeek(input) {
  7575. if (!this.isValid()) {
  7576. return input != null ? this : NaN;
  7577. }
  7578. // behaves the same as moment#day except
  7579. // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
  7580. // as a setter, sunday should belong to the previous week.
  7581. if (input != null) {
  7582. var weekday = parseIsoWeekday(input, this.localeData());
  7583. return this.day(this.day() % 7 ? weekday : weekday - 7);
  7584. } else {
  7585. return this.day() || 7;
  7586. }
  7587. }
  7588. function weekdaysRegex(isStrict) {
  7589. if (this._weekdaysParseExact) {
  7590. if (!hasOwnProp(this, '_weekdaysRegex')) {
  7591. computeWeekdaysParse.call(this);
  7592. }
  7593. if (isStrict) {
  7594. return this._weekdaysStrictRegex;
  7595. } else {
  7596. return this._weekdaysRegex;
  7597. }
  7598. } else {
  7599. if (!hasOwnProp(this, '_weekdaysRegex')) {
  7600. this._weekdaysRegex = defaultWeekdaysRegex;
  7601. }
  7602. return this._weekdaysStrictRegex && isStrict
  7603. ? this._weekdaysStrictRegex
  7604. : this._weekdaysRegex;
  7605. }
  7606. }
  7607. function weekdaysShortRegex(isStrict) {
  7608. if (this._weekdaysParseExact) {
  7609. if (!hasOwnProp(this, '_weekdaysRegex')) {
  7610. computeWeekdaysParse.call(this);
  7611. }
  7612. if (isStrict) {
  7613. return this._weekdaysShortStrictRegex;
  7614. } else {
  7615. return this._weekdaysShortRegex;
  7616. }
  7617. } else {
  7618. if (!hasOwnProp(this, '_weekdaysShortRegex')) {
  7619. this._weekdaysShortRegex = defaultWeekdaysShortRegex;
  7620. }
  7621. return this._weekdaysShortStrictRegex && isStrict
  7622. ? this._weekdaysShortStrictRegex
  7623. : this._weekdaysShortRegex;
  7624. }
  7625. }
  7626. function weekdaysMinRegex(isStrict) {
  7627. if (this._weekdaysParseExact) {
  7628. if (!hasOwnProp(this, '_weekdaysRegex')) {
  7629. computeWeekdaysParse.call(this);
  7630. }
  7631. if (isStrict) {
  7632. return this._weekdaysMinStrictRegex;
  7633. } else {
  7634. return this._weekdaysMinRegex;
  7635. }
  7636. } else {
  7637. if (!hasOwnProp(this, '_weekdaysMinRegex')) {
  7638. this._weekdaysMinRegex = defaultWeekdaysMinRegex;
  7639. }
  7640. return this._weekdaysMinStrictRegex && isStrict
  7641. ? this._weekdaysMinStrictRegex
  7642. : this._weekdaysMinRegex;
  7643. }
  7644. }
  7645. function computeWeekdaysParse() {
  7646. function cmpLenRev(a, b) {
  7647. return b.length - a.length;
  7648. }
  7649. var minPieces = [],
  7650. shortPieces = [],
  7651. longPieces = [],
  7652. mixedPieces = [],
  7653. i,
  7654. mom,
  7655. minp,
  7656. shortp,
  7657. longp;
  7658. for (i = 0; i < 7; i++) {
  7659. // make the regex if we don't have it already
  7660. mom = createUTC([2000, 1]).day(i);
  7661. minp = regexEscape(this.weekdaysMin(mom, ''));
  7662. shortp = regexEscape(this.weekdaysShort(mom, ''));
  7663. longp = regexEscape(this.weekdays(mom, ''));
  7664. minPieces.push(minp);
  7665. shortPieces.push(shortp);
  7666. longPieces.push(longp);
  7667. mixedPieces.push(minp);
  7668. mixedPieces.push(shortp);
  7669. mixedPieces.push(longp);
  7670. }
  7671. // Sorting makes sure if one weekday (or abbr) is a prefix of another it
  7672. // will match the longer piece.
  7673. minPieces.sort(cmpLenRev);
  7674. shortPieces.sort(cmpLenRev);
  7675. longPieces.sort(cmpLenRev);
  7676. mixedPieces.sort(cmpLenRev);
  7677. this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
  7678. this._weekdaysShortRegex = this._weekdaysRegex;
  7679. this._weekdaysMinRegex = this._weekdaysRegex;
  7680. this._weekdaysStrictRegex = new RegExp(
  7681. '^(' + longPieces.join('|') + ')',
  7682. 'i'
  7683. );
  7684. this._weekdaysShortStrictRegex = new RegExp(
  7685. '^(' + shortPieces.join('|') + ')',
  7686. 'i'
  7687. );
  7688. this._weekdaysMinStrictRegex = new RegExp(
  7689. '^(' + minPieces.join('|') + ')',
  7690. 'i'
  7691. );
  7692. }
  7693. // FORMATTING
  7694. function hFormat() {
  7695. return this.hours() % 12 || 12;
  7696. }
  7697. function kFormat() {
  7698. return this.hours() || 24;
  7699. }
  7700. addFormatToken('H', ['HH', 2], 0, 'hour');
  7701. addFormatToken('h', ['hh', 2], 0, hFormat);
  7702. addFormatToken('k', ['kk', 2], 0, kFormat);
  7703. addFormatToken('hmm', 0, 0, function () {
  7704. return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2);
  7705. });
  7706. addFormatToken('hmmss', 0, 0, function () {
  7707. return (
  7708. '' +
  7709. hFormat.apply(this) +
  7710. zeroFill(this.minutes(), 2) +
  7711. zeroFill(this.seconds(), 2)
  7712. );
  7713. });
  7714. addFormatToken('Hmm', 0, 0, function () {
  7715. return '' + this.hours() + zeroFill(this.minutes(), 2);
  7716. });
  7717. addFormatToken('Hmmss', 0, 0, function () {
  7718. return (
  7719. '' +
  7720. this.hours() +
  7721. zeroFill(this.minutes(), 2) +
  7722. zeroFill(this.seconds(), 2)
  7723. );
  7724. });
  7725. function meridiem(token, lowercase) {
  7726. addFormatToken(token, 0, 0, function () {
  7727. return this.localeData().meridiem(
  7728. this.hours(),
  7729. this.minutes(),
  7730. lowercase
  7731. );
  7732. });
  7733. }
  7734. meridiem('a', true);
  7735. meridiem('A', false);
  7736. // ALIASES
  7737. addUnitAlias('hour', 'h');
  7738. // PRIORITY
  7739. addUnitPriority('hour', 13);
  7740. // PARSING
  7741. function matchMeridiem(isStrict, locale) {
  7742. return locale._meridiemParse;
  7743. }
  7744. addRegexToken('a', matchMeridiem);
  7745. addRegexToken('A', matchMeridiem);
  7746. addRegexToken('H', match1to2);
  7747. addRegexToken('h', match1to2);
  7748. addRegexToken('k', match1to2);
  7749. addRegexToken('HH', match1to2, match2);
  7750. addRegexToken('hh', match1to2, match2);
  7751. addRegexToken('kk', match1to2, match2);
  7752. addRegexToken('hmm', match3to4);
  7753. addRegexToken('hmmss', match5to6);
  7754. addRegexToken('Hmm', match3to4);
  7755. addRegexToken('Hmmss', match5to6);
  7756. addParseToken(['H', 'HH'], HOUR);
  7757. addParseToken(['k', 'kk'], function (input, array, config) {
  7758. var kInput = toInt(input);
  7759. array[HOUR] = kInput === 24 ? 0 : kInput;
  7760. });
  7761. addParseToken(['a', 'A'], function (input, array, config) {
  7762. config._isPm = config._locale.isPM(input);
  7763. config._meridiem = input;
  7764. });
  7765. addParseToken(['h', 'hh'], function (input, array, config) {
  7766. array[HOUR] = toInt(input);
  7767. getParsingFlags(config).bigHour = true;
  7768. });
  7769. addParseToken('hmm', function (input, array, config) {
  7770. var pos = input.length - 2;
  7771. array[HOUR] = toInt(input.substr(0, pos));
  7772. array[MINUTE] = toInt(input.substr(pos));
  7773. getParsingFlags(config).bigHour = true;
  7774. });
  7775. addParseToken('hmmss', function (input, array, config) {
  7776. var pos1 = input.length - 4,
  7777. pos2 = input.length - 2;
  7778. array[HOUR] = toInt(input.substr(0, pos1));
  7779. array[MINUTE] = toInt(input.substr(pos1, 2));
  7780. array[SECOND] = toInt(input.substr(pos2));
  7781. getParsingFlags(config).bigHour = true;
  7782. });
  7783. addParseToken('Hmm', function (input, array, config) {
  7784. var pos = input.length - 2;
  7785. array[HOUR] = toInt(input.substr(0, pos));
  7786. array[MINUTE] = toInt(input.substr(pos));
  7787. });
  7788. addParseToken('Hmmss', function (input, array, config) {
  7789. var pos1 = input.length - 4,
  7790. pos2 = input.length - 2;
  7791. array[HOUR] = toInt(input.substr(0, pos1));
  7792. array[MINUTE] = toInt(input.substr(pos1, 2));
  7793. array[SECOND] = toInt(input.substr(pos2));
  7794. });
  7795. // LOCALES
  7796. function localeIsPM(input) {
  7797. // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
  7798. // Using charAt should be more compatible.
  7799. return (input + '').toLowerCase().charAt(0) === 'p';
  7800. }
  7801. var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i,
  7802. // Setting the hour should keep the time, because the user explicitly
  7803. // specified which hour they want. So trying to maintain the same hour (in
  7804. // a new timezone) makes sense. Adding/subtracting hours does not follow
  7805. // this rule.
  7806. getSetHour = makeGetSet('Hours', true);
  7807. function localeMeridiem(hours, minutes, isLower) {
  7808. if (hours > 11) {
  7809. return isLower ? 'pm' : 'PM';
  7810. } else {
  7811. return isLower ? 'am' : 'AM';
  7812. }
  7813. }
  7814. var baseConfig = {
  7815. calendar: defaultCalendar,
  7816. longDateFormat: defaultLongDateFormat,
  7817. invalidDate: defaultInvalidDate,
  7818. ordinal: defaultOrdinal,
  7819. dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse,
  7820. relativeTime: defaultRelativeTime,
  7821. months: defaultLocaleMonths,
  7822. monthsShort: defaultLocaleMonthsShort,
  7823. week: defaultLocaleWeek,
  7824. weekdays: defaultLocaleWeekdays,
  7825. weekdaysMin: defaultLocaleWeekdaysMin,
  7826. weekdaysShort: defaultLocaleWeekdaysShort,
  7827. meridiemParse: defaultLocaleMeridiemParse,
  7828. };
  7829. // internal storage for locale config files
  7830. var locales = {},
  7831. localeFamilies = {},
  7832. globalLocale;
  7833. function commonPrefix(arr1, arr2) {
  7834. var i,
  7835. minl = Math.min(arr1.length, arr2.length);
  7836. for (i = 0; i < minl; i += 1) {
  7837. if (arr1[i] !== arr2[i]) {
  7838. return i;
  7839. }
  7840. }
  7841. return minl;
  7842. }
  7843. function normalizeLocale(key) {
  7844. return key ? key.toLowerCase().replace('_', '-') : key;
  7845. }
  7846. // pick the locale from the array
  7847. // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
  7848. // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
  7849. function chooseLocale(names) {
  7850. var i = 0,
  7851. j,
  7852. next,
  7853. locale,
  7854. split;
  7855. while (i < names.length) {
  7856. split = normalizeLocale(names[i]).split('-');
  7857. j = split.length;
  7858. next = normalizeLocale(names[i + 1]);
  7859. next = next ? next.split('-') : null;
  7860. while (j > 0) {
  7861. locale = loadLocale(split.slice(0, j).join('-'));
  7862. if (locale) {
  7863. return locale;
  7864. }
  7865. if (
  7866. next &&
  7867. next.length >= j &&
  7868. commonPrefix(split, next) >= j - 1
  7869. ) {
  7870. //the next array item is better than a shallower substring of this one
  7871. break;
  7872. }
  7873. j--;
  7874. }
  7875. i++;
  7876. }
  7877. return globalLocale;
  7878. }
  7879. function loadLocale(name) {
  7880. var oldLocale = null,
  7881. aliasedRequire;
  7882. // TODO: Find a better way to register and load all the locales in Node
  7883. if (
  7884. locales[name] === undefined &&
  7885. 'object' !== 'undefined' &&
  7886. module &&
  7887. module.exports
  7888. ) {
  7889. try {
  7890. oldLocale = globalLocale._abbr;
  7891. aliasedRequire = commonjsRequire;
  7892. aliasedRequire('./locale/' + name);
  7893. getSetGlobalLocale(oldLocale);
  7894. } catch (e) {
  7895. // mark as not found to avoid repeating expensive file require call causing high CPU
  7896. // when trying to find en-US, en_US, en-us for every format call
  7897. locales[name] = null; // null means not found
  7898. }
  7899. }
  7900. return locales[name];
  7901. }
  7902. // This function will load locale and then set the global locale. If
  7903. // no arguments are passed in, it will simply return the current global
  7904. // locale key.
  7905. function getSetGlobalLocale(key, values) {
  7906. var data;
  7907. if (key) {
  7908. if (isUndefined(values)) {
  7909. data = getLocale(key);
  7910. } else {
  7911. data = defineLocale(key, values);
  7912. }
  7913. if (data) {
  7914. // moment.duration._locale = moment._locale = data;
  7915. globalLocale = data;
  7916. } else {
  7917. if (typeof console !== 'undefined' && console.warn) {
  7918. //warn user if arguments are passed but the locale could not be set
  7919. console.warn(
  7920. 'Locale ' + key + ' not found. Did you forget to load it?'
  7921. );
  7922. }
  7923. }
  7924. }
  7925. return globalLocale._abbr;
  7926. }
  7927. function defineLocale(name, config) {
  7928. if (config !== null) {
  7929. var locale,
  7930. parentConfig = baseConfig;
  7931. config.abbr = name;
  7932. if (locales[name] != null) {
  7933. deprecateSimple(
  7934. 'defineLocaleOverride',
  7935. 'use moment.updateLocale(localeName, config) to change ' +
  7936. 'an existing locale. moment.defineLocale(localeName, ' +
  7937. 'config) should only be used for creating a new locale ' +
  7938. 'See http://momentjs.com/guides/#/warnings/define-locale/ for more info.'
  7939. );
  7940. parentConfig = locales[name]._config;
  7941. } else if (config.parentLocale != null) {
  7942. if (locales[config.parentLocale] != null) {
  7943. parentConfig = locales[config.parentLocale]._config;
  7944. } else {
  7945. locale = loadLocale(config.parentLocale);
  7946. if (locale != null) {
  7947. parentConfig = locale._config;
  7948. } else {
  7949. if (!localeFamilies[config.parentLocale]) {
  7950. localeFamilies[config.parentLocale] = [];
  7951. }
  7952. localeFamilies[config.parentLocale].push({
  7953. name: name,
  7954. config: config,
  7955. });
  7956. return null;
  7957. }
  7958. }
  7959. }
  7960. locales[name] = new Locale(mergeConfigs(parentConfig, config));
  7961. if (localeFamilies[name]) {
  7962. localeFamilies[name].forEach(function (x) {
  7963. defineLocale(x.name, x.config);
  7964. });
  7965. }
  7966. // backwards compat for now: also set the locale
  7967. // make sure we set the locale AFTER all child locales have been
  7968. // created, so we won't end up with the child locale set.
  7969. getSetGlobalLocale(name);
  7970. return locales[name];
  7971. } else {
  7972. // useful for testing
  7973. delete locales[name];
  7974. return null;
  7975. }
  7976. }
  7977. function updateLocale(name, config) {
  7978. if (config != null) {
  7979. var locale,
  7980. tmpLocale,
  7981. parentConfig = baseConfig;
  7982. if (locales[name] != null && locales[name].parentLocale != null) {
  7983. // Update existing child locale in-place to avoid memory-leaks
  7984. locales[name].set(mergeConfigs(locales[name]._config, config));
  7985. } else {
  7986. // MERGE
  7987. tmpLocale = loadLocale(name);
  7988. if (tmpLocale != null) {
  7989. parentConfig = tmpLocale._config;
  7990. }
  7991. config = mergeConfigs(parentConfig, config);
  7992. if (tmpLocale == null) {
  7993. // updateLocale is called for creating a new locale
  7994. // Set abbr so it will have a name (getters return
  7995. // undefined otherwise).
  7996. config.abbr = name;
  7997. }
  7998. locale = new Locale(config);
  7999. locale.parentLocale = locales[name];
  8000. locales[name] = locale;
  8001. }
  8002. // backwards compat for now: also set the locale
  8003. getSetGlobalLocale(name);
  8004. } else {
  8005. // pass null for config to unupdate, useful for tests
  8006. if (locales[name] != null) {
  8007. if (locales[name].parentLocale != null) {
  8008. locales[name] = locales[name].parentLocale;
  8009. if (name === getSetGlobalLocale()) {
  8010. getSetGlobalLocale(name);
  8011. }
  8012. } else if (locales[name] != null) {
  8013. delete locales[name];
  8014. }
  8015. }
  8016. }
  8017. return locales[name];
  8018. }
  8019. // returns locale data
  8020. function getLocale(key) {
  8021. var locale;
  8022. if (key && key._locale && key._locale._abbr) {
  8023. key = key._locale._abbr;
  8024. }
  8025. if (!key) {
  8026. return globalLocale;
  8027. }
  8028. if (!isArray(key)) {
  8029. //short-circuit everything else
  8030. locale = loadLocale(key);
  8031. if (locale) {
  8032. return locale;
  8033. }
  8034. key = [key];
  8035. }
  8036. return chooseLocale(key);
  8037. }
  8038. function listLocales() {
  8039. return keys(locales);
  8040. }
  8041. function checkOverflow(m) {
  8042. var overflow,
  8043. a = m._a;
  8044. if (a && getParsingFlags(m).overflow === -2) {
  8045. overflow =
  8046. a[MONTH] < 0 || a[MONTH] > 11
  8047. ? MONTH
  8048. : a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH])
  8049. ? DATE
  8050. : a[HOUR] < 0 ||
  8051. a[HOUR] > 24 ||
  8052. (a[HOUR] === 24 &&
  8053. (a[MINUTE] !== 0 ||
  8054. a[SECOND] !== 0 ||
  8055. a[MILLISECOND] !== 0))
  8056. ? HOUR
  8057. : a[MINUTE] < 0 || a[MINUTE] > 59
  8058. ? MINUTE
  8059. : a[SECOND] < 0 || a[SECOND] > 59
  8060. ? SECOND
  8061. : a[MILLISECOND] < 0 || a[MILLISECOND] > 999
  8062. ? MILLISECOND
  8063. : -1;
  8064. if (
  8065. getParsingFlags(m)._overflowDayOfYear &&
  8066. (overflow < YEAR || overflow > DATE)
  8067. ) {
  8068. overflow = DATE;
  8069. }
  8070. if (getParsingFlags(m)._overflowWeeks && overflow === -1) {
  8071. overflow = WEEK;
  8072. }
  8073. if (getParsingFlags(m)._overflowWeekday && overflow === -1) {
  8074. overflow = WEEKDAY;
  8075. }
  8076. getParsingFlags(m).overflow = overflow;
  8077. }
  8078. return m;
  8079. }
  8080. // iso 8601 regex
  8081. // 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)
  8082. 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)?)?$/,
  8083. 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)?)?$/,
  8084. tzRegex = /Z|[+-]\d\d(?::?\d\d)?/,
  8085. isoDates = [
  8086. ['YYYYYY-MM-DD', /[+-]\d{6}-\d\d-\d\d/],
  8087. ['YYYY-MM-DD', /\d{4}-\d\d-\d\d/],
  8088. ['GGGG-[W]WW-E', /\d{4}-W\d\d-\d/],
  8089. ['GGGG-[W]WW', /\d{4}-W\d\d/, false],
  8090. ['YYYY-DDD', /\d{4}-\d{3}/],
  8091. ['YYYY-MM', /\d{4}-\d\d/, false],
  8092. ['YYYYYYMMDD', /[+-]\d{10}/],
  8093. ['YYYYMMDD', /\d{8}/],
  8094. ['GGGG[W]WWE', /\d{4}W\d{3}/],
  8095. ['GGGG[W]WW', /\d{4}W\d{2}/, false],
  8096. ['YYYYDDD', /\d{7}/],
  8097. ['YYYYMM', /\d{6}/, false],
  8098. ['YYYY', /\d{4}/, false],
  8099. ],
  8100. // iso time formats and regexes
  8101. isoTimes = [
  8102. ['HH:mm:ss.SSSS', /\d\d:\d\d:\d\d\.\d+/],
  8103. ['HH:mm:ss,SSSS', /\d\d:\d\d:\d\d,\d+/],
  8104. ['HH:mm:ss', /\d\d:\d\d:\d\d/],
  8105. ['HH:mm', /\d\d:\d\d/],
  8106. ['HHmmss.SSSS', /\d\d\d\d\d\d\.\d+/],
  8107. ['HHmmss,SSSS', /\d\d\d\d\d\d,\d+/],
  8108. ['HHmmss', /\d\d\d\d\d\d/],
  8109. ['HHmm', /\d\d\d\d/],
  8110. ['HH', /\d\d/],
  8111. ],
  8112. aspNetJsonRegex = /^\/?Date\((-?\d+)/i,
  8113. // RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3
  8114. 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}))$/,
  8115. obsOffsets = {
  8116. UT: 0,
  8117. GMT: 0,
  8118. EDT: -4 * 60,
  8119. EST: -5 * 60,
  8120. CDT: -5 * 60,
  8121. CST: -6 * 60,
  8122. MDT: -6 * 60,
  8123. MST: -7 * 60,
  8124. PDT: -7 * 60,
  8125. PST: -8 * 60,
  8126. };
  8127. // date from iso format
  8128. function configFromISO(config) {
  8129. var i,
  8130. l,
  8131. string = config._i,
  8132. match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string),
  8133. allowTime,
  8134. dateFormat,
  8135. timeFormat,
  8136. tzFormat;
  8137. if (match) {
  8138. getParsingFlags(config).iso = true;
  8139. for (i = 0, l = isoDates.length; i < l; i++) {
  8140. if (isoDates[i][1].exec(match[1])) {
  8141. dateFormat = isoDates[i][0];
  8142. allowTime = isoDates[i][2] !== false;
  8143. break;
  8144. }
  8145. }
  8146. if (dateFormat == null) {
  8147. config._isValid = false;
  8148. return;
  8149. }
  8150. if (match[3]) {
  8151. for (i = 0, l = isoTimes.length; i < l; i++) {
  8152. if (isoTimes[i][1].exec(match[3])) {
  8153. // match[2] should be 'T' or space
  8154. timeFormat = (match[2] || ' ') + isoTimes[i][0];
  8155. break;
  8156. }
  8157. }
  8158. if (timeFormat == null) {
  8159. config._isValid = false;
  8160. return;
  8161. }
  8162. }
  8163. if (!allowTime && timeFormat != null) {
  8164. config._isValid = false;
  8165. return;
  8166. }
  8167. if (match[4]) {
  8168. if (tzRegex.exec(match[4])) {
  8169. tzFormat = 'Z';
  8170. } else {
  8171. config._isValid = false;
  8172. return;
  8173. }
  8174. }
  8175. config._f = dateFormat + (timeFormat || '') + (tzFormat || '');
  8176. configFromStringAndFormat(config);
  8177. } else {
  8178. config._isValid = false;
  8179. }
  8180. }
  8181. function extractFromRFC2822Strings(
  8182. yearStr,
  8183. monthStr,
  8184. dayStr,
  8185. hourStr,
  8186. minuteStr,
  8187. secondStr
  8188. ) {
  8189. var result = [
  8190. untruncateYear(yearStr),
  8191. defaultLocaleMonthsShort.indexOf(monthStr),
  8192. parseInt(dayStr, 10),
  8193. parseInt(hourStr, 10),
  8194. parseInt(minuteStr, 10),
  8195. ];
  8196. if (secondStr) {
  8197. result.push(parseInt(secondStr, 10));
  8198. }
  8199. return result;
  8200. }
  8201. function untruncateYear(yearStr) {
  8202. var year = parseInt(yearStr, 10);
  8203. if (year <= 49) {
  8204. return 2000 + year;
  8205. } else if (year <= 999) {
  8206. return 1900 + year;
  8207. }
  8208. return year;
  8209. }
  8210. function preprocessRFC2822(s) {
  8211. // Remove comments and folding whitespace and replace multiple-spaces with a single space
  8212. return s
  8213. .replace(/\([^)]*\)|[\n\t]/g, ' ')
  8214. .replace(/(\s\s+)/g, ' ')
  8215. .replace(/^\s\s*/, '')
  8216. .replace(/\s\s*$/, '');
  8217. }
  8218. function checkWeekday(weekdayStr, parsedInput, config) {
  8219. if (weekdayStr) {
  8220. // TODO: Replace the vanilla JS Date object with an independent day-of-week check.
  8221. var weekdayProvided = defaultLocaleWeekdaysShort.indexOf(weekdayStr),
  8222. weekdayActual = new Date(
  8223. parsedInput[0],
  8224. parsedInput[1],
  8225. parsedInput[2]
  8226. ).getDay();
  8227. if (weekdayProvided !== weekdayActual) {
  8228. getParsingFlags(config).weekdayMismatch = true;
  8229. config._isValid = false;
  8230. return false;
  8231. }
  8232. }
  8233. return true;
  8234. }
  8235. function calculateOffset(obsOffset, militaryOffset, numOffset) {
  8236. if (obsOffset) {
  8237. return obsOffsets[obsOffset];
  8238. } else if (militaryOffset) {
  8239. // the only allowed military tz is Z
  8240. return 0;
  8241. } else {
  8242. var hm = parseInt(numOffset, 10),
  8243. m = hm % 100,
  8244. h = (hm - m) / 100;
  8245. return h * 60 + m;
  8246. }
  8247. }
  8248. // date and time from ref 2822 format
  8249. function configFromRFC2822(config) {
  8250. var match = rfc2822.exec(preprocessRFC2822(config._i)),
  8251. parsedArray;
  8252. if (match) {
  8253. parsedArray = extractFromRFC2822Strings(
  8254. match[4],
  8255. match[3],
  8256. match[2],
  8257. match[5],
  8258. match[6],
  8259. match[7]
  8260. );
  8261. if (!checkWeekday(match[1], parsedArray, config)) {
  8262. return;
  8263. }
  8264. config._a = parsedArray;
  8265. config._tzm = calculateOffset(match[8], match[9], match[10]);
  8266. config._d = createUTCDate.apply(null, config._a);
  8267. config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
  8268. getParsingFlags(config).rfc2822 = true;
  8269. } else {
  8270. config._isValid = false;
  8271. }
  8272. }
  8273. // date from 1) ASP.NET, 2) ISO, 3) RFC 2822 formats, or 4) optional fallback if parsing isn't strict
  8274. function configFromString(config) {
  8275. var matched = aspNetJsonRegex.exec(config._i);
  8276. if (matched !== null) {
  8277. config._d = new Date(+matched[1]);
  8278. return;
  8279. }
  8280. configFromISO(config);
  8281. if (config._isValid === false) {
  8282. delete config._isValid;
  8283. } else {
  8284. return;
  8285. }
  8286. configFromRFC2822(config);
  8287. if (config._isValid === false) {
  8288. delete config._isValid;
  8289. } else {
  8290. return;
  8291. }
  8292. if (config._strict) {
  8293. config._isValid = false;
  8294. } else {
  8295. // Final attempt, use Input Fallback
  8296. hooks.createFromInputFallback(config);
  8297. }
  8298. }
  8299. hooks.createFromInputFallback = deprecate(
  8300. 'value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), ' +
  8301. 'which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are ' +
  8302. 'discouraged. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.',
  8303. function (config) {
  8304. config._d = new Date(config._i + (config._useUTC ? ' UTC' : ''));
  8305. }
  8306. );
  8307. // Pick the first defined of two or three arguments.
  8308. function defaults(a, b, c) {
  8309. if (a != null) {
  8310. return a;
  8311. }
  8312. if (b != null) {
  8313. return b;
  8314. }
  8315. return c;
  8316. }
  8317. function currentDateArray(config) {
  8318. // hooks is actually the exported moment object
  8319. var nowValue = new Date(hooks.now());
  8320. if (config._useUTC) {
  8321. return [
  8322. nowValue.getUTCFullYear(),
  8323. nowValue.getUTCMonth(),
  8324. nowValue.getUTCDate(),
  8325. ];
  8326. }
  8327. return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()];
  8328. }
  8329. // convert an array to a date.
  8330. // the array should mirror the parameters below
  8331. // note: all values past the year are optional and will default to the lowest possible value.
  8332. // [year, month, day , hour, minute, second, millisecond]
  8333. function configFromArray(config) {
  8334. var i,
  8335. date,
  8336. input = [],
  8337. currentDate,
  8338. expectedWeekday,
  8339. yearToUse;
  8340. if (config._d) {
  8341. return;
  8342. }
  8343. currentDate = currentDateArray(config);
  8344. //compute day of the year from weeks and weekdays
  8345. if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
  8346. dayOfYearFromWeekInfo(config);
  8347. }
  8348. //if the day of the year is set, figure out what it is
  8349. if (config._dayOfYear != null) {
  8350. yearToUse = defaults(config._a[YEAR], currentDate[YEAR]);
  8351. if (
  8352. config._dayOfYear > daysInYear(yearToUse) ||
  8353. config._dayOfYear === 0
  8354. ) {
  8355. getParsingFlags(config)._overflowDayOfYear = true;
  8356. }
  8357. date = createUTCDate(yearToUse, 0, config._dayOfYear);
  8358. config._a[MONTH] = date.getUTCMonth();
  8359. config._a[DATE] = date.getUTCDate();
  8360. }
  8361. // Default to current date.
  8362. // * if no year, month, day of month are given, default to today
  8363. // * if day of month is given, default month and year
  8364. // * if month is given, default only year
  8365. // * if year is given, don't default anything
  8366. for (i = 0; i < 3 && config._a[i] == null; ++i) {
  8367. config._a[i] = input[i] = currentDate[i];
  8368. }
  8369. // Zero out whatever was not defaulted, including time
  8370. for (; i < 7; i++) {
  8371. config._a[i] = input[i] =
  8372. config._a[i] == null ? (i === 2 ? 1 : 0) : config._a[i];
  8373. }
  8374. // Check for 24:00:00.000
  8375. if (
  8376. config._a[HOUR] === 24 &&
  8377. config._a[MINUTE] === 0 &&
  8378. config._a[SECOND] === 0 &&
  8379. config._a[MILLISECOND] === 0
  8380. ) {
  8381. config._nextDay = true;
  8382. config._a[HOUR] = 0;
  8383. }
  8384. config._d = (config._useUTC ? createUTCDate : createDate).apply(
  8385. null,
  8386. input
  8387. );
  8388. expectedWeekday = config._useUTC
  8389. ? config._d.getUTCDay()
  8390. : config._d.getDay();
  8391. // Apply timezone offset from input. The actual utcOffset can be changed
  8392. // with parseZone.
  8393. if (config._tzm != null) {
  8394. config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
  8395. }
  8396. if (config._nextDay) {
  8397. config._a[HOUR] = 24;
  8398. }
  8399. // check for mismatching day of week
  8400. if (
  8401. config._w &&
  8402. typeof config._w.d !== 'undefined' &&
  8403. config._w.d !== expectedWeekday
  8404. ) {
  8405. getParsingFlags(config).weekdayMismatch = true;
  8406. }
  8407. }
  8408. function dayOfYearFromWeekInfo(config) {
  8409. var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow, curWeek;
  8410. w = config._w;
  8411. if (w.GG != null || w.W != null || w.E != null) {
  8412. dow = 1;
  8413. doy = 4;
  8414. // TODO: We need to take the current isoWeekYear, but that depends on
  8415. // how we interpret now (local, utc, fixed offset). So create
  8416. // a now version of current config (take local/utc/offset flags, and
  8417. // create now).
  8418. weekYear = defaults(
  8419. w.GG,
  8420. config._a[YEAR],
  8421. weekOfYear(createLocal(), 1, 4).year
  8422. );
  8423. week = defaults(w.W, 1);
  8424. weekday = defaults(w.E, 1);
  8425. if (weekday < 1 || weekday > 7) {
  8426. weekdayOverflow = true;
  8427. }
  8428. } else {
  8429. dow = config._locale._week.dow;
  8430. doy = config._locale._week.doy;
  8431. curWeek = weekOfYear(createLocal(), dow, doy);
  8432. weekYear = defaults(w.gg, config._a[YEAR], curWeek.year);
  8433. // Default to current week.
  8434. week = defaults(w.w, curWeek.week);
  8435. if (w.d != null) {
  8436. // weekday -- low day numbers are considered next week
  8437. weekday = w.d;
  8438. if (weekday < 0 || weekday > 6) {
  8439. weekdayOverflow = true;
  8440. }
  8441. } else if (w.e != null) {
  8442. // local weekday -- counting starts from beginning of week
  8443. weekday = w.e + dow;
  8444. if (w.e < 0 || w.e > 6) {
  8445. weekdayOverflow = true;
  8446. }
  8447. } else {
  8448. // default to beginning of week
  8449. weekday = dow;
  8450. }
  8451. }
  8452. if (week < 1 || week > weeksInYear(weekYear, dow, doy)) {
  8453. getParsingFlags(config)._overflowWeeks = true;
  8454. } else if (weekdayOverflow != null) {
  8455. getParsingFlags(config)._overflowWeekday = true;
  8456. } else {
  8457. temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy);
  8458. config._a[YEAR] = temp.year;
  8459. config._dayOfYear = temp.dayOfYear;
  8460. }
  8461. }
  8462. // constant that refers to the ISO standard
  8463. hooks.ISO_8601 = function () {};
  8464. // constant that refers to the RFC 2822 form
  8465. hooks.RFC_2822 = function () {};
  8466. // date from string and format string
  8467. function configFromStringAndFormat(config) {
  8468. // TODO: Move this to another part of the creation flow to prevent circular deps
  8469. if (config._f === hooks.ISO_8601) {
  8470. configFromISO(config);
  8471. return;
  8472. }
  8473. if (config._f === hooks.RFC_2822) {
  8474. configFromRFC2822(config);
  8475. return;
  8476. }
  8477. config._a = [];
  8478. getParsingFlags(config).empty = true;
  8479. // This array is used to make a Date, either with `new Date` or `Date.UTC`
  8480. var string = '' + config._i,
  8481. i,
  8482. parsedInput,
  8483. tokens,
  8484. token,
  8485. skipped,
  8486. stringLength = string.length,
  8487. totalParsedInputLength = 0,
  8488. era;
  8489. tokens =
  8490. expandFormat(config._f, config._locale).match(formattingTokens) || [];
  8491. for (i = 0; i < tokens.length; i++) {
  8492. token = tokens[i];
  8493. parsedInput = (string.match(getParseRegexForToken(token, config)) ||
  8494. [])[0];
  8495. if (parsedInput) {
  8496. skipped = string.substr(0, string.indexOf(parsedInput));
  8497. if (skipped.length > 0) {
  8498. getParsingFlags(config).unusedInput.push(skipped);
  8499. }
  8500. string = string.slice(
  8501. string.indexOf(parsedInput) + parsedInput.length
  8502. );
  8503. totalParsedInputLength += parsedInput.length;
  8504. }
  8505. // don't parse if it's not a known token
  8506. if (formatTokenFunctions[token]) {
  8507. if (parsedInput) {
  8508. getParsingFlags(config).empty = false;
  8509. } else {
  8510. getParsingFlags(config).unusedTokens.push(token);
  8511. }
  8512. addTimeToArrayFromToken(token, parsedInput, config);
  8513. } else if (config._strict && !parsedInput) {
  8514. getParsingFlags(config).unusedTokens.push(token);
  8515. }
  8516. }
  8517. // add remaining unparsed input length to the string
  8518. getParsingFlags(config).charsLeftOver =
  8519. stringLength - totalParsedInputLength;
  8520. if (string.length > 0) {
  8521. getParsingFlags(config).unusedInput.push(string);
  8522. }
  8523. // clear _12h flag if hour is <= 12
  8524. if (
  8525. config._a[HOUR] <= 12 &&
  8526. getParsingFlags(config).bigHour === true &&
  8527. config._a[HOUR] > 0
  8528. ) {
  8529. getParsingFlags(config).bigHour = undefined;
  8530. }
  8531. getParsingFlags(config).parsedDateParts = config._a.slice(0);
  8532. getParsingFlags(config).meridiem = config._meridiem;
  8533. // handle meridiem
  8534. config._a[HOUR] = meridiemFixWrap(
  8535. config._locale,
  8536. config._a[HOUR],
  8537. config._meridiem
  8538. );
  8539. // handle era
  8540. era = getParsingFlags(config).era;
  8541. if (era !== null) {
  8542. config._a[YEAR] = config._locale.erasConvertYear(era, config._a[YEAR]);
  8543. }
  8544. configFromArray(config);
  8545. checkOverflow(config);
  8546. }
  8547. function meridiemFixWrap(locale, hour, meridiem) {
  8548. var isPm;
  8549. if (meridiem == null) {
  8550. // nothing to do
  8551. return hour;
  8552. }
  8553. if (locale.meridiemHour != null) {
  8554. return locale.meridiemHour(hour, meridiem);
  8555. } else if (locale.isPM != null) {
  8556. // Fallback
  8557. isPm = locale.isPM(meridiem);
  8558. if (isPm && hour < 12) {
  8559. hour += 12;
  8560. }
  8561. if (!isPm && hour === 12) {
  8562. hour = 0;
  8563. }
  8564. return hour;
  8565. } else {
  8566. // this is not supposed to happen
  8567. return hour;
  8568. }
  8569. }
  8570. // date from string and array of format strings
  8571. function configFromStringAndArray(config) {
  8572. var tempConfig,
  8573. bestMoment,
  8574. scoreToBeat,
  8575. i,
  8576. currentScore,
  8577. validFormatFound,
  8578. bestFormatIsValid = false;
  8579. if (config._f.length === 0) {
  8580. getParsingFlags(config).invalidFormat = true;
  8581. config._d = new Date(NaN);
  8582. return;
  8583. }
  8584. for (i = 0; i < config._f.length; i++) {
  8585. currentScore = 0;
  8586. validFormatFound = false;
  8587. tempConfig = copyConfig({}, config);
  8588. if (config._useUTC != null) {
  8589. tempConfig._useUTC = config._useUTC;
  8590. }
  8591. tempConfig._f = config._f[i];
  8592. configFromStringAndFormat(tempConfig);
  8593. if (isValid(tempConfig)) {
  8594. validFormatFound = true;
  8595. }
  8596. // if there is any input that was not parsed add a penalty for that format
  8597. currentScore += getParsingFlags(tempConfig).charsLeftOver;
  8598. //or tokens
  8599. currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10;
  8600. getParsingFlags(tempConfig).score = currentScore;
  8601. if (!bestFormatIsValid) {
  8602. if (
  8603. scoreToBeat == null ||
  8604. currentScore < scoreToBeat ||
  8605. validFormatFound
  8606. ) {
  8607. scoreToBeat = currentScore;
  8608. bestMoment = tempConfig;
  8609. if (validFormatFound) {
  8610. bestFormatIsValid = true;
  8611. }
  8612. }
  8613. } else {
  8614. if (currentScore < scoreToBeat) {
  8615. scoreToBeat = currentScore;
  8616. bestMoment = tempConfig;
  8617. }
  8618. }
  8619. }
  8620. extend(config, bestMoment || tempConfig);
  8621. }
  8622. function configFromObject(config) {
  8623. if (config._d) {
  8624. return;
  8625. }
  8626. var i = normalizeObjectUnits(config._i),
  8627. dayOrDate = i.day === undefined ? i.date : i.day;
  8628. config._a = map(
  8629. [i.year, i.month, dayOrDate, i.hour, i.minute, i.second, i.millisecond],
  8630. function (obj) {
  8631. return obj && parseInt(obj, 10);
  8632. }
  8633. );
  8634. configFromArray(config);
  8635. }
  8636. function createFromConfig(config) {
  8637. var res = new Moment(checkOverflow(prepareConfig(config)));
  8638. if (res._nextDay) {
  8639. // Adding is smart enough around DST
  8640. res.add(1, 'd');
  8641. res._nextDay = undefined;
  8642. }
  8643. return res;
  8644. }
  8645. function prepareConfig(config) {
  8646. var input = config._i,
  8647. format = config._f;
  8648. config._locale = config._locale || getLocale(config._l);
  8649. if (input === null || (format === undefined && input === '')) {
  8650. return createInvalid({ nullInput: true });
  8651. }
  8652. if (typeof input === 'string') {
  8653. config._i = input = config._locale.preparse(input);
  8654. }
  8655. if (isMoment(input)) {
  8656. return new Moment(checkOverflow(input));
  8657. } else if (isDate(input)) {
  8658. config._d = input;
  8659. } else if (isArray(format)) {
  8660. configFromStringAndArray(config);
  8661. } else if (format) {
  8662. configFromStringAndFormat(config);
  8663. } else {
  8664. configFromInput(config);
  8665. }
  8666. if (!isValid(config)) {
  8667. config._d = null;
  8668. }
  8669. return config;
  8670. }
  8671. function configFromInput(config) {
  8672. var input = config._i;
  8673. if (isUndefined(input)) {
  8674. config._d = new Date(hooks.now());
  8675. } else if (isDate(input)) {
  8676. config._d = new Date(input.valueOf());
  8677. } else if (typeof input === 'string') {
  8678. configFromString(config);
  8679. } else if (isArray(input)) {
  8680. config._a = map(input.slice(0), function (obj) {
  8681. return parseInt(obj, 10);
  8682. });
  8683. configFromArray(config);
  8684. } else if (isObject(input)) {
  8685. configFromObject(config);
  8686. } else if (isNumber(input)) {
  8687. // from milliseconds
  8688. config._d = new Date(input);
  8689. } else {
  8690. hooks.createFromInputFallback(config);
  8691. }
  8692. }
  8693. function createLocalOrUTC(input, format, locale, strict, isUTC) {
  8694. var c = {};
  8695. if (format === true || format === false) {
  8696. strict = format;
  8697. format = undefined;
  8698. }
  8699. if (locale === true || locale === false) {
  8700. strict = locale;
  8701. locale = undefined;
  8702. }
  8703. if (
  8704. (isObject(input) && isObjectEmpty(input)) ||
  8705. (isArray(input) && input.length === 0)
  8706. ) {
  8707. input = undefined;
  8708. }
  8709. // object construction must be done this way.
  8710. // https://github.com/moment/moment/issues/1423
  8711. c._isAMomentObject = true;
  8712. c._useUTC = c._isUTC = isUTC;
  8713. c._l = locale;
  8714. c._i = input;
  8715. c._f = format;
  8716. c._strict = strict;
  8717. return createFromConfig(c);
  8718. }
  8719. function createLocal(input, format, locale, strict) {
  8720. return createLocalOrUTC(input, format, locale, strict, false);
  8721. }
  8722. var prototypeMin = deprecate(
  8723. 'moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/',
  8724. function () {
  8725. var other = createLocal.apply(null, arguments);
  8726. if (this.isValid() && other.isValid()) {
  8727. return other < this ? this : other;
  8728. } else {
  8729. return createInvalid();
  8730. }
  8731. }
  8732. ),
  8733. prototypeMax = deprecate(
  8734. 'moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/',
  8735. function () {
  8736. var other = createLocal.apply(null, arguments);
  8737. if (this.isValid() && other.isValid()) {
  8738. return other > this ? this : other;
  8739. } else {
  8740. return createInvalid();
  8741. }
  8742. }
  8743. );
  8744. // Pick a moment m from moments so that m[fn](other) is true for all
  8745. // other. This relies on the function fn to be transitive.
  8746. //
  8747. // moments should either be an array of moment objects or an array, whose
  8748. // first element is an array of moment objects.
  8749. function pickBy(fn, moments) {
  8750. var res, i;
  8751. if (moments.length === 1 && isArray(moments[0])) {
  8752. moments = moments[0];
  8753. }
  8754. if (!moments.length) {
  8755. return createLocal();
  8756. }
  8757. res = moments[0];
  8758. for (i = 1; i < moments.length; ++i) {
  8759. if (!moments[i].isValid() || moments[i][fn](res)) {
  8760. res = moments[i];
  8761. }
  8762. }
  8763. return res;
  8764. }
  8765. // TODO: Use [].sort instead?
  8766. function min() {
  8767. var args = [].slice.call(arguments, 0);
  8768. return pickBy('isBefore', args);
  8769. }
  8770. function max() {
  8771. var args = [].slice.call(arguments, 0);
  8772. return pickBy('isAfter', args);
  8773. }
  8774. var now = function () {
  8775. return Date.now ? Date.now() : +new Date();
  8776. };
  8777. var ordering = [
  8778. 'year',
  8779. 'quarter',
  8780. 'month',
  8781. 'week',
  8782. 'day',
  8783. 'hour',
  8784. 'minute',
  8785. 'second',
  8786. 'millisecond',
  8787. ];
  8788. function isDurationValid(m) {
  8789. var key,
  8790. unitHasDecimal = false,
  8791. i;
  8792. for (key in m) {
  8793. if (
  8794. hasOwnProp(m, key) &&
  8795. !(
  8796. indexOf.call(ordering, key) !== -1 &&
  8797. (m[key] == null || !isNaN(m[key]))
  8798. )
  8799. ) {
  8800. return false;
  8801. }
  8802. }
  8803. for (i = 0; i < ordering.length; ++i) {
  8804. if (m[ordering[i]]) {
  8805. if (unitHasDecimal) {
  8806. return false; // only allow non-integers for smallest unit
  8807. }
  8808. if (parseFloat(m[ordering[i]]) !== toInt(m[ordering[i]])) {
  8809. unitHasDecimal = true;
  8810. }
  8811. }
  8812. }
  8813. return true;
  8814. }
  8815. function isValid$1() {
  8816. return this._isValid;
  8817. }
  8818. function createInvalid$1() {
  8819. return createDuration(NaN);
  8820. }
  8821. function Duration(duration) {
  8822. var normalizedInput = normalizeObjectUnits(duration),
  8823. years = normalizedInput.year || 0,
  8824. quarters = normalizedInput.quarter || 0,
  8825. months = normalizedInput.month || 0,
  8826. weeks = normalizedInput.week || normalizedInput.isoWeek || 0,
  8827. days = normalizedInput.day || 0,
  8828. hours = normalizedInput.hour || 0,
  8829. minutes = normalizedInput.minute || 0,
  8830. seconds = normalizedInput.second || 0,
  8831. milliseconds = normalizedInput.millisecond || 0;
  8832. this._isValid = isDurationValid(normalizedInput);
  8833. // representation for dateAddRemove
  8834. this._milliseconds =
  8835. +milliseconds +
  8836. seconds * 1e3 + // 1000
  8837. minutes * 6e4 + // 1000 * 60
  8838. hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978
  8839. // Because of dateAddRemove treats 24 hours as different from a
  8840. // day when working around DST, we need to store them separately
  8841. this._days = +days + weeks * 7;
  8842. // It is impossible to translate months into days without knowing
  8843. // which months you are are talking about, so we have to store
  8844. // it separately.
  8845. this._months = +months + quarters * 3 + years * 12;
  8846. this._data = {};
  8847. this._locale = getLocale();
  8848. this._bubble();
  8849. }
  8850. function isDuration(obj) {
  8851. return obj instanceof Duration;
  8852. }
  8853. function absRound(number) {
  8854. if (number < 0) {
  8855. return Math.round(-1 * number) * -1;
  8856. } else {
  8857. return Math.round(number);
  8858. }
  8859. }
  8860. // compare two arrays, return the number of differences
  8861. function compareArrays(array1, array2, dontConvert) {
  8862. var len = Math.min(array1.length, array2.length),
  8863. lengthDiff = Math.abs(array1.length - array2.length),
  8864. diffs = 0,
  8865. i;
  8866. for (i = 0; i < len; i++) {
  8867. if (
  8868. (dontConvert && array1[i] !== array2[i]) ||
  8869. (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))
  8870. ) {
  8871. diffs++;
  8872. }
  8873. }
  8874. return diffs + lengthDiff;
  8875. }
  8876. // FORMATTING
  8877. function offset(token, separator) {
  8878. addFormatToken(token, 0, 0, function () {
  8879. var offset = this.utcOffset(),
  8880. sign = '+';
  8881. if (offset < 0) {
  8882. offset = -offset;
  8883. sign = '-';
  8884. }
  8885. return (
  8886. sign +
  8887. zeroFill(~~(offset / 60), 2) +
  8888. separator +
  8889. zeroFill(~~offset % 60, 2)
  8890. );
  8891. });
  8892. }
  8893. offset('Z', ':');
  8894. offset('ZZ', '');
  8895. // PARSING
  8896. addRegexToken('Z', matchShortOffset);
  8897. addRegexToken('ZZ', matchShortOffset);
  8898. addParseToken(['Z', 'ZZ'], function (input, array, config) {
  8899. config._useUTC = true;
  8900. config._tzm = offsetFromString(matchShortOffset, input);
  8901. });
  8902. // HELPERS
  8903. // timezone chunker
  8904. // '+10:00' > ['10', '00']
  8905. // '-1530' > ['-15', '30']
  8906. var chunkOffset = /([\+\-]|\d\d)/gi;
  8907. function offsetFromString(matcher, string) {
  8908. var matches = (string || '').match(matcher),
  8909. chunk,
  8910. parts,
  8911. minutes;
  8912. if (matches === null) {
  8913. return null;
  8914. }
  8915. chunk = matches[matches.length - 1] || [];
  8916. parts = (chunk + '').match(chunkOffset) || ['-', 0, 0];
  8917. minutes = +(parts[1] * 60) + toInt(parts[2]);
  8918. return minutes === 0 ? 0 : parts[0] === '+' ? minutes : -minutes;
  8919. }
  8920. // Return a moment from input, that is local/utc/zone equivalent to model.
  8921. function cloneWithOffset(input, model) {
  8922. var res, diff;
  8923. if (model._isUTC) {
  8924. res = model.clone();
  8925. diff =
  8926. (isMoment(input) || isDate(input)
  8927. ? input.valueOf()
  8928. : createLocal(input).valueOf()) - res.valueOf();
  8929. // Use low-level api, because this fn is low-level api.
  8930. res._d.setTime(res._d.valueOf() + diff);
  8931. hooks.updateOffset(res, false);
  8932. return res;
  8933. } else {
  8934. return createLocal(input).local();
  8935. }
  8936. }
  8937. function getDateOffset(m) {
  8938. // On Firefox.24 Date#getTimezoneOffset returns a floating point.
  8939. // https://github.com/moment/moment/pull/1871
  8940. return -Math.round(m._d.getTimezoneOffset());
  8941. }
  8942. // HOOKS
  8943. // This function will be called whenever a moment is mutated.
  8944. // It is intended to keep the offset in sync with the timezone.
  8945. hooks.updateOffset = function () {};
  8946. // MOMENTS
  8947. // keepLocalTime = true means only change the timezone, without
  8948. // affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]-->
  8949. // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset
  8950. // +0200, so we adjust the time as needed, to be valid.
  8951. //
  8952. // Keeping the time actually adds/subtracts (one hour)
  8953. // from the actual represented time. That is why we call updateOffset
  8954. // a second time. In case it wants us to change the offset again
  8955. // _changeInProgress == true case, then we have to adjust, because
  8956. // there is no such time in the given timezone.
  8957. function getSetOffset(input, keepLocalTime, keepMinutes) {
  8958. var offset = this._offset || 0,
  8959. localAdjust;
  8960. if (!this.isValid()) {
  8961. return input != null ? this : NaN;
  8962. }
  8963. if (input != null) {
  8964. if (typeof input === 'string') {
  8965. input = offsetFromString(matchShortOffset, input);
  8966. if (input === null) {
  8967. return this;
  8968. }
  8969. } else if (Math.abs(input) < 16 && !keepMinutes) {
  8970. input = input * 60;
  8971. }
  8972. if (!this._isUTC && keepLocalTime) {
  8973. localAdjust = getDateOffset(this);
  8974. }
  8975. this._offset = input;
  8976. this._isUTC = true;
  8977. if (localAdjust != null) {
  8978. this.add(localAdjust, 'm');
  8979. }
  8980. if (offset !== input) {
  8981. if (!keepLocalTime || this._changeInProgress) {
  8982. addSubtract(
  8983. this,
  8984. createDuration(input - offset, 'm'),
  8985. 1,
  8986. false
  8987. );
  8988. } else if (!this._changeInProgress) {
  8989. this._changeInProgress = true;
  8990. hooks.updateOffset(this, true);
  8991. this._changeInProgress = null;
  8992. }
  8993. }
  8994. return this;
  8995. } else {
  8996. return this._isUTC ? offset : getDateOffset(this);
  8997. }
  8998. }
  8999. function getSetZone(input, keepLocalTime) {
  9000. if (input != null) {
  9001. if (typeof input !== 'string') {
  9002. input = -input;
  9003. }
  9004. this.utcOffset(input, keepLocalTime);
  9005. return this;
  9006. } else {
  9007. return -this.utcOffset();
  9008. }
  9009. }
  9010. function setOffsetToUTC(keepLocalTime) {
  9011. return this.utcOffset(0, keepLocalTime);
  9012. }
  9013. function setOffsetToLocal(keepLocalTime) {
  9014. if (this._isUTC) {
  9015. this.utcOffset(0, keepLocalTime);
  9016. this._isUTC = false;
  9017. if (keepLocalTime) {
  9018. this.subtract(getDateOffset(this), 'm');
  9019. }
  9020. }
  9021. return this;
  9022. }
  9023. function setOffsetToParsedOffset() {
  9024. if (this._tzm != null) {
  9025. this.utcOffset(this._tzm, false, true);
  9026. } else if (typeof this._i === 'string') {
  9027. var tZone = offsetFromString(matchOffset, this._i);
  9028. if (tZone != null) {
  9029. this.utcOffset(tZone);
  9030. } else {
  9031. this.utcOffset(0, true);
  9032. }
  9033. }
  9034. return this;
  9035. }
  9036. function hasAlignedHourOffset(input) {
  9037. if (!this.isValid()) {
  9038. return false;
  9039. }
  9040. input = input ? createLocal(input).utcOffset() : 0;
  9041. return (this.utcOffset() - input) % 60 === 0;
  9042. }
  9043. function isDaylightSavingTime() {
  9044. return (
  9045. this.utcOffset() > this.clone().month(0).utcOffset() ||
  9046. this.utcOffset() > this.clone().month(5).utcOffset()
  9047. );
  9048. }
  9049. function isDaylightSavingTimeShifted() {
  9050. if (!isUndefined(this._isDSTShifted)) {
  9051. return this._isDSTShifted;
  9052. }
  9053. var c = {},
  9054. other;
  9055. copyConfig(c, this);
  9056. c = prepareConfig(c);
  9057. if (c._a) {
  9058. other = c._isUTC ? createUTC(c._a) : createLocal(c._a);
  9059. this._isDSTShifted =
  9060. this.isValid() && compareArrays(c._a, other.toArray()) > 0;
  9061. } else {
  9062. this._isDSTShifted = false;
  9063. }
  9064. return this._isDSTShifted;
  9065. }
  9066. function isLocal() {
  9067. return this.isValid() ? !this._isUTC : false;
  9068. }
  9069. function isUtcOffset() {
  9070. return this.isValid() ? this._isUTC : false;
  9071. }
  9072. function isUtc() {
  9073. return this.isValid() ? this._isUTC && this._offset === 0 : false;
  9074. }
  9075. // ASP.NET json date format regex
  9076. var aspNetRegex = /^(-|\+)?(?:(\d*)[. ])?(\d+):(\d+)(?::(\d+)(\.\d*)?)?$/,
  9077. // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
  9078. // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
  9079. // and further modified to allow for strings containing both week and day
  9080. isoRegex = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;
  9081. function createDuration(input, key) {
  9082. var duration = input,
  9083. // matching against regexp is expensive, do it on demand
  9084. match = null,
  9085. sign,
  9086. ret,
  9087. diffRes;
  9088. if (isDuration(input)) {
  9089. duration = {
  9090. ms: input._milliseconds,
  9091. d: input._days,
  9092. M: input._months,
  9093. };
  9094. } else if (isNumber(input) || !isNaN(+input)) {
  9095. duration = {};
  9096. if (key) {
  9097. duration[key] = +input;
  9098. } else {
  9099. duration.milliseconds = +input;
  9100. }
  9101. } else if ((match = aspNetRegex.exec(input))) {
  9102. sign = match[1] === '-' ? -1 : 1;
  9103. duration = {
  9104. y: 0,
  9105. d: toInt(match[DATE]) * sign,
  9106. h: toInt(match[HOUR]) * sign,
  9107. m: toInt(match[MINUTE]) * sign,
  9108. s: toInt(match[SECOND]) * sign,
  9109. ms: toInt(absRound(match[MILLISECOND] * 1000)) * sign, // the millisecond decimal point is included in the match
  9110. };
  9111. } else if ((match = isoRegex.exec(input))) {
  9112. sign = match[1] === '-' ? -1 : 1;
  9113. duration = {
  9114. y: parseIso(match[2], sign),
  9115. M: parseIso(match[3], sign),
  9116. w: parseIso(match[4], sign),
  9117. d: parseIso(match[5], sign),
  9118. h: parseIso(match[6], sign),
  9119. m: parseIso(match[7], sign),
  9120. s: parseIso(match[8], sign),
  9121. };
  9122. } else if (duration == null) {
  9123. // checks for null or undefined
  9124. duration = {};
  9125. } else if (
  9126. typeof duration === 'object' &&
  9127. ('from' in duration || 'to' in duration)
  9128. ) {
  9129. diffRes = momentsDifference(
  9130. createLocal(duration.from),
  9131. createLocal(duration.to)
  9132. );
  9133. duration = {};
  9134. duration.ms = diffRes.milliseconds;
  9135. duration.M = diffRes.months;
  9136. }
  9137. ret = new Duration(duration);
  9138. if (isDuration(input) && hasOwnProp(input, '_locale')) {
  9139. ret._locale = input._locale;
  9140. }
  9141. if (isDuration(input) && hasOwnProp(input, '_isValid')) {
  9142. ret._isValid = input._isValid;
  9143. }
  9144. return ret;
  9145. }
  9146. createDuration.fn = Duration.prototype;
  9147. createDuration.invalid = createInvalid$1;
  9148. function parseIso(inp, sign) {
  9149. // We'd normally use ~~inp for this, but unfortunately it also
  9150. // converts floats to ints.
  9151. // inp may be undefined, so careful calling replace on it.
  9152. var res = inp && parseFloat(inp.replace(',', '.'));
  9153. // apply sign while we're at it
  9154. return (isNaN(res) ? 0 : res) * sign;
  9155. }
  9156. function positiveMomentsDifference(base, other) {
  9157. var res = {};
  9158. res.months =
  9159. other.month() - base.month() + (other.year() - base.year()) * 12;
  9160. if (base.clone().add(res.months, 'M').isAfter(other)) {
  9161. --res.months;
  9162. }
  9163. res.milliseconds = +other - +base.clone().add(res.months, 'M');
  9164. return res;
  9165. }
  9166. function momentsDifference(base, other) {
  9167. var res;
  9168. if (!(base.isValid() && other.isValid())) {
  9169. return { milliseconds: 0, months: 0 };
  9170. }
  9171. other = cloneWithOffset(other, base);
  9172. if (base.isBefore(other)) {
  9173. res = positiveMomentsDifference(base, other);
  9174. } else {
  9175. res = positiveMomentsDifference(other, base);
  9176. res.milliseconds = -res.milliseconds;
  9177. res.months = -res.months;
  9178. }
  9179. return res;
  9180. }
  9181. // TODO: remove 'name' arg after deprecation is removed
  9182. function createAdder(direction, name) {
  9183. return function (val, period) {
  9184. var dur, tmp;
  9185. //invert the arguments, but complain about it
  9186. if (period !== null && !isNaN(+period)) {
  9187. deprecateSimple(
  9188. name,
  9189. 'moment().' +
  9190. name +
  9191. '(period, number) is deprecated. Please use moment().' +
  9192. name +
  9193. '(number, period). ' +
  9194. 'See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.'
  9195. );
  9196. tmp = val;
  9197. val = period;
  9198. period = tmp;
  9199. }
  9200. dur = createDuration(val, period);
  9201. addSubtract(this, dur, direction);
  9202. return this;
  9203. };
  9204. }
  9205. function addSubtract(mom, duration, isAdding, updateOffset) {
  9206. var milliseconds = duration._milliseconds,
  9207. days = absRound(duration._days),
  9208. months = absRound(duration._months);
  9209. if (!mom.isValid()) {
  9210. // No op
  9211. return;
  9212. }
  9213. updateOffset = updateOffset == null ? true : updateOffset;
  9214. if (months) {
  9215. setMonth(mom, get(mom, 'Month') + months * isAdding);
  9216. }
  9217. if (days) {
  9218. set$1(mom, 'Date', get(mom, 'Date') + days * isAdding);
  9219. }
  9220. if (milliseconds) {
  9221. mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding);
  9222. }
  9223. if (updateOffset) {
  9224. hooks.updateOffset(mom, days || months);
  9225. }
  9226. }
  9227. var add = createAdder(1, 'add'),
  9228. subtract = createAdder(-1, 'subtract');
  9229. function isString(input) {
  9230. return typeof input === 'string' || input instanceof String;
  9231. }
  9232. // type MomentInput = Moment | Date | string | number | (number | string)[] | MomentInputObject | void; // null | undefined
  9233. function isMomentInput(input) {
  9234. return (
  9235. isMoment(input) ||
  9236. isDate(input) ||
  9237. isString(input) ||
  9238. isNumber(input) ||
  9239. isNumberOrStringArray(input) ||
  9240. isMomentInputObject(input) ||
  9241. input === null ||
  9242. input === undefined
  9243. );
  9244. }
  9245. function isMomentInputObject(input) {
  9246. var objectTest = isObject(input) && !isObjectEmpty(input),
  9247. propertyTest = false,
  9248. properties = [
  9249. 'years',
  9250. 'year',
  9251. 'y',
  9252. 'months',
  9253. 'month',
  9254. 'M',
  9255. 'days',
  9256. 'day',
  9257. 'd',
  9258. 'dates',
  9259. 'date',
  9260. 'D',
  9261. 'hours',
  9262. 'hour',
  9263. 'h',
  9264. 'minutes',
  9265. 'minute',
  9266. 'm',
  9267. 'seconds',
  9268. 'second',
  9269. 's',
  9270. 'milliseconds',
  9271. 'millisecond',
  9272. 'ms',
  9273. ],
  9274. i,
  9275. property;
  9276. for (i = 0; i < properties.length; i += 1) {
  9277. property = properties[i];
  9278. propertyTest = propertyTest || hasOwnProp(input, property);
  9279. }
  9280. return objectTest && propertyTest;
  9281. }
  9282. function isNumberOrStringArray(input) {
  9283. var arrayTest = isArray(input),
  9284. dataTypeTest = false;
  9285. if (arrayTest) {
  9286. dataTypeTest =
  9287. input.filter(function (item) {
  9288. return !isNumber(item) && isString(input);
  9289. }).length === 0;
  9290. }
  9291. return arrayTest && dataTypeTest;
  9292. }
  9293. function isCalendarSpec(input) {
  9294. var objectTest = isObject(input) && !isObjectEmpty(input),
  9295. propertyTest = false,
  9296. properties = [
  9297. 'sameDay',
  9298. 'nextDay',
  9299. 'lastDay',
  9300. 'nextWeek',
  9301. 'lastWeek',
  9302. 'sameElse',
  9303. ],
  9304. i,
  9305. property;
  9306. for (i = 0; i < properties.length; i += 1) {
  9307. property = properties[i];
  9308. propertyTest = propertyTest || hasOwnProp(input, property);
  9309. }
  9310. return objectTest && propertyTest;
  9311. }
  9312. function getCalendarFormat(myMoment, now) {
  9313. var diff = myMoment.diff(now, 'days', true);
  9314. return diff < -6
  9315. ? 'sameElse'
  9316. : diff < -1
  9317. ? 'lastWeek'
  9318. : diff < 0
  9319. ? 'lastDay'
  9320. : diff < 1
  9321. ? 'sameDay'
  9322. : diff < 2
  9323. ? 'nextDay'
  9324. : diff < 7
  9325. ? 'nextWeek'
  9326. : 'sameElse';
  9327. }
  9328. function calendar$1(time, formats) {
  9329. // Support for single parameter, formats only overload to the calendar function
  9330. if (arguments.length === 1) {
  9331. if (!arguments[0]) {
  9332. time = undefined;
  9333. formats = undefined;
  9334. } else if (isMomentInput(arguments[0])) {
  9335. time = arguments[0];
  9336. formats = undefined;
  9337. } else if (isCalendarSpec(arguments[0])) {
  9338. formats = arguments[0];
  9339. time = undefined;
  9340. }
  9341. }
  9342. // We want to compare the start of today, vs this.
  9343. // Getting start-of-today depends on whether we're local/utc/offset or not.
  9344. var now = time || createLocal(),
  9345. sod = cloneWithOffset(now, this).startOf('day'),
  9346. format = hooks.calendarFormat(this, sod) || 'sameElse',
  9347. output =
  9348. formats &&
  9349. (isFunction(formats[format])
  9350. ? formats[format].call(this, now)
  9351. : formats[format]);
  9352. return this.format(
  9353. output || this.localeData().calendar(format, this, createLocal(now))
  9354. );
  9355. }
  9356. function clone() {
  9357. return new Moment(this);
  9358. }
  9359. function isAfter(input, units) {
  9360. var localInput = isMoment(input) ? input : createLocal(input);
  9361. if (!(this.isValid() && localInput.isValid())) {
  9362. return false;
  9363. }
  9364. units = normalizeUnits(units) || 'millisecond';
  9365. if (units === 'millisecond') {
  9366. return this.valueOf() > localInput.valueOf();
  9367. } else {
  9368. return localInput.valueOf() < this.clone().startOf(units).valueOf();
  9369. }
  9370. }
  9371. function isBefore(input, units) {
  9372. var localInput = isMoment(input) ? input : createLocal(input);
  9373. if (!(this.isValid() && localInput.isValid())) {
  9374. return false;
  9375. }
  9376. units = normalizeUnits(units) || 'millisecond';
  9377. if (units === 'millisecond') {
  9378. return this.valueOf() < localInput.valueOf();
  9379. } else {
  9380. return this.clone().endOf(units).valueOf() < localInput.valueOf();
  9381. }
  9382. }
  9383. function isBetween(from, to, units, inclusivity) {
  9384. var localFrom = isMoment(from) ? from : createLocal(from),
  9385. localTo = isMoment(to) ? to : createLocal(to);
  9386. if (!(this.isValid() && localFrom.isValid() && localTo.isValid())) {
  9387. return false;
  9388. }
  9389. inclusivity = inclusivity || '()';
  9390. return (
  9391. (inclusivity[0] === '('
  9392. ? this.isAfter(localFrom, units)
  9393. : !this.isBefore(localFrom, units)) &&
  9394. (inclusivity[1] === ')'
  9395. ? this.isBefore(localTo, units)
  9396. : !this.isAfter(localTo, units))
  9397. );
  9398. }
  9399. function isSame(input, units) {
  9400. var localInput = isMoment(input) ? input : createLocal(input),
  9401. inputMs;
  9402. if (!(this.isValid() && localInput.isValid())) {
  9403. return false;
  9404. }
  9405. units = normalizeUnits(units) || 'millisecond';
  9406. if (units === 'millisecond') {
  9407. return this.valueOf() === localInput.valueOf();
  9408. } else {
  9409. inputMs = localInput.valueOf();
  9410. return (
  9411. this.clone().startOf(units).valueOf() <= inputMs &&
  9412. inputMs <= this.clone().endOf(units).valueOf()
  9413. );
  9414. }
  9415. }
  9416. function isSameOrAfter(input, units) {
  9417. return this.isSame(input, units) || this.isAfter(input, units);
  9418. }
  9419. function isSameOrBefore(input, units) {
  9420. return this.isSame(input, units) || this.isBefore(input, units);
  9421. }
  9422. function diff(input, units, asFloat) {
  9423. var that, zoneDelta, output;
  9424. if (!this.isValid()) {
  9425. return NaN;
  9426. }
  9427. that = cloneWithOffset(input, this);
  9428. if (!that.isValid()) {
  9429. return NaN;
  9430. }
  9431. zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4;
  9432. units = normalizeUnits(units);
  9433. switch (units) {
  9434. case 'year':
  9435. output = monthDiff(this, that) / 12;
  9436. break;
  9437. case 'month':
  9438. output = monthDiff(this, that);
  9439. break;
  9440. case 'quarter':
  9441. output = monthDiff(this, that) / 3;
  9442. break;
  9443. case 'second':
  9444. output = (this - that) / 1e3;
  9445. break; // 1000
  9446. case 'minute':
  9447. output = (this - that) / 6e4;
  9448. break; // 1000 * 60
  9449. case 'hour':
  9450. output = (this - that) / 36e5;
  9451. break; // 1000 * 60 * 60
  9452. case 'day':
  9453. output = (this - that - zoneDelta) / 864e5;
  9454. break; // 1000 * 60 * 60 * 24, negate dst
  9455. case 'week':
  9456. output = (this - that - zoneDelta) / 6048e5;
  9457. break; // 1000 * 60 * 60 * 24 * 7, negate dst
  9458. default:
  9459. output = this - that;
  9460. }
  9461. return asFloat ? output : absFloor(output);
  9462. }
  9463. function monthDiff(a, b) {
  9464. if (a.date() < b.date()) {
  9465. // end-of-month calculations work correct when the start month has more
  9466. // days than the end month.
  9467. return -monthDiff(b, a);
  9468. }
  9469. // difference in months
  9470. var wholeMonthDiff = (b.year() - a.year()) * 12 + (b.month() - a.month()),
  9471. // b is in (anchor - 1 month, anchor + 1 month)
  9472. anchor = a.clone().add(wholeMonthDiff, 'months'),
  9473. anchor2,
  9474. adjust;
  9475. if (b - anchor < 0) {
  9476. anchor2 = a.clone().add(wholeMonthDiff - 1, 'months');
  9477. // linear across the month
  9478. adjust = (b - anchor) / (anchor - anchor2);
  9479. } else {
  9480. anchor2 = a.clone().add(wholeMonthDiff + 1, 'months');
  9481. // linear across the month
  9482. adjust = (b - anchor) / (anchor2 - anchor);
  9483. }
  9484. //check for negative zero, return zero if negative zero
  9485. return -(wholeMonthDiff + adjust) || 0;
  9486. }
  9487. hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ';
  9488. hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]';
  9489. function toString() {
  9490. return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ');
  9491. }
  9492. function toISOString(keepOffset) {
  9493. if (!this.isValid()) {
  9494. return null;
  9495. }
  9496. var utc = keepOffset !== true,
  9497. m = utc ? this.clone().utc() : this;
  9498. if (m.year() < 0 || m.year() > 9999) {
  9499. return formatMoment(
  9500. m,
  9501. utc
  9502. ? 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]'
  9503. : 'YYYYYY-MM-DD[T]HH:mm:ss.SSSZ'
  9504. );
  9505. }
  9506. if (isFunction(Date.prototype.toISOString)) {
  9507. // native implementation is ~50x faster, use it when we can
  9508. if (utc) {
  9509. return this.toDate().toISOString();
  9510. } else {
  9511. return new Date(this.valueOf() + this.utcOffset() * 60 * 1000)
  9512. .toISOString()
  9513. .replace('Z', formatMoment(m, 'Z'));
  9514. }
  9515. }
  9516. return formatMoment(
  9517. m,
  9518. utc ? 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYY-MM-DD[T]HH:mm:ss.SSSZ'
  9519. );
  9520. }
  9521. /**
  9522. * Return a human readable representation of a moment that can
  9523. * also be evaluated to get a new moment which is the same
  9524. *
  9525. * @link https://nodejs.org/dist/latest/docs/api/util.html#util_custom_inspect_function_on_objects
  9526. */
  9527. function inspect() {
  9528. if (!this.isValid()) {
  9529. return 'moment.invalid(/* ' + this._i + ' */)';
  9530. }
  9531. var func = 'moment',
  9532. zone = '',
  9533. prefix,
  9534. year,
  9535. datetime,
  9536. suffix;
  9537. if (!this.isLocal()) {
  9538. func = this.utcOffset() === 0 ? 'moment.utc' : 'moment.parseZone';
  9539. zone = 'Z';
  9540. }
  9541. prefix = '[' + func + '("]';
  9542. year = 0 <= this.year() && this.year() <= 9999 ? 'YYYY' : 'YYYYYY';
  9543. datetime = '-MM-DD[T]HH:mm:ss.SSS';
  9544. suffix = zone + '[")]';
  9545. return this.format(prefix + year + datetime + suffix);
  9546. }
  9547. function format(inputString) {
  9548. if (!inputString) {
  9549. inputString = this.isUtc()
  9550. ? hooks.defaultFormatUtc
  9551. : hooks.defaultFormat;
  9552. }
  9553. var output = formatMoment(this, inputString);
  9554. return this.localeData().postformat(output);
  9555. }
  9556. function from(time, withoutSuffix) {
  9557. if (
  9558. this.isValid() &&
  9559. ((isMoment(time) && time.isValid()) || createLocal(time).isValid())
  9560. ) {
  9561. return createDuration({ to: this, from: time })
  9562. .locale(this.locale())
  9563. .humanize(!withoutSuffix);
  9564. } else {
  9565. return this.localeData().invalidDate();
  9566. }
  9567. }
  9568. function fromNow(withoutSuffix) {
  9569. return this.from(createLocal(), withoutSuffix);
  9570. }
  9571. function to(time, withoutSuffix) {
  9572. if (
  9573. this.isValid() &&
  9574. ((isMoment(time) && time.isValid()) || createLocal(time).isValid())
  9575. ) {
  9576. return createDuration({ from: this, to: time })
  9577. .locale(this.locale())
  9578. .humanize(!withoutSuffix);
  9579. } else {
  9580. return this.localeData().invalidDate();
  9581. }
  9582. }
  9583. function toNow(withoutSuffix) {
  9584. return this.to(createLocal(), withoutSuffix);
  9585. }
  9586. // If passed a locale key, it will set the locale for this
  9587. // instance. Otherwise, it will return the locale configuration
  9588. // variables for this instance.
  9589. function locale(key) {
  9590. var newLocaleData;
  9591. if (key === undefined) {
  9592. return this._locale._abbr;
  9593. } else {
  9594. newLocaleData = getLocale(key);
  9595. if (newLocaleData != null) {
  9596. this._locale = newLocaleData;
  9597. }
  9598. return this;
  9599. }
  9600. }
  9601. var lang = deprecate(
  9602. 'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.',
  9603. function (key) {
  9604. if (key === undefined) {
  9605. return this.localeData();
  9606. } else {
  9607. return this.locale(key);
  9608. }
  9609. }
  9610. );
  9611. function localeData() {
  9612. return this._locale;
  9613. }
  9614. var MS_PER_SECOND = 1000,
  9615. MS_PER_MINUTE = 60 * MS_PER_SECOND,
  9616. MS_PER_HOUR = 60 * MS_PER_MINUTE,
  9617. MS_PER_400_YEARS = (365 * 400 + 97) * 24 * MS_PER_HOUR;
  9618. // actual modulo - handles negative numbers (for dates before 1970):
  9619. function mod$1(dividend, divisor) {
  9620. return ((dividend % divisor) + divisor) % divisor;
  9621. }
  9622. function localStartOfDate(y, m, d) {
  9623. // the date constructor remaps years 0-99 to 1900-1999
  9624. if (y < 100 && y >= 0) {
  9625. // preserve leap years using a full 400 year cycle, then reset
  9626. return new Date(y + 400, m, d) - MS_PER_400_YEARS;
  9627. } else {
  9628. return new Date(y, m, d).valueOf();
  9629. }
  9630. }
  9631. function utcStartOfDate(y, m, d) {
  9632. // Date.UTC remaps years 0-99 to 1900-1999
  9633. if (y < 100 && y >= 0) {
  9634. // preserve leap years using a full 400 year cycle, then reset
  9635. return Date.UTC(y + 400, m, d) - MS_PER_400_YEARS;
  9636. } else {
  9637. return Date.UTC(y, m, d);
  9638. }
  9639. }
  9640. function startOf(units) {
  9641. var time, startOfDate;
  9642. units = normalizeUnits(units);
  9643. if (units === undefined || units === 'millisecond' || !this.isValid()) {
  9644. return this;
  9645. }
  9646. startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate;
  9647. switch (units) {
  9648. case 'year':
  9649. time = startOfDate(this.year(), 0, 1);
  9650. break;
  9651. case 'quarter':
  9652. time = startOfDate(
  9653. this.year(),
  9654. this.month() - (this.month() % 3),
  9655. 1
  9656. );
  9657. break;
  9658. case 'month':
  9659. time = startOfDate(this.year(), this.month(), 1);
  9660. break;
  9661. case 'week':
  9662. time = startOfDate(
  9663. this.year(),
  9664. this.month(),
  9665. this.date() - this.weekday()
  9666. );
  9667. break;
  9668. case 'isoWeek':
  9669. time = startOfDate(
  9670. this.year(),
  9671. this.month(),
  9672. this.date() - (this.isoWeekday() - 1)
  9673. );
  9674. break;
  9675. case 'day':
  9676. case 'date':
  9677. time = startOfDate(this.year(), this.month(), this.date());
  9678. break;
  9679. case 'hour':
  9680. time = this._d.valueOf();
  9681. time -= mod$1(
  9682. time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE),
  9683. MS_PER_HOUR
  9684. );
  9685. break;
  9686. case 'minute':
  9687. time = this._d.valueOf();
  9688. time -= mod$1(time, MS_PER_MINUTE);
  9689. break;
  9690. case 'second':
  9691. time = this._d.valueOf();
  9692. time -= mod$1(time, MS_PER_SECOND);
  9693. break;
  9694. }
  9695. this._d.setTime(time);
  9696. hooks.updateOffset(this, true);
  9697. return this;
  9698. }
  9699. function endOf(units) {
  9700. var time, startOfDate;
  9701. units = normalizeUnits(units);
  9702. if (units === undefined || units === 'millisecond' || !this.isValid()) {
  9703. return this;
  9704. }
  9705. startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate;
  9706. switch (units) {
  9707. case 'year':
  9708. time = startOfDate(this.year() + 1, 0, 1) - 1;
  9709. break;
  9710. case 'quarter':
  9711. time =
  9712. startOfDate(
  9713. this.year(),
  9714. this.month() - (this.month() % 3) + 3,
  9715. 1
  9716. ) - 1;
  9717. break;
  9718. case 'month':
  9719. time = startOfDate(this.year(), this.month() + 1, 1) - 1;
  9720. break;
  9721. case 'week':
  9722. time =
  9723. startOfDate(
  9724. this.year(),
  9725. this.month(),
  9726. this.date() - this.weekday() + 7
  9727. ) - 1;
  9728. break;
  9729. case 'isoWeek':
  9730. time =
  9731. startOfDate(
  9732. this.year(),
  9733. this.month(),
  9734. this.date() - (this.isoWeekday() - 1) + 7
  9735. ) - 1;
  9736. break;
  9737. case 'day':
  9738. case 'date':
  9739. time = startOfDate(this.year(), this.month(), this.date() + 1) - 1;
  9740. break;
  9741. case 'hour':
  9742. time = this._d.valueOf();
  9743. time +=
  9744. MS_PER_HOUR -
  9745. mod$1(
  9746. time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE),
  9747. MS_PER_HOUR
  9748. ) -
  9749. 1;
  9750. break;
  9751. case 'minute':
  9752. time = this._d.valueOf();
  9753. time += MS_PER_MINUTE - mod$1(time, MS_PER_MINUTE) - 1;
  9754. break;
  9755. case 'second':
  9756. time = this._d.valueOf();
  9757. time += MS_PER_SECOND - mod$1(time, MS_PER_SECOND) - 1;
  9758. break;
  9759. }
  9760. this._d.setTime(time);
  9761. hooks.updateOffset(this, true);
  9762. return this;
  9763. }
  9764. function valueOf() {
  9765. return this._d.valueOf() - (this._offset || 0) * 60000;
  9766. }
  9767. function unix() {
  9768. return Math.floor(this.valueOf() / 1000);
  9769. }
  9770. function toDate() {
  9771. return new Date(this.valueOf());
  9772. }
  9773. function toArray() {
  9774. var m = this;
  9775. return [
  9776. m.year(),
  9777. m.month(),
  9778. m.date(),
  9779. m.hour(),
  9780. m.minute(),
  9781. m.second(),
  9782. m.millisecond(),
  9783. ];
  9784. }
  9785. function toObject() {
  9786. var m = this;
  9787. return {
  9788. years: m.year(),
  9789. months: m.month(),
  9790. date: m.date(),
  9791. hours: m.hours(),
  9792. minutes: m.minutes(),
  9793. seconds: m.seconds(),
  9794. milliseconds: m.milliseconds(),
  9795. };
  9796. }
  9797. function toJSON() {
  9798. // new Date(NaN).toJSON() === null
  9799. return this.isValid() ? this.toISOString() : null;
  9800. }
  9801. function isValid$2() {
  9802. return isValid(this);
  9803. }
  9804. function parsingFlags() {
  9805. return extend({}, getParsingFlags(this));
  9806. }
  9807. function invalidAt() {
  9808. return getParsingFlags(this).overflow;
  9809. }
  9810. function creationData() {
  9811. return {
  9812. input: this._i,
  9813. format: this._f,
  9814. locale: this._locale,
  9815. isUTC: this._isUTC,
  9816. strict: this._strict,
  9817. };
  9818. }
  9819. addFormatToken('N', 0, 0, 'eraAbbr');
  9820. addFormatToken('NN', 0, 0, 'eraAbbr');
  9821. addFormatToken('NNN', 0, 0, 'eraAbbr');
  9822. addFormatToken('NNNN', 0, 0, 'eraName');
  9823. addFormatToken('NNNNN', 0, 0, 'eraNarrow');
  9824. addFormatToken('y', ['y', 1], 'yo', 'eraYear');
  9825. addFormatToken('y', ['yy', 2], 0, 'eraYear');
  9826. addFormatToken('y', ['yyy', 3], 0, 'eraYear');
  9827. addFormatToken('y', ['yyyy', 4], 0, 'eraYear');
  9828. addRegexToken('N', matchEraAbbr);
  9829. addRegexToken('NN', matchEraAbbr);
  9830. addRegexToken('NNN', matchEraAbbr);
  9831. addRegexToken('NNNN', matchEraName);
  9832. addRegexToken('NNNNN', matchEraNarrow);
  9833. addParseToken(['N', 'NN', 'NNN', 'NNNN', 'NNNNN'], function (
  9834. input,
  9835. array,
  9836. config,
  9837. token
  9838. ) {
  9839. var era = config._locale.erasParse(input, token, config._strict);
  9840. if (era) {
  9841. getParsingFlags(config).era = era;
  9842. } else {
  9843. getParsingFlags(config).invalidEra = input;
  9844. }
  9845. });
  9846. addRegexToken('y', matchUnsigned);
  9847. addRegexToken('yy', matchUnsigned);
  9848. addRegexToken('yyy', matchUnsigned);
  9849. addRegexToken('yyyy', matchUnsigned);
  9850. addRegexToken('yo', matchEraYearOrdinal);
  9851. addParseToken(['y', 'yy', 'yyy', 'yyyy'], YEAR);
  9852. addParseToken(['yo'], function (input, array, config, token) {
  9853. var match;
  9854. if (config._locale._eraYearOrdinalRegex) {
  9855. match = input.match(config._locale._eraYearOrdinalRegex);
  9856. }
  9857. if (config._locale.eraYearOrdinalParse) {
  9858. array[YEAR] = config._locale.eraYearOrdinalParse(input, match);
  9859. } else {
  9860. array[YEAR] = parseInt(input, 10);
  9861. }
  9862. });
  9863. function localeEras(m, format) {
  9864. var i,
  9865. l,
  9866. date,
  9867. eras = this._eras || getLocale('en')._eras;
  9868. for (i = 0, l = eras.length; i < l; ++i) {
  9869. switch (typeof eras[i].since) {
  9870. case 'string':
  9871. // truncate time
  9872. date = hooks(eras[i].since).startOf('day');
  9873. eras[i].since = date.valueOf();
  9874. break;
  9875. }
  9876. switch (typeof eras[i].until) {
  9877. case 'undefined':
  9878. eras[i].until = +Infinity;
  9879. break;
  9880. case 'string':
  9881. // truncate time
  9882. date = hooks(eras[i].until).startOf('day').valueOf();
  9883. eras[i].until = date.valueOf();
  9884. break;
  9885. }
  9886. }
  9887. return eras;
  9888. }
  9889. function localeErasParse(eraName, format, strict) {
  9890. var i,
  9891. l,
  9892. eras = this.eras(),
  9893. name,
  9894. abbr,
  9895. narrow;
  9896. eraName = eraName.toUpperCase();
  9897. for (i = 0, l = eras.length; i < l; ++i) {
  9898. name = eras[i].name.toUpperCase();
  9899. abbr = eras[i].abbr.toUpperCase();
  9900. narrow = eras[i].narrow.toUpperCase();
  9901. if (strict) {
  9902. switch (format) {
  9903. case 'N':
  9904. case 'NN':
  9905. case 'NNN':
  9906. if (abbr === eraName) {
  9907. return eras[i];
  9908. }
  9909. break;
  9910. case 'NNNN':
  9911. if (name === eraName) {
  9912. return eras[i];
  9913. }
  9914. break;
  9915. case 'NNNNN':
  9916. if (narrow === eraName) {
  9917. return eras[i];
  9918. }
  9919. break;
  9920. }
  9921. } else if ([name, abbr, narrow].indexOf(eraName) >= 0) {
  9922. return eras[i];
  9923. }
  9924. }
  9925. }
  9926. function localeErasConvertYear(era, year) {
  9927. var dir = era.since <= era.until ? +1 : -1;
  9928. if (year === undefined) {
  9929. return hooks(era.since).year();
  9930. } else {
  9931. return hooks(era.since).year() + (year - era.offset) * dir;
  9932. }
  9933. }
  9934. function getEraName() {
  9935. var i,
  9936. l,
  9937. val,
  9938. eras = this.localeData().eras();
  9939. for (i = 0, l = eras.length; i < l; ++i) {
  9940. // truncate time
  9941. val = this.clone().startOf('day').valueOf();
  9942. if (eras[i].since <= val && val <= eras[i].until) {
  9943. return eras[i].name;
  9944. }
  9945. if (eras[i].until <= val && val <= eras[i].since) {
  9946. return eras[i].name;
  9947. }
  9948. }
  9949. return '';
  9950. }
  9951. function getEraNarrow() {
  9952. var i,
  9953. l,
  9954. val,
  9955. eras = this.localeData().eras();
  9956. for (i = 0, l = eras.length; i < l; ++i) {
  9957. // truncate time
  9958. val = this.clone().startOf('day').valueOf();
  9959. if (eras[i].since <= val && val <= eras[i].until) {
  9960. return eras[i].narrow;
  9961. }
  9962. if (eras[i].until <= val && val <= eras[i].since) {
  9963. return eras[i].narrow;
  9964. }
  9965. }
  9966. return '';
  9967. }
  9968. function getEraAbbr() {
  9969. var i,
  9970. l,
  9971. val,
  9972. eras = this.localeData().eras();
  9973. for (i = 0, l = eras.length; i < l; ++i) {
  9974. // truncate time
  9975. val = this.clone().startOf('day').valueOf();
  9976. if (eras[i].since <= val && val <= eras[i].until) {
  9977. return eras[i].abbr;
  9978. }
  9979. if (eras[i].until <= val && val <= eras[i].since) {
  9980. return eras[i].abbr;
  9981. }
  9982. }
  9983. return '';
  9984. }
  9985. function getEraYear() {
  9986. var i,
  9987. l,
  9988. dir,
  9989. val,
  9990. eras = this.localeData().eras();
  9991. for (i = 0, l = eras.length; i < l; ++i) {
  9992. dir = eras[i].since <= eras[i].until ? +1 : -1;
  9993. // truncate time
  9994. val = this.clone().startOf('day').valueOf();
  9995. if (
  9996. (eras[i].since <= val && val <= eras[i].until) ||
  9997. (eras[i].until <= val && val <= eras[i].since)
  9998. ) {
  9999. return (
  10000. (this.year() - hooks(eras[i].since).year()) * dir +
  10001. eras[i].offset
  10002. );
  10003. }
  10004. }
  10005. return this.year();
  10006. }
  10007. function erasNameRegex(isStrict) {
  10008. if (!hasOwnProp(this, '_erasNameRegex')) {
  10009. computeErasParse.call(this);
  10010. }
  10011. return isStrict ? this._erasNameRegex : this._erasRegex;
  10012. }
  10013. function erasAbbrRegex(isStrict) {
  10014. if (!hasOwnProp(this, '_erasAbbrRegex')) {
  10015. computeErasParse.call(this);
  10016. }
  10017. return isStrict ? this._erasAbbrRegex : this._erasRegex;
  10018. }
  10019. function erasNarrowRegex(isStrict) {
  10020. if (!hasOwnProp(this, '_erasNarrowRegex')) {
  10021. computeErasParse.call(this);
  10022. }
  10023. return isStrict ? this._erasNarrowRegex : this._erasRegex;
  10024. }
  10025. function matchEraAbbr(isStrict, locale) {
  10026. return locale.erasAbbrRegex(isStrict);
  10027. }
  10028. function matchEraName(isStrict, locale) {
  10029. return locale.erasNameRegex(isStrict);
  10030. }
  10031. function matchEraNarrow(isStrict, locale) {
  10032. return locale.erasNarrowRegex(isStrict);
  10033. }
  10034. function matchEraYearOrdinal(isStrict, locale) {
  10035. return locale._eraYearOrdinalRegex || matchUnsigned;
  10036. }
  10037. function computeErasParse() {
  10038. var abbrPieces = [],
  10039. namePieces = [],
  10040. narrowPieces = [],
  10041. mixedPieces = [],
  10042. i,
  10043. l,
  10044. eras = this.eras();
  10045. for (i = 0, l = eras.length; i < l; ++i) {
  10046. namePieces.push(regexEscape(eras[i].name));
  10047. abbrPieces.push(regexEscape(eras[i].abbr));
  10048. narrowPieces.push(regexEscape(eras[i].narrow));
  10049. mixedPieces.push(regexEscape(eras[i].name));
  10050. mixedPieces.push(regexEscape(eras[i].abbr));
  10051. mixedPieces.push(regexEscape(eras[i].narrow));
  10052. }
  10053. this._erasRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
  10054. this._erasNameRegex = new RegExp('^(' + namePieces.join('|') + ')', 'i');
  10055. this._erasAbbrRegex = new RegExp('^(' + abbrPieces.join('|') + ')', 'i');
  10056. this._erasNarrowRegex = new RegExp(
  10057. '^(' + narrowPieces.join('|') + ')',
  10058. 'i'
  10059. );
  10060. }
  10061. // FORMATTING
  10062. addFormatToken(0, ['gg', 2], 0, function () {
  10063. return this.weekYear() % 100;
  10064. });
  10065. addFormatToken(0, ['GG', 2], 0, function () {
  10066. return this.isoWeekYear() % 100;
  10067. });
  10068. function addWeekYearFormatToken(token, getter) {
  10069. addFormatToken(0, [token, token.length], 0, getter);
  10070. }
  10071. addWeekYearFormatToken('gggg', 'weekYear');
  10072. addWeekYearFormatToken('ggggg', 'weekYear');
  10073. addWeekYearFormatToken('GGGG', 'isoWeekYear');
  10074. addWeekYearFormatToken('GGGGG', 'isoWeekYear');
  10075. // ALIASES
  10076. addUnitAlias('weekYear', 'gg');
  10077. addUnitAlias('isoWeekYear', 'GG');
  10078. // PRIORITY
  10079. addUnitPriority('weekYear', 1);
  10080. addUnitPriority('isoWeekYear', 1);
  10081. // PARSING
  10082. addRegexToken('G', matchSigned);
  10083. addRegexToken('g', matchSigned);
  10084. addRegexToken('GG', match1to2, match2);
  10085. addRegexToken('gg', match1to2, match2);
  10086. addRegexToken('GGGG', match1to4, match4);
  10087. addRegexToken('gggg', match1to4, match4);
  10088. addRegexToken('GGGGG', match1to6, match6);
  10089. addRegexToken('ggggg', match1to6, match6);
  10090. addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function (
  10091. input,
  10092. week,
  10093. config,
  10094. token
  10095. ) {
  10096. week[token.substr(0, 2)] = toInt(input);
  10097. });
  10098. addWeekParseToken(['gg', 'GG'], function (input, week, config, token) {
  10099. week[token] = hooks.parseTwoDigitYear(input);
  10100. });
  10101. // MOMENTS
  10102. function getSetWeekYear(input) {
  10103. return getSetWeekYearHelper.call(
  10104. this,
  10105. input,
  10106. this.week(),
  10107. this.weekday(),
  10108. this.localeData()._week.dow,
  10109. this.localeData()._week.doy
  10110. );
  10111. }
  10112. function getSetISOWeekYear(input) {
  10113. return getSetWeekYearHelper.call(
  10114. this,
  10115. input,
  10116. this.isoWeek(),
  10117. this.isoWeekday(),
  10118. 1,
  10119. 4
  10120. );
  10121. }
  10122. function getISOWeeksInYear() {
  10123. return weeksInYear(this.year(), 1, 4);
  10124. }
  10125. function getISOWeeksInISOWeekYear() {
  10126. return weeksInYear(this.isoWeekYear(), 1, 4);
  10127. }
  10128. function getWeeksInYear() {
  10129. var weekInfo = this.localeData()._week;
  10130. return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
  10131. }
  10132. function getWeeksInWeekYear() {
  10133. var weekInfo = this.localeData()._week;
  10134. return weeksInYear(this.weekYear(), weekInfo.dow, weekInfo.doy);
  10135. }
  10136. function getSetWeekYearHelper(input, week, weekday, dow, doy) {
  10137. var weeksTarget;
  10138. if (input == null) {
  10139. return weekOfYear(this, dow, doy).year;
  10140. } else {
  10141. weeksTarget = weeksInYear(input, dow, doy);
  10142. if (week > weeksTarget) {
  10143. week = weeksTarget;
  10144. }
  10145. return setWeekAll.call(this, input, week, weekday, dow, doy);
  10146. }
  10147. }
  10148. function setWeekAll(weekYear, week, weekday, dow, doy) {
  10149. var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy),
  10150. date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear);
  10151. this.year(date.getUTCFullYear());
  10152. this.month(date.getUTCMonth());
  10153. this.date(date.getUTCDate());
  10154. return this;
  10155. }
  10156. // FORMATTING
  10157. addFormatToken('Q', 0, 'Qo', 'quarter');
  10158. // ALIASES
  10159. addUnitAlias('quarter', 'Q');
  10160. // PRIORITY
  10161. addUnitPriority('quarter', 7);
  10162. // PARSING
  10163. addRegexToken('Q', match1);
  10164. addParseToken('Q', function (input, array) {
  10165. array[MONTH] = (toInt(input) - 1) * 3;
  10166. });
  10167. // MOMENTS
  10168. function getSetQuarter(input) {
  10169. return input == null
  10170. ? Math.ceil((this.month() + 1) / 3)
  10171. : this.month((input - 1) * 3 + (this.month() % 3));
  10172. }
  10173. // FORMATTING
  10174. addFormatToken('D', ['DD', 2], 'Do', 'date');
  10175. // ALIASES
  10176. addUnitAlias('date', 'D');
  10177. // PRIORITY
  10178. addUnitPriority('date', 9);
  10179. // PARSING
  10180. addRegexToken('D', match1to2);
  10181. addRegexToken('DD', match1to2, match2);
  10182. addRegexToken('Do', function (isStrict, locale) {
  10183. // TODO: Remove "ordinalParse" fallback in next major release.
  10184. return isStrict
  10185. ? locale._dayOfMonthOrdinalParse || locale._ordinalParse
  10186. : locale._dayOfMonthOrdinalParseLenient;
  10187. });
  10188. addParseToken(['D', 'DD'], DATE);
  10189. addParseToken('Do', function (input, array) {
  10190. array[DATE] = toInt(input.match(match1to2)[0]);
  10191. });
  10192. // MOMENTS
  10193. var getSetDayOfMonth = makeGetSet('Date', true);
  10194. // FORMATTING
  10195. addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear');
  10196. // ALIASES
  10197. addUnitAlias('dayOfYear', 'DDD');
  10198. // PRIORITY
  10199. addUnitPriority('dayOfYear', 4);
  10200. // PARSING
  10201. addRegexToken('DDD', match1to3);
  10202. addRegexToken('DDDD', match3);
  10203. addParseToken(['DDD', 'DDDD'], function (input, array, config) {
  10204. config._dayOfYear = toInt(input);
  10205. });
  10206. // HELPERS
  10207. // MOMENTS
  10208. function getSetDayOfYear(input) {
  10209. var dayOfYear =
  10210. Math.round(
  10211. (this.clone().startOf('day') - this.clone().startOf('year')) / 864e5
  10212. ) + 1;
  10213. return input == null ? dayOfYear : this.add(input - dayOfYear, 'd');
  10214. }
  10215. // FORMATTING
  10216. addFormatToken('m', ['mm', 2], 0, 'minute');
  10217. // ALIASES
  10218. addUnitAlias('minute', 'm');
  10219. // PRIORITY
  10220. addUnitPriority('minute', 14);
  10221. // PARSING
  10222. addRegexToken('m', match1to2);
  10223. addRegexToken('mm', match1to2, match2);
  10224. addParseToken(['m', 'mm'], MINUTE);
  10225. // MOMENTS
  10226. var getSetMinute = makeGetSet('Minutes', false);
  10227. // FORMATTING
  10228. addFormatToken('s', ['ss', 2], 0, 'second');
  10229. // ALIASES
  10230. addUnitAlias('second', 's');
  10231. // PRIORITY
  10232. addUnitPriority('second', 15);
  10233. // PARSING
  10234. addRegexToken('s', match1to2);
  10235. addRegexToken('ss', match1to2, match2);
  10236. addParseToken(['s', 'ss'], SECOND);
  10237. // MOMENTS
  10238. var getSetSecond = makeGetSet('Seconds', false);
  10239. // FORMATTING
  10240. addFormatToken('S', 0, 0, function () {
  10241. return ~~(this.millisecond() / 100);
  10242. });
  10243. addFormatToken(0, ['SS', 2], 0, function () {
  10244. return ~~(this.millisecond() / 10);
  10245. });
  10246. addFormatToken(0, ['SSS', 3], 0, 'millisecond');
  10247. addFormatToken(0, ['SSSS', 4], 0, function () {
  10248. return this.millisecond() * 10;
  10249. });
  10250. addFormatToken(0, ['SSSSS', 5], 0, function () {
  10251. return this.millisecond() * 100;
  10252. });
  10253. addFormatToken(0, ['SSSSSS', 6], 0, function () {
  10254. return this.millisecond() * 1000;
  10255. });
  10256. addFormatToken(0, ['SSSSSSS', 7], 0, function () {
  10257. return this.millisecond() * 10000;
  10258. });
  10259. addFormatToken(0, ['SSSSSSSS', 8], 0, function () {
  10260. return this.millisecond() * 100000;
  10261. });
  10262. addFormatToken(0, ['SSSSSSSSS', 9], 0, function () {
  10263. return this.millisecond() * 1000000;
  10264. });
  10265. // ALIASES
  10266. addUnitAlias('millisecond', 'ms');
  10267. // PRIORITY
  10268. addUnitPriority('millisecond', 16);
  10269. // PARSING
  10270. addRegexToken('S', match1to3, match1);
  10271. addRegexToken('SS', match1to3, match2);
  10272. addRegexToken('SSS', match1to3, match3);
  10273. var token, getSetMillisecond;
  10274. for (token = 'SSSS'; token.length <= 9; token += 'S') {
  10275. addRegexToken(token, matchUnsigned);
  10276. }
  10277. function parseMs(input, array) {
  10278. array[MILLISECOND] = toInt(('0.' + input) * 1000);
  10279. }
  10280. for (token = 'S'; token.length <= 9; token += 'S') {
  10281. addParseToken(token, parseMs);
  10282. }
  10283. getSetMillisecond = makeGetSet('Milliseconds', false);
  10284. // FORMATTING
  10285. addFormatToken('z', 0, 0, 'zoneAbbr');
  10286. addFormatToken('zz', 0, 0, 'zoneName');
  10287. // MOMENTS
  10288. function getZoneAbbr() {
  10289. return this._isUTC ? 'UTC' : '';
  10290. }
  10291. function getZoneName() {
  10292. return this._isUTC ? 'Coordinated Universal Time' : '';
  10293. }
  10294. var proto = Moment.prototype;
  10295. proto.add = add;
  10296. proto.calendar = calendar$1;
  10297. proto.clone = clone;
  10298. proto.diff = diff;
  10299. proto.endOf = endOf;
  10300. proto.format = format;
  10301. proto.from = from;
  10302. proto.fromNow = fromNow;
  10303. proto.to = to;
  10304. proto.toNow = toNow;
  10305. proto.get = stringGet;
  10306. proto.invalidAt = invalidAt;
  10307. proto.isAfter = isAfter;
  10308. proto.isBefore = isBefore;
  10309. proto.isBetween = isBetween;
  10310. proto.isSame = isSame;
  10311. proto.isSameOrAfter = isSameOrAfter;
  10312. proto.isSameOrBefore = isSameOrBefore;
  10313. proto.isValid = isValid$2;
  10314. proto.lang = lang;
  10315. proto.locale = locale;
  10316. proto.localeData = localeData;
  10317. proto.max = prototypeMax;
  10318. proto.min = prototypeMin;
  10319. proto.parsingFlags = parsingFlags;
  10320. proto.set = stringSet;
  10321. proto.startOf = startOf;
  10322. proto.subtract = subtract;
  10323. proto.toArray = toArray;
  10324. proto.toObject = toObject;
  10325. proto.toDate = toDate;
  10326. proto.toISOString = toISOString;
  10327. proto.inspect = inspect;
  10328. if (typeof Symbol !== 'undefined' && Symbol.for != null) {
  10329. proto[Symbol.for('nodejs.util.inspect.custom')] = function () {
  10330. return 'Moment<' + this.format() + '>';
  10331. };
  10332. }
  10333. proto.toJSON = toJSON;
  10334. proto.toString = toString;
  10335. proto.unix = unix;
  10336. proto.valueOf = valueOf;
  10337. proto.creationData = creationData;
  10338. proto.eraName = getEraName;
  10339. proto.eraNarrow = getEraNarrow;
  10340. proto.eraAbbr = getEraAbbr;
  10341. proto.eraYear = getEraYear;
  10342. proto.year = getSetYear;
  10343. proto.isLeapYear = getIsLeapYear;
  10344. proto.weekYear = getSetWeekYear;
  10345. proto.isoWeekYear = getSetISOWeekYear;
  10346. proto.quarter = proto.quarters = getSetQuarter;
  10347. proto.month = getSetMonth;
  10348. proto.daysInMonth = getDaysInMonth;
  10349. proto.week = proto.weeks = getSetWeek;
  10350. proto.isoWeek = proto.isoWeeks = getSetISOWeek;
  10351. proto.weeksInYear = getWeeksInYear;
  10352. proto.weeksInWeekYear = getWeeksInWeekYear;
  10353. proto.isoWeeksInYear = getISOWeeksInYear;
  10354. proto.isoWeeksInISOWeekYear = getISOWeeksInISOWeekYear;
  10355. proto.date = getSetDayOfMonth;
  10356. proto.day = proto.days = getSetDayOfWeek;
  10357. proto.weekday = getSetLocaleDayOfWeek;
  10358. proto.isoWeekday = getSetISODayOfWeek;
  10359. proto.dayOfYear = getSetDayOfYear;
  10360. proto.hour = proto.hours = getSetHour;
  10361. proto.minute = proto.minutes = getSetMinute;
  10362. proto.second = proto.seconds = getSetSecond;
  10363. proto.millisecond = proto.milliseconds = getSetMillisecond;
  10364. proto.utcOffset = getSetOffset;
  10365. proto.utc = setOffsetToUTC;
  10366. proto.local = setOffsetToLocal;
  10367. proto.parseZone = setOffsetToParsedOffset;
  10368. proto.hasAlignedHourOffset = hasAlignedHourOffset;
  10369. proto.isDST = isDaylightSavingTime;
  10370. proto.isLocal = isLocal;
  10371. proto.isUtcOffset = isUtcOffset;
  10372. proto.isUtc = isUtc;
  10373. proto.isUTC = isUtc;
  10374. proto.zoneAbbr = getZoneAbbr;
  10375. proto.zoneName = getZoneName;
  10376. proto.dates = deprecate(
  10377. 'dates accessor is deprecated. Use date instead.',
  10378. getSetDayOfMonth
  10379. );
  10380. proto.months = deprecate(
  10381. 'months accessor is deprecated. Use month instead',
  10382. getSetMonth
  10383. );
  10384. proto.years = deprecate(
  10385. 'years accessor is deprecated. Use year instead',
  10386. getSetYear
  10387. );
  10388. proto.zone = deprecate(
  10389. 'moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/',
  10390. getSetZone
  10391. );
  10392. proto.isDSTShifted = deprecate(
  10393. 'isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information',
  10394. isDaylightSavingTimeShifted
  10395. );
  10396. function createUnix(input) {
  10397. return createLocal(input * 1000);
  10398. }
  10399. function createInZone() {
  10400. return createLocal.apply(null, arguments).parseZone();
  10401. }
  10402. function preParsePostFormat(string) {
  10403. return string;
  10404. }
  10405. var proto$1 = Locale.prototype;
  10406. proto$1.calendar = calendar;
  10407. proto$1.longDateFormat = longDateFormat;
  10408. proto$1.invalidDate = invalidDate;
  10409. proto$1.ordinal = ordinal;
  10410. proto$1.preparse = preParsePostFormat;
  10411. proto$1.postformat = preParsePostFormat;
  10412. proto$1.relativeTime = relativeTime;
  10413. proto$1.pastFuture = pastFuture;
  10414. proto$1.set = set;
  10415. proto$1.eras = localeEras;
  10416. proto$1.erasParse = localeErasParse;
  10417. proto$1.erasConvertYear = localeErasConvertYear;
  10418. proto$1.erasAbbrRegex = erasAbbrRegex;
  10419. proto$1.erasNameRegex = erasNameRegex;
  10420. proto$1.erasNarrowRegex = erasNarrowRegex;
  10421. proto$1.months = localeMonths;
  10422. proto$1.monthsShort = localeMonthsShort;
  10423. proto$1.monthsParse = localeMonthsParse;
  10424. proto$1.monthsRegex = monthsRegex;
  10425. proto$1.monthsShortRegex = monthsShortRegex;
  10426. proto$1.week = localeWeek;
  10427. proto$1.firstDayOfYear = localeFirstDayOfYear;
  10428. proto$1.firstDayOfWeek = localeFirstDayOfWeek;
  10429. proto$1.weekdays = localeWeekdays;
  10430. proto$1.weekdaysMin = localeWeekdaysMin;
  10431. proto$1.weekdaysShort = localeWeekdaysShort;
  10432. proto$1.weekdaysParse = localeWeekdaysParse;
  10433. proto$1.weekdaysRegex = weekdaysRegex;
  10434. proto$1.weekdaysShortRegex = weekdaysShortRegex;
  10435. proto$1.weekdaysMinRegex = weekdaysMinRegex;
  10436. proto$1.isPM = localeIsPM;
  10437. proto$1.meridiem = localeMeridiem;
  10438. function get$1(format, index, field, setter) {
  10439. var locale = getLocale(),
  10440. utc = createUTC().set(setter, index);
  10441. return locale[field](utc, format);
  10442. }
  10443. function listMonthsImpl(format, index, field) {
  10444. if (isNumber(format)) {
  10445. index = format;
  10446. format = undefined;
  10447. }
  10448. format = format || '';
  10449. if (index != null) {
  10450. return get$1(format, index, field, 'month');
  10451. }
  10452. var i,
  10453. out = [];
  10454. for (i = 0; i < 12; i++) {
  10455. out[i] = get$1(format, i, field, 'month');
  10456. }
  10457. return out;
  10458. }
  10459. // ()
  10460. // (5)
  10461. // (fmt, 5)
  10462. // (fmt)
  10463. // (true)
  10464. // (true, 5)
  10465. // (true, fmt, 5)
  10466. // (true, fmt)
  10467. function listWeekdaysImpl(localeSorted, format, index, field) {
  10468. if (typeof localeSorted === 'boolean') {
  10469. if (isNumber(format)) {
  10470. index = format;
  10471. format = undefined;
  10472. }
  10473. format = format || '';
  10474. } else {
  10475. format = localeSorted;
  10476. index = format;
  10477. localeSorted = false;
  10478. if (isNumber(format)) {
  10479. index = format;
  10480. format = undefined;
  10481. }
  10482. format = format || '';
  10483. }
  10484. var locale = getLocale(),
  10485. shift = localeSorted ? locale._week.dow : 0,
  10486. i,
  10487. out = [];
  10488. if (index != null) {
  10489. return get$1(format, (index + shift) % 7, field, 'day');
  10490. }
  10491. for (i = 0; i < 7; i++) {
  10492. out[i] = get$1(format, (i + shift) % 7, field, 'day');
  10493. }
  10494. return out;
  10495. }
  10496. function listMonths(format, index) {
  10497. return listMonthsImpl(format, index, 'months');
  10498. }
  10499. function listMonthsShort(format, index) {
  10500. return listMonthsImpl(format, index, 'monthsShort');
  10501. }
  10502. function listWeekdays(localeSorted, format, index) {
  10503. return listWeekdaysImpl(localeSorted, format, index, 'weekdays');
  10504. }
  10505. function listWeekdaysShort(localeSorted, format, index) {
  10506. return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort');
  10507. }
  10508. function listWeekdaysMin(localeSorted, format, index) {
  10509. return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin');
  10510. }
  10511. getSetGlobalLocale('en', {
  10512. eras: [
  10513. {
  10514. since: '0001-01-01',
  10515. until: +Infinity,
  10516. offset: 1,
  10517. name: 'Anno Domini',
  10518. narrow: 'AD',
  10519. abbr: 'AD',
  10520. },
  10521. {
  10522. since: '0000-12-31',
  10523. until: -Infinity,
  10524. offset: 1,
  10525. name: 'Before Christ',
  10526. narrow: 'BC',
  10527. abbr: 'BC',
  10528. },
  10529. ],
  10530. dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/,
  10531. ordinal: function (number) {
  10532. var b = number % 10,
  10533. output =
  10534. toInt((number % 100) / 10) === 1
  10535. ? 'th'
  10536. : b === 1
  10537. ? 'st'
  10538. : b === 2
  10539. ? 'nd'
  10540. : b === 3
  10541. ? 'rd'
  10542. : 'th';
  10543. return number + output;
  10544. },
  10545. });
  10546. // Side effect imports
  10547. hooks.lang = deprecate(
  10548. 'moment.lang is deprecated. Use moment.locale instead.',
  10549. getSetGlobalLocale
  10550. );
  10551. hooks.langData = deprecate(
  10552. 'moment.langData is deprecated. Use moment.localeData instead.',
  10553. getLocale
  10554. );
  10555. var mathAbs = Math.abs;
  10556. function abs() {
  10557. var data = this._data;
  10558. this._milliseconds = mathAbs(this._milliseconds);
  10559. this._days = mathAbs(this._days);
  10560. this._months = mathAbs(this._months);
  10561. data.milliseconds = mathAbs(data.milliseconds);
  10562. data.seconds = mathAbs(data.seconds);
  10563. data.minutes = mathAbs(data.minutes);
  10564. data.hours = mathAbs(data.hours);
  10565. data.months = mathAbs(data.months);
  10566. data.years = mathAbs(data.years);
  10567. return this;
  10568. }
  10569. function addSubtract$1(duration, input, value, direction) {
  10570. var other = createDuration(input, value);
  10571. duration._milliseconds += direction * other._milliseconds;
  10572. duration._days += direction * other._days;
  10573. duration._months += direction * other._months;
  10574. return duration._bubble();
  10575. }
  10576. // supports only 2.0-style add(1, 's') or add(duration)
  10577. function add$1(input, value) {
  10578. return addSubtract$1(this, input, value, 1);
  10579. }
  10580. // supports only 2.0-style subtract(1, 's') or subtract(duration)
  10581. function subtract$1(input, value) {
  10582. return addSubtract$1(this, input, value, -1);
  10583. }
  10584. function absCeil(number) {
  10585. if (number < 0) {
  10586. return Math.floor(number);
  10587. } else {
  10588. return Math.ceil(number);
  10589. }
  10590. }
  10591. function bubble() {
  10592. var milliseconds = this._milliseconds,
  10593. days = this._days,
  10594. months = this._months,
  10595. data = this._data,
  10596. seconds,
  10597. minutes,
  10598. hours,
  10599. years,
  10600. monthsFromDays;
  10601. // if we have a mix of positive and negative values, bubble down first
  10602. // check: https://github.com/moment/moment/issues/2166
  10603. if (
  10604. !(
  10605. (milliseconds >= 0 && days >= 0 && months >= 0) ||
  10606. (milliseconds <= 0 && days <= 0 && months <= 0)
  10607. )
  10608. ) {
  10609. milliseconds += absCeil(monthsToDays(months) + days) * 864e5;
  10610. days = 0;
  10611. months = 0;
  10612. }
  10613. // The following code bubbles up values, see the tests for
  10614. // examples of what that means.
  10615. data.milliseconds = milliseconds % 1000;
  10616. seconds = absFloor(milliseconds / 1000);
  10617. data.seconds = seconds % 60;
  10618. minutes = absFloor(seconds / 60);
  10619. data.minutes = minutes % 60;
  10620. hours = absFloor(minutes / 60);
  10621. data.hours = hours % 24;
  10622. days += absFloor(hours / 24);
  10623. // convert days to months
  10624. monthsFromDays = absFloor(daysToMonths(days));
  10625. months += monthsFromDays;
  10626. days -= absCeil(monthsToDays(monthsFromDays));
  10627. // 12 months -> 1 year
  10628. years = absFloor(months / 12);
  10629. months %= 12;
  10630. data.days = days;
  10631. data.months = months;
  10632. data.years = years;
  10633. return this;
  10634. }
  10635. function daysToMonths(days) {
  10636. // 400 years have 146097 days (taking into account leap year rules)
  10637. // 400 years have 12 months === 4800
  10638. return (days * 4800) / 146097;
  10639. }
  10640. function monthsToDays(months) {
  10641. // the reverse of daysToMonths
  10642. return (months * 146097) / 4800;
  10643. }
  10644. function as(units) {
  10645. if (!this.isValid()) {
  10646. return NaN;
  10647. }
  10648. var days,
  10649. months,
  10650. milliseconds = this._milliseconds;
  10651. units = normalizeUnits(units);
  10652. if (units === 'month' || units === 'quarter' || units === 'year') {
  10653. days = this._days + milliseconds / 864e5;
  10654. months = this._months + daysToMonths(days);
  10655. switch (units) {
  10656. case 'month':
  10657. return months;
  10658. case 'quarter':
  10659. return months / 3;
  10660. case 'year':
  10661. return months / 12;
  10662. }
  10663. } else {
  10664. // handle milliseconds separately because of floating point math errors (issue #1867)
  10665. days = this._days + Math.round(monthsToDays(this._months));
  10666. switch (units) {
  10667. case 'week':
  10668. return days / 7 + milliseconds / 6048e5;
  10669. case 'day':
  10670. return days + milliseconds / 864e5;
  10671. case 'hour':
  10672. return days * 24 + milliseconds / 36e5;
  10673. case 'minute':
  10674. return days * 1440 + milliseconds / 6e4;
  10675. case 'second':
  10676. return days * 86400 + milliseconds / 1000;
  10677. // Math.floor prevents floating point math errors here
  10678. case 'millisecond':
  10679. return Math.floor(days * 864e5) + milliseconds;
  10680. default:
  10681. throw new Error('Unknown unit ' + units);
  10682. }
  10683. }
  10684. }
  10685. // TODO: Use this.as('ms')?
  10686. function valueOf$1() {
  10687. if (!this.isValid()) {
  10688. return NaN;
  10689. }
  10690. return (
  10691. this._milliseconds +
  10692. this._days * 864e5 +
  10693. (this._months % 12) * 2592e6 +
  10694. toInt(this._months / 12) * 31536e6
  10695. );
  10696. }
  10697. function makeAs(alias) {
  10698. return function () {
  10699. return this.as(alias);
  10700. };
  10701. }
  10702. var asMilliseconds = makeAs('ms'),
  10703. asSeconds = makeAs('s'),
  10704. asMinutes = makeAs('m'),
  10705. asHours = makeAs('h'),
  10706. asDays = makeAs('d'),
  10707. asWeeks = makeAs('w'),
  10708. asMonths = makeAs('M'),
  10709. asQuarters = makeAs('Q'),
  10710. asYears = makeAs('y');
  10711. function clone$1() {
  10712. return createDuration(this);
  10713. }
  10714. function get$2(units) {
  10715. units = normalizeUnits(units);
  10716. return this.isValid() ? this[units + 's']() : NaN;
  10717. }
  10718. function makeGetter(name) {
  10719. return function () {
  10720. return this.isValid() ? this._data[name] : NaN;
  10721. };
  10722. }
  10723. var milliseconds = makeGetter('milliseconds'),
  10724. seconds = makeGetter('seconds'),
  10725. minutes = makeGetter('minutes'),
  10726. hours = makeGetter('hours'),
  10727. days = makeGetter('days'),
  10728. months = makeGetter('months'),
  10729. years = makeGetter('years');
  10730. function weeks() {
  10731. return absFloor(this.days() / 7);
  10732. }
  10733. var round = Math.round,
  10734. thresholds = {
  10735. ss: 44, // a few seconds to seconds
  10736. s: 45, // seconds to minute
  10737. m: 45, // minutes to hour
  10738. h: 22, // hours to day
  10739. d: 26, // days to month/week
  10740. w: null, // weeks to month
  10741. M: 11, // months to year
  10742. };
  10743. // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
  10744. function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) {
  10745. return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
  10746. }
  10747. function relativeTime$1(posNegDuration, withoutSuffix, thresholds, locale) {
  10748. var duration = createDuration(posNegDuration).abs(),
  10749. seconds = round(duration.as('s')),
  10750. minutes = round(duration.as('m')),
  10751. hours = round(duration.as('h')),
  10752. days = round(duration.as('d')),
  10753. months = round(duration.as('M')),
  10754. weeks = round(duration.as('w')),
  10755. years = round(duration.as('y')),
  10756. a =
  10757. (seconds <= thresholds.ss && ['s', seconds]) ||
  10758. (seconds < thresholds.s && ['ss', seconds]) ||
  10759. (minutes <= 1 && ['m']) ||
  10760. (minutes < thresholds.m && ['mm', minutes]) ||
  10761. (hours <= 1 && ['h']) ||
  10762. (hours < thresholds.h && ['hh', hours]) ||
  10763. (days <= 1 && ['d']) ||
  10764. (days < thresholds.d && ['dd', days]);
  10765. if (thresholds.w != null) {
  10766. a =
  10767. a ||
  10768. (weeks <= 1 && ['w']) ||
  10769. (weeks < thresholds.w && ['ww', weeks]);
  10770. }
  10771. a = a ||
  10772. (months <= 1 && ['M']) ||
  10773. (months < thresholds.M && ['MM', months]) ||
  10774. (years <= 1 && ['y']) || ['yy', years];
  10775. a[2] = withoutSuffix;
  10776. a[3] = +posNegDuration > 0;
  10777. a[4] = locale;
  10778. return substituteTimeAgo.apply(null, a);
  10779. }
  10780. // This function allows you to set the rounding function for relative time strings
  10781. function getSetRelativeTimeRounding(roundingFunction) {
  10782. if (roundingFunction === undefined) {
  10783. return round;
  10784. }
  10785. if (typeof roundingFunction === 'function') {
  10786. round = roundingFunction;
  10787. return true;
  10788. }
  10789. return false;
  10790. }
  10791. // This function allows you to set a threshold for relative time strings
  10792. function getSetRelativeTimeThreshold(threshold, limit) {
  10793. if (thresholds[threshold] === undefined) {
  10794. return false;
  10795. }
  10796. if (limit === undefined) {
  10797. return thresholds[threshold];
  10798. }
  10799. thresholds[threshold] = limit;
  10800. if (threshold === 's') {
  10801. thresholds.ss = limit - 1;
  10802. }
  10803. return true;
  10804. }
  10805. function humanize(argWithSuffix, argThresholds) {
  10806. if (!this.isValid()) {
  10807. return this.localeData().invalidDate();
  10808. }
  10809. var withSuffix = false,
  10810. th = thresholds,
  10811. locale,
  10812. output;
  10813. if (typeof argWithSuffix === 'object') {
  10814. argThresholds = argWithSuffix;
  10815. argWithSuffix = false;
  10816. }
  10817. if (typeof argWithSuffix === 'boolean') {
  10818. withSuffix = argWithSuffix;
  10819. }
  10820. if (typeof argThresholds === 'object') {
  10821. th = Object.assign({}, thresholds, argThresholds);
  10822. if (argThresholds.s != null && argThresholds.ss == null) {
  10823. th.ss = argThresholds.s - 1;
  10824. }
  10825. }
  10826. locale = this.localeData();
  10827. output = relativeTime$1(this, !withSuffix, th, locale);
  10828. if (withSuffix) {
  10829. output = locale.pastFuture(+this, output);
  10830. }
  10831. return locale.postformat(output);
  10832. }
  10833. var abs$1 = Math.abs;
  10834. function sign(x) {
  10835. return (x > 0) - (x < 0) || +x;
  10836. }
  10837. function toISOString$1() {
  10838. // for ISO strings we do not use the normal bubbling rules:
  10839. // * milliseconds bubble up until they become hours
  10840. // * days do not bubble at all
  10841. // * months bubble up until they become years
  10842. // This is because there is no context-free conversion between hours and days
  10843. // (think of clock changes)
  10844. // and also not between days and months (28-31 days per month)
  10845. if (!this.isValid()) {
  10846. return this.localeData().invalidDate();
  10847. }
  10848. var seconds = abs$1(this._milliseconds) / 1000,
  10849. days = abs$1(this._days),
  10850. months = abs$1(this._months),
  10851. minutes,
  10852. hours,
  10853. years,
  10854. s,
  10855. total = this.asSeconds(),
  10856. totalSign,
  10857. ymSign,
  10858. daysSign,
  10859. hmsSign;
  10860. if (!total) {
  10861. // this is the same as C#'s (Noda) and python (isodate)...
  10862. // but not other JS (goog.date)
  10863. return 'P0D';
  10864. }
  10865. // 3600 seconds -> 60 minutes -> 1 hour
  10866. minutes = absFloor(seconds / 60);
  10867. hours = absFloor(minutes / 60);
  10868. seconds %= 60;
  10869. minutes %= 60;
  10870. // 12 months -> 1 year
  10871. years = absFloor(months / 12);
  10872. months %= 12;
  10873. // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
  10874. s = seconds ? seconds.toFixed(3).replace(/\.?0+$/, '') : '';
  10875. totalSign = total < 0 ? '-' : '';
  10876. ymSign = sign(this._months) !== sign(total) ? '-' : '';
  10877. daysSign = sign(this._days) !== sign(total) ? '-' : '';
  10878. hmsSign = sign(this._milliseconds) !== sign(total) ? '-' : '';
  10879. return (
  10880. totalSign +
  10881. 'P' +
  10882. (years ? ymSign + years + 'Y' : '') +
  10883. (months ? ymSign + months + 'M' : '') +
  10884. (days ? daysSign + days + 'D' : '') +
  10885. (hours || minutes || seconds ? 'T' : '') +
  10886. (hours ? hmsSign + hours + 'H' : '') +
  10887. (minutes ? hmsSign + minutes + 'M' : '') +
  10888. (seconds ? hmsSign + s + 'S' : '')
  10889. );
  10890. }
  10891. var proto$2 = Duration.prototype;
  10892. proto$2.isValid = isValid$1;
  10893. proto$2.abs = abs;
  10894. proto$2.add = add$1;
  10895. proto$2.subtract = subtract$1;
  10896. proto$2.as = as;
  10897. proto$2.asMilliseconds = asMilliseconds;
  10898. proto$2.asSeconds = asSeconds;
  10899. proto$2.asMinutes = asMinutes;
  10900. proto$2.asHours = asHours;
  10901. proto$2.asDays = asDays;
  10902. proto$2.asWeeks = asWeeks;
  10903. proto$2.asMonths = asMonths;
  10904. proto$2.asQuarters = asQuarters;
  10905. proto$2.asYears = asYears;
  10906. proto$2.valueOf = valueOf$1;
  10907. proto$2._bubble = bubble;
  10908. proto$2.clone = clone$1;
  10909. proto$2.get = get$2;
  10910. proto$2.milliseconds = milliseconds;
  10911. proto$2.seconds = seconds;
  10912. proto$2.minutes = minutes;
  10913. proto$2.hours = hours;
  10914. proto$2.days = days;
  10915. proto$2.weeks = weeks;
  10916. proto$2.months = months;
  10917. proto$2.years = years;
  10918. proto$2.humanize = humanize;
  10919. proto$2.toISOString = toISOString$1;
  10920. proto$2.toString = toISOString$1;
  10921. proto$2.toJSON = toISOString$1;
  10922. proto$2.locale = locale;
  10923. proto$2.localeData = localeData;
  10924. proto$2.toIsoString = deprecate(
  10925. 'toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)',
  10926. toISOString$1
  10927. );
  10928. proto$2.lang = lang;
  10929. // FORMATTING
  10930. addFormatToken('X', 0, 0, 'unix');
  10931. addFormatToken('x', 0, 0, 'valueOf');
  10932. // PARSING
  10933. addRegexToken('x', matchSigned);
  10934. addRegexToken('X', matchTimestamp);
  10935. addParseToken('X', function (input, array, config) {
  10936. config._d = new Date(parseFloat(input) * 1000);
  10937. });
  10938. addParseToken('x', function (input, array, config) {
  10939. config._d = new Date(toInt(input));
  10940. });
  10941. //! moment.js
  10942. hooks.version = '2.29.1';
  10943. setHookCallback(createLocal);
  10944. hooks.fn = proto;
  10945. hooks.min = min;
  10946. hooks.max = max;
  10947. hooks.now = now;
  10948. hooks.utc = createUTC;
  10949. hooks.unix = createUnix;
  10950. hooks.months = listMonths;
  10951. hooks.isDate = isDate;
  10952. hooks.locale = getSetGlobalLocale;
  10953. hooks.invalid = createInvalid;
  10954. hooks.duration = createDuration;
  10955. hooks.isMoment = isMoment;
  10956. hooks.weekdays = listWeekdays;
  10957. hooks.parseZone = createInZone;
  10958. hooks.localeData = getLocale;
  10959. hooks.isDuration = isDuration;
  10960. hooks.monthsShort = listMonthsShort;
  10961. hooks.weekdaysMin = listWeekdaysMin;
  10962. hooks.defineLocale = defineLocale;
  10963. hooks.updateLocale = updateLocale;
  10964. hooks.locales = listLocales;
  10965. hooks.weekdaysShort = listWeekdaysShort;
  10966. hooks.normalizeUnits = normalizeUnits;
  10967. hooks.relativeTimeRounding = getSetRelativeTimeRounding;
  10968. hooks.relativeTimeThreshold = getSetRelativeTimeThreshold;
  10969. hooks.calendarFormat = getCalendarFormat;
  10970. hooks.prototype = proto;
  10971. // currently HTML5 input type only supports 24-hour formats
  10972. hooks.HTML5_FMT = {
  10973. DATETIME_LOCAL: 'YYYY-MM-DDTHH:mm', // <input type="datetime-local" />
  10974. DATETIME_LOCAL_SECONDS: 'YYYY-MM-DDTHH:mm:ss', // <input type="datetime-local" step="1" />
  10975. DATETIME_LOCAL_MS: 'YYYY-MM-DDTHH:mm:ss.SSS', // <input type="datetime-local" step="0.001" />
  10976. DATE: 'YYYY-MM-DD', // <input type="date" />
  10977. TIME: 'HH:mm', // <input type="time" />
  10978. TIME_SECONDS: 'HH:mm:ss', // <input type="time" step="1" />
  10979. TIME_MS: 'HH:mm:ss.SSS', // <input type="time" step="0.001" />
  10980. WEEK: 'GGGG-[W]WW', // <input type="week" />
  10981. MONTH: 'YYYY-MM', // <input type="month" />
  10982. };
  10983. return hooks;
  10984. })));
  10985. }, "E:/elixir/production_A/bbhverse/node_modules/moment");
  10986. let array8 = arrayUntyped,
  10987. array16 = arrayUntyped,
  10988. array32 = arrayUntyped,
  10989. arrayLengthen = arrayLengthenUntyped,
  10990. arrayWiden = arrayWidenUntyped;
  10991. if (typeof Uint8Array !== "undefined") {
  10992. array8 = function(n) { return new Uint8Array(n); };
  10993. array16 = function(n) { return new Uint16Array(n); };
  10994. array32 = function(n) { return new Uint32Array(n); };
  10995. arrayLengthen = function(array, length) {
  10996. if (array.length >= length) return array;
  10997. var copy = new array.constructor(length);
  10998. copy.set(array);
  10999. return copy;
  11000. };
  11001. arrayWiden = function(array, width) {
  11002. var copy;
  11003. switch (width) {
  11004. case 16: copy = array16(array.length); break;
  11005. case 32: copy = array32(array.length); break;
  11006. default: throw new Error("invalid array width!");
  11007. }
  11008. copy.set(array);
  11009. return copy;
  11010. };
  11011. }
  11012. function arrayUntyped(n) {
  11013. var array = new Array(n), i = -1;
  11014. while (++i < n) array[i] = 0;
  11015. return array;
  11016. }
  11017. function arrayLengthenUntyped(array, length) {
  11018. var n = array.length;
  11019. while (n < length) array[n++] = 0;
  11020. return array;
  11021. }
  11022. function arrayWidenUntyped(array, width) {
  11023. if (width > 32) throw new Error("invalid array width!");
  11024. return array;
  11025. }
  11026. // An arbitrarily-wide array of bitmasks
  11027. function bitarray(n) {
  11028. this.length = n;
  11029. this.subarrays = 1;
  11030. this.width = 8;
  11031. this.masks = {
  11032. 0: 0
  11033. };
  11034. this[0] = array8(n);
  11035. }
  11036. bitarray.prototype.lengthen = function(n) {
  11037. var i, len;
  11038. for (i = 0, len = this.subarrays; i < len; ++i) {
  11039. this[i] = arrayLengthen(this[i], n);
  11040. }
  11041. this.length = n;
  11042. };
  11043. // Reserve a new bit index in the array, returns {offset, one}
  11044. bitarray.prototype.add = function() {
  11045. var m, w, one, i, len;
  11046. for (i = 0, len = this.subarrays; i < len; ++i) {
  11047. m = this.masks[i];
  11048. w = this.width - (32 * i);
  11049. // isolate the rightmost zero bit and return it as an unsigned int of 32 bits, if NaN or -1, return a 0
  11050. one = (~m & (m + 1)) >>> 0;
  11051. if (w >= 32 && !one) {
  11052. continue;
  11053. }
  11054. if (w < 32 && (one & (1 << w))) {
  11055. // widen this subarray
  11056. this[i] = arrayWiden(this[i], w <<= 1);
  11057. this.width = 32 * i + w;
  11058. }
  11059. this.masks[i] |= one;
  11060. return {
  11061. offset: i,
  11062. one: one
  11063. };
  11064. }
  11065. // add a new subarray
  11066. this[this.subarrays] = array8(this.length);
  11067. this.masks[this.subarrays] = 1;
  11068. this.width += 8;
  11069. return {
  11070. offset: this.subarrays++,
  11071. one: 1
  11072. };
  11073. };
  11074. // Copy record from index src to index dest
  11075. bitarray.prototype.copy = function(dest, src) {
  11076. var i, len;
  11077. for (i = 0, len = this.subarrays; i < len; ++i) {
  11078. this[i][dest] = this[i][src];
  11079. }
  11080. };
  11081. // Truncate the array to the given length
  11082. bitarray.prototype.truncate = function(n) {
  11083. var i, len;
  11084. for (i = 0, len = this.subarrays; i < len; ++i) {
  11085. for (var j = this.length - 1; j >= n; j--) {
  11086. this[i][j] = 0;
  11087. }
  11088. }
  11089. this.length = n;
  11090. };
  11091. // Checks that all bits for the given index are 0
  11092. bitarray.prototype.zero = function(n) {
  11093. var i, len;
  11094. for (i = 0, len = this.subarrays; i < len; ++i) {
  11095. if (this[i][n]) {
  11096. return false;
  11097. }
  11098. }
  11099. return true;
  11100. };
  11101. // Checks that all bits for the given index are 0 except for possibly one
  11102. bitarray.prototype.zeroExcept = function(n, offset, zero) {
  11103. var i, len;
  11104. for (i = 0, len = this.subarrays; i < len; ++i) {
  11105. if (i === offset ? this[i][n] & zero : this[i][n]) {
  11106. return false;
  11107. }
  11108. }
  11109. return true;
  11110. };
  11111. // Checks that all bits for the given index are 0 except for the specified mask.
  11112. // The mask should be an array of the same size as the filter subarrays width.
  11113. bitarray.prototype.zeroExceptMask = function(n, mask) {
  11114. var i, len;
  11115. for (i = 0, len = this.subarrays; i < len; ++i) {
  11116. if (this[i][n] & mask[i]) {
  11117. return false;
  11118. }
  11119. }
  11120. return true;
  11121. };
  11122. // Checks that only the specified bit is set for the given index
  11123. bitarray.prototype.only = function(n, offset, one) {
  11124. var i, len;
  11125. for (i = 0, len = this.subarrays; i < len; ++i) {
  11126. if (this[i][n] != (i === offset ? one : 0)) {
  11127. return false;
  11128. }
  11129. }
  11130. return true;
  11131. };
  11132. // Checks that only the specified bit is set for the given index except for possibly one other
  11133. bitarray.prototype.onlyExcept = function(n, offset, zero, onlyOffset, onlyOne) {
  11134. var mask;
  11135. var i, len;
  11136. for (i = 0, len = this.subarrays; i < len; ++i) {
  11137. mask = this[i][n];
  11138. if (i === offset)
  11139. mask = (mask & zero) >>> 0;
  11140. if (mask != (i === onlyOffset ? onlyOne : 0)) {
  11141. return false;
  11142. }
  11143. }
  11144. return true;
  11145. };
  11146. var xfilterArray = {
  11147. array8: arrayUntyped,
  11148. array16: arrayUntyped,
  11149. array32: arrayUntyped,
  11150. arrayLengthen: arrayLengthenUntyped,
  11151. arrayWiden: arrayWidenUntyped,
  11152. bitarray: bitarray
  11153. };
  11154. const filterExact = (bisect, value) => {
  11155. return function(values) {
  11156. var n = values.length;
  11157. return [bisect.left(values, value, 0, n), bisect.right(values, value, 0, n)];
  11158. };
  11159. };
  11160. const filterRange = (bisect, range) => {
  11161. var min = range[0],
  11162. max = range[1];
  11163. return function(values) {
  11164. var n = values.length;
  11165. return [bisect.left(values, min, 0, n), bisect.left(values, max, 0, n)];
  11166. };
  11167. };
  11168. const filterAll = values => {
  11169. return [0, values.length];
  11170. };
  11171. var xfilterFilter = {
  11172. filterExact,
  11173. filterRange,
  11174. filterAll
  11175. };
  11176. var cr_identity = d => {
  11177. return d;
  11178. };
  11179. var cr_null = () => {
  11180. return null;
  11181. };
  11182. var cr_zero = () => {
  11183. return 0;
  11184. };
  11185. function heap_by(f) {
  11186. // Builds a binary heap within the specified array a[lo:hi]. The heap has the
  11187. // property such that the parent a[lo+i] is always less than or equal to its
  11188. // two children: a[lo+2*i+1] and a[lo+2*i+2].
  11189. function heap(a, lo, hi) {
  11190. var n = hi - lo,
  11191. i = (n >>> 1) + 1;
  11192. while (--i > 0) sift(a, i, n, lo);
  11193. return a;
  11194. }
  11195. // Sorts the specified array a[lo:hi] in descending order, assuming it is
  11196. // already a heap.
  11197. function sort(a, lo, hi) {
  11198. var n = hi - lo,
  11199. t;
  11200. while (--n > 0) t = a[lo], a[lo] = a[lo + n], a[lo + n] = t, sift(a, 1, n, lo);
  11201. return a;
  11202. }
  11203. // Sifts the element a[lo+i-1] down the heap, where the heap is the contiguous
  11204. // slice of array a[lo:lo+n]. This method can also be used to update the heap
  11205. // incrementally, without incurring the full cost of reconstructing the heap.
  11206. function sift(a, i, n, lo) {
  11207. var d = a[--lo + i],
  11208. x = f(d),
  11209. child;
  11210. while ((child = i << 1) <= n) {
  11211. if (child < n && f(a[lo + child]) > f(a[lo + child + 1])) child++;
  11212. if (x <= f(a[lo + child])) break;
  11213. a[lo + i] = a[lo + child];
  11214. i = child;
  11215. }
  11216. a[lo + i] = d;
  11217. }
  11218. heap.sort = sort;
  11219. return heap;
  11220. }
  11221. const h$1 = heap_by(cr_identity);
  11222. h$1.by = heap_by;
  11223. function heapselect_by(f) {
  11224. var heap = h$1.by(f);
  11225. // Returns a new array containing the top k elements in the array a[lo:hi].
  11226. // The returned array is not sorted, but maintains the heap property. If k is
  11227. // greater than hi - lo, then fewer than k elements will be returned. The
  11228. // order of elements in a is unchanged by this operation.
  11229. function heapselect(a, lo, hi, k) {
  11230. var queue = new Array(k = Math.min(hi - lo, k)),
  11231. min,
  11232. i,
  11233. d;
  11234. for (i = 0; i < k; ++i) queue[i] = a[lo++];
  11235. heap(queue, 0, k);
  11236. if (lo < hi) {
  11237. min = f(queue[0]);
  11238. do {
  11239. if (f(d = a[lo]) > min) {
  11240. queue[0] = d;
  11241. min = f(heap(queue, 0, k)[0]);
  11242. }
  11243. } while (++lo < hi);
  11244. }
  11245. return queue;
  11246. }
  11247. return heapselect;
  11248. }
  11249. const h = heapselect_by(cr_identity);
  11250. h.by = heapselect_by; // assign the raw function to the export as well
  11251. function bisect_by(f) {
  11252. // Locate the insertion point for x in a to maintain sorted order. The
  11253. // arguments lo and hi may be used to specify a subset of the array which
  11254. // should be considered; by default the entire array is used. If x is already
  11255. // present in a, the insertion point will be before (to the left of) any
  11256. // existing entries. The return value is suitable for use as the first
  11257. // argument to `array.splice` assuming that a is already sorted.
  11258. //
  11259. // The returned insertion point i partitions the array a into two halves so
  11260. // that all v < x for v in a[lo:i] for the left side and all v >= x for v in
  11261. // a[i:hi] for the right side.
  11262. function bisectLeft(a, x, lo, hi) {
  11263. while (lo < hi) {
  11264. var mid = lo + hi >>> 1;
  11265. if (f(a[mid]) < x) lo = mid + 1;
  11266. else hi = mid;
  11267. }
  11268. return lo;
  11269. }
  11270. // Similar to bisectLeft, but returns an insertion point which comes after (to
  11271. // the right of) any existing entries of x in a.
  11272. //
  11273. // The returned insertion point i partitions the array into two halves so that
  11274. // all v <= x for v in a[lo:i] for the left side and all v > x for v in
  11275. // a[i:hi] for the right side.
  11276. function bisectRight(a, x, lo, hi) {
  11277. while (lo < hi) {
  11278. var mid = lo + hi >>> 1;
  11279. if (x < f(a[mid])) hi = mid;
  11280. else lo = mid + 1;
  11281. }
  11282. return lo;
  11283. }
  11284. bisectRight.right = bisectRight;
  11285. bisectRight.left = bisectLeft;
  11286. return bisectRight;
  11287. }
  11288. const bisect = bisect_by(cr_identity);
  11289. bisect.by = bisect_by; // assign the raw function to the export as well
  11290. var permute = (array, index, deep) => {
  11291. for (var i = 0, n = index.length, copy = deep ? JSON.parse(JSON.stringify(array)) : new Array(n); i < n; ++i) {
  11292. copy[i] = array[index[i]];
  11293. }
  11294. return copy;
  11295. };
  11296. const reduceIncrement = p => {
  11297. return p + 1;
  11298. };
  11299. const reduceDecrement = p => {
  11300. return p - 1;
  11301. };
  11302. const reduceAdd = f => {
  11303. return function(p, v) {
  11304. return p + +f(v);
  11305. };
  11306. };
  11307. const reduceSubtract = f => {
  11308. return function(p, v) {
  11309. return p - f(v);
  11310. };
  11311. };
  11312. var xfilterReduce = {
  11313. reduceIncrement,
  11314. reduceDecrement,
  11315. reduceAdd,
  11316. reduceSubtract
  11317. };
  11318. 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)}
  11319. // Note(cg): result was previsouly using lodash.result, not ESM compatible.
  11320. const get = (obj, prop) => {
  11321. const value = obj[prop];
  11322. return (typeof value === 'function') ? value.call(obj) : value;
  11323. };
  11324. /**
  11325. * get value of object at a deep path.
  11326. * if the resolved value is a function,
  11327. * it's invoked with the `this` binding of
  11328. * its parent object and its result is returned.
  11329. *
  11330. * @param {Object} obj the object (e.g. { 'a': [{ 'b': { 'c1': 3, 'c2': 4} }], 'd': {e:1} }; )
  11331. * @param {String} path deep path (e.g. `d.e`` or `a[0].b.c1`. Dot notation (a.0.b)is also supported)
  11332. * @return {Any} the resolved value
  11333. */
  11334. const reg = /\[([\w\d]+)\]/g;
  11335. var result = (obj, path) => {
  11336. return deep(get, obj, path.replace(reg, '.$1'))
  11337. };
  11338. // constants
  11339. var REMOVED_INDEX = -1;
  11340. crossfilter$1.heap = h$1;
  11341. crossfilter$1.heapselect = h;
  11342. crossfilter$1.bisect = bisect;
  11343. crossfilter$1.permute = permute;
  11344. function crossfilter$1() {
  11345. var crossfilter = {
  11346. add: add,
  11347. remove: removeData,
  11348. dimension: dimension,
  11349. groupAll: groupAll,
  11350. size: size,
  11351. all: all,
  11352. allFiltered: allFiltered,
  11353. onChange: onChange,
  11354. isElementFiltered: isElementFiltered
  11355. };
  11356. var data = [], // the records
  11357. n = 0, // the number of records; data.length
  11358. filters, // 1 is filtered out
  11359. filterListeners = [], // when the filters change
  11360. dataListeners = [], // when data is added
  11361. removeDataListeners = [], // when data is removed
  11362. callbacks = [];
  11363. filters = new xfilterArray.bitarray(0);
  11364. // Adds the specified new records to this crossfilter.
  11365. function add(newData) {
  11366. var n0 = n,
  11367. n1 = newData.length;
  11368. // If there's actually new data to add…
  11369. // Merge the new data into the existing data.
  11370. // Lengthen the filter bitset to handle the new records.
  11371. // Notify listeners (dimensions and groups) that new data is available.
  11372. if (n1) {
  11373. data = data.concat(newData);
  11374. filters.lengthen(n += n1);
  11375. dataListeners.forEach(function(l) { l(newData, n0, n1); });
  11376. triggerOnChange('dataAdded');
  11377. }
  11378. return crossfilter;
  11379. }
  11380. // Removes all records that match the current filters, or if a predicate function is passed,
  11381. // removes all records matching the predicate (ignoring filters).
  11382. function removeData(predicate) {
  11383. var // Mapping from old record indexes to new indexes (after records removed)
  11384. newIndex = new Array(n),
  11385. removed = [],
  11386. usePred = typeof predicate === 'function',
  11387. shouldRemove = function (i) {
  11388. return usePred ? predicate(data[i], i) : filters.zero(i)
  11389. };
  11390. for (var index1 = 0, index2 = 0; index1 < n; ++index1) {
  11391. if ( shouldRemove(index1) ) {
  11392. removed.push(index1);
  11393. newIndex[index1] = REMOVED_INDEX;
  11394. } else {
  11395. newIndex[index1] = index2++;
  11396. }
  11397. }
  11398. // Remove all matching records from groups.
  11399. filterListeners.forEach(function(l) { l(-1, -1, [], removed, true); });
  11400. // Update indexes.
  11401. removeDataListeners.forEach(function(l) { l(newIndex); });
  11402. // Remove old filters and data by overwriting.
  11403. for (var index3 = 0, index4 = 0; index3 < n; ++index3) {
  11404. if ( newIndex[index3] !== REMOVED_INDEX ) {
  11405. if (index3 !== index4) filters.copy(index4, index3), data[index4] = data[index3];
  11406. ++index4;
  11407. }
  11408. }
  11409. data.length = n = index4;
  11410. filters.truncate(index4);
  11411. triggerOnChange('dataRemoved');
  11412. }
  11413. function maskForDimensions(dimensions) {
  11414. var n,
  11415. d,
  11416. len,
  11417. id,
  11418. mask = Array(filters.subarrays);
  11419. for (n = 0; n < filters.subarrays; n++) { mask[n] = ~0; }
  11420. for (d = 0, len = dimensions.length; d < len; d++) {
  11421. // The top bits of the ID are the subarray offset and the lower bits are the bit
  11422. // offset of the "one" mask.
  11423. id = dimensions[d].id();
  11424. mask[id >> 7] &= ~(0x1 << (id & 0x3f));
  11425. }
  11426. return mask;
  11427. }
  11428. // Return true if the data element at index i is filtered IN.
  11429. // Optionally, ignore the filters of any dimensions in the ignore_dimensions list.
  11430. function isElementFiltered(i, ignore_dimensions) {
  11431. var mask = maskForDimensions(ignore_dimensions || []);
  11432. return filters.zeroExceptMask(i,mask);
  11433. }
  11434. // Adds a new dimension with the specified value accessor function.
  11435. function dimension(value, iterable) {
  11436. if (typeof value === 'string') {
  11437. var accessorPath = value;
  11438. value = function(d) { return result(d, accessorPath); };
  11439. }
  11440. var dimension = {
  11441. filter: filter,
  11442. filterExact: filterExact,
  11443. filterRange: filterRange,
  11444. filterFunction: filterFunction,
  11445. filterAll: filterAll,
  11446. currentFilter: currentFilter,
  11447. hasCurrentFilter: hasCurrentFilter,
  11448. top: top,
  11449. bottom: bottom,
  11450. group: group,
  11451. groupAll: groupAll,
  11452. dispose: dispose,
  11453. remove: dispose, // for backwards-compatibility
  11454. accessor: value,
  11455. id: function() { return id; }
  11456. };
  11457. var one, // lowest unset bit as mask, e.g., 00001000
  11458. zero, // inverted one, e.g., 11110111
  11459. offset, // offset into the filters arrays
  11460. id, // unique ID for this dimension (reused when dimensions are disposed)
  11461. values, // sorted, cached array
  11462. index, // maps sorted value index -> record index (in data)
  11463. newValues, // temporary array storing newly-added values
  11464. newIndex, // temporary array storing newly-added index
  11465. iterablesIndexCount,
  11466. iterablesIndexFilterStatus,
  11467. iterablesEmptyRows = [],
  11468. sortRange = function(n) {
  11469. return cr_range(n).sort(function(A, B) {
  11470. var a = newValues[A], b = newValues[B];
  11471. return a < b ? -1 : a > b ? 1 : A - B;
  11472. });
  11473. },
  11474. refilter = xfilterFilter.filterAll, // for recomputing filter
  11475. refilterFunction, // the custom filter function in use
  11476. filterValue, // the value used for filtering (value, array, function or undefined)
  11477. filterValuePresent, // true if filterValue contains something
  11478. indexListeners = [], // when data is added
  11479. dimensionGroups = [],
  11480. lo0 = 0,
  11481. hi0 = 0,
  11482. t = 0,
  11483. k;
  11484. // Updating a dimension is a two-stage process. First, we must update the
  11485. // associated filters for the newly-added records. Once all dimensions have
  11486. // updated their filters, the groups are notified to update.
  11487. dataListeners.unshift(preAdd);
  11488. dataListeners.push(postAdd);
  11489. removeDataListeners.push(removeData);
  11490. // Add a new dimension in the filter bitmap and store the offset and bitmask.
  11491. var tmp = filters.add();
  11492. offset = tmp.offset;
  11493. one = tmp.one;
  11494. zero = ~one;
  11495. // Create a unique ID for the dimension
  11496. // IDs will be re-used if dimensions are disposed.
  11497. // For internal use the ID is the subarray offset shifted left 7 bits or'd with the
  11498. // bit offset of the set bit in the dimension's "one" mask.
  11499. id = (offset << 7) | (Math.log(one) / Math.log(2));
  11500. preAdd(data, 0, n);
  11501. postAdd(data, 0, n);
  11502. // Incorporates the specified new records into this dimension.
  11503. // This function is responsible for updating filters, values, and index.
  11504. function preAdd(newData, n0, n1) {
  11505. var newIterablesIndexCount,
  11506. newIterablesIndexFilterStatus;
  11507. if (iterable){
  11508. // Count all the values
  11509. t = 0;
  11510. j = 0;
  11511. k = [];
  11512. for (var i0 = 0; i0 < newData.length; i0++) {
  11513. for(j = 0, k = value(newData[i0]); j < k.length; j++) {
  11514. t++;
  11515. }
  11516. }
  11517. newValues = [];
  11518. newIterablesIndexCount = cr_range(newData.length);
  11519. newIterablesIndexFilterStatus = cr_index(t,1);
  11520. var unsortedIndex = cr_range(t);
  11521. for (var l = 0, index1 = 0; index1 < newData.length; index1++) {
  11522. k = value(newData[index1]);
  11523. //
  11524. if(!k.length){
  11525. newIterablesIndexCount[index1] = 0;
  11526. iterablesEmptyRows.push(index1 + n0);
  11527. continue;
  11528. }
  11529. newIterablesIndexCount[index1] = k.length;
  11530. for (j = 0; j < k.length; j++) {
  11531. newValues.push(k[j]);
  11532. unsortedIndex[l] = index1;
  11533. l++;
  11534. }
  11535. }
  11536. // Create the Sort map used to sort both the values and the valueToData indices
  11537. var sortMap = sortRange(t);
  11538. // Use the sortMap to sort the newValues
  11539. newValues = permute(newValues, sortMap);
  11540. // Use the sortMap to sort the unsortedIndex map
  11541. // newIndex should be a map of sortedValue -> crossfilterData
  11542. newIndex = permute(unsortedIndex, sortMap);
  11543. } else {
  11544. // Permute new values into natural order using a standard sorted index.
  11545. newValues = newData.map(value);
  11546. newIndex = sortRange(n1);
  11547. newValues = permute(newValues, newIndex);
  11548. }
  11549. // Bisect newValues to determine which new records are selected.
  11550. var bounds = refilter(newValues), lo1 = bounds[0], hi1 = bounds[1];
  11551. var index2, index3, index4;
  11552. if(iterable) {
  11553. n1 = t;
  11554. if (refilterFunction) {
  11555. for (index2 = 0; index2 < n1; ++index2) {
  11556. if (!refilterFunction(newValues[index2], index2)) {
  11557. if(--newIterablesIndexCount[newIndex[index2]] === 0) {
  11558. filters[offset][newIndex[index2] + n0] |= one;
  11559. }
  11560. newIterablesIndexFilterStatus[index2] = 1;
  11561. }
  11562. }
  11563. } else {
  11564. for (index3 = 0; index3 < lo1; ++index3) {
  11565. if(--newIterablesIndexCount[newIndex[index3]] === 0) {
  11566. filters[offset][newIndex[index3] + n0] |= one;
  11567. }
  11568. newIterablesIndexFilterStatus[index3] = 1;
  11569. }
  11570. for (index4 = hi1; index4 < n1; ++index4) {
  11571. if(--newIterablesIndexCount[newIndex[index4]] === 0) {
  11572. filters[offset][newIndex[index4] + n0] |= one;
  11573. }
  11574. newIterablesIndexFilterStatus[index4] = 1;
  11575. }
  11576. }
  11577. } else {
  11578. if (refilterFunction) {
  11579. for (index2 = 0; index2 < n1; ++index2) {
  11580. if (!refilterFunction(newValues[index2], index2)) {
  11581. filters[offset][newIndex[index2] + n0] |= one;
  11582. }
  11583. }
  11584. } else {
  11585. for (index3 = 0; index3 < lo1; ++index3) {
  11586. filters[offset][newIndex[index3] + n0] |= one;
  11587. }
  11588. for (index4 = hi1; index4 < n1; ++index4) {
  11589. filters[offset][newIndex[index4] + n0] |= one;
  11590. }
  11591. }
  11592. }
  11593. // If this dimension previously had no data, then we don't need to do the
  11594. // more expensive merge operation; use the new values and index as-is.
  11595. if (!n0) {
  11596. values = newValues;
  11597. index = newIndex;
  11598. iterablesIndexCount = newIterablesIndexCount;
  11599. iterablesIndexFilterStatus = newIterablesIndexFilterStatus;
  11600. lo0 = lo1;
  11601. hi0 = hi1;
  11602. return;
  11603. }
  11604. var oldValues = values,
  11605. oldIndex = index,
  11606. oldIterablesIndexFilterStatus = iterablesIndexFilterStatus,
  11607. old_n0,
  11608. i1 = 0;
  11609. i0 = 0;
  11610. if(iterable){
  11611. old_n0 = n0;
  11612. n0 = oldValues.length;
  11613. n1 = t;
  11614. }
  11615. // Otherwise, create new arrays into which to merge new and old.
  11616. values = iterable ? new Array(n0 + n1) : new Array(n);
  11617. index = iterable ? new Array(n0 + n1) : cr_index(n, n);
  11618. if(iterable) iterablesIndexFilterStatus = cr_index(n0 + n1, 1);
  11619. // Concatenate the newIterablesIndexCount onto the old one.
  11620. if(iterable) {
  11621. var oldiiclength = iterablesIndexCount.length;
  11622. iterablesIndexCount = xfilterArray.arrayLengthen(iterablesIndexCount, n);
  11623. for(var j=0; j+oldiiclength < n; j++) {
  11624. iterablesIndexCount[j+oldiiclength] = newIterablesIndexCount[j];
  11625. }
  11626. }
  11627. // Merge the old and new sorted values, and old and new index.
  11628. var index5 = 0;
  11629. for (; i0 < n0 && i1 < n1; ++index5) {
  11630. if (oldValues[i0] < newValues[i1]) {
  11631. values[index5] = oldValues[i0];
  11632. if(iterable) iterablesIndexFilterStatus[index5] = oldIterablesIndexFilterStatus[i0];
  11633. index[index5] = oldIndex[i0++];
  11634. } else {
  11635. values[index5] = newValues[i1];
  11636. if(iterable) iterablesIndexFilterStatus[index5] = newIterablesIndexFilterStatus[i1];
  11637. index[index5] = newIndex[i1++] + (iterable ? old_n0 : n0);
  11638. }
  11639. }
  11640. // Add any remaining old values.
  11641. for (; i0 < n0; ++i0, ++index5) {
  11642. values[index5] = oldValues[i0];
  11643. if(iterable) iterablesIndexFilterStatus[index5] = oldIterablesIndexFilterStatus[i0];
  11644. index[index5] = oldIndex[i0];
  11645. }
  11646. // Add any remaining new values.
  11647. for (; i1 < n1; ++i1, ++index5) {
  11648. values[index5] = newValues[i1];
  11649. if(iterable) iterablesIndexFilterStatus[index5] = newIterablesIndexFilterStatus[i1];
  11650. index[index5] = newIndex[i1] + (iterable ? old_n0 : n0);
  11651. }
  11652. // Bisect again to recompute lo0 and hi0.
  11653. bounds = refilter(values), lo0 = bounds[0], hi0 = bounds[1];
  11654. }
  11655. // When all filters have updated, notify index listeners of the new values.
  11656. function postAdd(newData, n0, n1) {
  11657. indexListeners.forEach(function(l) { l(newValues, newIndex, n0, n1); });
  11658. newValues = newIndex = null;
  11659. }
  11660. function removeData(reIndex) {
  11661. if (iterable) {
  11662. for (var i0 = 0, i1 = 0; i0 < iterablesEmptyRows.length; i0++) {
  11663. if (reIndex[iterablesEmptyRows[i0]] !== REMOVED_INDEX) {
  11664. iterablesEmptyRows[i1] = reIndex[iterablesEmptyRows[i0]];
  11665. i1++;
  11666. }
  11667. }
  11668. iterablesEmptyRows.length = i1;
  11669. for (i0 = 0, i1 = 0; i0 < n; i0++) {
  11670. if (reIndex[i0] !== REMOVED_INDEX) {
  11671. if (i1 !== i0) iterablesIndexCount[i1] = iterablesIndexCount[i0];
  11672. i1++;
  11673. }
  11674. }
  11675. iterablesIndexCount = iterablesIndexCount.slice(0, i1);
  11676. }
  11677. // Rewrite our index, overwriting removed values
  11678. var n0 = values.length;
  11679. for (var i = 0, j = 0, oldDataIndex; i < n0; ++i) {
  11680. oldDataIndex = index[i];
  11681. if (reIndex[oldDataIndex] !== REMOVED_INDEX) {
  11682. if (i !== j) values[j] = values[i];
  11683. index[j] = reIndex[oldDataIndex];
  11684. if (iterable) {
  11685. iterablesIndexFilterStatus[j] = iterablesIndexFilterStatus[i];
  11686. }
  11687. ++j;
  11688. }
  11689. }
  11690. values.length = j;
  11691. if (iterable) iterablesIndexFilterStatus = iterablesIndexFilterStatus.slice(0, j);
  11692. while (j < n0) index[j++] = 0;
  11693. // Bisect again to recompute lo0 and hi0.
  11694. var bounds = refilter(values);
  11695. lo0 = bounds[0], hi0 = bounds[1];
  11696. }
  11697. // Updates the selected values based on the specified bounds [lo, hi].
  11698. // This implementation is used by all the public filter methods.
  11699. function filterIndexBounds(bounds) {
  11700. var lo1 = bounds[0],
  11701. hi1 = bounds[1];
  11702. if (refilterFunction) {
  11703. refilterFunction = null;
  11704. filterIndexFunction(function(d, i) { return lo1 <= i && i < hi1; }, bounds[0] === 0 && bounds[1] === values.length);
  11705. lo0 = lo1;
  11706. hi0 = hi1;
  11707. return dimension;
  11708. }
  11709. var i,
  11710. j,
  11711. k,
  11712. added = [],
  11713. removed = [],
  11714. valueIndexAdded = [],
  11715. valueIndexRemoved = [];
  11716. // Fast incremental update based on previous lo index.
  11717. if (lo1 < lo0) {
  11718. for (i = lo1, j = Math.min(lo0, hi1); i < j; ++i) {
  11719. added.push(index[i]);
  11720. valueIndexAdded.push(i);
  11721. }
  11722. } else if (lo1 > lo0) {
  11723. for (i = lo0, j = Math.min(lo1, hi0); i < j; ++i) {
  11724. removed.push(index[i]);
  11725. valueIndexRemoved.push(i);
  11726. }
  11727. }
  11728. // Fast incremental update based on previous hi index.
  11729. if (hi1 > hi0) {
  11730. for (i = Math.max(lo1, hi0), j = hi1; i < j; ++i) {
  11731. added.push(index[i]);
  11732. valueIndexAdded.push(i);
  11733. }
  11734. } else if (hi1 < hi0) {
  11735. for (i = Math.max(lo0, hi1), j = hi0; i < j; ++i) {
  11736. removed.push(index[i]);
  11737. valueIndexRemoved.push(i);
  11738. }
  11739. }
  11740. if(!iterable) {
  11741. // Flip filters normally.
  11742. for(i=0; i<added.length; i++) {
  11743. filters[offset][added[i]] ^= one;
  11744. }
  11745. for(i=0; i<removed.length; i++) {
  11746. filters[offset][removed[i]] ^= one;
  11747. }
  11748. } else {
  11749. // For iterables, we need to figure out if the row has been completely removed vs partially included
  11750. // Only count a row as added if it is not already being aggregated. Only count a row
  11751. // as removed if the last element being aggregated is removed.
  11752. var newAdded = [];
  11753. var newRemoved = [];
  11754. for (i = 0; i < added.length; i++) {
  11755. iterablesIndexCount[added[i]]++;
  11756. iterablesIndexFilterStatus[valueIndexAdded[i]] = 0;
  11757. if(iterablesIndexCount[added[i]] === 1) {
  11758. filters[offset][added[i]] ^= one;
  11759. newAdded.push(added[i]);
  11760. }
  11761. }
  11762. for (i = 0; i < removed.length; i++) {
  11763. iterablesIndexCount[removed[i]]--;
  11764. iterablesIndexFilterStatus[valueIndexRemoved[i]] = 1;
  11765. if(iterablesIndexCount[removed[i]] === 0) {
  11766. filters[offset][removed[i]] ^= one;
  11767. newRemoved.push(removed[i]);
  11768. }
  11769. }
  11770. added = newAdded;
  11771. removed = newRemoved;
  11772. // Now handle empty rows.
  11773. if(refilter === xfilterFilter.filterAll) {
  11774. for(i = 0; i < iterablesEmptyRows.length; i++) {
  11775. if((filters[offset][k = iterablesEmptyRows[i]] & one)) {
  11776. // Was not in the filter, so set the filter and add
  11777. filters[offset][k] ^= one;
  11778. added.push(k);
  11779. }
  11780. }
  11781. } else {
  11782. // filter in place - remove empty rows if necessary
  11783. for(i = 0; i < iterablesEmptyRows.length; i++) {
  11784. if(!(filters[offset][k = iterablesEmptyRows[i]] & one)) {
  11785. // Was in the filter, so set the filter and remove
  11786. filters[offset][k] ^= one;
  11787. removed.push(k);
  11788. }
  11789. }
  11790. }
  11791. }
  11792. lo0 = lo1;
  11793. hi0 = hi1;
  11794. filterListeners.forEach(function(l) { l(one, offset, added, removed); });
  11795. triggerOnChange('filtered');
  11796. return dimension;
  11797. }
  11798. // Filters this dimension using the specified range, value, or null.
  11799. // If the range is null, this is equivalent to filterAll.
  11800. // If the range is an array, this is equivalent to filterRange.
  11801. // Otherwise, this is equivalent to filterExact.
  11802. function filter(range) {
  11803. return range == null
  11804. ? filterAll() : Array.isArray(range)
  11805. ? filterRange(range) : typeof range === "function"
  11806. ? filterFunction(range)
  11807. : filterExact(range);
  11808. }
  11809. // Filters this dimension to select the exact value.
  11810. function filterExact(value) {
  11811. filterValue = value;
  11812. filterValuePresent = true;
  11813. return filterIndexBounds((refilter = xfilterFilter.filterExact(bisect, value))(values));
  11814. }
  11815. // Filters this dimension to select the specified range [lo, hi].
  11816. // The lower bound is inclusive, and the upper bound is exclusive.
  11817. function filterRange(range) {
  11818. filterValue = range;
  11819. filterValuePresent = true;
  11820. return filterIndexBounds((refilter = xfilterFilter.filterRange(bisect, range))(values));
  11821. }
  11822. // Clears any filters on this dimension.
  11823. function filterAll() {
  11824. filterValue = undefined;
  11825. filterValuePresent = false;
  11826. return filterIndexBounds((refilter = xfilterFilter.filterAll)(values));
  11827. }
  11828. // Filters this dimension using an arbitrary function.
  11829. function filterFunction(f) {
  11830. filterValue = f;
  11831. filterValuePresent = true;
  11832. refilterFunction = f;
  11833. refilter = xfilterFilter.filterAll;
  11834. filterIndexFunction(f, false);
  11835. var bounds = refilter(values);
  11836. lo0 = bounds[0], hi0 = bounds[1];
  11837. return dimension;
  11838. }
  11839. function filterIndexFunction(f, filterAll) {
  11840. var i,
  11841. k,
  11842. x,
  11843. added = [],
  11844. removed = [],
  11845. valueIndexAdded = [],
  11846. valueIndexRemoved = [],
  11847. indexLength = values.length;
  11848. if(!iterable) {
  11849. for (i = 0; i < indexLength; ++i) {
  11850. if (!(filters[offset][k = index[i]] & one) ^ !!(x = f(values[i], i))) {
  11851. if (x) added.push(k);
  11852. else removed.push(k);
  11853. }
  11854. }
  11855. }
  11856. if(iterable) {
  11857. for(i=0; i < indexLength; ++i) {
  11858. if(f(values[i], i)) {
  11859. added.push(index[i]);
  11860. valueIndexAdded.push(i);
  11861. } else {
  11862. removed.push(index[i]);
  11863. valueIndexRemoved.push(i);
  11864. }
  11865. }
  11866. }
  11867. if(!iterable) {
  11868. for(i=0; i<added.length; i++) {
  11869. if(filters[offset][added[i]] & one) filters[offset][added[i]] &= zero;
  11870. }
  11871. for(i=0; i<removed.length; i++) {
  11872. if(!(filters[offset][removed[i]] & one)) filters[offset][removed[i]] |= one;
  11873. }
  11874. } else {
  11875. var newAdded = [];
  11876. var newRemoved = [];
  11877. for (i = 0; i < added.length; i++) {
  11878. // First check this particular value needs to be added
  11879. if(iterablesIndexFilterStatus[valueIndexAdded[i]] === 1) {
  11880. iterablesIndexCount[added[i]]++;
  11881. iterablesIndexFilterStatus[valueIndexAdded[i]] = 0;
  11882. if(iterablesIndexCount[added[i]] === 1) {
  11883. filters[offset][added[i]] ^= one;
  11884. newAdded.push(added[i]);
  11885. }
  11886. }
  11887. }
  11888. for (i = 0; i < removed.length; i++) {
  11889. // First check this particular value needs to be removed
  11890. if(iterablesIndexFilterStatus[valueIndexRemoved[i]] === 0) {
  11891. iterablesIndexCount[removed[i]]--;
  11892. iterablesIndexFilterStatus[valueIndexRemoved[i]] = 1;
  11893. if(iterablesIndexCount[removed[i]] === 0) {
  11894. filters[offset][removed[i]] ^= one;
  11895. newRemoved.push(removed[i]);
  11896. }
  11897. }
  11898. }
  11899. added = newAdded;
  11900. removed = newRemoved;
  11901. // Now handle empty rows.
  11902. if(filterAll) {
  11903. for(i = 0; i < iterablesEmptyRows.length; i++) {
  11904. if((filters[offset][k = iterablesEmptyRows[i]] & one)) {
  11905. // Was not in the filter, so set the filter and add
  11906. filters[offset][k] ^= one;
  11907. added.push(k);
  11908. }
  11909. }
  11910. } else {
  11911. // filter in place - remove empty rows if necessary
  11912. for(i = 0; i < iterablesEmptyRows.length; i++) {
  11913. if(!(filters[offset][k = iterablesEmptyRows[i]] & one)) {
  11914. // Was in the filter, so set the filter and remove
  11915. filters[offset][k] ^= one;
  11916. removed.push(k);
  11917. }
  11918. }
  11919. }
  11920. }
  11921. filterListeners.forEach(function(l) { l(one, offset, added, removed); });
  11922. triggerOnChange('filtered');
  11923. }
  11924. function currentFilter() {
  11925. return filterValue;
  11926. }
  11927. function hasCurrentFilter() {
  11928. return filterValuePresent;
  11929. }
  11930. // Returns the top K selected records based on this dimension's order.
  11931. // Note: observes this dimension's filter, unlike group and groupAll.
  11932. function top(k, top_offset) {
  11933. var array = [],
  11934. i = hi0,
  11935. j,
  11936. toSkip = 0;
  11937. if(top_offset && top_offset > 0) toSkip = top_offset;
  11938. while (--i >= lo0 && k > 0) {
  11939. if (filters.zero(j = index[i])) {
  11940. if(toSkip > 0) {
  11941. //skip matching row
  11942. --toSkip;
  11943. } else {
  11944. array.push(data[j]);
  11945. --k;
  11946. }
  11947. }
  11948. }
  11949. if(iterable){
  11950. for(i = 0; i < iterablesEmptyRows.length && k > 0; i++) {
  11951. // Add row with empty iterable column at the end
  11952. if(filters.zero(j = iterablesEmptyRows[i])) {
  11953. if(toSkip > 0) {
  11954. //skip matching row
  11955. --toSkip;
  11956. } else {
  11957. array.push(data[j]);
  11958. --k;
  11959. }
  11960. }
  11961. }
  11962. }
  11963. return array;
  11964. }
  11965. // Returns the bottom K selected records based on this dimension's order.
  11966. // Note: observes this dimension's filter, unlike group and groupAll.
  11967. function bottom(k, bottom_offset) {
  11968. var array = [],
  11969. i,
  11970. j,
  11971. toSkip = 0;
  11972. if(bottom_offset && bottom_offset > 0) toSkip = bottom_offset;
  11973. if(iterable) {
  11974. // Add row with empty iterable column at the top
  11975. for(i = 0; i < iterablesEmptyRows.length && k > 0; i++) {
  11976. if(filters.zero(j = iterablesEmptyRows[i])) {
  11977. if(toSkip > 0) {
  11978. //skip matching row
  11979. --toSkip;
  11980. } else {
  11981. array.push(data[j]);
  11982. --k;
  11983. }
  11984. }
  11985. }
  11986. }
  11987. i = lo0;
  11988. while (i < hi0 && k > 0) {
  11989. if (filters.zero(j = index[i])) {
  11990. if(toSkip > 0) {
  11991. //skip matching row
  11992. --toSkip;
  11993. } else {
  11994. array.push(data[j]);
  11995. --k;
  11996. }
  11997. }
  11998. i++;
  11999. }
  12000. return array;
  12001. }
  12002. // Adds a new group to this dimension, using the specified key function.
  12003. function group(key) {
  12004. var group = {
  12005. top: top,
  12006. all: all,
  12007. reduce: reduce,
  12008. reduceCount: reduceCount,
  12009. reduceSum: reduceSum,
  12010. order: order,
  12011. orderNatural: orderNatural,
  12012. size: size,
  12013. dispose: dispose,
  12014. remove: dispose // for backwards-compatibility
  12015. };
  12016. // Ensure that this group will be removed when the dimension is removed.
  12017. dimensionGroups.push(group);
  12018. var groups, // array of {key, value}
  12019. groupIndex, // object id ↦ group id
  12020. groupWidth = 8,
  12021. groupCapacity = capacity(groupWidth),
  12022. k = 0, // cardinality
  12023. select,
  12024. heap,
  12025. reduceAdd,
  12026. reduceRemove,
  12027. reduceInitial,
  12028. update = cr_null,
  12029. reset = cr_null,
  12030. resetNeeded = true,
  12031. groupAll = key === cr_null,
  12032. n0old;
  12033. if (arguments.length < 1) key = cr_identity;
  12034. // The group listens to the crossfilter for when any dimension changes, so
  12035. // that it can update the associated reduce values. It must also listen to
  12036. // the parent dimension for when data is added, and compute new keys.
  12037. filterListeners.push(update);
  12038. indexListeners.push(add);
  12039. removeDataListeners.push(removeData);
  12040. // Incorporate any existing data into the grouping.
  12041. add(values, index, 0, n);
  12042. // Incorporates the specified new values into this group.
  12043. // This function is responsible for updating groups and groupIndex.
  12044. function add(newValues, newIndex, n0, n1) {
  12045. if(iterable) {
  12046. n0old = n0;
  12047. n0 = values.length - newValues.length;
  12048. n1 = newValues.length;
  12049. }
  12050. var oldGroups = groups,
  12051. reIndex = iterable ? [] : cr_index(k, groupCapacity),
  12052. add = reduceAdd,
  12053. remove = reduceRemove,
  12054. initial = reduceInitial,
  12055. k0 = k, // old cardinality
  12056. i0 = 0, // index of old group
  12057. i1 = 0, // index of new record
  12058. j, // object id
  12059. g0, // old group
  12060. x0, // old key
  12061. x1, // new key
  12062. g, // group to add
  12063. x; // key of group to add
  12064. // If a reset is needed, we don't need to update the reduce values.
  12065. if (resetNeeded) add = initial = cr_null;
  12066. if (resetNeeded) remove = initial = cr_null;
  12067. // Reset the new groups (k is a lower bound).
  12068. // Also, make sure that groupIndex exists and is long enough.
  12069. groups = new Array(k), k = 0;
  12070. if(iterable){
  12071. groupIndex = k0 ? groupIndex : [];
  12072. }
  12073. else {
  12074. groupIndex = k0 > 1 ? xfilterArray.arrayLengthen(groupIndex, n) : cr_index(n, groupCapacity);
  12075. }
  12076. // Get the first old key (x0 of g0), if it exists.
  12077. if (k0) x0 = (g0 = oldGroups[0]).key;
  12078. // Find the first new key (x1), skipping NaN keys.
  12079. while (i1 < n1 && !((x1 = key(newValues[i1])) >= x1)) ++i1;
  12080. // While new keys remain…
  12081. while (i1 < n1) {
  12082. // Determine the lesser of the two current keys; new and old.
  12083. // If there are no old keys remaining, then always add the new key.
  12084. if (g0 && x0 <= x1) {
  12085. g = g0, x = x0;
  12086. // Record the new index of the old group.
  12087. reIndex[i0] = k;
  12088. // Retrieve the next old key.
  12089. g0 = oldGroups[++i0];
  12090. if (g0) x0 = g0.key;
  12091. } else {
  12092. g = {key: x1, value: initial()}, x = x1;
  12093. }
  12094. // Add the lesser group.
  12095. groups[k] = g;
  12096. // Add any selected records belonging to the added group, while
  12097. // advancing the new key and populating the associated group index.
  12098. while (x1 <= x) {
  12099. j = newIndex[i1] + (iterable ? n0old : n0);
  12100. if(iterable){
  12101. if(groupIndex[j]){
  12102. groupIndex[j].push(k);
  12103. }
  12104. else {
  12105. groupIndex[j] = [k];
  12106. }
  12107. }
  12108. else {
  12109. groupIndex[j] = k;
  12110. }
  12111. // Always add new values to groups. Only remove when not in filter.
  12112. // This gives groups full information on data life-cycle.
  12113. g.value = add(g.value, data[j], true);
  12114. if (!filters.zeroExcept(j, offset, zero)) g.value = remove(g.value, data[j], false);
  12115. if (++i1 >= n1) break;
  12116. x1 = key(newValues[i1]);
  12117. }
  12118. groupIncrement();
  12119. }
  12120. // Add any remaining old groups that were greater th1an all new keys.
  12121. // No incremental reduce is needed; these groups have no new records.
  12122. // Also record the new index of the old group.
  12123. while (i0 < k0) {
  12124. groups[reIndex[i0] = k] = oldGroups[i0++];
  12125. groupIncrement();
  12126. }
  12127. // Fill in gaps with empty arrays where there may have been rows with empty iterables
  12128. if(iterable){
  12129. for (var index1 = 0; index1 < n; index1++) {
  12130. if(!groupIndex[index1]){
  12131. groupIndex[index1] = [];
  12132. }
  12133. }
  12134. }
  12135. // If we added any new groups before any old groups,
  12136. // update the group index of all the old records.
  12137. if(k > i0){
  12138. if(iterable){
  12139. for (i0 = 0; i0 < n0old; ++i0) {
  12140. for (index1 = 0; index1 < groupIndex[i0].length; index1++) {
  12141. groupIndex[i0][index1] = reIndex[groupIndex[i0][index1]];
  12142. }
  12143. }
  12144. }
  12145. else {
  12146. for (i0 = 0; i0 < n0; ++i0) {
  12147. groupIndex[i0] = reIndex[groupIndex[i0]];
  12148. }
  12149. }
  12150. }
  12151. // Modify the update and reset behavior based on the cardinality.
  12152. // If the cardinality is less than or equal to one, then the groupIndex
  12153. // is not needed. If the cardinality is zero, then there are no records
  12154. // and therefore no groups to update or reset. Note that we also must
  12155. // change the registered listener to point to the new method.
  12156. j = filterListeners.indexOf(update);
  12157. if (k > 1 || iterable) {
  12158. update = updateMany;
  12159. reset = resetMany;
  12160. } else {
  12161. if (!k && groupAll) {
  12162. k = 1;
  12163. groups = [{key: null, value: initial()}];
  12164. }
  12165. if (k === 1) {
  12166. update = updateOne;
  12167. reset = resetOne;
  12168. } else {
  12169. update = cr_null;
  12170. reset = cr_null;
  12171. }
  12172. groupIndex = null;
  12173. }
  12174. filterListeners[j] = update;
  12175. // Count the number of added groups,
  12176. // and widen the group index as needed.
  12177. function groupIncrement() {
  12178. if(iterable){
  12179. k++;
  12180. return
  12181. }
  12182. if (++k === groupCapacity) {
  12183. reIndex = xfilterArray.arrayWiden(reIndex, groupWidth <<= 1);
  12184. groupIndex = xfilterArray.arrayWiden(groupIndex, groupWidth);
  12185. groupCapacity = capacity(groupWidth);
  12186. }
  12187. }
  12188. }
  12189. function removeData(reIndex) {
  12190. if (k > 1 || iterable) {
  12191. var oldK = k,
  12192. oldGroups = groups,
  12193. seenGroups = cr_index(oldK, oldK),
  12194. i,
  12195. i0,
  12196. j;
  12197. // Filter out non-matches by copying matching group index entries to
  12198. // the beginning of the array.
  12199. if (!iterable) {
  12200. for (i = 0, j = 0; i < n; ++i) {
  12201. if (reIndex[i] !== REMOVED_INDEX) {
  12202. seenGroups[groupIndex[j] = groupIndex[i]] = 1;
  12203. ++j;
  12204. }
  12205. }
  12206. } else {
  12207. for (i = 0, j = 0; i < n; ++i) {
  12208. if (reIndex[i] !== REMOVED_INDEX) {
  12209. groupIndex[j] = groupIndex[i];
  12210. for (i0 = 0; i0 < groupIndex[j].length; i0++) {
  12211. seenGroups[groupIndex[j][i0]] = 1;
  12212. }
  12213. ++j;
  12214. }
  12215. }
  12216. groupIndex = groupIndex.slice(0, j);
  12217. }
  12218. // Reassemble groups including only those groups that were referred
  12219. // to by matching group index entries. Note the new group index in
  12220. // seenGroups.
  12221. groups = [], k = 0;
  12222. for (i = 0; i < oldK; ++i) {
  12223. if (seenGroups[i]) {
  12224. seenGroups[i] = k++;
  12225. groups.push(oldGroups[i]);
  12226. }
  12227. }
  12228. if (k > 1 || iterable) {
  12229. // Reindex the group index using seenGroups to find the new index.
  12230. if (!iterable) {
  12231. for (i = 0; i < j; ++i) groupIndex[i] = seenGroups[groupIndex[i]];
  12232. } else {
  12233. for (i = 0; i < j; ++i) {
  12234. for (i0 = 0; i0 < groupIndex[i].length; ++i0) {
  12235. groupIndex[i][i0] = seenGroups[groupIndex[i][i0]];
  12236. }
  12237. }
  12238. }
  12239. } else {
  12240. groupIndex = null;
  12241. }
  12242. filterListeners[filterListeners.indexOf(update)] = k > 1 || iterable
  12243. ? (reset = resetMany, update = updateMany)
  12244. : k === 1 ? (reset = resetOne, update = updateOne)
  12245. : reset = update = cr_null;
  12246. } else if (k === 1) {
  12247. if (groupAll) return;
  12248. for (var index3 = 0; index3 < n; ++index3) if (reIndex[index3] !== REMOVED_INDEX) return;
  12249. groups = [], k = 0;
  12250. filterListeners[filterListeners.indexOf(update)] =
  12251. update = reset = cr_null;
  12252. }
  12253. }
  12254. // Reduces the specified selected or deselected records.
  12255. // This function is only used when the cardinality is greater than 1.
  12256. // notFilter indicates a crossfilter.add/remove operation.
  12257. function updateMany(filterOne, filterOffset, added, removed, notFilter) {
  12258. if ((filterOne === one && filterOffset === offset) || resetNeeded) return;
  12259. var i,
  12260. j,
  12261. k,
  12262. n,
  12263. g;
  12264. if(iterable){
  12265. // Add the added values.
  12266. for (i = 0, n = added.length; i < n; ++i) {
  12267. if (filters.zeroExcept(k = added[i], offset, zero)) {
  12268. for (j = 0; j < groupIndex[k].length; j++) {
  12269. g = groups[groupIndex[k][j]];
  12270. g.value = reduceAdd(g.value, data[k], false, j);
  12271. }
  12272. }
  12273. }
  12274. // Remove the removed values.
  12275. for (i = 0, n = removed.length; i < n; ++i) {
  12276. if (filters.onlyExcept(k = removed[i], offset, zero, filterOffset, filterOne)) {
  12277. for (j = 0; j < groupIndex[k].length; j++) {
  12278. g = groups[groupIndex[k][j]];
  12279. g.value = reduceRemove(g.value, data[k], notFilter, j);
  12280. }
  12281. }
  12282. }
  12283. return;
  12284. }
  12285. // Add the added values.
  12286. for (i = 0, n = added.length; i < n; ++i) {
  12287. if (filters.zeroExcept(k = added[i], offset, zero)) {
  12288. g = groups[groupIndex[k]];
  12289. g.value = reduceAdd(g.value, data[k], false);
  12290. }
  12291. }
  12292. // Remove the removed values.
  12293. for (i = 0, n = removed.length; i < n; ++i) {
  12294. if (filters.onlyExcept(k = removed[i], offset, zero, filterOffset, filterOne)) {
  12295. g = groups[groupIndex[k]];
  12296. g.value = reduceRemove(g.value, data[k], notFilter);
  12297. }
  12298. }
  12299. }
  12300. // Reduces the specified selected or deselected records.
  12301. // This function is only used when the cardinality is 1.
  12302. // notFilter indicates a crossfilter.add/remove operation.
  12303. function updateOne(filterOne, filterOffset, added, removed, notFilter) {
  12304. if ((filterOne === one && filterOffset === offset) || resetNeeded) return;
  12305. var i,
  12306. k,
  12307. n,
  12308. g = groups[0];
  12309. // Add the added values.
  12310. for (i = 0, n = added.length; i < n; ++i) {
  12311. if (filters.zeroExcept(k = added[i], offset, zero)) {
  12312. g.value = reduceAdd(g.value, data[k], false);
  12313. }
  12314. }
  12315. // Remove the removed values.
  12316. for (i = 0, n = removed.length; i < n; ++i) {
  12317. if (filters.onlyExcept(k = removed[i], offset, zero, filterOffset, filterOne)) {
  12318. g.value = reduceRemove(g.value, data[k], notFilter);
  12319. }
  12320. }
  12321. }
  12322. // Recomputes the group reduce values from scratch.
  12323. // This function is only used when the cardinality is greater than 1.
  12324. function resetMany() {
  12325. var i,
  12326. j,
  12327. g;
  12328. // Reset all group values.
  12329. for (i = 0; i < k; ++i) {
  12330. groups[i].value = reduceInitial();
  12331. }
  12332. // We add all records and then remove filtered records so that reducers
  12333. // can build an 'unfiltered' view even if there are already filters in
  12334. // place on other dimensions.
  12335. if(iterable){
  12336. for (i = 0; i < n; ++i) {
  12337. for (j = 0; j < groupIndex[i].length; j++) {
  12338. g = groups[groupIndex[i][j]];
  12339. g.value = reduceAdd(g.value, data[i], true, j);
  12340. }
  12341. }
  12342. for (i = 0; i < n; ++i) {
  12343. if (!filters.zeroExcept(i, offset, zero)) {
  12344. for (j = 0; j < groupIndex[i].length; j++) {
  12345. g = groups[groupIndex[i][j]];
  12346. g.value = reduceRemove(g.value, data[i], false, j);
  12347. }
  12348. }
  12349. }
  12350. return;
  12351. }
  12352. for (i = 0; i < n; ++i) {
  12353. g = groups[groupIndex[i]];
  12354. g.value = reduceAdd(g.value, data[i], true);
  12355. }
  12356. for (i = 0; i < n; ++i) {
  12357. if (!filters.zeroExcept(i, offset, zero)) {
  12358. g = groups[groupIndex[i]];
  12359. g.value = reduceRemove(g.value, data[i], false);
  12360. }
  12361. }
  12362. }
  12363. // Recomputes the group reduce values from scratch.
  12364. // This function is only used when the cardinality is 1.
  12365. function resetOne() {
  12366. var i,
  12367. g = groups[0];
  12368. // Reset the singleton group values.
  12369. g.value = reduceInitial();
  12370. // We add all records and then remove filtered records so that reducers
  12371. // can build an 'unfiltered' view even if there are already filters in
  12372. // place on other dimensions.
  12373. for (i = 0; i < n; ++i) {
  12374. g.value = reduceAdd(g.value, data[i], true);
  12375. }
  12376. for (i = 0; i < n; ++i) {
  12377. if (!filters.zeroExcept(i, offset, zero)) {
  12378. g.value = reduceRemove(g.value, data[i], false);
  12379. }
  12380. }
  12381. }
  12382. // Returns the array of group values, in the dimension's natural order.
  12383. function all() {
  12384. if (resetNeeded) reset(), resetNeeded = false;
  12385. return groups;
  12386. }
  12387. // Returns a new array containing the top K group values, in reduce order.
  12388. function top(k) {
  12389. var top = select(all(), 0, groups.length, k);
  12390. return heap.sort(top, 0, top.length);
  12391. }
  12392. // Sets the reduce behavior for this group to use the specified functions.
  12393. // This method lazily recomputes the reduce values, waiting until needed.
  12394. function reduce(add, remove, initial) {
  12395. reduceAdd = add;
  12396. reduceRemove = remove;
  12397. reduceInitial = initial;
  12398. resetNeeded = true;
  12399. return group;
  12400. }
  12401. // A convenience method for reducing by count.
  12402. function reduceCount() {
  12403. return reduce(xfilterReduce.reduceIncrement, xfilterReduce.reduceDecrement, cr_zero);
  12404. }
  12405. // A convenience method for reducing by sum(value).
  12406. function reduceSum(value) {
  12407. return reduce(xfilterReduce.reduceAdd(value), xfilterReduce.reduceSubtract(value), cr_zero);
  12408. }
  12409. // Sets the reduce order, using the specified accessor.
  12410. function order(value) {
  12411. select = h.by(valueOf);
  12412. heap = h$1.by(valueOf);
  12413. function valueOf(d) { return value(d.value); }
  12414. return group;
  12415. }
  12416. // A convenience method for natural ordering by reduce value.
  12417. function orderNatural() {
  12418. return order(cr_identity);
  12419. }
  12420. // Returns the cardinality of this group, irrespective of any filters.
  12421. function size() {
  12422. return k;
  12423. }
  12424. // Removes this group and associated event listeners.
  12425. function dispose() {
  12426. var i = filterListeners.indexOf(update);
  12427. if (i >= 0) filterListeners.splice(i, 1);
  12428. i = indexListeners.indexOf(add);
  12429. if (i >= 0) indexListeners.splice(i, 1);
  12430. i = removeDataListeners.indexOf(removeData);
  12431. if (i >= 0) removeDataListeners.splice(i, 1);
  12432. i = dimensionGroups.indexOf(group);
  12433. if (i >= 0) dimensionGroups.splice(i, 1);
  12434. return group;
  12435. }
  12436. return reduceCount().orderNatural();
  12437. }
  12438. // A convenience function for generating a singleton group.
  12439. function groupAll() {
  12440. var g = group(cr_null), all = g.all;
  12441. delete g.all;
  12442. delete g.top;
  12443. delete g.order;
  12444. delete g.orderNatural;
  12445. delete g.size;
  12446. g.value = function() { return all()[0].value; };
  12447. return g;
  12448. }
  12449. // Removes this dimension and associated groups and event listeners.
  12450. function dispose() {
  12451. dimensionGroups.forEach(function(group) { group.dispose(); });
  12452. var i = dataListeners.indexOf(preAdd);
  12453. if (i >= 0) dataListeners.splice(i, 1);
  12454. i = dataListeners.indexOf(postAdd);
  12455. if (i >= 0) dataListeners.splice(i, 1);
  12456. i = removeDataListeners.indexOf(removeData);
  12457. if (i >= 0) removeDataListeners.splice(i, 1);
  12458. filters.masks[offset] &= zero;
  12459. return filterAll();
  12460. }
  12461. return dimension;
  12462. }
  12463. // A convenience method for groupAll on a dummy dimension.
  12464. // This implementation can be optimized since it always has cardinality 1.
  12465. function groupAll() {
  12466. var group = {
  12467. reduce: reduce,
  12468. reduceCount: reduceCount,
  12469. reduceSum: reduceSum,
  12470. value: value,
  12471. dispose: dispose,
  12472. remove: dispose // for backwards-compatibility
  12473. };
  12474. var reduceValue,
  12475. reduceAdd,
  12476. reduceRemove,
  12477. reduceInitial,
  12478. resetNeeded = true;
  12479. // The group listens to the crossfilter for when any dimension changes, so
  12480. // that it can update the reduce value. It must also listen to the parent
  12481. // dimension for when data is added.
  12482. filterListeners.push(update);
  12483. dataListeners.push(add);
  12484. // For consistency; actually a no-op since resetNeeded is true.
  12485. add(data, 0);
  12486. // Incorporates the specified new values into this group.
  12487. function add(newData, n0) {
  12488. var i;
  12489. if (resetNeeded) return;
  12490. // Cycle through all the values.
  12491. for (i = n0; i < n; ++i) {
  12492. // Add all values all the time.
  12493. reduceValue = reduceAdd(reduceValue, data[i], true);
  12494. // Remove the value if filtered.
  12495. if (!filters.zero(i)) {
  12496. reduceValue = reduceRemove(reduceValue, data[i], false);
  12497. }
  12498. }
  12499. }
  12500. // Reduces the specified selected or deselected records.
  12501. function update(filterOne, filterOffset, added, removed, notFilter) {
  12502. var i,
  12503. k,
  12504. n;
  12505. if (resetNeeded) return;
  12506. // Add the added values.
  12507. for (i = 0, n = added.length; i < n; ++i) {
  12508. if (filters.zero(k = added[i])) {
  12509. reduceValue = reduceAdd(reduceValue, data[k], notFilter);
  12510. }
  12511. }
  12512. // Remove the removed values.
  12513. for (i = 0, n = removed.length; i < n; ++i) {
  12514. if (filters.only(k = removed[i], filterOffset, filterOne)) {
  12515. reduceValue = reduceRemove(reduceValue, data[k], notFilter);
  12516. }
  12517. }
  12518. }
  12519. // Recomputes the group reduce value from scratch.
  12520. function reset() {
  12521. var i;
  12522. reduceValue = reduceInitial();
  12523. // Cycle through all the values.
  12524. for (i = 0; i < n; ++i) {
  12525. // Add all values all the time.
  12526. reduceValue = reduceAdd(reduceValue, data[i], true);
  12527. // Remove the value if it is filtered.
  12528. if (!filters.zero(i)) {
  12529. reduceValue = reduceRemove(reduceValue, data[i], false);
  12530. }
  12531. }
  12532. }
  12533. // Sets the reduce behavior for this group to use the specified functions.
  12534. // This method lazily recomputes the reduce value, waiting until needed.
  12535. function reduce(add, remove, initial) {
  12536. reduceAdd = add;
  12537. reduceRemove = remove;
  12538. reduceInitial = initial;
  12539. resetNeeded = true;
  12540. return group;
  12541. }
  12542. // A convenience method for reducing by count.
  12543. function reduceCount() {
  12544. return reduce(xfilterReduce.reduceIncrement, xfilterReduce.reduceDecrement, cr_zero);
  12545. }
  12546. // A convenience method for reducing by sum(value).
  12547. function reduceSum(value) {
  12548. return reduce(xfilterReduce.reduceAdd(value), xfilterReduce.reduceSubtract(value), cr_zero);
  12549. }
  12550. // Returns the computed reduce value.
  12551. function value() {
  12552. if (resetNeeded) reset(), resetNeeded = false;
  12553. return reduceValue;
  12554. }
  12555. // Removes this group and associated event listeners.
  12556. function dispose() {
  12557. var i = filterListeners.indexOf(update);
  12558. if (i >= 0) filterListeners.splice(i, 1);
  12559. i = dataListeners.indexOf(add);
  12560. if (i >= 0) dataListeners.splice(i, 1);
  12561. return group;
  12562. }
  12563. return reduceCount();
  12564. }
  12565. // Returns the number of records in this crossfilter, irrespective of any filters.
  12566. function size() {
  12567. return n;
  12568. }
  12569. // Returns the raw row data contained in this crossfilter
  12570. function all(){
  12571. return data;
  12572. }
  12573. // Returns row data with all dimension filters applied, except for filters in ignore_dimensions
  12574. function allFiltered(ignore_dimensions) {
  12575. var array = [],
  12576. i = 0,
  12577. mask = maskForDimensions(ignore_dimensions || []);
  12578. for (i = 0; i < n; i++) {
  12579. if (filters.zeroExceptMask(i, mask)) {
  12580. array.push(data[i]);
  12581. }
  12582. }
  12583. return array;
  12584. }
  12585. function onChange(cb){
  12586. if(typeof cb !== 'function'){
  12587. /* eslint no-console: 0 */
  12588. console.warn('onChange callback parameter must be a function!');
  12589. return;
  12590. }
  12591. callbacks.push(cb);
  12592. return function(){
  12593. callbacks.splice(callbacks.indexOf(cb), 1);
  12594. };
  12595. }
  12596. function triggerOnChange(eventName){
  12597. for (var i = 0; i < callbacks.length; i++) {
  12598. callbacks[i](eventName);
  12599. }
  12600. }
  12601. return arguments.length
  12602. ? add(arguments[0])
  12603. : crossfilter;
  12604. }
  12605. // Returns an array of size n, big enough to store ids up to m.
  12606. function cr_index(n, m) {
  12607. return (m < 0x101
  12608. ? xfilterArray.array8 : m < 0x10001
  12609. ? xfilterArray.array16
  12610. : xfilterArray.array32)(n);
  12611. }
  12612. // Constructs a new array of size n, with sequential values from 0 to n - 1.
  12613. function cr_range(n) {
  12614. var range = cr_index(n, n);
  12615. for (var i = -1; ++i < n;) range[i] = i;
  12616. return range;
  12617. }
  12618. function capacity(w) {
  12619. return w === 8
  12620. ? 0x100 : w === 16
  12621. ? 0x10000
  12622. : 0x100000000;
  12623. }
  12624. var main = /*#__PURE__*/Object.freeze({
  12625. __proto__: null,
  12626. 'default': crossfilter$1
  12627. });
  12628. var crossfilterreq = /*@__PURE__*/getAugmentedNamespace(main);
  12629. const crossfilter = crossfilterreq.default ? crossfilterreq.default : crossfilterreq;
  12630. // -------------------------------------------------------------------
  12631. // dx = multidimensional Crossfilter = Wrapper for crossfilter
  12632. var dx = {
  12633. indexFns : { id : function (d) { return d.id || "" } }
  12634. , createIndexFn : function(indexFn, dim){
  12635. var indexFns = {
  12636. dim : function(d) { return d[dim] || "" }
  12637. , dimId : function(d) { return d[dim + 'Id'] || "" }
  12638. };
  12639. if(Object.prototype.toString.call(indexFn) === '[object Function]' ) return indexFn;
  12640. if(indexFn) return function(d) { return d[indexFn] || "" } // Assume its the column name on the data.
  12641. indexFn = function(d){
  12642. // First time execution detects key to use. We try [dim] then[{{dim}}Id] then [id]
  12643. // This is though dangerous if first item has missing data i.e. d[dim] is undefined even though other rows have d[dim]
  12644. console.error('default generated indexFn on non existence of model property is dangerous.');
  12645. indexFn = d[dim] ? indexFns['dim'] : d[dim + 'Id'] ? indexFns['dimId'] : dx.indexFns['id'];
  12646. dx.indexFns['id'] === indexFn ? console.error('Warning : dimension name not found. Using id as default is not recommended.') : null;
  12647. // Since we were called after the dimension processing has started we will continue to get called until each item is processed.
  12648. // We therefore switch the function that will get called from next time onwards.
  12649. return indexFn(d); //
  12650. };
  12651. return function(d){ return indexFn(d) }
  12652. }
  12653. , filter : function(filter, dim){
  12654. // Note : Ensure that the filter function that you pass in is the same function object. This is the only way to prevent bloat.
  12655. if(!filter) { console.warn('Useless call to filter without a real filter.'); return;} // All filters should already be in place since we are stateful.
  12656. var filterable = dim ? this.dims[dim] : this;
  12657. // Filters are shared between master and dimension on data.
  12658. if(!filterable.wkFilters.get(filter)) {
  12659. filterable.wkFilters.set(filter, true);
  12660. filterable.filters.push(filter); // PB : Note -- Push unique distinct filters ! This will bloat if duplicates are pushed.
  12661. }
  12662. // PB : TODO -- Check CF may not re-evaluate filters if it detects no change in filter.
  12663. if(filterable.dxFd){
  12664. // This is a master dim with attached fact dimension. this.model should give us the column name on the fact data.
  12665. filterable.dxFd.filter( filterable.__filter );
  12666. }
  12667. filterable.dxF.filter(filterable.__filter);
  12668. // If it does re-evaluate following cascade code is not required.
  12669. // Cascade to all nested dimensions which are implicitly bound.
  12670. // Object.keys(specs.dims).forEach((dim)=>{
  12671. // this.dims[dim].dxF.filter( this.dims[dim].__filter )
  12672. // })
  12673. // Handle other custom bound Dimensions on this dimension.
  12674. // Master and Data crossfilters are implicitly bound.
  12675. // this.dims[dim].dxFm ? this.dims[dim].dxFm.filter( this.dims[dim].__filter ) : null;
  12676. // this.dims[dim].dxFd ? this.dims[dim].dxFd.filter( this.dims[dim].__filter ) : null;
  12677. }
  12678. , filterAll : function(dim){
  12679. var filterable = dim ? this.dims[dim] : this;
  12680. if(filterable.dxFd){
  12681. // This is a master dim with attached fact dimension. this.model should give us the column name on the fact data.
  12682. filterable.dxFd.filterAll();
  12683. }
  12684. filterable.dxF.filterAll( );
  12685. // Cascade to all nested dimensions.
  12686. // Object.keys(specs.dims).forEach((dim)=>{
  12687. // specs[dim][dx] = specs[dim].data ? dx.create( specs[dim] ) : null;
  12688. // dx.__createPairedDx(specs, dim);
  12689. // })
  12690. }
  12691. , addFilter : function(filter, dim) {
  12692. dim = dim || 'id';
  12693. this.dims[dim].filters.push(filter);
  12694. }
  12695. , __initDim : function(oDim){
  12696. var __filter = function(d){
  12697. for(var f=0; f < oDim.filters.length; f++) {
  12698. // Filter function will be called on the dimension.
  12699. // PB : TODO accept any scope instead of only the dimension.
  12700. if(!oDim.filters[f].call(oDim, d)) return false;
  12701. }
  12702. return true;
  12703. };
  12704. return oDim ? (()=>{
  12705. oDim.wkFilters = new(WeakMap);
  12706. oDim.filters = []; oDim.__filter = __filter;
  12707. return oDim
  12708. })()
  12709. : { wkFilters : new(WeakMap), filters : [], __filter : __filter }
  12710. }
  12711. , __createPairedDx : function(specs, dim, idxFn){
  12712. var oDim = dim === 'id' ? specs : specs.dims[dim];
  12713. idxFn = idxFn || dx.createIndexFn(oDim.indexFn, dim);
  12714. oDim.dxU = specs.ndxU.dimension( idxFn );
  12715. oDim.dxF = specs.ndxF.dimension( idxFn );
  12716. }
  12717. , create : function( specs ){
  12718. specs.ndxF = crossfilter(specs.data);
  12719. specs.ndxU = crossfilter(specs.data);
  12720. // specs.dims ? null : specs.dims = { 'id' : null }
  12721. // specs.dims['id'] = dx.__initDim(specs.dims['id'])
  12722. dx.__initDim(specs); // id Dimension is merged with dx itself. Other dimensions will be found in dims.
  12723. dx.__createPairedDx(specs, 'id', dx.indexFns.id);
  12724. specs.dims ? Object.keys(specs.dims).forEach((dim)=>{
  12725. specs.dims[dim].data ? (()=>{
  12726. // We have some master data for this dimension.
  12727. dx.create( specs.dims[dim] );
  12728. // PB : TODO -- We should probably bind the an array dx's ...
  12729. // Eg: An array of master dx's for a fact dx...
  12730. // i.e specs.bound = [ dx1 = practitioner, dx2 = xyz etc...]
  12731. })()
  12732. : dx.__initDim(specs.dims[dim]);
  12733. var idxFn = dx.createIndexFn(specs.dims[dim].indexFn, dim);
  12734. specs.dims[dim].dxFd = specs.ndxF.dimension( idxFn );
  12735. specs.dims[dim].dxUd = specs.ndxU.dimension( idxFn );
  12736. }) : null;
  12737. specs.filter = this.filter;
  12738. specs.filterAll = this.filterAll;
  12739. return specs;
  12740. }
  12741. // , exclude : ( dxU, dxF, filterFn )=>{
  12742. // // Excludes filtered from unfiltered.
  12743. // var filterFn = null;
  12744. // if(this.get('selected_doctor.id')) {
  12745. // }
  12746. // else {
  12747. // var __inclusions = [];
  12748. // var __exclusions = [];
  12749. // practitionersDimUnfiltered.top(Infinity).forEach((availablePractitioner)=>{
  12750. // // Per Doc
  12751. // ndxFiltered.filterAll()
  12752. // practitionersDimFiltered.filter(availablePractitioner.id);
  12753. // var freeTimes = getFreeTimes(tRange, practitionersDimFiltered);
  12754. // if(freeTimes.length > 0) { /*available*/
  12755. // __inclusions.push(availablePractitioner) }
  12756. // else {
  12757. // __exclusions.push(availablePractitioner)
  12758. // }
  12759. // })
  12760. // filterFn = ()=> { return ((inclusions, exclusions)=>{
  12761. // for(var f in filters) {
  12762. // if(!filters[f]) return false;
  12763. // }
  12764. // return true;
  12765. // })(__inclusions, __exclusions) } ;
  12766. // practitionersDimFiltered.filter(filterFn);
  12767. // }
  12768. // return filterFn;
  12769. // }
  12770. };
  12771. var dx_1 = dx;
  12772. var commonmasks = {
  12773. "bed": {
  12774. "wards": {
  12775. "Bone Marrow Transplantation Unit": {
  12776. "title": "Bone Marrow Transplantation Unit",
  12777. "v1wardId": "BMTU",
  12778. "mask": "1"
  12779. },
  12780. "BRB (Birthing Room A-Big)": {
  12781. "title": "BRB (Birthing Room A-Big)",
  12782. "v1wardId": "BRB",
  12783. "mask": "2"
  12784. },
  12785. "BRSP (Birthing Room-Special Private Ward)": {
  12786. "title": "BRSP (Birthing Room-Special Private Ward)",
  12787. "v1wardId": "BRSP",
  12788. "mask": "4"
  12789. },
  12790. "CCU (Coronary Care Unit)": {
  12791. "title": "CCU (Coronary Care Unit)",
  12792. "v1wardId": "CCU",
  12793. "mask": "8"
  12794. },
  12795. "Chemotherapy Unit": {
  12796. "title": "Chemotherapy Unit",
  12797. "v1wardId": "CHEMOTHERAPY",
  12798. "mask": "16"
  12799. },
  12800. "High Intensive Care Unit": {
  12801. "title": "High Intensive Care Unit",
  12802. "v1wardId": "HICU",
  12803. "mask": "32"
  12804. },
  12805. "ICU (Intensive Care Unit )": {
  12806. "title": "ICU (Intensive Care Unit )",
  12807. "v1wardId": "ICU",
  12808. "mask": "64"
  12809. },
  12810. "Labour Room A": {
  12811. "title": "Labour Room A",
  12812. "v1wardId": "LDPRA",
  12813. "mask": "128"
  12814. },
  12815. "Labour Room B": {
  12816. "title": "Labour Room B",
  12817. "v1wardId": "LDPRB",
  12818. "mask": "256"
  12819. },
  12820. "LLC Covid Ward": {
  12821. "title": "LLC Covid Ward",
  12822. "v1wardId": "LLCCOVIDWARD",
  12823. "mask": "512"
  12824. },
  12825. "Mortury": {
  12826. "title": "Mortury",
  12827. "v1wardId": "MORTURY",
  12828. "mask": "1024"
  12829. },
  12830. "NCU (Neonetal Care Unit)": {
  12831. "title": "NCU (Neonetal Care Unit)",
  12832. "v1wardId": "NCU",
  12833. "mask": "2048"
  12834. },
  12835. "Neonatal Intensive Care unit2": {
  12836. "title": "Neonatal Intensive Care unit2",
  12837. "v1wardId": "NICU2",
  12838. "mask": "4096"
  12839. },
  12840. "Operation Theatre": {
  12841. "title": "Operation Theatre",
  12842. "v1wardId": "OT",
  12843. "mask": "8192"
  12844. },
  12845. "Patient Parking Area": {
  12846. "title": "Patient Parking Area",
  12847. "v1wardId": "PARKING",
  12848. "mask": "16384"
  12849. },
  12850. "PCU (Peadiatric Care Unit)": {
  12851. "title": "PCU (Peadiatric Care Unit)",
  12852. "v1wardId": "PCU",
  12853. "mask": "32768"
  12854. },
  12855. "Private Ward": {
  12856. "title": "Private Ward",
  12857. "v1wardId": "PVTWARD",
  12858. "mask": "65536"
  12859. },
  12860. "SPPVT (Special Private)": {
  12861. "title": "SPPVT (Special Private)",
  12862. "v1wardId": "SPLPVT",
  12863. "mask": "131072"
  12864. },
  12865. "Special Private": {
  12866. "title": "Special Private",
  12867. "v1wardId": "SPPVT",
  12868. "mask": "262144"
  12869. },
  12870. "Wing 01-Female": {
  12871. "title": "Wing 01-Female",
  12872. "v1wardId": "W1FEMALE",
  12873. "mask": "524288"
  12874. },
  12875. "Wing 01-Maternity": {
  12876. "title": "Wing 01-Maternity",
  12877. "v1wardId": "W1MATERNITY",
  12878. "mask": "1048576"
  12879. },
  12880. "Wing 01-SP": {
  12881. "title": "Wing 01-SP",
  12882. "v1wardId": "W1SEMIPRIVATE",
  12883. "mask": "2097152"
  12884. },
  12885. "Wing 02-Female": {
  12886. "title": "Wing 02-Female",
  12887. "v1wardId": "WING02",
  12888. "mask": "4194304"
  12889. },
  12890. "Wing 02-Paediatric": {
  12891. "title": "Wing 02-Paediatric",
  12892. "v1wardId": "WING02PED",
  12893. "mask": "8388608"
  12894. },
  12895. "Wing 03": {
  12896. "title": "Wing 03",
  12897. "v1wardId": "WING03",
  12898. "mask": "16777216"
  12899. },
  12900. "Wing 04": {
  12901. "title": "Wing 04",
  12902. "v1wardId": "WING04",
  12903. "mask": "33554432"
  12904. },
  12905. "Wing 05": {
  12906. "title": "Wing 05",
  12907. "v1wardId": "WING05",
  12908. "mask": "67108864"
  12909. },
  12910. "Wing 06": {
  12911. "title": "Wing 06",
  12912. "v1wardId": "WING06",
  12913. "mask": "134217728"
  12914. },
  12915. "PVTWR (Private Wad)": {
  12916. "title": "PVTWR (Private Wad)",
  12917. "v1wardId": "WINGPC",
  12918. "read": 4,
  12919. "write": 4,
  12920. "mask": "268435456"
  12921. },
  12922. "Inactive": {
  12923. "title": "Inactive",
  12924. "v1wardId": "Inactive",
  12925. "mask": "536870912"
  12926. }
  12927. },
  12928. "bedclassifications": {
  12929. "Bassinet": {
  12930. "v1bedclassificationId": "BNT",
  12931. "title": "Bassinet",
  12932. "category": "Ward Type",
  12933. "read": 4,
  12934. "write": 4,
  12935. "mask": "1"
  12936. },
  12937. "Birthing Room": {
  12938. "v1bedclassificationId": "BRB",
  12939. "title": "Birthing Room",
  12940. "category": "Ward Type",
  12941. "mask": "2"
  12942. },
  12943. "Casualty": {
  12944. "v1bedclassificationId": "CASUALTY",
  12945. "title": "Casualty",
  12946. "category": "Ward Type",
  12947. "mask": "4"
  12948. },
  12949. "Coronary Care Unit": {
  12950. "v1bedclassificationId": "CCU",
  12951. "title": "Coronary Care Unit",
  12952. "category": "Ward Type",
  12953. "mask": "8"
  12954. },
  12955. "Chemotherapy": {
  12956. "v1bedclassificationId": "CHEMO",
  12957. "title": "Chemotherapy",
  12958. "category": "Ward Type",
  12959. "mask": "16"
  12960. },
  12961. "Day Care": {
  12962. "v1bedclassificationId": "DAYCAR",
  12963. "title": "Day Care",
  12964. "category": "Ward Type",
  12965. "mask": "32"
  12966. },
  12967. "Geriatric": {
  12968. "v1bedclassificationId": "GER",
  12969. "title": "Geriatric",
  12970. "category": "Ward Type",
  12971. "mask": "64"
  12972. },
  12973. "Labour Room": {
  12974. "v1bedclassificationId": "LBR",
  12975. "title": "Labour Room",
  12976. "category": "Ward Type",
  12977. "mask": "128"
  12978. },
  12979. "High Dependency Care Unit": {
  12980. "v1bedclassificationId": "HDU",
  12981. "title": "High Dependency Care Unit",
  12982. "category": "Ward Type",
  12983. "mask": "256"
  12984. },
  12985. "Intensive Care Unit": {
  12986. "v1bedclassificationId": "Intensive Care Unit",
  12987. "title": "Intensive Care Unit",
  12988. "category": "Ward Type",
  12989. "mask": "512"
  12990. },
  12991. "High Risk Labour Room": {
  12992. "v1bedclassificationId": "HRLBR",
  12993. "title": "High Risk Labour Room",
  12994. "category": "Ward Type",
  12995. "mask": "1024"
  12996. },
  12997. "High Intensive Care Unit": {
  12998. "v1bedclassificationId": "HICU",
  12999. "title": "High Intensive Care Unit",
  13000. "category": "Ward Type",
  13001. "mask": "2048"
  13002. },
  13003. "Neonatal Intensive Care Unit": {
  13004. "v1bedclassificationId": "NCU",
  13005. "title": "Neonatal Intensive Care Unit",
  13006. "category": "Ward Type",
  13007. "mask": "4096"
  13008. },
  13009. "Paediatric Intensive Care Unit": {
  13010. "v1bedclassificationId": "PCU",
  13011. "title": "Paediatric Intensive Care Unit",
  13012. "category": "Ward Type",
  13013. "mask": "8192"
  13014. },
  13015. "With TV": {
  13016. "v1bedclassificationId": "WTV",
  13017. "title": "With TV",
  13018. "category": "Amenities",
  13019. "mask": "16384"
  13020. },
  13021. "With AC": {
  13022. "v1bedclassificationId": "WAC",
  13023. "title": "With AC",
  13024. "category": "Amenities",
  13025. "mask": "32768"
  13026. },
  13027. "General Semi Private": {
  13028. "v1bedclassificationId": "GSP",
  13029. "title": "General Semi Private",
  13030. "category": "Bill Category",
  13031. "mask": "65536"
  13032. },
  13033. "General": {
  13034. "v1bedclassificationId": "GEN",
  13035. "title": "General",
  13036. "category": "Bill Category",
  13037. "mask": "131072"
  13038. },
  13039. "Private": {
  13040. "v1bedclassificationId": "PVT",
  13041. "title": "Private",
  13042. "category": "Bill Category",
  13043. "mask": "262144"
  13044. },
  13045. "Delux": {
  13046. "v1bedclassificationId": "DLX",
  13047. "title": "Delux",
  13048. "category": "Bill Category",
  13049. "mask": "524288"
  13050. },
  13051. "VIP": {
  13052. "v1bedclassificationId": "VIP",
  13053. "title": "VIP",
  13054. "category": "Bed Type",
  13055. "read": 4,
  13056. "write": 4,
  13057. "mask": "1048576"
  13058. },
  13059. "Regular": {
  13060. "v1bedclassificationId": "Regular",
  13061. "title": "Regular",
  13062. "category": "Bed Type",
  13063. "read": 4,
  13064. "write": 4,
  13065. "mask": "2097152"
  13066. },
  13067. "Premium Economy": {
  13068. "v1bedclassificationId": "Premium Economy",
  13069. "title": "Premium Economy",
  13070. "category": "Bed Type",
  13071. "read": 4,
  13072. "write": 4,
  13073. "mask": "4194304"
  13074. },
  13075. "Economy": {
  13076. "v1bedclassificationId": "Economy",
  13077. "title": "Economy",
  13078. "category": "Bed Type",
  13079. "read": 4,
  13080. "write": 4,
  13081. "mask": "8388608"
  13082. },
  13083. "Full room": {
  13084. "v1bedclassificationId": "FULL",
  13085. "title": "Full room",
  13086. "category": "Bed Type",
  13087. "read": 4,
  13088. "write": 4,
  13089. "mask": "16777216"
  13090. },
  13091. "Triple Share": {
  13092. "v1bedclassificationId": "TIO",
  13093. "title": "Triple Share",
  13094. "category": "Bed Type",
  13095. "read": 4,
  13096. "write": 4,
  13097. "mask": "33554432"
  13098. },
  13099. "Twin Share": {
  13100. "v1bedclassificationId": "TWIN",
  13101. "title": "Twin Share",
  13102. "category": "Bed Type",
  13103. "read": 4,
  13104. "write": 4,
  13105. "mask": "67108864"
  13106. },
  13107. "Special Private": {
  13108. "v1bedclassificationId": "SPPVT",
  13109. "title": "Special Private",
  13110. "category": "Bill Category",
  13111. "mask": "134217728"
  13112. },
  13113. "Male": {
  13114. "v1bedclassificationId": "MALE",
  13115. "title": "Male",
  13116. "read": 4,
  13117. "category": "Gender Type",
  13118. "mask": "268435456"
  13119. },
  13120. "Female": {
  13121. "v1bedclassificationId": "FEMALE",
  13122. "title": "Female",
  13123. "read": 4,
  13124. "category": "Gender Type",
  13125. "mask": "536870912"
  13126. },
  13127. "Other": {
  13128. "v1bedclassificationId": "OTHGEN",
  13129. "title": "Other",
  13130. "read": 4,
  13131. "category": "Gender Type",
  13132. "mask": "1073741824"
  13133. },
  13134. "Adult": {
  13135. "v1bedclassificationId": "ADLT",
  13136. "title": "Adult",
  13137. "category": "Age Based",
  13138. "mask": "2147483648"
  13139. },
  13140. "Paediatric": {
  13141. "v1bedclassificationId": "PAD",
  13142. "title": "Paediatric",
  13143. "category": "Age Based",
  13144. "mask": "4294967296"
  13145. },
  13146. "Neonatal": {
  13147. "v1bedclassificationId": "NEO",
  13148. "title": "Neonatal",
  13149. "category": "Age Based",
  13150. "mask": "8589934592"
  13151. },
  13152. "Admissible Bed": {
  13153. "v1bedclassificationId": "ADM",
  13154. "title": "Admissible Bed",
  13155. "category": "Admissible Category",
  13156. "read": 4,
  13157. "write": 4,
  13158. "mask": "17179869184"
  13159. },
  13160. "Non Admissible Bed": {
  13161. "v1bedclassificationId": "NAADM",
  13162. "title": "Non Admissible Bed",
  13163. "category": "Admissible Category",
  13164. "read": 4,
  13165. "write": 4,
  13166. "mask": "34359738368"
  13167. },
  13168. "Limited Admissible Bed": {
  13169. "v1bedclassificationId": "LMADM",
  13170. "title": "Limited Admissible Bed",
  13171. "category": "Admissible Category",
  13172. "read": 4,
  13173. "write": 4,
  13174. "mask": "68719476736"
  13175. },
  13176. "Infected": {
  13177. "v1bedclassificationId": "INFECTED",
  13178. "title": "Infected",
  13179. "category": "Clinical",
  13180. "read": 8,
  13181. "write": 8,
  13182. "mask": "137438953472"
  13183. },
  13184. "Clean": {
  13185. "v1bedclassificationId": "CLEAN",
  13186. "title": "Clean",
  13187. "category": "Clinical",
  13188. "read": 8,
  13189. "write": 8,
  13190. "mask": "274877906944"
  13191. },
  13192. "Isolation": {
  13193. "v1bedclassificationId": "ISOLATION",
  13194. "title": "Isolation",
  13195. "category": "Clinical",
  13196. "read": 8,
  13197. "write": 8,
  13198. "mask": "549755813888"
  13199. },
  13200. "Ward": {
  13201. "v1bedclassificationId": "Ward",
  13202. "title": "Ward",
  13203. "category": "Uncategorized",
  13204. "read": 4,
  13205. "write": 4,
  13206. "mask": "1099511627776"
  13207. },
  13208. "ICU": {
  13209. "v1bedclassificationId": "ICU",
  13210. "title": "ICU",
  13211. "category": "Uncategorized",
  13212. "read": 4,
  13213. "write": 4,
  13214. "mask": "2199023255552"
  13215. },
  13216. "Inactive": {
  13217. "title": "Inactive",
  13218. "v1bedclassificationId": "Inactive",
  13219. "read": 4,
  13220. "write": 4,
  13221. "mask": "4398046511104"
  13222. }
  13223. },
  13224. "bedoccupancyclassifications": {
  13225. "Bassinet": {
  13226. "v1bedclassificationId": "BNT",
  13227. "title": "Bassinet",
  13228. "category": "Ward Type",
  13229. "read": 4,
  13230. "write": 4,
  13231. "mask": "1"
  13232. },
  13233. "Birthing Room": {
  13234. "v1bedclassificationId": "BRB",
  13235. "title": "Birthing Room",
  13236. "category": "Ward Type",
  13237. "mask": "2"
  13238. },
  13239. "Casualty": {
  13240. "v1bedclassificationId": "CASUALTY",
  13241. "title": "Casualty",
  13242. "category": "Ward Type",
  13243. "mask": "4"
  13244. },
  13245. "Coronary Care Unit": {
  13246. "v1bedclassificationId": "CCU",
  13247. "title": "Coronary Care Unit",
  13248. "category": "Ward Type",
  13249. "mask": "8"
  13250. },
  13251. "Chemotherapy": {
  13252. "v1bedclassificationId": "CHEMO",
  13253. "title": "Chemotherapy",
  13254. "category": "Ward Type",
  13255. "mask": "16"
  13256. },
  13257. "Day Care": {
  13258. "v1bedclassificationId": "DAYCAR",
  13259. "title": "Day Care",
  13260. "category": "Ward Type",
  13261. "mask": "32"
  13262. },
  13263. "Geriatric": {
  13264. "v1bedclassificationId": "GER",
  13265. "title": "Geriatric",
  13266. "category": "Ward Type",
  13267. "mask": "64"
  13268. },
  13269. "Labour Room": {
  13270. "v1bedclassificationId": "LBR",
  13271. "title": "Labour Room",
  13272. "category": "Ward Type",
  13273. "mask": "128"
  13274. },
  13275. "High Dependency Care Unit": {
  13276. "v1bedclassificationId": "HDU",
  13277. "title": "High Dependency Care Unit",
  13278. "category": "Ward Type",
  13279. "mask": "256"
  13280. },
  13281. "Intensive Care Unit": {
  13282. "v1bedclassificationId": "Intensive Care Unit",
  13283. "title": "Intensive Care Unit",
  13284. "category": "Ward Type",
  13285. "mask": "512"
  13286. },
  13287. "High Risk Labour Room": {
  13288. "v1bedclassificationId": "HRLBR",
  13289. "title": "High Risk Labour Room",
  13290. "category": "Ward Type",
  13291. "mask": "1024"
  13292. },
  13293. "High Intensive Care Unit": {
  13294. "v1bedclassificationId": "HICU",
  13295. "title": "High Intensive Care Unit",
  13296. "category": "Ward Type",
  13297. "mask": "2048"
  13298. },
  13299. "Neonatal Intensive Care Unit": {
  13300. "v1bedclassificationId": "NCU",
  13301. "title": "Neonatal Intensive Care Unit",
  13302. "category": "Ward Type",
  13303. "mask": "4096"
  13304. },
  13305. "Paediatric Intensive Care Unit": {
  13306. "v1bedclassificationId": "PCU",
  13307. "title": "Paediatric Intensive Care Unit",
  13308. "category": "Ward Type",
  13309. "mask": "8192"
  13310. },
  13311. "With TV": {
  13312. "v1bedclassificationId": "WTV",
  13313. "title": "With TV",
  13314. "category": "Amenities",
  13315. "mask": "16384"
  13316. },
  13317. "With AC": {
  13318. "v1bedclassificationId": "WAC",
  13319. "title": "With AC",
  13320. "category": "Amenities",
  13321. "mask": "32768"
  13322. },
  13323. "General Semi Private": {
  13324. "v1bedclassificationId": "GSP",
  13325. "title": "General Semi Private",
  13326. "category": "Bill Category",
  13327. "mask": "65536"
  13328. },
  13329. "General": {
  13330. "v1bedclassificationId": "GEN",
  13331. "title": "General",
  13332. "category": "Bill Category",
  13333. "mask": "131072"
  13334. },
  13335. "Private": {
  13336. "v1bedclassificationId": "PVT",
  13337. "title": "Private",
  13338. "category": "Bill Category",
  13339. "mask": "262144"
  13340. },
  13341. "Delux": {
  13342. "v1bedclassificationId": "DLX",
  13343. "title": "Delux",
  13344. "category": "Bill Category",
  13345. "mask": "524288"
  13346. },
  13347. "VIP": {
  13348. "v1bedclassificationId": "VIP",
  13349. "title": "VIP",
  13350. "category": "Bed Type",
  13351. "read": 4,
  13352. "write": 4,
  13353. "mask": "1048576"
  13354. },
  13355. "Regular": {
  13356. "v1bedclassificationId": "Regular",
  13357. "title": "Regular",
  13358. "category": "Bed Type",
  13359. "read": 4,
  13360. "write": 4,
  13361. "mask": "2097152"
  13362. },
  13363. "Premium Economy": {
  13364. "v1bedclassificationId": "Premium Economy",
  13365. "title": "Premium Economy",
  13366. "category": "Bed Type",
  13367. "read": 4,
  13368. "write": 4,
  13369. "mask": "4194304"
  13370. },
  13371. "Economy": {
  13372. "v1bedclassificationId": "Economy",
  13373. "title": "Economy",
  13374. "category": "Bed Type",
  13375. "read": 4,
  13376. "write": 4,
  13377. "mask": "8388608"
  13378. },
  13379. "Full room": {
  13380. "v1bedclassificationId": "FULL",
  13381. "title": "Full room",
  13382. "category": "Bed Type",
  13383. "read": 4,
  13384. "write": 4,
  13385. "mask": "16777216"
  13386. },
  13387. "Triple Share": {
  13388. "v1bedclassificationId": "TIO",
  13389. "title": "Triple Share",
  13390. "category": "Bed Type",
  13391. "read": 4,
  13392. "write": 4,
  13393. "mask": "33554432"
  13394. },
  13395. "Twin Share": {
  13396. "v1bedclassificationId": "TWIN",
  13397. "title": "Twin Share",
  13398. "category": "Bed Type",
  13399. "read": 4,
  13400. "write": 4,
  13401. "mask": "67108864"
  13402. },
  13403. "Special Private": {
  13404. "v1bedclassificationId": "SPPVT",
  13405. "title": "Special Private",
  13406. "category": "Bill Category",
  13407. "mask": "134217728"
  13408. },
  13409. "Male": {
  13410. "v1bedclassificationId": "MALE",
  13411. "title": "Male",
  13412. "read": 4,
  13413. "category": "Gender Type",
  13414. "mask": "268435456"
  13415. },
  13416. "Female": {
  13417. "v1bedclassificationId": "FEMALE",
  13418. "title": "Female",
  13419. "read": 4,
  13420. "category": "Gender Type",
  13421. "mask": "536870912"
  13422. },
  13423. "Other": {
  13424. "v1bedclassificationId": "OTHGEN",
  13425. "title": "Other",
  13426. "read": 4,
  13427. "category": "Gender Type",
  13428. "mask": "1073741824"
  13429. },
  13430. "Adult": {
  13431. "v1bedclassificationId": "ADLT",
  13432. "title": "Adult",
  13433. "category": "Age Based",
  13434. "mask": "2147483648"
  13435. },
  13436. "Paediatric": {
  13437. "v1bedclassificationId": "PAD",
  13438. "title": "Paediatric",
  13439. "category": "Age Based",
  13440. "mask": "4294967296"
  13441. },
  13442. "Neonatal": {
  13443. "v1bedclassificationId": "NEO",
  13444. "title": "Neonatal",
  13445. "category": "Age Based",
  13446. "mask": "8589934592"
  13447. },
  13448. "Admissible Bed": {
  13449. "v1bedclassificationId": "ADM",
  13450. "title": "Admissible Bed",
  13451. "category": "Admissible Category",
  13452. "read": 4,
  13453. "write": 4,
  13454. "mask": "17179869184"
  13455. },
  13456. "Non Admissible Bed": {
  13457. "v1bedclassificationId": "NAADM",
  13458. "title": "Non Admissible Bed",
  13459. "category": "Admissible Category",
  13460. "read": 4,
  13461. "write": 4,
  13462. "mask": "34359738368"
  13463. },
  13464. "Limited Admissible Bed": {
  13465. "v1bedclassificationId": "LMADM",
  13466. "title": "Limited Admissible Bed",
  13467. "category": "Admissible Category",
  13468. "read": 4,
  13469. "write": 4,
  13470. "mask": "68719476736"
  13471. },
  13472. "Infected": {
  13473. "v1bedclassificationId": "INFECTED",
  13474. "title": "Infected",
  13475. "category": "Clinical",
  13476. "read": 8,
  13477. "write": 8,
  13478. "mask": "137438953472"
  13479. },
  13480. "Clean": {
  13481. "v1bedclassificationId": "CLEAN",
  13482. "title": "Clean",
  13483. "category": "Clinical",
  13484. "read": 8,
  13485. "write": 8,
  13486. "mask": "274877906944"
  13487. },
  13488. "Isolation": {
  13489. "v1bedclassificationId": "ISOLATION",
  13490. "title": "Isolation",
  13491. "category": "Clinical",
  13492. "read": 8,
  13493. "write": 8,
  13494. "mask": "549755813888"
  13495. },
  13496. "Ward": {
  13497. "v1bedclassificationId": "Ward",
  13498. "title": "Ward",
  13499. "category": "Uncategorized",
  13500. "read": 4,
  13501. "write": 4,
  13502. "mask": "1099511627776"
  13503. },
  13504. "ICU": {
  13505. "v1bedclassificationId": "ICU",
  13506. "title": "ICU",
  13507. "category": "Uncategorized",
  13508. "read": 4,
  13509. "write": 4,
  13510. "mask": "2199023255552"
  13511. },
  13512. "Inactive": {
  13513. "title": "Inactive",
  13514. "v1bedclassificationId": "Inactive",
  13515. "read": 4,
  13516. "write": 4,
  13517. "mask": "4398046511104"
  13518. }
  13519. }
  13520. },
  13521. "dentalmr": {
  13522. "habits": {
  13523. "Chewing": {
  13524. "title": "Chewing",
  13525. "mask": "1"
  13526. },
  13527. "Smoking": {
  13528. "title": "Smoking",
  13529. "mask": "2"
  13530. },
  13531. "Alchohol": {
  13532. "title": "Alchohol",
  13533. "mask": "4"
  13534. },
  13535. "Other": {
  13536. "title": "Other",
  13537. "mask": "8"
  13538. }
  13539. },
  13540. "oralhygienestatuses": {
  13541. "Calculus": {
  13542. "title": "Calculus",
  13543. "mask": "1"
  13544. },
  13545. "Strain": {
  13546. "title": "Strain",
  13547. "mask": "2"
  13548. },
  13549. "Debris": {
  13550. "title": "Debris",
  13551. "mask": "4"
  13552. },
  13553. "Sub-gingival-calculus": {
  13554. "title": "Sub-gingival-calculus",
  13555. "mask": "8"
  13556. }
  13557. },
  13558. "periodontiums": {
  13559. "Mobility": {
  13560. "title": "Mobility",
  13561. "mask": "1"
  13562. },
  13563. "GR": {
  13564. "title": "GR",
  13565. "mask": "2"
  13566. },
  13567. "PP": {
  13568. "title": "PP",
  13569. "mask": "4"
  13570. },
  13571. "BOP": {
  13572. "title": "BOP",
  13573. "mask": "8"
  13574. },
  13575. "Gingival-inflamation": {
  13576. "title": "Gingival-inflamation",
  13577. "mask": "16"
  13578. }
  13579. },
  13580. "abbreviations": {
  13581. "AA": {
  13582. "title": "AA",
  13583. "mask": "1"
  13584. },
  13585. "AS#": {
  13586. "title": "AS#",
  13587. "mask": "2"
  13588. },
  13589. "AP#": {
  13590. "title": "AP#",
  13591. "mask": "4"
  13592. },
  13593. "AV": {
  13594. "title": "AV",
  13595. "mask": "8"
  13596. },
  13597. "BoP": {
  13598. "title": "BoP",
  13599. "mask": "16"
  13600. },
  13601. "MA": {
  13602. "title": "MA",
  13603. "mask": "32"
  13604. },
  13605. "DA": {
  13606. "title": "DA",
  13607. "mask": "64"
  13608. },
  13609. "H": {
  13610. "title": "H",
  13611. "mask": "128"
  13612. },
  13613. "V": {
  13614. "title": "V",
  13615. "mask": "256"
  13616. },
  13617. "D1": {
  13618. "title": "D1",
  13619. "mask": "512"
  13620. },
  13621. "D2": {
  13622. "title": "D2",
  13623. "mask": "1024"
  13624. },
  13625. "D3": {
  13626. "title": "D3",
  13627. "mask": "2048"
  13628. },
  13629. "D4": {
  13630. "title": "D4",
  13631. "mask": "4096"
  13632. },
  13633. "C": {
  13634. "title": "C",
  13635. "mask": "8192"
  13636. },
  13637. "DT": {
  13638. "title": "DT",
  13639. "mask": "16384"
  13640. },
  13641. "CRF": {
  13642. "title": "CRF",
  13643. "mask": "32768"
  13644. },
  13645. "EX": {
  13646. "title": "EX",
  13647. "mask": "65536"
  13648. },
  13649. "EF": {
  13650. "title": "EF",
  13651. "mask": "131072"
  13652. },
  13653. "EDF": {
  13654. "title": "EDF",
  13655. "mask": "262144"
  13656. },
  13657. "EDP": {
  13658. "title": "EDP",
  13659. "mask": "524288"
  13660. },
  13661. "#EDP": {
  13662. "title": "#EDP",
  13663. "mask": "1048576"
  13664. },
  13665. "E": {
  13666. "title": "E",
  13667. "mask": "2097152"
  13668. },
  13669. "ED": {
  13670. "title": "ED",
  13671. "mask": "4194304"
  13672. },
  13673. "F1": {
  13674. "title": "F1",
  13675. "mask": "8388608"
  13676. },
  13677. "F2": {
  13678. "title": "F2",
  13679. "mask": "16777216"
  13680. },
  13681. "F3": {
  13682. "title": "F3",
  13683. "mask": "33554432"
  13684. },
  13685. "GH": {
  13686. "title": "GH",
  13687. "mask": "67108864"
  13688. },
  13689. "IMP": {
  13690. "title": "IMP",
  13691. "mask": "134217728"
  13692. },
  13693. "IL": {
  13694. "title": "IL",
  13695. "mask": "268435456"
  13696. },
  13697. "LL": {
  13698. "title": "LL",
  13699. "mask": "536870912"
  13700. },
  13701. "MO&DO": {
  13702. "title": "MO&DO",
  13703. "mask": "1073741824"
  13704. },
  13705. "AC": {
  13706. "title": "AC",
  13707. "mask": "2147483648"
  13708. },
  13709. "AT": {
  13710. "title": "AT",
  13711. "mask": "4294967296"
  13712. },
  13713. "BR": {
  13714. "title": "BR",
  13715. "mask": "8589934592"
  13716. },
  13717. "CR": {
  13718. "title": "CR",
  13719. "mask": "17179869184"
  13720. },
  13721. "#E": {
  13722. "title": "#E",
  13723. "mask": "34359738368"
  13724. },
  13725. "F": {
  13726. "title": "F",
  13727. "mask": "68719476736"
  13728. },
  13729. "#F": {
  13730. "title": "#F",
  13731. "mask": "137438953472"
  13732. },
  13733. "FD": {
  13734. "title": "FD",
  13735. "mask": "274877906944"
  13736. },
  13737. "GR": {
  13738. "title": "GR",
  13739. "mask": "549755813888"
  13740. },
  13741. "X": {
  13742. "title": "X",
  13743. "mask": "1099511627776"
  13744. },
  13745. "M1": {
  13746. "title": "M1",
  13747. "mask": "2199023255552"
  13748. },
  13749. "M2": {
  13750. "title": "M2",
  13751. "mask": "4398046511104"
  13752. },
  13753. "M3": {
  13754. "title": "M3",
  13755. "mask": "8796093022208"
  13756. }
  13757. },
  13758. "teethposition": {
  13759. "upperleft": {
  13760. "title": "upperleft",
  13761. "mask": "1"
  13762. },
  13763. "upperright": {
  13764. "title": "upperright",
  13765. "mask": "2"
  13766. },
  13767. "lowerleft": {
  13768. "title": "lowerleft",
  13769. "mask": "4"
  13770. },
  13771. "lowerright": {
  13772. "title": "lowerright",
  13773. "mask": "8"
  13774. },
  13775. "position1": {
  13776. "title": "position1",
  13777. "mask": "16"
  13778. },
  13779. "position2": {
  13780. "title": "position2",
  13781. "mask": "32"
  13782. },
  13783. "position3": {
  13784. "title": "position3",
  13785. "mask": "64"
  13786. },
  13787. "position4": {
  13788. "title": "position4",
  13789. "mask": "128"
  13790. },
  13791. "position5": {
  13792. "title": "position5",
  13793. "mask": "256"
  13794. },
  13795. "position6": {
  13796. "title": "position6",
  13797. "mask": "512"
  13798. },
  13799. "position7": {
  13800. "title": "position7",
  13801. "mask": "1024"
  13802. },
  13803. "position8": {
  13804. "title": "position8",
  13805. "mask": "2048"
  13806. },
  13807. "ischildteeth": {
  13808. "title": "ischildteeth",
  13809. "mask": "4096"
  13810. }
  13811. }
  13812. },
  13813. "item": {
  13814. "ITEMCLASS": {
  13815. "PURCHASABLE": {
  13816. "title": "PURCHASABLE",
  13817. "mask": "1"
  13818. },
  13819. "SERVICES": {
  13820. "title": "SERVICES",
  13821. "mask": "2"
  13822. },
  13823. "GOODS": {
  13824. "title": "GOODS",
  13825. "mask": "4"
  13826. },
  13827. "SALEABLE": {
  13828. "title": "SALEABLE",
  13829. "mask": "8"
  13830. },
  13831. "CONSUMABLE": {
  13832. "title": "CONSUMABLE",
  13833. "mask": "16"
  13834. },
  13835. "STOCKABLE": {
  13836. "title": "STOCKABLE",
  13837. "mask": "32"
  13838. },
  13839. "NONSTOCK": {
  13840. "title": "NONSTOCK",
  13841. "mask": "64"
  13842. },
  13843. "DISCOUNTS": {
  13844. "title": "DISCOUNTS",
  13845. "mask": "128"
  13846. },
  13847. "PHARMACEUTICALS": {
  13848. "title": "PHARMACEUTICALS",
  13849. "mask": "256"
  13850. },
  13851. "TERMS": {
  13852. "title": "TERMS",
  13853. "mask": "512"
  13854. },
  13855. "SHEETITEMS": {
  13856. "title": "SHEETITEMS",
  13857. "mask": "1024"
  13858. },
  13859. "CAPITALITEM": {
  13860. "title": "CAPITALITEM",
  13861. "mask": "2048"
  13862. },
  13863. "HIGHRISK": {
  13864. "title": "PURCHASABLE",
  13865. "mask": "4096"
  13866. },
  13867. "PURCHASEINACTIVATED": {
  13868. "title": "PURCHASABLE",
  13869. "mask": "8192"
  13870. },
  13871. "SALEINACTIVATED": {
  13872. "title": "PURCHASABLE",
  13873. "mask": "16384"
  13874. },
  13875. "GENERALITEMS": {
  13876. "title": "GENERALITEMS",
  13877. "mask": "32768"
  13878. },
  13879. }
  13880. },
  13881. "location":{
  13882. "locationclass":{
  13883. "CAN RECEIVE EXTERNAL":{
  13884. "title":"CAN RECEIVE EXTERNAL",
  13885. "mask":"1"
  13886. },
  13887. "SALEABLE":{
  13888. "title":"SALEABLE",
  13889. "mask":"2"
  13890. },
  13891. "CONSUMABLE":{
  13892. "title":"CONSUMABLE",
  13893. "mask":"4"
  13894. },
  13895. "STOCKABLE":{
  13896. "title":"STOCKABLE",
  13897. "mask":"8"
  13898. },
  13899. "PHARMACEUTICALS":{
  13900. "title":"PHARMACEUTICALS",
  13901. "mask":"16"
  13902. },
  13903. "GENERAL ITEMS":{
  13904. "title":"GENERAL ITEMS",
  13905. "mask":"32"
  13906. },
  13907. "CAN RECEIVE INTERNAL":{
  13908. "title":"CAN RECEIVE INTERNAL",
  13909. "mask":"64"
  13910. }
  13911. }
  13912. },
  13913. "user": {
  13914. "roles": {
  13915. "guest": {
  13916. "title": "guest",
  13917. "mask": "1"
  13918. },
  13919. "superadmin": {
  13920. "title": "superadmin",
  13921. "mask": "2"
  13922. },
  13923. "nurseadmin": {
  13924. "title": "nurseadmin",
  13925. "mask": "4"
  13926. },
  13927. "nurse": {
  13928. "title": "nurse",
  13929. "mask": "8"
  13930. },
  13931. "bedadmin": {
  13932. "title": "bedadmin",
  13933. "mask": "16"
  13934. }
  13935. }
  13936. },
  13937. "prescribableform" : {
  13938. "beforebreakfast" : { mask : 1},
  13939. "afterbreakfast" : { mask : 2},
  13940. "emptystomach" : { mask : 4},
  13941. "afterfood" : { mask : 8},
  13942. "beforelunch" : { mask : 16},
  13943. "afterlunch" : { mask : 32},
  13944. "beforedinner" : { mask : 64},
  13945. "afterdinner" : { mask : 128},
  13946. }
  13947. };
  13948. // export { commonmasks };
  13949. var m_common = commonmasks;
  13950. try {
  13951. var x = BigInt(0);
  13952. }
  13953. catch(e){
  13954. console.warn('BigInt check failed. Falling back to Number');
  13955. // PB : TODO -- All Number issues with bitmasks will fail since BigInt is not available.
  13956. // Eg : Older Safari versions will not work
  13957. // PB : TODO -- provide a proper polyfill for older Safari Browsers in the ember build.
  13958. BigInt = Number;
  13959. }
  13960. // -------------------------------
  13961. // Command line option parsing
  13962. // -------------------------------
  13963. function cliargs$1(args, opts) {
  13964. if (!opts) opts = {};
  13965. var flags = { bools : {}, strings : {}, unknownFn: null };
  13966. if (typeof opts['unknown'] === 'function') {
  13967. flags.unknownFn = opts['unknown'];
  13968. }
  13969. if (typeof opts['boolean'] === 'boolean' && opts['boolean']) {
  13970. flags.allBools = true;
  13971. } else {
  13972. [].concat(opts['boolean']).filter(Boolean).forEach(function (key) {
  13973. flags.bools[key] = true;
  13974. });
  13975. }
  13976. var aliases = {};
  13977. Object.keys(opts.alias || {}).forEach(function (key) {
  13978. aliases[key] = [].concat(opts.alias[key]);
  13979. aliases[key].forEach(function (x) {
  13980. aliases[x] = [key].concat(aliases[key].filter(function (y) {
  13981. return x !== y;
  13982. }));
  13983. });
  13984. });
  13985. [].concat(opts.string).filter(Boolean).forEach(function (key) {
  13986. flags.strings[key] = true;
  13987. if (aliases[key]) {
  13988. flags.strings[aliases[key]] = true;
  13989. }
  13990. });
  13991. var defaults = opts['default'] || {};
  13992. var argv = { _ : [] };
  13993. Object.keys(flags.bools).forEach(function (key) {
  13994. setArg(key, defaults[key] === undefined ? false : defaults[key]);
  13995. });
  13996. var notFlags = [];
  13997. if (args.indexOf('--') !== -1) {
  13998. notFlags = args.slice(args.indexOf('--')+1);
  13999. args = args.slice(0, args.indexOf('--'));
  14000. }
  14001. function argDefined(key, arg) {
  14002. return (flags.allBools && /^--[^=]+$/.test(arg)) ||
  14003. flags.strings[key] || flags.bools[key] || aliases[key];
  14004. }
  14005. function setArg (key, val, arg) {
  14006. if (arg && flags.unknownFn && !argDefined(key, arg)) {
  14007. if (flags.unknownFn(arg) === false) return;
  14008. }
  14009. var value = !flags.strings[key] && isNumber(val)
  14010. ? Number(val) : val
  14011. ;
  14012. setKey(argv, key.split('.'), value);
  14013. (aliases[key] || []).forEach(function (x) {
  14014. setKey(argv, x.split('.'), value);
  14015. });
  14016. }
  14017. function setKey (obj, keys, value) {
  14018. var o = obj;
  14019. keys.slice(0,-1).forEach(function (key) {
  14020. if (o[key] === undefined) o[key] = {};
  14021. o = o[key];
  14022. });
  14023. var key = keys[keys.length - 1];
  14024. if (o[key] === undefined || flags.bools[key] || typeof o[key] === 'boolean') {
  14025. o[key] = value;
  14026. }
  14027. else if (Array.isArray(o[key])) {
  14028. o[key].push(value);
  14029. }
  14030. else {
  14031. o[key] = [ o[key], value ];
  14032. }
  14033. }
  14034. function aliasIsBoolean(key) {
  14035. return aliases[key].some(function (x) {
  14036. return flags.bools[x];
  14037. });
  14038. }
  14039. for (var i = 0; i < args.length; i++) {
  14040. var arg = args[i];
  14041. if (/^--.+=/.test(arg)) {
  14042. // Using [\s\S] instead of . because js doesn't support the
  14043. // 'dotall' regex modifier. See:
  14044. // http://stackoverflow.com/a/1068308/13216
  14045. var m = arg.match(/^--([^=]+)=([\s\S]*)$/);
  14046. var key = m[1];
  14047. var value = m[2];
  14048. if (flags.bools[key]) {
  14049. value = value !== 'false';
  14050. }
  14051. setArg(key, value, arg);
  14052. }
  14053. else if (/^--no-.+/.test(arg)) {
  14054. var key = arg.match(/^--no-(.+)/)[1];
  14055. setArg(key, false, arg);
  14056. }
  14057. else if (/^--.+/.test(arg)) {
  14058. var key = arg.match(/^--(.+)/)[1];
  14059. var next = args[i + 1];
  14060. if (next !== undefined && !/^-/.test(next)
  14061. && !flags.bools[key]
  14062. && !flags.allBools
  14063. && (aliases[key] ? !aliasIsBoolean(key) : true)) {
  14064. setArg(key, next, arg);
  14065. i++;
  14066. }
  14067. else if (/^(true|false)$/.test(next)) {
  14068. setArg(key, next === 'true', arg);
  14069. i++;
  14070. }
  14071. else {
  14072. setArg(key, flags.strings[key] ? '' : true, arg);
  14073. }
  14074. }
  14075. else if (/^-[^-]+/.test(arg)) {
  14076. var letters = arg.slice(1,-1).split('');
  14077. var broken = false;
  14078. for (var j = 0; j < letters.length; j++) {
  14079. var next = arg.slice(j+2);
  14080. if (next === '-') {
  14081. setArg(letters[j], next, arg);
  14082. continue;
  14083. }
  14084. if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) {
  14085. setArg(letters[j], next.split('=')[1], arg);
  14086. broken = true;
  14087. break;
  14088. }
  14089. if (/[A-Za-z]/.test(letters[j])
  14090. && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
  14091. setArg(letters[j], next, arg);
  14092. broken = true;
  14093. break;
  14094. }
  14095. if (letters[j+1] && letters[j+1].match(/\W/)) {
  14096. setArg(letters[j], arg.slice(j+2), arg);
  14097. broken = true;
  14098. break;
  14099. }
  14100. else {
  14101. setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg);
  14102. }
  14103. }
  14104. var key = arg.slice(-1)[0];
  14105. if (!broken && key !== '-') {
  14106. if (args[i+1] && !/^(-|--)[^-]/.test(args[i+1])
  14107. && !flags.bools[key]
  14108. && (aliases[key] ? !aliasIsBoolean(key) : true)) {
  14109. setArg(key, args[i+1], arg);
  14110. i++;
  14111. }
  14112. else if (args[i+1] && /true|false/.test(args[i+1])) {
  14113. setArg(key, args[i+1] === 'true', arg);
  14114. i++;
  14115. }
  14116. else {
  14117. setArg(key, flags.strings[key] ? '' : true, arg);
  14118. }
  14119. }
  14120. }
  14121. else {
  14122. if (!flags.unknownFn || flags.unknownFn(arg) !== false) {
  14123. argv._.push(
  14124. flags.strings['_'] || !isNumber(arg) ? arg : Number(arg)
  14125. );
  14126. }
  14127. if (opts.stopEarly) {
  14128. argv._.push.apply(argv._, args.slice(i + 1));
  14129. break;
  14130. }
  14131. }
  14132. }
  14133. Object.keys(defaults).forEach(function (key) {
  14134. if (!hasKey(argv, key.split('.'))) {
  14135. setKey(argv, key.split('.'), defaults[key]);
  14136. (aliases[key] || []).forEach(function (x) {
  14137. setKey(argv, x.split('.'), defaults[key]);
  14138. });
  14139. }
  14140. });
  14141. if (opts['--']) {
  14142. argv['--'] = new Array();
  14143. notFlags.forEach(function(key) {
  14144. argv['--'].push(key);
  14145. });
  14146. }
  14147. else {
  14148. notFlags.forEach(function(key) {
  14149. argv._.push(key);
  14150. });
  14151. }
  14152. return argv;
  14153. }
  14154. /*
  14155. Iterable task should return either truthy or false
  14156. Any fn will return only one value for an array of iterables. If any one iterable fails, the return value would be false.
  14157. If all succeed , the return value will be true.
  14158. If continueOnFailure is false, an execption is raised on any one failure
  14159. */
  14160. function any$1(iterable, continueOnFailure) {
  14161. var cancelsignal = Symbol();
  14162. return iterable.reduce(
  14163. (p, tasq, i ,a) => {
  14164. var handleError = (err, pVal)=>{
  14165. if(err !== cancelsignal) {
  14166. // Cancel only once on first failure.
  14167. console.log('Failed : ' + err.message + ' ' + JSON.stringify(pVal));
  14168. console.dir(p);
  14169. console.warn('Possible failure for task with result : ' + JSON.stringify(pVal));
  14170. if(i>0 && a[i-1].info) console.dir(a[i-1].info);
  14171. console.error('Error : ' + err.stack);
  14172. console.error(a[i-1]);
  14173. a[i-1] ? console.log("tasq : " + a[i-1].toString()) : null;
  14174. if(!continueOnFailure) {console.log("Cancelling remaining on any one failure ..."); throw cancelsignal}
  14175. else return pVal;
  14176. // tasq ? console.log("tasq : " + tasq.toString()) : null; // Previous task is what failed not the one we are going to run.
  14177. }
  14178. };
  14179. if(Promise.resolve(p) === p ) {
  14180. if(i>0 && a[i-1].info) p.info = a[i-1].info;
  14181. return p.then((pVal) => {
  14182. // Falsy values are no longer treated as task failure exceptions. Specially for Promises.
  14183. // Even tasq function wrappers are required to return promises that eventually either resolve or reject..
  14184. // Failures are known for promises on reject.
  14185. // In future if we support direct sync function execution with a result examination for failure
  14186. // we could examine the result of the function as falsy's... or a result evaluator handler needs to be passed in...
  14187. // if(!pVal) handleError({ error : true, message : 'Failed without result' }, pVal)
  14188. // Truthy values are failures if obj has error=true.
  14189. if(pVal && pVal.error) handleError(pVal, pVal);
  14190. var trycall = function(tasq){
  14191. try {
  14192. var result = tasq(); // PB : TODO -- Handle scope for call
  14193. if(tasq.resultHandler) return tasq.resultHandler(result)
  14194. // if(!result) throw result; // Default failure detection for functions is falsy values.
  14195. return result
  14196. } catch (error) {
  14197. console.error(error);
  14198. console.error('Error : ' + error ? error.stack : 'No stack');
  14199. if(!continueOnFailure) throw error; // PB : TODO -- Support array of results for any with or without continueonfailure.
  14200. }
  14201. };
  14202. var handleNext = ()=>{
  14203. console.log('Task finished with result : ' + JSON.stringify(pVal));
  14204. if(i>0 && a[i-1].info) console.dir(a[i-1].info);
  14205. if(!tasq && !continueOnFailure) { console.log('Error : No task specified.'); throw false;}
  14206. else if(!tasq) { console.log('Error : No task specified.'); return false;}
  14207. return (Promise.resolve(tasq) === tasq ) ? tasq : trycall(tasq) ;
  14208. };
  14209. if(Promise.resolve(pVal) === pVal) {
  14210. // Passed in function retured a promise. We still need to wait for it.
  14211. pVal.then((pVal)=>{ return handleNext(); });
  14212. }
  14213. else return handleNext()
  14214. }).catch((error) => {
  14215. if(error !== cancelsignal) {
  14216. console.log(`E3 : i = ${i} `);
  14217. if(error.result) console.error(`error.result`);
  14218. console.error('Error : ' + (error.message || error.messages));
  14219. console.error('Error : ' + error.stack);
  14220. tasq ? console.log("tasq : " + tasq.toString()) : null;
  14221. console.log('debugData 3-------------------------');
  14222. // handleError()
  14223. throw error
  14224. }
  14225. else throw cancelsignal;
  14226. })
  14227. }
  14228. else if(!p) {
  14229. handleError({ error : true, message : 'Failed without result' }, pVal);
  14230. console.log("Bypass remaining on prior failure");
  14231. return false; // All remaining tasks will return false in the any results even if they are promisies still running or functions not initiated.
  14232. }
  14233. else return p; // A truthy value
  14234. }
  14235. , Promise.resolve(true)
  14236. );
  14237. }
  14238. function hasKey (obj, keys) {
  14239. var o = obj;
  14240. keys.slice(0,-1).forEach(function (key) {
  14241. o = (o[key] || {});
  14242. });
  14243. var key = keys[keys.length - 1];
  14244. return key in o;
  14245. }
  14246. function isNumber (x) {
  14247. if (typeof x === 'number') return true;
  14248. if (/^0x[0-9a-f]+$/i.test(x)) return true;
  14249. return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
  14250. }
  14251. // {{from}}, {{to}}
  14252. // -- Extraday bounding range limits
  14253. // -- null => no bounds => infinite past for {{from}} and infinite future for {{to}}
  14254. // {{recurring}} === 0 there is no frequency or pattern that repeats within the bounded range.
  14255. // -- Therefore the bounded range is the SINGULAR event
  14256. // -- => {{start}} === {{from}} and {{end}} === {{to}}
  14257. // {{recurring}} = {{pattern}}
  14258. // Many envents either recurring at a regular or irregular extraday frequency specified by bits in {{recurring}}.
  14259. // => pattern defines the frequency. pattern is limited to frequencies >= 1 day.
  14260. // -- A paterrn of all bits daysbits or datesbits turned on is all days.
  14261. // Example: {{from}} === null, {{to}} === null, recurring ==== 0b111111 is all days.
  14262. // Additional Time and frequence information will be found in
  14263. // {{start}}, {{end}}, {{for}} {{every}} {{duration???}}
  14264. // -- Irregular Time Patterns within a day are currently not supported but can be supported
  14265. // by another intraday recurring pattern mask {{recurrence To be appropriately renamed}}.
  14266. // hour(24bits), min(60 bits), sec(60bits), ms(1000bits ???) match.
  14267. // -- 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.
  14268. // -- All offsets are datetime offsets from 1st Jan 1900 ( SQL Server )
  14269. // {{repeat}} -- is a repeated offset from an anchor. {{from}}, {{start}} are the only anchors.
  14270. // {{period}} -- if period is specified {{end}} is computed as (n-1)*{{repaat}} + {{period}} <= {{to}} boundary. Where n is the number of occurences.
  14271. // It is preferred for {{end}} to always be computed since we need to explode all events to qualify them wth the pattern anyway.
  14272. // {{start}}, {{end}} offsets defining a window with or without a datetime anchor = {{from}} or queried @from normalized to UTC begining of day.
  14273. // -- {{start}} -- Anchored offset to {{from}} or UTC begining of day > queried @from.
  14274. // -- Eg: +8:00 hours from anchor every 24 hours --- {{start}} = 8:00 {{repeat}} = 24hours.
  14275. // => implicitly a recurring repeating subdivision of {{from}} and {{to}} -- defaults to every day if {{every}} is not specified.
  14276. // -- for which day ? => at a minimum {{from}} should not be null
  14277. // -- If no {{from}} and {{to}} are specifed => unbounded so applicable from current date in a windowed form to past and future.
  14278. // -- We only present a windowed set of events for the range being queried.
  14279. // -- Need not be communicated to the client in exploded form. It is the clients responsibility to explode events for presentation.
  14280. // -- Usually an Intraday bounding range but can span multiple days.
  14281. // -- {{recurring}} => filtered by those extraday patterns bound or unbound.
  14282. // -- IMPORTANT NOTE : {{recurring}} is not essential for a recurring event.
  14283. // A recurring pattern is only one way of defining a recurring event mostly irregular patterns.
  14284. // A recurring event with regular intervals can be defined using {{every}} starting at {{start}} or {{from}} if start is not defined.
  14285. // -- {{recurring}} === 0
  14286. // => no pattern but can be recurring, if subdivisions will not repeat beyond {{start}} and {{end}} at an extraday frequency.
  14287. // -- But could be either a single event or an intraday repeating pattern for longer than a single day.
  14288. // -- Since there is no extraday recurring pattern there is nothing to filter for days dates months.
  14289. // -- {{start}} and {{end}} can span multiple consecutive days with or without an extraday pattern.
  14290. // -- specified by the duration between {{start}} and {{end}} from 1st Jan 1970 to whenever {{end}} is.
  14291. // -- single events are better specified as {{from}} and {{to}}
  14292. // -- instead of {{from}} {start} {{end}} which is interpreted equivalent.
  14293. // -- {{every}} => intraday regular frequency of every
  14294. // -- Eg : 2 hours
  14295. // -- {{for}} => for a period of
  14296. // -- Eg : 75 minutes
  14297. // -- {{for}} !== {{every}} provision for intermediate gaps or pauses in the regular {{every}} frequency
  14298. // -- {{duration}} => with an event duration of
  14299. // -- Eg : 15 minutes
  14300. // -- equally distributed and occupying {{for}} without intermediate gaps
  14301. // -- provides for a 3rd level further subdivision at {{for}} without any intermediate gaps.
  14302. // -- {{for}} === {{every}} => {{every}} subdivision has no gaps
  14303. // -- {{duration}} === null => no subdivision of {{for}} => {{for}} is the event
  14304. // -- {{for}} === null => no subdivision of {{every}} {{every}} is itself the event
  14305. // -- Eg : {{start}} = 8:12am 519ms, {{end}} = 8:00pm, {{every}} = 1 hour 6mins 20ms, {{for}} = 13 minutes 5 ms
  14306. // -- PB : TODO -- Do we need an n {{occurences}} limit ? which possibly makes {{end}} redundant. System will pick whichever is earlier.
  14307. // -- Note : It is not possible for {{for}} to repeat and occupy all of {{for}} with equal subdivision
  14308. // However same effect can achived with {{duration}} which occupieas all of {{for}} with {{for}}==={{every}}
  14309. //
  14310. // -- Irregular intraday time frequencies. See discussion above.
  14311. // {{quota}} -- quota limit at event. PB : TODO -- Is this required?
  14312. // The same effect can be achieved with a subdivision of granular time slots
  14313. // However qty will actually be computationally more efficient and address subdivision issues where fractions don't round up properly...
  14314. // {{available}}
  14315. // -- 0 => Unavialability Pattern
  14316. // -- 1 => Availability Pattern
  14317. // -------------------------------------------------------------------
  14318. // timeUtils
  14319. const daysbits = 7;
  14320. const datesbits = 31;
  14321. const monthsbits = 12;
  14322. // 2**53-1 (+/-) is largest integer precision for 64 bit floating point IEE 754
  14323. // 7 + 31 + 12 = 50 bits which fits.
  14324. const datebitOffset = daysbits;
  14325. const monthbitOffset = datesbits + daysbits; // Months are 0 based. So we need to offeset by 1 more so 31st is not overrwritten.
  14326. const monthsMask = 0b111111111111 * 2** (monthbitOffset);
  14327. const datesMask = 0b1111111111111111111111111111111 * 2 ** (datebitOffset);
  14328. const daysMask = 0b1111111;
  14329. var timeUtils = {
  14330. // PB : TODO -- Currently assuming event e1 is a sub 1 day duration. Which may not be true.
  14331. toRecurringPattern( event ){
  14332. var dayBitToSet = event.from.getDay(); // 0 based Index
  14333. var dateBitToSet = event.from.getDate() + datebitOffset - 1; // Dates are 1 based.
  14334. var monthBitToSet = event.from.getMonth() + monthbitOffset; // 0 based
  14335. var recurring = 2**dayBitToSet + 2**dateBitToSet + 2**monthBitToSet;
  14336. // PB : TODO -- loop through all matching masks until the end.
  14337. return {
  14338. from : event.from, to : event.to, recurring: recurring
  14339. , start: new Date ( event.from - new Date( moment(event.from).startOf('day') ) )
  14340. , end: new Date ( event.to - new Date( moment(event.to).startOf('day') ) )
  14341. }
  14342. }
  14343. , getSkipFunction(r, boundedRange){
  14344. var areMonthsSelected = monthsMask & r.recurring;
  14345. var areDatesSelected = datesMask & r.recurring;
  14346. var areDaysSelected = daysMask & r.recurring;
  14347. if(!areMonthsSelected && !areDatesSelected && !areDaysSelected) {
  14348. console.error("Null patterns are useless for selection. This is probably not a recurring pattern");
  14349. return null;
  14350. }
  14351. var filter = { from : boundedRange && boundedRange.from || new Date(moment().startOf('day')), to : boundedRange && boundedRange.to };
  14352. // Returns how much to skip for next available value for a dimension.
  14353. var reset = Symbol('reset');
  14354. var stop = Symbol('stop');
  14355. var skipFn = {
  14356. create : (options)=>{
  14357. var startFrom = options.startFrom;
  14358. options.nBits;
  14359. return {
  14360. originOffset : null // From the origin.
  14361. , getSkipGenerator : (selected)=>{
  14362. var startOffset = null; // From position to start from.
  14363. // var cycleEntryPoint = null;
  14364. var nextCycleIndex = 0;
  14365. var incrementCycle = [];
  14366. var previous = 0;
  14367. // Discover the cycle from the bitmask.
  14368. for(var b = 0; b < nBits; b++) {
  14369. if(selected & 1) {
  14370. if(utils.js.isNull(originOffset)) this.originOffset = b;
  14371. if(utils.js.isNull(startOffset) && (startFrom - b) <= 0){
  14372. // startOffset cannot be negative. cycleEntryPoint is from the origin and is the entrypoint when there is no fitler.from...
  14373. startOffset = b - startFrom; // As measured from filter.from i.e from startingPoint
  14374. // cycleEntryPoint = b
  14375. nextCycleIndex = incrementCycle.length-1; // The place to enter cycle after startoffset aligns to currentCycleIndex.
  14376. }
  14377. incrementCycle.push(1 + b - previous); // We keep pushing and then splice in the first item as the last item to make this cyclical.
  14378. previous = 1 + b; // Minimum incrment is always 1;
  14379. }
  14380. }
  14381. // Due to the cyclical nature incrementCycle[0] has the increment to the second item
  14382. // and incrementCycle[incrementCycle.length-1] points to first item in cycle.
  14383. incrementCycle.push(incrementCycle.splice(0,1));
  14384. if(nextCycleIndex < 0) nextCycleIndex = 0;
  14385. return function*(){
  14386. var signal = false;
  14387. signal = yield startOffset; // Could be 0. Aligns to the first match in the cycle after from.
  14388. var i = nextCycleIndex;
  14389. for(;;){
  14390. for(; i < incrementCycle.length; i++ ) {
  14391. signal = yield incrementCycle[i];
  14392. if(reset === signal) { signal = yield this.originOffset; break; }
  14393. if(signal === stop || signal.done) return null;
  14394. }
  14395. i = 0;
  14396. }
  14397. }
  14398. }
  14399. // Generator for Irregular boundaries.
  14400. , getNextDateGenerator(selection){
  14401. var iterator = this.getSkipGenerator(selection);
  14402. return function*(){
  14403. var nextPotentialDate = moment(potentialDate).add(iterator.next(), 'd');
  14404. if(nextPotentialDate.month() != potentialDate.getMonth()) {
  14405. // Handle month boundary increments.
  14406. nextPotentialDate.startOf('month').add(dateIterator.next(reset), 'm');
  14407. }
  14408. var potentialDate = nextPotentialDate;
  14409. yield nextPotentialDate;
  14410. }
  14411. }
  14412. // Cyclical Generator.
  14413. , getNextGenerator(options, selection){
  14414. this.getSkipGenerator(selection);
  14415. var next = filter.from;
  14416. return function*(){
  14417. yield next = moment(next).add(dayIterator.next(), 'd');
  14418. }
  14419. }
  14420. }
  14421. }
  14422. };
  14423. var monthSkipper = skipFn.create({ nBits : monthsbits, startFrom : filter.from.getMonth() });
  14424. var daySkipper = skipFn.create({ nBits : daysbits, startFrom : filter.from.getDay() });
  14425. var dateSkipper = skipFn.create({ nBits : datebits, startFrom : filter.from.getDate()-1 }); // Skipfn requires a 0 based startFrom.
  14426. if(!areMonthsSelected && !areDatesSelected) return daySkipper(areDaysSelected)
  14427. else if(!areDatesSelected && !areDaysSelected) return monthSkipper(areMonthsSelected/2**(datesbits + daysbits))
  14428. else if(!areMonthsSelected && !areDaysSelected) return dateSkipper(areDatesSelected/2**(daysbits))
  14429. else {
  14430. if(!areMonthsSelected) {
  14431. // Dates, Days are selected.
  14432. return function*(){
  14433. var dateIterator = dateSkipper.getNextDateGenerator({ nBits : datebits, startFrom : filter.from.getDate()-1 }, areDatesSelected/2**(daysbits));
  14434. var dayIterator = daySkipper.getNextGenerator({ nBits : daysbits, startFrom : filter.from.getDay() }, areDaysSelected);
  14435. var potentialDay = null;
  14436. var potentialDate = dateIterator.next(); // Irregular cycle end...
  14437. if(isAnd) {
  14438. // Both day and date shuld match.
  14439. for(;;){
  14440. for(; (potentialDay = dayIterator.next()) < potentialDate ;);
  14441. // PB : TODO -- If we never hit the equals condition this will be a perpetual loop.
  14442. // If both are integer skips we will have a LCM and therefore hit this condition.
  14443. // In the case of sets of irregular skips we still will have the sum of each set also have an LCM.
  14444. // However for irregular boundaries we cannot predict whether an LCM exists and if a equality condition will ever be met.
  14445. // In such cases we need to protect from an infinite loop that will never yield.
  14446. // For dates though despite the irregular boundaries the pattern is that every date, month combination falls on every day of week.
  14447. if(potentialDay == potentialDate) {
  14448. yield potentialDay;
  14449. potentialDate = dateIterator.next();
  14450. continue;
  14451. }
  14452. for(; (potentialDate = dateIterator.next()) < potentialDay;);
  14453. }
  14454. }
  14455. else {
  14456. for(;;){
  14457. for(; (potentialDay = dayIterator.next()) < potentialDate ;) {
  14458. if(stop === (yield potentialDay)) return null;
  14459. }
  14460. if(potentialDay == potentialDate) {
  14461. potentialDate = dateIterator.next();
  14462. continue; // We need to yield in sorted sequence.
  14463. }
  14464. for(; (potentialDate = dateIterator.next()) < potentialDay;) {
  14465. if(stop === (yield potentialDate)) return null;
  14466. }
  14467. }
  14468. }
  14469. }
  14470. }
  14471. }
  14472. }
  14473. , skipThisRecurrable : Symbol('skipThisRecurrable')
  14474. , stopThisIterator : Symbol('stopThisIterator')
  14475. , toEvents( r, boundedRange){
  14476. if(!boundedRange.to) throw 'toEvents requires a bounded Range with an end to terminate. Use generater for unbounded operations'
  14477. ({ from : boundedRange.from || new Date(moment(new Date()).startOf('day')), to : boundedRange.to });
  14478. }
  14479. , jsstart : function(){
  14480. return new Date(moment(new Date(0)).startOf('day')) //1st Jan 1970 12AM local time
  14481. }
  14482. // Returns the whole event that is qualified even by a partial intersection.
  14483. , getEventGenerator : function* (objOrArray, boundedRange, getEvent) {
  14484. getEvent = getEvent || function(r, startOfDayFrom, start, end) {
  14485. var event = Object.assign( {}, r);
  14486. delete event.recurring;
  14487. event.from = new Date (startOfDayFrom.getTime() + start.getTime() + utils.getTZOffsetMilliseconds() );
  14488. event.to = new Date ( startOfDayFrom.getTime() + end.getTime() + utils.getTZOffsetMilliseconds());
  14489. // { from : new Date ( startOfDayFrom.getTime() + start.getTime() ) , to : new Date ( startOfDayFrom.getTime() + end.getTime()) }
  14490. return event
  14491. };
  14492. var recurrables = utils.js.isObject(objOrArray) ? [objOrArray] : objOrArray;
  14493. // We need to start somewhere. We dont need an end as we keep generating perpetually.
  14494. var filter = { from : boundedRange && boundedRange.from || new Date(moment().startOf('day')), to : boundedRange && boundedRange.to };
  14495. for(var gIdx=0; gIdx < recurrables.length; gIdx++){
  14496. // Explode eachRecurrable to list of qualified events
  14497. var eachRecurrable = recurrables[gIdx]; // eachRecurrable -> Recurrable event (eg)
  14498. if( eachRecurrable.to && eachRecurrable.to <= filter.from ) continue; // Disjoint. No need to generate. Usually a past recurring pattern.
  14499. var startFrom = filter.from;
  14500. if( eachRecurrable.from) {
  14501. if(filter.to && filter.to <= eachRecurrable.from ) continue; // Disjoint.
  14502. if(eachRecurrable.from >= filter.from) startFrom = eachRecurrable.from;
  14503. }
  14504. var startOfDayFrom = new Date( moment(startFrom).startOf('day') ); // PB : TODO -- IMP pattern TZ...
  14505. var next = null;
  14506. var stopAt = eachRecurrable.to ? filter.to ? Math.min(filter.to, eachRecurrable.to) : eachRecurrable.to : filter.to ? filter.to : false;
  14507. var shouldStop = stopAt ? ()=>{ return option === this.skipThisRecurrable || next.from >= stopAt } : ()=>{ return option === this.skipThisRecurrable || false }; // Perpetual callee can stop asking for next()..
  14508. // time recurring patterns are sorted and sequential so there is no chance we will find any more after end.
  14509. // which implies there is no need to test the rest of the recurring patterns until end of the boundary
  14510. if(filter.to && eachRecurrable.to) {
  14511. var stopAt = new Date(Min(filter.to, eachRecurrable.to));
  14512. shouldStop = ()=>{ return option === this.skipThisRecurrable || (stopAt <= next.to ? stopAt : false) };
  14513. }
  14514. var start = eachRecurrable.start || this.jsstart();
  14515. var end = eachRecurrable.end || new Date(moment(start).add(1, "d"));
  14516. var option = true;
  14517. next = getEvent(eachRecurrable, startOfDayFrom, start, end);
  14518. while( !shouldStop() ) {
  14519. // PB : TODO -- If we provide an impossible pattern match we will perpetually not match and end up in an infinite loop.
  14520. var patternMatched = this.__hasPatternIntersection(next, eachRecurrable);
  14521. if(patternMatched) option = yield next;
  14522. if(option === this.stopThisIterator) return null;
  14523. // PB : TODO -- Instead of checking every day skip straightaway to the next sequential pattern match.
  14524. startOfDayFrom = new Date( moment(startOfDayFrom).add(1, 'd') );
  14525. next = getEvent(eachRecurrable, startOfDayFrom, start, end);
  14526. }
  14527. }
  14528. }
  14529. // PB : TODO -- Generator that returns a series of intersections events.
  14530. // , recurringIntersectionsG : ()=>{}
  14531. , isEvent : function(obj){
  14532. return !obj.recurring
  14533. }
  14534. , isRecurringPattern : function(obj){
  14535. return obj.recurring
  14536. }
  14537. , hasEventIntersection( e1Orr1, e2Orr2 ){
  14538. return utils.timeUtils.isEvent(e1Orr1) && utils.timeUtils.isRecurringPattern( e2Orr2 ) ? utils.timeUtils.__recurringHasIntersection( e1Orr1, e2Orr2 )
  14539. : utils.timeUtils.isEvent(e2Orr2 ) && utils.timeUtils.isRecurringPattern( e1Orr1 ) ? utils.timeUtils.__recurringHasIntersection( e2Orr2, e1Orr1 )
  14540. : utils.timeUtils.isEvent(e1Orr1) && utils.timeUtils.isEvent(e2Orr2) ? utils.timeUtils.__hasEventIntersection( e1Orr1, e2Orr2 )
  14541. : utils.timeUtils.__willPatternsIntersect( e1Orr1, e2Orr2 ) //(()=>{throw 'PB : TDOO -- To Be implemented'})()
  14542. }
  14543. , __hasPatternIntersection( e1, p2 ){
  14544. var areMonthsSelected = monthsMask & p2.recurring;
  14545. var areDatesSelected = datesMask & p2.recurring;
  14546. var areDaysSelected = daysMask & p2.recurring;
  14547. // PB : TODO -- Gaurd against impossible patters like 29th Feb, 31st April etc...
  14548. if(!areMonthsSelected && !areDatesSelected && !areDaysSelected) {
  14549. console.error("Null patterns are useless for selection. This is probably not a recurring pattern");
  14550. return null; // Null patterns result in null intersection.
  14551. }
  14552. var isAnd = false;
  14553. if(!areMonthsSelected && !areDatesSelected || !areMonthsSelected && !areDaysSelected || !areDatesSelected && !areDaysSelected ) ;
  14554. else {
  14555. isAnd = p2.isAnd;
  14556. }
  14557. var p1 = this.toRecurringPattern(e1);
  14558. var patternMatched = p1.recurring & p2.recurring;
  14559. // 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.
  14560. // And that is what is being queried... for any degree of usefulness.
  14561. return ( isAnd ? p1.recurring === patternMatched : patternMatched );
  14562. // returns truthy pattern that intersects.
  14563. }
  14564. , __willPatternsIntersect( p1, p2 ){
  14565. if(p1.from && p2.to && p2.to <= p1.from) return false;
  14566. if(p2.from && p1.to && p1.to <= p2.from) return false;
  14567. var areMonthsSelected = monthsMask & p2.recurring;
  14568. var areDatesSelected = datesMask & p2.recurring;
  14569. var areDaysSelected = daysMask & p2.recurring;
  14570. // PB : TODO -- Gaurd against impossible patters like 29th Feb, 31st April etc...
  14571. if(!areMonthsSelected && !areDatesSelected && !areDaysSelected) {
  14572. console.error("Null patterns are useless for selection. This is probably not a recurring pattern");
  14573. return null; // Null patterns result in null intersection.
  14574. }
  14575. var isAnd = false;
  14576. if(!areMonthsSelected && !areDatesSelected || !areMonthsSelected && !areDaysSelected || !areDatesSelected && !areDaysSelected ) ;
  14577. else {
  14578. isAnd = p2.isAnd;
  14579. }
  14580. var areP1MonthsSelected = monthsMask & p1.recurring;
  14581. var areP1DatesSelected = datesMask & p1.recurring;
  14582. var areP1DaysSelected = daysMask & p1.recurring;
  14583. // PB : TODO -- Gaurd against impossible patters like 29th Feb, 31st April etc...
  14584. if(!areP1MonthsSelected && !areP1DatesSelected && !areP1DaysSelected) {
  14585. console.error("Null patterns are useless for selection. This is probably not a recurring pattern");
  14586. return null; // Null patterns result in null intersection.
  14587. }
  14588. var isP1And = false;
  14589. if(!areP1MonthsSelected && !areP1DatesSelected || !areP1MonthsSelected && !areP1DaysSelected || !areP1DatesSelected && !areP1DaysSelected ) ;
  14590. else {
  14591. isP1And = p1.isAnd;
  14592. }
  14593. if(isAnd && isP1And === isAnd ) {
  14594. return p1.recurring === p2.recurring;
  14595. }
  14596. else if(isAnd) {
  14597. matchtarget = p2.recurring ;
  14598. }
  14599. else if(isP1And ) {
  14600. matchtarget = p1.recurring ;
  14601. }
  14602. var patternMatched = p1.recurring & p2.recurring;
  14603. // 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.
  14604. // And that is what is being queried... for any degree of usefulness.
  14605. var __patternMatched = ( isAnd || isP1And ? matchtarget === patternMatched : patternMatched );
  14606. if(__patternMatched) {
  14607. if(p1.start && p2.end && p2.end <= p1.start) return false;
  14608. if(p2.start && p1.end && p1.end <= p2.start) return false;
  14609. return true;
  14610. }
  14611. else {
  14612. return false
  14613. }
  14614. // returns truthy pattern that intersects.
  14615. }
  14616. , __recurringHasIntersection(e1, r1){
  14617. // PB : TODO -- Date patterns UTC or Local ? i.e does a Monday mask match UTC Mondays or Local Mondays ????
  14618. // PB : TODO -- Use recunrence generator insteadof startOf today hack based on simplified same day start end assumptions.
  14619. if(e1.from && r1.to && r1.to <= e1.from) return false;
  14620. if(r1.from && e1.to && e1.to <= r1.from) return false;
  14621. // Returns intersection or false.
  14622. return ( utils.timeUtils.__hasPatternIntersection(e1, r1) ) ? (()=>{
  14623. // new Date ( new Date( this.rdata.get('unavailablefrom') ) - new Date( moment().startOf('day') ) )
  14624. var startOfe1 = new Date( moment(e1.from).startOf('day') );
  14625. var r1E = {
  14626. from: new Date(startOfe1.getTime() + r1.start.getTime() + utils.getTZOffsetMilliseconds() )
  14627. , to: new Date(startOfe1.getTime() + r1.end.getTime() + utils.getTZOffsetMilliseconds() )
  14628. };
  14629. return utils.timeUtils.__hasEventIntersection(e1, r1E)
  14630. })()
  14631. : false
  14632. }
  14633. // Checks if two non recurring i.e singular events intersect and if so returns the actual intersection.
  14634. , __hasEventIntersection(e1, e2){
  14635. // PB : TODO -- No assertions for invalid inputs e.from is expected to be <= e.to
  14636. if(!e1.from && !e1.to) return e2;
  14637. if(!e2.from && !e2.to) return e1;
  14638. var e1FromAnde2To = e1.from && e2.to;
  14639. var e2FromAnde1To = e2.from && e1.to;
  14640. var __aFrombTo = (a, b)=>{
  14641. // boundary value overlap is insufficient for intersection. At least 1 millisecond diff is required.
  14642. return (a.from >= b.to ? false
  14643. : a.to && a.to > b.to || !a.to ?
  14644. { from : b.from && b.from > a.from ? b.from : a.from, to : b.to }
  14645. : b.from && b.from >= a.to ? false : { from : b.from && b.from > a.from ? b.from : a.from, to : a.to }
  14646. )
  14647. };
  14648. var result = e1FromAnde2To ? __aFrombTo(e1, e2)
  14649. :( e2FromAnde1To ? __aFrombTo(e2, e1)
  14650. : /* e1FromAnde2To is false and e2FromAnde1To is false => either both froms or both tos exist */
  14651. e1.from ? { from: new Date(Math.max(e1.from, e2.from)) } : { to: new Date(Math.min(e1.to, e2.to)) });
  14652. return result
  14653. }
  14654. , exludeIntersection(freeTimes, e) {
  14655. // Removal of unavilable times will split and splice into the same freeTimes array.
  14656. for(var i =0; i < freeTimes.length; i++) {
  14657. var intersection = timeUtils.hasEventIntersection(freeTimes[i], e);
  14658. if(intersection) {
  14659. // Edit freetime to correct for current collision.
  14660. if(freeTimes[i].from >= intersection.from && freeTimes[i].to <= intersection.to) {
  14661. freeTimes.splice(i,1); i = i-1;
  14662. }
  14663. else {
  14664. var right = Object.assign({}, freeTimes[i]);
  14665. right.from = intersection.to;
  14666. freeTimes[i].to = intersection.from;
  14667. if( right.from < right.to ) {
  14668. freeTimes.splice(++i,0, right); // Skip this we have already processed it.
  14669. }
  14670. }
  14671. }
  14672. }
  14673. }
  14674. , getFreeTimes( tRange, events, dimensions) {
  14675. var freeTimes = [tRange];
  14676. for(var eIdx = 0; eIdx < events.length; eIdx++) {
  14677. var e = events[eIdx];
  14678. timeUtils.exludeIntersection(freeTimes, e);
  14679. if(freeTimes.length === 0) break;
  14680. }
  14681. // { result : freeTimes.length > 0, freeTimes : freeTimes}
  14682. return freeTimes;
  14683. }
  14684. // PB : TODO -- Timeutils Test cases. Comment in production.
  14685. , testAll(){
  14686. // // Disjoint
  14687. // var expected = false
  14688. // var actual = null;
  14689. expected = 2**4 + 2**(6+21) + 2**(5+31+6);
  14690. actual = this.toRecurringPattern(
  14691. { from : new Date('5/21/2020, 11:45:00 PM'), to : new Date('5/22/2020, 00:15:00 AM') } ).recurring;
  14692. if(expected !== actual ) throw (' TEST FAILED toRecurringPattern : expected = ' + expected + ' actual = ' + actual)
  14693. // actual = this.__hasEventIntersection(
  14694. // { from : new Date('5/21/2020, 11:45:00 PM'), to : new Date('5/22/2020, 00:15:00 AM') }
  14695. // , { from : new Date('5/22/2020, 11:45:00 PM'), to : new Date('5/23/2020, 00:15:00 AM') })
  14696. // if(expected !== actual ) throw (' TEST FAILED Disjoint : expected = ' + expected + ' actual = ' + actual)
  14697. // // Interleaved
  14698. // expected = JSON.stringify({ from : new Date('5/22/2020, 00:00:00 AM'), to : new Date('5/22/2020, 00:15:00 AM') })
  14699. // actual = this.__hasEventIntersection(
  14700. // { from : new Date('5/21/2020, 11:45:00 PM'), to : new Date('5/22/2020, 00:15:00 AM') }
  14701. // , { from : new Date('5/22/2020, 00:00:00 AM'), to : new Date('5/22/2020, 00:30:00 AM') })
  14702. // if(expected !== JSON.stringify(actual) ) throw (' TEST FAILED Interleaved : expected = ' + expected + ' actual = ' + JSON.stringify(actual))
  14703. // // Subset
  14704. // expected = JSON.stringify({ from : new Date('5/22/2020, 00:00:00 AM'), to : new Date('5/22/2020, 00:10:00 AM') })
  14705. // actual = this.__hasEventIntersection(
  14706. // { from : new Date('5/21/2020, 11:45:00 PM'), to : new Date('5/22/2020, 00:15:00 AM') }
  14707. // , { from : new Date('5/22/2020, 00:00:00 AM'), to : new Date('5/22/2020, 00:10:00 AM') })
  14708. // if(expected !== JSON.stringify(actual) ) throw (' TEST FAILED Interleaved : expected = ' + expected + ' actual = ' + JSON.stringify(actual))
  14709. // Null
  14710. // Boundary Test Cases....
  14711. var r1 = {
  14712. end: new Date("1970-01-01T11:00:00.000Z")
  14713. , every: null
  14714. , from: new Date("2020-06-04T06:30:00.000Z")
  14715. , id: "DC664060-A0A8-11EA-8B3D-7771F3D49CC1"
  14716. , migrationstate: 1
  14717. , practitionerId: "5FDF1790-8288-11E9-9044-91D8D8658887"
  14718. , purpose: "Meeting"
  14719. , recurring: 106
  14720. , start: new Date("1970-01-01T06:30:00.000Z")
  14721. , status: "SCHEDULED"
  14722. , to: null
  14723. };
  14724. var e1 = {
  14725. availability: false
  14726. , end: null
  14727. , every: null
  14728. , for: null
  14729. , from: new Date("2020-06-08T11:00:00.000Z")
  14730. , id: "AEC5A7E1-A96D-11EA-8DE7-19E354C126F4"
  14731. , migrationstate: 8
  14732. , patientId: "271F4970-F173-4530-A894-68F520BF7945"
  14733. , patientmob: "9944715969"
  14734. , patientname: "SAMUEL RAJA DURAI J"
  14735. , practitionerId: "5FDF1790-8288-11E9-9044-91D8D8658887"
  14736. , purpose: "Appointment"
  14737. , start: null
  14738. , status: "SCHEDULED"
  14739. , to: new Date("2020-06-08T11:15:00.000Z")
  14740. };
  14741. this.hasEventIntersection(e1, r1);
  14742. debugger
  14743. // Iterators
  14744. var eventIterator = this.getEventGenerator({ recurring : 2**1 }); // All Mondays from today.
  14745. for(var i=0, e; i<10 && !(e=eventIterator.next()).done; i++) {
  14746. console.dir(e);
  14747. }
  14748. }
  14749. };
  14750. function promisify(ctx, asyncoperation, arraylikearguments) {
  14751. var originalcallback = arraylikearguments.splice(arraylikearguments.length-1, 1)[0];
  14752. return new Promise(function(resolve, reject) {
  14753. asyncoperation.call(ctx, ...arraylikearguments, function(err, result) {
  14754. if (err) return reject(arguments);
  14755. resolve(arguments);
  14756. });
  14757. }).then((aArr)=>{
  14758. originalcallback(...aArr);
  14759. return aArr[1]
  14760. }).catch(function(aArr){
  14761. originalcallback(...aArr);
  14762. throw aArr[0];
  14763. });
  14764. }
  14765. var Tasq$1 = (function(){
  14766. var __proto__ = {
  14767. };
  14768. var listeners = [];
  14769. function Tasq(first, ...rest){
  14770. first.info = utils.assign({ args : rest }, __proto__);
  14771. return first
  14772. }
  14773. Tasq.create = Tasq;
  14774. Tasq.addlistener = (l)=>{ listeners.push(l); };
  14775. Tasq.catch = (e)=>{ console.error(e); console.error(e.messages.join(' ')); listeners.forEach(l => { l(e); } );};
  14776. Tasq.then = (d)=>{ listeners.forEach(l => { l(null, d); } ); return d};
  14777. return Tasq
  14778. })();
  14779. var Traq$1 = (function(){
  14780. var __proto__ = {};
  14781. var log = {
  14782. SUCCESS : []
  14783. , FAILURE : []
  14784. , SKIPPED : []
  14785. };
  14786. Traq$1 = function(){ return utils.assign({}, __proto__) };
  14787. Traq$1.create = Traq$1;
  14788. Traq$1.statuslog = statuslog;
  14789. function statuslog(err, data){
  14790. if(err) log.FAILURE.push( {err, data} );
  14791. else log.SUCCESS.push(data);
  14792. }
  14793. Traq$1.notify = (event)=>{
  14794. if(event.error) log.FAILURE.push( event );
  14795. else log.SUCCESS.push(event);
  14796. };
  14797. Traq$1.finally = ()=>{
  14798. console.log('Total : ' + (log.SKIPPED.length + log.SUCCESS.length + log.FAILURE.length));
  14799. console.log('Pass : ' + log.SUCCESS.length );
  14800. console.log('Fail : ' + log.FAILURE.length);
  14801. console.log('Skipped : ' + log.SKIPPED.length);
  14802. console.log('FAILURES');
  14803. console.log([JSON.stringify(log.FAILURE)]);
  14804. };
  14805. return Traq$1
  14806. })();
  14807. var tzoffset = 0;
  14808. var utils = {
  14809. commonmasks : m_common,
  14810. escapeRegExp(string) {
  14811. return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
  14812. }
  14813. , getTZOffsetMilliseconds : (()=>{
  14814. var d = new Date();
  14815. var t1 = d.toISOString().replace('Z','');
  14816. var t2 = d.toISOString();
  14817. tzoffset = ( new Date(t2) - (new Date(t1))); // /60/60/1000 -- milliseconds.
  14818. return ()=>{ return tzoffset}
  14819. })()
  14820. , getLocalDateYYYYMMDD(date){
  14821. var d = new Date();
  14822. d.setTime(tzoffset + new Date(date).getTime());
  14823. return d.toISOString().slice(0,10).replace(/-/g,"")
  14824. }
  14825. , assign(target /** , ...sources */) {
  14826. return utils.assign_core(false, ...arguments)
  14827. }
  14828. , assign_caseless(target /** , ...sources */) {
  14829. return utils.assign_core(true, ...arguments)
  14830. }
  14831. // assign
  14832. , assign_core(ignorecase, target /** , ...sources */) {
  14833. // Important use this instead of Object.assign.
  14834. // Object.assign has several limitations.
  14835. // 1) It doesn't skip intermediates if the final overriden value is already determined.
  14836. // This implementation address this.
  14837. // 2) It is shallow and doesn't clone object references and therefore risks side effects to original nested objects.
  14838. // This implementation deep clones objects arrays and other types with some limitations.
  14839. // 3) Does not merge but allways overrides.
  14840. // Merges objects and arrays. Overides primitives.
  14841. // Array merge is by default a concatenation.
  14842. // PB : TODO -- If corresponding array indices have objects they can be merged like lodash.
  14843. // 4) Does not retain non writable and configurable attributes.
  14844. // This implementation copies descirptors so clones retain non writability and configurability identical to the source.
  14845. // 5) Recursion can cause infinite recursion. Object.assign doesn't deal with this.
  14846. // Detects and avides ininite recursion.
  14847. 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.
  14848. var getNormalizedKey = ignorecase ? (key)=>key : (key)=> key.toLowerCase(); // returns a normalized equivalent key.
  14849. // We do a right to left iterations!
  14850. // overrideKeys = true;
  14851. // PB : Note -- IMPORTANT alreadyScanned has side effects..
  14852. var alreadyScanned = (key)=>{
  14853. Object.keys(target).forEach(k => {
  14854. cpi[k.toLowerCase()] = k;
  14855. if(cpi[k.toLowerCase()] !== k){
  14856. Object.defineProperty( target, cpi[k.toLowerCase()], Object.getOwnPropertyDescriptor(target, k) ); // Relocate to new overridden key
  14857. delete target[tkeys[tkidx]]; // PB : TODO -- review that accessors are not called during delete !
  14858. }
  14859. });
  14860. alreadyScanned = ()=>{ return true; }; // Dont do anything next time we are called.
  14861. // Its not necessary that we found it.
  14862. cpi[key.toLowerCase()] ? null : cpi[key.toLowerCase()] = key;
  14863. return false;
  14864. };
  14865. // PB : Note -- IMPORTANT findEqualKey has side effects..
  14866. var findEqualKey = (key) => {
  14867. // If equiv key on the target is what the target key should ultimately be we will cache all possible now.
  14868. // However in the overrideKeys case this is not true in which case we postpone until the first one found in the overrider.
  14869. {
  14870. if(alreadyScanned(key)) { cpi[key.toLowerCase()] ? null : cpi[key.toLowerCase()] = key; } }
  14871. var targetKey = cpi[key.toLowerCase()];
  14872. return { targetKey, propertyDescriptor : Object.getOwnPropertyDescriptor(target, targetKey) }
  14873. };
  14874. var hOP = Object.prototype.hasOwnProperty;
  14875. var __assign = function(ignorecase, target /** , ...sources */) {
  14876. if(utils.js.isUndefined(target)) return; // There is noting to assign to. We just play dumb. Why did the caller even call us ?
  14877. // PB : TODO -- we need a flag to support undefined overrides. Default behavior is to retain as much as possible.
  14878. // if(utils.js.isUndefined(arguments[arguments.length-1])) return undefined;
  14879. var undef = 0;
  14880. for(; undef < arguments.length-1 && utils.js.isUndefined(arguments[arguments.length-undef-1]); undef++); // Skip all undefined overrides.
  14881. if(undef === arguments.length-1) return target;
  14882. if(utils.js.isPrimitive(arguments[arguments.length-1-undef])) return arguments[arguments.length-1-undef];
  14883. else {
  14884. // PB : TODO -- Primitive targets cannot be preserved.
  14885. // Target should be decided on first non primitive discovery.
  14886. // Arrays don't work properly yet...
  14887. // We start with a temporary object and if there is a primitive override it will override this temporary object altogether.
  14888. // PB : TODO -- We could convert primitives to their respective object counterparts... Howeer strings with indexes and arrays will get messy.
  14889. if(utils.js.isPrimitive(target)) {
  14890. target = {};
  14891. } }
  14892. for(var
  14893. finalized = {} // One instance for each structurally corresponding key that has already been overridden. Order need not be guaranteed.
  14894. , overrideOrMerge = function (originalkey) {
  14895. // Decision merge or override default to the following.
  14896. // Primitives are overridden by non Primitives ( arrays or objects )
  14897. // Non Primitives are overridden by Primitives. There is no concept of assigning Primitives as new named attributes of Objects.
  14898. // Objects assigned to Objects will be merged.
  14899. // Arrays assigned to Arrays will be merged i.e concatenated. PB : TOOD -- Order will be ??? target then right to left for sources.
  14900. // PB : TODO -- We should avoid examining or tampering with the value during clone and should find another way to make this decision.
  14901. // We do not want side effects to occur while examining the value. Accessors and proxies can do this.
  14902. // Currently assuming simple use cases at this point...
  14903. // Ideally Accessor Descriptors should be postponed for evaluation when runtime access to value is required.
  14904. var { targetKey, dL } = findEqualKey(originalkey);
  14905. var dR = Object.getOwnPropertyDescriptor(this, originalkey);
  14906. if(!dL) {
  14907. // target did not have what it should be according to what was specifed. Lets check for other possibilities.
  14908. dL = Object.getOwnPropertyDescriptor(target, originalkey);
  14909. if(!dL) { Object.defineProperty( target, targetKey, dR ); finalized[targetKey] = true; return; }
  14910. }
  14911. if(!utils.js.isUndefined( dR.writable )) { // writable attribute is present only in Data Descriptor Case
  14912. var valR = this[originalkey]; // We can examine data descriptors without any side effects. ( PB : TODO -- Proxies ! are expected to be transparent !! )
  14913. if(utils.js.isPrimitive( valR )) {
  14914. finalized[targetKey] = true;
  14915. // Primitive values also are implicitly cloned by Data Descriptors when defineProperty is called.
  14916. // Advantage is writable / configurable permissions are retained instead of simple assignment.
  14917. Object.defineProperty( target, targetKey, dR );
  14918. return
  14919. }
  14920. // If its not primitive it may need to get merged if the Left value is also non primitive and of a compatible type...
  14921. }
  14922. // PB : TODO -- Data descriptor that is not writable needs to be handled !? proper check to handle value etc required.
  14923. if(utils.js.isUndefined( dR.writable ) || utils.js.isUndefined( dL.writable ) ){
  14924. // One or both of them is an accessor descriptor.
  14925. // If either one of them is an accessor we need to postpone the merge to runtime evaluation on access.
  14926. var dChosen = !utils.js.isUndefined( dL.writable ) ? dR : dL; // Figure out which one is the accessor.
  14927. // Accessor Descriptors cannot be examined due to possible side effects and possible differences
  14928. // in the value and its type at the point of execution.
  14929. // Since the accessed value here is meaningless we don't know what type it will eventually be at the point wehre
  14930. // real program code needs the value !!!
  14931. // There are 2 options
  14932. // 1) we could do a decoupling here (at clone time) and capture the value.
  14933. // 2) or we could postpone until run time evaluation.
  14934. // Since in either case We need to examine the value it may be superior to evaluate at runtime and decide then.
  14935. // Although decoupling is important and better done as early as possible the delayed value is more important.
  14936. // PB : TODO -- We should provide a pref to evaluate and decouple at clone time
  14937. // PB : TODO -- The postponing strategy has one more issue where delayed override can clobber target modifications on the left side.
  14938. // -- Causing unexpected values specifically when the delayed override value from the source is expected.
  14939. // Ideally the value that was set intermediately should supercede.
  14940. // -- The preferred behaviour implemented here is to decouple on first set such that the intermediate value set on the clone supercedes.
  14941. // Original getter needs to access value in original context.
  14942. // Setters need to be redirected to "cloned setter" in current context.
  14943. var ctx = this;
  14944. var dRGetter = !utils.js.isUndefined( dR.writable ) ? function(){ return dR.value} : dR.get;
  14945. var dLGetter = !utils.js.isUndefined( dL.writable ) ? function(){ return dL.value} : dL.get;
  14946. var valForSetter = null;
  14947. dR.configurable;
  14948. if(!utils.js.isUndefined( dL.writable )) {
  14949. // Oridinarily since we postpone we need to refrence and reevaluete valL also at access time coz the target val could have been switched.
  14950. // The target is now an accessor which gets decoupled on first set in that case there is no need to re-evaluate.
  14951. // These getters are still valid until such a first set happens until which time the valL remains
  14952. // It is therefore possible to cache the valL and use it instead of target[key] at access time....
  14953. var valL = target[targetKey];
  14954. if(utils.js.isPrimitive(valL)) { dChosen.get = function(){ return dRGetter.call(ctx) }; }
  14955. else { dChosen.get = function(){
  14956. // In this case decoupling could happen on first access instead of first set.
  14957. return utils.assign_core(ignorecase, valL, dRGetter.call(ctx))
  14958. };
  14959. }
  14960. }
  14961. else {
  14962. // rVal could be an accessor or a nonPrimitive. Either case it needs to be mreged in.
  14963. dChosen.get = function(){ return utils.assign_core(ignorecase, dLGetter.call(target), dRGetter.call(ctx)) };
  14964. }
  14965. // __setter ! Although this is running in the current context we cant use the dR.set setter like so dL.set = dR.set
  14966. // this is dangerous as we do not know what else the setter does !!!. We don't konw what the getter does either
  14967. // but we need to do a one time read in any case wheter at clone time or at access time.
  14968. dChosen.set = function(val) {
  14969. // First time set on clone decouples
  14970. dChosen.get = function() { return valForSetter};
  14971. dChosen.set = function(val) { return valForSetter = val };
  14972. dChosen.configurable = true;
  14973. Object.defineProperty( target, targetKey, dChosen );
  14974. return valForSetter = val
  14975. };
  14976. dChosen.configurable = true;
  14977. Object.defineProperty( target, targetKey, dChosen );
  14978. finalized[targetKey] = true;
  14979. return
  14980. }
  14981. // Neither is an accessor. valR is nonPrimitive, dL is not an Accessor
  14982. // Target is also a Data Descriptor. We can examine it as well to take a decision.
  14983. var valL = target[targetKey]; // We can examine data descriptors without any side effects. ( Proxies ! are expected to be transparent !! )
  14984. if(utils.js.isPrimitive( valL )) {
  14985. if(!utils.js.isNull( valR ) && !utils.js.isUndefined( valR )) {
  14986. finalized[targetKey] = true;
  14987. Object.defineProperty( target, targetKey, dR );
  14988. }
  14989. return
  14990. }
  14991. else {
  14992. // Neither is Primitive.
  14993. // console.log('Assign Iter...')
  14994. if(valL === valR) { finalized[targetKey] = true; return true;}
  14995. if(utils.js.isObject( valL ) && utils.js.isObject( valR )) { utils.assign_core(ignorecase, valL, valR ); finalized[targetKey] = true; return;}
  14996. if(utils.js.isArray( valL ) && utils.js.isArray( valR )) { target[targetKey] = valL.concat(valR); finalized[targetKey] = true; return;}
  14997. if(utils.js.isNull( valL ) || utils.js.isNull( valR )) { target[targetKey] = valR; finalized[targetKey] = true; return;}
  14998. if(utils.js.isUndefined( valL ) && utils.js.isUndefined( valR )) { target[targetKey] = valR; finalized[targetKey] = true; return;}
  14999. // Functions are tricky. Closures and bound functinos will continue to refer to source locations and could cause unpredictable behaviour.
  15000. // However if such bound functions are being used the intention must be retention of such linkage.
  15001. if(utils.js.isFunction( valL ) && utils.js.isFunction( valR )) { target[targetKey] = valR; return;}
  15002. // Unsupported assign / merge for property datemodified data types Thu Sep 10 2020 15:59:38 GMT+0530 (India Standard Time)
  15003. // , Thu Sep 10 2020 15:54:22 GMT+0530 (India Standard Time)
  15004. // SAM : TODO dates are not getting merged.
  15005. if(utils.js.isDate( valL ) && utils.js.isDate( valR )) { target[targetKey] = valR; return;}
  15006. var msg = `Unsupported assign / merge for property ${targetKey} data types ` + valL + ' , ' + valR;
  15007. console.error(msg);
  15008. throw msg;
  15009. }
  15010. }
  15011. , appendmissing = function (originalkey) {
  15012. var standardizedKey = getNormalizedKey(originalkey);
  15013. if (!hOP.call(finalized, standardizedKey)) overrideOrMerge.call(this, originalkey);
  15014. }
  15015. // Start from the rightmost and override or merge.
  15016. , _junkvar = Object.keys(arguments[arguments.length-1-undef]).forEach(overrideOrMerge, arguments[arguments.length-1-undef])
  15017. , i = arguments.length-1-undef;
  15018. 2 < i--;
  15019. utils.js.isUndefined(arguments[i]) ? null :
  15020. // Intermediate primitives are useless. Skipped coz the target has already been assigned.
  15021. utils.js.isPrimitive(arguments[i]) ? null
  15022. : Object.keys(arguments[i]).forEach(appendmissing, arguments[i])
  15023. ){}
  15024. return target;
  15025. };
  15026. return __assign(...arguments)
  15027. }
  15028. // PB : TODO -- Proper type checking.
  15029. // , __TPL__typeHandlers : {
  15030. // '[object String]' : defaultFn
  15031. // , '[object Array]' : defaultFn
  15032. // , '[object Object]' : defaultFn
  15033. // , '[object Null]' : defaultFn
  15034. // , '[object Undefined]' : defaultFn
  15035. // , '[object Date]' : defaultFn
  15036. // , '[object RegExp]' : defaultFn
  15037. // , '[object Function]' : defaultFn
  15038. // }
  15039. // PB : TODO -- Proper type checking.
  15040. // Javascript language utilities that should have been really in the language itself.
  15041. , js : {
  15042. typeInstances : [
  15043. ""
  15044. , 0
  15045. , true
  15046. , null
  15047. , // undefined
  15048. , []
  15049. , {}
  15050. , Symbol()
  15051. , new Date()
  15052. , /.*/
  15053. , Promise.resolve(true)
  15054. , function() {}
  15055. , BigInt(0)
  15056. ]
  15057. , proxyable : []
  15058. , nonproxyable : []
  15059. , isString(x) {
  15060. return Object.prototype.toString.call(x) === "[object String]"
  15061. }
  15062. , isNumber(x) {
  15063. return Object.prototype.toString.call(x) === '[object Number]'
  15064. }
  15065. , isBoolean(x) {
  15066. return Object.prototype.toString.call(x) === '[object Boolean]'
  15067. }
  15068. , isNull(x) {
  15069. return Object.prototype.toString.call(x) === '[object Null]'
  15070. }
  15071. , isUndefined(x) {
  15072. return Object.prototype.toString.call(x) === '[object Undefined]'
  15073. }
  15074. , isArray(x) {
  15075. return Object.prototype.toString.call(x) === '[object Array]'
  15076. }
  15077. , isObject(x) {
  15078. return Object.prototype.toString.call(x) === '[object Object]'
  15079. }
  15080. , isSymbol(x) {
  15081. return Object.prototype.toString.call(x) === '[object Symbol]'
  15082. }
  15083. , isDate(x) {
  15084. return Object.prototype.toString.call(x) === '[object Date]'
  15085. }
  15086. , isRegExp(x) {
  15087. return Object.prototype.toString.call(x) === '[object RegExp]'
  15088. }
  15089. , isPromise(x) {
  15090. return Promise.resolve(x) === x
  15091. }
  15092. , isPromiseOrFunction(o) {
  15093. if(utils.js.isPromise( o ) || utils.js.isFunction(o)) return true;
  15094. return false;
  15095. }
  15096. , isFunction(x) {
  15097. return Object.prototype.toString.call(x) === '[object Function]'
  15098. }
  15099. , isBigInt(x) {
  15100. return Object.prototype.toString.call(x) === '[object BigInt]'
  15101. }
  15102. , isDataDescriptor(d) { return (utils.js.isUndefined(d.set) && utils.js.isUndefined(d.get)) ? d : false }
  15103. // Grouping JS Types into 4 Groups
  15104. // Primitives
  15105. // -- boolean, String, Number
  15106. // Arrays
  15107. // Objects
  15108. // Special
  15109. // -- date, regexp, function ... and other unkown types
  15110. , typeGroups() {
  15111. return [
  15112. '[Primitive]'
  15113. , '[Null]'
  15114. , '[Undefined]'
  15115. , '[Symbol]'
  15116. , '[Array]'
  15117. , '[Object]'
  15118. , '[Special]'
  15119. ]
  15120. }
  15121. , typeGroup(x) {
  15122. var tgMap = {
  15123. '[object String]' : '[Primitive]'
  15124. , '[object Number]' : '[Primitive]'
  15125. , '[object Boolean]' : '[Primitive]'
  15126. , '[object Null]' : '[Null]'
  15127. , '[object Undefined]' : '[Undefined]'
  15128. , '[object Symbol]' : '[Symbol]'
  15129. , '[object BigInt]' : '[BigInt]'
  15130. , '[object Array]' : '[Array]'
  15131. , '[object Object]' : '[Object]'
  15132. , '[object Date]' : '[Special]'
  15133. , '[object RegExp]' : '[Special]'
  15134. , '[object Function]' : '[Special]'
  15135. , '[object Promise]' : '[Special]'
  15136. };
  15137. return tgMap[Object.prototype.toString.call(x)]
  15138. }
  15139. , getTypeInfo(x) {
  15140. var typeMap = {
  15141. '[object String]' : //__assign(typeInfo,
  15142. { typeGroup : '[Primitive]', isString : true, isPrimitive : true
  15143. , create : ()=>{return ""} }
  15144. //)
  15145. , '[object Number]' : { typeGroup : '[Primitive]', isNumber : true, isNumeric : true, isPrimitive : true
  15146. , create : ()=>{return 1}}
  15147. , '[object Boolean]' : { typeGroup : '[Primitive]', isBoolean : true, isPrimitive : true
  15148. , create : ()=>{return true}}
  15149. , '[object Null]' : { typeGroup : '[Null]', isNull : true
  15150. , create : ()=>{return null}}
  15151. , '[object Undefined]' : { typeGroup : '[Undefined]', isUndefined : true
  15152. , create : ()=>{return }}
  15153. , '[object Symbol]' : { typeGroup : '[Symbol]', isSymbol : true
  15154. , create : ()=>{return new Symbol()}}
  15155. , '[object BigInt]' : { typeGroup : '[BigInt]', isNumeric : true, isPrimitive : true
  15156. , create : ()=>{return new BigInt()}}
  15157. , '[object Array]' : { typeGroup : '[Array]', isArray : true
  15158. , create : ()=>{return []}}
  15159. , '[object Object]' : { typeGroup : '[Object]', isObject : true
  15160. , create : ()=>{return {}}}
  15161. , '[object Date]' : { typeGroup : '[Special]', isDate : true
  15162. , create : ()=>{return new Date}}
  15163. , '[object RegExp]' : { typeGroup : '[Special]', isRegExp : true
  15164. , create : ()=>{return new RegExp}}
  15165. , '[object Function]' : { typeGroup : '[Special]', isFunction : true
  15166. , create : ()=>{return new Function}}
  15167. , '[object Promise]' : { typeGroup : '[Special]', isPromise : true
  15168. , create : ()=>{ throw "Blank promise cannot be created."}}
  15169. };
  15170. return typeMap[Object.prototype.toString.call(x)]
  15171. }
  15172. , isPrimitive(x) {
  15173. var xType = this.nativeType(x);
  15174. return xType === '[object Boolean]' || xType === '[object String]' || xType === '[object Number]' || xType === '[object Symbol]' ||
  15175. xType === '[object BigInt]'
  15176. }
  15177. , isSpecial(x) {
  15178. return !isArray(x) && !isObject(x) && !isPrimitive(x)
  15179. }
  15180. , nativeTypes() {
  15181. return [
  15182. // Primitives
  15183. '[object String]'
  15184. , '[object Number]'
  15185. , '[object Boolean]'
  15186. , '[object Null]'
  15187. , '[object Undefined]'
  15188. , '[object Symbol]'
  15189. , '[object BigInt]'
  15190. // Non Primitives.
  15191. , '[object Array]'
  15192. , '[object Object]'
  15193. , '[object Date]'
  15194. , '[object RegExp]'
  15195. , '[object Function]'
  15196. , '[object Promise]'
  15197. ]
  15198. }
  15199. , nativeType(x) { return Object.prototype.toString.call(x) }
  15200. }
  15201. // Upsert for a hash ??
  15202. , hashupsert : function(oA, oB){
  15203. Object.keys(oA).forEach(( oAKey )=>{
  15204. if(oB[oAKey]) {
  15205. var distinct = new Set(oA[oAKey]);
  15206. oB[oAKey].forEach((each)=>{
  15207. distinct.add(each);
  15208. });
  15209. oA[oAKey] = Array.from(distinct);
  15210. }
  15211. });
  15212. }
  15213. // Upsert for an array.
  15214. // Also the same as pushdistinct. Target is expected to have only one instance.
  15215. , upsert(arr, val) {
  15216. // 0 -- did nothing
  15217. // 2 -- inserted
  15218. // 3 -- updated
  15219. // PB: TODO -- We can use (new Set(arr)).add ???. But is this more expensive ?
  15220. var found = arr.find((element)=>{ return element === val});
  15221. return found ? utils.js.isObject(val) && utils.js.isObject(val) ? (Object.assign( found, val), 3) : 0
  15222. : (arr.push(val), 2) ;
  15223. }
  15224. // accumulate
  15225. // o[toVectorPropName] which is an array
  15226. // and o[propName] which is a string
  15227. // into vectorTarget which is an array
  15228. // already previously accumulated in a similar manner probably already attached as oTarget[toVectorPropName]
  15229. // 0 or undefined or null -- didnt do anything. ( val doesn't exist )
  15230. // 1 -- created target and inserted val
  15231. // 2 -- didn't create target but inserted val
  15232. // 3 -- didn't create target but updated val and also handled o[propName].
  15233. , accumulate : function(val, o, propName, toVectorPropName, vectorTargetCreator,
  15234. identityEvaluator
  15235. ){
  15236. var created = 0;
  15237. if(utils.js.isUndefined(val)) return; // Nothing to do i.e. nothing was provided to accumulate. We don't accumulate undefined.
  15238. if(val === o[propName]) return; // Nothing to do.
  15239. var vectorTargetContainer = o[toVectorPropName] || (o[toVectorPropName] = {});
  15240. if(!vectorTargetCreator) vectorTargetCreator = { create : (val)=>{
  15241. return val ? vectorTargetContainer[o["id"]] = [val] : [] } };
  15242. var vectorTarget = vectorTargetContainer[o["id"]];
  15243. if(!vectorTarget) {
  15244. created = 1;
  15245. vectorTarget = vectorTargetContainer[o["id"]] = vectorTargetCreator.create(o[propName]);
  15246. }
  15247. if(!identityEvaluator) identityEvaluator = (a, b)=>{ return a === b };
  15248. var upsertResult = 0;
  15249. if(!created && !utils.js.isUndefined(o[propName])) {
  15250. if(!vectorTargetContainer[o["id"]].find((element)=>{ return identityEvaluator(element, o[propName]) })) {
  15251. upsertResult = utils.upsert(vectorTarget, o[propName]);
  15252. }
  15253. }
  15254. upsertResult = utils.upsert(vectorTarget, val);
  15255. return created ? created : upsertResult;
  15256. }
  15257. // async Utils
  15258. , async : {
  15259. all(list, task){
  15260. var queueditems=[];
  15261. list.forEach(function(v, i, a) {
  15262. queueditems.push(task(v, i, a));
  15263. });
  15264. return Promise.all(queueditems)
  15265. }
  15266. }
  15267. // PB : TODO -- Remove these.
  15268. // , fsdb : require('./fsdb/fsdb')
  15269. // , xlsx : require('./fsdb/xlsx')
  15270. // , xlsxvalidator : require('./fsdb/xlsxvalidator')
  15271. , timeUtils
  15272. , dx: dx_1
  15273. , cliargs: cliargs$1
  15274. , any: any$1
  15275. , promisify
  15276. , moment
  15277. , Tasq: Tasq$1
  15278. , Traq: Traq$1
  15279. };
  15280. var utils_1 = utils;
  15281. var naiveFallback = function () {
  15282. if (typeof self === "object" && self) return self;
  15283. if (typeof window === "object" && window) return window;
  15284. throw new Error("Unable to resolve global `this`");
  15285. };
  15286. // https://mathiasbynens.be/notes/globalthis
  15287. var globalThis_1 = (function () {
  15288. if (this) return this;
  15289. // Unexpected strict mode (may happen if e.g. bundled into ESM module)
  15290. // Fallback to standard globalThis if available
  15291. if (typeof globalThis === "object" && globalThis) return globalThis;
  15292. // Thanks @mathiasbynens -> https://mathiasbynens.be/notes/globalthis
  15293. // In all ES5+ engines global object inherits from Object.prototype
  15294. // (if you approached one that doesn't please report)
  15295. try {
  15296. Object.prototype.__defineGetter__('__global__', function() {
  15297. return this;
  15298. });
  15299. __global__.globalThis = __global__; // lolwat
  15300. } catch (error) {
  15301. // Unfortunate case of updates to Object.prototype being restricted
  15302. // via preventExtensions, seal or freeze
  15303. return naiveFallback();
  15304. }
  15305. try {
  15306. // Safari case (window.__global__ works, but __global__ does not)
  15307. if (!__global__) return naiveFallback();
  15308. return __global__;
  15309. } finally {
  15310. delete Object.prototype.__global__;
  15311. }
  15312. })();
  15313. // A selector based channels implementation as compared to a simple array.
  15314. var channelMixin = (function() {
  15315. // get channels that qualify for a selector.
  15316. function getSubscriptions(selector) {
  15317. console.dir(this.__channels);
  15318. var filtered = this.__channels; // start with the world...
  15319. // Selector is a simple list of tags.
  15320. for(var select in selector) {
  15321. if(!filtered[selector[select]]) {
  15322. // If the assumption is that all indexes are properly built it implies this channel doesn't exist.
  15323. return []; // We are looking for all selectors therefore if even one fails we don't have anything.
  15324. }
  15325. filtered = filtered[selector[select]];
  15326. }
  15327. return filtered['__data']; // Flattened array
  15328. }
  15329. function addSubscription(selector, func, context) {
  15330. var unfulfilled = selector.splice(0);
  15331. var filtered = this.__channels; // start with the world...
  15332. console.log(filtered);
  15333. for(var select in unfulfilled) {
  15334. if(!filtered[unfulfilled[select]]) {
  15335. filtered[unfulfilled[select]] = { __data : [] };
  15336. }
  15337. filtered = filtered[unfulfilled[select]];
  15338. unfulfilled = unfulfilled.splice(0,1);
  15339. }
  15340. // PB : TODO -- All accessor paths need to be indexed !
  15341. // Will currently fail if not published and queried in the same order.
  15342. filtered.__data.push({context: context, callback: func});
  15343. }
  15344. return function(){
  15345. this.__channels = {};
  15346. this.getSubscriptions = getSubscriptions;
  15347. this.addSubscription = addSubscription;
  15348. return this;
  15349. }
  15350. })();
  15351. // Mediator pattern.
  15352. var mediator = (function() {
  15353. var __subscribe = function(selector, func, context) {
  15354. var subscriptions = this.channels.getSubscriptions(selector);
  15355. if(subscriptions.length < 1){
  15356. this.channels.addSubscription(selector, func, context);
  15357. }
  15358. return this;
  15359. };
  15360. var __publish = function(selector) {
  15361. console.log('publishing for selector ' + selector);
  15362. var subscriptions = this.channels.getSubscriptions(selector);
  15363. console.log(subscriptions);
  15364. if(subscriptions.length < 1){ return; }
  15365. var args = Array.prototype.slice.call(arguments, 1);
  15366. for(i=0; i < subscriptions.length; i++) {
  15367. subscription = subscriptions[i];
  15368. subscription.callback.apply(subscription.context, args);
  15369. }
  15370. return this;
  15371. };
  15372. return function mediator() {
  15373. var thisObj = this ? this : {};
  15374. Object.defineProperty(thisObj, 'channels', { value : channelMixin.apply({}), writable: false, enumerable : false});
  15375. thisObj.publish = __publish;
  15376. thisObj.subscribe = __subscribe;
  15377. return thisObj;
  15378. };
  15379. })();
  15380. // Unique ID creation requires a high quality random # generator. In the browser we therefore
  15381. // require the crypto API and do not support built-in fallback to lower quality random number
  15382. // generators (like Math.random()).
  15383. var getRandomValues;
  15384. var rnds8 = new Uint8Array(16);
  15385. function rng() {
  15386. // lazy load so that environments that need to polyfill have a chance to do so
  15387. if (!getRandomValues) {
  15388. // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also,
  15389. // find the complete implementation of crypto (msCrypto) on IE11.
  15390. getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto);
  15391. if (!getRandomValues) {
  15392. throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
  15393. }
  15394. }
  15395. return getRandomValues(rnds8);
  15396. }
  15397. 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;
  15398. function validate(uuid) {
  15399. return typeof uuid === 'string' && REGEX.test(uuid);
  15400. }
  15401. /**
  15402. * Convert array of 16 byte values to UUID string format of the form:
  15403. * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
  15404. */
  15405. var byteToHex = [];
  15406. for (var i$1 = 0; i$1 < 256; ++i$1) {
  15407. byteToHex.push((i$1 + 0x100).toString(16).substr(1));
  15408. }
  15409. function stringify(arr) {
  15410. var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  15411. // Note: Be careful editing this code! It's been tuned for performance
  15412. // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
  15413. 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
  15414. // of the following:
  15415. // - One or more input array values don't map to a hex octet (leading to
  15416. // "undefined" in the uuid)
  15417. // - Invalid input values for the RFC `version` or `variant` fields
  15418. if (!validate(uuid)) {
  15419. throw TypeError('Stringified UUID is invalid');
  15420. }
  15421. return uuid;
  15422. }
  15423. //
  15424. // Inspired by https://github.com/LiosK/UUID.js
  15425. // and http://docs.python.org/library/uuid.html
  15426. var _nodeId;
  15427. var _clockseq; // Previous uuid creation time
  15428. var _lastMSecs = 0;
  15429. var _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details
  15430. function v1(options, buf, offset) {
  15431. var i = buf && offset || 0;
  15432. var b = buf || new Array(16);
  15433. options = options || {};
  15434. var node = options.node || _nodeId;
  15435. var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not
  15436. // specified. We do this lazily to minimize issues related to insufficient
  15437. // system entropy. See #189
  15438. if (node == null || clockseq == null) {
  15439. var seedBytes = options.random || (options.rng || rng)();
  15440. if (node == null) {
  15441. // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
  15442. node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];
  15443. }
  15444. if (clockseq == null) {
  15445. // Per 4.2.2, randomize (14 bit) clockseq
  15446. clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;
  15447. }
  15448. } // UUID timestamps are 100 nano-second units since the Gregorian epoch,
  15449. // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
  15450. // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
  15451. // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
  15452. var msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock
  15453. // cycle to simulate higher resolution clock
  15454. var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs)
  15455. var dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression
  15456. if (dt < 0 && options.clockseq === undefined) {
  15457. clockseq = clockseq + 1 & 0x3fff;
  15458. } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
  15459. // time interval
  15460. if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
  15461. nsecs = 0;
  15462. } // Per 4.2.1.2 Throw error if too many uuids are requested
  15463. if (nsecs >= 10000) {
  15464. throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");
  15465. }
  15466. _lastMSecs = msecs;
  15467. _lastNSecs = nsecs;
  15468. _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
  15469. msecs += 12219292800000; // `time_low`
  15470. var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
  15471. b[i++] = tl >>> 24 & 0xff;
  15472. b[i++] = tl >>> 16 & 0xff;
  15473. b[i++] = tl >>> 8 & 0xff;
  15474. b[i++] = tl & 0xff; // `time_mid`
  15475. var tmh = msecs / 0x100000000 * 10000 & 0xfffffff;
  15476. b[i++] = tmh >>> 8 & 0xff;
  15477. b[i++] = tmh & 0xff; // `time_high_and_version`
  15478. b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
  15479. b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
  15480. b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low`
  15481. b[i++] = clockseq & 0xff; // `node`
  15482. for (var n = 0; n < 6; ++n) {
  15483. b[i + n] = node[n];
  15484. }
  15485. return buf || stringify(b);
  15486. }
  15487. function parse$1(uuid) {
  15488. if (!validate(uuid)) {
  15489. throw TypeError('Invalid UUID');
  15490. }
  15491. var v;
  15492. var arr = new Uint8Array(16); // Parse ########-....-....-....-............
  15493. arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;
  15494. arr[1] = v >>> 16 & 0xff;
  15495. arr[2] = v >>> 8 & 0xff;
  15496. arr[3] = v & 0xff; // Parse ........-####-....-....-............
  15497. arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;
  15498. arr[5] = v & 0xff; // Parse ........-....-####-....-............
  15499. arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;
  15500. arr[7] = v & 0xff; // Parse ........-....-....-####-............
  15501. arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;
  15502. arr[9] = v & 0xff; // Parse ........-....-....-....-############
  15503. // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes)
  15504. arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;
  15505. arr[11] = v / 0x100000000 & 0xff;
  15506. arr[12] = v >>> 24 & 0xff;
  15507. arr[13] = v >>> 16 & 0xff;
  15508. arr[14] = v >>> 8 & 0xff;
  15509. arr[15] = v & 0xff;
  15510. return arr;
  15511. }
  15512. function stringToBytes(str) {
  15513. str = unescape(encodeURIComponent(str)); // UTF8 escape
  15514. var bytes = [];
  15515. for (var i = 0; i < str.length; ++i) {
  15516. bytes.push(str.charCodeAt(i));
  15517. }
  15518. return bytes;
  15519. }
  15520. var DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
  15521. var URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';
  15522. function v35 (name, version, hashfunc) {
  15523. function generateUUID(value, namespace, buf, offset) {
  15524. if (typeof value === 'string') {
  15525. value = stringToBytes(value);
  15526. }
  15527. if (typeof namespace === 'string') {
  15528. namespace = parse$1(namespace);
  15529. }
  15530. if (namespace.length !== 16) {
  15531. throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');
  15532. } // Compute hash of namespace and value, Per 4.3
  15533. // Future: Use spread syntax when supported on all platforms, e.g. `bytes =
  15534. // hashfunc([...namespace, ... value])`
  15535. var bytes = new Uint8Array(16 + value.length);
  15536. bytes.set(namespace);
  15537. bytes.set(value, namespace.length);
  15538. bytes = hashfunc(bytes);
  15539. bytes[6] = bytes[6] & 0x0f | version;
  15540. bytes[8] = bytes[8] & 0x3f | 0x80;
  15541. if (buf) {
  15542. offset = offset || 0;
  15543. for (var i = 0; i < 16; ++i) {
  15544. buf[offset + i] = bytes[i];
  15545. }
  15546. return buf;
  15547. }
  15548. return stringify(bytes);
  15549. } // Function#name is not settable on some platforms (#270)
  15550. try {
  15551. generateUUID.name = name; // eslint-disable-next-line no-empty
  15552. } catch (err) {} // For CommonJS default export support
  15553. generateUUID.DNS = DNS;
  15554. generateUUID.URL = URL;
  15555. return generateUUID;
  15556. }
  15557. /*
  15558. * Browser-compatible JavaScript MD5
  15559. *
  15560. * Modification of JavaScript MD5
  15561. * https://github.com/blueimp/JavaScript-MD5
  15562. *
  15563. * Copyright 2011, Sebastian Tschan
  15564. * https://blueimp.net
  15565. *
  15566. * Licensed under the MIT license:
  15567. * https://opensource.org/licenses/MIT
  15568. *
  15569. * Based on
  15570. * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
  15571. * Digest Algorithm, as defined in RFC 1321.
  15572. * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009
  15573. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
  15574. * Distributed under the BSD License
  15575. * See http://pajhome.org.uk/crypt/md5 for more info.
  15576. */
  15577. function md5(bytes) {
  15578. if (typeof bytes === 'string') {
  15579. var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape
  15580. bytes = new Uint8Array(msg.length);
  15581. for (var i = 0; i < msg.length; ++i) {
  15582. bytes[i] = msg.charCodeAt(i);
  15583. }
  15584. }
  15585. return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8));
  15586. }
  15587. /*
  15588. * Convert an array of little-endian words to an array of bytes
  15589. */
  15590. function md5ToHexEncodedArray(input) {
  15591. var output = [];
  15592. var length32 = input.length * 32;
  15593. var hexTab = '0123456789abcdef';
  15594. for (var i = 0; i < length32; i += 8) {
  15595. var x = input[i >> 5] >>> i % 32 & 0xff;
  15596. var hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16);
  15597. output.push(hex);
  15598. }
  15599. return output;
  15600. }
  15601. /**
  15602. * Calculate output length with padding and bit length
  15603. */
  15604. function getOutputLength(inputLength8) {
  15605. return (inputLength8 + 64 >>> 9 << 4) + 14 + 1;
  15606. }
  15607. /*
  15608. * Calculate the MD5 of an array of little-endian words, and a bit length.
  15609. */
  15610. function wordsToMd5(x, len) {
  15611. /* append padding */
  15612. x[len >> 5] |= 0x80 << len % 32;
  15613. x[getOutputLength(len) - 1] = len;
  15614. var a = 1732584193;
  15615. var b = -271733879;
  15616. var c = -1732584194;
  15617. var d = 271733878;
  15618. for (var i = 0; i < x.length; i += 16) {
  15619. var olda = a;
  15620. var oldb = b;
  15621. var oldc = c;
  15622. var oldd = d;
  15623. a = md5ff(a, b, c, d, x[i], 7, -680876936);
  15624. d = md5ff(d, a, b, c, x[i + 1], 12, -389564586);
  15625. c = md5ff(c, d, a, b, x[i + 2], 17, 606105819);
  15626. b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330);
  15627. a = md5ff(a, b, c, d, x[i + 4], 7, -176418897);
  15628. d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426);
  15629. c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341);
  15630. b = md5ff(b, c, d, a, x[i + 7], 22, -45705983);
  15631. a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416);
  15632. d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417);
  15633. c = md5ff(c, d, a, b, x[i + 10], 17, -42063);
  15634. b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162);
  15635. a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682);
  15636. d = md5ff(d, a, b, c, x[i + 13], 12, -40341101);
  15637. c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290);
  15638. b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329);
  15639. a = md5gg(a, b, c, d, x[i + 1], 5, -165796510);
  15640. d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632);
  15641. c = md5gg(c, d, a, b, x[i + 11], 14, 643717713);
  15642. b = md5gg(b, c, d, a, x[i], 20, -373897302);
  15643. a = md5gg(a, b, c, d, x[i + 5], 5, -701558691);
  15644. d = md5gg(d, a, b, c, x[i + 10], 9, 38016083);
  15645. c = md5gg(c, d, a, b, x[i + 15], 14, -660478335);
  15646. b = md5gg(b, c, d, a, x[i + 4], 20, -405537848);
  15647. a = md5gg(a, b, c, d, x[i + 9], 5, 568446438);
  15648. d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690);
  15649. c = md5gg(c, d, a, b, x[i + 3], 14, -187363961);
  15650. b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501);
  15651. a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467);
  15652. d = md5gg(d, a, b, c, x[i + 2], 9, -51403784);
  15653. c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473);
  15654. b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734);
  15655. a = md5hh(a, b, c, d, x[i + 5], 4, -378558);
  15656. d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463);
  15657. c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562);
  15658. b = md5hh(b, c, d, a, x[i + 14], 23, -35309556);
  15659. a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060);
  15660. d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353);
  15661. c = md5hh(c, d, a, b, x[i + 7], 16, -155497632);
  15662. b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640);
  15663. a = md5hh(a, b, c, d, x[i + 13], 4, 681279174);
  15664. d = md5hh(d, a, b, c, x[i], 11, -358537222);
  15665. c = md5hh(c, d, a, b, x[i + 3], 16, -722521979);
  15666. b = md5hh(b, c, d, a, x[i + 6], 23, 76029189);
  15667. a = md5hh(a, b, c, d, x[i + 9], 4, -640364487);
  15668. d = md5hh(d, a, b, c, x[i + 12], 11, -421815835);
  15669. c = md5hh(c, d, a, b, x[i + 15], 16, 530742520);
  15670. b = md5hh(b, c, d, a, x[i + 2], 23, -995338651);
  15671. a = md5ii(a, b, c, d, x[i], 6, -198630844);
  15672. d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415);
  15673. c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905);
  15674. b = md5ii(b, c, d, a, x[i + 5], 21, -57434055);
  15675. a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571);
  15676. d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606);
  15677. c = md5ii(c, d, a, b, x[i + 10], 15, -1051523);
  15678. b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799);
  15679. a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359);
  15680. d = md5ii(d, a, b, c, x[i + 15], 10, -30611744);
  15681. c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380);
  15682. b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649);
  15683. a = md5ii(a, b, c, d, x[i + 4], 6, -145523070);
  15684. d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379);
  15685. c = md5ii(c, d, a, b, x[i + 2], 15, 718787259);
  15686. b = md5ii(b, c, d, a, x[i + 9], 21, -343485551);
  15687. a = safeAdd(a, olda);
  15688. b = safeAdd(b, oldb);
  15689. c = safeAdd(c, oldc);
  15690. d = safeAdd(d, oldd);
  15691. }
  15692. return [a, b, c, d];
  15693. }
  15694. /*
  15695. * Convert an array bytes to an array of little-endian words
  15696. * Characters >255 have their high-byte silently ignored.
  15697. */
  15698. function bytesToWords(input) {
  15699. if (input.length === 0) {
  15700. return [];
  15701. }
  15702. var length8 = input.length * 8;
  15703. var output = new Uint32Array(getOutputLength(length8));
  15704. for (var i = 0; i < length8; i += 8) {
  15705. output[i >> 5] |= (input[i / 8] & 0xff) << i % 32;
  15706. }
  15707. return output;
  15708. }
  15709. /*
  15710. * Add integers, wrapping at 2^32. This uses 16-bit operations internally
  15711. * to work around bugs in some JS interpreters.
  15712. */
  15713. function safeAdd(x, y) {
  15714. var lsw = (x & 0xffff) + (y & 0xffff);
  15715. var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  15716. return msw << 16 | lsw & 0xffff;
  15717. }
  15718. /*
  15719. * Bitwise rotate a 32-bit number to the left.
  15720. */
  15721. function bitRotateLeft(num, cnt) {
  15722. return num << cnt | num >>> 32 - cnt;
  15723. }
  15724. /*
  15725. * These functions implement the four basic operations the algorithm uses.
  15726. */
  15727. function md5cmn(q, a, b, x, s, t) {
  15728. return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b);
  15729. }
  15730. function md5ff(a, b, c, d, x, s, t) {
  15731. return md5cmn(b & c | ~b & d, a, b, x, s, t);
  15732. }
  15733. function md5gg(a, b, c, d, x, s, t) {
  15734. return md5cmn(b & d | c & ~d, a, b, x, s, t);
  15735. }
  15736. function md5hh(a, b, c, d, x, s, t) {
  15737. return md5cmn(b ^ c ^ d, a, b, x, s, t);
  15738. }
  15739. function md5ii(a, b, c, d, x, s, t) {
  15740. return md5cmn(c ^ (b | ~d), a, b, x, s, t);
  15741. }
  15742. var v3 = v35('v3', 0x30, md5);
  15743. function v4(options, buf, offset) {
  15744. options = options || {};
  15745. var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
  15746. rnds[6] = rnds[6] & 0x0f | 0x40;
  15747. rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
  15748. if (buf) {
  15749. offset = offset || 0;
  15750. for (var i = 0; i < 16; ++i) {
  15751. buf[offset + i] = rnds[i];
  15752. }
  15753. return buf;
  15754. }
  15755. return stringify(rnds);
  15756. }
  15757. // Adapted from Chris Veness' SHA1 code at
  15758. // http://www.movable-type.co.uk/scripts/sha1.html
  15759. function f(s, x, y, z) {
  15760. switch (s) {
  15761. case 0:
  15762. return x & y ^ ~x & z;
  15763. case 1:
  15764. return x ^ y ^ z;
  15765. case 2:
  15766. return x & y ^ x & z ^ y & z;
  15767. case 3:
  15768. return x ^ y ^ z;
  15769. }
  15770. }
  15771. function ROTL(x, n) {
  15772. return x << n | x >>> 32 - n;
  15773. }
  15774. function sha1(bytes) {
  15775. var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];
  15776. var H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];
  15777. if (typeof bytes === 'string') {
  15778. var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape
  15779. bytes = [];
  15780. for (var i = 0; i < msg.length; ++i) {
  15781. bytes.push(msg.charCodeAt(i));
  15782. }
  15783. } else if (!Array.isArray(bytes)) {
  15784. // Convert Array-like to Array
  15785. bytes = Array.prototype.slice.call(bytes);
  15786. }
  15787. bytes.push(0x80);
  15788. var l = bytes.length / 4 + 2;
  15789. var N = Math.ceil(l / 16);
  15790. var M = new Array(N);
  15791. for (var _i = 0; _i < N; ++_i) {
  15792. var arr = new Uint32Array(16);
  15793. for (var j = 0; j < 16; ++j) {
  15794. 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];
  15795. }
  15796. M[_i] = arr;
  15797. }
  15798. M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32);
  15799. M[N - 1][14] = Math.floor(M[N - 1][14]);
  15800. M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff;
  15801. for (var _i2 = 0; _i2 < N; ++_i2) {
  15802. var W = new Uint32Array(80);
  15803. for (var t = 0; t < 16; ++t) {
  15804. W[t] = M[_i2][t];
  15805. }
  15806. for (var _t = 16; _t < 80; ++_t) {
  15807. W[_t] = ROTL(W[_t - 3] ^ W[_t - 8] ^ W[_t - 14] ^ W[_t - 16], 1);
  15808. }
  15809. var a = H[0];
  15810. var b = H[1];
  15811. var c = H[2];
  15812. var d = H[3];
  15813. var e = H[4];
  15814. for (var _t2 = 0; _t2 < 80; ++_t2) {
  15815. var s = Math.floor(_t2 / 20);
  15816. var T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[_t2] >>> 0;
  15817. e = d;
  15818. d = c;
  15819. c = ROTL(b, 30) >>> 0;
  15820. b = a;
  15821. a = T;
  15822. }
  15823. H[0] = H[0] + a >>> 0;
  15824. H[1] = H[1] + b >>> 0;
  15825. H[2] = H[2] + c >>> 0;
  15826. H[3] = H[3] + d >>> 0;
  15827. H[4] = H[4] + e >>> 0;
  15828. }
  15829. 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];
  15830. }
  15831. var v5 = v35('v5', 0x50, sha1);
  15832. var nil = '00000000-0000-0000-0000-000000000000';
  15833. function version$1(uuid) {
  15834. if (!validate(uuid)) {
  15835. throw TypeError('Invalid UUID');
  15836. }
  15837. return parseInt(uuid.substr(14, 1), 16);
  15838. }
  15839. var esmBrowser = /*#__PURE__*/Object.freeze({
  15840. __proto__: null,
  15841. v1: v1,
  15842. v3: v3,
  15843. v4: v4,
  15844. v5: v5,
  15845. NIL: nil,
  15846. version: version$1,
  15847. validate: validate,
  15848. stringify: stringify,
  15849. parse: parse$1
  15850. });
  15851. var require$$1 = /*@__PURE__*/getAugmentedNamespace(esmBrowser);
  15852. // var __g = __G.__g;
  15853. globalThis_1.mediator = mediator.apply({});
  15854. // __g.mediator = __g.mediator.apply({})
  15855. console.dir(globalThis_1.mediator);
  15856. const indexHelper = (function(){
  15857. var getPermutations = function(array){
  15858. var permutations = {};
  15859. // l(array.splice(0, 1))
  15860. for(var i in array) {
  15861. // l(array[i]);
  15862. var aclone = array.slice(0);
  15863. aclone.splice(i, 1);
  15864. permutations[array[i]] = getPermutations(aclone );
  15865. }
  15866. return permutations
  15867. };
  15868. var getCombinations = function(array){
  15869. // P & C
  15870. // http://www.scielo.br/scielo.php?script=sci_arttext&pid=S0104-65002001000200009
  15871. var set = [];
  15872. var alen = array.length;
  15873. var combinations = 1 << alen; // Math.pow(2, array.length);
  15874. for (var i = 1; i < combinations ; i++){
  15875. var combination= [];
  15876. for (var j=0;j<alen;j++) {
  15877. if ((i & (1 << j))){
  15878. combination.push(array[j]);
  15879. }
  15880. }
  15881. set.push(combination);
  15882. }
  15883. return set;
  15884. };
  15885. return function(obj) {
  15886. obj.getPermutations = getPermutations;
  15887. // obj.getPermutations = getPermutations_HeapsMethod;
  15888. obj.getCombinations = getCombinations;
  15889. return obj;
  15890. };
  15891. })();
  15892. const AnyStore = (function(){
  15893. // A store that can store any type and lookup any type.
  15894. // Weakmaps cannot have primitives as keys and hashs cannot have objects as keys.
  15895. // This wraps hash and a weakmap into an abstract class that routes to the appropriate
  15896. // store based on the type of the object.
  15897. const getForPrimitive = function(primitive, target) { return target.storeForPrmitives[primitive] };
  15898. const getForObject = function(obj, target) { return target.storeForObjects.get(obj) };
  15899. const getForSymbol = function(symbol, target) { return target.storeForObjects.get(target.__symbolToObj[symbol]) };
  15900. const setForPrimitive = function(primitive, content, target) {
  15901. // PB : -- Note : Importatn -- No difference between 100 and "100" due to JS keys all being strings...
  15902. target.storeForPrmitives[primitive] = content;
  15903. return content;
  15904. };
  15905. const setForObject = function(obj, content, target) {
  15906. // PB : TODO -- need to listen to changes in content and its attributes to re-index it.
  15907. target.storeForObjects.set(obj, content);
  15908. return content;
  15909. };
  15910. const setForSymbol = function(symbol, content, target) {
  15911. // PB : TODO -- need to listen to changes in content and its attributes to re-index it.
  15912. target.storeForObjects.set(target.__symbolToObj[symbol], content);
  15913. return content;
  15914. };
  15915. const getFor = {
  15916. '[object String]' : getForPrimitive
  15917. , '[object Object]' : getForObject
  15918. , '[object Symbol]' : getForSymbol
  15919. };
  15920. getFor['[object Number]'] = getFor['[object String]'];
  15921. getFor['[object Array]'] = getFor['[object Object]'];
  15922. const setFor = {
  15923. '[object String]' : setForPrimitive
  15924. , '[object Object]' : setForObject
  15925. , '[object Symbol]' : setForSymbol
  15926. };
  15927. setFor['[object Number]'] = setFor['[object String]'];
  15928. setFor['[object Array]'] = setFor['[object Object]'];
  15929. function IndexFactory(__symbolFromObj, __symbolToObj, valuecompare) {
  15930. // In some cases we are looking for value equivalence and in others referenced object equivalence.
  15931. // Implicit behavior is to use referenced object equivalence as valuecompare is undefined.
  15932. // What we really need is dereferencing until real value is reached.
  15933. // And value compare in scope even if the value is an extremely long stream of bits..
  15934. // Both of these are expensive in terms of scanning and finding the info required.
  15935. // p[p.Index(what, true)] !! is not a value compare for find.
  15936. // We also need to deal with sorting and filtering....
  15937. if(valuecompare) throw "Not yet implemented."
  15938. return function Index(anyThing, bDontCreate){ return utils_1.js.isPrimitive(anyThing) ? anyThing : (__symbolFromObj.get(anyThing) ? __symbolFromObj.get(anyThing) :
  15939. (()=>{
  15940. if(bDontCreate) return
  15941. var newSymbol = Symbol();
  15942. __symbolFromObj.set(anyThing, newSymbol);
  15943. __symbolToObj[newSymbol] = anyThing;
  15944. return newSymbol })()
  15945. ) }
  15946. }
  15947. function AnyStore(){
  15948. // Dispatch based on type of prop.
  15949. var targ = { storeForPrmitives : {}, storeForObjects : new WeakMap(), __symbolToObj : {}, __symbolFromObj : new WeakMap() };
  15950. var p = new Proxy( targ
  15951. , {
  15952. // PB : TODO -- Proxy handler gets hit for Index function prop..
  15953. get: function (target, prop) { return getFor[utils_1.js.nativeType(prop)](prop, target); }
  15954. , set: function (target, prop, content) { return setFor[utils_1.js.nativeType(prop)](prop, content, target); }
  15955. });
  15956. p.Index = IndexFactory(targ.__symbolFromObj, targ.__symbolToObj);
  15957. p.get = (what)=>{ return p[p.Index(what, true)] };
  15958. p.set = (what, content)=>{ return p[p.Index(what)] = content};
  15959. return p
  15960. }
  15961. AnyStore.create = AnyStore;
  15962. return AnyStore
  15963. })();
  15964. function expandUint32Array(arr, data) {
  15965. const newArray = new Uint32Array(arr.length + data.length);
  15966. newArray.set(arr); // copy old data
  15967. newArray.set(data, arr.length); // copy new data after end of old data
  15968. return newArray;
  15969. }
  15970. const HEX_FFFFFFFF = 0xFFFFFFFF;
  15971. const HEX_FFFF0000 = 0xFFFF0000;
  15972. const HEX_FF00 = 0xFF00;
  15973. const HEX_F0 = 0xF0;
  15974. const HEX_0C = 0x0C;
  15975. const MAX_32BITS = HEX_FFFFFFFF;
  15976. const MAX_53BITS = Number.MAX_SAFE_INTEGER;
  15977. const BIGINT_HEX_FFFFFFFF = BigInt(HEX_FFFFFFFF);
  15978. BigInt(HEX_FFFF0000);
  15979. BigInt(HEX_FF00);
  15980. BigInt(HEX_F0);
  15981. BigInt(HEX_0C);
  15982. const BIGINT_MAX_32BITS = BIGINT_HEX_FFFFFFFF;
  15983. const BIGINT_0 = BigInt(0);
  15984. const BIGINT_1 = BigInt(1);
  15985. BigInt(2);
  15986. BigInt(4);
  15987. BigInt(8);
  15988. BigInt(16);
  15989. const BIGINT_32 = BigInt(32);
  15990. // Only Positive numbers;
  15991. function *bigIntBufferGenerator(bn){
  15992. // len = len || find32BitArrLen(bn); // Inefficeint to detect. Lets just iterate and see where it ends...
  15993. var signal = {};
  15994. var stop = Symbol();
  15995. var i = 0;
  15996. for(;;){
  15997. var bits32 = new Uint32Array(1);
  15998. if(bn > MAX_32BITS){
  15999. bits32[0]= Number((bn & BIGINT_MAX_32BITS));
  16000. signal = (yield {i, bits32}) || {};
  16001. if(signal === stop || signal.done) return {i, bits32};
  16002. bn >>= BIGINT_32;
  16003. i++;
  16004. }
  16005. else {
  16006. bits32[0] = Number(bn);
  16007. return {i, bits32};
  16008. }
  16009. }
  16010. }
  16011. function bigIntToBuffer(bn) {
  16012. // if(utils.js.isUndefined(bn) || utils.js.isNull(bn)) throw 'bigIntToBuffer suported only for BigInts...'
  16013. if(!utils_1.js.isBigInt(bn)) throw 'bigIntToBuffer suported only for BigInts...'
  16014. // PB : Note -- bn must be passed in. Callee should validate.
  16015. var buffer = null;
  16016. var iterator = bigIntBufferGenerator(bn);
  16017. var next = iterator.next();
  16018. if(next && !next.done) buffer = next.value.bits32;
  16019. else return next.value.bits32;
  16020. while(!(next = iterator.next()).done) {
  16021. // PB : TODO -- Ineffficient copy in a loop !!
  16022. // It would be really nice to know how much space is needed. In the absence lets do binary expansion.
  16023. buffer = expandUint32Array(buffer, next.value.bits32);
  16024. }
  16025. buffer = expandUint32Array(buffer, next.value.bits32);
  16026. return buffer;
  16027. }
  16028. function bufferToBigInt(buffer) {
  16029. // PB : Note -- buffer must be a Uint32Array. Callee should validate.
  16030. var bn = BIGINT_0;
  16031. for(var i=buffer.length; --i > -1;){ bn <<= BIGINT_32; bn |= BigInt(buffer[i]); }
  16032. return bn;
  16033. }
  16034. // A bitmask can also be specified by a index number of the bit in a BitArray
  16035. // Implemented as a class to distinguish from a mask value.
  16036. // For convenieance mask value is provided the ability to be passed in as a Number althout BitIndexes are more naturally in the Number Space..
  16037. // mask values larger than 32 bits will implicitly need to be converted to BitArrays.
  16038. const BitIndex = (function() { function BitIndex(){ return this } // BitIndex constructor.
  16039. // Should support Numbers, BigInt and Uint32Array.
  16040. function __is__(t){ if(t === BitIndex) return true; }
  16041. function __is(type){ return typeof this === type ? true : __is__(type) }
  16042. function __create(n){
  16043. return BitIndex.apply({
  16044. value : n
  16045. , is : __is
  16046. })
  16047. }
  16048. __create.create = __create;
  16049. return __create
  16050. })();
  16051. // function leftshift(m){ return utils.js.isNumber(m) ? leftshift_Number(m) : leftshift_BigInt(m) } // Universal.
  16052. function leftshift_Number(m){ return m << 1 }
  16053. function leftshift_BigInt(m){ return m << BIGINT_1 }
  16054. // function leftshift_Uint32Array(m) { throw "leftshift_Uint32Array not yet implemented." }
  16055. function indexOfLSB32(x, gptwo){
  16056. // x needs to be a 32 bit number.
  16057. // Private functions don't do validations to avoid overhead of validation.
  16058. // Only public api's need to validate inputs.
  16059. if(x === 0) return null;
  16060. var i = 0;
  16061. x & 0xFFFF0000 && (i += 16, x >>= 16),
  16062. x & 0xFF00 && (i += 8, x >>= 8),
  16063. x & 0xF0 && (i += 4, x >>= 4),
  16064. x & 0x0C && (i += 2, x>>= 2),
  16065. x & 2 && (i += 1);
  16066. // x & 1 && (i = 0);
  16067. return i;
  16068. }
  16069. // PB : TODO -- Not yet implemented... profile to see if this is any more performant.
  16070. // function indexOfLSB_BigInt_DeBruijn(x, gptwo){
  16071. // // x needs to be a BigInt.
  16072. // // gptwo needs to be BigInt
  16073. // // Private functions don't do validations to avoid overhead of validation.
  16074. // // Only public api's need to validate inputs.
  16075. // if(x === 0) return null;
  16076. // gptwo = gptwo || x & -x;
  16077. // // DeBruijn explodes on multiplication and needs to work on BigInts even if the results are containted in 32 bits...
  16078. // // PB : TODO -- Not sure if this is faster. In any case BigInts are slower.
  16079. // var MultiplyDeBruijnBitPosition = [
  16080. // 0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
  16081. // 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
  16082. // ];
  16083. // return MultiplyDeBruijnBitPosition[( ( gptwo * BigInt( 0x077CB531 )) >> BigInt(27) ) % BigInt(32) ];
  16084. // }
  16085. // https://stackoverflow.com/questions/757059/position-of-least-significant-bit-that-is-set
  16086. // http://graphics.stanford.edu/~seander/bithacks.html
  16087. const BitArrayUpto32Bits = (function(){
  16088. function validateBitLength(length){ if(length > 32) throw 'BitArrayUpto32Bits doesnt accept BitLength > 32' }
  16089. function __createA(arr){
  16090. validateBitLength(arr.length);
  16091. var created = __create();
  16092. // PB : TODO -- Changes this to preincrement. Mask need not overflow for 32 bits...
  16093. var iterateUpto = [
  16094. ()=>{for(var i =0 ; i < 1; i++) { console.log(i); created.assignMask(arr[i], { title : arr[i]}); }}
  16095. , ()=>{for(var i =1 ; i < Math.min(31, arr.length); i++) { console.log(i); created.assignMask(arr[i], { title : arr[i]}, leftshift_Number ); }}
  16096. , ()=>{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 } ); }}
  16097. ];
  16098. arr.length > 31 ? iterateUpto.forEach(f=>f()) :
  16099. arr.length > 1 ? iterateUpto.slice(0,2).forEach(f=>f()) :
  16100. iterateUpto[0]();
  16101. return created;
  16102. }
  16103. function __createO(o){
  16104. var arr = Object.keys(o);
  16105. validateBitLength(arr.length);
  16106. var created = __create();
  16107. var iterateUpto = [
  16108. ()=>{for(var i =0 ; i < 1; i++) { console.log(i); created.assignMask(arr[i], o[arr[i]]); }}
  16109. , ()=>{for(var i =1 ; i < Math.min(31, arr.length); i++) { console.log(i); created.assignMask(arr[i], o[arr[i]], leftshift_Number ); }}
  16110. , ()=>{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 } ); }}
  16111. ];
  16112. arr.length > 31 ? iterateUpto.forEach(f=>f()) :
  16113. arr.length > 1 ? iterateUpto.slice(0,2).forEach(f=>f()) :
  16114. iterateUpto[0]();
  16115. return created;
  16116. }
  16117. function __create(){
  16118. var labels = {};
  16119. var masks = {};
  16120. var currentMaxMask;
  16121. function __nextMask(){ __nextMask = leftshift_Number;
  16122. return currentMaxMask = 1; }
  16123. // var store = ??? new Uint32Array(1)var mxn = Mixin.create()
  16124. utils_1.assign(mxn,
  16125. {
  16126. validateMask(m){
  16127. if(__is(m, BitIndex)) {
  16128. if(m > 32) throw 'BitArrayUpto32Bits doesnt accept BitIndex > 32'
  16129. return { BitIndex, labels : [masks[indexToMask(m.value)]]
  16130. // , indices : m.value
  16131. }
  16132. }
  16133. if(m > MAX_32BITS) throw "BitArrayUpto32Bits only supports numbers upto MAX_32BITS "
  16134. if(!utils_1.js.isNumber(+m)) throw "BitArrayUpto32Bits requires Numbers upto MAX_32BITS "
  16135. return true;
  16136. }
  16137. , labelsToMask : (__labels)=>{
  16138. var result = 0; __labels.forEach(l=>{ result |= labels[l]; });
  16139. return result >>> 0;
  16140. }
  16141. , hasMask : function(label) { return labels[label] ? labels[label].mask : null ; }
  16142. , maskToLabels(m, transformEach){
  16143. var valid = this.validateMask(m);
  16144. if(!valid) throw "Invalid Mask"
  16145. if(valid.BitIndex) return valid.labels;
  16146. var __labels = [];
  16147. for(var gptwo;gptwo=m&-m;m^=gptwo) {
  16148. if(!masks[gptwo]) { console.log('Error : Invalid mask passed in.'); }
  16149. else __labels.push( transformEach(masks[Number(gptwo)], labels[masks[Number(gptwo)]]) );
  16150. }
  16151. return __labels;
  16152. }
  16153. , labelToMask : (l)=>{ return labels[l] }
  16154. , bit_or : (a, b)=>a | b
  16155. , bit_and : (a, b)=>a & b
  16156. , bit_xor : (a, b)=>a ^ b
  16157. , bit_not : (a)=> ~a
  16158. , assignMask : function(label, entity, incrementFn) {
  16159. var lmask = this.hasMask(label); if(lmask) return lmask; // Already assigned.
  16160. labels[label] = entity;
  16161. 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.
  16162. masks[labels[label].mask] = label;
  16163. return labels[label];
  16164. }
  16165. , msbIndex : function(v) { throw "msb Not yet implemented" }
  16166. , indexToMask : function(index) {
  16167. if(index > 31) throw 'Not supported beyond 32 bits.'
  16168. return (1 << index) >>> 0;
  16169. }
  16170. , indicesToMask : function(indices){
  16171. var mask = 0;
  16172. indices.forEach(index=>{
  16173. if(index > 31) throw 'Not supported beyond 32 bits.'
  16174. mask |= (1 << index);
  16175. });
  16176. return mask >>> 0;
  16177. }
  16178. , maskToIndices : function(m) {
  16179. var valid = this.validateMask(m);
  16180. if(!valid) throw "Invalid Mask"
  16181. if(valid.BitIndex) return [m.value];
  16182. var indices = [];
  16183. var gptwo;
  16184. for (;gptwo=m&-m;m^=gptwo) indices.push(indexOfLSB32(gptwo));
  16185. return indices;
  16186. }
  16187. , bit_shiftl : (a, s)=>{ return a << s }
  16188. , bit_shiftr : (a, s)=>{ return a >> s }
  16189. , bit_shiftr_uz : (a)=>{ return a >>> 0} // Unsigned right shift by 0.
  16190. // , bit_shiftl_1 : ()=>{}
  16191. , toJSON(radix, eachFn){
  16192. var transFormed = {};
  16193. if(!eachFn) return labels;
  16194. Object.keys(labels).forEach(label =>{
  16195. transFormed[label] = eachFn(labels[label]);
  16196. });
  16197. return transFormed;
  16198. }
  16199. , test(){
  16200. Object.keys(masks).forEach((v, i)=> {
  16201. console.log( v );
  16202. console.log( i + ' : ' + v.toString(2) );
  16203. console.log( this.maskToIndices(v));
  16204. });
  16205. console.log( (173).toString(2) );
  16206. this.maskToIndices(173).map( (i)=>{ console.log( i ); });
  16207. console.log('indicesToMask :' + this.indicesToMask([1,4,31]).toString(2));
  16208. }
  16209. });
  16210. }
  16211. var creatorFor = {
  16212. '[object Array]' : __createA
  16213. , '[object Object]' : __createO
  16214. , 'undefined' : function(){ return __create() }
  16215. };
  16216. // PB : TODO -- Constructor is not preserved... But mixing in an external passed in object is what we want to achive.
  16217. function BitArrayUpto32Bits(){
  16218. return arguments.length ? creatorFor[utils_1.js.nativeType(arguments[0])](...arguments) :
  16219. creatorFor['undefined'](...arguments)}
  16220. BitArrayUpto32Bits.create = BitArrayUpto32Bits;
  16221. return BitArrayUpto32Bits
  16222. })();
  16223. const Mixin = (function(){
  16224. function create(){
  16225. var __mixins = new WeakMap();
  16226. __mixins.set(Mixin, true);
  16227. function __is__(t, type){
  16228. if(utils_1.js.isPrimitive(t)) return false;
  16229. if(!t || !t.mixins) return false;
  16230. return t.mixins().get(type) ? true : false ; }
  16231. function __is(v, type){ return typeof v === type ? true : __is__(v, type) }
  16232. return { addMixin : (clazz)=>{ __mixins.set(clazz, true);}
  16233. , is : __is
  16234. }
  16235. }
  16236. return {create}
  16237. })();
  16238. const BitArrayBigInt = (function(){
  16239. function __createA(arr){
  16240. var created = __create();
  16241. for(var i =0 ; i < 1; i++) { created.assignMask(arr[i], { title : arr[i]}); }
  16242. for(var i =1 ; i < arr.length; i++) { created.assignMask(arr[i], { title : arr[i]}, leftshift_BigInt ); }
  16243. return created;
  16244. }
  16245. function __createO(o){
  16246. var arr = Object.keys(o);
  16247. var created = __create();
  16248. for(var i =0 ; i < 1; i++) { created.assignMask(arr[i], o[arr[i]]); }
  16249. for(var i =1 ; i < arr.length; i++) { created.assignMask(arr[i], o[arr[i]], leftshift_BigInt ); }
  16250. return created;
  16251. }
  16252. function __create(){
  16253. var labels = {};
  16254. var masks = {};
  16255. var currentMaxMask;
  16256. function __nextMask(){ __nextMask = leftshift_BigInt;
  16257. return currentMaxMask = BIGINT_1; }
  16258. // var store = ??? new Uint32Array(1)
  16259. var mxn = Mixin.create();
  16260. var created = utils_1.assign(mxn,
  16261. {
  16262. validateMask(m){
  16263. if(mxn.is(m, BitIndex)) {
  16264. return { BitIndex, labels : [masks[indexToMask(m.value)]] }
  16265. }
  16266. if(!utils_1.js.isBigInt(BigInt(m))) throw "BitArrayBigInt requires BigInt Mask "
  16267. return true;
  16268. }
  16269. , labelsToMask : (__labels)=>{
  16270. var result = BIGINT_0; __labels.forEach(l=>{ result |= labels[l]; });
  16271. return result ;
  16272. }
  16273. , hasMask : function(label) { return labels[label] ? labels[label].mask : null ; }
  16274. , maskToLabels(m, transformEach){
  16275. m = BigInt(m);
  16276. var valid = this.validateMask(m);
  16277. if(!valid) throw "Invalid Mask"
  16278. if(valid.BitIndex) return valid.labels;
  16279. var __labels = [];
  16280. for(var gptwo;gptwo=m&-m;m^=gptwo) {
  16281. if(!masks[gptwo]) { console.log('Error : Invalid mask passed in.'); }
  16282. else __labels.push( transformEach(masks[Number(gptwo)], labels[masks[Number(gptwo)]]) );
  16283. }
  16284. return __labels;
  16285. }
  16286. , labelToMask : (l)=>{ return labels[l] }
  16287. , bit_or : (a, b)=>a | b
  16288. , bit_and : (a, b)=>a & b
  16289. , bit_xor : (a, b)=>a ^ b
  16290. , bit_not : (a)=> ~a
  16291. , assignMask : function(label, entity, incrementFn) {
  16292. var lmask = this.hasMask(label); if(lmask) throw `Duplicate assignment for same label ${label} not allowed : mask (${lmask}) ` // Already assigned.
  16293. labels[label] = entity;
  16294. 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.
  16295. masks[labels[label].mask] = label;
  16296. return labels[label];
  16297. }
  16298. , msbIndex : function(v) { throw "msb Not yet implemented" }
  16299. , indexToMask : function(index) {
  16300. return BIGINT_1 << index;
  16301. }
  16302. , indicesToMask : function(indices){
  16303. var mask = 0;
  16304. indices.forEach(index=>{
  16305. mask |= (1 << index);
  16306. });
  16307. return mask;
  16308. }
  16309. , maskToIndices : function(m) {
  16310. var valid = this.validateMask(m);
  16311. if(!valid) throw "Invalid Mask"
  16312. if(valid.BitIndex) return [m.value];
  16313. var indices = [];
  16314. var gptwo;
  16315. var iterator = bigIntBufferGenerator(BigInt(m));
  16316. var next;
  16317. // if(next && !next.done) buffer = next.value.bits32;
  16318. // else return next.value.bits32;
  16319. var i = 0;
  16320. while(!(next = iterator.next()).done) {
  16321. next.value.bits32 > 0 ?
  16322. ( ()=> { for(;gptwo=(next.value.bits32& -next.value.bits32) ;next.value.bits32^=gptwo) indices.push(32 * i + indexOfLSB32(gptwo)); } )
  16323. : null;
  16324. i++;
  16325. }
  16326. for(;gptwo=(next.value.bits32&-next.value.bits32);next.value.bits32^=gptwo) indices.push(32 * i + indexOfLSB32(gptwo));
  16327. return indices;
  16328. }
  16329. , bit_shiftl : (a, s)=>{ return a << s }
  16330. , bit_shiftr : (a, s)=>{ return a >> s }
  16331. , bit_shiftr_uz : (a)=>{ throw "BigInt doesnt suppored unsigned right shift."} // Unsigned right shift by 0.
  16332. // , bit_shiftl_1 : ()=>{}
  16333. , toJSON(radix, eachFn){
  16334. var transFormed = {};
  16335. if(!eachFn) return labels;
  16336. Object.keys(labels).forEach(label =>{
  16337. transFormed[label] = eachFn(labels[label]);
  16338. });
  16339. return transFormed;
  16340. }
  16341. , tosqlcte() {
  16342. var select = '';
  16343. // debugger
  16344. Object.keys(labels).forEach((label, index, array) =>{
  16345. var labelObject = labels[label];
  16346. var rowselect = 'select ';
  16347. Object.keys(labelObject).forEach((key, index, array) =>{
  16348. rowselect = rowselect + ` '${labelObject[key]}' ${key}`;
  16349. if(array.length !== index+1) rowselect = rowselect + ',';
  16350. });
  16351. select = select + rowselect;
  16352. if(array.length !== index+1) select = select + '\n union all \n';
  16353. });
  16354. console.log(select);
  16355. return labels
  16356. }
  16357. , test(){
  16358. Object.keys(masks).forEach((v, i)=> {
  16359. console.log( v );
  16360. console.log( i + ' : ' + v.toString(2) );
  16361. console.log( this.maskToIndices(v));
  16362. });
  16363. console.log( (173).toString(2) );
  16364. this.maskToIndices(173).map( (i)=>{ console.log( i ); });
  16365. console.log('indicesToMask :' + this.indicesToMask([1,4,31]).toString(2));
  16366. console.log(BigInt(2535301200456458802993406410752));
  16367. console.log('bigIntToBuffer : ' + bigIntToBuffer(BigInt(2535301200456458802993406410752) ));
  16368. console.log('bufferToBigInt : ' + bufferToBigInt( bigIntToBuffer(BigInt(2535301200456458802993406410752)) ));
  16369. }
  16370. }
  16371. );
  16372. created.addMixin(BitArrayBigInt);
  16373. return created;
  16374. }
  16375. var creatorFor = {
  16376. '[object Array]' : __createA
  16377. , '[object Object]' : __createO
  16378. , 'undefined' : function(){ return __create() }
  16379. };
  16380. // PB : TODO -- Constructor is not preserved... But mixing in an external passed in object is what we want to achive.
  16381. function BitArrayBigInt(){
  16382. return arguments.length ? creatorFor[utils_1.js.nativeType(arguments[0])](...arguments) :
  16383. creatorFor['undefined'](...arguments)}
  16384. BitArrayBigInt.create = BitArrayBigInt;
  16385. return BitArrayBigInt
  16386. })();
  16387. // > 32 bits upto 53 bits.
  16388. const BitArrayUpto53Bits = (function(){
  16389. function validateBitLength(length){ if(length > 53) throw 'BitArrayUpto53Bits doesnt accept BitLength > 53' }
  16390. function __createO(o, options){
  16391. var arr = Object.keys(o);
  16392. validateBitLength(arr.length);
  16393. var created = __create();
  16394. var iterateUpto = [
  16395. ()=>{for(var i =0 ; i < 1; i++) { console.log(i); created.assignMask(arr[i], o[arr[i]]); }}
  16396. , ()=>{for(var i =1 ; i < Math.min(31, arr.length); i++) { console.log(i); created.assignMask(arr[i], o[arr[i]], leftshift_Number ); }}
  16397. , ()=>{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 } ); }}
  16398. , ()=>{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) } ); }}
  16399. ];
  16400. arr.length > 32 ? iterateUpto.forEach(f=>f()) :
  16401. arr.length > 31 ? iterateUpto.slice(0,3).forEach(f=>f()) :
  16402. arr.length > 1 ? iterateUpto.slice(0,2).forEach(f=>f()) :
  16403. iterateUpto[0]();
  16404. return created;
  16405. }
  16406. function __createA(arrInp, options){
  16407. validateBitLength(arrInp.length);
  16408. var created = __create();
  16409. var arr = [];
  16410. var pregencache = [];
  16411. // PB : Changed to preincrement. Mask need not overflow for 53 bits...
  16412. var iterateUpto = [
  16413. (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]} ); }}
  16414. , (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 ); }}
  16415. , (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 } ); }}
  16416. , (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) } ); }}
  16417. ];
  16418. if(options && options.pregenerated) {
  16419. arrInp.forEach((inp=>{
  16420. if(!options.pregenerated[inp] || !options.pregenerated[inp].mask) {
  16421. // Doesn't have a mask so needs generation.
  16422. arr.push(inp);
  16423. pregencache[inp] = options.pregenerated[inp];
  16424. }
  16425. else if(!options.pregenerated[inp]) arr.push(inp);
  16426. }));
  16427. Object.keys(options.pregenerated).forEach(p=>{
  16428. if(pregencache[p]) return;
  16429. created.assignMask(p, options.pregenerated[p], created.assignMaxAsNextIncrement );
  16430. });
  16431. var prelen = Object.keys(created.toJSON()).length;
  16432. prelen > 31 ? iterateUpto.slice(3).forEach(f=>f(prelen)) :
  16433. prelen > 30 ?
  16434. (prelen + arr.length) > 32 ? iterateUpto.slice(2).forEach(f=>f(prelen))
  16435. : iterateUpto.slice(2, 3).forEach(f=>f(prelen))
  16436. :
  16437. prelen > 0 ?
  16438. (prelen + arr.length) > 32 ? iterateUpto.slice(1).forEach(f=>f(prelen))
  16439. : (prelen + arr.length) > 31 ? iterateUpto.slice(1,3).forEach(f=>f(prelen)) :
  16440. iterateUpto.slice(1,2).forEach(f=>f(prelen))
  16441. :
  16442. arr.length > 32 ? iterateUpto.forEach(f=>f(prelen)) :
  16443. arr.length > 31 ? iterateUpto.slice(0,3).forEach(f=>f(prelen)) :
  16444. arr.length > 1 ? iterateUpto.slice(0,2).forEach(f=>f(prelen)) :
  16445. iterateUpto[0](prelen);
  16446. }
  16447. else {
  16448. arr = arrInp;
  16449. arr.length > 32 ? iterateUpto.forEach(f=>f(0)) :
  16450. arr.length > 31 ? iterateUpto.slice(0,3).forEach(f=>f(0)) :
  16451. arr.length > 1 ? iterateUpto.slice(0,2).forEach(f=>f(0)) :
  16452. iterateUpto[0](0);
  16453. }
  16454. return created;
  16455. }
  16456. function __create(){
  16457. var labels = {};
  16458. var masks = {};
  16459. var currentMaxMask;
  16460. function __nextMask(){ __nextMask = leftshift_Number;
  16461. return currentMaxMask = 1; }
  16462. // var store = ??? new Uint32Array(1)
  16463. var mxn = Mixin.create();
  16464. var created = utils_1.assign(mxn,
  16465. {
  16466. assignMaxAsNextIncrement(possibleMax) {
  16467. if(currentMaxMask && currentMaxMask < possibleMax) currentMaxMask = possibleMax;
  16468. else currentMaxMask = possibleMax;
  16469. }
  16470. , validateMask(m){
  16471. if(mxn.is(m, BitIndex)) {
  16472. return { BitIndex, labels : [masks[indexToMask(m.value)]] }
  16473. }
  16474. if(m > MAX_53BITS) throw "BitArrayUpto53Bits only supports numbers upto MAX_53BITS "
  16475. if(!utils_1.js.isNumber(+m)) throw "BitArrayUpto53Bits requires Numbers upto MAX_53BITS "
  16476. return true;
  16477. }
  16478. , labelsToMask : (__labels)=>{
  16479. var result = 0; __labels.forEach(l=>{ result |= labels[l]; });
  16480. return result >>> 0;
  16481. }
  16482. , hasMask : function(label) { return labels[label] ? labels[label].mask : null ; }
  16483. , maskToLabels(m, transformEach){
  16484. var valid = this.validateMask(m);
  16485. if(!valid) throw "Invalid Mask"
  16486. if(valid.BitIndex) return valid.labels;
  16487. var __labels = [];
  16488. var m = BigInt(m);
  16489. // for(var gptwo;gptwo=this.bit_and(m,-m); gptwo = this.bit_xor(m,gptwo)) {
  16490. for(var gptwo;gptwo=m&-m;m^=gptwo) {
  16491. if(!masks[Number(gptwo)]) { console.log('Error : Invalid mask passed in.'); }
  16492. else __labels.push( transformEach(masks[Number(gptwo)], labels[masks[Number(gptwo)]]) );
  16493. }
  16494. return __labels;
  16495. }
  16496. , labelToMask : (l)=>{ return labels[l] }
  16497. , bit_or : (a, b) => {
  16498. return bit_opFn_Upto53(a,b, (a, b)=>a | b)
  16499. }
  16500. , bit_and : (a, b) => bit_opFn_Upto53(a,b, (a, b)=>a & b)
  16501. , bit_xor : (a, b) => bit_opFn_Upto53(a,b, (a, b)=>a ^ b)
  16502. , bit_not : (a) => Number(~BigInt(a))
  16503. , assignMask : function(label, entity, onassignment) {
  16504. if(entity && entity.mask && masks[entity.mask]) {
  16505. throw 'Mask collision. Cannot assign requested mask. ' + entity
  16506. }
  16507. var pregenerated = labels[label] || entity;
  16508. // var lmask = this.hasMask(label); if(lmask) return lmask; // Already assigned.
  16509. // Everything is overridable except mask.
  16510. if(pregenerated && pregenerated.mask) {
  16511. onassignment = (onassignment || created.assignMaxAsNextIncrement);
  16512. labels[label] = utils_1.assign(pregenerated, entity, {mask : pregenerated.mask});
  16513. onassignment(pregenerated.mask);
  16514. }
  16515. else {
  16516. onassignment = (onassignment || __nextMask);
  16517. labels[label] = entity;
  16518. 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.
  16519. }
  16520. masks[labels[label].mask] = label;
  16521. return labels[label];
  16522. }
  16523. , msbIndex : function(v) { throw "msb Not yet implemented" }
  16524. , indexToMask : function(index) {
  16525. if(index > 52) throw 'Not supported beyond 53 bits.'
  16526. return Number(BigInt(1) << BigInt(index));
  16527. }
  16528. , indicesToMask : function(indices){
  16529. var mask = BigInt(0);
  16530. indices.forEach(index=>{
  16531. if(index > 52) throw 'Not supported beyond 53 bits.'
  16532. mask |= (BIGINT_1 << BigInt(index));
  16533. });
  16534. return Number(mask);
  16535. }
  16536. , maskToIndices : function(m) {
  16537. var valid = this.validateMask(m);
  16538. if(!valid) throw "Invalid Mask"
  16539. if(valid.BitIndex) return [m.value];
  16540. var indices = [];
  16541. var gptwo;
  16542. if(m > MAX_32BITS) {
  16543. var iterator = bigIntBufferGenerator(BigInt(m));
  16544. var next;
  16545. // if(next && !next.done) buffer = next.value.bits32;
  16546. // else return next.value.bits32;
  16547. var i = 0;
  16548. while(!(next = iterator.next()).done) {
  16549. next.value.bits32 > 0 ?
  16550. ( ()=> { for(;gptwo=(next.value.bits32& -next.value.bits32) ;next.value.bits32^=gptwo) indices.push(32 * i + indexOfLSB32(gptwo)); } )
  16551. : null;
  16552. i++;
  16553. }
  16554. for(;gptwo=(next.value.bits32&-next.value.bits32);next.value.bits32^=gptwo) indices.push(32 * i + indexOfLSB32(gptwo));
  16555. }
  16556. else {
  16557. m = Number(m);
  16558. for (;gptwo=m&-m;m^=gptwo) indices.push(indexOfLSB32(gptwo)); }
  16559. // for (;gptwo=BigInt(m)&BigInt(-m);m^=gptwo) indices.push(indexOfLSB32(m, gptwo))
  16560. return indices;
  16561. }
  16562. , bit_shiftl : (a, s)=>{ return a << s }
  16563. , bit_shiftr : (a, s)=>{ return a >> s }
  16564. , bit_shiftr_uz : (a)=>{ return a >>> 0} // Unsigned right shift by 0.
  16565. // , bit_shiftl_1 : ()=>{}
  16566. , toJSON(radix, eachFn){
  16567. var transFormed = {};
  16568. if(!eachFn) return labels;
  16569. Object.keys(labels).forEach(label =>{
  16570. transFormed[label] = eachFn(labels[label]);
  16571. });
  16572. return transFormed;
  16573. }
  16574. , tosqlcte() {
  16575. var select = '';
  16576. // debugger
  16577. Object.keys(labels).forEach((label, index, array) =>{
  16578. var labelObject = labels[label];
  16579. var rowselect = 'select ';
  16580. Object.keys(labelObject).forEach((key, index, array) =>{
  16581. rowselect = rowselect + ` '${labelObject[key]}' ${key}`;
  16582. if(array.length !== index+1) rowselect = rowselect + ',';
  16583. });
  16584. select = select + rowselect;
  16585. if(array.length !== index+1) select = select + '\n union all \n';
  16586. });
  16587. console.log(select);
  16588. return labels
  16589. }
  16590. , test(){
  16591. Object.keys(masks).forEach((v, i)=> {
  16592. console.log( v );
  16593. console.log( i + ' : ' + v.toString(2) );
  16594. console.log( this.maskToIndices(v));
  16595. });
  16596. console.log( (173).toString(2) );
  16597. this.maskToIndices(173).map( (i)=>{ console.log( i ); });
  16598. console.log('indicesToMask :' + this.indicesToMask([1,4,31]).toString(2));
  16599. }
  16600. });
  16601. return created;
  16602. }
  16603. var creatorFor = {
  16604. '[object Array]' : __createA
  16605. , '[object Object]' : __createO
  16606. , 'undefined' : function(){ return __create() }
  16607. };
  16608. // PB : TODO -- Constructor is not preserved... But mixing in an external passed in object is what we want to achive.
  16609. function BitArrayUpto53Bits(){
  16610. return arguments.length ? creatorFor[utils_1.js.nativeType(arguments[0])](...arguments) :
  16611. creatorFor['undefined'](...arguments)}
  16612. BitArrayUpto53Bits.create = BitArrayUpto53Bits;
  16613. return BitArrayUpto53Bits
  16614. })();
  16615. function bit_opFn_Upto53(a, b, opFn){
  16616. return Number(opFn(BigInt(a), BigInt(b) ))
  16617. // var result = new Uint32Array(2);
  16618. // result[0] = opFn( (a / POWER32)>>0 , (b / POWER32)>>0 )
  16619. // result[1] = opFn(a % POWER32, b % POWER32)
  16620. // return POWER32 * result[0] + result[1];
  16621. }
  16622. // An arbitrarily-wide array of bits. Can be used for bitmasks longer than 32 bits in JS.
  16623. const BitArray = (function(){
  16624. // const NEEDS_BIT_SPLIT = (b)=> b > Number.MAX_SAFE_INTEGER;
  16625. // const MAX_SAFE_MASK_LENGTH = 32
  16626. // function getMinMax(a, b){
  16627. // return a.length > b.length ? { min : b.length, minX : b, max : a.length, maxX : a }
  16628. // : { min : a.length, minX : a, max : b.length, maxX : b }
  16629. // }
  16630. // function getTypes(a, b){
  16631. // var aIsPrimitive = utils.js.isPrimitive(a);
  16632. // var bIsPrimitive = utils.js.isPrimitive(b);
  16633. // return { a : aIsPrimitive, b : bIsPrimitive }
  16634. // }
  16635. // // Binary oprations
  16636. // function bit_opFn(a, b, opFn){
  16637. // var tt = getTypes(a, b);
  16638. // var mm = {}
  16639. // var getRemaining = function(){ return mm.maxX.subarray(mm.min, mm.max-1)}
  16640. // if(tt.a && tt.b) {
  16641. // // both are primitive
  16642. // mm = { min : 1, minX : [a], max : 1, maxX : [b]}
  16643. // getRemaining = function(){ return []}
  16644. // }
  16645. // else if(tt.a){
  16646. // // b is bitarray
  16647. // mm = { min : 1, minX : [a], max : b.length, maxX : b}
  16648. // }
  16649. // else if(tt.b){
  16650. // mm = { min : 1, minX : [b], max : a.length, maxX : a}
  16651. // }
  16652. // else {
  16653. // var mm = getMinMax(a, b)
  16654. // }
  16655. // var result = new Uint32Array(mm.max);
  16656. // for (var i = 0; i < mm.min; ++i) { result.set( [opFn(mm.minX[i], mm.maxX[i])], i) }
  16657. // // js.utils.isPrimitive(mm.maxX) ?
  16658. // var remaining = getRemaining()
  16659. // remaining.length > 0 ? result.set( remaining, mm.min) : null;
  16660. // return result;
  16661. // }
  16662. // // Unary operations
  16663. // function bit_opFnU(mm, opFn){
  16664. // var result = new Uint32Array(mm.length);
  16665. // for (var i = 0; i < mm.min; ++i) { result.set( opFn(a), i) }
  16666. // result.set( mm.maxX.subarray(mm.min, mm.max-1), mm.min)
  16667. // return result;
  16668. // }
  16669. // function __expand(){
  16670. // }
  16671. function __createA(arr){
  16672. // Create a new BitArray
  16673. // Assign Unique bits to each item in an array of labels.
  16674. arr.length % 32;
  16675. arr.length/32 >>> 0;
  16676. var created = arr.length > 53 ?
  16677. BitArrayBigInt.create(...arguments) : arr.length > 32 ?
  16678. BitArrayUpto53Bits.create(...arguments) :
  16679. BitArrayUpto32Bits.create(...arguments);
  16680. return created;
  16681. }
  16682. function __createO(o){
  16683. // Create a new BitArray
  16684. // Assign Unique bits to each item in an array of labels.
  16685. var arr = Object.keys(o);
  16686. arr.length % 32;
  16687. arr.length/32 >>> 0;
  16688. var created = arr.length > 53 ?
  16689. BitArrayBigInt.create(...arguments) : arr.length > 32 ?
  16690. BitArrayUpto53Bits.create(...arguments) :
  16691. BitArrayUpto32Bits.create(...arguments);
  16692. return created;
  16693. }
  16694. function __create(){
  16695. // var store = new Uint32Array(1)
  16696. Mixin.create();
  16697. var created = BitArrayBigInt.create();
  16698. created.addMixin(BitArray);
  16699. return created;
  16700. }
  16701. var creatorFor = {
  16702. '[object Array]' : __createA
  16703. , '[object Object]' : __createO
  16704. , 'undefined' : function(){ return __create() }
  16705. };
  16706. // PB : TODO -- Constructor for BitArrays read from files that have been generated and saved.
  16707. // PB : TODO -- Constructor is not preserved... But mixing in an external passed in object is what we want to achive.
  16708. function BitArray(){
  16709. return arguments.length ? creatorFor[utils_1.js.nativeType(arguments[0])](...arguments) :
  16710. creatorFor['undefined'](...arguments)}
  16711. BitArray.create = BitArray;
  16712. return BitArray
  16713. })();
  16714. // var uuidv1 = require('uuid/v1');
  16715. const { v1: uuidv1 } = require$$1;
  16716. console.log(uuidv1);
  16717. // Mixins.
  16718. const mixs = {
  16719. // __JSTPL : (function() {
  16720. // function __f() {}
  16721. // return function() {
  16722. // this.f = __f;
  16723. // return this;
  16724. // };
  16725. // })()
  16726. // Return a set of mixins.
  16727. kernelMixin : (function() {
  16728. // Wrapper to generate the currently chosen UUID version
  16729. // In JS UUID v4 vs v1 -> In browsers v1 has the timestamp but uses a random number for the node part.
  16730. function __getuuid() {
  16731. return uuidv1();
  16732. }
  16733. // uuid property Mainstream getter after lazy init
  16734. function __get() {
  16735. return this.kernel.uuidv1;
  16736. }
  16737. // uuid property First Time getter for lazy init.
  16738. function __firstGet() {
  16739. this.kernel.uuidv1 = __getuuid();
  16740. __finalize.apply(this);
  16741. return this.uuid;
  16742. }
  16743. function __finalize(){
  16744. Object.defineProperty(this.kernel, 'uuidv1', { writable : false, configurable : false});
  16745. Object.defineProperty(this, 'uuid', {
  16746. get : __get
  16747. , enumerable : true
  16748. , configurable : false
  16749. });
  16750. Object.defineProperty(this, 'kernel', {
  16751. enumerable : false
  16752. , configurable : false
  16753. , writable : false
  16754. });
  16755. }
  16756. function __defineKernel(){
  16757. // MAC and time. Guaranteed unique unless generated way too fast or parallelly.
  16758. //const uuidv1 = utils.core.uuidV1; // (date-time and MAC address)
  16759. //const uuidv2 = // (date-time and MAC Address, DCE security version)
  16760. // (namespace name-based) ...
  16761. //const uuidv3md5 = require('uuid/v3');
  16762. //const uuidv5sha1 = require('uuid/v3'); // SHA1(v5) is broken
  16763. //const uuidv4 = require('uuid/v4'); //(random)
  16764. // Kernel Properties are promoted onto the object itself without value as getters and setters as
  16765. // configurable = false
  16766. // enumerable = false
  16767. // writable = false
  16768. Object.defineProperty(this, 'kernel', { value :{}, writable : true });
  16769. // Keep it lazy. Only generate on first use. Which could be first time persistence.
  16770. Object.defineProperty(this.kernel, 'uuidv1', { writable : true, configurable : true});
  16771. // PB : TODO -- Note : A hash of the content may need to be computed dynamically.
  16772. // The best place to do this is on persistance. In memory objects undergo a lot of changes so the hash keeps varying.
  16773. // It therefore becomes unnecessary to compute the hash very frequently. We may need to do this lazily when accessed or
  16774. // simply use all attributes for comparison. The value of a hash is useful only when the attributes are not changing
  16775. // and the hash is precomputed and ready to be used. We need to use gits methodology to track changes.
  16776. }
  16777. function __loadKernel() {
  16778. // Reinitialize the kernel for an object that already has a uuid probably loaded from a JSON.
  16779. this.kernel.uuidv1 = this.uuid;
  16780. __finalize.apply(this);
  16781. }
  16782. function __attachKernel() {
  16783. // Dont mess with something that already has a kernel.
  16784. if(this.hasOwnProperty('kernel')) {
  16785. l('Already has kernel');
  16786. return this;
  16787. }
  16788. __defineKernel.apply(this);
  16789. if(this.hasOwnProperty('uuid')) {
  16790. l('Already has uuid');
  16791. __loadKernel.apply(this);
  16792. return this;
  16793. }
  16794. Object.defineProperty(this, 'uuid', { get : __firstGet, configurable : true});
  16795. return this;
  16796. }
  16797. var __kernelInstanceMixin = function() {
  16798. return __attachKernel.apply(this);
  16799. };
  16800. __kernelInstanceMixin.getuuid = __getuuid;
  16801. return __kernelInstanceMixin;
  16802. })()
  16803. // Publishes messages to a message queue broker or mediator.
  16804. , publisherMixin : (function() {
  16805. function __publish() {
  16806. }
  16807. return function() {
  16808. this.publish = __publish;
  16809. return this;
  16810. };
  16811. })()
  16812. };
  16813. // Note : Prophelpers are not mixed into the object and hence need to be applied on some other object.
  16814. const helpers = {
  16815. indexHelper : indexHelper
  16816. , meta : (function() {
  16817. // Mainly to observe changes to object properties.
  16818. // A kernel uuid is a prerequisite.
  16819. function spy(obj, prop, action) {
  16820. action = action || 'set';
  16821. if(action != 'set') {
  16822. throw 'Currently only set actions can be observed on properties';
  16823. }
  16824. // Get the current descriptor
  16825. var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
  16826. var value = obj[prop];
  16827. if(descriptor && descriptor.get && descriptor.get.$meta){
  16828. var originalset = descriptor.set;
  16829. descriptor.set = function(newValue) {
  16830. globalThis_1.mediator.publish(obj.uuid + '.' + prop, 'willchange', {from : value, to : newValue});
  16831. originalset(newValue);
  16832. globalThis_1.mediator.publish(obj.uuid + '.' + prop, 'haschanged', {from : value, to : newValue});
  16833. };
  16834. return this;
  16835. }
  16836. descriptor = {
  16837. get: function() {
  16838. return value;
  16839. },
  16840. set: function(newValue) {
  16841. globalThis_1.mediator.publish([obj.uuid, prop, 'willchange'], {from : value, to : newValue});
  16842. value = newValue;
  16843. globalThis_1.mediator.publish([obj.uuid, prop, 'haschanged' ], {from : value, to : newValue});
  16844. }
  16845. };
  16846. descriptor.get.$meta = {};
  16847. Object.defineProperty(obj, prop, descriptor);
  16848. return this;
  16849. }
  16850. function getCustomPropertyDescriptor(obj, prop) {
  16851. var actualDescriptor = Object.getOwnPropertyDescriptor(obj, prop);
  16852. if (actualDescriptor && actualDescriptor.get && actualDescriptor.get.$meta) {
  16853. return actualDescriptor;
  16854. }
  16855. var value = obj[prop];
  16856. var descriptor = {
  16857. get: function() {
  16858. return value;
  16859. },
  16860. set: function(newValue) {
  16861. value = newValue;
  16862. }
  16863. };
  16864. descriptor.get.$meta = {};
  16865. Object.defineProperty(obj, prop, descriptor);
  16866. return Object.getOwnPropertyDescriptor(obj, prop);
  16867. }
  16868. function setPropertyAttribute(obj, propertyName, attributeName, attributeValue) {
  16869. var descriptor = getCustomPropertyDescriptor(obj, propertyName);
  16870. descriptor.get.$meta[attributeName] = attributeValue;
  16871. }
  16872. function getPropertyAttributes(obj, propertyName) {
  16873. var descriptor = getCustomPropertyDescriptor(obj, propertyName);
  16874. return descriptor.get.$meta;
  16875. }
  16876. function getPropertyAttribute(obj, propertyName, attributeName) {
  16877. return getPropertyAttributes(obj, propertyName)[attributeName];
  16878. }
  16879. return function(obj) {
  16880. obj.getPropertyAttribute = getPropertyAttribute;
  16881. obj.getPropertyAttributes = getPropertyAttributes;
  16882. obj.setPropertyAttribute = setPropertyAttribute;
  16883. obj.spy = spy;
  16884. return obj;
  16885. };
  16886. })()
  16887. };
  16888. var core = function(object){
  16889. // l('in \tFunction core')
  16890. return {
  16891. mixs
  16892. , helpers
  16893. , AnyStore
  16894. , BitArray
  16895. , BitArrayUpto32Bits
  16896. , BitArrayUpto53Bits
  16897. , BitArrayBigInt
  16898. // core object instances
  16899. , uuidv1
  16900. , Rule
  16901. }
  16902. };
  16903. // export default core;
  16904. var core_1 = core;
  16905. // console.dir(__g.mediator)
  16906. // try {
  16907. // console.log( '__g === global : ' + (__g === global) )
  16908. // }
  16909. // catch(e){
  16910. // console.log( '__g === global : ' + false )
  16911. // }
  16912. // try {
  16913. // console.log( '__g === globalThis : ' + (__g === globalThis) )
  16914. // }
  16915. // catch(e){
  16916. // console.log( '__g === globalThis : ' + false )
  16917. // }
  16918. function *bigIntBitGenerator(){
  16919. var signal = {};
  16920. var stop = Symbol();
  16921. var iId = 0;
  16922. var bit = BIGINT_1;
  16923. for(;;){
  16924. signal = (yield { iId, bit }) || {};
  16925. if(signal === stop || signal.done) return { iId, bit };
  16926. bit = bit << BIGINT_1;
  16927. iId++;
  16928. }
  16929. }
  16930. var Rule = (function(){
  16931. // Immutable private static.
  16932. var __Rule = {};
  16933. // Overridable public static shared on the instance as well as convenience functions.
  16934. // When the extend method is used the instance methods also correspond.
  16935. // IMP : NOTE -- However instance overrides do not switch the static ones attached to the class.
  16936. // These could also be called statically with call or apply Eg: fn.apply(this)
  16937. var _XRule = { assignbit, getParticipating };
  16938. // Extendable public static
  16939. // _Rule should not be referenced anywhere... as its members can be swithed.
  16940. var _Rule = {
  16941. extend : function(extension){
  16942. function __create(){ return init.call({}) }
  16943. function __createO(o){ return init.call(o) }
  16944. function __createA(a){ a.forEach(r=> __createO(r)); return a }
  16945. var creatorFor = {
  16946. '[object Array]' : __createA
  16947. , '[object Object]' : __createO
  16948. , 'undefined' : function(){ return __create() }
  16949. };
  16950. function Rule(){ return arguments.length ? creatorFor[utils_1.js.nativeType(arguments[0])](...arguments) : creatorFor['undefined'](...arguments) }
  16951. // All static extensions shall be available on the instance as well.
  16952. var _extension = utils_1.assign({}, _XRule, extension);
  16953. function init() { return utils_1.assign(this, rProto, _extension, __newInstance(this), this) } _extension.init = init;
  16954. utils_1.assign(Rule, _Rule, _extension, __Rule);
  16955. // Immutable public static methods.
  16956. Rule.create = Rule;
  16957. Rule.build = buildRules;
  16958. Rule.match = match;
  16959. Rule.connect = connectRules;
  16960. Rule.branch = function(as, ...rest){
  16961. // PB : TODO -- All lists will be invalidated when we splice rules in...
  16962. // Rule.create()
  16963. // Replace an exisiting rule node with an intermediate rule that connects this rule to another rule.
  16964. console.error('Not yet implemented.');
  16965. };
  16966. // from loopback-connector/lib/sql.js
  16967. // PB : TODO -- a generic multipurpose buildwhere which doesn't enforce model property existence
  16968. // Convert from a natural filter to key val expanded filter.
  16969. // Convert In clauses to one rule for each listed values.
  16970. // Do not output the where clause but inlude the operator in the result assosiated with the respective params.
  16971. // Handle mask overflows gracefully
  16972. /**
  16973. * @param where
  16974. * @returns {ChoppedRules}
  16975. */
  16976. function buildRules(where, data, fullResult, parentRule) {
  16977. let columnValue;
  16978. if (!where) return Promise.resolve(fullResult) ;
  16979. if (typeof where !== 'object' || Array.isArray(where)) {
  16980. debug('Invalid value for where: %j', where);
  16981. return Promise.resolve(fullResult);
  16982. }
  16983. var ruleset = [];
  16984. // var id = Object.keys(where).length > 1 ? null : data ? data.id : null;
  16985. var id = data ? data.id : null;
  16986. fullResult = fullResult || [];
  16987. var createIntermediate = createIntermediateParentLess;
  16988. var immediateParentP = null;
  16989. if(parentRule) {
  16990. immediateParentP = parentRule;
  16991. createIntermediate = createIntermediateWithParent;
  16992. }
  16993. if(Object.keys(where).length > 1) {
  16994. immediateParentP = createIntermediate({operator : AND}, ()=>{ return [] }, parentRule);
  16995. ruleset.push(immediateParentP);
  16996. fullResult.push(immediateParentP);
  16997. createIntermediate = createIntermediateWithParent;
  16998. }
  16999. for (const key in where) {
  17000. // Handle and/or operators
  17001. if (key === AND || key === OR) {
  17002. const clauses = where[key];
  17003. if (Array.isArray(clauses)) {
  17004. if(clauses.length > 1) {
  17005. var rp = createIntermediate({operator : key}, (rParent)=>{
  17006. var list = [];
  17007. for (let i = 0, n = clauses.length; i < n; i++) {
  17008. list.push(buildRules(clauses[i], null, fullResult).then( ruleForClause => {
  17009. connectRules(operators[rParent.operator].bit, ruleForClause, rParent);
  17010. return ruleForClause;
  17011. }));
  17012. }
  17013. return list;
  17014. }, immediateParentP);
  17015. ruleset.push(rp);
  17016. fullResult.push(rp);
  17017. }
  17018. else {
  17019. // An outer 'or' OR 'and' condition is meaningless if we have only 1 clause. At least two are required to make sense.
  17020. // We just drop the wrapped grouped (or or and) condition and promote then inner clause to the same level. =
  17021. var rP = buildRules(clauses[0], null, fullResult, immediateParentP);
  17022. // fullResult.push(rP) // Buildrules should should have already pushed this.
  17023. ruleset.push(rP); // buildRules should have already linked parent and child.
  17024. }
  17025. continue;
  17026. }
  17027. else {
  17028. throw 'Invalid filter '
  17029. }
  17030. }
  17031. // eslint-disable one-var
  17032. let expression = where[key];
  17033. let p = key;
  17034. var op ='eq';
  17035. const columnName = columnEscaped(/* modelinstance || */ where, key);
  17036. // eslint-enable one-var
  17037. if (expression === null || expression === undefined) {
  17038. // If null has been passed in we should match null.
  17039. expression = null;
  17040. var rpromise = assignbit(Rule.create(rChild, { key : columnName, value : toColumnValue(p, expression)})).then((rChild)=>{
  17041. if(immediateParentP) {
  17042. return immediateParentP.then((immediateParent)=> {
  17043. connectRules(operators[immediateParent.operator].bit, rChild, immediateParent);
  17044. return rChild
  17045. })
  17046. }
  17047. // PB : TODO -- Unwrapped decendents update on parent!!!
  17048. return rChild
  17049. }).catch(e=>{ console.error('null expression : ' + e); });
  17050. fullResult.push(rpromise);
  17051. ruleset.push(rpromise);
  17052. } else if (expression && expression.constructor === Object) {
  17053. const operator = Object.keys(expression)[0];
  17054. expression = expression[operator];
  17055. if (operator === INQ || operator === NIN || operator === BETWEEN) {
  17056. columnValue = [];
  17057. op = operator === INQ ? (EQ) : operator === NIN ? (NEQ) : (LTE);
  17058. if (Array.isArray(expression)) {
  17059. // Column value is a list
  17060. for (let j = 0, m = expression.length; j < m; j++) {
  17061. columnValue.push(toColumnValue(p, expression[j]));
  17062. }
  17063. } else {
  17064. columnValue.push(toColumnValue(p, expression[j]));
  17065. }
  17066. if (operator === BETWEEN) {
  17067. var rp = createIntermediate({operator : AND}, (rParent)=>{
  17068. // BETWEEN v1 AND v2
  17069. columnValue[0] === undefined ? null : columnValue[0];
  17070. columnValue[1] === undefined ? null : columnValue[1];
  17071. if(expression.length !== 2) console.error('Invalid between operator parameter length');
  17072. var list = [];
  17073. list.push(assignbit(Rule.create({key : columnName, value : columnValue[0], operator : GTE})).then((rChild)=>{
  17074. connectRules(operators[rParent.operator].bit, rChild, rParent);
  17075. return rChild
  17076. }));
  17077. list.push(assignbit(Rule.create({key : columnName, value : columnValue[1], operator : LTE})).then((rChild)=>{
  17078. connectRules(operators[rParent.operator].bit, rChild, rParent);
  17079. return rChild
  17080. }));
  17081. fullResult.push.apply(fullResult, list);
  17082. return list;
  17083. }, immediateParentP);
  17084. ruleset.push(rp);
  17085. fullResult.push(rp);
  17086. } else {
  17087. var rp = createIntermediate({operator : OR}, (rParent)=>{
  17088. // IN (v1,v2,v3) or NOT IN (v1,v2,v3)
  17089. // PB : TODO -- loopbacks handling of nulls is questionable. Invalid rules match nulls and return data.
  17090. if (columnValue.length === 0) {
  17091. if (operator === INQ) {
  17092. columnValue = [null];
  17093. } else {
  17094. // nin () is true
  17095. // nin : [null] is a world query which is an invalid filter. We don't support yet.
  17096. return [];
  17097. }
  17098. }
  17099. var list = [];
  17100. for (let j = 0, m = columnValue.length; j < m; j++) {
  17101. list.push(
  17102. assignbit(Rule.create({key : columnName, value : toColumnValue(p, columnValue[j]), operator : op})).then((rChild)=>{
  17103. connectRules(operators[rParent.operator].bit, rChild, rParent);
  17104. return rChild
  17105. })
  17106. );
  17107. }
  17108. fullResult.push.apply(fullResult, list);
  17109. return list
  17110. }, immediateParentP);
  17111. ruleset.push(rp);
  17112. fullResult.push(rp);
  17113. }
  17114. } else if (operator === 'regexp' && expression instanceof RegExp) {
  17115. // do not coerce RegExp based on property definitions
  17116. var rpromise = assignbit(Rule.create({key : columnName, value : toColumnValue(p, expression), operator})).then((rChild)=>{
  17117. if(immediateParentP) {
  17118. return immediateParentP.then((immediateParent)=> {
  17119. connectRules(operators[immediateParent.operator].bit, rChild, immediateParent);
  17120. return rChild
  17121. })
  17122. }
  17123. // PB : TODO -- Unwrapped decendents update on parent!!!
  17124. return rChild
  17125. }).catch(e=>{ console.error('Regexp expression : ' + e); });
  17126. fullResult.push(rpromise);
  17127. ruleset.push(rpromise);
  17128. // columnValue = expression;
  17129. } else {
  17130. var rpromise = assignbit(Rule.create({key : columnName, value : toColumnValue(p, expression), operator})).then((rChild)=>{
  17131. if(immediateParentP) {
  17132. return immediateParentP.then((immediateParent)=> {
  17133. connectRules(operators[immediateParent.operator].bit, rChild, immediateParent);
  17134. return rChild
  17135. })
  17136. }
  17137. // PB : TODO -- Unwrapped decendents update on parent!!!
  17138. return rChild
  17139. }).catch(e=>{ console.error('other expression : ' + e); });
  17140. fullResult.push(rpromise);
  17141. ruleset.push(rpromise);
  17142. // columnValue = toColumnValue(p, expression);
  17143. }
  17144. } else {
  17145. if(utils_1.js.isArray(expression)) throw 'Invalid array value for filter. Implicit INQ not supported. '
  17146. // ruleProcessor[EQ]();
  17147. var rpromise = assignbit(Rule.create({key : columnName, value : toColumnValue(p, expression), operator : EQ})).then((rChild)=>{
  17148. if(immediateParentP) {
  17149. return immediateParentP.then((immediateParent)=> {
  17150. connectRules(operators[immediateParent.operator].bit, rChild, immediateParent);
  17151. return rChild
  17152. })
  17153. }
  17154. // PB : TODO -- Unwrapped decendents update on parent!!!
  17155. return rChild
  17156. }).catch(e=>{ console.error('other expression : ' + e); });
  17157. fullResult.push(rpromise);
  17158. ruleset.push(rpromise);
  17159. }
  17160. }
  17161. return Promise.all(ruleset).then(()=>{
  17162. if(immediateParentP){
  17163. return immediateParentP;
  17164. }
  17165. if(ruleset.length > 1) {
  17166. // If only 1 rule there is no point in having an outer implicit and.
  17167. // If length is > 1 it implies there are a mixture of ands ors and raw rules specified as an outer object
  17168. // and we need to return the grouped rule.
  17169. // var grpromise = Promise.all(ruleset).then( (list)=>{
  17170. // var grouped = Rule.create({ id, operator : AND }).assignbit();
  17171. // return grouped.then(r=>{
  17172. // r.list = list;
  17173. // return r
  17174. // })
  17175. // });
  17176. // fullResult.push(grpromise)
  17177. // return grpromise
  17178. return ruleset[ruleset.length-1].then((r)=>{ r.id = id || r.id; return r});
  17179. }
  17180. else if(ruleset.length > 0) {
  17181. return ruleset[0].then((r)=>{ r.id = id || r.id; return r});
  17182. }
  17183. else {
  17184. return fullResult[fullResult.length-1].then((r)=>{ r.id = id || r.id; return r});
  17185. }
  17186. })
  17187. }
  17188. return Rule
  17189. }
  17190. };
  17191. var createIntermediateParentLess = (interMediatGroupParent, createChildren)=>{
  17192. var interMediatGroupParentP = assignbit(Rule.create(interMediatGroupParent)).then((rIntermediate)=>{
  17193. return rIntermediate
  17194. });
  17195. var grpromise = interMediatGroupParentP.then((rParent)=>{
  17196. // var rParent = resolved[1]
  17197. // if(immediateParentP) {
  17198. // connectRules( operators[ resolved[0].operator].bit, rParent, resolved[0] )
  17199. // // PB : Note -- we connect right here and after children are properly created we update parent descendents when we unwrap to root parent.
  17200. // rParent.ancestors |= resolved[0].ancestors | resolved[0].bit // PB : TODO -- should ancestors be included in the mask ???
  17201. // }
  17202. // PB : TODO -- When we unwind descendents on ancestors need to be updated.
  17203. // PB : TODO -- Why is this group not getting pushed into the full list.
  17204. // Also what happens when caluse[i] is an array ? Does a group get created and also clause i ?
  17205. return Promise.all(createChildren(rParent)).then( (list)=>{
  17206. // PB : TODO -- We don't know yet whether id needs to be assigned to this rule
  17207. // or an outer grouped rule.
  17208. rParent.list = list;
  17209. return rParent
  17210. });
  17211. });
  17212. return grpromise;
  17213. };
  17214. var createIntermediateWithParent = (interMediatGroupParent, createChildren, immediateParentP)=>{
  17215. var interMediatGroupParentP = assignbit(Rule.create(interMediatGroupParent)).then((rIntermediate)=>{
  17216. return immediateParentP.then((immediateParent)=>{
  17217. connectRules(operators[immediateParent.operator].bit, rIntermediate, immediateParent);
  17218. return rIntermediate
  17219. })
  17220. });
  17221. var grpromise = interMediatGroupParentP.then((rParent)=>{
  17222. // var rParent = resolved[1]
  17223. // if(immediateParentP) {
  17224. // connectRules( operators[ resolved[0].operator].bit, rParent, resolved[0] )
  17225. // // PB : Note -- we connect right here and after children are properly created we update parent descendents when we unwrap to root parent.
  17226. // rParent.ancestors |= resolved[0].ancestors | resolved[0].bit // PB : TODO -- should ancestors be included in the mask ???
  17227. // }
  17228. // PB : TODO -- When we unwind descendents on ancestors need to be updated.
  17229. // PB : TODO -- Why is this group not getting pushed into the full list.
  17230. // Also what happens when caluse[i] is an array ? Does a group get created and also clause i ?
  17231. return Promise.all(createChildren(rParent)).then( (list)=>{
  17232. // PB : TODO -- We don't know yet whether id needs to be assigned to this rule
  17233. // or an outer grouped rule.
  17234. rParent.list = list;
  17235. return rParent
  17236. });
  17237. });
  17238. return grpromise;
  17239. };
  17240. // Literals
  17241. const EQ = 'eq';
  17242. const LTE = 'lte';
  17243. const GTE = 'gte';
  17244. const LT = 'lt';
  17245. const GT = 'gt';
  17246. const AND = 'and';
  17247. const OR = 'or';
  17248. const INQ = 'inq';
  17249. const BETWEEN = 'between';
  17250. const NIN = 'nin';
  17251. const NEQ = 'neq';
  17252. __Rule.EQ = 1;
  17253. __Rule.LTE = 2;
  17254. __Rule.GTE = 4;
  17255. __Rule.LT = 8;
  17256. __Rule.GT = 16;
  17257. __Rule.AND = 32;
  17258. __Rule.OR = 64;
  17259. var operators = {
  17260. eq : { operator : '=', bit : __Rule.EQ}
  17261. , lte : { operator : '<=', bit : __Rule.LTE}
  17262. , gte : { operator : '>=', bit : __Rule.GTE}
  17263. , lt : { operator : '<', bit : __Rule.LT}
  17264. , gt : { operator : '>', bit : __Rule.GT}
  17265. , and : { operator : AND, bit : __Rule.AND}
  17266. , or : { operator : OR, bit : __Rule.OR}
  17267. };
  17268. var operatorsIndex = {};
  17269. Object.keys(operators).forEach(op => operatorsIndex[operators[op].bit] = operators[op] );
  17270. function __newInstance(o){
  17271. var d = new Date();
  17272. var id = o.id || uuidv1();
  17273. return { v1ruleId : id, id, datecreated : d, datemodified : d
  17274. , permissive : BIGINT_0, restrictive : BIGINT_0, descendents : BIGINT_0, ancestors : BIGINT_0, list :[] }
  17275. }
  17276. var globalBitIterator = bigIntBitGenerator();
  17277. function assignbit(rule){ var g = globalBitIterator.next().value; rule.bit = g.bit; rule.ruleiId = g.iId;
  17278. return Promise.resolve(rule); // PB : TODO -- remove backward compatible promisification...
  17279. }
  17280. // Find leaf rules from a set of rules ( in a database of rules ) that match the inputs
  17281. function getParticipating(iRule, rList, cb){
  17282. return Promise.all(iRule.results).then((iRules)=>{
  17283. var SUCCESS = BIGINT_0;
  17284. var FAILURE = BIGINT_0;
  17285. var mask = BIGINT_0;
  17286. var results = rList.filter(rule => {
  17287. var found = iRules.find( iR => {
  17288. if(iR === rule || iR.id === rule.id ||
  17289. iR.key === rule.key &&
  17290. ( rule.operator == GT && (
  17291. rule.value <= iR.value && iR.operator == GT
  17292. || rule.value < iR.value && ( iR.operator == GTE || iR.operator == EQ )
  17293. )
  17294. || rule.operator == GTE && (
  17295. rule.value <= iR.value && (iR.operator == GTE || iR.operator == EQ)
  17296. || (iR.value - rule.value) >= 0 && iR.operator == GT
  17297. )
  17298. || rule.operator == LT && (
  17299. rule.value >= iR.value && iR.operator == LT
  17300. || rule.value > iR.value && ( iR.operator == LTE || iR.operator == EQ )
  17301. )
  17302. || rule.operator == LTE && (
  17303. rule.value >= iR.value && (iR.operator == LTE || iR.operator == EQ)
  17304. || (rule.value - iR.value) >= 0 && iR.operator == LT
  17305. )
  17306. || rule.operator == EQ && (
  17307. rule.value == iR.value && iR.operator == EQ
  17308. )
  17309. )
  17310. ) {
  17311. SUCCESS |= rule.bit;
  17312. mask |= rule.mask;
  17313. return true;
  17314. }
  17315. });
  17316. if(!found) {
  17317. if(rule.isleaf) { FAILURE |= rule.bit; }
  17318. else {
  17319. // Composite rule evaluation here is incomplete since we are still iterating and finding leaf level participants.
  17320. // Optimistically computed in case we get lucky here on first pass for result caching efficiency.
  17321. // No point in attempting a full evaluation for composite rule through parts as parts are still being evaluated.
  17322. // A priority evaluation registration of leaf level descendents with a async postponed evaluation task for this rule...
  17323. // may help with evaulation of relevant rules earlier....
  17324. // This specific rules full evaluation may be moot if no asserting participants can be found.
  17325. // Or all its ancestral rules are already true without needing this rule to be evaluated....
  17326. if(rule.permissive & SUCCESS ) { SUCCESS |= rule.bit; mask |= rule.mask; return true; }
  17327. if(rule.restrictive & FAILURE) {FAILURE |= rule.bit; }
  17328. if(rule.restrictive && (rule.restrictive & SUCCESS) === rule.restrictive) { SUCCESS |= rule.bit; mask |= rule.mask; return true; }
  17329. if(rule.permissive && (rule.permissive & FAILURE) === rule.permissive) {FAILURE |= rule.bit; }
  17330. // if((rule.descendents & SUCCESS) === rule.descendents) {
  17331. // // Implies all intermediate groups are true. We only need to examine direct leaf connections.
  17332. // SUCCESS |= rule.bit;
  17333. // mask |= rule.mask;
  17334. // }
  17335. }
  17336. }
  17337. return found;
  17338. });
  17339. if(utils_1.js.isFunction(arguments[arguments.length-1])) { return cb(null, { SUCCESS, FAILURE, mask, results} ) }
  17340. else return { mask, list : found};
  17341. });
  17342. }
  17343. function getParticipatingRoots(participating, rList, cb){
  17344. var qualifiedRoots = [];
  17345. rList.forEach((r)=>{
  17346. if(r.isRoot && evaluate(r, participating)){ qualifiedRoots.push(r); }
  17347. });
  17348. cb(null, qualifiedRoots);
  17349. }
  17350. function toColumnValue(p, v) { return v; }
  17351. function columnEscaped(inst, p) { return p; }
  17352. function getsql_cond_group(){
  17353. if(!this.list) { console.warn(`${this.operator} condition without list is moot`); return ''}
  17354. if(this.list.length < 2) {
  17355. this.list.push( this.list[0] ); // PB : TOOD -- We are adding instead of eliminating Redundant groups ...
  17356. }
  17357. var slqexprs = [];
  17358. this.list.forEach(r => slqexprs.push(r.sql) );
  17359. return '( ' + slqexprs.join( ` ${this.operator} `) + ' )'
  17360. }
  17361. function getfilter_cond_group(){
  17362. if(!this.list) { console.warn(`${this.operator} condition without list is moot`); return ''}
  17363. if(this.list.length < 2) {
  17364. this.list.push( this.list[0] ); // PB : TOOD -- We are adding instead of eliminating Redundant groups ...
  17365. }
  17366. var filterexprs = [];
  17367. this.list.forEach(r => filterexprs.push(r.filter) );
  17368. return filterexprs;
  17369. }
  17370. // PB : TODO -- This might be easier done in a stored procedure.
  17371. // It will also help if participating is not the whole list but the filtered list relevant for this rule.
  17372. // Relocation so inline functions don't need to be redefined again and again.
  17373. // Implement __Rule.isRoot
  17374. var evaluate = function(rule, participating){
  17375. if(rule.bit & participating.SUCCESS ) return true;
  17376. if(rule.bit & participating.FAILURE) return false
  17377. if(rule.permissive & participating.SUCCESS ) { participating.SUCCESS |= rule.bit; return true }
  17378. if(rule.restrictive & participating.FAILURE) {participating.FAILURE |= rule.bit; return false;}
  17379. if(rule.restrictive && (rule.restrictive & participating.SUCCESS) === rule.restrictive) { participating.SUCCESS |= rule.bit; return true }
  17380. if(rule.permissive && (rule.permissive & participating.FAILURE) === rule.permissive) {participating.FAILURE |= rule.bit; return false;}
  17381. // 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.
  17382. if(rule.isleaf) {
  17383. if(participating.results.find( pp => pp === rule )) { participating.SUCCESS |= rule.bit; return true }
  17384. else { participating.FAILURE |= rule.bit; return false; }
  17385. }
  17386. // else {
  17387. // // If descendents are true we can extract only the ones that are direct connections and
  17388. // // Evaluate...
  17389. // var alldescendentsAreTrue = false;
  17390. // if((rule.descendents & participating.SUCCESS) === rule.descendents) {
  17391. // // Implies all intermediate groups are true. We only need to examine direct leaf connections.
  17392. // alldescendentsAreTrue = true;
  17393. // }
  17394. // }
  17395. // getUnevaluated
  17396. var permissive = rule.permissive & (BigInt(-1)-participating.SUCCESS) & (BigInt(-1)-participating.FAILURE);
  17397. for(var rc in rule.list){
  17398. var r = rule.list[rc];
  17399. if(r.bit & permissive) {
  17400. if(evaluate(r, participating)) { participating.SUCCESS |= r.bit; participating.SUCCESS |= rule.bit; return true }
  17401. else participating.FAILURE |= r.bit;
  17402. }
  17403. }
  17404. if(rule.permissive){ participating.FAILURE |= rule.bit; return false; }
  17405. // getUnevaluated.
  17406. var restrictive = rule.restrictive & (BigInt(-1)-participating.SUCCESS) & (BigInt(-1)-participating.FAILURE);
  17407. for(var rc in rule.list){
  17408. var r = rule.list[rc];
  17409. if(r.bit & restrictive) {
  17410. if(!evaluate(r, participating)) { participating.FAILURE |= r.bit; participating.FAILURE |= rule.bit; return false}
  17411. participating.SUCCESS |= r.bit;
  17412. }
  17413. }
  17414. if(rule.restrictive){ participating.SUCCESS |= rule.bit; return true; }
  17415. throw 'Error : A group rule should either be permissive or restrictive...'
  17416. };
  17417. var match = function (inputs, rList, cb) {
  17418. var results = [];
  17419. Rule.build(inputs, clause, results).then((inputRule)=>{
  17420. inputRule.results = results;
  17421. // inputs are usually individual assertions. An and / or condition between individual assertions are usually not useful.
  17422. // Unless the assertion is of the form
  17423. // Eg : this indiviudal's age is between x and y which is kind of rare.
  17424. // A negation is also not how an assertion is typically made. However not from location C or D is a possible assertion.
  17425. // An or assertion is still more rare and is usually an abstraction to not be specific.
  17426. // Eg : The user is from location A or B and uses either a Mac or Ubuntu OS.
  17427. // Although the user has specific characteristics the specificity is not disclosed in the inputs.
  17428. // And is adequate to distinguish the inputs from amongst a superset.
  17429. // 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.
  17430. // 1) The simplest and fastest use case is exact matches of input assertions with and exact match of saved rules.
  17431. // 2) exact input values with condition groups in the rules is also supportable.
  17432. // 3) complex input rules as abstract or range assertions matching
  17433. // complex rules that have range or absctract conditions -- How to Implement ??
  17434. // IMPLEMENTATION AS SQL
  17435. // FIND PARTICIPATING rules that evaluate true.
  17436. /* WHERE rule.key = input.key ( rule.operator = '>' AND rule.value <= input.value AND input.operator = '>'
  17437. OR rule.operator = '>' AND rule.value < input.value AND input.operator = '>='
  17438. OR rule.operator = '>=' AND rule.value <= input.value AND (input.operator = '>=' OR input.operator = '=')
  17439. ) AND
  17440. ( rule.operator = '<' AND rule.value <= input.value AND input.operator = '<'
  17441. OR rule.operator = '<' AND rule.value < input.value AND input.operator = '<='
  17442. OR rule.operator = '<=' AND rule.value <= input.value AND (input.operator = '<=' OR input.operator = '=')
  17443. )
  17444. */
  17445. // QUALIFY ALL ( GROUPED and LEAF ) RULES that evaluate true using the assertions from the participating rules.
  17446. /*
  17447. LEFT JOIN rule
  17448. WHERE participating.bit = (participating.bit & rule.mask)
  17449. -- and rule.operator = 'or'
  17450. -- or rule.mask = (allparticipating.mask & rule.mask ) and rule.operator = 'and'
  17451. */
  17452. /* USE THE QUALIFED RULES TO EVALUEATE RESULTS for GROUP LEVELS and ROOT RULES.
  17453. Any grouped rule is associated with 3 kinds evaluation sets composed of rules that are either leaf
  17454. level rules directly or through other promoted grouped rules or groups.
  17455. Evaluation Sets.
  17456. Permissive rules, Restrictive rules, Indeterminant rules
  17457. 1) Permissive bits turn the whole group to true if any one is true.
  17458. Irrespective of all the other participating leaf rules.
  17459. It is therefore not required to evaluate any other types of leaf rules.
  17460. 2) Restrictive rules turn the whole group to false if any one is false.
  17461. If there are no permissive rules it then becomes relevant to evaluate the restrictive rules.
  17462. Other Indeterminant rule evaluation is therefore not relevant.
  17463. 3) Indeterminant rules need to be evaluated at run time.
  17464. -- Are typically unevaluated nested groups
  17465. -- Or can be Individual Evaluated results
  17466. which don't yet determine the overall result and mean anything
  17467. until a complex hierarchy of conditions
  17468. are evaluated and collectively satisifed.
  17469. -- Since we do not (yet) support rule negations
  17470. -- it necessarily implies that if all of the Indeterminant set items are true then the whole group is true.
  17471. -- which then implies we can bypass the Indeterminant group and subgroup structure evaluation for efficiency.
  17472. -- Pre-Evaluated promotion to parent group evaluation sets to parent groups evaluation sets.
  17473. Composition of a subgroup can be promoted directly into the parent groups evaluation sets when certain conditions are met.
  17474. When There are no Permissive rules
  17475. AND ( There are no restrictive rules OR all the restrictive rules are true )
  17476. Then evaluation of the descendents rule set is required until we reach all leaf level nodes.
  17477. Subgroups are recursively evaluated using these same 3 steps.
  17478. Following caching efficiencies can be precomputed and stored with the parents rule sets as rule promotions.
  17479. If the sub group rule participates in parents permissive set.
  17480. All of its permissive rules should be added to the parent groups permissive set.
  17481. -- The sub group has no restrictive and descendents sets sub group bit need not be in the parents permissive set.
  17482. If subgroup has restricitve sets and no descendents sets
  17483. -- and is a subset of the parent groups restrictive set
  17484. -- then subgroup bit can be removed from parents permissive and restrictive groups.
  17485. -- This is good for preventing re-evaluation of the sub group for efficiency.
  17486. -- else subgroup bit should be present in the permissive
  17487. Sub group has descendents sets
  17488. -- the sub group bit must necessarily be added to the parents permissive set.
  17489. If the sub group rule participates in the parents restrictive set
  17490. - Sub Group is Pure Permissive = Has no restrictive set or descendents set
  17491. Runtime Evaluate.
  17492. - Sub Group is Pure Restrictive = Has no permissive or descendents set
  17493. -- Restrictive set of sub group should be promoted into the restrictive set of the parent
  17494. -- sub group bit should be removed from all parent sets for effciency by bypassing subgroup evaluation.
  17495. - All other cases Runtime Evaluate.
  17496. Sub Group participates in descendents set.
  17497. -- Run time evaluation.
  17498. */
  17499. getParticipating(inputRule, rList, (err, participating)=>{
  17500. getParticipatingRoots(participating, rList, (err, participatingRoots)=>{
  17501. cb(null, participatingRoots);
  17502. });
  17503. });
  17504. });
  17505. };
  17506. // PB : TODO -- Creations are easy. Edits and updates for addition of a single rule are expensive due to cascading updates to all relations.
  17507. // Connections can be made in multiple dimensions. For Rules we currlently only implement the child and parent dimensions.
  17508. // PB : TODO -ve dimensions ?? In this implementation there are no negative dimensions...
  17509. // So both -ve and +ve dimensions are independent. But can be marked as opposites.
  17510. // Note : Therefore Child and Parent are different independent dimensions.
  17511. // They may not be exactly oposing in this case ( Rules are networks ) and some circular loops may exist.
  17512. var connectRules = function(as, ...rest){ return branch[as](...rest) };
  17513. var branch = {};
  17514. branch[__Rule.AND] = function(rChild, rParent, refresh){
  17515. rChild.ancestors |= rParent.ancestors | rParent.bit; // This should set the whole ancestral network.
  17516. if(rParent.permissive || rParent.operator === OR) throw 'Error Invalid rule addition to parent'
  17517. if(rParent.restrictive & rChild.bit) return; // Was already connected within this and.
  17518. rParent.list.push(rChild);
  17519. // if(!rParent.permissive && !rParent.restrictive) {
  17520. // if(rParent.operator !== AND && rParent.operator !== OR) {
  17521. // if(!rParent.operator) rParent.operator = AND; // Implicit AND if unspeicified
  17522. // else throw 'Incomplete parent. Invalid operator or no operator specified.'
  17523. // }
  17524. // rParent.operator === AND ? rParent.restrictive |= rChild.bit : rParent.permissive |= rChild.bit ;
  17525. // }
  17526. // Promotions : All child rules are only a bunch of Ands or ors
  17527. // they can be flattened directly into the containing rule.
  17528. // if(!rParent.permissive) { rParent.restrictive |= rChild.restrictive; rParent.restrictive |= rChild.bit; }
  17529. // if(!rParent.restrictive) { rParent.permissive |= rChild.permissive; rParent.permissive |= rChild.bit; }
  17530. rParent.restrictive |= rChild.restrictive | rChild.bit;
  17531. // Descendents should be all non immediate descendents.
  17532. // Immmediate descendents can always be computed as (r.permissive | r.restrictive) & !r.descendents
  17533. // child may be either permissive or restrictive. Since child.restrictive is already added in.
  17534. rParent.descendents |= rChild.descendents | rChild.permissive | rChild.restrictive ;
  17535. // If we add another ancestral network to one of the ancestors we need to cascaded it down to the child network.
  17536. // and vice versa.
  17537. if(refresh){
  17538. // PB : TODO -- Cascading refreshes should avoid circular loops..
  17539. rChild.refreshDescendents(rChild.ancestors);
  17540. rParent.refreshAncestors(rParent.descendents);
  17541. }
  17542. };
  17543. branch[__Rule.OR] = function(rChild, rParent, refresh){
  17544. rChild.ancestors |= rParent.ancestors | rParent.bit;
  17545. if(rParent.restrictive || rParent.operator !== OR) throw 'Error Invalid rule addition to parent'
  17546. if(rParent.permissive & rChild.bit) return
  17547. rParent.list.push(rChild);
  17548. rParent.permissive |= rChild.permissive | rChild.bit;
  17549. rParent.descendents |= rChild.descendents | rChild.permissive | rChild.restrictive ;
  17550. if(refresh){
  17551. rChild.refreshDescendents(rChild.ancestors); // This should set the whole ancestral network.
  17552. rParent.refreshAncestors(rParent.descendents);
  17553. }
  17554. };
  17555. var rProto = { migrationstate : 8, operator : EQ
  17556. , evaluate // PB : TODO -- Enforce preconditions for evaluate on instance. Eg. Assignbit is a precondition for evaluate or match.
  17557. , connect : function(parent){
  17558. connectRules(operators[parent.operator].bit, this, parent);
  17559. }
  17560. // PB : TODO -- Cloning descriptors using assgin is expense. Review and just atttach to each new instance...
  17561. , get sql(){
  17562. var getSql = this.operator === AND ? getsql_cond_group : this.operator === OR ? getsql_cond_group
  17563. : ()=>this.key + ' ' + operators[this.operator].operator + ` '${this.value}' `;
  17564. return getSql.call(this)
  17565. }
  17566. , get filter(){
  17567. var getFilter = this.operator === AND ? getfilter_cond_group : this.operator === OR ? getgetfilter_cond_group
  17568. : ()=>{
  17569. var f = {};
  17570. f[this.key] = {};
  17571. f[this.key][this.operator] = this.value; return f;};
  17572. return getFilter.call(this)
  17573. }
  17574. // PB : TODO -- this.siblings will be a nice addtion.
  17575. , get mask(){ return this.permissive | this.restrictive | this.descendents | this.ancestors | this.bit }
  17576. , get isIndependent() { return this.bit === this.mask }
  17577. , get isRoot() { return !this.ancestors }
  17578. , get isChild() { return this.ancestors }
  17579. , get isParent() { return (this.permissive | this.restrictive | this.descendents) }
  17580. , get isleaf() { return !(this.permissive | this.restrictive | this.descendents) }
  17581. , get iscomposite() { return this.list.length > 1 } // PB : TODO -- Non composite parents may be possible to collapse
  17582. };
  17583. return _Rule.extend()
  17584. })();
  17585. utils_1.core = core_1;
  17586. var bbhverse = utils_1;
  17587. const { spawn: spawn$1, spawnSync } = childProcess__default['default'];
  17588. function nodeShellExec$1() {
  17589. var args = Array.from(arguments);
  17590. var opts = args[2] = args[2] || {};
  17591. opts.title ? null : opts.title = `${args[0]} ${args[1] }`;
  17592. const child = spawn$1(...arguments);
  17593. // // const spawn = require('child_process').spawn;
  17594. // const s = spawn(
  17595. // 'C:\\Program Files\\Git\\bin\\sh.exe'
  17596. // , ['notepad', 'index'], { cwd: __dirname });
  17597. var p = new Promise(function(resolve, reject){
  17598. if(!opts.detached) {
  17599. var messages = []; // PB : TODO -- Explore stream for Task level aggregation to prevent interleaved messages from multiple tasks...
  17600. var success = true;
  17601. if(opts.stdio !== 'ignore') {
  17602. child.stdout.setEncoding('utf8');
  17603. child.stderr.setEncoding('utf8');
  17604. child.stdout.on('data', (chunk) => {
  17605. chunk.trim() === '' ? null : messages.push(chunk); /* console.log('d: ' + chunk) */
  17606. process.stdout.write( chunk );
  17607. });
  17608. child.on('error', (chunk) => { success = false; messages.push(chunk); /* console.error('e: ' + chunk) */ } );
  17609. child.stderr.on('data', (chunk) => {
  17610. if(messages.join('').indexOf('fatal: not a git repository') > -1) opts.haserrors = true;
  17611. messages.push(chunk);
  17612. process.stdout.write( chunk );
  17613. // console.error('stderr e: ' + chunk)
  17614. });
  17615. }
  17616. child.on('close', (code) => {
  17617. var logEntry = { code, success };
  17618. if(+code !== 0 || opts.haserrors) { success = false; logEntry = { result: `${opts.title} exited with code ${code}`, success, code };} if(opts.stdio !== 'ignore') {
  17619. logEntry = { result: `${opts.title} exited with code ${code}`, messages, code };
  17620. logEntry.success = success;
  17621. if(opts.runas){
  17622. // success ? logEntry.success = true : null;
  17623. fs__default['default'].writeFileSync('run.log', ', ' + JSON.stringify(logEntry), {'flag':'a+'} );
  17624. }
  17625. else {
  17626. // console.log( messages.join('') )
  17627. process.stdout.write( messages.join('') );
  17628. }
  17629. }
  17630. if(code !== 0 || opts.haserrors) return reject(logEntry)
  17631. resolve(logEntry);
  17632. });
  17633. }
  17634. else {
  17635. child.unref();
  17636. resolve(true);
  17637. }
  17638. });
  17639. p.process = child;
  17640. return p;
  17641. }
  17642. var prompt = function(choices, label, defaultchoice){
  17643. return this.prompter.ask(
  17644. `${label} \n ` + Object.keys(choices).map(choice => { return ` ${(+choice) + 1}) ${choices[choice]} `}).join('\n') + `\n default ( <= ${ defaultchoice || choices[0]} ) : `
  17645. ).then(choice => {
  17646. if(!choice) return defaultchoice || choices[0];
  17647. if(choice && isNaN(+choice)) return choice;
  17648. return choices[choice + 1];
  17649. })
  17650. };
  17651. var cli = {
  17652. nodeShellExec: nodeShellExec$1
  17653. , get prompter() {
  17654. var prompt_interface = {
  17655. ask : function(q){
  17656. // Needs to be serialized. Parallel asks are not possible.
  17657. const clii = readline__default['default'].createInterface({ input: process.stdin, output: process.stdout });
  17658. return new Promise((resolve, reject)=>{
  17659. clii.question(q, (answer)=>{
  17660. clii.close();
  17661. resolve(answer);
  17662. });
  17663. })
  17664. }
  17665. };
  17666. return prompt_interface
  17667. }
  17668. , prompt
  17669. };
  17670. var cliverse = cli;
  17671. var colorName = {
  17672. "aliceblue": [240, 248, 255],
  17673. "antiquewhite": [250, 235, 215],
  17674. "aqua": [0, 255, 255],
  17675. "aquamarine": [127, 255, 212],
  17676. "azure": [240, 255, 255],
  17677. "beige": [245, 245, 220],
  17678. "bisque": [255, 228, 196],
  17679. "black": [0, 0, 0],
  17680. "blanchedalmond": [255, 235, 205],
  17681. "blue": [0, 0, 255],
  17682. "blueviolet": [138, 43, 226],
  17683. "brown": [165, 42, 42],
  17684. "burlywood": [222, 184, 135],
  17685. "cadetblue": [95, 158, 160],
  17686. "chartreuse": [127, 255, 0],
  17687. "chocolate": [210, 105, 30],
  17688. "coral": [255, 127, 80],
  17689. "cornflowerblue": [100, 149, 237],
  17690. "cornsilk": [255, 248, 220],
  17691. "crimson": [220, 20, 60],
  17692. "cyan": [0, 255, 255],
  17693. "darkblue": [0, 0, 139],
  17694. "darkcyan": [0, 139, 139],
  17695. "darkgoldenrod": [184, 134, 11],
  17696. "darkgray": [169, 169, 169],
  17697. "darkgreen": [0, 100, 0],
  17698. "darkgrey": [169, 169, 169],
  17699. "darkkhaki": [189, 183, 107],
  17700. "darkmagenta": [139, 0, 139],
  17701. "darkolivegreen": [85, 107, 47],
  17702. "darkorange": [255, 140, 0],
  17703. "darkorchid": [153, 50, 204],
  17704. "darkred": [139, 0, 0],
  17705. "darksalmon": [233, 150, 122],
  17706. "darkseagreen": [143, 188, 143],
  17707. "darkslateblue": [72, 61, 139],
  17708. "darkslategray": [47, 79, 79],
  17709. "darkslategrey": [47, 79, 79],
  17710. "darkturquoise": [0, 206, 209],
  17711. "darkviolet": [148, 0, 211],
  17712. "deeppink": [255, 20, 147],
  17713. "deepskyblue": [0, 191, 255],
  17714. "dimgray": [105, 105, 105],
  17715. "dimgrey": [105, 105, 105],
  17716. "dodgerblue": [30, 144, 255],
  17717. "firebrick": [178, 34, 34],
  17718. "floralwhite": [255, 250, 240],
  17719. "forestgreen": [34, 139, 34],
  17720. "fuchsia": [255, 0, 255],
  17721. "gainsboro": [220, 220, 220],
  17722. "ghostwhite": [248, 248, 255],
  17723. "gold": [255, 215, 0],
  17724. "goldenrod": [218, 165, 32],
  17725. "gray": [128, 128, 128],
  17726. "green": [0, 128, 0],
  17727. "greenyellow": [173, 255, 47],
  17728. "grey": [128, 128, 128],
  17729. "honeydew": [240, 255, 240],
  17730. "hotpink": [255, 105, 180],
  17731. "indianred": [205, 92, 92],
  17732. "indigo": [75, 0, 130],
  17733. "ivory": [255, 255, 240],
  17734. "khaki": [240, 230, 140],
  17735. "lavender": [230, 230, 250],
  17736. "lavenderblush": [255, 240, 245],
  17737. "lawngreen": [124, 252, 0],
  17738. "lemonchiffon": [255, 250, 205],
  17739. "lightblue": [173, 216, 230],
  17740. "lightcoral": [240, 128, 128],
  17741. "lightcyan": [224, 255, 255],
  17742. "lightgoldenrodyellow": [250, 250, 210],
  17743. "lightgray": [211, 211, 211],
  17744. "lightgreen": [144, 238, 144],
  17745. "lightgrey": [211, 211, 211],
  17746. "lightpink": [255, 182, 193],
  17747. "lightsalmon": [255, 160, 122],
  17748. "lightseagreen": [32, 178, 170],
  17749. "lightskyblue": [135, 206, 250],
  17750. "lightslategray": [119, 136, 153],
  17751. "lightslategrey": [119, 136, 153],
  17752. "lightsteelblue": [176, 196, 222],
  17753. "lightyellow": [255, 255, 224],
  17754. "lime": [0, 255, 0],
  17755. "limegreen": [50, 205, 50],
  17756. "linen": [250, 240, 230],
  17757. "magenta": [255, 0, 255],
  17758. "maroon": [128, 0, 0],
  17759. "mediumaquamarine": [102, 205, 170],
  17760. "mediumblue": [0, 0, 205],
  17761. "mediumorchid": [186, 85, 211],
  17762. "mediumpurple": [147, 112, 219],
  17763. "mediumseagreen": [60, 179, 113],
  17764. "mediumslateblue": [123, 104, 238],
  17765. "mediumspringgreen": [0, 250, 154],
  17766. "mediumturquoise": [72, 209, 204],
  17767. "mediumvioletred": [199, 21, 133],
  17768. "midnightblue": [25, 25, 112],
  17769. "mintcream": [245, 255, 250],
  17770. "mistyrose": [255, 228, 225],
  17771. "moccasin": [255, 228, 181],
  17772. "navajowhite": [255, 222, 173],
  17773. "navy": [0, 0, 128],
  17774. "oldlace": [253, 245, 230],
  17775. "olive": [128, 128, 0],
  17776. "olivedrab": [107, 142, 35],
  17777. "orange": [255, 165, 0],
  17778. "orangered": [255, 69, 0],
  17779. "orchid": [218, 112, 214],
  17780. "palegoldenrod": [238, 232, 170],
  17781. "palegreen": [152, 251, 152],
  17782. "paleturquoise": [175, 238, 238],
  17783. "palevioletred": [219, 112, 147],
  17784. "papayawhip": [255, 239, 213],
  17785. "peachpuff": [255, 218, 185],
  17786. "peru": [205, 133, 63],
  17787. "pink": [255, 192, 203],
  17788. "plum": [221, 160, 221],
  17789. "powderblue": [176, 224, 230],
  17790. "purple": [128, 0, 128],
  17791. "rebeccapurple": [102, 51, 153],
  17792. "red": [255, 0, 0],
  17793. "rosybrown": [188, 143, 143],
  17794. "royalblue": [65, 105, 225],
  17795. "saddlebrown": [139, 69, 19],
  17796. "salmon": [250, 128, 114],
  17797. "sandybrown": [244, 164, 96],
  17798. "seagreen": [46, 139, 87],
  17799. "seashell": [255, 245, 238],
  17800. "sienna": [160, 82, 45],
  17801. "silver": [192, 192, 192],
  17802. "skyblue": [135, 206, 235],
  17803. "slateblue": [106, 90, 205],
  17804. "slategray": [112, 128, 144],
  17805. "slategrey": [112, 128, 144],
  17806. "snow": [255, 250, 250],
  17807. "springgreen": [0, 255, 127],
  17808. "steelblue": [70, 130, 180],
  17809. "tan": [210, 180, 140],
  17810. "teal": [0, 128, 128],
  17811. "thistle": [216, 191, 216],
  17812. "tomato": [255, 99, 71],
  17813. "turquoise": [64, 224, 208],
  17814. "violet": [238, 130, 238],
  17815. "wheat": [245, 222, 179],
  17816. "white": [255, 255, 255],
  17817. "whitesmoke": [245, 245, 245],
  17818. "yellow": [255, 255, 0],
  17819. "yellowgreen": [154, 205, 50]
  17820. };
  17821. /* MIT license */
  17822. /* eslint-disable no-mixed-operators */
  17823. // NOTE: conversions should only return primitive values (i.e. arrays, or
  17824. // values that give correct `typeof` results).
  17825. // do not use box values types (i.e. Number(), String(), etc.)
  17826. const reverseKeywords = {};
  17827. for (const key of Object.keys(colorName)) {
  17828. reverseKeywords[colorName[key]] = key;
  17829. }
  17830. const convert$1 = {
  17831. rgb: {channels: 3, labels: 'rgb'},
  17832. hsl: {channels: 3, labels: 'hsl'},
  17833. hsv: {channels: 3, labels: 'hsv'},
  17834. hwb: {channels: 3, labels: 'hwb'},
  17835. cmyk: {channels: 4, labels: 'cmyk'},
  17836. xyz: {channels: 3, labels: 'xyz'},
  17837. lab: {channels: 3, labels: 'lab'},
  17838. lch: {channels: 3, labels: 'lch'},
  17839. hex: {channels: 1, labels: ['hex']},
  17840. keyword: {channels: 1, labels: ['keyword']},
  17841. ansi16: {channels: 1, labels: ['ansi16']},
  17842. ansi256: {channels: 1, labels: ['ansi256']},
  17843. hcg: {channels: 3, labels: ['h', 'c', 'g']},
  17844. apple: {channels: 3, labels: ['r16', 'g16', 'b16']},
  17845. gray: {channels: 1, labels: ['gray']}
  17846. };
  17847. var conversions = convert$1;
  17848. // Hide .channels and .labels properties
  17849. for (const model of Object.keys(convert$1)) {
  17850. if (!('channels' in convert$1[model])) {
  17851. throw new Error('missing channels property: ' + model);
  17852. }
  17853. if (!('labels' in convert$1[model])) {
  17854. throw new Error('missing channel labels property: ' + model);
  17855. }
  17856. if (convert$1[model].labels.length !== convert$1[model].channels) {
  17857. throw new Error('channel and label counts mismatch: ' + model);
  17858. }
  17859. const {channels, labels} = convert$1[model];
  17860. delete convert$1[model].channels;
  17861. delete convert$1[model].labels;
  17862. Object.defineProperty(convert$1[model], 'channels', {value: channels});
  17863. Object.defineProperty(convert$1[model], 'labels', {value: labels});
  17864. }
  17865. convert$1.rgb.hsl = function (rgb) {
  17866. const r = rgb[0] / 255;
  17867. const g = rgb[1] / 255;
  17868. const b = rgb[2] / 255;
  17869. const min = Math.min(r, g, b);
  17870. const max = Math.max(r, g, b);
  17871. const delta = max - min;
  17872. let h;
  17873. let s;
  17874. if (max === min) {
  17875. h = 0;
  17876. } else if (r === max) {
  17877. h = (g - b) / delta;
  17878. } else if (g === max) {
  17879. h = 2 + (b - r) / delta;
  17880. } else if (b === max) {
  17881. h = 4 + (r - g) / delta;
  17882. }
  17883. h = Math.min(h * 60, 360);
  17884. if (h < 0) {
  17885. h += 360;
  17886. }
  17887. const l = (min + max) / 2;
  17888. if (max === min) {
  17889. s = 0;
  17890. } else if (l <= 0.5) {
  17891. s = delta / (max + min);
  17892. } else {
  17893. s = delta / (2 - max - min);
  17894. }
  17895. return [h, s * 100, l * 100];
  17896. };
  17897. convert$1.rgb.hsv = function (rgb) {
  17898. let rdif;
  17899. let gdif;
  17900. let bdif;
  17901. let h;
  17902. let s;
  17903. const r = rgb[0] / 255;
  17904. const g = rgb[1] / 255;
  17905. const b = rgb[2] / 255;
  17906. const v = Math.max(r, g, b);
  17907. const diff = v - Math.min(r, g, b);
  17908. const diffc = function (c) {
  17909. return (v - c) / 6 / diff + 1 / 2;
  17910. };
  17911. if (diff === 0) {
  17912. h = 0;
  17913. s = 0;
  17914. } else {
  17915. s = diff / v;
  17916. rdif = diffc(r);
  17917. gdif = diffc(g);
  17918. bdif = diffc(b);
  17919. if (r === v) {
  17920. h = bdif - gdif;
  17921. } else if (g === v) {
  17922. h = (1 / 3) + rdif - bdif;
  17923. } else if (b === v) {
  17924. h = (2 / 3) + gdif - rdif;
  17925. }
  17926. if (h < 0) {
  17927. h += 1;
  17928. } else if (h > 1) {
  17929. h -= 1;
  17930. }
  17931. }
  17932. return [
  17933. h * 360,
  17934. s * 100,
  17935. v * 100
  17936. ];
  17937. };
  17938. convert$1.rgb.hwb = function (rgb) {
  17939. const r = rgb[0];
  17940. const g = rgb[1];
  17941. let b = rgb[2];
  17942. const h = convert$1.rgb.hsl(rgb)[0];
  17943. const w = 1 / 255 * Math.min(r, Math.min(g, b));
  17944. b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
  17945. return [h, w * 100, b * 100];
  17946. };
  17947. convert$1.rgb.cmyk = function (rgb) {
  17948. const r = rgb[0] / 255;
  17949. const g = rgb[1] / 255;
  17950. const b = rgb[2] / 255;
  17951. const k = Math.min(1 - r, 1 - g, 1 - b);
  17952. const c = (1 - r - k) / (1 - k) || 0;
  17953. const m = (1 - g - k) / (1 - k) || 0;
  17954. const y = (1 - b - k) / (1 - k) || 0;
  17955. return [c * 100, m * 100, y * 100, k * 100];
  17956. };
  17957. function comparativeDistance(x, y) {
  17958. /*
  17959. See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
  17960. */
  17961. return (
  17962. ((x[0] - y[0]) ** 2) +
  17963. ((x[1] - y[1]) ** 2) +
  17964. ((x[2] - y[2]) ** 2)
  17965. );
  17966. }
  17967. convert$1.rgb.keyword = function (rgb) {
  17968. const reversed = reverseKeywords[rgb];
  17969. if (reversed) {
  17970. return reversed;
  17971. }
  17972. let currentClosestDistance = Infinity;
  17973. let currentClosestKeyword;
  17974. for (const keyword of Object.keys(colorName)) {
  17975. const value = colorName[keyword];
  17976. // Compute comparative distance
  17977. const distance = comparativeDistance(rgb, value);
  17978. // Check if its less, if so set as closest
  17979. if (distance < currentClosestDistance) {
  17980. currentClosestDistance = distance;
  17981. currentClosestKeyword = keyword;
  17982. }
  17983. }
  17984. return currentClosestKeyword;
  17985. };
  17986. convert$1.keyword.rgb = function (keyword) {
  17987. return colorName[keyword];
  17988. };
  17989. convert$1.rgb.xyz = function (rgb) {
  17990. let r = rgb[0] / 255;
  17991. let g = rgb[1] / 255;
  17992. let b = rgb[2] / 255;
  17993. // Assume sRGB
  17994. r = r > 0.04045 ? (((r + 0.055) / 1.055) ** 2.4) : (r / 12.92);
  17995. g = g > 0.04045 ? (((g + 0.055) / 1.055) ** 2.4) : (g / 12.92);
  17996. b = b > 0.04045 ? (((b + 0.055) / 1.055) ** 2.4) : (b / 12.92);
  17997. const x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805);
  17998. const y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722);
  17999. const z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505);
  18000. return [x * 100, y * 100, z * 100];
  18001. };
  18002. convert$1.rgb.lab = function (rgb) {
  18003. const xyz = convert$1.rgb.xyz(rgb);
  18004. let x = xyz[0];
  18005. let y = xyz[1];
  18006. let z = xyz[2];
  18007. x /= 95.047;
  18008. y /= 100;
  18009. z /= 108.883;
  18010. x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116);
  18011. y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116);
  18012. z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116);
  18013. const l = (116 * y) - 16;
  18014. const a = 500 * (x - y);
  18015. const b = 200 * (y - z);
  18016. return [l, a, b];
  18017. };
  18018. convert$1.hsl.rgb = function (hsl) {
  18019. const h = hsl[0] / 360;
  18020. const s = hsl[1] / 100;
  18021. const l = hsl[2] / 100;
  18022. let t2;
  18023. let t3;
  18024. let val;
  18025. if (s === 0) {
  18026. val = l * 255;
  18027. return [val, val, val];
  18028. }
  18029. if (l < 0.5) {
  18030. t2 = l * (1 + s);
  18031. } else {
  18032. t2 = l + s - l * s;
  18033. }
  18034. const t1 = 2 * l - t2;
  18035. const rgb = [0, 0, 0];
  18036. for (let i = 0; i < 3; i++) {
  18037. t3 = h + 1 / 3 * -(i - 1);
  18038. if (t3 < 0) {
  18039. t3++;
  18040. }
  18041. if (t3 > 1) {
  18042. t3--;
  18043. }
  18044. if (6 * t3 < 1) {
  18045. val = t1 + (t2 - t1) * 6 * t3;
  18046. } else if (2 * t3 < 1) {
  18047. val = t2;
  18048. } else if (3 * t3 < 2) {
  18049. val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
  18050. } else {
  18051. val = t1;
  18052. }
  18053. rgb[i] = val * 255;
  18054. }
  18055. return rgb;
  18056. };
  18057. convert$1.hsl.hsv = function (hsl) {
  18058. const h = hsl[0];
  18059. let s = hsl[1] / 100;
  18060. let l = hsl[2] / 100;
  18061. let smin = s;
  18062. const lmin = Math.max(l, 0.01);
  18063. l *= 2;
  18064. s *= (l <= 1) ? l : 2 - l;
  18065. smin *= lmin <= 1 ? lmin : 2 - lmin;
  18066. const v = (l + s) / 2;
  18067. const sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s);
  18068. return [h, sv * 100, v * 100];
  18069. };
  18070. convert$1.hsv.rgb = function (hsv) {
  18071. const h = hsv[0] / 60;
  18072. const s = hsv[1] / 100;
  18073. let v = hsv[2] / 100;
  18074. const hi = Math.floor(h) % 6;
  18075. const f = h - Math.floor(h);
  18076. const p = 255 * v * (1 - s);
  18077. const q = 255 * v * (1 - (s * f));
  18078. const t = 255 * v * (1 - (s * (1 - f)));
  18079. v *= 255;
  18080. switch (hi) {
  18081. case 0:
  18082. return [v, t, p];
  18083. case 1:
  18084. return [q, v, p];
  18085. case 2:
  18086. return [p, v, t];
  18087. case 3:
  18088. return [p, q, v];
  18089. case 4:
  18090. return [t, p, v];
  18091. case 5:
  18092. return [v, p, q];
  18093. }
  18094. };
  18095. convert$1.hsv.hsl = function (hsv) {
  18096. const h = hsv[0];
  18097. const s = hsv[1] / 100;
  18098. const v = hsv[2] / 100;
  18099. const vmin = Math.max(v, 0.01);
  18100. let sl;
  18101. let l;
  18102. l = (2 - s) * v;
  18103. const lmin = (2 - s) * vmin;
  18104. sl = s * vmin;
  18105. sl /= (lmin <= 1) ? lmin : 2 - lmin;
  18106. sl = sl || 0;
  18107. l /= 2;
  18108. return [h, sl * 100, l * 100];
  18109. };
  18110. // http://dev.w3.org/csswg/css-color/#hwb-to-rgb
  18111. convert$1.hwb.rgb = function (hwb) {
  18112. const h = hwb[0] / 360;
  18113. let wh = hwb[1] / 100;
  18114. let bl = hwb[2] / 100;
  18115. const ratio = wh + bl;
  18116. let f;
  18117. // Wh + bl cant be > 1
  18118. if (ratio > 1) {
  18119. wh /= ratio;
  18120. bl /= ratio;
  18121. }
  18122. const i = Math.floor(6 * h);
  18123. const v = 1 - bl;
  18124. f = 6 * h - i;
  18125. if ((i & 0x01) !== 0) {
  18126. f = 1 - f;
  18127. }
  18128. const n = wh + f * (v - wh); // Linear interpolation
  18129. let r;
  18130. let g;
  18131. let b;
  18132. /* eslint-disable max-statements-per-line,no-multi-spaces */
  18133. switch (i) {
  18134. default:
  18135. case 6:
  18136. case 0: r = v; g = n; b = wh; break;
  18137. case 1: r = n; g = v; b = wh; break;
  18138. case 2: r = wh; g = v; b = n; break;
  18139. case 3: r = wh; g = n; b = v; break;
  18140. case 4: r = n; g = wh; b = v; break;
  18141. case 5: r = v; g = wh; b = n; break;
  18142. }
  18143. /* eslint-enable max-statements-per-line,no-multi-spaces */
  18144. return [r * 255, g * 255, b * 255];
  18145. };
  18146. convert$1.cmyk.rgb = function (cmyk) {
  18147. const c = cmyk[0] / 100;
  18148. const m = cmyk[1] / 100;
  18149. const y = cmyk[2] / 100;
  18150. const k = cmyk[3] / 100;
  18151. const r = 1 - Math.min(1, c * (1 - k) + k);
  18152. const g = 1 - Math.min(1, m * (1 - k) + k);
  18153. const b = 1 - Math.min(1, y * (1 - k) + k);
  18154. return [r * 255, g * 255, b * 255];
  18155. };
  18156. convert$1.xyz.rgb = function (xyz) {
  18157. const x = xyz[0] / 100;
  18158. const y = xyz[1] / 100;
  18159. const z = xyz[2] / 100;
  18160. let r;
  18161. let g;
  18162. let b;
  18163. r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);
  18164. g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);
  18165. b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570);
  18166. // Assume sRGB
  18167. r = r > 0.0031308
  18168. ? ((1.055 * (r ** (1.0 / 2.4))) - 0.055)
  18169. : r * 12.92;
  18170. g = g > 0.0031308
  18171. ? ((1.055 * (g ** (1.0 / 2.4))) - 0.055)
  18172. : g * 12.92;
  18173. b = b > 0.0031308
  18174. ? ((1.055 * (b ** (1.0 / 2.4))) - 0.055)
  18175. : b * 12.92;
  18176. r = Math.min(Math.max(0, r), 1);
  18177. g = Math.min(Math.max(0, g), 1);
  18178. b = Math.min(Math.max(0, b), 1);
  18179. return [r * 255, g * 255, b * 255];
  18180. };
  18181. convert$1.xyz.lab = function (xyz) {
  18182. let x = xyz[0];
  18183. let y = xyz[1];
  18184. let z = xyz[2];
  18185. x /= 95.047;
  18186. y /= 100;
  18187. z /= 108.883;
  18188. x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116);
  18189. y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116);
  18190. z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116);
  18191. const l = (116 * y) - 16;
  18192. const a = 500 * (x - y);
  18193. const b = 200 * (y - z);
  18194. return [l, a, b];
  18195. };
  18196. convert$1.lab.xyz = function (lab) {
  18197. const l = lab[0];
  18198. const a = lab[1];
  18199. const b = lab[2];
  18200. let x;
  18201. let y;
  18202. let z;
  18203. y = (l + 16) / 116;
  18204. x = a / 500 + y;
  18205. z = y - b / 200;
  18206. const y2 = y ** 3;
  18207. const x2 = x ** 3;
  18208. const z2 = z ** 3;
  18209. y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
  18210. x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
  18211. z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
  18212. x *= 95.047;
  18213. y *= 100;
  18214. z *= 108.883;
  18215. return [x, y, z];
  18216. };
  18217. convert$1.lab.lch = function (lab) {
  18218. const l = lab[0];
  18219. const a = lab[1];
  18220. const b = lab[2];
  18221. let h;
  18222. const hr = Math.atan2(b, a);
  18223. h = hr * 360 / 2 / Math.PI;
  18224. if (h < 0) {
  18225. h += 360;
  18226. }
  18227. const c = Math.sqrt(a * a + b * b);
  18228. return [l, c, h];
  18229. };
  18230. convert$1.lch.lab = function (lch) {
  18231. const l = lch[0];
  18232. const c = lch[1];
  18233. const h = lch[2];
  18234. const hr = h / 360 * 2 * Math.PI;
  18235. const a = c * Math.cos(hr);
  18236. const b = c * Math.sin(hr);
  18237. return [l, a, b];
  18238. };
  18239. convert$1.rgb.ansi16 = function (args, saturation = null) {
  18240. const [r, g, b] = args;
  18241. let value = saturation === null ? convert$1.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization
  18242. value = Math.round(value / 50);
  18243. if (value === 0) {
  18244. return 30;
  18245. }
  18246. let ansi = 30
  18247. + ((Math.round(b / 255) << 2)
  18248. | (Math.round(g / 255) << 1)
  18249. | Math.round(r / 255));
  18250. if (value === 2) {
  18251. ansi += 60;
  18252. }
  18253. return ansi;
  18254. };
  18255. convert$1.hsv.ansi16 = function (args) {
  18256. // Optimization here; we already know the value and don't need to get
  18257. // it converted for us.
  18258. return convert$1.rgb.ansi16(convert$1.hsv.rgb(args), args[2]);
  18259. };
  18260. convert$1.rgb.ansi256 = function (args) {
  18261. const r = args[0];
  18262. const g = args[1];
  18263. const b = args[2];
  18264. // We use the extended greyscale palette here, with the exception of
  18265. // black and white. normal palette only has 4 greyscale shades.
  18266. if (r === g && g === b) {
  18267. if (r < 8) {
  18268. return 16;
  18269. }
  18270. if (r > 248) {
  18271. return 231;
  18272. }
  18273. return Math.round(((r - 8) / 247) * 24) + 232;
  18274. }
  18275. const ansi = 16
  18276. + (36 * Math.round(r / 255 * 5))
  18277. + (6 * Math.round(g / 255 * 5))
  18278. + Math.round(b / 255 * 5);
  18279. return ansi;
  18280. };
  18281. convert$1.ansi16.rgb = function (args) {
  18282. let color = args % 10;
  18283. // Handle greyscale
  18284. if (color === 0 || color === 7) {
  18285. if (args > 50) {
  18286. color += 3.5;
  18287. }
  18288. color = color / 10.5 * 255;
  18289. return [color, color, color];
  18290. }
  18291. const mult = (~~(args > 50) + 1) * 0.5;
  18292. const r = ((color & 1) * mult) * 255;
  18293. const g = (((color >> 1) & 1) * mult) * 255;
  18294. const b = (((color >> 2) & 1) * mult) * 255;
  18295. return [r, g, b];
  18296. };
  18297. convert$1.ansi256.rgb = function (args) {
  18298. // Handle greyscale
  18299. if (args >= 232) {
  18300. const c = (args - 232) * 10 + 8;
  18301. return [c, c, c];
  18302. }
  18303. args -= 16;
  18304. let rem;
  18305. const r = Math.floor(args / 36) / 5 * 255;
  18306. const g = Math.floor((rem = args % 36) / 6) / 5 * 255;
  18307. const b = (rem % 6) / 5 * 255;
  18308. return [r, g, b];
  18309. };
  18310. convert$1.rgb.hex = function (args) {
  18311. const integer = ((Math.round(args[0]) & 0xFF) << 16)
  18312. + ((Math.round(args[1]) & 0xFF) << 8)
  18313. + (Math.round(args[2]) & 0xFF);
  18314. const string = integer.toString(16).toUpperCase();
  18315. return '000000'.substring(string.length) + string;
  18316. };
  18317. convert$1.hex.rgb = function (args) {
  18318. const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
  18319. if (!match) {
  18320. return [0, 0, 0];
  18321. }
  18322. let colorString = match[0];
  18323. if (match[0].length === 3) {
  18324. colorString = colorString.split('').map(char => {
  18325. return char + char;
  18326. }).join('');
  18327. }
  18328. const integer = parseInt(colorString, 16);
  18329. const r = (integer >> 16) & 0xFF;
  18330. const g = (integer >> 8) & 0xFF;
  18331. const b = integer & 0xFF;
  18332. return [r, g, b];
  18333. };
  18334. convert$1.rgb.hcg = function (rgb) {
  18335. const r = rgb[0] / 255;
  18336. const g = rgb[1] / 255;
  18337. const b = rgb[2] / 255;
  18338. const max = Math.max(Math.max(r, g), b);
  18339. const min = Math.min(Math.min(r, g), b);
  18340. const chroma = (max - min);
  18341. let grayscale;
  18342. let hue;
  18343. if (chroma < 1) {
  18344. grayscale = min / (1 - chroma);
  18345. } else {
  18346. grayscale = 0;
  18347. }
  18348. if (chroma <= 0) {
  18349. hue = 0;
  18350. } else
  18351. if (max === r) {
  18352. hue = ((g - b) / chroma) % 6;
  18353. } else
  18354. if (max === g) {
  18355. hue = 2 + (b - r) / chroma;
  18356. } else {
  18357. hue = 4 + (r - g) / chroma;
  18358. }
  18359. hue /= 6;
  18360. hue %= 1;
  18361. return [hue * 360, chroma * 100, grayscale * 100];
  18362. };
  18363. convert$1.hsl.hcg = function (hsl) {
  18364. const s = hsl[1] / 100;
  18365. const l = hsl[2] / 100;
  18366. const c = l < 0.5 ? (2.0 * s * l) : (2.0 * s * (1.0 - l));
  18367. let f = 0;
  18368. if (c < 1.0) {
  18369. f = (l - 0.5 * c) / (1.0 - c);
  18370. }
  18371. return [hsl[0], c * 100, f * 100];
  18372. };
  18373. convert$1.hsv.hcg = function (hsv) {
  18374. const s = hsv[1] / 100;
  18375. const v = hsv[2] / 100;
  18376. const c = s * v;
  18377. let f = 0;
  18378. if (c < 1.0) {
  18379. f = (v - c) / (1 - c);
  18380. }
  18381. return [hsv[0], c * 100, f * 100];
  18382. };
  18383. convert$1.hcg.rgb = function (hcg) {
  18384. const h = hcg[0] / 360;
  18385. const c = hcg[1] / 100;
  18386. const g = hcg[2] / 100;
  18387. if (c === 0.0) {
  18388. return [g * 255, g * 255, g * 255];
  18389. }
  18390. const pure = [0, 0, 0];
  18391. const hi = (h % 1) * 6;
  18392. const v = hi % 1;
  18393. const w = 1 - v;
  18394. let mg = 0;
  18395. /* eslint-disable max-statements-per-line */
  18396. switch (Math.floor(hi)) {
  18397. case 0:
  18398. pure[0] = 1; pure[1] = v; pure[2] = 0; break;
  18399. case 1:
  18400. pure[0] = w; pure[1] = 1; pure[2] = 0; break;
  18401. case 2:
  18402. pure[0] = 0; pure[1] = 1; pure[2] = v; break;
  18403. case 3:
  18404. pure[0] = 0; pure[1] = w; pure[2] = 1; break;
  18405. case 4:
  18406. pure[0] = v; pure[1] = 0; pure[2] = 1; break;
  18407. default:
  18408. pure[0] = 1; pure[1] = 0; pure[2] = w;
  18409. }
  18410. /* eslint-enable max-statements-per-line */
  18411. mg = (1.0 - c) * g;
  18412. return [
  18413. (c * pure[0] + mg) * 255,
  18414. (c * pure[1] + mg) * 255,
  18415. (c * pure[2] + mg) * 255
  18416. ];
  18417. };
  18418. convert$1.hcg.hsv = function (hcg) {
  18419. const c = hcg[1] / 100;
  18420. const g = hcg[2] / 100;
  18421. const v = c + g * (1.0 - c);
  18422. let f = 0;
  18423. if (v > 0.0) {
  18424. f = c / v;
  18425. }
  18426. return [hcg[0], f * 100, v * 100];
  18427. };
  18428. convert$1.hcg.hsl = function (hcg) {
  18429. const c = hcg[1] / 100;
  18430. const g = hcg[2] / 100;
  18431. const l = g * (1.0 - c) + 0.5 * c;
  18432. let s = 0;
  18433. if (l > 0.0 && l < 0.5) {
  18434. s = c / (2 * l);
  18435. } else
  18436. if (l >= 0.5 && l < 1.0) {
  18437. s = c / (2 * (1 - l));
  18438. }
  18439. return [hcg[0], s * 100, l * 100];
  18440. };
  18441. convert$1.hcg.hwb = function (hcg) {
  18442. const c = hcg[1] / 100;
  18443. const g = hcg[2] / 100;
  18444. const v = c + g * (1.0 - c);
  18445. return [hcg[0], (v - c) * 100, (1 - v) * 100];
  18446. };
  18447. convert$1.hwb.hcg = function (hwb) {
  18448. const w = hwb[1] / 100;
  18449. const b = hwb[2] / 100;
  18450. const v = 1 - b;
  18451. const c = v - w;
  18452. let g = 0;
  18453. if (c < 1) {
  18454. g = (v - c) / (1 - c);
  18455. }
  18456. return [hwb[0], c * 100, g * 100];
  18457. };
  18458. convert$1.apple.rgb = function (apple) {
  18459. return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255];
  18460. };
  18461. convert$1.rgb.apple = function (rgb) {
  18462. return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535];
  18463. };
  18464. convert$1.gray.rgb = function (args) {
  18465. return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
  18466. };
  18467. convert$1.gray.hsl = function (args) {
  18468. return [0, 0, args[0]];
  18469. };
  18470. convert$1.gray.hsv = convert$1.gray.hsl;
  18471. convert$1.gray.hwb = function (gray) {
  18472. return [0, 100, gray[0]];
  18473. };
  18474. convert$1.gray.cmyk = function (gray) {
  18475. return [0, 0, 0, gray[0]];
  18476. };
  18477. convert$1.gray.lab = function (gray) {
  18478. return [gray[0], 0, 0];
  18479. };
  18480. convert$1.gray.hex = function (gray) {
  18481. const val = Math.round(gray[0] / 100 * 255) & 0xFF;
  18482. const integer = (val << 16) + (val << 8) + val;
  18483. const string = integer.toString(16).toUpperCase();
  18484. return '000000'.substring(string.length) + string;
  18485. };
  18486. convert$1.rgb.gray = function (rgb) {
  18487. const val = (rgb[0] + rgb[1] + rgb[2]) / 3;
  18488. return [val / 255 * 100];
  18489. };
  18490. /*
  18491. This function routes a model to all other models.
  18492. all functions that are routed have a property `.conversion` attached
  18493. to the returned synthetic function. This property is an array
  18494. of strings, each with the steps in between the 'from' and 'to'
  18495. color models (inclusive).
  18496. conversions that are not possible simply are not included.
  18497. */
  18498. function buildGraph() {
  18499. const graph = {};
  18500. // https://jsperf.com/object-keys-vs-for-in-with-closure/3
  18501. const models = Object.keys(conversions);
  18502. for (let len = models.length, i = 0; i < len; i++) {
  18503. graph[models[i]] = {
  18504. // http://jsperf.com/1-vs-infinity
  18505. // micro-opt, but this is simple.
  18506. distance: -1,
  18507. parent: null
  18508. };
  18509. }
  18510. return graph;
  18511. }
  18512. // https://en.wikipedia.org/wiki/Breadth-first_search
  18513. function deriveBFS(fromModel) {
  18514. const graph = buildGraph();
  18515. const queue = [fromModel]; // Unshift -> queue -> pop
  18516. graph[fromModel].distance = 0;
  18517. while (queue.length) {
  18518. const current = queue.pop();
  18519. const adjacents = Object.keys(conversions[current]);
  18520. for (let len = adjacents.length, i = 0; i < len; i++) {
  18521. const adjacent = adjacents[i];
  18522. const node = graph[adjacent];
  18523. if (node.distance === -1) {
  18524. node.distance = graph[current].distance + 1;
  18525. node.parent = current;
  18526. queue.unshift(adjacent);
  18527. }
  18528. }
  18529. }
  18530. return graph;
  18531. }
  18532. function link(from, to) {
  18533. return function (args) {
  18534. return to(from(args));
  18535. };
  18536. }
  18537. function wrapConversion(toModel, graph) {
  18538. const path = [graph[toModel].parent, toModel];
  18539. let fn = conversions[graph[toModel].parent][toModel];
  18540. let cur = graph[toModel].parent;
  18541. while (graph[cur].parent) {
  18542. path.unshift(graph[cur].parent);
  18543. fn = link(conversions[graph[cur].parent][cur], fn);
  18544. cur = graph[cur].parent;
  18545. }
  18546. fn.conversion = path;
  18547. return fn;
  18548. }
  18549. var route = function (fromModel) {
  18550. const graph = deriveBFS(fromModel);
  18551. const conversion = {};
  18552. const models = Object.keys(graph);
  18553. for (let len = models.length, i = 0; i < len; i++) {
  18554. const toModel = models[i];
  18555. const node = graph[toModel];
  18556. if (node.parent === null) {
  18557. // No possible conversion, or this node is the source model.
  18558. continue;
  18559. }
  18560. conversion[toModel] = wrapConversion(toModel, graph);
  18561. }
  18562. return conversion;
  18563. };
  18564. const convert = {};
  18565. const models = Object.keys(conversions);
  18566. function wrapRaw(fn) {
  18567. const wrappedFn = function (...args) {
  18568. const arg0 = args[0];
  18569. if (arg0 === undefined || arg0 === null) {
  18570. return arg0;
  18571. }
  18572. if (arg0.length > 1) {
  18573. args = arg0;
  18574. }
  18575. return fn(args);
  18576. };
  18577. // Preserve .conversion property if there is one
  18578. if ('conversion' in fn) {
  18579. wrappedFn.conversion = fn.conversion;
  18580. }
  18581. return wrappedFn;
  18582. }
  18583. function wrapRounded(fn) {
  18584. const wrappedFn = function (...args) {
  18585. const arg0 = args[0];
  18586. if (arg0 === undefined || arg0 === null) {
  18587. return arg0;
  18588. }
  18589. if (arg0.length > 1) {
  18590. args = arg0;
  18591. }
  18592. const result = fn(args);
  18593. // We're assuming the result is an array here.
  18594. // see notice in conversions.js; don't use box types
  18595. // in conversion functions.
  18596. if (typeof result === 'object') {
  18597. for (let len = result.length, i = 0; i < len; i++) {
  18598. result[i] = Math.round(result[i]);
  18599. }
  18600. }
  18601. return result;
  18602. };
  18603. // Preserve .conversion property if there is one
  18604. if ('conversion' in fn) {
  18605. wrappedFn.conversion = fn.conversion;
  18606. }
  18607. return wrappedFn;
  18608. }
  18609. models.forEach(fromModel => {
  18610. convert[fromModel] = {};
  18611. Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels});
  18612. Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels});
  18613. const routes = route(fromModel);
  18614. const routeModels = Object.keys(routes);
  18615. routeModels.forEach(toModel => {
  18616. const fn = routes[toModel];
  18617. convert[fromModel][toModel] = wrapRounded(fn);
  18618. convert[fromModel][toModel].raw = wrapRaw(fn);
  18619. });
  18620. });
  18621. var colorConvert = convert;
  18622. var ansiStyles = createCommonjsModule(function (module) {
  18623. const wrapAnsi16 = (fn, offset) => (...args) => {
  18624. const code = fn(...args);
  18625. return `\u001B[${code + offset}m`;
  18626. };
  18627. const wrapAnsi256 = (fn, offset) => (...args) => {
  18628. const code = fn(...args);
  18629. return `\u001B[${38 + offset};5;${code}m`;
  18630. };
  18631. const wrapAnsi16m = (fn, offset) => (...args) => {
  18632. const rgb = fn(...args);
  18633. return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
  18634. };
  18635. const ansi2ansi = n => n;
  18636. const rgb2rgb = (r, g, b) => [r, g, b];
  18637. const setLazyProperty = (object, property, get) => {
  18638. Object.defineProperty(object, property, {
  18639. get: () => {
  18640. const value = get();
  18641. Object.defineProperty(object, property, {
  18642. value,
  18643. enumerable: true,
  18644. configurable: true
  18645. });
  18646. return value;
  18647. },
  18648. enumerable: true,
  18649. configurable: true
  18650. });
  18651. };
  18652. /** @type {typeof import('color-convert')} */
  18653. let colorConvert$1;
  18654. const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => {
  18655. if (colorConvert$1 === undefined) {
  18656. colorConvert$1 = colorConvert;
  18657. }
  18658. const offset = isBackground ? 10 : 0;
  18659. const styles = {};
  18660. for (const [sourceSpace, suite] of Object.entries(colorConvert$1)) {
  18661. const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace;
  18662. if (sourceSpace === targetSpace) {
  18663. styles[name] = wrap(identity, offset);
  18664. } else if (typeof suite === 'object') {
  18665. styles[name] = wrap(suite[targetSpace], offset);
  18666. }
  18667. }
  18668. return styles;
  18669. };
  18670. function assembleStyles() {
  18671. const codes = new Map();
  18672. const styles = {
  18673. modifier: {
  18674. reset: [0, 0],
  18675. // 21 isn't widely supported and 22 does the same thing
  18676. bold: [1, 22],
  18677. dim: [2, 22],
  18678. italic: [3, 23],
  18679. underline: [4, 24],
  18680. inverse: [7, 27],
  18681. hidden: [8, 28],
  18682. strikethrough: [9, 29]
  18683. },
  18684. color: {
  18685. black: [30, 39],
  18686. red: [31, 39],
  18687. green: [32, 39],
  18688. yellow: [33, 39],
  18689. blue: [34, 39],
  18690. magenta: [35, 39],
  18691. cyan: [36, 39],
  18692. white: [37, 39],
  18693. // Bright color
  18694. blackBright: [90, 39],
  18695. redBright: [91, 39],
  18696. greenBright: [92, 39],
  18697. yellowBright: [93, 39],
  18698. blueBright: [94, 39],
  18699. magentaBright: [95, 39],
  18700. cyanBright: [96, 39],
  18701. whiteBright: [97, 39]
  18702. },
  18703. bgColor: {
  18704. bgBlack: [40, 49],
  18705. bgRed: [41, 49],
  18706. bgGreen: [42, 49],
  18707. bgYellow: [43, 49],
  18708. bgBlue: [44, 49],
  18709. bgMagenta: [45, 49],
  18710. bgCyan: [46, 49],
  18711. bgWhite: [47, 49],
  18712. // Bright color
  18713. bgBlackBright: [100, 49],
  18714. bgRedBright: [101, 49],
  18715. bgGreenBright: [102, 49],
  18716. bgYellowBright: [103, 49],
  18717. bgBlueBright: [104, 49],
  18718. bgMagentaBright: [105, 49],
  18719. bgCyanBright: [106, 49],
  18720. bgWhiteBright: [107, 49]
  18721. }
  18722. };
  18723. // Alias bright black as gray (and grey)
  18724. styles.color.gray = styles.color.blackBright;
  18725. styles.bgColor.bgGray = styles.bgColor.bgBlackBright;
  18726. styles.color.grey = styles.color.blackBright;
  18727. styles.bgColor.bgGrey = styles.bgColor.bgBlackBright;
  18728. for (const [groupName, group] of Object.entries(styles)) {
  18729. for (const [styleName, style] of Object.entries(group)) {
  18730. styles[styleName] = {
  18731. open: `\u001B[${style[0]}m`,
  18732. close: `\u001B[${style[1]}m`
  18733. };
  18734. group[styleName] = styles[styleName];
  18735. codes.set(style[0], style[1]);
  18736. }
  18737. Object.defineProperty(styles, groupName, {
  18738. value: group,
  18739. enumerable: false
  18740. });
  18741. }
  18742. Object.defineProperty(styles, 'codes', {
  18743. value: codes,
  18744. enumerable: false
  18745. });
  18746. styles.color.close = '\u001B[39m';
  18747. styles.bgColor.close = '\u001B[49m';
  18748. setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false));
  18749. setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false));
  18750. setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false));
  18751. setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true));
  18752. setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true));
  18753. setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true));
  18754. return styles;
  18755. }
  18756. // Make the export immutable
  18757. Object.defineProperty(module, 'exports', {
  18758. enumerable: true,
  18759. get: assembleStyles
  18760. });
  18761. }, "/$$rollup_base$$/node_modules/ansi-styles");
  18762. var hasFlag = (flag, argv = process.argv) => {
  18763. const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');
  18764. const position = argv.indexOf(prefix + flag);
  18765. const terminatorPosition = argv.indexOf('--');
  18766. return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
  18767. };
  18768. const {env: env$1} = process;
  18769. let forceColor;
  18770. if (hasFlag('no-color') ||
  18771. hasFlag('no-colors') ||
  18772. hasFlag('color=false') ||
  18773. hasFlag('color=never')) {
  18774. forceColor = 0;
  18775. } else if (hasFlag('color') ||
  18776. hasFlag('colors') ||
  18777. hasFlag('color=true') ||
  18778. hasFlag('color=always')) {
  18779. forceColor = 1;
  18780. }
  18781. if ('FORCE_COLOR' in env$1) {
  18782. if (env$1.FORCE_COLOR === 'true') {
  18783. forceColor = 1;
  18784. } else if (env$1.FORCE_COLOR === 'false') {
  18785. forceColor = 0;
  18786. } else {
  18787. forceColor = env$1.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env$1.FORCE_COLOR, 10), 3);
  18788. }
  18789. }
  18790. function translateLevel(level) {
  18791. if (level === 0) {
  18792. return false;
  18793. }
  18794. return {
  18795. level,
  18796. hasBasic: true,
  18797. has256: level >= 2,
  18798. has16m: level >= 3
  18799. };
  18800. }
  18801. function supportsColor(haveStream, streamIsTTY) {
  18802. if (forceColor === 0) {
  18803. return 0;
  18804. }
  18805. if (hasFlag('color=16m') ||
  18806. hasFlag('color=full') ||
  18807. hasFlag('color=truecolor')) {
  18808. return 3;
  18809. }
  18810. if (hasFlag('color=256')) {
  18811. return 2;
  18812. }
  18813. if (haveStream && !streamIsTTY && forceColor === undefined) {
  18814. return 0;
  18815. }
  18816. const min = forceColor || 0;
  18817. if (env$1.TERM === 'dumb') {
  18818. return min;
  18819. }
  18820. if (process.platform === 'win32') {
  18821. // Windows 10 build 10586 is the first Windows release that supports 256 colors.
  18822. // Windows 10 build 14931 is the first release that supports 16m/TrueColor.
  18823. const osRelease = os__default['default'].release().split('.');
  18824. if (
  18825. Number(osRelease[0]) >= 10 &&
  18826. Number(osRelease[2]) >= 10586
  18827. ) {
  18828. return Number(osRelease[2]) >= 14931 ? 3 : 2;
  18829. }
  18830. return 1;
  18831. }
  18832. if ('CI' in env$1) {
  18833. if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env$1) || env$1.CI_NAME === 'codeship') {
  18834. return 1;
  18835. }
  18836. return min;
  18837. }
  18838. if ('TEAMCITY_VERSION' in env$1) {
  18839. return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$1.TEAMCITY_VERSION) ? 1 : 0;
  18840. }
  18841. if (env$1.COLORTERM === 'truecolor') {
  18842. return 3;
  18843. }
  18844. if ('TERM_PROGRAM' in env$1) {
  18845. const version = parseInt((env$1.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
  18846. switch (env$1.TERM_PROGRAM) {
  18847. case 'iTerm.app':
  18848. return version >= 3 ? 3 : 2;
  18849. case 'Apple_Terminal':
  18850. return 2;
  18851. // No default
  18852. }
  18853. }
  18854. if (/-256(color)?$/i.test(env$1.TERM)) {
  18855. return 2;
  18856. }
  18857. if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$1.TERM)) {
  18858. return 1;
  18859. }
  18860. if ('COLORTERM' in env$1) {
  18861. return 1;
  18862. }
  18863. return min;
  18864. }
  18865. function getSupportLevel(stream) {
  18866. const level = supportsColor(stream, stream && stream.isTTY);
  18867. return translateLevel(level);
  18868. }
  18869. var supportsColor_1 = {
  18870. supportsColor: getSupportLevel,
  18871. stdout: translateLevel(supportsColor(true, tty__default['default'].isatty(1))),
  18872. stderr: translateLevel(supportsColor(true, tty__default['default'].isatty(2)))
  18873. };
  18874. const stringReplaceAll$1 = (string, substring, replacer) => {
  18875. let index = string.indexOf(substring);
  18876. if (index === -1) {
  18877. return string;
  18878. }
  18879. const substringLength = substring.length;
  18880. let endIndex = 0;
  18881. let returnValue = '';
  18882. do {
  18883. returnValue += string.substr(endIndex, index - endIndex) + substring + replacer;
  18884. endIndex = index + substringLength;
  18885. index = string.indexOf(substring, endIndex);
  18886. } while (index !== -1);
  18887. returnValue += string.substr(endIndex);
  18888. return returnValue;
  18889. };
  18890. const stringEncaseCRLFWithFirstIndex$1 = (string, prefix, postfix, index) => {
  18891. let endIndex = 0;
  18892. let returnValue = '';
  18893. do {
  18894. const gotCR = string[index - 1] === '\r';
  18895. returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix;
  18896. endIndex = index + 1;
  18897. index = string.indexOf('\n', endIndex);
  18898. } while (index !== -1);
  18899. returnValue += string.substr(endIndex);
  18900. return returnValue;
  18901. };
  18902. var util = {
  18903. stringReplaceAll: stringReplaceAll$1,
  18904. stringEncaseCRLFWithFirstIndex: stringEncaseCRLFWithFirstIndex$1
  18905. };
  18906. 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;
  18907. const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
  18908. const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
  18909. const ESCAPE_REGEX = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi;
  18910. const ESCAPES = new Map([
  18911. ['n', '\n'],
  18912. ['r', '\r'],
  18913. ['t', '\t'],
  18914. ['b', '\b'],
  18915. ['f', '\f'],
  18916. ['v', '\v'],
  18917. ['0', '\0'],
  18918. ['\\', '\\'],
  18919. ['e', '\u001B'],
  18920. ['a', '\u0007']
  18921. ]);
  18922. function unescape$1(c) {
  18923. const u = c[0] === 'u';
  18924. const bracket = c[1] === '{';
  18925. if ((u && !bracket && c.length === 5) || (c[0] === 'x' && c.length === 3)) {
  18926. return String.fromCharCode(parseInt(c.slice(1), 16));
  18927. }
  18928. if (u && bracket) {
  18929. return String.fromCodePoint(parseInt(c.slice(2, -1), 16));
  18930. }
  18931. return ESCAPES.get(c) || c;
  18932. }
  18933. function parseArguments(name, arguments_) {
  18934. const results = [];
  18935. const chunks = arguments_.trim().split(/\s*,\s*/g);
  18936. let matches;
  18937. for (const chunk of chunks) {
  18938. const number = Number(chunk);
  18939. if (!Number.isNaN(number)) {
  18940. results.push(number);
  18941. } else if ((matches = chunk.match(STRING_REGEX))) {
  18942. results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, character) => escape ? unescape$1(escape) : character));
  18943. } else {
  18944. throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
  18945. }
  18946. }
  18947. return results;
  18948. }
  18949. function parseStyle(style) {
  18950. STYLE_REGEX.lastIndex = 0;
  18951. const results = [];
  18952. let matches;
  18953. while ((matches = STYLE_REGEX.exec(style)) !== null) {
  18954. const name = matches[1];
  18955. if (matches[2]) {
  18956. const args = parseArguments(name, matches[2]);
  18957. results.push([name].concat(args));
  18958. } else {
  18959. results.push([name]);
  18960. }
  18961. }
  18962. return results;
  18963. }
  18964. function buildStyle(chalk, styles) {
  18965. const enabled = {};
  18966. for (const layer of styles) {
  18967. for (const style of layer.styles) {
  18968. enabled[style[0]] = layer.inverse ? null : style.slice(1);
  18969. }
  18970. }
  18971. let current = chalk;
  18972. for (const [styleName, styles] of Object.entries(enabled)) {
  18973. if (!Array.isArray(styles)) {
  18974. continue;
  18975. }
  18976. if (!(styleName in current)) {
  18977. throw new Error(`Unknown Chalk style: ${styleName}`);
  18978. }
  18979. current = styles.length > 0 ? current[styleName](...styles) : current[styleName];
  18980. }
  18981. return current;
  18982. }
  18983. var templates = (chalk, temporary) => {
  18984. const styles = [];
  18985. const chunks = [];
  18986. let chunk = [];
  18987. // eslint-disable-next-line max-params
  18988. temporary.replace(TEMPLATE_REGEX, (m, escapeCharacter, inverse, style, close, character) => {
  18989. if (escapeCharacter) {
  18990. chunk.push(unescape$1(escapeCharacter));
  18991. } else if (style) {
  18992. const string = chunk.join('');
  18993. chunk = [];
  18994. chunks.push(styles.length === 0 ? string : buildStyle(chalk, styles)(string));
  18995. styles.push({inverse, styles: parseStyle(style)});
  18996. } else if (close) {
  18997. if (styles.length === 0) {
  18998. throw new Error('Found extraneous } in Chalk template literal');
  18999. }
  19000. chunks.push(buildStyle(chalk, styles)(chunk.join('')));
  19001. chunk = [];
  19002. styles.pop();
  19003. } else {
  19004. chunk.push(character);
  19005. }
  19006. });
  19007. chunks.push(chunk.join(''));
  19008. if (styles.length > 0) {
  19009. const errMessage = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
  19010. throw new Error(errMessage);
  19011. }
  19012. return chunks.join('');
  19013. };
  19014. const {stdout: stdoutColor, stderr: stderrColor} = supportsColor_1;
  19015. const {
  19016. stringReplaceAll,
  19017. stringEncaseCRLFWithFirstIndex
  19018. } = util;
  19019. const {isArray: isArray$2} = Array;
  19020. // `supportsColor.level` → `ansiStyles.color[name]` mapping
  19021. const levelMapping = [
  19022. 'ansi',
  19023. 'ansi',
  19024. 'ansi256',
  19025. 'ansi16m'
  19026. ];
  19027. const styles = Object.create(null);
  19028. const applyOptions = (object, options = {}) => {
  19029. if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
  19030. throw new Error('The `level` option should be an integer from 0 to 3');
  19031. }
  19032. // Detect level if not set manually
  19033. const colorLevel = stdoutColor ? stdoutColor.level : 0;
  19034. object.level = options.level === undefined ? colorLevel : options.level;
  19035. };
  19036. class ChalkClass {
  19037. constructor(options) {
  19038. // eslint-disable-next-line no-constructor-return
  19039. return chalkFactory(options);
  19040. }
  19041. }
  19042. const chalkFactory = options => {
  19043. const chalk = {};
  19044. applyOptions(chalk, options);
  19045. chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_);
  19046. Object.setPrototypeOf(chalk, Chalk.prototype);
  19047. Object.setPrototypeOf(chalk.template, chalk);
  19048. chalk.template.constructor = () => {
  19049. throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.');
  19050. };
  19051. chalk.template.Instance = ChalkClass;
  19052. return chalk.template;
  19053. };
  19054. function Chalk(options) {
  19055. return chalkFactory(options);
  19056. }
  19057. for (const [styleName, style] of Object.entries(ansiStyles)) {
  19058. styles[styleName] = {
  19059. get() {
  19060. const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty);
  19061. Object.defineProperty(this, styleName, {value: builder});
  19062. return builder;
  19063. }
  19064. };
  19065. }
  19066. styles.visible = {
  19067. get() {
  19068. const builder = createBuilder(this, this._styler, true);
  19069. Object.defineProperty(this, 'visible', {value: builder});
  19070. return builder;
  19071. }
  19072. };
  19073. const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256'];
  19074. for (const model of usedModels) {
  19075. styles[model] = {
  19076. get() {
  19077. const {level} = this;
  19078. return function (...arguments_) {
  19079. const styler = createStyler(ansiStyles.color[levelMapping[level]][model](...arguments_), ansiStyles.color.close, this._styler);
  19080. return createBuilder(this, styler, this._isEmpty);
  19081. };
  19082. }
  19083. };
  19084. }
  19085. for (const model of usedModels) {
  19086. const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
  19087. styles[bgModel] = {
  19088. get() {
  19089. const {level} = this;
  19090. return function (...arguments_) {
  19091. const styler = createStyler(ansiStyles.bgColor[levelMapping[level]][model](...arguments_), ansiStyles.bgColor.close, this._styler);
  19092. return createBuilder(this, styler, this._isEmpty);
  19093. };
  19094. }
  19095. };
  19096. }
  19097. const proto = Object.defineProperties(() => {}, {
  19098. ...styles,
  19099. level: {
  19100. enumerable: true,
  19101. get() {
  19102. return this._generator.level;
  19103. },
  19104. set(level) {
  19105. this._generator.level = level;
  19106. }
  19107. }
  19108. });
  19109. const createStyler = (open, close, parent) => {
  19110. let openAll;
  19111. let closeAll;
  19112. if (parent === undefined) {
  19113. openAll = open;
  19114. closeAll = close;
  19115. } else {
  19116. openAll = parent.openAll + open;
  19117. closeAll = close + parent.closeAll;
  19118. }
  19119. return {
  19120. open,
  19121. close,
  19122. openAll,
  19123. closeAll,
  19124. parent
  19125. };
  19126. };
  19127. const createBuilder = (self, _styler, _isEmpty) => {
  19128. const builder = (...arguments_) => {
  19129. if (isArray$2(arguments_[0]) && isArray$2(arguments_[0].raw)) {
  19130. // Called as a template literal, for example: chalk.red`2 + 3 = {bold ${2+3}}`
  19131. return applyStyle(builder, chalkTag(builder, ...arguments_));
  19132. }
  19133. // Single argument is hot path, implicit coercion is faster than anything
  19134. // eslint-disable-next-line no-implicit-coercion
  19135. return applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' '));
  19136. };
  19137. // We alter the prototype because we must return a function, but there is
  19138. // no way to create a function with a different prototype
  19139. Object.setPrototypeOf(builder, proto);
  19140. builder._generator = self;
  19141. builder._styler = _styler;
  19142. builder._isEmpty = _isEmpty;
  19143. return builder;
  19144. };
  19145. const applyStyle = (self, string) => {
  19146. if (self.level <= 0 || !string) {
  19147. return self._isEmpty ? '' : string;
  19148. }
  19149. let styler = self._styler;
  19150. if (styler === undefined) {
  19151. return string;
  19152. }
  19153. const {openAll, closeAll} = styler;
  19154. if (string.indexOf('\u001B') !== -1) {
  19155. while (styler !== undefined) {
  19156. // Replace any instances already present with a re-opening code
  19157. // otherwise only the part of the string until said closing code
  19158. // will be colored, and the rest will simply be 'plain'.
  19159. string = stringReplaceAll(string, styler.close, styler.open);
  19160. styler = styler.parent;
  19161. }
  19162. }
  19163. // We can move both next actions out of loop, because remaining actions in loop won't have
  19164. // any/visible effect on parts we add here. Close the styling before a linebreak and reopen
  19165. // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92
  19166. const lfIndex = string.indexOf('\n');
  19167. if (lfIndex !== -1) {
  19168. string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
  19169. }
  19170. return openAll + string + closeAll;
  19171. };
  19172. let template;
  19173. const chalkTag = (chalk, ...strings) => {
  19174. const [firstString] = strings;
  19175. if (!isArray$2(firstString) || !isArray$2(firstString.raw)) {
  19176. // If chalk() was called by itself or with a string,
  19177. // return the string itself as a string.
  19178. return strings.join(' ');
  19179. }
  19180. const arguments_ = strings.slice(1);
  19181. const parts = [firstString.raw[0]];
  19182. for (let i = 1; i < firstString.length; i++) {
  19183. parts.push(
  19184. String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'),
  19185. String(firstString.raw[i])
  19186. );
  19187. }
  19188. if (template === undefined) {
  19189. template = templates;
  19190. }
  19191. return template(chalk, parts.join(''));
  19192. };
  19193. Object.defineProperties(Chalk.prototype, styles);
  19194. const chalk = Chalk(); // eslint-disable-line new-cap
  19195. chalk.supportsColor = stdoutColor;
  19196. chalk.stderr = Chalk({level: stderrColor ? stderrColor.level : 0}); // eslint-disable-line new-cap
  19197. chalk.stderr.supportsColor = stderrColor;
  19198. var source = chalk;
  19199. // Copyright Joyent, Inc. and other Node contributors.
  19200. //
  19201. // Permission is hereby granted, free of charge, to any person obtaining a
  19202. // copy of this software and associated documentation files (the
  19203. // "Software"), to deal in the Software without restriction, including
  19204. // without limitation the rights to use, copy, modify, merge, publish,
  19205. // distribute, sublicense, and/or sell copies of the Software, and to permit
  19206. // persons to whom the Software is furnished to do so, subject to the
  19207. // following conditions:
  19208. //
  19209. // The above copyright notice and this permission notice shall be included
  19210. // in all copies or substantial portions of the Software.
  19211. //
  19212. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  19213. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  19214. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  19215. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  19216. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  19217. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  19218. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  19219. var isWindows = process.platform === 'win32';
  19220. // JavaScript implementation of realpath, ported from node pre-v6
  19221. var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG);
  19222. function rethrow() {
  19223. // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and
  19224. // is fairly slow to generate.
  19225. var callback;
  19226. if (DEBUG) {
  19227. var backtrace = new Error;
  19228. callback = debugCallback;
  19229. } else
  19230. callback = missingCallback;
  19231. return callback;
  19232. function debugCallback(err) {
  19233. if (err) {
  19234. backtrace.message = err.message;
  19235. err = backtrace;
  19236. missingCallback(err);
  19237. }
  19238. }
  19239. function missingCallback(err) {
  19240. if (err) {
  19241. if (process.throwDeprecation)
  19242. throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs
  19243. else if (!process.noDeprecation) {
  19244. var msg = 'fs: missing callback ' + (err.stack || err.message);
  19245. if (process.traceDeprecation)
  19246. console.trace(msg);
  19247. else
  19248. console.error(msg);
  19249. }
  19250. }
  19251. }
  19252. }
  19253. function maybeCallback(cb) {
  19254. return typeof cb === 'function' ? cb : rethrow();
  19255. }
  19256. path__default['default'].normalize;
  19257. // Regexp that finds the next partion of a (partial) path
  19258. // result is [base_with_slash, base], e.g. ['somedir/', 'somedir']
  19259. if (isWindows) {
  19260. var nextPartRe = /(.*?)(?:[\/\\]+|$)/g;
  19261. } else {
  19262. var nextPartRe = /(.*?)(?:[\/]+|$)/g;
  19263. }
  19264. // Regex to find the device root, including trailing slash. E.g. 'c:\\'.
  19265. if (isWindows) {
  19266. var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/;
  19267. } else {
  19268. var splitRootRe = /^[\/]*/;
  19269. }
  19270. var realpathSync$1 = function realpathSync(p, cache) {
  19271. // make p is absolute
  19272. p = path__default['default'].resolve(p);
  19273. if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
  19274. return cache[p];
  19275. }
  19276. var original = p,
  19277. seenLinks = {},
  19278. knownHard = {};
  19279. // current character position in p
  19280. var pos;
  19281. // the partial path so far, including a trailing slash if any
  19282. var current;
  19283. // the partial path without a trailing slash (except when pointing at a root)
  19284. var base;
  19285. // the partial path scanned in the previous round, with slash
  19286. var previous;
  19287. start();
  19288. function start() {
  19289. // Skip over roots
  19290. var m = splitRootRe.exec(p);
  19291. pos = m[0].length;
  19292. current = m[0];
  19293. base = m[0];
  19294. previous = '';
  19295. // On windows, check that the root exists. On unix there is no need.
  19296. if (isWindows && !knownHard[base]) {
  19297. fs__default['default'].lstatSync(base);
  19298. knownHard[base] = true;
  19299. }
  19300. }
  19301. // walk down the path, swapping out linked pathparts for their real
  19302. // values
  19303. // NB: p.length changes.
  19304. while (pos < p.length) {
  19305. // find the next part
  19306. nextPartRe.lastIndex = pos;
  19307. var result = nextPartRe.exec(p);
  19308. previous = current;
  19309. current += result[0];
  19310. base = previous + result[1];
  19311. pos = nextPartRe.lastIndex;
  19312. // continue if not a symlink
  19313. if (knownHard[base] || (cache && cache[base] === base)) {
  19314. continue;
  19315. }
  19316. var resolvedLink;
  19317. if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
  19318. // some known symbolic link. no need to stat again.
  19319. resolvedLink = cache[base];
  19320. } else {
  19321. var stat = fs__default['default'].lstatSync(base);
  19322. if (!stat.isSymbolicLink()) {
  19323. knownHard[base] = true;
  19324. if (cache) cache[base] = base;
  19325. continue;
  19326. }
  19327. // read the link if it wasn't read before
  19328. // dev/ino always return 0 on windows, so skip the check.
  19329. var linkTarget = null;
  19330. if (!isWindows) {
  19331. var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
  19332. if (seenLinks.hasOwnProperty(id)) {
  19333. linkTarget = seenLinks[id];
  19334. }
  19335. }
  19336. if (linkTarget === null) {
  19337. fs__default['default'].statSync(base);
  19338. linkTarget = fs__default['default'].readlinkSync(base);
  19339. }
  19340. resolvedLink = path__default['default'].resolve(previous, linkTarget);
  19341. // track this, if given a cache.
  19342. if (cache) cache[base] = resolvedLink;
  19343. if (!isWindows) seenLinks[id] = linkTarget;
  19344. }
  19345. // resolve the link, then start over
  19346. p = path__default['default'].resolve(resolvedLink, p.slice(pos));
  19347. start();
  19348. }
  19349. if (cache) cache[original] = p;
  19350. return p;
  19351. };
  19352. var realpath$1 = function realpath(p, cache, cb) {
  19353. if (typeof cb !== 'function') {
  19354. cb = maybeCallback(cache);
  19355. cache = null;
  19356. }
  19357. // make p is absolute
  19358. p = path__default['default'].resolve(p);
  19359. if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
  19360. return process.nextTick(cb.bind(null, null, cache[p]));
  19361. }
  19362. var original = p,
  19363. seenLinks = {},
  19364. knownHard = {};
  19365. // current character position in p
  19366. var pos;
  19367. // the partial path so far, including a trailing slash if any
  19368. var current;
  19369. // the partial path without a trailing slash (except when pointing at a root)
  19370. var base;
  19371. // the partial path scanned in the previous round, with slash
  19372. var previous;
  19373. start();
  19374. function start() {
  19375. // Skip over roots
  19376. var m = splitRootRe.exec(p);
  19377. pos = m[0].length;
  19378. current = m[0];
  19379. base = m[0];
  19380. previous = '';
  19381. // On windows, check that the root exists. On unix there is no need.
  19382. if (isWindows && !knownHard[base]) {
  19383. fs__default['default'].lstat(base, function(err) {
  19384. if (err) return cb(err);
  19385. knownHard[base] = true;
  19386. LOOP();
  19387. });
  19388. } else {
  19389. process.nextTick(LOOP);
  19390. }
  19391. }
  19392. // walk down the path, swapping out linked pathparts for their real
  19393. // values
  19394. function LOOP() {
  19395. // stop if scanned past end of path
  19396. if (pos >= p.length) {
  19397. if (cache) cache[original] = p;
  19398. return cb(null, p);
  19399. }
  19400. // find the next part
  19401. nextPartRe.lastIndex = pos;
  19402. var result = nextPartRe.exec(p);
  19403. previous = current;
  19404. current += result[0];
  19405. base = previous + result[1];
  19406. pos = nextPartRe.lastIndex;
  19407. // continue if not a symlink
  19408. if (knownHard[base] || (cache && cache[base] === base)) {
  19409. return process.nextTick(LOOP);
  19410. }
  19411. if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
  19412. // known symbolic link. no need to stat again.
  19413. return gotResolvedLink(cache[base]);
  19414. }
  19415. return fs__default['default'].lstat(base, gotStat);
  19416. }
  19417. function gotStat(err, stat) {
  19418. if (err) return cb(err);
  19419. // if not a symlink, skip to the next path part
  19420. if (!stat.isSymbolicLink()) {
  19421. knownHard[base] = true;
  19422. if (cache) cache[base] = base;
  19423. return process.nextTick(LOOP);
  19424. }
  19425. // stat & read the link if not read before
  19426. // call gotTarget as soon as the link target is known
  19427. // dev/ino always return 0 on windows, so skip the check.
  19428. if (!isWindows) {
  19429. var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
  19430. if (seenLinks.hasOwnProperty(id)) {
  19431. return gotTarget(null, seenLinks[id], base);
  19432. }
  19433. }
  19434. fs__default['default'].stat(base, function(err) {
  19435. if (err) return cb(err);
  19436. fs__default['default'].readlink(base, function(err, target) {
  19437. if (!isWindows) seenLinks[id] = target;
  19438. gotTarget(err, target);
  19439. });
  19440. });
  19441. }
  19442. function gotTarget(err, target, base) {
  19443. if (err) return cb(err);
  19444. var resolvedLink = path__default['default'].resolve(previous, target);
  19445. if (cache) cache[base] = resolvedLink;
  19446. gotResolvedLink(resolvedLink);
  19447. }
  19448. function gotResolvedLink(resolvedLink) {
  19449. // resolve the link, then start over
  19450. p = path__default['default'].resolve(resolvedLink, p.slice(pos));
  19451. start();
  19452. }
  19453. };
  19454. var old = {
  19455. realpathSync: realpathSync$1,
  19456. realpath: realpath$1
  19457. };
  19458. var fs_realpath = realpath;
  19459. realpath.realpath = realpath;
  19460. realpath.sync = realpathSync;
  19461. realpath.realpathSync = realpathSync;
  19462. realpath.monkeypatch = monkeypatch;
  19463. realpath.unmonkeypatch = unmonkeypatch;
  19464. var origRealpath = fs__default['default'].realpath;
  19465. var origRealpathSync = fs__default['default'].realpathSync;
  19466. var version = process.version;
  19467. var ok = /^v[0-5]\./.test(version);
  19468. function newError (er) {
  19469. return er && er.syscall === 'realpath' && (
  19470. er.code === 'ELOOP' ||
  19471. er.code === 'ENOMEM' ||
  19472. er.code === 'ENAMETOOLONG'
  19473. )
  19474. }
  19475. function realpath (p, cache, cb) {
  19476. if (ok) {
  19477. return origRealpath(p, cache, cb)
  19478. }
  19479. if (typeof cache === 'function') {
  19480. cb = cache;
  19481. cache = null;
  19482. }
  19483. origRealpath(p, cache, function (er, result) {
  19484. if (newError(er)) {
  19485. old.realpath(p, cache, cb);
  19486. } else {
  19487. cb(er, result);
  19488. }
  19489. });
  19490. }
  19491. function realpathSync (p, cache) {
  19492. if (ok) {
  19493. return origRealpathSync(p, cache)
  19494. }
  19495. try {
  19496. return origRealpathSync(p, cache)
  19497. } catch (er) {
  19498. if (newError(er)) {
  19499. return old.realpathSync(p, cache)
  19500. } else {
  19501. throw er
  19502. }
  19503. }
  19504. }
  19505. function monkeypatch () {
  19506. fs__default['default'].realpath = realpath;
  19507. fs__default['default'].realpathSync = realpathSync;
  19508. }
  19509. function unmonkeypatch () {
  19510. fs__default['default'].realpath = origRealpath;
  19511. fs__default['default'].realpathSync = origRealpathSync;
  19512. }
  19513. var concatMap = function (xs, fn) {
  19514. var res = [];
  19515. for (var i = 0; i < xs.length; i++) {
  19516. var x = fn(xs[i], i);
  19517. if (isArray$1(x)) res.push.apply(res, x);
  19518. else res.push(x);
  19519. }
  19520. return res;
  19521. };
  19522. var isArray$1 = Array.isArray || function (xs) {
  19523. return Object.prototype.toString.call(xs) === '[object Array]';
  19524. };
  19525. var balancedMatch = balanced;
  19526. function balanced(a, b, str) {
  19527. if (a instanceof RegExp) a = maybeMatch(a, str);
  19528. if (b instanceof RegExp) b = maybeMatch(b, str);
  19529. var r = range(a, b, str);
  19530. return r && {
  19531. start: r[0],
  19532. end: r[1],
  19533. pre: str.slice(0, r[0]),
  19534. body: str.slice(r[0] + a.length, r[1]),
  19535. post: str.slice(r[1] + b.length)
  19536. };
  19537. }
  19538. function maybeMatch(reg, str) {
  19539. var m = str.match(reg);
  19540. return m ? m[0] : null;
  19541. }
  19542. balanced.range = range;
  19543. function range(a, b, str) {
  19544. var begs, beg, left, right, result;
  19545. var ai = str.indexOf(a);
  19546. var bi = str.indexOf(b, ai + 1);
  19547. var i = ai;
  19548. if (ai >= 0 && bi > 0) {
  19549. if(a===b) {
  19550. return [ai, bi];
  19551. }
  19552. begs = [];
  19553. left = str.length;
  19554. while (i >= 0 && !result) {
  19555. if (i == ai) {
  19556. begs.push(i);
  19557. ai = str.indexOf(a, i + 1);
  19558. } else if (begs.length == 1) {
  19559. result = [ begs.pop(), bi ];
  19560. } else {
  19561. beg = begs.pop();
  19562. if (beg < left) {
  19563. left = beg;
  19564. right = bi;
  19565. }
  19566. bi = str.indexOf(b, i + 1);
  19567. }
  19568. i = ai < bi && ai >= 0 ? ai : bi;
  19569. }
  19570. if (begs.length) {
  19571. result = [ left, right ];
  19572. }
  19573. }
  19574. return result;
  19575. }
  19576. var braceExpansion = expandTop;
  19577. var escSlash = '\0SLASH'+Math.random()+'\0';
  19578. var escOpen = '\0OPEN'+Math.random()+'\0';
  19579. var escClose = '\0CLOSE'+Math.random()+'\0';
  19580. var escComma = '\0COMMA'+Math.random()+'\0';
  19581. var escPeriod = '\0PERIOD'+Math.random()+'\0';
  19582. function numeric(str) {
  19583. return parseInt(str, 10) == str
  19584. ? parseInt(str, 10)
  19585. : str.charCodeAt(0);
  19586. }
  19587. function escapeBraces(str) {
  19588. return str.split('\\\\').join(escSlash)
  19589. .split('\\{').join(escOpen)
  19590. .split('\\}').join(escClose)
  19591. .split('\\,').join(escComma)
  19592. .split('\\.').join(escPeriod);
  19593. }
  19594. function unescapeBraces(str) {
  19595. return str.split(escSlash).join('\\')
  19596. .split(escOpen).join('{')
  19597. .split(escClose).join('}')
  19598. .split(escComma).join(',')
  19599. .split(escPeriod).join('.');
  19600. }
  19601. // Basically just str.split(","), but handling cases
  19602. // where we have nested braced sections, which should be
  19603. // treated as individual members, like {a,{b,c},d}
  19604. function parseCommaParts(str) {
  19605. if (!str)
  19606. return [''];
  19607. var parts = [];
  19608. var m = balancedMatch('{', '}', str);
  19609. if (!m)
  19610. return str.split(',');
  19611. var pre = m.pre;
  19612. var body = m.body;
  19613. var post = m.post;
  19614. var p = pre.split(',');
  19615. p[p.length-1] += '{' + body + '}';
  19616. var postParts = parseCommaParts(post);
  19617. if (post.length) {
  19618. p[p.length-1] += postParts.shift();
  19619. p.push.apply(p, postParts);
  19620. }
  19621. parts.push.apply(parts, p);
  19622. return parts;
  19623. }
  19624. function expandTop(str) {
  19625. if (!str)
  19626. return [];
  19627. // I don't know why Bash 4.3 does this, but it does.
  19628. // Anything starting with {} will have the first two bytes preserved
  19629. // but *only* at the top level, so {},a}b will not expand to anything,
  19630. // but a{},b}c will be expanded to [a}c,abc].
  19631. // One could argue that this is a bug in Bash, but since the goal of
  19632. // this module is to match Bash's rules, we escape a leading {}
  19633. if (str.substr(0, 2) === '{}') {
  19634. str = '\\{\\}' + str.substr(2);
  19635. }
  19636. return expand(escapeBraces(str), true).map(unescapeBraces);
  19637. }
  19638. function embrace(str) {
  19639. return '{' + str + '}';
  19640. }
  19641. function isPadded(el) {
  19642. return /^-?0\d/.test(el);
  19643. }
  19644. function lte(i, y) {
  19645. return i <= y;
  19646. }
  19647. function gte(i, y) {
  19648. return i >= y;
  19649. }
  19650. function expand(str, isTop) {
  19651. var expansions = [];
  19652. var m = balancedMatch('{', '}', str);
  19653. if (!m || /\$$/.test(m.pre)) return [str];
  19654. var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
  19655. var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
  19656. var isSequence = isNumericSequence || isAlphaSequence;
  19657. var isOptions = m.body.indexOf(',') >= 0;
  19658. if (!isSequence && !isOptions) {
  19659. // {a},b}
  19660. if (m.post.match(/,.*\}/)) {
  19661. str = m.pre + '{' + m.body + escClose + m.post;
  19662. return expand(str);
  19663. }
  19664. return [str];
  19665. }
  19666. var n;
  19667. if (isSequence) {
  19668. n = m.body.split(/\.\./);
  19669. } else {
  19670. n = parseCommaParts(m.body);
  19671. if (n.length === 1) {
  19672. // x{{a,b}}y ==> x{a}y x{b}y
  19673. n = expand(n[0], false).map(embrace);
  19674. if (n.length === 1) {
  19675. var post = m.post.length
  19676. ? expand(m.post, false)
  19677. : [''];
  19678. return post.map(function(p) {
  19679. return m.pre + n[0] + p;
  19680. });
  19681. }
  19682. }
  19683. }
  19684. // at this point, n is the parts, and we know it's not a comma set
  19685. // with a single entry.
  19686. // no need to expand pre, since it is guaranteed to be free of brace-sets
  19687. var pre = m.pre;
  19688. var post = m.post.length
  19689. ? expand(m.post, false)
  19690. : [''];
  19691. var N;
  19692. if (isSequence) {
  19693. var x = numeric(n[0]);
  19694. var y = numeric(n[1]);
  19695. var width = Math.max(n[0].length, n[1].length);
  19696. var incr = n.length == 3
  19697. ? Math.abs(numeric(n[2]))
  19698. : 1;
  19699. var test = lte;
  19700. var reverse = y < x;
  19701. if (reverse) {
  19702. incr *= -1;
  19703. test = gte;
  19704. }
  19705. var pad = n.some(isPadded);
  19706. N = [];
  19707. for (var i = x; test(i, y); i += incr) {
  19708. var c;
  19709. if (isAlphaSequence) {
  19710. c = String.fromCharCode(i);
  19711. if (c === '\\')
  19712. c = '';
  19713. } else {
  19714. c = String(i);
  19715. if (pad) {
  19716. var need = width - c.length;
  19717. if (need > 0) {
  19718. var z = new Array(need + 1).join('0');
  19719. if (i < 0)
  19720. c = '-' + z + c.slice(1);
  19721. else
  19722. c = z + c;
  19723. }
  19724. }
  19725. }
  19726. N.push(c);
  19727. }
  19728. } else {
  19729. N = concatMap(n, function(el) { return expand(el, false) });
  19730. }
  19731. for (var j = 0; j < N.length; j++) {
  19732. for (var k = 0; k < post.length; k++) {
  19733. var expansion = pre + N[j] + post[k];
  19734. if (!isTop || isSequence || expansion)
  19735. expansions.push(expansion);
  19736. }
  19737. }
  19738. return expansions;
  19739. }
  19740. var minimatch_1 = minimatch;
  19741. minimatch.Minimatch = Minimatch$1;
  19742. var path = { sep: '/' };
  19743. try {
  19744. path = path__default['default'];
  19745. } catch (er) {}
  19746. var GLOBSTAR = minimatch.GLOBSTAR = Minimatch$1.GLOBSTAR = {};
  19747. var plTypes = {
  19748. '!': { open: '(?:(?!(?:', close: '))[^/]*?)'},
  19749. '?': { open: '(?:', close: ')?' },
  19750. '+': { open: '(?:', close: ')+' },
  19751. '*': { open: '(?:', close: ')*' },
  19752. '@': { open: '(?:', close: ')' }
  19753. };
  19754. // any single thing other than /
  19755. // don't need to escape / when using new RegExp()
  19756. var qmark = '[^/]';
  19757. // * => any number of characters
  19758. var star = qmark + '*?';
  19759. // ** when dots are allowed. Anything goes, except .. and .
  19760. // not (^ or / followed by one or two dots followed by $ or /),
  19761. // followed by anything, any number of times.
  19762. var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?';
  19763. // not a ^ or / followed by a dot,
  19764. // followed by anything, any number of times.
  19765. var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?';
  19766. // characters that need to be escaped in RegExp.
  19767. var reSpecials = charSet('().*{}+?[]^$\\!');
  19768. // "abc" -> { a:true, b:true, c:true }
  19769. function charSet (s) {
  19770. return s.split('').reduce(function (set, c) {
  19771. set[c] = true;
  19772. return set
  19773. }, {})
  19774. }
  19775. // normalizes slashes.
  19776. var slashSplit = /\/+/;
  19777. minimatch.filter = filter;
  19778. function filter (pattern, options) {
  19779. options = options || {};
  19780. return function (p, i, list) {
  19781. return minimatch(p, pattern, options)
  19782. }
  19783. }
  19784. function ext (a, b) {
  19785. a = a || {};
  19786. b = b || {};
  19787. var t = {};
  19788. Object.keys(b).forEach(function (k) {
  19789. t[k] = b[k];
  19790. });
  19791. Object.keys(a).forEach(function (k) {
  19792. t[k] = a[k];
  19793. });
  19794. return t
  19795. }
  19796. minimatch.defaults = function (def) {
  19797. if (!def || !Object.keys(def).length) return minimatch
  19798. var orig = minimatch;
  19799. var m = function minimatch (p, pattern, options) {
  19800. return orig.minimatch(p, pattern, ext(def, options))
  19801. };
  19802. m.Minimatch = function Minimatch (pattern, options) {
  19803. return new orig.Minimatch(pattern, ext(def, options))
  19804. };
  19805. return m
  19806. };
  19807. Minimatch$1.defaults = function (def) {
  19808. if (!def || !Object.keys(def).length) return Minimatch$1
  19809. return minimatch.defaults(def).Minimatch
  19810. };
  19811. function minimatch (p, pattern, options) {
  19812. if (typeof pattern !== 'string') {
  19813. throw new TypeError('glob pattern string required')
  19814. }
  19815. if (!options) options = {};
  19816. // shortcut: comments match nothing.
  19817. if (!options.nocomment && pattern.charAt(0) === '#') {
  19818. return false
  19819. }
  19820. // "" only matches ""
  19821. if (pattern.trim() === '') return p === ''
  19822. return new Minimatch$1(pattern, options).match(p)
  19823. }
  19824. function Minimatch$1 (pattern, options) {
  19825. if (!(this instanceof Minimatch$1)) {
  19826. return new Minimatch$1(pattern, options)
  19827. }
  19828. if (typeof pattern !== 'string') {
  19829. throw new TypeError('glob pattern string required')
  19830. }
  19831. if (!options) options = {};
  19832. pattern = pattern.trim();
  19833. // windows support: need to use /, not \
  19834. if (path.sep !== '/') {
  19835. pattern = pattern.split(path.sep).join('/');
  19836. }
  19837. this.options = options;
  19838. this.set = [];
  19839. this.pattern = pattern;
  19840. this.regexp = null;
  19841. this.negate = false;
  19842. this.comment = false;
  19843. this.empty = false;
  19844. // make the set of regexps etc.
  19845. this.make();
  19846. }
  19847. Minimatch$1.prototype.debug = function () {};
  19848. Minimatch$1.prototype.make = make;
  19849. function make () {
  19850. // don't do it more than once.
  19851. if (this._made) return
  19852. var pattern = this.pattern;
  19853. var options = this.options;
  19854. // empty patterns and comments match nothing.
  19855. if (!options.nocomment && pattern.charAt(0) === '#') {
  19856. this.comment = true;
  19857. return
  19858. }
  19859. if (!pattern) {
  19860. this.empty = true;
  19861. return
  19862. }
  19863. // step 1: figure out negation, etc.
  19864. this.parseNegate();
  19865. // step 2: expand braces
  19866. var set = this.globSet = this.braceExpand();
  19867. if (options.debug) this.debug = console.error;
  19868. this.debug(this.pattern, set);
  19869. // step 3: now we have a set, so turn each one into a series of path-portion
  19870. // matching patterns.
  19871. // These will be regexps, except in the case of "**", which is
  19872. // set to the GLOBSTAR object for globstar behavior,
  19873. // and will not contain any / characters
  19874. set = this.globParts = set.map(function (s) {
  19875. return s.split(slashSplit)
  19876. });
  19877. this.debug(this.pattern, set);
  19878. // glob --> regexps
  19879. set = set.map(function (s, si, set) {
  19880. return s.map(this.parse, this)
  19881. }, this);
  19882. this.debug(this.pattern, set);
  19883. // filter out everything that didn't compile properly.
  19884. set = set.filter(function (s) {
  19885. return s.indexOf(false) === -1
  19886. });
  19887. this.debug(this.pattern, set);
  19888. this.set = set;
  19889. }
  19890. Minimatch$1.prototype.parseNegate = parseNegate;
  19891. function parseNegate () {
  19892. var pattern = this.pattern;
  19893. var negate = false;
  19894. var options = this.options;
  19895. var negateOffset = 0;
  19896. if (options.nonegate) return
  19897. for (var i = 0, l = pattern.length
  19898. ; i < l && pattern.charAt(i) === '!'
  19899. ; i++) {
  19900. negate = !negate;
  19901. negateOffset++;
  19902. }
  19903. if (negateOffset) this.pattern = pattern.substr(negateOffset);
  19904. this.negate = negate;
  19905. }
  19906. // Brace expansion:
  19907. // a{b,c}d -> abd acd
  19908. // a{b,}c -> abc ac
  19909. // a{0..3}d -> a0d a1d a2d a3d
  19910. // a{b,c{d,e}f}g -> abg acdfg acefg
  19911. // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
  19912. //
  19913. // Invalid sets are not expanded.
  19914. // a{2..}b -> a{2..}b
  19915. // a{b}c -> a{b}c
  19916. minimatch.braceExpand = function (pattern, options) {
  19917. return braceExpand(pattern, options)
  19918. };
  19919. Minimatch$1.prototype.braceExpand = braceExpand;
  19920. function braceExpand (pattern, options) {
  19921. if (!options) {
  19922. if (this instanceof Minimatch$1) {
  19923. options = this.options;
  19924. } else {
  19925. options = {};
  19926. }
  19927. }
  19928. pattern = typeof pattern === 'undefined'
  19929. ? this.pattern : pattern;
  19930. if (typeof pattern === 'undefined') {
  19931. throw new TypeError('undefined pattern')
  19932. }
  19933. if (options.nobrace ||
  19934. !pattern.match(/\{.*\}/)) {
  19935. // shortcut. no need to expand.
  19936. return [pattern]
  19937. }
  19938. return braceExpansion(pattern)
  19939. }
  19940. // parse a component of the expanded set.
  19941. // At this point, no pattern may contain "/" in it
  19942. // so we're going to return a 2d array, where each entry is the full
  19943. // pattern, split on '/', and then turned into a regular expression.
  19944. // A regexp is made at the end which joins each array with an
  19945. // escaped /, and another full one which joins each regexp with |.
  19946. //
  19947. // Following the lead of Bash 4.1, note that "**" only has special meaning
  19948. // when it is the *only* thing in a path portion. Otherwise, any series
  19949. // of * is equivalent to a single *. Globstar behavior is enabled by
  19950. // default, and can be disabled by setting options.noglobstar.
  19951. Minimatch$1.prototype.parse = parse;
  19952. var SUBPARSE = {};
  19953. function parse (pattern, isSub) {
  19954. if (pattern.length > 1024 * 64) {
  19955. throw new TypeError('pattern is too long')
  19956. }
  19957. var options = this.options;
  19958. // shortcuts
  19959. if (!options.noglobstar && pattern === '**') return GLOBSTAR
  19960. if (pattern === '') return ''
  19961. var re = '';
  19962. var hasMagic = !!options.nocase;
  19963. var escaping = false;
  19964. // ? => one single character
  19965. var patternListStack = [];
  19966. var negativeLists = [];
  19967. var stateChar;
  19968. var inClass = false;
  19969. var reClassStart = -1;
  19970. var classStart = -1;
  19971. // . and .. never match anything that doesn't start with .,
  19972. // even when options.dot is set.
  19973. var patternStart = pattern.charAt(0) === '.' ? '' // anything
  19974. // not (start or / followed by . or .. followed by / or end)
  19975. : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))'
  19976. : '(?!\\.)';
  19977. var self = this;
  19978. function clearStateChar () {
  19979. if (stateChar) {
  19980. // we had some state-tracking character
  19981. // that wasn't consumed by this pass.
  19982. switch (stateChar) {
  19983. case '*':
  19984. re += star;
  19985. hasMagic = true;
  19986. break
  19987. case '?':
  19988. re += qmark;
  19989. hasMagic = true;
  19990. break
  19991. default:
  19992. re += '\\' + stateChar;
  19993. break
  19994. }
  19995. self.debug('clearStateChar %j %j', stateChar, re);
  19996. stateChar = false;
  19997. }
  19998. }
  19999. for (var i = 0, len = pattern.length, c
  20000. ; (i < len) && (c = pattern.charAt(i))
  20001. ; i++) {
  20002. this.debug('%s\t%s %s %j', pattern, i, re, c);
  20003. // skip over any that are escaped.
  20004. if (escaping && reSpecials[c]) {
  20005. re += '\\' + c;
  20006. escaping = false;
  20007. continue
  20008. }
  20009. switch (c) {
  20010. case '/':
  20011. // completely not allowed, even escaped.
  20012. // Should already be path-split by now.
  20013. return false
  20014. case '\\':
  20015. clearStateChar();
  20016. escaping = true;
  20017. continue
  20018. // the various stateChar values
  20019. // for the "extglob" stuff.
  20020. case '?':
  20021. case '*':
  20022. case '+':
  20023. case '@':
  20024. case '!':
  20025. this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c);
  20026. // all of those are literals inside a class, except that
  20027. // the glob [!a] means [^a] in regexp
  20028. if (inClass) {
  20029. this.debug(' in class');
  20030. if (c === '!' && i === classStart + 1) c = '^';
  20031. re += c;
  20032. continue
  20033. }
  20034. // if we already have a stateChar, then it means
  20035. // that there was something like ** or +? in there.
  20036. // Handle the stateChar, then proceed with this one.
  20037. self.debug('call clearStateChar %j', stateChar);
  20038. clearStateChar();
  20039. stateChar = c;
  20040. // if extglob is disabled, then +(asdf|foo) isn't a thing.
  20041. // just clear the statechar *now*, rather than even diving into
  20042. // the patternList stuff.
  20043. if (options.noext) clearStateChar();
  20044. continue
  20045. case '(':
  20046. if (inClass) {
  20047. re += '(';
  20048. continue
  20049. }
  20050. if (!stateChar) {
  20051. re += '\\(';
  20052. continue
  20053. }
  20054. patternListStack.push({
  20055. type: stateChar,
  20056. start: i - 1,
  20057. reStart: re.length,
  20058. open: plTypes[stateChar].open,
  20059. close: plTypes[stateChar].close
  20060. });
  20061. // negation is (?:(?!js)[^/]*)
  20062. re += stateChar === '!' ? '(?:(?!(?:' : '(?:';
  20063. this.debug('plType %j %j', stateChar, re);
  20064. stateChar = false;
  20065. continue
  20066. case ')':
  20067. if (inClass || !patternListStack.length) {
  20068. re += '\\)';
  20069. continue
  20070. }
  20071. clearStateChar();
  20072. hasMagic = true;
  20073. var pl = patternListStack.pop();
  20074. // negation is (?:(?!js)[^/]*)
  20075. // The others are (?:<pattern>)<type>
  20076. re += pl.close;
  20077. if (pl.type === '!') {
  20078. negativeLists.push(pl);
  20079. }
  20080. pl.reEnd = re.length;
  20081. continue
  20082. case '|':
  20083. if (inClass || !patternListStack.length || escaping) {
  20084. re += '\\|';
  20085. escaping = false;
  20086. continue
  20087. }
  20088. clearStateChar();
  20089. re += '|';
  20090. continue
  20091. // these are mostly the same in regexp and glob
  20092. case '[':
  20093. // swallow any state-tracking char before the [
  20094. clearStateChar();
  20095. if (inClass) {
  20096. re += '\\' + c;
  20097. continue
  20098. }
  20099. inClass = true;
  20100. classStart = i;
  20101. reClassStart = re.length;
  20102. re += c;
  20103. continue
  20104. case ']':
  20105. // a right bracket shall lose its special
  20106. // meaning and represent itself in
  20107. // a bracket expression if it occurs
  20108. // first in the list. -- POSIX.2 2.8.3.2
  20109. if (i === classStart + 1 || !inClass) {
  20110. re += '\\' + c;
  20111. escaping = false;
  20112. continue
  20113. }
  20114. // handle the case where we left a class open.
  20115. // "[z-a]" is valid, equivalent to "\[z-a\]"
  20116. if (inClass) {
  20117. // split where the last [ was, make sure we don't have
  20118. // an invalid re. if so, re-walk the contents of the
  20119. // would-be class to re-translate any characters that
  20120. // were passed through as-is
  20121. // TODO: It would probably be faster to determine this
  20122. // without a try/catch and a new RegExp, but it's tricky
  20123. // to do safely. For now, this is safe and works.
  20124. var cs = pattern.substring(classStart + 1, i);
  20125. try {
  20126. RegExp('[' + cs + ']');
  20127. } catch (er) {
  20128. // not a valid class!
  20129. var sp = this.parse(cs, SUBPARSE);
  20130. re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]';
  20131. hasMagic = hasMagic || sp[1];
  20132. inClass = false;
  20133. continue
  20134. }
  20135. }
  20136. // finish up the class.
  20137. hasMagic = true;
  20138. inClass = false;
  20139. re += c;
  20140. continue
  20141. default:
  20142. // swallow any state char that wasn't consumed
  20143. clearStateChar();
  20144. if (escaping) {
  20145. // no need
  20146. escaping = false;
  20147. } else if (reSpecials[c]
  20148. && !(c === '^' && inClass)) {
  20149. re += '\\';
  20150. }
  20151. re += c;
  20152. } // switch
  20153. } // for
  20154. // handle the case where we left a class open.
  20155. // "[abc" is valid, equivalent to "\[abc"
  20156. if (inClass) {
  20157. // split where the last [ was, and escape it
  20158. // this is a huge pita. We now have to re-walk
  20159. // the contents of the would-be class to re-translate
  20160. // any characters that were passed through as-is
  20161. cs = pattern.substr(classStart + 1);
  20162. sp = this.parse(cs, SUBPARSE);
  20163. re = re.substr(0, reClassStart) + '\\[' + sp[0];
  20164. hasMagic = hasMagic || sp[1];
  20165. }
  20166. // handle the case where we had a +( thing at the *end*
  20167. // of the pattern.
  20168. // each pattern list stack adds 3 chars, and we need to go through
  20169. // and escape any | chars that were passed through as-is for the regexp.
  20170. // Go through and escape them, taking care not to double-escape any
  20171. // | chars that were already escaped.
  20172. for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
  20173. var tail = re.slice(pl.reStart + pl.open.length);
  20174. this.debug('setting tail', re, pl);
  20175. // maybe some even number of \, then maybe 1 \, followed by a |
  20176. tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) {
  20177. if (!$2) {
  20178. // the | isn't already escaped, so escape it.
  20179. $2 = '\\';
  20180. }
  20181. // need to escape all those slashes *again*, without escaping the
  20182. // one that we need for escaping the | character. As it works out,
  20183. // escaping an even number of slashes can be done by simply repeating
  20184. // it exactly after itself. That's why this trick works.
  20185. //
  20186. // I am sorry that you have to see this.
  20187. return $1 + $1 + $2 + '|'
  20188. });
  20189. this.debug('tail=%j\n %s', tail, tail, pl, re);
  20190. var t = pl.type === '*' ? star
  20191. : pl.type === '?' ? qmark
  20192. : '\\' + pl.type;
  20193. hasMagic = true;
  20194. re = re.slice(0, pl.reStart) + t + '\\(' + tail;
  20195. }
  20196. // handle trailing things that only matter at the very end.
  20197. clearStateChar();
  20198. if (escaping) {
  20199. // trailing \\
  20200. re += '\\\\';
  20201. }
  20202. // only need to apply the nodot start if the re starts with
  20203. // something that could conceivably capture a dot
  20204. var addPatternStart = false;
  20205. switch (re.charAt(0)) {
  20206. case '.':
  20207. case '[':
  20208. case '(': addPatternStart = true;
  20209. }
  20210. // Hack to work around lack of negative lookbehind in JS
  20211. // A pattern like: *.!(x).!(y|z) needs to ensure that a name
  20212. // like 'a.xyz.yz' doesn't match. So, the first negative
  20213. // lookahead, has to look ALL the way ahead, to the end of
  20214. // the pattern.
  20215. for (var n = negativeLists.length - 1; n > -1; n--) {
  20216. var nl = negativeLists[n];
  20217. var nlBefore = re.slice(0, nl.reStart);
  20218. var nlFirst = re.slice(nl.reStart, nl.reEnd - 8);
  20219. var nlLast = re.slice(nl.reEnd - 8, nl.reEnd);
  20220. var nlAfter = re.slice(nl.reEnd);
  20221. nlLast += nlAfter;
  20222. // Handle nested stuff like *(*.js|!(*.json)), where open parens
  20223. // mean that we should *not* include the ) in the bit that is considered
  20224. // "after" the negated section.
  20225. var openParensBefore = nlBefore.split('(').length - 1;
  20226. var cleanAfter = nlAfter;
  20227. for (i = 0; i < openParensBefore; i++) {
  20228. cleanAfter = cleanAfter.replace(/\)[+*?]?/, '');
  20229. }
  20230. nlAfter = cleanAfter;
  20231. var dollar = '';
  20232. if (nlAfter === '' && isSub !== SUBPARSE) {
  20233. dollar = '$';
  20234. }
  20235. var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast;
  20236. re = newRe;
  20237. }
  20238. // if the re is not "" at this point, then we need to make sure
  20239. // it doesn't match against an empty path part.
  20240. // Otherwise a/* will match a/, which it should not.
  20241. if (re !== '' && hasMagic) {
  20242. re = '(?=.)' + re;
  20243. }
  20244. if (addPatternStart) {
  20245. re = patternStart + re;
  20246. }
  20247. // parsing just a piece of a larger pattern.
  20248. if (isSub === SUBPARSE) {
  20249. return [re, hasMagic]
  20250. }
  20251. // skip the regexp for non-magical patterns
  20252. // unescape anything in it, though, so that it'll be
  20253. // an exact match against a file etc.
  20254. if (!hasMagic) {
  20255. return globUnescape(pattern)
  20256. }
  20257. var flags = options.nocase ? 'i' : '';
  20258. try {
  20259. var regExp = new RegExp('^' + re + '$', flags);
  20260. } catch (er) {
  20261. // If it was an invalid regular expression, then it can't match
  20262. // anything. This trick looks for a character after the end of
  20263. // the string, which is of course impossible, except in multi-line
  20264. // mode, but it's not a /m regex.
  20265. return new RegExp('$.')
  20266. }
  20267. regExp._glob = pattern;
  20268. regExp._src = re;
  20269. return regExp
  20270. }
  20271. minimatch.makeRe = function (pattern, options) {
  20272. return new Minimatch$1(pattern, options || {}).makeRe()
  20273. };
  20274. Minimatch$1.prototype.makeRe = makeRe;
  20275. function makeRe () {
  20276. if (this.regexp || this.regexp === false) return this.regexp
  20277. // at this point, this.set is a 2d array of partial
  20278. // pattern strings, or "**".
  20279. //
  20280. // It's better to use .match(). This function shouldn't
  20281. // be used, really, but it's pretty convenient sometimes,
  20282. // when you just want to work with a regex.
  20283. var set = this.set;
  20284. if (!set.length) {
  20285. this.regexp = false;
  20286. return this.regexp
  20287. }
  20288. var options = this.options;
  20289. var twoStar = options.noglobstar ? star
  20290. : options.dot ? twoStarDot
  20291. : twoStarNoDot;
  20292. var flags = options.nocase ? 'i' : '';
  20293. var re = set.map(function (pattern) {
  20294. return pattern.map(function (p) {
  20295. return (p === GLOBSTAR) ? twoStar
  20296. : (typeof p === 'string') ? regExpEscape(p)
  20297. : p._src
  20298. }).join('\\\/')
  20299. }).join('|');
  20300. // must match entire pattern
  20301. // ending in a * or ** will make it less strict.
  20302. re = '^(?:' + re + ')$';
  20303. // can match anything, as long as it's not this.
  20304. if (this.negate) re = '^(?!' + re + ').*$';
  20305. try {
  20306. this.regexp = new RegExp(re, flags);
  20307. } catch (ex) {
  20308. this.regexp = false;
  20309. }
  20310. return this.regexp
  20311. }
  20312. minimatch.match = function (list, pattern, options) {
  20313. options = options || {};
  20314. var mm = new Minimatch$1(pattern, options);
  20315. list = list.filter(function (f) {
  20316. return mm.match(f)
  20317. });
  20318. if (mm.options.nonull && !list.length) {
  20319. list.push(pattern);
  20320. }
  20321. return list
  20322. };
  20323. Minimatch$1.prototype.match = match;
  20324. function match (f, partial) {
  20325. this.debug('match', f, this.pattern);
  20326. // short-circuit in the case of busted things.
  20327. // comments, etc.
  20328. if (this.comment) return false
  20329. if (this.empty) return f === ''
  20330. if (f === '/' && partial) return true
  20331. var options = this.options;
  20332. // windows: need to use /, not \
  20333. if (path.sep !== '/') {
  20334. f = f.split(path.sep).join('/');
  20335. }
  20336. // treat the test path as a set of pathparts.
  20337. f = f.split(slashSplit);
  20338. this.debug(this.pattern, 'split', f);
  20339. // just ONE of the pattern sets in this.set needs to match
  20340. // in order for it to be valid. If negating, then just one
  20341. // match means that we have failed.
  20342. // Either way, return on the first hit.
  20343. var set = this.set;
  20344. this.debug(this.pattern, 'set', set);
  20345. // Find the basename of the path by looking for the last non-empty segment
  20346. var filename;
  20347. var i;
  20348. for (i = f.length - 1; i >= 0; i--) {
  20349. filename = f[i];
  20350. if (filename) break
  20351. }
  20352. for (i = 0; i < set.length; i++) {
  20353. var pattern = set[i];
  20354. var file = f;
  20355. if (options.matchBase && pattern.length === 1) {
  20356. file = [filename];
  20357. }
  20358. var hit = this.matchOne(file, pattern, partial);
  20359. if (hit) {
  20360. if (options.flipNegate) return true
  20361. return !this.negate
  20362. }
  20363. }
  20364. // didn't get any hits. this is success if it's a negative
  20365. // pattern, failure otherwise.
  20366. if (options.flipNegate) return false
  20367. return this.negate
  20368. }
  20369. // set partial to true to test if, for example,
  20370. // "/a/b" matches the start of "/*/b/*/d"
  20371. // Partial means, if you run out of file before you run
  20372. // out of pattern, then that's fine, as long as all
  20373. // the parts match.
  20374. Minimatch$1.prototype.matchOne = function (file, pattern, partial) {
  20375. var options = this.options;
  20376. this.debug('matchOne',
  20377. { 'this': this, file: file, pattern: pattern });
  20378. this.debug('matchOne', file.length, pattern.length);
  20379. for (var fi = 0,
  20380. pi = 0,
  20381. fl = file.length,
  20382. pl = pattern.length
  20383. ; (fi < fl) && (pi < pl)
  20384. ; fi++, pi++) {
  20385. this.debug('matchOne loop');
  20386. var p = pattern[pi];
  20387. var f = file[fi];
  20388. this.debug(pattern, p, f);
  20389. // should be impossible.
  20390. // some invalid regexp stuff in the set.
  20391. if (p === false) return false
  20392. if (p === GLOBSTAR) {
  20393. this.debug('GLOBSTAR', [pattern, p, f]);
  20394. // "**"
  20395. // a/**/b/**/c would match the following:
  20396. // a/b/x/y/z/c
  20397. // a/x/y/z/b/c
  20398. // a/b/x/b/x/c
  20399. // a/b/c
  20400. // To do this, take the rest of the pattern after
  20401. // the **, and see if it would match the file remainder.
  20402. // If so, return success.
  20403. // If not, the ** "swallows" a segment, and try again.
  20404. // This is recursively awful.
  20405. //
  20406. // a/**/b/**/c matching a/b/x/y/z/c
  20407. // - a matches a
  20408. // - doublestar
  20409. // - matchOne(b/x/y/z/c, b/**/c)
  20410. // - b matches b
  20411. // - doublestar
  20412. // - matchOne(x/y/z/c, c) -> no
  20413. // - matchOne(y/z/c, c) -> no
  20414. // - matchOne(z/c, c) -> no
  20415. // - matchOne(c, c) yes, hit
  20416. var fr = fi;
  20417. var pr = pi + 1;
  20418. if (pr === pl) {
  20419. this.debug('** at the end');
  20420. // a ** at the end will just swallow the rest.
  20421. // We have found a match.
  20422. // however, it will not swallow /.x, unless
  20423. // options.dot is set.
  20424. // . and .. are *never* matched by **, for explosively
  20425. // exponential reasons.
  20426. for (; fi < fl; fi++) {
  20427. if (file[fi] === '.' || file[fi] === '..' ||
  20428. (!options.dot && file[fi].charAt(0) === '.')) return false
  20429. }
  20430. return true
  20431. }
  20432. // ok, let's see if we can swallow whatever we can.
  20433. while (fr < fl) {
  20434. var swallowee = file[fr];
  20435. this.debug('\nglobstar while', file, fr, pattern, pr, swallowee);
  20436. // XXX remove this slice. Just pass the start index.
  20437. if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
  20438. this.debug('globstar found match!', fr, fl, swallowee);
  20439. // found a match.
  20440. return true
  20441. } else {
  20442. // can't swallow "." or ".." ever.
  20443. // can only swallow ".foo" when explicitly asked.
  20444. if (swallowee === '.' || swallowee === '..' ||
  20445. (!options.dot && swallowee.charAt(0) === '.')) {
  20446. this.debug('dot detected!', file, fr, pattern, pr);
  20447. break
  20448. }
  20449. // ** swallows a segment, and continue.
  20450. this.debug('globstar swallow a segment, and continue');
  20451. fr++;
  20452. }
  20453. }
  20454. // no match was found.
  20455. // However, in partial mode, we can't say this is necessarily over.
  20456. // If there's more *pattern* left, then
  20457. if (partial) {
  20458. // ran out of file
  20459. this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
  20460. if (fr === fl) return true
  20461. }
  20462. return false
  20463. }
  20464. // something other than **
  20465. // non-magic patterns just have to match exactly
  20466. // patterns with magic have been turned into regexps.
  20467. var hit;
  20468. if (typeof p === 'string') {
  20469. if (options.nocase) {
  20470. hit = f.toLowerCase() === p.toLowerCase();
  20471. } else {
  20472. hit = f === p;
  20473. }
  20474. this.debug('string match', p, f, hit);
  20475. } else {
  20476. hit = f.match(p);
  20477. this.debug('pattern match', p, f, hit);
  20478. }
  20479. if (!hit) return false
  20480. }
  20481. // Note: ending in / means that we'll get a final ""
  20482. // at the end of the pattern. This can only match a
  20483. // corresponding "" at the end of the file.
  20484. // If the file ends in /, then it can only match a
  20485. // a pattern that ends in /, unless the pattern just
  20486. // doesn't have any more for it. But, a/b/ should *not*
  20487. // match "a/b/*", even though "" matches against the
  20488. // [^/]*? pattern, except in partial mode, where it might
  20489. // simply not be reached yet.
  20490. // However, a/b/ should still satisfy a/*
  20491. // now either we fell off the end of the pattern, or we're done.
  20492. if (fi === fl && pi === pl) {
  20493. // ran out of pattern and filename at the same time.
  20494. // an exact hit!
  20495. return true
  20496. } else if (fi === fl) {
  20497. // ran out of file, but still had pattern left.
  20498. // this is ok if we're doing the match as part of
  20499. // a glob fs traversal.
  20500. return partial
  20501. } else if (pi === pl) {
  20502. // ran out of pattern, still have file left.
  20503. // this is only acceptable if we're on the very last
  20504. // empty segment of a file with a trailing slash.
  20505. // a/* should match a/b/
  20506. var emptyFileEnd = (fi === fl - 1) && (file[fi] === '');
  20507. return emptyFileEnd
  20508. }
  20509. // should be unreachable.
  20510. throw new Error('wtf?')
  20511. };
  20512. // replace stuff like \* with *
  20513. function globUnescape (s) {
  20514. return s.replace(/\\(.)/g, '$1')
  20515. }
  20516. function regExpEscape (s) {
  20517. return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
  20518. }
  20519. var inherits_browser = createCommonjsModule(function (module) {
  20520. if (typeof Object.create === 'function') {
  20521. // implementation from standard node.js 'util' module
  20522. module.exports = function inherits(ctor, superCtor) {
  20523. if (superCtor) {
  20524. ctor.super_ = superCtor;
  20525. ctor.prototype = Object.create(superCtor.prototype, {
  20526. constructor: {
  20527. value: ctor,
  20528. enumerable: false,
  20529. writable: true,
  20530. configurable: true
  20531. }
  20532. });
  20533. }
  20534. };
  20535. } else {
  20536. // old school shim for old browsers
  20537. module.exports = function inherits(ctor, superCtor) {
  20538. if (superCtor) {
  20539. ctor.super_ = superCtor;
  20540. var TempCtor = function () {};
  20541. TempCtor.prototype = superCtor.prototype;
  20542. ctor.prototype = new TempCtor();
  20543. ctor.prototype.constructor = ctor;
  20544. }
  20545. };
  20546. }
  20547. }, "/$$rollup_base$$/node_modules/inherits");
  20548. var inherits = createCommonjsModule(function (module) {
  20549. try {
  20550. var util = require$$0__default['default'];
  20551. /* istanbul ignore next */
  20552. if (typeof util.inherits !== 'function') throw '';
  20553. module.exports = util.inherits;
  20554. } catch (e) {
  20555. /* istanbul ignore next */
  20556. module.exports = inherits_browser;
  20557. }
  20558. }, "/$$rollup_base$$/node_modules/inherits");
  20559. function posix(path) {
  20560. return path.charAt(0) === '/';
  20561. }
  20562. function win32(path) {
  20563. // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56
  20564. var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/;
  20565. var result = splitDeviceRe.exec(path);
  20566. var device = result[1] || '';
  20567. var isUnc = Boolean(device && device.charAt(1) !== ':');
  20568. // UNC paths are always absolute
  20569. return Boolean(result[2] || isUnc);
  20570. }
  20571. var pathIsAbsolute = process.platform === 'win32' ? win32 : posix;
  20572. var posix_1 = posix;
  20573. var win32_1 = win32;
  20574. pathIsAbsolute.posix = posix_1;
  20575. pathIsAbsolute.win32 = win32_1;
  20576. var setopts_1 = setopts$2;
  20577. var ownProp_1 = ownProp$2;
  20578. var makeAbs_1 = makeAbs;
  20579. var finish_1 = finish;
  20580. var mark_1 = mark;
  20581. var isIgnored_1 = isIgnored$2;
  20582. var childrenIgnored_1 = childrenIgnored$2;
  20583. function ownProp$2 (obj, field) {
  20584. return Object.prototype.hasOwnProperty.call(obj, field)
  20585. }
  20586. var Minimatch = minimatch_1.Minimatch;
  20587. function alphasort (a, b) {
  20588. return a.localeCompare(b, 'en')
  20589. }
  20590. function setupIgnores (self, options) {
  20591. self.ignore = options.ignore || [];
  20592. if (!Array.isArray(self.ignore))
  20593. self.ignore = [self.ignore];
  20594. if (self.ignore.length) {
  20595. self.ignore = self.ignore.map(ignoreMap);
  20596. }
  20597. }
  20598. // ignore patterns are always in dot:true mode.
  20599. function ignoreMap (pattern) {
  20600. var gmatcher = null;
  20601. if (pattern.slice(-3) === '/**') {
  20602. var gpattern = pattern.replace(/(\/\*\*)+$/, '');
  20603. gmatcher = new Minimatch(gpattern, { dot: true });
  20604. }
  20605. return {
  20606. matcher: new Minimatch(pattern, { dot: true }),
  20607. gmatcher: gmatcher
  20608. }
  20609. }
  20610. function setopts$2 (self, pattern, options) {
  20611. if (!options)
  20612. options = {};
  20613. // base-matching: just use globstar for that.
  20614. if (options.matchBase && -1 === pattern.indexOf("/")) {
  20615. if (options.noglobstar) {
  20616. throw new Error("base matching requires globstar")
  20617. }
  20618. pattern = "**/" + pattern;
  20619. }
  20620. self.silent = !!options.silent;
  20621. self.pattern = pattern;
  20622. self.strict = options.strict !== false;
  20623. self.realpath = !!options.realpath;
  20624. self.realpathCache = options.realpathCache || Object.create(null);
  20625. self.follow = !!options.follow;
  20626. self.dot = !!options.dot;
  20627. self.mark = !!options.mark;
  20628. self.nodir = !!options.nodir;
  20629. if (self.nodir)
  20630. self.mark = true;
  20631. self.sync = !!options.sync;
  20632. self.nounique = !!options.nounique;
  20633. self.nonull = !!options.nonull;
  20634. self.nosort = !!options.nosort;
  20635. self.nocase = !!options.nocase;
  20636. self.stat = !!options.stat;
  20637. self.noprocess = !!options.noprocess;
  20638. self.absolute = !!options.absolute;
  20639. self.maxLength = options.maxLength || Infinity;
  20640. self.cache = options.cache || Object.create(null);
  20641. self.statCache = options.statCache || Object.create(null);
  20642. self.symlinks = options.symlinks || Object.create(null);
  20643. setupIgnores(self, options);
  20644. self.changedCwd = false;
  20645. var cwd = process.cwd();
  20646. if (!ownProp$2(options, "cwd"))
  20647. self.cwd = cwd;
  20648. else {
  20649. self.cwd = path__default['default'].resolve(options.cwd);
  20650. self.changedCwd = self.cwd !== cwd;
  20651. }
  20652. self.root = options.root || path__default['default'].resolve(self.cwd, "/");
  20653. self.root = path__default['default'].resolve(self.root);
  20654. if (process.platform === "win32")
  20655. self.root = self.root.replace(/\\/g, "/");
  20656. // TODO: is an absolute `cwd` supposed to be resolved against `root`?
  20657. // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test')
  20658. self.cwdAbs = pathIsAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd);
  20659. if (process.platform === "win32")
  20660. self.cwdAbs = self.cwdAbs.replace(/\\/g, "/");
  20661. self.nomount = !!options.nomount;
  20662. // disable comments and negation in Minimatch.
  20663. // Note that they are not supported in Glob itself anyway.
  20664. options.nonegate = true;
  20665. options.nocomment = true;
  20666. self.minimatch = new Minimatch(pattern, options);
  20667. self.options = self.minimatch.options;
  20668. }
  20669. function finish (self) {
  20670. var nou = self.nounique;
  20671. var all = nou ? [] : Object.create(null);
  20672. for (var i = 0, l = self.matches.length; i < l; i ++) {
  20673. var matches = self.matches[i];
  20674. if (!matches || Object.keys(matches).length === 0) {
  20675. if (self.nonull) {
  20676. // do like the shell, and spit out the literal glob
  20677. var literal = self.minimatch.globSet[i];
  20678. if (nou)
  20679. all.push(literal);
  20680. else
  20681. all[literal] = true;
  20682. }
  20683. } else {
  20684. // had matches
  20685. var m = Object.keys(matches);
  20686. if (nou)
  20687. all.push.apply(all, m);
  20688. else
  20689. m.forEach(function (m) {
  20690. all[m] = true;
  20691. });
  20692. }
  20693. }
  20694. if (!nou)
  20695. all = Object.keys(all);
  20696. if (!self.nosort)
  20697. all = all.sort(alphasort);
  20698. // at *some* point we statted all of these
  20699. if (self.mark) {
  20700. for (var i = 0; i < all.length; i++) {
  20701. all[i] = self._mark(all[i]);
  20702. }
  20703. if (self.nodir) {
  20704. all = all.filter(function (e) {
  20705. var notDir = !(/\/$/.test(e));
  20706. var c = self.cache[e] || self.cache[makeAbs(self, e)];
  20707. if (notDir && c)
  20708. notDir = c !== 'DIR' && !Array.isArray(c);
  20709. return notDir
  20710. });
  20711. }
  20712. }
  20713. if (self.ignore.length)
  20714. all = all.filter(function(m) {
  20715. return !isIgnored$2(self, m)
  20716. });
  20717. self.found = all;
  20718. }
  20719. function mark (self, p) {
  20720. var abs = makeAbs(self, p);
  20721. var c = self.cache[abs];
  20722. var m = p;
  20723. if (c) {
  20724. var isDir = c === 'DIR' || Array.isArray(c);
  20725. var slash = p.slice(-1) === '/';
  20726. if (isDir && !slash)
  20727. m += '/';
  20728. else if (!isDir && slash)
  20729. m = m.slice(0, -1);
  20730. if (m !== p) {
  20731. var mabs = makeAbs(self, m);
  20732. self.statCache[mabs] = self.statCache[abs];
  20733. self.cache[mabs] = self.cache[abs];
  20734. }
  20735. }
  20736. return m
  20737. }
  20738. // lotta situps...
  20739. function makeAbs (self, f) {
  20740. var abs = f;
  20741. if (f.charAt(0) === '/') {
  20742. abs = path__default['default'].join(self.root, f);
  20743. } else if (pathIsAbsolute(f) || f === '') {
  20744. abs = f;
  20745. } else if (self.changedCwd) {
  20746. abs = path__default['default'].resolve(self.cwd, f);
  20747. } else {
  20748. abs = path__default['default'].resolve(f);
  20749. }
  20750. if (process.platform === 'win32')
  20751. abs = abs.replace(/\\/g, '/');
  20752. return abs
  20753. }
  20754. // Return true, if pattern ends with globstar '**', for the accompanying parent directory.
  20755. // Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents
  20756. function isIgnored$2 (self, path) {
  20757. if (!self.ignore.length)
  20758. return false
  20759. return self.ignore.some(function(item) {
  20760. return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path))
  20761. })
  20762. }
  20763. function childrenIgnored$2 (self, path) {
  20764. if (!self.ignore.length)
  20765. return false
  20766. return self.ignore.some(function(item) {
  20767. return !!(item.gmatcher && item.gmatcher.match(path))
  20768. })
  20769. }
  20770. var common = {
  20771. setopts: setopts_1,
  20772. ownProp: ownProp_1,
  20773. makeAbs: makeAbs_1,
  20774. finish: finish_1,
  20775. mark: mark_1,
  20776. isIgnored: isIgnored_1,
  20777. childrenIgnored: childrenIgnored_1
  20778. };
  20779. var sync = globSync;
  20780. globSync.GlobSync = GlobSync$1;
  20781. var setopts$1 = common.setopts;
  20782. var ownProp$1 = common.ownProp;
  20783. var childrenIgnored$1 = common.childrenIgnored;
  20784. var isIgnored$1 = common.isIgnored;
  20785. function globSync (pattern, options) {
  20786. if (typeof options === 'function' || arguments.length === 3)
  20787. throw new TypeError('callback provided to sync glob\n'+
  20788. 'See: https://github.com/isaacs/node-glob/issues/167')
  20789. return new GlobSync$1(pattern, options).found
  20790. }
  20791. function GlobSync$1 (pattern, options) {
  20792. if (!pattern)
  20793. throw new Error('must provide pattern')
  20794. if (typeof options === 'function' || arguments.length === 3)
  20795. throw new TypeError('callback provided to sync glob\n'+
  20796. 'See: https://github.com/isaacs/node-glob/issues/167')
  20797. if (!(this instanceof GlobSync$1))
  20798. return new GlobSync$1(pattern, options)
  20799. setopts$1(this, pattern, options);
  20800. if (this.noprocess)
  20801. return this
  20802. var n = this.minimatch.set.length;
  20803. this.matches = new Array(n);
  20804. for (var i = 0; i < n; i ++) {
  20805. this._process(this.minimatch.set[i], i, false);
  20806. }
  20807. this._finish();
  20808. }
  20809. GlobSync$1.prototype._finish = function () {
  20810. assert__default['default'](this instanceof GlobSync$1);
  20811. if (this.realpath) {
  20812. var self = this;
  20813. this.matches.forEach(function (matchset, index) {
  20814. var set = self.matches[index] = Object.create(null);
  20815. for (var p in matchset) {
  20816. try {
  20817. p = self._makeAbs(p);
  20818. var real = fs_realpath.realpathSync(p, self.realpathCache);
  20819. set[real] = true;
  20820. } catch (er) {
  20821. if (er.syscall === 'stat')
  20822. set[self._makeAbs(p)] = true;
  20823. else
  20824. throw er
  20825. }
  20826. }
  20827. });
  20828. }
  20829. common.finish(this);
  20830. };
  20831. GlobSync$1.prototype._process = function (pattern, index, inGlobStar) {
  20832. assert__default['default'](this instanceof GlobSync$1);
  20833. // Get the first [n] parts of pattern that are all strings.
  20834. var n = 0;
  20835. while (typeof pattern[n] === 'string') {
  20836. n ++;
  20837. }
  20838. // now n is the index of the first one that is *not* a string.
  20839. // See if there's anything else
  20840. var prefix;
  20841. switch (n) {
  20842. // if not, then this is rather simple
  20843. case pattern.length:
  20844. this._processSimple(pattern.join('/'), index);
  20845. return
  20846. case 0:
  20847. // pattern *starts* with some non-trivial item.
  20848. // going to readdir(cwd), but not include the prefix in matches.
  20849. prefix = null;
  20850. break
  20851. default:
  20852. // pattern has some string bits in the front.
  20853. // whatever it starts with, whether that's 'absolute' like /foo/bar,
  20854. // or 'relative' like '../baz'
  20855. prefix = pattern.slice(0, n).join('/');
  20856. break
  20857. }
  20858. var remain = pattern.slice(n);
  20859. // get the list of entries.
  20860. var read;
  20861. if (prefix === null)
  20862. read = '.';
  20863. else if (pathIsAbsolute(prefix) || pathIsAbsolute(pattern.join('/'))) {
  20864. if (!prefix || !pathIsAbsolute(prefix))
  20865. prefix = '/' + prefix;
  20866. read = prefix;
  20867. } else
  20868. read = prefix;
  20869. var abs = this._makeAbs(read);
  20870. //if ignored, skip processing
  20871. if (childrenIgnored$1(this, read))
  20872. return
  20873. var isGlobStar = remain[0] === minimatch_1.GLOBSTAR;
  20874. if (isGlobStar)
  20875. this._processGlobStar(prefix, read, abs, remain, index, inGlobStar);
  20876. else
  20877. this._processReaddir(prefix, read, abs, remain, index, inGlobStar);
  20878. };
  20879. GlobSync$1.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) {
  20880. var entries = this._readdir(abs, inGlobStar);
  20881. // if the abs isn't a dir, then nothing can match!
  20882. if (!entries)
  20883. return
  20884. // It will only match dot entries if it starts with a dot, or if
  20885. // dot is set. Stuff like @(.foo|.bar) isn't allowed.
  20886. var pn = remain[0];
  20887. var negate = !!this.minimatch.negate;
  20888. var rawGlob = pn._glob;
  20889. var dotOk = this.dot || rawGlob.charAt(0) === '.';
  20890. var matchedEntries = [];
  20891. for (var i = 0; i < entries.length; i++) {
  20892. var e = entries[i];
  20893. if (e.charAt(0) !== '.' || dotOk) {
  20894. var m;
  20895. if (negate && !prefix) {
  20896. m = !e.match(pn);
  20897. } else {
  20898. m = e.match(pn);
  20899. }
  20900. if (m)
  20901. matchedEntries.push(e);
  20902. }
  20903. }
  20904. var len = matchedEntries.length;
  20905. // If there are no matched entries, then nothing matches.
  20906. if (len === 0)
  20907. return
  20908. // if this is the last remaining pattern bit, then no need for
  20909. // an additional stat *unless* the user has specified mark or
  20910. // stat explicitly. We know they exist, since readdir returned
  20911. // them.
  20912. if (remain.length === 1 && !this.mark && !this.stat) {
  20913. if (!this.matches[index])
  20914. this.matches[index] = Object.create(null);
  20915. for (var i = 0; i < len; i ++) {
  20916. var e = matchedEntries[i];
  20917. if (prefix) {
  20918. if (prefix.slice(-1) !== '/')
  20919. e = prefix + '/' + e;
  20920. else
  20921. e = prefix + e;
  20922. }
  20923. if (e.charAt(0) === '/' && !this.nomount) {
  20924. e = path__default['default'].join(this.root, e);
  20925. }
  20926. this._emitMatch(index, e);
  20927. }
  20928. // This was the last one, and no stats were needed
  20929. return
  20930. }
  20931. // now test all matched entries as stand-ins for that part
  20932. // of the pattern.
  20933. remain.shift();
  20934. for (var i = 0; i < len; i ++) {
  20935. var e = matchedEntries[i];
  20936. var newPattern;
  20937. if (prefix)
  20938. newPattern = [prefix, e];
  20939. else
  20940. newPattern = [e];
  20941. this._process(newPattern.concat(remain), index, inGlobStar);
  20942. }
  20943. };
  20944. GlobSync$1.prototype._emitMatch = function (index, e) {
  20945. if (isIgnored$1(this, e))
  20946. return
  20947. var abs = this._makeAbs(e);
  20948. if (this.mark)
  20949. e = this._mark(e);
  20950. if (this.absolute) {
  20951. e = abs;
  20952. }
  20953. if (this.matches[index][e])
  20954. return
  20955. if (this.nodir) {
  20956. var c = this.cache[abs];
  20957. if (c === 'DIR' || Array.isArray(c))
  20958. return
  20959. }
  20960. this.matches[index][e] = true;
  20961. if (this.stat)
  20962. this._stat(e);
  20963. };
  20964. GlobSync$1.prototype._readdirInGlobStar = function (abs) {
  20965. // follow all symlinked directories forever
  20966. // just proceed as if this is a non-globstar situation
  20967. if (this.follow)
  20968. return this._readdir(abs, false)
  20969. var entries;
  20970. var lstat;
  20971. try {
  20972. lstat = fs__default['default'].lstatSync(abs);
  20973. } catch (er) {
  20974. if (er.code === 'ENOENT') {
  20975. // lstat failed, doesn't exist
  20976. return null
  20977. }
  20978. }
  20979. var isSym = lstat && lstat.isSymbolicLink();
  20980. this.symlinks[abs] = isSym;
  20981. // If it's not a symlink or a dir, then it's definitely a regular file.
  20982. // don't bother doing a readdir in that case.
  20983. if (!isSym && lstat && !lstat.isDirectory())
  20984. this.cache[abs] = 'FILE';
  20985. else
  20986. entries = this._readdir(abs, false);
  20987. return entries
  20988. };
  20989. GlobSync$1.prototype._readdir = function (abs, inGlobStar) {
  20990. if (inGlobStar && !ownProp$1(this.symlinks, abs))
  20991. return this._readdirInGlobStar(abs)
  20992. if (ownProp$1(this.cache, abs)) {
  20993. var c = this.cache[abs];
  20994. if (!c || c === 'FILE')
  20995. return null
  20996. if (Array.isArray(c))
  20997. return c
  20998. }
  20999. try {
  21000. return this._readdirEntries(abs, fs__default['default'].readdirSync(abs))
  21001. } catch (er) {
  21002. this._readdirError(abs, er);
  21003. return null
  21004. }
  21005. };
  21006. GlobSync$1.prototype._readdirEntries = function (abs, entries) {
  21007. // if we haven't asked to stat everything, then just
  21008. // assume that everything in there exists, so we can avoid
  21009. // having to stat it a second time.
  21010. if (!this.mark && !this.stat) {
  21011. for (var i = 0; i < entries.length; i ++) {
  21012. var e = entries[i];
  21013. if (abs === '/')
  21014. e = abs + e;
  21015. else
  21016. e = abs + '/' + e;
  21017. this.cache[e] = true;
  21018. }
  21019. }
  21020. this.cache[abs] = entries;
  21021. // mark and cache dir-ness
  21022. return entries
  21023. };
  21024. GlobSync$1.prototype._readdirError = function (f, er) {
  21025. // handle errors, and cache the information
  21026. switch (er.code) {
  21027. case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
  21028. case 'ENOTDIR': // totally normal. means it *does* exist.
  21029. var abs = this._makeAbs(f);
  21030. this.cache[abs] = 'FILE';
  21031. if (abs === this.cwdAbs) {
  21032. var error = new Error(er.code + ' invalid cwd ' + this.cwd);
  21033. error.path = this.cwd;
  21034. error.code = er.code;
  21035. throw error
  21036. }
  21037. break
  21038. case 'ENOENT': // not terribly unusual
  21039. case 'ELOOP':
  21040. case 'ENAMETOOLONG':
  21041. case 'UNKNOWN':
  21042. this.cache[this._makeAbs(f)] = false;
  21043. break
  21044. default: // some unusual error. Treat as failure.
  21045. this.cache[this._makeAbs(f)] = false;
  21046. if (this.strict)
  21047. throw er
  21048. if (!this.silent)
  21049. console.error('glob error', er);
  21050. break
  21051. }
  21052. };
  21053. GlobSync$1.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) {
  21054. var entries = this._readdir(abs, inGlobStar);
  21055. // no entries means not a dir, so it can never have matches
  21056. // foo.txt/** doesn't match foo.txt
  21057. if (!entries)
  21058. return
  21059. // test without the globstar, and with every child both below
  21060. // and replacing the globstar.
  21061. var remainWithoutGlobStar = remain.slice(1);
  21062. var gspref = prefix ? [ prefix ] : [];
  21063. var noGlobStar = gspref.concat(remainWithoutGlobStar);
  21064. // the noGlobStar pattern exits the inGlobStar state
  21065. this._process(noGlobStar, index, false);
  21066. var len = entries.length;
  21067. var isSym = this.symlinks[abs];
  21068. // If it's a symlink, and we're in a globstar, then stop
  21069. if (isSym && inGlobStar)
  21070. return
  21071. for (var i = 0; i < len; i++) {
  21072. var e = entries[i];
  21073. if (e.charAt(0) === '.' && !this.dot)
  21074. continue
  21075. // these two cases enter the inGlobStar state
  21076. var instead = gspref.concat(entries[i], remainWithoutGlobStar);
  21077. this._process(instead, index, true);
  21078. var below = gspref.concat(entries[i], remain);
  21079. this._process(below, index, true);
  21080. }
  21081. };
  21082. GlobSync$1.prototype._processSimple = function (prefix, index) {
  21083. // XXX review this. Shouldn't it be doing the mounting etc
  21084. // before doing stat? kinda weird?
  21085. var exists = this._stat(prefix);
  21086. if (!this.matches[index])
  21087. this.matches[index] = Object.create(null);
  21088. // If it doesn't exist, then just mark the lack of results
  21089. if (!exists)
  21090. return
  21091. if (prefix && pathIsAbsolute(prefix) && !this.nomount) {
  21092. var trail = /[\/\\]$/.test(prefix);
  21093. if (prefix.charAt(0) === '/') {
  21094. prefix = path__default['default'].join(this.root, prefix);
  21095. } else {
  21096. prefix = path__default['default'].resolve(this.root, prefix);
  21097. if (trail)
  21098. prefix += '/';
  21099. }
  21100. }
  21101. if (process.platform === 'win32')
  21102. prefix = prefix.replace(/\\/g, '/');
  21103. // Mark this as a match
  21104. this._emitMatch(index, prefix);
  21105. };
  21106. // Returns either 'DIR', 'FILE', or false
  21107. GlobSync$1.prototype._stat = function (f) {
  21108. var abs = this._makeAbs(f);
  21109. var needDir = f.slice(-1) === '/';
  21110. if (f.length > this.maxLength)
  21111. return false
  21112. if (!this.stat && ownProp$1(this.cache, abs)) {
  21113. var c = this.cache[abs];
  21114. if (Array.isArray(c))
  21115. c = 'DIR';
  21116. // It exists, but maybe not how we need it
  21117. if (!needDir || c === 'DIR')
  21118. return c
  21119. if (needDir && c === 'FILE')
  21120. return false
  21121. // otherwise we have to stat, because maybe c=true
  21122. // if we know it exists, but not what it is.
  21123. }
  21124. var stat = this.statCache[abs];
  21125. if (!stat) {
  21126. var lstat;
  21127. try {
  21128. lstat = fs__default['default'].lstatSync(abs);
  21129. } catch (er) {
  21130. if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
  21131. this.statCache[abs] = false;
  21132. return false
  21133. }
  21134. }
  21135. if (lstat && lstat.isSymbolicLink()) {
  21136. try {
  21137. stat = fs__default['default'].statSync(abs);
  21138. } catch (er) {
  21139. stat = lstat;
  21140. }
  21141. } else {
  21142. stat = lstat;
  21143. }
  21144. }
  21145. this.statCache[abs] = stat;
  21146. var c = true;
  21147. if (stat)
  21148. c = stat.isDirectory() ? 'DIR' : 'FILE';
  21149. this.cache[abs] = this.cache[abs] || c;
  21150. if (needDir && c === 'FILE')
  21151. return false
  21152. return c
  21153. };
  21154. GlobSync$1.prototype._mark = function (p) {
  21155. return common.mark(this, p)
  21156. };
  21157. GlobSync$1.prototype._makeAbs = function (f) {
  21158. return common.makeAbs(this, f)
  21159. };
  21160. // Returns a wrapper function that returns a wrapped callback
  21161. // The wrapper function should do some stuff, and return a
  21162. // presumably different callback function.
  21163. // This makes sure that own properties are retained, so that
  21164. // decorations and such are not lost along the way.
  21165. var wrappy_1 = wrappy;
  21166. function wrappy (fn, cb) {
  21167. if (fn && cb) return wrappy(fn)(cb)
  21168. if (typeof fn !== 'function')
  21169. throw new TypeError('need wrapper function')
  21170. Object.keys(fn).forEach(function (k) {
  21171. wrapper[k] = fn[k];
  21172. });
  21173. return wrapper
  21174. function wrapper() {
  21175. var args = new Array(arguments.length);
  21176. for (var i = 0; i < args.length; i++) {
  21177. args[i] = arguments[i];
  21178. }
  21179. var ret = fn.apply(this, args);
  21180. var cb = args[args.length-1];
  21181. if (typeof ret === 'function' && ret !== cb) {
  21182. Object.keys(cb).forEach(function (k) {
  21183. ret[k] = cb[k];
  21184. });
  21185. }
  21186. return ret
  21187. }
  21188. }
  21189. var once_1 = wrappy_1(once);
  21190. var strict = wrappy_1(onceStrict);
  21191. once.proto = once(function () {
  21192. Object.defineProperty(Function.prototype, 'once', {
  21193. value: function () {
  21194. return once(this)
  21195. },
  21196. configurable: true
  21197. });
  21198. Object.defineProperty(Function.prototype, 'onceStrict', {
  21199. value: function () {
  21200. return onceStrict(this)
  21201. },
  21202. configurable: true
  21203. });
  21204. });
  21205. function once (fn) {
  21206. var f = function () {
  21207. if (f.called) return f.value
  21208. f.called = true;
  21209. return f.value = fn.apply(this, arguments)
  21210. };
  21211. f.called = false;
  21212. return f
  21213. }
  21214. function onceStrict (fn) {
  21215. var f = function () {
  21216. if (f.called)
  21217. throw new Error(f.onceError)
  21218. f.called = true;
  21219. return f.value = fn.apply(this, arguments)
  21220. };
  21221. var name = fn.name || 'Function wrapped with `once`';
  21222. f.onceError = name + " shouldn't be called more than once";
  21223. f.called = false;
  21224. return f
  21225. }
  21226. once_1.strict = strict;
  21227. var reqs = Object.create(null);
  21228. var inflight_1 = wrappy_1(inflight);
  21229. function inflight (key, cb) {
  21230. if (reqs[key]) {
  21231. reqs[key].push(cb);
  21232. return null
  21233. } else {
  21234. reqs[key] = [cb];
  21235. return makeres(key)
  21236. }
  21237. }
  21238. function makeres (key) {
  21239. return once_1(function RES () {
  21240. var cbs = reqs[key];
  21241. var len = cbs.length;
  21242. var args = slice(arguments);
  21243. // XXX It's somewhat ambiguous whether a new callback added in this
  21244. // pass should be queued for later execution if something in the
  21245. // list of callbacks throws, or if it should just be discarded.
  21246. // However, it's such an edge case that it hardly matters, and either
  21247. // choice is likely as surprising as the other.
  21248. // As it happens, we do go ahead and schedule it for later execution.
  21249. try {
  21250. for (var i = 0; i < len; i++) {
  21251. cbs[i].apply(null, args);
  21252. }
  21253. } finally {
  21254. if (cbs.length > len) {
  21255. // added more in the interim.
  21256. // de-zalgo, just in case, but don't call again.
  21257. cbs.splice(0, len);
  21258. process.nextTick(function () {
  21259. RES.apply(null, args);
  21260. });
  21261. } else {
  21262. delete reqs[key];
  21263. }
  21264. }
  21265. })
  21266. }
  21267. function slice (args) {
  21268. var length = args.length;
  21269. var array = [];
  21270. for (var i = 0; i < length; i++) array[i] = args[i];
  21271. return array
  21272. }
  21273. var EE = require$$0__default$1['default'].EventEmitter;
  21274. var setopts = common.setopts;
  21275. var ownProp = common.ownProp;
  21276. var childrenIgnored = common.childrenIgnored;
  21277. var isIgnored = common.isIgnored;
  21278. var GlobSync = sync.GlobSync;
  21279. inherits(Glob, EE);
  21280. function Glob (pattern, options, cb) {
  21281. if (typeof options === 'function') {
  21282. cb = options;
  21283. options = null;
  21284. }
  21285. if (options && options.sync) {
  21286. if (cb)
  21287. throw new TypeError('callback provided to sync glob')
  21288. return new GlobSync(pattern, options)
  21289. }
  21290. if (!(this instanceof Glob))
  21291. return new Glob(pattern, options, cb)
  21292. setopts(this, pattern, options);
  21293. this._didRealPath = false;
  21294. // process each pattern in the minimatch set
  21295. var n = this.minimatch.set.length;
  21296. // The matches are stored as {<filename>: true,...} so that
  21297. // duplicates are automagically pruned.
  21298. // Later, we do an Object.keys() on these.
  21299. // Keep them as a list so we can fill in when nonull is set.
  21300. this.matches = new Array(n);
  21301. if (typeof cb === 'function') {
  21302. cb = once_1(cb);
  21303. this.on('error', cb);
  21304. this.on('end', function (matches) {
  21305. cb(null, matches);
  21306. });
  21307. }
  21308. var self = this;
  21309. this._processing = 0;
  21310. this._emitQueue = [];
  21311. this._processQueue = [];
  21312. this.paused = false;
  21313. if (this.noprocess)
  21314. return this
  21315. if (n === 0)
  21316. return done()
  21317. var sync = true;
  21318. for (var i = 0; i < n; i ++) {
  21319. this._process(this.minimatch.set[i], i, false, done);
  21320. }
  21321. sync = false;
  21322. function done () {
  21323. --self._processing;
  21324. if (self._processing <= 0) {
  21325. if (sync) {
  21326. process.nextTick(function () {
  21327. self._finish();
  21328. });
  21329. } else {
  21330. self._finish();
  21331. }
  21332. }
  21333. }
  21334. }
  21335. Glob.prototype._finish = function () {
  21336. assert__default['default'](this instanceof Glob);
  21337. if (this.aborted)
  21338. return
  21339. if (this.realpath && !this._didRealpath)
  21340. return this._realpath()
  21341. common.finish(this);
  21342. this.emit('end', this.found);
  21343. };
  21344. Glob.prototype._realpath = function () {
  21345. if (this._didRealpath)
  21346. return
  21347. this._didRealpath = true;
  21348. var n = this.matches.length;
  21349. if (n === 0)
  21350. return this._finish()
  21351. var self = this;
  21352. for (var i = 0; i < this.matches.length; i++)
  21353. this._realpathSet(i, next);
  21354. function next () {
  21355. if (--n === 0)
  21356. self._finish();
  21357. }
  21358. };
  21359. Glob.prototype._realpathSet = function (index, cb) {
  21360. var matchset = this.matches[index];
  21361. if (!matchset)
  21362. return cb()
  21363. var found = Object.keys(matchset);
  21364. var self = this;
  21365. var n = found.length;
  21366. if (n === 0)
  21367. return cb()
  21368. var set = this.matches[index] = Object.create(null);
  21369. found.forEach(function (p, i) {
  21370. // If there's a problem with the stat, then it means that
  21371. // one or more of the links in the realpath couldn't be
  21372. // resolved. just return the abs value in that case.
  21373. p = self._makeAbs(p);
  21374. fs_realpath.realpath(p, self.realpathCache, function (er, real) {
  21375. if (!er)
  21376. set[real] = true;
  21377. else if (er.syscall === 'stat')
  21378. set[p] = true;
  21379. else
  21380. self.emit('error', er); // srsly wtf right here
  21381. if (--n === 0) {
  21382. self.matches[index] = set;
  21383. cb();
  21384. }
  21385. });
  21386. });
  21387. };
  21388. Glob.prototype._mark = function (p) {
  21389. return common.mark(this, p)
  21390. };
  21391. Glob.prototype._makeAbs = function (f) {
  21392. return common.makeAbs(this, f)
  21393. };
  21394. Glob.prototype.abort = function () {
  21395. this.aborted = true;
  21396. this.emit('abort');
  21397. };
  21398. Glob.prototype.pause = function () {
  21399. if (!this.paused) {
  21400. this.paused = true;
  21401. this.emit('pause');
  21402. }
  21403. };
  21404. Glob.prototype.resume = function () {
  21405. if (this.paused) {
  21406. this.emit('resume');
  21407. this.paused = false;
  21408. if (this._emitQueue.length) {
  21409. var eq = this._emitQueue.slice(0);
  21410. this._emitQueue.length = 0;
  21411. for (var i = 0; i < eq.length; i ++) {
  21412. var e = eq[i];
  21413. this._emitMatch(e[0], e[1]);
  21414. }
  21415. }
  21416. if (this._processQueue.length) {
  21417. var pq = this._processQueue.slice(0);
  21418. this._processQueue.length = 0;
  21419. for (var i = 0; i < pq.length; i ++) {
  21420. var p = pq[i];
  21421. this._processing--;
  21422. this._process(p[0], p[1], p[2], p[3]);
  21423. }
  21424. }
  21425. }
  21426. };
  21427. Glob.prototype._process = function (pattern, index, inGlobStar, cb) {
  21428. assert__default['default'](this instanceof Glob);
  21429. assert__default['default'](typeof cb === 'function');
  21430. if (this.aborted)
  21431. return
  21432. this._processing++;
  21433. if (this.paused) {
  21434. this._processQueue.push([pattern, index, inGlobStar, cb]);
  21435. return
  21436. }
  21437. //console.error('PROCESS %d', this._processing, pattern)
  21438. // Get the first [n] parts of pattern that are all strings.
  21439. var n = 0;
  21440. while (typeof pattern[n] === 'string') {
  21441. n ++;
  21442. }
  21443. // now n is the index of the first one that is *not* a string.
  21444. // see if there's anything else
  21445. var prefix;
  21446. switch (n) {
  21447. // if not, then this is rather simple
  21448. case pattern.length:
  21449. this._processSimple(pattern.join('/'), index, cb);
  21450. return
  21451. case 0:
  21452. // pattern *starts* with some non-trivial item.
  21453. // going to readdir(cwd), but not include the prefix in matches.
  21454. prefix = null;
  21455. break
  21456. default:
  21457. // pattern has some string bits in the front.
  21458. // whatever it starts with, whether that's 'absolute' like /foo/bar,
  21459. // or 'relative' like '../baz'
  21460. prefix = pattern.slice(0, n).join('/');
  21461. break
  21462. }
  21463. var remain = pattern.slice(n);
  21464. // get the list of entries.
  21465. var read;
  21466. if (prefix === null)
  21467. read = '.';
  21468. else if (pathIsAbsolute(prefix) || pathIsAbsolute(pattern.join('/'))) {
  21469. if (!prefix || !pathIsAbsolute(prefix))
  21470. prefix = '/' + prefix;
  21471. read = prefix;
  21472. } else
  21473. read = prefix;
  21474. var abs = this._makeAbs(read);
  21475. //if ignored, skip _processing
  21476. if (childrenIgnored(this, read))
  21477. return cb()
  21478. var isGlobStar = remain[0] === minimatch_1.GLOBSTAR;
  21479. if (isGlobStar)
  21480. this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb);
  21481. else
  21482. this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb);
  21483. };
  21484. Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) {
  21485. var self = this;
  21486. this._readdir(abs, inGlobStar, function (er, entries) {
  21487. return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb)
  21488. });
  21489. };
  21490. Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
  21491. // if the abs isn't a dir, then nothing can match!
  21492. if (!entries)
  21493. return cb()
  21494. // It will only match dot entries if it starts with a dot, or if
  21495. // dot is set. Stuff like @(.foo|.bar) isn't allowed.
  21496. var pn = remain[0];
  21497. var negate = !!this.minimatch.negate;
  21498. var rawGlob = pn._glob;
  21499. var dotOk = this.dot || rawGlob.charAt(0) === '.';
  21500. var matchedEntries = [];
  21501. for (var i = 0; i < entries.length; i++) {
  21502. var e = entries[i];
  21503. if (e.charAt(0) !== '.' || dotOk) {
  21504. var m;
  21505. if (negate && !prefix) {
  21506. m = !e.match(pn);
  21507. } else {
  21508. m = e.match(pn);
  21509. }
  21510. if (m)
  21511. matchedEntries.push(e);
  21512. }
  21513. }
  21514. //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries)
  21515. var len = matchedEntries.length;
  21516. // If there are no matched entries, then nothing matches.
  21517. if (len === 0)
  21518. return cb()
  21519. // if this is the last remaining pattern bit, then no need for
  21520. // an additional stat *unless* the user has specified mark or
  21521. // stat explicitly. We know they exist, since readdir returned
  21522. // them.
  21523. if (remain.length === 1 && !this.mark && !this.stat) {
  21524. if (!this.matches[index])
  21525. this.matches[index] = Object.create(null);
  21526. for (var i = 0; i < len; i ++) {
  21527. var e = matchedEntries[i];
  21528. if (prefix) {
  21529. if (prefix !== '/')
  21530. e = prefix + '/' + e;
  21531. else
  21532. e = prefix + e;
  21533. }
  21534. if (e.charAt(0) === '/' && !this.nomount) {
  21535. e = path__default['default'].join(this.root, e);
  21536. }
  21537. this._emitMatch(index, e);
  21538. }
  21539. // This was the last one, and no stats were needed
  21540. return cb()
  21541. }
  21542. // now test all matched entries as stand-ins for that part
  21543. // of the pattern.
  21544. remain.shift();
  21545. for (var i = 0; i < len; i ++) {
  21546. var e = matchedEntries[i];
  21547. if (prefix) {
  21548. if (prefix !== '/')
  21549. e = prefix + '/' + e;
  21550. else
  21551. e = prefix + e;
  21552. }
  21553. this._process([e].concat(remain), index, inGlobStar, cb);
  21554. }
  21555. cb();
  21556. };
  21557. Glob.prototype._emitMatch = function (index, e) {
  21558. if (this.aborted)
  21559. return
  21560. if (isIgnored(this, e))
  21561. return
  21562. if (this.paused) {
  21563. this._emitQueue.push([index, e]);
  21564. return
  21565. }
  21566. var abs = pathIsAbsolute(e) ? e : this._makeAbs(e);
  21567. if (this.mark)
  21568. e = this._mark(e);
  21569. if (this.absolute)
  21570. e = abs;
  21571. if (this.matches[index][e])
  21572. return
  21573. if (this.nodir) {
  21574. var c = this.cache[abs];
  21575. if (c === 'DIR' || Array.isArray(c))
  21576. return
  21577. }
  21578. this.matches[index][e] = true;
  21579. var st = this.statCache[abs];
  21580. if (st)
  21581. this.emit('stat', e, st);
  21582. this.emit('match', e);
  21583. };
  21584. Glob.prototype._readdirInGlobStar = function (abs, cb) {
  21585. if (this.aborted)
  21586. return
  21587. // follow all symlinked directories forever
  21588. // just proceed as if this is a non-globstar situation
  21589. if (this.follow)
  21590. return this._readdir(abs, false, cb)
  21591. var lstatkey = 'lstat\0' + abs;
  21592. var self = this;
  21593. var lstatcb = inflight_1(lstatkey, lstatcb_);
  21594. if (lstatcb)
  21595. fs__default['default'].lstat(abs, lstatcb);
  21596. function lstatcb_ (er, lstat) {
  21597. if (er && er.code === 'ENOENT')
  21598. return cb()
  21599. var isSym = lstat && lstat.isSymbolicLink();
  21600. self.symlinks[abs] = isSym;
  21601. // If it's not a symlink or a dir, then it's definitely a regular file.
  21602. // don't bother doing a readdir in that case.
  21603. if (!isSym && lstat && !lstat.isDirectory()) {
  21604. self.cache[abs] = 'FILE';
  21605. cb();
  21606. } else
  21607. self._readdir(abs, false, cb);
  21608. }
  21609. };
  21610. Glob.prototype._readdir = function (abs, inGlobStar, cb) {
  21611. if (this.aborted)
  21612. return
  21613. cb = inflight_1('readdir\0'+abs+'\0'+inGlobStar, cb);
  21614. if (!cb)
  21615. return
  21616. //console.error('RD %j %j', +inGlobStar, abs)
  21617. if (inGlobStar && !ownProp(this.symlinks, abs))
  21618. return this._readdirInGlobStar(abs, cb)
  21619. if (ownProp(this.cache, abs)) {
  21620. var c = this.cache[abs];
  21621. if (!c || c === 'FILE')
  21622. return cb()
  21623. if (Array.isArray(c))
  21624. return cb(null, c)
  21625. }
  21626. fs__default['default'].readdir(abs, readdirCb(this, abs, cb));
  21627. };
  21628. function readdirCb (self, abs, cb) {
  21629. return function (er, entries) {
  21630. if (er)
  21631. self._readdirError(abs, er, cb);
  21632. else
  21633. self._readdirEntries(abs, entries, cb);
  21634. }
  21635. }
  21636. Glob.prototype._readdirEntries = function (abs, entries, cb) {
  21637. if (this.aborted)
  21638. return
  21639. // if we haven't asked to stat everything, then just
  21640. // assume that everything in there exists, so we can avoid
  21641. // having to stat it a second time.
  21642. if (!this.mark && !this.stat) {
  21643. for (var i = 0; i < entries.length; i ++) {
  21644. var e = entries[i];
  21645. if (abs === '/')
  21646. e = abs + e;
  21647. else
  21648. e = abs + '/' + e;
  21649. this.cache[e] = true;
  21650. }
  21651. }
  21652. this.cache[abs] = entries;
  21653. return cb(null, entries)
  21654. };
  21655. Glob.prototype._readdirError = function (f, er, cb) {
  21656. if (this.aborted)
  21657. return
  21658. // handle errors, and cache the information
  21659. switch (er.code) {
  21660. case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
  21661. case 'ENOTDIR': // totally normal. means it *does* exist.
  21662. var abs = this._makeAbs(f);
  21663. this.cache[abs] = 'FILE';
  21664. if (abs === this.cwdAbs) {
  21665. var error = new Error(er.code + ' invalid cwd ' + this.cwd);
  21666. error.path = this.cwd;
  21667. error.code = er.code;
  21668. this.emit('error', error);
  21669. this.abort();
  21670. }
  21671. break
  21672. case 'ENOENT': // not terribly unusual
  21673. case 'ELOOP':
  21674. case 'ENAMETOOLONG':
  21675. case 'UNKNOWN':
  21676. this.cache[this._makeAbs(f)] = false;
  21677. break
  21678. default: // some unusual error. Treat as failure.
  21679. this.cache[this._makeAbs(f)] = false;
  21680. if (this.strict) {
  21681. this.emit('error', er);
  21682. // If the error is handled, then we abort
  21683. // if not, we threw out of here
  21684. this.abort();
  21685. }
  21686. if (!this.silent)
  21687. console.error('glob error', er);
  21688. break
  21689. }
  21690. return cb()
  21691. };
  21692. Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) {
  21693. var self = this;
  21694. this._readdir(abs, inGlobStar, function (er, entries) {
  21695. self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb);
  21696. });
  21697. };
  21698. Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
  21699. //console.error('pgs2', prefix, remain[0], entries)
  21700. // no entries means not a dir, so it can never have matches
  21701. // foo.txt/** doesn't match foo.txt
  21702. if (!entries)
  21703. return cb()
  21704. // test without the globstar, and with every child both below
  21705. // and replacing the globstar.
  21706. var remainWithoutGlobStar = remain.slice(1);
  21707. var gspref = prefix ? [ prefix ] : [];
  21708. var noGlobStar = gspref.concat(remainWithoutGlobStar);
  21709. // the noGlobStar pattern exits the inGlobStar state
  21710. this._process(noGlobStar, index, false, cb);
  21711. var isSym = this.symlinks[abs];
  21712. var len = entries.length;
  21713. // If it's a symlink, and we're in a globstar, then stop
  21714. if (isSym && inGlobStar)
  21715. return cb()
  21716. for (var i = 0; i < len; i++) {
  21717. var e = entries[i];
  21718. if (e.charAt(0) === '.' && !this.dot)
  21719. continue
  21720. // these two cases enter the inGlobStar state
  21721. var instead = gspref.concat(entries[i], remainWithoutGlobStar);
  21722. this._process(instead, index, true, cb);
  21723. var below = gspref.concat(entries[i], remain);
  21724. this._process(below, index, true, cb);
  21725. }
  21726. cb();
  21727. };
  21728. Glob.prototype._processSimple = function (prefix, index, cb) {
  21729. // XXX review this. Shouldn't it be doing the mounting etc
  21730. // before doing stat? kinda weird?
  21731. var self = this;
  21732. this._stat(prefix, function (er, exists) {
  21733. self._processSimple2(prefix, index, er, exists, cb);
  21734. });
  21735. };
  21736. Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) {
  21737. //console.error('ps2', prefix, exists)
  21738. if (!this.matches[index])
  21739. this.matches[index] = Object.create(null);
  21740. // If it doesn't exist, then just mark the lack of results
  21741. if (!exists)
  21742. return cb()
  21743. if (prefix && pathIsAbsolute(prefix) && !this.nomount) {
  21744. var trail = /[\/\\]$/.test(prefix);
  21745. if (prefix.charAt(0) === '/') {
  21746. prefix = path__default['default'].join(this.root, prefix);
  21747. } else {
  21748. prefix = path__default['default'].resolve(this.root, prefix);
  21749. if (trail)
  21750. prefix += '/';
  21751. }
  21752. }
  21753. if (process.platform === 'win32')
  21754. prefix = prefix.replace(/\\/g, '/');
  21755. // Mark this as a match
  21756. this._emitMatch(index, prefix);
  21757. cb();
  21758. };
  21759. // Returns either 'DIR', 'FILE', or false
  21760. Glob.prototype._stat = function (f, cb) {
  21761. var abs = this._makeAbs(f);
  21762. var needDir = f.slice(-1) === '/';
  21763. if (f.length > this.maxLength)
  21764. return cb()
  21765. if (!this.stat && ownProp(this.cache, abs)) {
  21766. var c = this.cache[abs];
  21767. if (Array.isArray(c))
  21768. c = 'DIR';
  21769. // It exists, but maybe not how we need it
  21770. if (!needDir || c === 'DIR')
  21771. return cb(null, c)
  21772. if (needDir && c === 'FILE')
  21773. return cb()
  21774. // otherwise we have to stat, because maybe c=true
  21775. // if we know it exists, but not what it is.
  21776. }
  21777. var stat = this.statCache[abs];
  21778. if (stat !== undefined) {
  21779. if (stat === false)
  21780. return cb(null, stat)
  21781. else {
  21782. var type = stat.isDirectory() ? 'DIR' : 'FILE';
  21783. if (needDir && type === 'FILE')
  21784. return cb()
  21785. else
  21786. return cb(null, type, stat)
  21787. }
  21788. }
  21789. var self = this;
  21790. var statcb = inflight_1('stat\0' + abs, lstatcb_);
  21791. if (statcb)
  21792. fs__default['default'].lstat(abs, statcb);
  21793. function lstatcb_ (er, lstat) {
  21794. if (lstat && lstat.isSymbolicLink()) {
  21795. // If it's a symlink, then treat it as the target, unless
  21796. // the target does not exist, then treat it as a file.
  21797. return fs__default['default'].stat(abs, function (er, stat) {
  21798. if (er)
  21799. self._stat2(f, abs, null, lstat, cb);
  21800. else
  21801. self._stat2(f, abs, er, stat, cb);
  21802. })
  21803. } else {
  21804. self._stat2(f, abs, er, lstat, cb);
  21805. }
  21806. }
  21807. };
  21808. Glob.prototype._stat2 = function (f, abs, er, stat, cb) {
  21809. if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
  21810. this.statCache[abs] = false;
  21811. return cb()
  21812. }
  21813. var needDir = f.slice(-1) === '/';
  21814. this.statCache[abs] = stat;
  21815. if (abs.slice(-1) === '/' && stat && !stat.isDirectory())
  21816. return cb(null, false, stat)
  21817. var c = true;
  21818. if (stat)
  21819. c = stat.isDirectory() ? 'DIR' : 'FILE';
  21820. this.cache[abs] = this.cache[abs] || c;
  21821. if (needDir && c === 'FILE')
  21822. return cb()
  21823. return cb(null, c, stat)
  21824. };
  21825. var spawn = childProcess__default['default'].spawn;
  21826. var exec = childProcess__default['default'].exec;
  21827. var treeKill = function (pid, signal, callback) {
  21828. if (typeof signal === 'function' && callback === undefined) {
  21829. callback = signal;
  21830. signal = undefined;
  21831. }
  21832. pid = parseInt(pid);
  21833. if (Number.isNaN(pid)) {
  21834. if (callback) {
  21835. return callback(new Error("pid must be a number"));
  21836. } else {
  21837. throw new Error("pid must be a number");
  21838. }
  21839. }
  21840. var tree = {};
  21841. var pidsToProcess = {};
  21842. tree[pid] = [];
  21843. pidsToProcess[pid] = 1;
  21844. switch (process.platform) {
  21845. case 'win32':
  21846. exec('taskkill /pid ' + pid + ' /T /F', callback);
  21847. break;
  21848. case 'darwin':
  21849. buildProcessTree(pid, tree, pidsToProcess, function (parentPid) {
  21850. return spawn('pgrep', ['-P', parentPid]);
  21851. }, function () {
  21852. killAll(tree, signal, callback);
  21853. });
  21854. break;
  21855. // case 'sunos':
  21856. // buildProcessTreeSunOS(pid, tree, pidsToProcess, function () {
  21857. // killAll(tree, signal, callback);
  21858. // });
  21859. // break;
  21860. default: // Linux
  21861. buildProcessTree(pid, tree, pidsToProcess, function (parentPid) {
  21862. return spawn('ps', ['-o', 'pid', '--no-headers', '--ppid', parentPid]);
  21863. }, function () {
  21864. killAll(tree, signal, callback);
  21865. });
  21866. break;
  21867. }
  21868. };
  21869. function killAll (tree, signal, callback) {
  21870. var killed = {};
  21871. try {
  21872. Object.keys(tree).forEach(function (pid) {
  21873. tree[pid].forEach(function (pidpid) {
  21874. if (!killed[pidpid]) {
  21875. killPid(pidpid, signal);
  21876. killed[pidpid] = 1;
  21877. }
  21878. });
  21879. if (!killed[pid]) {
  21880. killPid(pid, signal);
  21881. killed[pid] = 1;
  21882. }
  21883. });
  21884. } catch (err) {
  21885. if (callback) {
  21886. return callback(err);
  21887. } else {
  21888. throw err;
  21889. }
  21890. }
  21891. if (callback) {
  21892. return callback();
  21893. }
  21894. }
  21895. function killPid(pid, signal) {
  21896. try {
  21897. process.kill(parseInt(pid, 10), signal);
  21898. }
  21899. catch (err) {
  21900. if (err.code !== 'ESRCH') throw err;
  21901. }
  21902. }
  21903. function buildProcessTree (parentPid, tree, pidsToProcess, spawnChildProcessesList, cb) {
  21904. var ps = spawnChildProcessesList(parentPid);
  21905. var allData = '';
  21906. ps.stdout.on('data', function (data) {
  21907. var data = data.toString('ascii');
  21908. allData += data;
  21909. });
  21910. var onClose = function (code) {
  21911. delete pidsToProcess[parentPid];
  21912. if (code != 0) {
  21913. // no more parent processes
  21914. if (Object.keys(pidsToProcess).length == 0) {
  21915. cb();
  21916. }
  21917. return;
  21918. }
  21919. allData.match(/\d+/g).forEach(function (pid) {
  21920. pid = parseInt(pid, 10);
  21921. tree[parentPid].push(pid);
  21922. tree[pid] = [];
  21923. pidsToProcess[pid] = 1;
  21924. buildProcessTree(pid, tree, pidsToProcess, spawnChildProcessesList, cb);
  21925. });
  21926. };
  21927. ps.on('close', onClose);
  21928. }
  21929. var any = bbhverse.any;
  21930. var Tasq = bbhverse.Tasq;
  21931. var statuslog = bbhverse.Traq;
  21932. var Traq = bbhverse.Traq;
  21933. Tasq.addlistener(statuslog.statuslog);
  21934. var nodeShellExec = cliverse.nodeShellExec;
  21935. const BUILD_VERSION = 'Version: 1.0.0 - built on August 23, 2021 14:13:43';
  21936. const runtimestamp = (new Date()).getTime();
  21937. function getVersion() { return BUILD_VERSION; }
  21938. console.log(getVersion());
  21939. // 'use strict';
  21940. // PB : TODO -- make sure folder context is proper coz we can now run elxr from anywhere.
  21941. // PB : TODO --
  21942. // runas bypass non elevated tasks when we request privelege
  21943. // runas message is always error needs to be fixed.
  21944. // runas wait needs to be parallelized.
  21945. // suppress elevation check error messages
  21946. // support runas lauched directly from shell.
  21947. // pass in environment in hta to shellexecute.
  21948. const { existsSync } = fs__default['default'];
  21949. const fs = fs__default['default'];
  21950. const cliargs = bbhverse.cliargs;
  21951. const processedArgs = cliargs(process.argv.slice(2));
  21952. console.dir(processedArgs);
  21953. var ENV = Object.assign({}, process.env); // Shallow clone it.
  21954. const { readdir } = fs__default['default'].promises;
  21955. // Directory shallow walk and do perform on each dir.
  21956. const dirs = async (perform, path) => {
  21957. for (const dir of await readdir(path || process.cwd(), { withFileTypes: true })) {
  21958. if (dir.isDirectory()) perform(dir);
  21959. }
  21960. };
  21961. var getShellTask = (command, args, options) => {
  21962. options = options || {};
  21963. return () => {
  21964. var p = nodeShellExec.apply(null, [command, args, Object.assign({
  21965. inherit: true, shell: true, env: ENV, title: `${command} ${args}`
  21966. }, options)
  21967. ]);
  21968. if (options.ignorefailures) {
  21969. return p.catch(e => {
  21970. // Ignore. Not a major error.
  21971. })
  21972. }
  21973. else return p;
  21974. }
  21975. };
  21976. var callsheltask = (args) => { return () => { return nodeShellExec.apply(null, args) } };
  21977. var getTaskCheckExists = (command, options) => {
  21978. options = options || {};
  21979. return () => {
  21980. var p = nodeShellExec.apply(null, ['where', [command]]);
  21981. if (options.ignorefailures) {
  21982. return p.then(() => { return true }).catch(e => { // Ignore. Not a major error.
  21983. return false;
  21984. })
  21985. }
  21986. else return p.then(() => { return true });
  21987. }
  21988. };
  21989. var getTaskWithElevation = function(tasdef){
  21990. return ()=>{
  21991. if (__isElevated) {
  21992. return tasdef.elevatedpulltasks().then(()=>{
  21993. // PB : TODO -- Every elevation should have its own messaging file. Async writes from multiple processes are a problem here...
  21994. fs.writeFileSync('run.done', 'success');
  21995. }).catch(e=>{
  21996. fs.writeFileSync('run.done', 'failure');
  21997. });
  21998. }
  21999. else {
  22000. // PB : TODO -- Rename op['runas'] to 'elevate'
  22001. var __runasresult = null;
  22002. return op['runas']().then((r) => { return __runasresult = r; })
  22003. .catch((e) => {
  22004. console.error(e);
  22005. })
  22006. .finally(() => {
  22007. if(__runasresult && !__runasresult.skipped) fs.unlinkSync('run.done');
  22008. if (!processedArgs.runas) { return tasdef.regularpulltasks(); }
  22009. })
  22010. }
  22011. }
  22012. };
  22013. var getTaskWithoutElevation = function(tasdef){
  22014. return ()=>{
  22015. if(!processedArgs.runas) { return tasdef.regularpulltasks(); }
  22016. }
  22017. };
  22018. var gitops = {
  22019. getdiscoverbranchcmd : function(repo){
  22020. var parameters = ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;'];
  22021. var cmd = [gitbash
  22022. , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  22023. , { cwd: instanceroot + '/' + repo, title: 'pull all origins for ' + repo + ' ' + parameters.join(' ') }];
  22024. return cmd
  22025. }
  22026. };
  22027. var getPullCmd = (repo, branch) => {
  22028. // console.log(useGitPull)var getPullCmd = (repo, branch) => {
  22029. // console.log(useGitPull)
  22030. // var pullCmd = [gitInstallDir
  22031. // , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  22032. // , { cwd: instanceroot + '/' + repo, title: 'pull all origins for ' + repo }]
  22033. if(branch) {
  22034. var parameters = ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;'];
  22035. var pullCmd = [ gitbash
  22036. , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  22037. , { cwd: instanceroot + '/' + repo, title : 'pull all origins for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }];
  22038. }
  22039. else {
  22040. console.warn('No branch was specified detecting from working client.');
  22041. // First check if working client exits.
  22042. // if (existsSync(instanceroot + '/' + repo)) {
  22043. var pullCmd = gitops.getdiscoverbranchcmd(repo);
  22044. // }
  22045. // else performpull
  22046. }
  22047. // var pullCmd = ['pullall', [], { cwd : repo }]
  22048. if (useGitPull) pullCmd = ['git', ['pull'], {
  22049. inherit: true, shell: true,
  22050. cwd: instanceroot + '/' + repo
  22051. // , env: process.env
  22052. , runas: processedArgs.runas
  22053. , title: `git pull ${repo}`
  22054. }];
  22055. return pullCmd
  22056. };
  22057. var performPull = (repo, branch) => {
  22058. // PB : TODO -- Handle no branch passed in case.
  22059. // if(!branch) { throw 'No branch specified' }
  22060. if (existsSync(instanceroot + '/' + repo)) {
  22061. var branchprint = branch ? ' branch :' + branch : '';
  22062. console.log('pulling ' + instanceroot + '/' + repo + branchprint );
  22063. return nodeShellExec.apply(null, getPullCmd(repo, branch)).then(() => {
  22064. if (__isElevated) {
  22065. fs.writeFileSync('run.log', ', ' + JSON.stringify({ repo, success: true }), { 'flag': 'a+' });
  22066. }
  22067. else statuslog.statuslog(null, repo);
  22068. return true;
  22069. })
  22070. .catch((e) => {
  22071. e.repo = repo;
  22072. if (__isElevated) {
  22073. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' });
  22074. }
  22075. else statuslog.statuslog(e); console.error(e);
  22076. })
  22077. }
  22078. else {
  22079. console.log('cloning ' + repo);
  22080. // PB : TODO -- detect if a clonable repo exists in currentGitAuthUser
  22081. return nodeShellExec('git', ['clone', '-c', 'core.symlinks=true', selectedinstance.reposerver + `/${defaultRepoOwner}/` + repo + '.git'],
  22082. {
  22083. inherit: true, shell: true,
  22084. env: process.env
  22085. , cwd : instanceroot
  22086. , runas: processedArgs.runas
  22087. }).catch((e) => {
  22088. throw e;
  22089. }).then(() => {
  22090. return nodeShellExec('git', ['config', '--replace-all', 'core.symlinks', true],
  22091. {
  22092. inherit: true, shell: true,
  22093. env: process.env
  22094. , cwd: instanceroot + '/' + repo
  22095. , runas: processedArgs.runas
  22096. , title: `git core.symlinks --replace-all true for ${selectedinstance.reposerver + `/${defaultRepoOwner}/` + repo + '.git'}`
  22097. })
  22098. .then(() => {
  22099. if (__isElevated) {
  22100. fs.writeFileSync('run.log', ', ' + JSON.stringify({ repo, success: true }), { 'flag': 'a+' });
  22101. }
  22102. else statuslog.statuslog(null, repo);
  22103. })
  22104. .catch((e) => {
  22105. e.repo = repo;
  22106. if (__isElevated) {
  22107. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' });
  22108. }
  22109. else statuslog.statuslog(e);
  22110. })
  22111. })
  22112. .catch(e => {
  22113. e.repo = repo;
  22114. if (__isElevated) {
  22115. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' });
  22116. }
  22117. else statuslog.statuslog(e);
  22118. })
  22119. }
  22120. };
  22121. // PB : TODO -- If we are run from an elevated shell it never moves forward and simply exits.
  22122. // -- Currently workaround is to always run from a non-elevated shell.
  22123. var __isElevated = null; // We assume non-Elevated until someone evaluates and sets this variable.
  22124. var acquireElevationState = () => {
  22125. if (__isElevated === null) {
  22126. return nodeShellExec("fsutil", ["dirty", "query", "C:"], {
  22127. inherit: true
  22128. // , shell: true
  22129. , stdio: 'ignore'
  22130. , env: process.env
  22131. , title: `check privileged execution mode using "fsutil dirty query C:"`
  22132. }).then((exitcode) => {
  22133. console.log('Elevated');
  22134. __isElevated = true;
  22135. return true;
  22136. }).catch(() => {
  22137. __isElevated = false;
  22138. console.log('Not Elevated');
  22139. return false;
  22140. });
  22141. }
  22142. else return Promise.resolve(__isElevated);
  22143. };
  22144. var repomanifest = null;
  22145. var defaultRepoOwner = 'chess';
  22146. var elevatedRunasRepos = null;
  22147. var gitRepos = null;
  22148. // grep -qxF 'alias elxr="node elxr/index.js"' ~/.bash_profile || echo 'alias elxr="node elxr/index.js"' >> ~/.bash_profile
  22149. // nodeShellExec('echo', ['elxr'], { inherit : true}) //, {stdio: "inherit"}
  22150. var dbForLabel = function (label) {
  22151. var dbsForLabel = {
  22152. devmysql: 'mysql'
  22153. , development: 'mssql'
  22154. , production: 'mssql'
  22155. };
  22156. return dbsForLabel[label] || 'mysql'
  22157. };
  22158. // SAM : TODO Use nodeshellexec where to detect git installation dir
  22159. var gitbash = "C:\\Program Files\\Git\\bin\\sh.exe";
  22160. // var gitbash = "G:\\Installed\\Git\\bin\\sh.exe"
  22161. // Relevant git repos
  22162. // var repomanifest = require('../'+repomanifest.instanceName+'-config-'+ nodeenv +'/repo-manifest')()
  22163. var exludeMergeRepos = [];
  22164. var useGitPull = processedArgs.useGitPull || false;
  22165. // elxr cli operations
  22166. var op = {
  22167. 'h': () => { console.log(elxr.help()); return '-h' }
  22168. , 'clean' : () => {
  22169. // delete all node_module folders and links.
  22170. var tasklist = [];
  22171. dirs( (repodir)=> tasklist.push(getShellTask('rm',['-rf', 'node_modules'], { cwd : instanceroot + '/' + repodir.name })()), instanceroot );
  22172. return Promise.all(tasklist)
  22173. }
  22174. , 'undefined': () => { return op.h(); }
  22175. , 'reset': () => {
  22176. // Reset NPM packages semver so major versions can be updated.
  22177. const fs = fs__default['default'];
  22178. const wipeDependencies = (__package) => {
  22179. const file = fs.readFileSync(__package + '/package.json');
  22180. const content = JSON.parse(file);
  22181. for (var devDep in content.devDependencies) {
  22182. if (content.devDependencies[devDep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  22183. content.devDependencies[devDep] = '*';
  22184. }
  22185. }
  22186. for (var dep in content.dependencies) {
  22187. if (content.dependencies[dep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  22188. content.dependencies[dep] = '*';
  22189. }
  22190. }
  22191. fs.writeFileSync(__package + '/package.json', JSON.stringify(content));
  22192. };
  22193. var repos = ['client'];
  22194. // repos = gitRepos;
  22195. repos.forEach(wipeDependencies);
  22196. // if (require.main === module) {
  22197. // } else {
  22198. // module.exports = wipeDependencies
  22199. // }
  22200. }
  22201. , 'upgrade': () => {
  22202. console.log('upgrade.......');
  22203. var tasks = [
  22204. () => {
  22205. var p = nodeShellExec('npm', ['i', '-g', 'npm-upgrade'], {
  22206. inherit: true, shell: true
  22207. , env: process.env
  22208. }).catch((e) => { console.error(e); });
  22209. p.position = 1;
  22210. console.log('One');
  22211. return p;
  22212. }
  22213. , () => {
  22214. var p = nodeShellExec('npm', ['cache', 'clean', '-f'], {
  22215. inherit: true, shell: true
  22216. , env: process.env
  22217. }).catch((e) => { console.error(e); });
  22218. p.position = 2;
  22219. console.log('Two');
  22220. return p;
  22221. }
  22222. , () => {
  22223. var p = nodeShellExec('npm', ['install', '-g', 'n'], {
  22224. inherit: true, shell: true
  22225. , env: process.env
  22226. }).catch((e) => { console.error(e); });
  22227. p.position = 3;
  22228. console.log('Three');
  22229. return p;
  22230. }
  22231. , () => {
  22232. var p = nodeShellExec('n', ['latest'], {
  22233. inherit: true, shell: true
  22234. , env: process.env
  22235. }).catch((e) => { console.error(e); });
  22236. p.position = 4;
  22237. console.log('Four');
  22238. return p;
  22239. }
  22240. ];
  22241. any(tasks);
  22242. console.log('.......done');
  22243. console.log('Running exlr upgrade in : ' + path__default['default'].dirname(__dirname));
  22244. console.log('Currently only upgrades ember : ' + path__default['default'].dirname(__dirname));
  22245. console.info('Uninstalling existing ember globally');
  22246. var step1 = nodeShellExec('cmd', ['/c', 'npm', 'uninstall', '-g', 'ember-cli'], {
  22247. stdio: ['pipe', process.stdout, process.stderr],
  22248. inherit: true,
  22249. shell: true,
  22250. cwd: path__default['default'].dirname(__dirname),
  22251. env: env
  22252. });
  22253. step1.on('close', () => {
  22254. console.info('Installing ember globally');
  22255. var step2 = nodeShellExec('cmd', ['/c', 'npm', 'install', '-g', 'ember-cli'], {
  22256. stdio: ['pipe', process.stdout, process.stderr],
  22257. inherit: true,
  22258. shell: true,
  22259. cwd: path__default['default'].dirname(__dirname),
  22260. env: env
  22261. });
  22262. step2.on('close', () => {
  22263. nodeShellExec('cmd', ['/c', 'ember', '--version'], {
  22264. stdio: ['pipe', process.stdout, process.stderr],
  22265. inherit: true,
  22266. shell: true,
  22267. cwd: path__default['default'].dirname(__dirname),
  22268. env: env
  22269. });
  22270. });
  22271. });
  22272. }
  22273. , 'runas': () => {
  22274. if(processedArgs.skipelevated) return Promise.resolve({ skipped : true });
  22275. console.log('Testing Elevation');
  22276. if (__isElevated) {
  22277. try {
  22278. op[processedArgs.label || processedArgs._[0] || 'h']();
  22279. }
  22280. catch (e) {
  22281. console.error('Error Invalid command : ' + e);
  22282. fs.writeFileSync('run.done', 'error');
  22283. }
  22284. finally {
  22285. }
  22286. }
  22287. else {
  22288. console.log('Requesting Elevated Privileges');
  22289. // Wait for the runas to complete before we read it.
  22290. try {
  22291. fs.unlinkSync('run.done');
  22292. fs.unlinkSync('run.log');
  22293. }
  22294. catch (e) { } //Ignore
  22295. // Find node path to send to hta.
  22296. return nodeShellExec('where', ['node']).then(r => {
  22297. var namedArgs = [];
  22298. console.log('result : ' + JSON.stringify(r));
  22299. Object.keys(processedArgs).forEach((v) => { v != '_' ? namedArgs.push('--' + v + '=' + processedArgs[v]) : null; });
  22300. // PB : TODO -- Convert all the cli args back to string.
  22301. var args = [`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`].concat(processedArgs._).concat(namedArgs.join(' ')); args.push('--runas=self');
  22302. args.push('--nodepath=' + r[r.length - 1]);
  22303. if (!processedArgs.node_env) args.push('--node_env=' + ENV.NODE_ENV);
  22304. if (processedArgs.debug) args.push('--debug=true'); // Enable to debug elevated..
  22305. return nodeShellExec('MSHTA', [`"${args.join('" "')}"`]
  22306. , {
  22307. inherit: true
  22308. , shell: true
  22309. , env: ENV
  22310. , runas: 'self'
  22311. , title: `runas`
  22312. }
  22313. ).then(() => {
  22314. // runas returned.
  22315. try {
  22316. // PB : TODO -- Log is comma prefixed. Needs to be proper JSON.
  22317. var runaslog = JSON.parse('[ { "success" : true, "result" : "started"}' + fs.readFileSync('run.log', { flags: 'a+' }) + ']');
  22318. runaslog.forEach((logEntry) => {
  22319. statuslog.statuslog(logEntry.success ? null : logEntry, logEntry);
  22320. logEntry.success ? (console.log(['success :' + logEntry.result]), console.log((logEntry.messages || []).join(' '))) : (console.error(['error :' + logEntry.result]), console.error((logEntry.messages || []).join(' ')));
  22321. });
  22322. }
  22323. catch (e) {
  22324. // We must have a runas log
  22325. statuslog.statuslog(e);
  22326. console.error('Run log error probably was not created by runas : ' + e);
  22327. }
  22328. })
  22329. .catch(err => console.error('Elevation failed : ' + err));
  22330. })
  22331. }
  22332. }
  22333. , 'push': () => {
  22334. if (!processedArgs._[1]) { console.error('push all not supported. Specify repo name'); return }
  22335. // init remote bare from local
  22336. // pushandinitremotebare
  22337. // https://www.jeffgeerling.com/blogs/jeff-geerling/push-your-git-repositories
  22338. // connect to repo server -- net use 172.16.0.27
  22339. // cd 172.16.0.27/repos/
  22340. // mkdir repo.git
  22341. // cd repo.git
  22342. // git init --bare
  22343. // cd localrepo
  22344. // git remote rename origin githubclone
  22345. // git remote add origin //172.16.0.27/repos/repo.git
  22346. // git push origin master
  22347. var repo = processedArgs._[1];
  22348. var sequentialTaskShellCommands = [];
  22349. if (!existsSync(`Z:/${repo}.git`)) {
  22350. sequentialTaskShellCommands = [
  22351. // ['net', ['use', 'Z:', selectedinstance.reposerver.replace('/','\\')], {
  22352. // inherit : true, shell: true
  22353. // , env: process.env
  22354. // }]
  22355. ['pwd', { cwd: 'Z:', inherit: true }]
  22356. , ['mkdir', [`${repo}.git`], {
  22357. cwd: `Z:`
  22358. , inherit: true, shell: true
  22359. , env: process.env
  22360. }]
  22361. , ['pwd', { cwd: `Z:/${repo}.git`, inherit: true }]
  22362. , ['git', ['init', '--bare'], {
  22363. cwd: `Z:/${repo}.git`
  22364. , inherit: true, shell: true
  22365. , env: process.env
  22366. }]
  22367. // PB : TODO -- Do this conditionally only...
  22368. , ['git', ['remote', 'rename', 'origin', 'githubclone'], { cwd: `${instanceroot + '/' + repo}` }, (err) => {
  22369. console.log('Ignoring origin rename error : ' + err); return true; //return true to continue.
  22370. }] // PB ; Todo -- new repositories created locally will not have origin. Handle this failure.
  22371. , ['git', ['remote', 'add', 'origin', `${selectedinstance.reposerver}/${repo}.git`], { cwd: `${instanceroot + '/' + repo}` }]
  22372. // PB : TODO -- If threre is a gitbubclone origin
  22373. // Set the master to pull from the local repo.
  22374. ];
  22375. if (!existsSync(`Z:`)) {
  22376. sequentialTaskShellCommands.splice(0, 0, ['net', ['use', 'Z:', selectedinstance.reposerver.replace(/\//gm, '\\')], {
  22377. inherit: true, shell: true
  22378. , env: process.env
  22379. }]);
  22380. console.warn('Adding network drive z: for repo server. ' + sequentialTaskShellCommands[0]);
  22381. // throw 'done'
  22382. }
  22383. }
  22384. sequentialTaskShellCommands.push(['git', ['push', 'origin', 'master'], { cwd: `${instanceroot + '/' + repo}` }]);
  22385. // console.dir(sequentialTaskShellCommands);
  22386. var tasks = [];
  22387. sequentialTaskShellCommands.forEach(shellcmd => {
  22388. // console.log(shellcmd)
  22389. tasks.push(() => {
  22390. var p = nodeShellExec.apply(null, shellcmd.slice(0, 3)).catch((e) => { if (shellcmd[3]) { return shellcmd[3]() } else { console.error(e); } });
  22391. return p;
  22392. });
  22393. });
  22394. any(tasks);
  22395. }
  22396. , 'is-git-repo': (dir) => {
  22397. return nodeShellExec('git', ['-C', dir.name, 'rev-parse'], { stdio: 'ignore' })
  22398. }
  22399. // git remote equivalents...
  22400. // git branch --set-upstream-to=elixir-unc/master master
  22401. // git push --set-upstream elixir-unc branch..
  22402. , 'remote': (args) => {
  22403. // Subcommands!
  22404. if(!processedArgs.v) return false;
  22405. var serial_perform = (repo) => {
  22406. var options = { cwd: instanceroot + '/' + repo };
  22407. return [
  22408. ['git', ['remote', '-v'], options]
  22409. ]
  22410. };
  22411. var x = (args) => {
  22412. var tasq = () => {
  22413. // console.log(args)
  22414. return nodeShellExec.apply(null, args).catch(e => {
  22415. // We continue on failure.
  22416. console.error(tasq.toString());
  22417. })
  22418. };
  22419. tasq.toString = function(){
  22420. return JSON.stringify(args)
  22421. };
  22422. return tasq;
  22423. };
  22424. var perform = (dir) => {
  22425. return any(serial_perform(dir.name).map(x))
  22426. };
  22427. dirs(perform);
  22428. }
  22429. , 'remote set-url': (args) => {
  22430. // git remote set-url elixir-unc //10.10.5.60/gitrepo/chess/bbhverse
  22431. var __args = {
  22432. remotename : args.remotename || processedArgs._[2]
  22433. , url : args.url || processedArgs._[3]
  22434. };
  22435. // pushable doesn't mean the remote doesn't support being pushed to.
  22436. // 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.
  22437. // PB : TODO -- change this to enablepushing.
  22438. // By default pushing should be disabled. Also developers permissions on the remote is a secondary check for pushing.
  22439. var pushable = processedArgs.pushable || false;
  22440. remotename = __args.remotename;
  22441. url = __args.url;
  22442. var serial_perform_git_seturl = (repo) => {
  22443. // console.log(repo)
  22444. if (pushable) {
  22445. return [
  22446. ['git', ['remote', 'set-url', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  22447. , ['git', ['remote', `set-url`, '--push', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  22448. ]
  22449. }
  22450. else {
  22451. return [
  22452. ['git', ['remote', 'set-url', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  22453. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  22454. ]
  22455. }
  22456. };
  22457. var x = (args) => {
  22458. var tasq = () => {
  22459. // console.log(args)
  22460. return nodeShellExec.apply(null, args).catch(e => {
  22461. // We continue on failure.
  22462. console.error(tasq.toString());
  22463. })
  22464. };
  22465. tasq.toString = function(){
  22466. return JSON.stringify(args)
  22467. };
  22468. return tasq;
  22469. };
  22470. var perform_git_seturl = (dir) => {
  22471. op['is-git-repo'](dir).then((logEntry) => {
  22472. return any(serial_perform_git_seturl(dir.name).map(x))
  22473. }).catch((e) => {
  22474. // console.log('Failed : ' + dir.name)
  22475. });
  22476. };
  22477. dirs(perform_git_seturl);
  22478. }
  22479. , 'add': (remotename, url, branch) => {
  22480. var pushable = processedArgs.pushable || false;
  22481. remotename = remotename || processedArgs._[1];
  22482. url = url || processedArgs._[2];
  22483. branch = branch || processedArgs._[3];
  22484. var serial_perform_git_add = (repo) => {
  22485. // console.log(repo)
  22486. if (pushable) {
  22487. return [
  22488. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  22489. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
  22490. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  22491. ]
  22492. }
  22493. else {
  22494. return [
  22495. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  22496. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  22497. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
  22498. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  22499. ]
  22500. }
  22501. };
  22502. var x = (args) => {
  22503. return () => {
  22504. // console.log(args)
  22505. return nodeShellExec.apply(null, args)
  22506. }
  22507. // return Promise.resolve(true)
  22508. };
  22509. var perform_git_add = (dir) => {
  22510. op['is-git-repo'](dir).then((logEntry) => {
  22511. // console.log(code)
  22512. if (logEntry.success) {
  22513. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  22514. console.log('skipped : ' + dir.name + ', reason : A remote with same name already exists.');
  22515. })
  22516. .catch((e) => {
  22517. any(serial_perform_git_add(dir.name).map(x));
  22518. });
  22519. }
  22520. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  22521. }).catch((e) => {
  22522. // console.log('Failed : ' + dir.name)
  22523. });
  22524. };
  22525. fs__default['default'].promises;
  22526. dirs(perform_git_add);
  22527. }
  22528. , 'remote remove': (args) => {
  22529. var __args = {
  22530. remotename : args.remotename|| processedArgs._[2]
  22531. };
  22532. var remotename = __args.remotename;
  22533. var serial_perform_git_remove = (repo) => {
  22534. // console.log(repo)
  22535. return [
  22536. ['git', ['remote', 'remove', remotename], { cwd: instanceroot + '/' + repo }]
  22537. ]
  22538. };
  22539. var x = (args) => {
  22540. return () => {
  22541. // console.log(args)
  22542. return nodeShellExec.apply(null, args)
  22543. }
  22544. // return Promise.resolve(true)
  22545. };
  22546. var perform_git_remove = (dir) => {
  22547. op['is-git-repo'](dir).then((logEntry) => {
  22548. // console.log(code)
  22549. if (logEntry.success) {
  22550. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  22551. any(serial_perform_git_remove(dir.name).map(x));
  22552. })
  22553. .catch((e) => {
  22554. console.log('skipped : ' + dir.name + `, reason : No remote named ${remotename}`);
  22555. });
  22556. }
  22557. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  22558. }).catch((e) => {
  22559. // console.log('Failed : ' + dir.name)
  22560. });
  22561. };
  22562. fs__default['default'].promises;
  22563. dirs(perform_git_remove);
  22564. }
  22565. , 'init-gitea': (user) => {
  22566. user = user || processedArgs._[1];
  22567. if (!user) throw 'User name required'
  22568. var serial_perform_init_gitea = (repo) => {
  22569. // console.log(repo)
  22570. return [
  22571. ['git', ['remote', 'add', 'chess', `${selectedinstance.reposerver}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  22572. , ['git', ['remote', 'set-url', '--push', 'chess', 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  22573. , ['git', ['remote', 'set-url', 'origin', `${selectedinstance.reposerver}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  22574. ]
  22575. };
  22576. var x = (args) => {
  22577. return () => {
  22578. // console.log(args)
  22579. return nodeShellExec.apply(null, args)
  22580. }
  22581. // return Promise.resolve(true)
  22582. };
  22583. var perform_init_gitea = (dir) => {
  22584. op['is-git-repo'](dir).then((logEntry) => {
  22585. // console.log(code)
  22586. if (logEntry.success) {
  22587. nodeShellExec('git', ['remote', 'get-url', 'chess'], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  22588. console.log('skipped : ' + dir.name + ', reason : Already has remote chess ');
  22589. })
  22590. .catch((e) => {
  22591. any(serial_perform_init_gitea(dir.name).map(x));
  22592. });
  22593. }
  22594. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  22595. }).catch((e) => {
  22596. // console.log('Failed : ' + dir.name)
  22597. });
  22598. };
  22599. fs__default['default'].promises;
  22600. dirs(perform_init_gitea);
  22601. }
  22602. , 'syncmaster': (label) => {
  22603. // Usage :
  22604. // elxr pull -- Defaults to run config
  22605. Object.assign({}, process.env); // Shallow clone it.
  22606. // console.dir(env)
  22607. console.log('Running exlr pull : ' + path__default['default'].dirname(__dirname));
  22608. if (!processedArgs.runas) gitRepos.map((def) => performPull(def.repo, def.branch || 'master'));
  22609. if (__isElevated) {
  22610. return any(elevatedRunasRepos.map((def) => performPull(def.repo, def.branch || 'master'))).then(() => {
  22611. fs.writeFileSync('run.done', 'success');
  22612. }).catch(() => {
  22613. fs.writeFileSync('run.done', 'error');
  22614. })
  22615. }
  22616. else return op['runas']()
  22617. }
  22618. , 'repo-relocate' : function(args){
  22619. // relocate a subfolder in source repo to same subfolder in target repo with history.
  22620. var args = args || {
  22621. remotebase : processedArgs._[4] || 'http://git.bbh/chess/'
  22622. , folder : processedArgs._[3] || 'server'
  22623. , sourcerepo : processedArgs._[2] || 'client'
  22624. , targetrepo : processedArgs._[1] || 'elixir-server'
  22625. };
  22626. var sourcerepooptions = { cwd: `${instanceroot}/relocate/${args.sourcerepo}`
  22627. // , stdio: ['pipe', process.stdout, process.stderr]
  22628. , inherit: true,
  22629. shell: true,
  22630. env: process.env
  22631. , runas: processedArgs.runas
  22632. };
  22633. return op['repo-split'](args).then(()=>{
  22634. return op['repo-merge'](args).then(()=>{
  22635. // cleanup folder from source.
  22636. var cmdseq = [
  22637. ['rm', ['-rf', `${args.folder}`], sourcerepooptions ]
  22638. // commits have to intentional...
  22639. // , ['git', ['commit', '-a', '-m', `relocate folder ${args.folder} to ${targetrepo}`], sourcerepooptions ]
  22640. ];
  22641. return any(cmdseq.map(callsheltask))
  22642. })
  22643. }).catch(e=>{console.error(e);})
  22644. }
  22645. , 'repo-split' : function(args) {
  22646. // https://gist.github.com/smdabdoub/17065c348289158277b5
  22647. /**
  22648. * Eg : folder, remotebase, sourcerepo, targetrepo
  22649. * args.folder = 'server'
  22650. * args.remotebase = 'https://git.bbh/chess/'
  22651. * args.sourcerepo = 'client'
  22652. * args.targetrepo = 'elixir-server'
  22653. */
  22654. var args = args || {
  22655. folder : 'server'
  22656. , remotebase : 'http://git.bbh/chess/'
  22657. , sourcerepo : 'client'
  22658. , targetrepo : 'elixir-server'
  22659. };
  22660. var options = { cwd: `${instanceroot}/relocate`
  22661. // , stdio: ['pipe', process.stdout, process.stderr]
  22662. , inherit: true,
  22663. shell: true,
  22664. env: process.env
  22665. , runas: processedArgs.runas
  22666. };
  22667. var cmdseq = [
  22668. // create a temporary working dir in current folder where we started execution.
  22669. ['mkdir', [ '-p', 'relocate']]
  22670. , ['git', ['clone', `${args.remotebase}${args.sourcerepo}`], options ]
  22671. , ['git', ['clone', `${args.sourcerepo}`, `relocate-${args.sourcerepo}-${args.folder}`], options]
  22672. , ['git', ['clone', `${args.remotebase}${args.targetrepo}`, `relocate-${args.targetrepo}-${args.folder}`], options]
  22673. ];
  22674. return any(cmdseq.map(callsheltask)).then(() => {
  22675. // , ['git', ['subtree', 'split', '-P', `${args.folder}`, '-b', `relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
  22676. // split doesnt retain folder structure we need to move and commit ourselves through a branch to retain history...
  22677. // , ['git', [`checkout relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
  22678. // , ['mkdir', [`${args.folder}`], sourcerepooptions]
  22679. // , ['git', ['mv', `!(${args.folder})`, `${args.folder}`], sourcerepooptions ] // requires shopt -s extglob
  22680. // , ['git', ['commit', `-m`, 'Moved to same subfolder after subtree split in branch'] , sourcerepooptions]
  22681. // subtree split and filter-branch are options. We currently use repo-filter.
  22682. return op['filter-repo'](args)
  22683. }).catch(e=>{console.error(e); throw 'failed'})
  22684. }
  22685. , 'repo-merge' : function(args) {
  22686. // Merge source repo into target repo
  22687. var args = args || {
  22688. folder : 'server'
  22689. , remotebase : 'http://git.bbh/chess/'
  22690. , sourcerepo : 'client'
  22691. , targetrepo : 'elixir-server'
  22692. };
  22693. ({ cwd: `${instanceroot}/relocate/relocate-${args.sourcerepo}-${args.folder}`
  22694. // , stdio: ['pipe', process.stdout, process.stderr]
  22695. , inherit: true,
  22696. shell: true,
  22697. env: process.env
  22698. , runas: processedArgs.runas
  22699. });
  22700. var targetrepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.targetrepo}-${args.folder}`
  22701. // , stdio: ['pipe', process.stdout, process.stderr]
  22702. , inherit: true,
  22703. shell: true,
  22704. env: process.env
  22705. , runas: processedArgs.runas
  22706. };
  22707. var cmdseq = [
  22708. ['git', ['pull', `../relocate-${args.sourcerepo}-${args.folder}`, `master`, '--allow-unrelated-histories']
  22709. , targetrepooptions ]
  22710. // , ['git', ['push', targetrepooptions ] // manual push for now..
  22711. ];
  22712. return any(cmdseq.map(callsheltask)).catch(e=>{console.error(e);})
  22713. }
  22714. , 'filter-repo' : function(args){
  22715. // Merge source repo into target repo
  22716. var args = args || {
  22717. folder : 'server'
  22718. , remotebase : 'http://git.bbh/chess/'
  22719. , targetrepo : 'elixir-server'
  22720. };
  22721. var targetrepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.sourcerepo}-${args.folder}`
  22722. , inherit: true, shell: true
  22723. , env: process.env
  22724. , runas: processedArgs.runas
  22725. };
  22726. var cmdseq = [
  22727. // git checkout -b feature/merge-old-project
  22728. // git remote add src-project ../src-project
  22729. ['git', ['filter-repo', '--path', `${args.folder}`], targetrepooptions ]
  22730. ];
  22731. return any(cmdseq.map(callsheltask)).catch(e=>{console.error(e); throw 'failed' })
  22732. }
  22733. , 'filter-branch' : function(preservefolder, repo){
  22734. // https://stackoverflow.com/questions/359424/detach-move-subdirectory-into-separate-git-repository
  22735. // git subtree split -P <name-of-folder> -b <name-of-new-branch>
  22736. // Preserve a specific folder.
  22737. // PB : TODO -- filter-branch has known issues. Explore subtree and filter-repo...
  22738. /*
  22739. git clone repo reposplit
  22740. git filter-branch --tag-name-filter cat --prune-empty --subdirectory-filter {{folder}} -- --all
  22741. git remote rm origin
  22742. */
  22743. throw 'filter-repo-history not yet implmented pls refer to manual commands in code.'
  22744. }
  22745. // , 'repo-merge-folder' : function(mergetarget, mergesource, mergefolder){
  22746. // // Merge repo2 into a subfolder in repo1
  22747. // // https://alexharv074.github.io/puppet/2017/10/04/merge-a-git-repository-and-its-history-into-a-subdirectory-of-a-second-git-repository.html
  22748. // // https://thoughts.t37.net/merging-2-different-git-repositories-without-losing-your-history-de7a06bba804
  22749. // /*
  22750. // cd repo1
  22751. // git remote add -f tempmergesource ../{{mergesource}}/.git
  22752. // git merge -s ours --no-commit tempmergesource/master --allow-unrelated-histories
  22753. // git read-tree --prefix={{mergefolder}} -u tempmergesource/master:
  22754. // git commit
  22755. // // Repair History
  22756. // // === git filter-branch --tree-filter '(echo === $GIT_COMMIT:; git ls-tree $GIT_COMMIT) >> /tmp/tree.log'
  22757. // #!/usr/bin/env bash
  22758. // first=ed4f16becc2f03820c164e0617bb98f12ff49ef0
  22759. // last=038e26e21bd60fa265d6637261f3bc918780d2e8
  22760. // subdir=server
  22761. // git filter-branch --tree-filter '
  22762. // first='"$first"'
  22763. // last='"$last"'
  22764. // subdir='"$subdir"'
  22765. // log_file=/tmp/filter.log
  22766. // [ "$GIT_COMMIT" = "$first" ] && seen_first=true
  22767. // if [ "$seen_first" = "true" ] && [ "$seen_last" != "true" ]; then
  22768. // echo "=== $GIT_COMMIT: making changes"
  22769. // files=$(git ls-tree --name-only $GIT_COMMIT)
  22770. // mkdir -p $subdir
  22771. // for i in $files; do
  22772. // mv $i $subdir || echo "ERR: mv $i $subdir failed"
  22773. // done
  22774. // else
  22775. // echo "=== $GIT_COMMIT: ignoring"
  22776. // fi \
  22777. // >> $log_file
  22778. // [ "$GIT_COMMIT" = "$last" ] && seen_last=true
  22779. // status=0 # tell tree-filter never to fail
  22780. // '
  22781. // git remote rm tempmergesource
  22782. // */
  22783. // // better alternative for history
  22784. // /**
  22785. // *
  22786. // git clone git@server.com:old-project.git
  22787. // git clone git@server.com:new-project.git
  22788. // cd old-project
  22789. // mkdir old-project
  22790. // git mv !(old-project) old-project
  22791. // ls -la and gt mv hidden files ....
  22792. // git commit -a -S -m “Moving old project into its own subdirectory”
  22793. // cd ../new-project
  22794. // git remote add old-project ../old-project
  22795. // git fetch old-project
  22796. // git checkout -b feature/merge-old-project
  22797. // git merge -S --allow-unrelated-histories old-project/master
  22798. // git push origin feature/merge-old-project
  22799. // git remote rm old-project
  22800. // */
  22801. // throw 'merge-repos not yet implmented pls refer to manual commands in code.'
  22802. // }
  22803. , 'pull' : (label) => {
  22804. // Usage :
  22805. // elxr pull -- Defaults to run config
  22806. return elxr.getpulltask(selectedinstance)()
  22807. }
  22808. , 'isInstalled': () => {
  22809. return nodeShellExec('where', [processedArgs._[1]], { inherit: true }).then(() => {
  22810. console.log(processedArgs._[1] + ' exists.');
  22811. return true;
  22812. });
  22813. }
  22814. , 'i' : () => {
  22815. var tasks = [];
  22816. // tasks.push(op['pull']);
  22817. tasks.push(getShellTask.apply(null, ['rm', [instanceroot + '/run.js'], { ignorefailures: true }]));
  22818. tasks.push(op['use']);
  22819. if (!__isElevated) {
  22820. tasks.push(op['npmi']);
  22821. }
  22822. // var tasksdefs = [
  22823. // ['elxr', ['pull']]
  22824. // , ['elxr', ['use', 'elixir']]
  22825. // , ['elxr', ['npmi']]
  22826. // ]
  22827. // tasksdefs.forEach(tasksdef=>{
  22828. // tasks.push( ()=> nodeShellExec.apply(null, tasksdef) )
  22829. // })
  22830. return any(tasks);
  22831. }
  22832. , 'npmi': () => {
  22833. var tasks = [];
  22834. // Build fails without babel...
  22835. tasks.push(getShellTask(
  22836. 'npm',[ 'i', '-g', 'babel-cli' ]
  22837. ) );
  22838. var npmbuildrepos = ['loopback-jsonapi-model-serializer'];
  22839. npmbuildrepos = [];
  22840. npmbuildrepos.forEach(repo => {
  22841. tasks.push(() => {
  22842. return nodeShellExec('npm', ['i --force'], {
  22843. inherit: true, shell: true
  22844. , cwd: instanceroot + '/' + repo
  22845. , env: process.env
  22846. , title: `npm i for ${repo}`
  22847. }).catch((e) => {
  22848. console.error('Ignoring Benign Error'); console.error(e);
  22849. }).then(() => {
  22850. console.log(`--npm run build for ${repo}--------------------`);
  22851. return nodeShellExec('npm', ['run build'], {
  22852. inherit: true, shell: true
  22853. , cwd: instanceroot + '/' + repo
  22854. , env: process.env
  22855. , title: `npm run build for ${repo}`
  22856. }).then(Tasq.then).catch(Tasq.catch)
  22857. })
  22858. });
  22859. });
  22860. any(tasks).then(() => {
  22861. gitRepos.push('client/server');
  22862. gitRepos = gitRepos.concat(elevatedRunasRepos);
  22863. // gitRepos = [
  22864. // // 'bbhverse', 'serververse', 'elixir-server',
  22865. // // 'clientverse',
  22866. // 'client'
  22867. // ];
  22868. var rmtasks = [];
  22869. var repotasks = [];
  22870. var env = Object.assign({}, process.env);
  22871. delete env.NODE_ENV;
  22872. gitRepos.forEach(repodef => {
  22873. rmtasks.push(
  22874. // () => {
  22875. // console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
  22876. // return nodeShellExec(`"${gitbash}"`, ['-c', '"rm package-lock.json"'], {
  22877. nodeShellExec('rm', ['package-lock.json'], {
  22878. inherit: true, shell: true
  22879. , cwd: instanceroot + '/' + repodef.repo
  22880. , env: process.env
  22881. , title: `rm 'package-lock.json' for ${repodef.repo}`
  22882. })
  22883. .then(()=>{
  22884. console.log(`--rm package-lock.json for ${repodef.repo}--------------------`);
  22885. }).catch((e) => { console.error(e); })
  22886. // }
  22887. );
  22888. if (npmbuildrepos.indexOf(repodef.repo) < 0) {
  22889. repotasks.push(
  22890. () => {
  22891. console.log(`--npm i for ${repodef.repo}--------------------`);
  22892. var p = nodeShellExec('npm', ['i', '--force'], {
  22893. inherit: true, shell: true
  22894. , cwd: instanceroot + '/' + repodef.repo
  22895. , env
  22896. , title: `npm i for ${repodef.repo}`
  22897. }).then(Tasq.then).catch(Tasq.catch);
  22898. return p;
  22899. });
  22900. }
  22901. });
  22902. // PB : NOTE -- npm i for client does not complete when NODE_ENV=production
  22903. // therefore bower doesn't get installed !!! which then fails installing the bower dependenciew !!!
  22904. // We work around this by running npm i for client without any NODE_ENV which probably defualts to development.
  22905. // PB : TODO -- Investigate why NODE_ENF has an impact on npm i !??
  22906. // Second time try also doesnt work.
  22907. // repotasks.push(
  22908. // () => {
  22909. // var env = Object.assign({}, process.env)
  22910. // delete env.NODE_ENV
  22911. // console.log(`--------------------second time npm i for client--------------------`)
  22912. // return nodeShellExec(`"${gitbash}"`, ['-c', '"npm i --force"'], {
  22913. // // return nodeShellExec('npm', ['i --force'], {
  22914. // inherit: true, shell: true
  22915. // , cwd: instanceroot + '/' + 'client'
  22916. // , env
  22917. // , title: `npm i for client`
  22918. // }).then(Tasq.then).catch(Tasq.catch)
  22919. // })
  22920. var bowerRepos = [{ repo : 'client'}];
  22921. bowerRepos.forEach(repodef => {
  22922. repotasks.push(() => {
  22923. console.log(instanceroot + '/' + repodef.repo + '/node_modules/bower/bin/bower');
  22924. // var p = nodeShellExec('node_modules/bower/bin/bower', ['install'], {
  22925. var p = nodeShellExec(`"${gitbash}"`, ['-c', '"node_modules/bower/bin/bower i"'], {
  22926. inherit: true, shell: true
  22927. , cwd: instanceroot + '/' + repodef.repo
  22928. , env: process.env
  22929. , title: `bower i for ${repodef.repo}`
  22930. }).then(Tasq.then).catch(Tasq.catch);
  22931. return p;
  22932. });
  22933. });
  22934. // console.log('rmtasks.length : ' + rmtasks.length)
  22935. return Promise.all(rmtasks).then(() => any(repotasks));
  22936. }).catch(e => {
  22937. }).finally(statuslog.finally);
  22938. }
  22939. , 'start': (label) => {
  22940. console.log('Starting Elixir Server.');
  22941. var env = Object.assign({}, process.env); // Shallow clone it.
  22942. // console.dir(env)
  22943. env.NODE_ENV = process.env.NODE_ENV || 'development';
  22944. env.DEBUG = 'loopback:connector:' + dbForLabel(label);
  22945. var cmd = env.NODE_ENV === 'development' ? 'nodemon' : 'node';
  22946. // cmd = 'node'
  22947. cmd = [cmd, ['--inspect=9228', 'elixir/server.js']];
  22948. var childPromise = nodeShellExec(...cmd, {
  22949. // inherit : true,
  22950. shell: true,
  22951. detached: true,
  22952. stdio: 'ignore',
  22953. cwd: instanceroot + '/' + 'elixir-server'
  22954. , env: env
  22955. });
  22956. var child = childPromise.process;
  22957. if (typeof child.pid !== 'undefined') {
  22958. console.log(`started Elixir Server PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  22959. fs.writeFileSync('.elixir-server.elixir.server.pid', child.pid, {
  22960. encoding: 'utf8'
  22961. });
  22962. }
  22963. // nodeShellExec('node', ['--inspect=9226', ' bin/www'], {
  22964. // inherit : true,
  22965. // shell: true, detached: true,
  22966. // cwd : 'qms/server',
  22967. // env: env,
  22968. // shell : true
  22969. // })
  22970. // nodeShellExec('ember', ['s'], {
  22971. // // inherit : true,
  22972. // shell: true, detached: true,
  22973. // cwd : 'client/',
  22974. // env: env
  22975. // })
  22976. console.log('Starting Elixir Client Host.');
  22977. var cmd = ['ember', ['s']];
  22978. var childPromise = nodeShellExec(...cmd, {
  22979. // var childPromise = nodeShellExec('node', ['--inspect=9227', './node_modules/.bin/ember', 's'], {
  22980. // PB : TODO -- ember debugging.
  22981. // inherit : true,
  22982. shell: true,
  22983. detached: true,
  22984. stdio: 'ignore',
  22985. cwd: instanceroot + '/' + 'client'
  22986. , env: env
  22987. });
  22988. // .catch(e=>console.error(e))
  22989. child = childPromise.process;
  22990. if (typeof child.pid !== 'undefined') {
  22991. console.log(`started Elixir Client Host PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  22992. fs.writeFileSync('.client.server.pid', child.pid, {
  22993. encoding: 'utf8'
  22994. });
  22995. }
  22996. }
  22997. , 'stop': (label) => {
  22998. const kill = treeKill;
  22999. var serverPid = fs.readFileSync('.elixir-server.elixir.server.pid', {
  23000. encoding: 'utf8'
  23001. });
  23002. fs.unlinkSync('.elixir-server.elixir.server.pid');
  23003. console.log(serverPid);
  23004. kill(serverPid);
  23005. serverPid = fs.readFileSync('.client.server.pid', {
  23006. encoding: 'utf8'
  23007. });
  23008. fs.unlinkSync('.client.server.pid');
  23009. console.log(serverPid);
  23010. kill(serverPid);
  23011. }
  23012. , 'model' : () => {
  23013. if (__isElevated) {
  23014. var tasks = [
  23015. () => {
  23016. var p = nodeShellExec('mklink', [ `${processedArgs._[2]}.json`
  23017. , `..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`], {
  23018. inherit: true, shell: true
  23019. , cwd : instanceroot + `/${selectedinstance.instanceName}-server/${selectedinstance.instanceName}/models`
  23020. , title: `mklink ${processedArgs._[2]}.json ..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`
  23021. , env: process.env
  23022. }).catch((e) => { console.error(e); });
  23023. return p;
  23024. }
  23025. ];
  23026. return any(tasks).then(() => {
  23027. fs.writeFileSync('run.done', 'success');
  23028. }).catch(() => {
  23029. fs.writeFileSync('run.done', 'error');
  23030. })
  23031. }
  23032. else return op['runas']()
  23033. }
  23034. , 'use' : () => {
  23035. // use a certain named instance.
  23036. // Eg :
  23037. // 1) elxr use elixir
  23038. // 2) elxr use cihsr
  23039. // If environment is not specified defaults to development.
  23040. // 1) NODE=test elxr use elixir
  23041. /*// Steps
  23042. 1) Delete Config and Data symlinks
  23043. 2) Make Links for config ({{name}}-config-{{node_env}}) and data with the NODE_ENV specified or default to dev
  23044. 3) Iterates all repos and pull all. 'git', ['pull', '--all'].
  23045. 4) Iterates all repos and checkout to the ENV specified. 'git', ['checkout', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  23046. 5) Iterates all repos and merge from source configured in mergesource. 'git', ['merge', mergesource],
  23047. */
  23048. var runconfig = { NODE_ENV: repomanifest.node_env };
  23049. try { runconfig = Object.assign(runconfig, commonjsRequire(instanceroot + '/run.js',"/$$rollup_base$$")); } catch (e) { }
  23050. // We no longer need to check ruans.. ??? if we were initiated from self invoked privileged shell ?
  23051. if (( /*processedArgs.runas && processedArgs.runas !== 'self' &&*/ !processedArgs.force) &&
  23052. runconfig.NODE_ENV && runconfig.NODE_ENV === (repomanifest.node_env || runconfig.NODE_ENV) &&
  23053. repomanifest.instanceName && runconfig.use === repomanifest.instanceName) {
  23054. console.log(`No change detected. Already using requested specs : ${runconfig.NODE_ENV} ${runconfig.use}`);
  23055. if (processedArgs.runas) { fs.writeFileSync('run.done', 'success'); }
  23056. return
  23057. }
  23058. var tasks = [
  23059. () => {
  23060. if (existsSync('config')) {
  23061. var p = nodeShellExec('rmdir', ['config'], { inherit: true, shell: true, env: process.env }
  23062. ).catch((err) => { console.log('Ignoring benign error : ' + err); return true; });
  23063. return p;
  23064. }
  23065. else return Promise.resolve(true);
  23066. },
  23067. () => {
  23068. if (existsSync('data')) {
  23069. var p = nodeShellExec('rmdir', ['data'], { inherit: true, shell: true, env: process.env }
  23070. ).catch((err) => { console.log('Ignoring benign error : ' + err); return true; });
  23071. return p;
  23072. }
  23073. else return Promise.resolve(true);
  23074. },
  23075. ];
  23076. runconfig.NODE_ENV = process.env.NODE_ENV = process.env.NODE_ENV || runconfig.NODE_ENV || 'development';
  23077. if (processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1];
  23078. if (!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' }
  23079. // console.log(process.env.cwd)
  23080. fs.writeFileSync(instanceroot + '/run.js', 'module.exports = ' + JSON.stringify(runconfig));
  23081. // Maps an environment to a branch. Not required if the branch is appropriately named.
  23082. var checkoutMap = { 'development': 'master' };
  23083. var branch = checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV;
  23084. var performPullOrCloneForBranch = (def)=>{
  23085. var promise = Promise.resolve(true);
  23086. if (!branch) {
  23087. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo);
  23088. promise = nodeShellExec.apply(null, dscoverbranchcmd(repo)).then(__branch=>{ branch = __branch;})
  23089. .catch((e) => { console.error(e); return { error: true, message: repo } });
  23090. }
  23091. return promise = promise.then(()=>{ return elxr.getpulltask(def)() }).catch(e => { console.error( 'performPullOrCloneForBranch : Failed ' + e );})
  23092. };
  23093. var performCloneAndCheckout = null;
  23094. // cant use git checkout -b it fails when branch already exists.
  23095. var performCheckout = performCloneAndCheckout = (def) => {if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  23096. return performPullOrCloneForBranch(def).then(()=>{
  23097. nodeShellExec('git', ['checkout', def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  23098. // return nodeShellExec('git', ['switch', '-m', '-C', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  23099. // inherit : true, shell: true,
  23100. cwd: instanceroot + '/' + def.repo
  23101. // , stdio : ignore // Use when we want to silence output completely.
  23102. , runas: processedArgs.runas
  23103. , title: `git checkout ${def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${def.repo}`
  23104. }).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 } });
  23105. })
  23106. };
  23107. var mergeSources = {
  23108. 'development': null,
  23109. 'test': 'master',
  23110. 'production': 'master'
  23111. };
  23112. var mergesource = mergeSources[checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV];
  23113. // Checkout is reduced to pull provided the current branch is the targetbranch
  23114. if(branch === mergesource) performCheckout = (def) => {
  23115. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo);
  23116. return nodeShellExec.apply(null, dscoverbranchcmd(repo)).then(__branch=>{
  23117. if(branch === __branch) return performCloneAndCheckout(def)
  23118. return performPullOrCloneForBranch(def)
  23119. })
  23120. .catch((e) => { console.error(e); return { error: true, message: repo } })
  23121. };
  23122. // else performCheckout = (def) => { return performPullOrCloneForBranch(def) }
  23123. var performPullAll = (def) => {
  23124. if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  23125. return nodeShellExec('git', ['pull', '--all'], {
  23126. // inherit : true, shell: true,
  23127. cwd: instanceroot + '/' + def.repo
  23128. , runas: processedArgs.runas
  23129. , title: `git pull -all for ${checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} ${def.repo}`
  23130. }).catch((e) => { console.error(e); return { error: true, message: def.repo } })
  23131. };
  23132. var excludeCheckouts = Object.assign(exludeMergeRepos);
  23133. delete excludeCheckouts[`elixir-config-${runconfig.NODE_ENV}`];
  23134. delete excludeCheckouts[`cihsr-config-${runconfig.NODE_ENV}`];
  23135. var performMerge = (def) => {
  23136. if (exludeMergeRepos[def.repo]) return Promise.resolve({ 'skipped': true })
  23137. return nodeShellExec('git', ['merge', mergesource], {
  23138. inherit: true, shell: true,
  23139. cwd: instanceroot + '/' + def.repo
  23140. , runas: processedArgs.runas
  23141. }).catch((e) => { console.error(e); })
  23142. };
  23143. if(!mergesource || branch === mergesource) performMerge = () => { return Promise.resolve(true) };
  23144. // var performRepoOperation = function(def) {
  23145. // elevatedRunasRepos.map((repo) => enqueueCheckout({ repo, branch: def.branch, requiresElevation : true }))
  23146. // return any(gitRepos.map((repo) => performCheckout({ repo, branch: def.branch})))
  23147. // }
  23148. return any(tasks).then(() => {
  23149. var pr = Promise.resolve(true);
  23150. if (!__isElevated) {
  23151. pr = op['runas']();
  23152. return pr.then(()=>{
  23153. //target is the env is we specify in elxr use command. Default is dev
  23154. //Switch to target branch
  23155. return any(gitRepos.map((repodef) => { return performCheckout({ repo : repodef.repo, branch}).catch(e=>{ console.log(e); }) } ))
  23156. // pull or clone target branch
  23157. .then(() => {
  23158. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  23159. return any(gitRepos.map((repo) => performPullAll(repo)))
  23160. })
  23161. // switch to source branch
  23162. .then( () => {
  23163. if(!mergesource || branch === mergesource ) return Promise.resolve(true) // Dont do anything if there is no source to merge from.
  23164. return any(gitRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource})))
  23165. })
  23166. //Pull on merge source branch
  23167. .then( () => {
  23168. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  23169. return any(gitRepos.map((repo) => performPullAll(repo)))
  23170. })
  23171. //Switch to target branch
  23172. .then( () => {
  23173. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  23174. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch})))
  23175. })
  23176. .then( //Merge source branch to target branch
  23177. () => {
  23178. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  23179. return any(gitRepos.map((repo) => performMerge( repo ))).catch(err => { console.error('error in performMerge ' + err); })
  23180. })
  23181. })
  23182. }
  23183. else {
  23184. tasks = [
  23185. () => {
  23186. // Use junctions to avoid npm package issues
  23187. var p = nodeShellExec('mklink', ['/J', 'config', runconfig.use + '-config' + '-' + process.env.NODE_ENV], {
  23188. inherit: true, shell: true
  23189. , cwd : instanceroot
  23190. , env: process.env
  23191. }).catch((e) => { console.error(e); });
  23192. return p;
  23193. }
  23194. ];
  23195. if (processedArgs._[1]) {
  23196. tasks = tasks.concat(
  23197. [
  23198. () => {
  23199. var p = nodeShellExec('mklink', ['/J', 'data', runconfig.use + '-data'], {
  23200. inherit: true, shell: true
  23201. , cwd : instanceroot
  23202. , env: process.env
  23203. }).catch((e) => { console.error(e); });
  23204. return p;
  23205. }
  23206. ]
  23207. );
  23208. }
  23209. return any(tasks).then(()=>{
  23210. // checkout target branch
  23211. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  23212. // pull or clone target branch
  23213. .then(() => {
  23214. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  23215. return any(elevatedRunasRepos.map((repo) => performPullAll(repo)))
  23216. })
  23217. // switch to source branch
  23218. .then( () => {
  23219. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  23220. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource, requiresElevation : true})))
  23221. })
  23222. //Pull on merge source branch
  23223. .then( () => {
  23224. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  23225. return any(elevatedRunasRepos.map((repodef) => performPullAll({repo : repodef.repo, requiresElevation : true })))
  23226. })
  23227. //Switch to target branch
  23228. .then( () => {
  23229. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  23230. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  23231. })
  23232. .then( //Merge source branch to target branch
  23233. () => {
  23234. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  23235. return any(elevatedRunasRepos.map((repodef) => performMerge({ repo : repodef.repo, requiresElevation : true }))).catch(err => { console.error('error in performMerge ' + err); })
  23236. })
  23237. .then(() => {
  23238. fs.writeFileSync('run.done', 'success');
  23239. }).catch(() => {
  23240. fs.writeFileSync('run.done', 'error');
  23241. })
  23242. })
  23243. }
  23244. }).catch(() => {
  23245. fs.writeFileSync('run.done', 'error');
  23246. })
  23247. // Antibiotic stewardship program.
  23248. // 1st use is fine.
  23249. // Max vials dispense
  23250. // 2nd use Pharmacy needs justification Form.
  23251. // Approval after a certain period of time.
  23252. }
  23253. , 'g': () => {
  23254. if (processedArgs.h) {
  23255. console.log('elxr g [modelname] => generate a model named [modelname]');
  23256. console.log('elxr g => regenerate all known models');
  23257. return
  23258. }
  23259. // nodeShellExec('npm', ['init', '-y'], options);
  23260. // nodeShellExec('npm', ['init', '-y'], options);
  23261. // })
  23262. var g = {
  23263. 'client': () => {
  23264. // ember new --skip-bower --no-welcome --skip-git -b {{blueprint}}
  23265. console.info('Creating new ember client named : ' + processedArgs._[2]);
  23266. nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
  23267. stdio: ['pipe', process.stdout, process.stderr],
  23268. inherit: true,
  23269. shell: true,
  23270. cwd: path__default['default'].dirname(__dirname),
  23271. env: env
  23272. });
  23273. },
  23274. 'modelr': () => {
  23275. var tasks = [
  23276. () => {
  23277. var p = nodeShellExec('"ember"', [
  23278. 'g'
  23279. , 'modelr'
  23280. , processedArgs._[2]], {
  23281. inherit: true, shell: true, env: process.env
  23282. }).then(() => {
  23283. console.log('Blueprint generation complete for : ' + processedArgs._[2]);
  23284. return true;
  23285. }).catch((e) => { console.error(e); });
  23286. return p;
  23287. },
  23288. () => {
  23289. var chromePrefsFile = "C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data\\chess\\Preferences";
  23290. var chromeprefs = fs.readFileSync(chromePrefsFile, { encoding: 'utf8' });
  23291. chromeprefs = JSON.parse(chromeprefs);
  23292. var previous = chromeprefs.download.default_directory;
  23293. var parentDir = path__default['default'].dirname(__dirname);
  23294. chromeprefs.download.default_directory = parentDir + "\\client\\app\\templates\\components\\resource";
  23295. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs));
  23296. // PB : TODO -- detect where chrome is installed.
  23297. // PB : TODO -- set the download dir to the place where files are needed.
  23298. var p = nodeShellExec('"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"', [
  23299. '--user-data-dir="C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data"'
  23300. , '--profile-directory="chess"'
  23301. , 'http://localhost:4200/admin/crud/create/' + processedArgs._[2]], {
  23302. inherit: true, shell: true
  23303. , env: process.env
  23304. }).then(() => {
  23305. chromeprefs.download.default_directory = previous;
  23306. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs));
  23307. return true;
  23308. }).catch((e) => { console.error(e); });
  23309. return p;
  23310. }
  23311. ,
  23312. () => {
  23313. console.log('Browser process should have closed here....');
  23314. return true;
  23315. }
  23316. ];
  23317. any(tasks);
  23318. }
  23319. };
  23320. g[processedArgs._[1]]();
  23321. }
  23322. };
  23323. var cliname = 'elxr';
  23324. var ver = '1.1';
  23325. var readme = `
  23326. Command syntax examples
  23327. elxr
  23328. Displays help. Same as elxr h
  23329. elxr i
  23330. Runs interactive propmts to help choose installation options.
  23331. NODE_ENV={{yourenvironment}} elxr {{cmd}} {{instancename}} {{otheroptions}}
  23332. General command syntax.
  23333. Eg: NODE_ENV=development elxr pull elixir
  23334. Note : Although {{instancename}} is generally a positional parameter supplied immediately after the cmd for most cmd's.
  23335. The specific cmd defines what the value is interpreted as.
  23336. There are several cmds that do not require an {{instancename}} parameter.
  23337. Eg: elxr remote remove origin
  23338. Git operations or passthrough external commands on all repository folders in you working directory.
  23339. Main objectives.
  23340. elxr cli is a wrapper around other shell commands and api based operations.
  23341. One of the main objetives it achives is ease of use of repeating an individual cmd multiple times on all targets.
  23342. Eg: A git operation like pull can be repeated consistently on a set of git repositories.
  23343. `;
  23344. var help = `
  23345. ${readme}
  23346. # list of commands... please refer dveloper documentation for ${cliname}
  23347. ${
  23348. // util.inspect(
  23349. [Object.keys(op)]
  23350. // )
  23351. }
  23352. `;
  23353. var elxr = {
  23354. help() {
  23355. return source.cyanBright(`
  23356. -------------------------------------------------------------------------------
  23357. *** BBH Elixir ***
  23358. -------------------------------------------------------------------------------
  23359. elxr ${ver}
  23360. A cli tool for chess
  23361. ${help}
  23362. -------------------------------------------------------------------------------
  23363. `)
  23364. }
  23365. , info() {
  23366. return source.cyanBright(`
  23367. -------------------------------------------------------------------------------
  23368. *** BBH Elixir ***
  23369. -------------------------------------------------------------------------------
  23370. elxr ${ver}
  23371. A cli tool for chess
  23372. -------------------------------------------------------------------------------
  23373. `)
  23374. }
  23375. , getpulltask(def){
  23376. // def can be an instance config
  23377. // Or an object with many repos and elevated repos
  23378. // Or a single repo ( Either Elevated or normal. )
  23379. def = def || {
  23380. repos : repomanifest.repos,
  23381. elevated : repomanifest.elevated
  23382. };
  23383. var elevatedpulltasks = null;
  23384. if(def.repo) {
  23385. // Single repo case.
  23386. if(def.repo.requiresElevation) {
  23387. elevatedpulltasks = function() {
  23388. return performPull(def.repo).then(() => {
  23389. return true;
  23390. }).catch((e) => {
  23391. console.error(e);
  23392. })
  23393. };
  23394. return
  23395. }
  23396. else {
  23397. var regularpulltasks = function(){
  23398. var pendingpulls = [];
  23399. pendingpulls.push(performPull(def.repo));
  23400. return Promise.all(pendingpulls).finally(Traq.finally)
  23401. };
  23402. }
  23403. if(elevatedpulltasks) return getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  23404. else return getTaskWithoutElevation({ regularpulltasks})
  23405. }
  23406. // console.log(`-------------------Processing pull for : ${def.repo} ${def.branch}`)
  23407. console.dir(def);
  23408. Object.assign({}, process.env); // Shallow clone it.
  23409. console.log('Running exlr pull : ' + path__default['default'].dirname(__dirname));
  23410. processedArgs.useGitPull || false;
  23411. if(def.elevated || def.repos) {
  23412. if(def.elevated) def.requiresElevation = true;
  23413. else delete def.requiresElevation;
  23414. }
  23415. else {
  23416. if(def.requiresElevation) def.elevated = [def];
  23417. else def.repos = [def];
  23418. }
  23419. var regularpulltasks = function(){ return Promise.resolve(true) };
  23420. if(def.elevated){
  23421. elevatedpulltasks = function() {
  23422. return any(def.elevated.map((def) => performPull(def.repo))).then(() => {
  23423. return true;
  23424. }).catch((e) => {
  23425. console.error(e);
  23426. })
  23427. };
  23428. }
  23429. if(def.repos) {
  23430. var regularpulltasks = function(){
  23431. var pendingpulls = [];
  23432. def.repos.forEach((def) => { pendingpulls.push(performPull(def.repo)); });
  23433. return Promise.all(pendingpulls).finally(Traq.finally)
  23434. };
  23435. }
  23436. if(elevatedpulltasks) return getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  23437. else return getTaskWithoutElevation({ regularpulltasks})
  23438. }
  23439. };
  23440. function preworkerconfig(){
  23441. // Everything runs after this check is completed. Elevation occurs out of process when needed.
  23442. gitRepos = repomanifest.repos;
  23443. // gitRepos = ['chess-server-lib'];
  23444. // Repositiories that have symlinks that require elevated priviletes in windows to create symlinks
  23445. elevatedRunasRepos = repomanifest.elevated;
  23446. // Repos that should excluded from merge for releases...
  23447. exludeMergeRepos = repomanifest.exludeMergeRepos;
  23448. }
  23449. // The main elxr cli process
  23450. function elxrworker() {
  23451. var subcommandlabels = {
  23452. remote : (`remote ${processedArgs._[1] || ''}`).trim()
  23453. };
  23454. var __runcmd = function (label) {
  23455. var distinquishedlabel = subcommandlabels[label] || label;
  23456. return op[distinquishedlabel] ? op[distinquishedlabel](processedArgs) : null;
  23457. };
  23458. // --runas
  23459. if (processedArgs.runas) {
  23460. // Weve been asked to run in priviledged mode. Check if we already are privileged.
  23461. return __runcmd('runas')
  23462. }
  23463. else return __runcmd(processedArgs.label || processedArgs._[0] || 'h');
  23464. }
  23465. var getManifest = function () {
  23466. // Once choices are made we need to load config according to those choices.
  23467. // No trace of a previous run...
  23468. // Default Config...
  23469. return repomanifest = selectedinstance;
  23470. };
  23471. function acquireChoices(selectedinstance) {
  23472. console.warn(source.yellow(`
  23473. -------------------------------------------------------------------------------
  23474. Warning : Cannot locate your preferred configuration since it was not specified
  23475. You should fork the default chess configuration to customize and make it
  23476. your own instance with a named config as
  23477. {{yourowninstancename}}-config-{{yourchosenenvironment}}
  23478. And then run this tool as follows
  23479. NODE_ENV={{yourchosenenvironment}} elxr i {{yourowninstancename}}
  23480. OR
  23481. Run this tool with the following command to use a quick start default.
  23482. elxr --default
  23483. OR
  23484. Choose one of the options below to run interactively.
  23485. We will run your choice at the next prompt.
  23486. -------------------------------------------------------------------------------
  23487. `));
  23488. var prompt = cliverse.prompter;
  23489. return prompt.ask(`Choose an option :
  23490. d) Install the default chess instance.
  23491. => elxr i chess node_env=development --default
  23492. n) Create your custom new instance interactively
  23493. => elxr i {{instanceName}} node_env={{environment}}
  23494. i) Choose an instance and environment to install
  23495. => elxr i {{instanceName}} node_env={{environment}}
  23496. c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  23497. => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  23498. h) Help
  23499. q) Quit
  23500. Default <= d
  23501. : `).then((choice) => {
  23502. if (choice && choice === 'd' || !choice) {
  23503. processedArgs._[0] = 'i';
  23504. selectedinstance.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess';
  23505. selectedinstance.node_env = processedArgs.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env || 'development';
  23506. selectedinstance.reposerver = 'https://git.bbh.org.in';
  23507. getManifest(); // PB : TODO -- acquire the manifest directly from http url instead of clone before cloning the config. Since
  23508. // This is because the manifest at any server location can redirect to the preferred server..
  23509. }
  23510. else if (choice === 'h') {
  23511. processedArgs._[0] = 'h';
  23512. fs.writeFileSync('run.done', 'noop help');
  23513. console.log(elxr.help()); process.exit();
  23514. }
  23515. else if (choice === 'n' || choice === 'i') {
  23516. var p1 = cliverse.prompter;
  23517. return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  23518. processedArgs._[0] = 'i';
  23519. selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName;
  23520. return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  23521. selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env;
  23522. if (choice === 'n') {
  23523. selectedinstance.reposerver = 'https://git.bbh.org.in';
  23524. console.warn(
  23525. source.magenta('No Option Available. Your account may not have privileges. You can request here http://git.bbh.org.in/chess'));
  23526. process.exit();
  23527. }
  23528. return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  23529. selectedinstance.reposerver = reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in';
  23530. })
  23531. })
  23532. })
  23533. } else if (choice === 'c') {
  23534. var p1 = cliverse.prompter;
  23535. return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  23536. selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName;
  23537. return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  23538. selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env;
  23539. return p1.ask(`Enter cmd :
  23540. p) pull
  23541. Default <= p
  23542. : `).then(function (cmd) {
  23543. if (!cmd || cmd === 'p') {
  23544. processedArgs._[0] = 'pull';
  23545. }
  23546. else processedArgs._[0] = cmd;
  23547. return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  23548. selectedinstance.reposerver = reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in';
  23549. })
  23550. })
  23551. })
  23552. })
  23553. } else {
  23554. console.log(source.gray(`Default option not exercised. Please follow manual instructions to customize your instance here http://git.bbh.org.in/chess and try again.`));
  23555. fs.writeFileSync('run.log', ', ' + JSON.stringify({ success: 'quit without execution' }), { 'flag': 'a+' });
  23556. fs.writeFileSync('run.done', 'noop quit');
  23557. process.exit();
  23558. }
  23559. })
  23560. }
  23561. var mergeObjByKey = function(arrOfObjs, keyName) {
  23562. var keyedDistinct = {};
  23563. var distinctArrOfObjs = [];
  23564. arrOfObjs.forEach( o => {
  23565. if(o) (keyedDistinct[o[keyName]] || (keyedDistinct[o[keyName]] = []) ).push(o);
  23566. });
  23567. Object.keys(keyedDistinct).forEach(key => {
  23568. distinctArrOfObjs.push( bbhverse.assign( ...keyedDistinct[key] ) ); // PB : TODO -- Shallow use utils.assign
  23569. });
  23570. return distinctArrOfObjs;
  23571. };
  23572. var cacheWriteInstanceConfig = function(chessinstances){
  23573. var instanceName = chessinstances['current_run'].instanceName;
  23574. var node_env = chessinstances['current_run'].node_env;
  23575. chessinstances[instanceName][node_env].repos = mergeObjByKey(chessinstances[instanceName][node_env].repos, 'repo') ;
  23576. chessinstances[instanceName][node_env].elevated = mergeObjByKey(chessinstances[instanceName][node_env].elevated, 'repo') ;
  23577. fs.writeFileSync(instanceroot + '/chessinstances.js', 'module.exports = ' + JSON.stringify(chessinstances, null, 2) + '', { 'flag': 'w' });
  23578. };
  23579. var acquireConfig = function (selected, chessinstances) {
  23580. var configrepo = selected.instanceName + '-config-' + selected.node_env;
  23581. return performPull(configrepo).then(() => {
  23582. var manifestpath = path__default['default'].normalize(selected.root + '/' + selected.instanceName + '-config-' + selected.node_env + '/repo-manifest');
  23583. repomanifest = commonjsRequire(manifestpath,"/$$rollup_base$$")();
  23584. chessinstances = chessinstances || {};
  23585. chessinstances[selected.instanceName] = chessinstances[selected.instanceName] || {};
  23586. chessinstances[selected.instanceName][selected.node_env] = chessinstances[selected.instanceName][selected.node_env] || {};
  23587. chessinstances['current_run'] = { instanceName: selected.instanceName, node_env: selected.node_env };
  23588. // Config from server always override merges into selection ecept for the current selection.
  23589. // PB : TODO -- utils.assign Array merges are non-distinct...
  23590. selectedinstance = bbhverse.assign(chessinstances[selected.instanceName][selected.node_env], selected, repomanifest);
  23591. // chessinstances[selectedinstance.instanceName][selectedinstance.node_env] = selectedinstance;
  23592. cacheWriteInstanceConfig(chessinstances);
  23593. selectedinstance = chessinstances[selected.instanceName][selected.node_env];
  23594. // PB : TODO -- We should probably write the new server config also...
  23595. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0]; // PB : TODO -- Attempt first one that is available and online...
  23596. ENV.NODE_ENV = selectedinstance.node_env;
  23597. })
  23598. .catch((e) => {
  23599. console.error(e);
  23600. console.error('Config acquisition failed.');
  23601. })
  23602. };
  23603. var launchpath = process.cwd().replace(/\\/, '/');
  23604. var thisscriptdir = __dirname;
  23605. var instanceroot = launchpath;
  23606. var detectInstance = function () {
  23607. console.log(`launchpath = ${launchpath}`);
  23608. console.log(`thisscriptdir = ${thisscriptdir}`);
  23609. var root = launchpath;
  23610. // We need a reference to the root director for elxr cli to be properly oriented.
  23611. if ((launchpath + path__default['default'].normalize('/elxr')) === thisscriptdir) {
  23612. // We ran unbuilt from the proper root with elxr subfolder.
  23613. console.log(`Instance Path : ${root}`);
  23614. }
  23615. else {
  23616. if (launchpath === thisscriptdir) {
  23617. // Same directory doesn't mean we are being run from elxr directory or the root directory.
  23618. // It could be a standalone elxr build which may or maynot be in the proper location.
  23619. if (BUILD_VERSION.indexOf('Version: {version} - built on {date}') > -1) {
  23620. // Unbuilt therefore we are in the elxr directory.
  23621. root = path__default['default'].normalize(launchpath + '/..');
  23622. }
  23623. else {
  23624. // Built version.
  23625. // check if we have a elxr subfolder.
  23626. if (fs.existsSync(launchpath + '/..' + path__default['default'].normalize('/elxr'))) {
  23627. // Probably in the right place.
  23628. root = path__default['default'].normalize(launchpath + '/..');
  23629. }
  23630. else {
  23631. // Assume launchpath is meaningless.
  23632. // Figure it out from the input instance name and environment parameters if we are in the right location.
  23633. root = path__default['default'].normalize(launchpath + '/' + processedArgs._[1] + '/' + processedArgs.node_env);
  23634. }
  23635. }
  23636. }
  23637. }
  23638. instanceroot = root.replace(/\\/, '/');
  23639. __default.root = root;
  23640. return Promise.resolve(__default);
  23641. };
  23642. //
  23643. var __default = {
  23644. // Default is public server only.
  23645. // All public repos are by default available.
  23646. reposervers: ['https://git.bbh.org.in']
  23647. , repos: [
  23648. 'setup'
  23649. , 'elxr'
  23650. , 'loopback-connector-mysql'
  23651. , 'loopback-jsonapi-model-serializer'
  23652. , 'loopback-component-jsonapi'
  23653. , 'ember-service-worker'
  23654. , 'ember-service-worker-asset-cache'
  23655. , 'ember-service-worker-cache-fallback'
  23656. , 'ember-service-worker-index'
  23657. , 'ember-sw-client-route'
  23658. ]
  23659. , elevated: []
  23660. , exludeMergeRepos: {}
  23661. , instanceName: 'chess'
  23662. // Runas windowshta clobbers and removes the NODE_ENV !!! We therefore pass it in.
  23663. , node_env: 'development'
  23664. };
  23665. var __interactve_promts = {
  23666. get reposerver(){
  23667. return cliverse.prompt(this.reposervers, 'git default repo').then(reposerver => {
  23668. Object.defineProperty(this, 'reposerver', {
  23669. value: reposerver,
  23670. writable: false,
  23671. configurable : true,
  23672. enumerable : true
  23673. });
  23674. return reposerver
  23675. })
  23676. }
  23677. , set reposerver(reposerver){
  23678. Object.defineProperty(this, 'reposerver', {
  23679. value: reposerver,
  23680. writable: false,
  23681. configurable : true,
  23682. enumerable : true
  23683. });
  23684. return reposerver
  23685. }
  23686. };
  23687. var downloadsdir = '../Downloads';
  23688. var prerequisites = [
  23689. {
  23690. shellcmd: 'git',
  23691. url: 'https://github.com/git-for-windows/git/releases/download/v2.31.0.windows.1/Git-2.31.0-64-bit.exe'
  23692. , installer: 'Git-2.31.0-64-bit.exe'
  23693. , installcmd: ['cmd', ['/c', 'start',
  23694. '/WAIT', path__default['default'].resolve(downloadsdir + '/' + 'Git-2.31.0-64-bit.exe')
  23695. , '/VERYSILENT'
  23696. // , '/MERGETASKS=!runcode' // This is required only for vscode...
  23697. ]]
  23698. , preinstallsteps: function() {
  23699. var prompt = cliverse.prompter;
  23700. var steps = [
  23701. () => {
  23702. if (!existsSync(downloadsdir + '/' + this.installer)) {
  23703. return nodeShellExec(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, [this.url, downloadsdir + '/' + this.installer])
  23704. }
  23705. else return Promise.resolve(true)
  23706. }
  23707. ];
  23708. var prompts = [
  23709. () => prompt.ask(`git user name : ( <= ${gitUser} )`).then((user) => { gitUser = user; })
  23710. , () => prompt.ask(`git email : ( <= ${gitEmail} )`).then((email) => { gitEmail = email; })
  23711. ];
  23712. return any([any(steps), any(prompts)])
  23713. }
  23714. , installsteps: function () {
  23715. return any([this.installcmd].map(callsheltask))
  23716. }
  23717. , postinstallsteps: function(){
  23718. var gitUser = 'guest';
  23719. var gitEmail = 'guest@bbh.org.in';
  23720. var prompts = [];
  23721. prompts.push(
  23722. ()=>{
  23723. var choices = { 0 : 'guest', 1 : 'chessdemo' };
  23724. return cliverse.prompt(choices, 'git user name').then(gituser => gitUser = gituser)
  23725. }
  23726. );
  23727. prompts.push(
  23728. ()=>{
  23729. var choices = { 0 : 'guest@bbh.org.in', 1 : 'chessdemo@bbh.org.in' };
  23730. return cliverse.prompt(choices, 'git user email').then(gitemail => gitEmail = gitemail)
  23731. }
  23732. );
  23733. return any(prompts).then(()=>{
  23734. var steps = [
  23735. ['git', ['config', '--global', '--add', 'user.name', `${gitUser}`]]
  23736. , ['git', ['config', '--global', '--add', 'user.email', `${gitEmail}`]]
  23737. ];
  23738. return any(steps.map(callsheltask)).then(() => {
  23739. })
  23740. });
  23741. }
  23742. , install: function () {
  23743. return any([ /*this.preinstallsteps,*/ this.installsteps.bind(this), this.postinstallsteps.bind(this)])
  23744. }
  23745. , verifyAndInstall : function(){
  23746. return getTaskCheckExists(this.shellcmd, { ignorefailures: true })().then((exists) => {
  23747. if(exists) {
  23748. // return any(['git', ['config', '--global', '-l']].map(callsheltask))
  23749. return this.getUser(null, this.postinstallsteps.bind(this))
  23750. }
  23751. return this.install();
  23752. });
  23753. }
  23754. , getUser : function(repo, onNoResult){
  23755. onNoResult = onNoResult || function(){return false};
  23756. var globalOrLocal = '--global';
  23757. if(!repo) globalOrLocal = '--global';
  23758. else globalOrLocal = '--local';
  23759. return any([['git', ['config', globalOrLocal, '--get-all', 'user.name']]].map(callsheltask)).then((result)=>{
  23760. // not yet configured.
  23761. if(!result.success) return onNoResult()
  23762. else {
  23763. var users = result.messages[0].trim().split('\n');
  23764. if(users.length === 0 ||
  23765. users.length === 1 && users[0] === 'guest') {
  23766. return onNoResult()
  23767. }
  23768. else return users[0]; // PB : TODO == We should probably prompt with all the users available for selection !
  23769. }
  23770. })
  23771. .catch((e)=>{
  23772. console.log(e);
  23773. return onNoResult()
  23774. })
  23775. }
  23776. }
  23777. ,
  23778. {
  23779. shellcmd: 'node',
  23780. url: 'https://nodejs.org/dist/v14.16.0/node-v14.16.0-x64.msi'
  23781. , installer: 'node-v14.16.0-x64.msi'
  23782. , installcmd: ['MSIEXEC.exe', ['/i'
  23783. , path__default['default'].resolve(downloadsdir + '/' + 'node-v14.16.0-x64.msi')
  23784. , 'ACCEPT=YES', '/passive']]
  23785. , install : function() { return any([this.installcmd].map(callsheltask)).then(() => { }) }
  23786. }
  23787. ];
  23788. prerequisites.forEach(p=>{ prerequisites[p.shellcmd] = p; });
  23789. function ensureDirectoryExistence(filePath) {
  23790. var dirname = path__default['default'].dirname(filePath);
  23791. if (fs.existsSync(dirname)) {
  23792. return filePath;
  23793. }
  23794. ensureDirectoryExistence(dirname);
  23795. fs.mkdirSync(dirname);
  23796. return filePath;
  23797. }
  23798. var mainTasks = [];
  23799. function verifyAndInstallPrerequisites() {
  23800. fs.writeFileSync(ensureDirectoryExistence(path__default['default'].normalize(`${selectedinstance.root}/${downloadsdir}/readme.txt`)), `${getVersion()} Your local downloads for this instance`);
  23801. // PB : TODO include and build from files... using rollup..
  23802. var downloadbatch =
  23803. `::**************************************************************************
  23804. :Download_ <url> <File>
  23805. Powershell.exe ^
  23806. $AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'; ^
  23807. [System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols; ^
  23808. (New-Object System.Net.WebClient).DownloadFile('%1','%2')
  23809. exit /b
  23810. ::**************************************************************************`;
  23811. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, downloadbatch);
  23812. var windowselevate =
  23813. `
  23814. <html><HTA:APPLICATION ID="windowselevate" icon="#"/>
  23815. <script language="vbscript">
  23816. document.title = "elxr control panel"
  23817. self.ResizeTo 200,600
  23818. Sub Window_Onload
  23819. self.MoveTo (screen.availWidth - (document.body.clientWidth + 40)),10
  23820. End Sub
  23821. Set objShell = CreateObject("WScript.Shell")
  23822. Set objENV = objShell.Environment("Process")
  23823. dim NODE_ENV
  23824. NODE_ENV = objENV("NODE_ENV")
  23825. </script>
  23826. <script language="javascript">
  23827. //WINDOWSTATE="minimize" SHOWINTASKBAR="no" SYSMENU="no" CAPTION="no"
  23828. // https://devblogs.microsoft.com/scripting/how-can-i-pass-command-line-variables-to-an-hta-when-it-starts/
  23829. // alert(windowselevate.commandLine)
  23830. var args = windowselevate.commandLine.split('"').slice(3);
  23831. // alert(args)
  23832. var processedArgs = { _ : [] }
  23833. var namedArgs = [];
  23834. for(var item in args){
  23835. if(args[item].charAt(0) === '-'){
  23836. namedArgs.push(args[item])
  23837. var split = args[item].split('=');
  23838. processedArgs[split[0].slice(2)] = split[1] || true;
  23839. }
  23840. else processedArgs._.push(args[item]);
  23841. }
  23842. // args = args.forEach(function(item){ })
  23843. // alert('processedArgs._ : ' + processedArgs._);
  23844. // alert(processedArgs.runas);
  23845. // PB : TODO -- Convert all the cli args back to string.
  23846. var cargs = (processedArgs.debug ? '--inspect-brk=9228' : '') + ' elxr ' + processedArgs._.join(' ') + ' ' + namedArgs.join(' ');
  23847. // alert(cargs)
  23848. var shell = new ActiveXObject('shell.application');
  23849. // alert('launching node privilged. ' + processedArgs['nodepath'])
  23850. // shell.ShellExecute('where', 'node', '', '', 10);
  23851. shell.ShellExecute('node', cargs, '', 'runas', 1);
  23852. // shell.ShellExecute(processedArgs['nodepath'], cargs, '', 'runas', 1);
  23853. var fso = new ActiveXObject('Scripting.FileSystemObject');
  23854. window.onload = function() {
  23855. document.body.style.backgroundColor = 'black';
  23856. document.body.style.fontFamily = 'arial';
  23857. var log = document.createElement('div');
  23858. log.innerHTML='Please Wait';
  23859. function l(msg){ log.innerHTML+= msg; };
  23860. log.style.color = 'blue';
  23861. log.style.width = '95%';
  23862. log.id = 'log';
  23863. document.body.appendChild(log);
  23864. l('<Br/>Current config : ')
  23865. l('<Br/>NODE_ENV = ' + NODE_ENV)
  23866. l('<Br/>cmd = ' + processedArgs._[0])
  23867. processedArgs._[1] === 'use' ? l('<Br/>using = ' + processedArgs._[2]) : null;
  23868. l('<Br/><Br/>')
  23869. var timer = function(){
  23870. l('.');
  23871. if(fso.FileExists("run.done")) close();
  23872. else window.setTimeout(timer, 1000);
  23873. };
  23874. window.setTimeout(timer, 3000);
  23875. };
  23876. </script>
  23877. </html>
  23878. `;
  23879. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`, windowselevate);
  23880. var downloadtasks = [];
  23881. var installtasks = [];
  23882. prerequisites.forEach(preq => {
  23883. downloadtasks.push(getTaskCheckExists(preq.shellcmd, { ignorefailures: true })().then((exists) => {
  23884. if (exists) console.log(`${preq.shellcmd} exists`);
  23885. else {
  23886. console.log(`${preq.shellcmd} is not installed`);
  23887. return preq.preinstallsteps.call(preq).then(() => {
  23888. installtasks.push(preq.install.bind(preq));
  23889. })
  23890. }
  23891. }));
  23892. });
  23893. return Promise.all(downloadtasks).then(() => { return any(installtasks) })
  23894. }
  23895. var getPromptableAsyncPropDescriptor = function(propName, choices, defaultchoise){
  23896. return {
  23897. get (){
  23898. return cliverse.prompt( choices, propName, defaultchoise).then(propValue => {
  23899. Object.defineProperty(this, propName, {
  23900. value: propValue,
  23901. writable: false,
  23902. configurable : true,
  23903. enumerable : true
  23904. });
  23905. return propValue
  23906. })
  23907. }
  23908. // , set (propValue){
  23909. // Object.defineProperty(this, propName, {
  23910. // value: propValue,
  23911. // writable: false,
  23912. // configurable : true,
  23913. // enumerable : true
  23914. // })
  23915. // return propValue;
  23916. // }
  23917. , configurable : true
  23918. , enumerable : true
  23919. }
  23920. };
  23921. // function updateselection(selected) { selectedinstance = utils.assign(selectedinstance, selected) }
  23922. var selectedinstance = null;
  23923. var chessinstances = { current_run : {} };
  23924. acquireElevationState().then(() => {
  23925. var clioverrides = { };
  23926. function initinstances(chessinstances, selected) {
  23927. chessinstances.current_run.instanceName = processedArgs._[1] = processedArgs._[1] || chessinstances.current_run.instanceName || selected.instanceName;
  23928. chessinstances.current_run.node_env = processedArgs.node_env = processedArgs.node_env || chessinstances.current_run.node_env || selected.node_env;
  23929. chessinstances[chessinstances.current_run.instanceName] = chessinstances[chessinstances.current_run.instanceName] || {};
  23930. // Override sequence.
  23931. // __default, chessinstances[current_run], instanceName-config-development, cliargs, interactve_promts
  23932. selectedinstance = Object.assign(
  23933. selected
  23934. , chessinstances[chessinstances.current_run.instanceName][chessinstances.current_run.node_env]
  23935. , clioverrides
  23936. // , __interactve_promts -- Cant just override. Also need selectedinstance to be ready...
  23937. );
  23938. repomanifest = selectedinstance;
  23939. return chessinstances
  23940. }
  23941. function acquirelocalinstances(selected){
  23942. var chessinstances = bbhverse.assign(commonjsRequire(path__default['default'].normalize(selected.root + '/chessinstances.js'),"/$$rollup_base$$"));
  23943. return chessinstances
  23944. }
  23945. var noprerequisites = {
  23946. add : true, 'set-url' : true, 'repo-relocate' : true
  23947. , remote : true
  23948. };
  23949. var skipprereqs = {};
  23950. var maintask = () => {
  23951. // Default cmd to run !
  23952. processedArgs._[0] === processedArgs._[0] || 'pull';
  23953. // selectedinstance.reposerver = repomanifest.reposervers[0] // PB : TODO -- Attempt first one that is available and online from all that are available...
  23954. if(!noprerequisites[processedArgs._[0]]
  23955. && !skipprereqs[processedArgs._[0]]
  23956. ) {
  23957. return prerequisites.git.verifyAndInstall().then(()=>{
  23958. return acquireConfig(selectedinstance, chessinstances).catch((err) => {
  23959. console.error('Chosen cofiguraton failed or not found. Fix config and rerun or chose another.');
  23960. console.error(err);
  23961. }).then(() => { preworkerconfig(); return elxrworker() })
  23962. // .finally(()=>{
  23963. // fs.writeFileSync('run.log', ', ' + JSON.stringify({ error: e.message }), { 'flag': 'a+' })
  23964. // if(!e.success) fs.writeFileSync('run.done', 'error');
  23965. // // return process.exit()
  23966. // })
  23967. })
  23968. }
  23969. else {
  23970. console.log('cmd has no preqs or has been configured to skip preqs');
  23971. preworkerconfig();
  23972. return elxrworker()
  23973. }
  23974. };
  23975. const retaincount = 2;
  23976. var min = runtimestamp;
  23977. var collect = [];
  23978. if(noprerequisites[processedArgs._[0]]
  23979. || skipprereqs[processedArgs._[0]]
  23980. ) {
  23981. return elxrworker()
  23982. }
  23983. return detectInstance().then((detectedInstance)=>{
  23984. processedArgs._[1] ? clioverrides.instanceName = processedArgs._[1]: null;
  23985. processedArgs.node_env ? clioverrides.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env
  23986. : (process.env.NODE_ENV && process.env.NODE_ENV.trim()) ? clioverrides.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()): null;
  23987. selectedinstance = Object.assign(detectedInstance, clioverrides);
  23988. var todo = Promise.resolve(true);
  23989. var promptkeys = { 'instanceName' : processedArgs._[1] };
  23990. var reconfirm = {
  23991. 'instanceName' : selectedinstance['instanceName'] === 'chess'
  23992. };
  23993. var prompts = [];
  23994. var eachPrompt = function(k, i, a){
  23995. // No local instances config found. We use a default initialized instance available in selectedinstance
  23996. // Confirm those that were not supplied as user choices in runtime args and proceed to reattempt.
  23997. if(promptkeys[k] && selectedinstance[k] !== promptkeys[k] || promptkeys[k] === undefined && selectedinstance[k] === undefined
  23998. || reconfirm[k]) {
  23999. prompts.push(async ()=>{
  24000. // PB : NOTE -- Important in async cases when this needs to be in the same state as when it was invoked.
  24001. // We take a snapshot... Shallow.. !! If required deep should be used based on use case.
  24002. // If latest altered state is required we can reerence this directly.
  24003. // var asyncthis = Object.assign(this);
  24004. Object.defineProperty(selectedinstance, k, getPromptableAsyncPropDescriptor(k, choices[k], promptkeys[k] || selectedinstance[k] ));
  24005. return await selectedinstance[k]
  24006. });
  24007. }
  24008. delete promptkeys[k];
  24009. };
  24010. try {
  24011. chessinstances = acquirelocalinstances(selectedinstance);
  24012. initinstances(chessinstances, selectedinstance);
  24013. var instanceNameChoices = new Set(Object.keys( chessinstances) );
  24014. instanceNameChoices.delete('current_run');
  24015. instanceNameChoices.add(selectedinstance['instanceName']);
  24016. if(promptkeys['instanceName']) instanceNameChoices.add(promptkeys['instanceName']);
  24017. var choices = {
  24018. 'instanceName' : Array.from(instanceNameChoices)
  24019. , 'reposerver' : selectedinstance['reposervers']
  24020. };
  24021. Object.keys(__interactve_promts).forEach(eachPrompt, __interactve_promts);
  24022. Object.keys(promptkeys).forEach(eachPrompt, promptkeys);
  24023. todo = any(prompts).then(()=>{ return selectedinstance });
  24024. }
  24025. catch (e) {
  24026. console.error(e); // Missing chessinstances is not an error...
  24027. initinstances(chessinstances, selectedinstance);
  24028. var instanceNameChoices = new Set(Object.keys( chessinstances) );
  24029. instanceNameChoices.delete('current_run');
  24030. instanceNameChoices.add(selectedinstance['instanceName']);
  24031. if(promptkeys['instanceName']) instanceNameChoices.add(promptkeys['instanceName']);
  24032. var choices = {
  24033. 'instanceName' : Array.from(instanceNameChoices)
  24034. , 'reposerver' : selectedinstance['reposervers']
  24035. };
  24036. Object.keys(__interactve_promts).forEach(eachPrompt, __interactve_promts);
  24037. Object.keys(promptkeys).forEach(eachPrompt, promptkeys);
  24038. todo = any(prompts).then(()=>{ return selectedinstance });
  24039. if(!processedArgs._[0] || !selectedinstance.node_env || !selectedinstance.instanceName){
  24040. // Weve been told what to do.
  24041. todo = todo.then(() => { return acquireChoices(selectedinstance) });
  24042. }
  24043. todo = todo.then(() => {
  24044. try {
  24045. chessinstances = acquirelocalinstances(selectedinstance);
  24046. initinstances(chessinstances, selectedinstance);
  24047. }
  24048. catch (e) {
  24049. console.error(e);
  24050. console.log('No local instances config found in current root = ' + selectedinstance.root);
  24051. console.log('A config will be createed with the instance and environment chosen...');
  24052. // return (async ()=>{return await __default.reposerver})().then(()=>{
  24053. // // selectedinstance = Object.assign(detectedInstance, clioverrides);
  24054. // return selectedinstance = Object.assign(__default, selectedinstance);
  24055. // })
  24056. return selectedinstance
  24057. }
  24058. });
  24059. }
  24060. return todo
  24061. })
  24062. .then(()=>{
  24063. if(!__isElevated) {
  24064. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/readme.txt`);
  24065. // collect garbage
  24066. return dirs( (dir)=>{
  24067. var matches = /run-(.*)/gm.exec(dir.name);
  24068. if(matches) {
  24069. if(+(matches[1]) < min) {
  24070. min = matches[1];
  24071. collect.splice( 0, 0, matches[1] );
  24072. }
  24073. else collect.push(matches[1]);
  24074. }
  24075. }, `${selectedinstance.root}/.elxr` ).then(()=>{
  24076. // delete garbage
  24077. if(collect.length > retaincount) {
  24078. var asyncs = [];
  24079. while((collect.length - asyncs.length) > retaincount) {
  24080. asyncs.push(getShellTask('rm',['-rf', `run-${collect[asyncs.length]}`], { cwd : `${selectedinstance.root}/.elxr` })());
  24081. }
  24082. return Promise.all(asyncs)
  24083. }
  24084. else return true
  24085. })
  24086. }
  24087. else return true;
  24088. })
  24089. .then(()=>{
  24090. // PB : TODO -- Keep only the last n runs...
  24091. // Currently it retains 2*n when proc needs to be relaunched in elevated mode !!!
  24092. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`);
  24093. if (!__isElevated || processedArgs.forceprereqs && !__isElevated ) mainTasks.push(verifyAndInstallPrerequisites);
  24094. mainTasks.push(maintask);
  24095. return any(mainTasks);
  24096. })
  24097. });
  24098. // Sample instances config.
  24099. // var instances = {
  24100. // "elixir": {
  24101. // "production": {
  24102. // "reposervers": ["http://git.bbh", "https://git.bbh.org.in"]
  24103. // , "repos": ["ember-masonry-grid", "client", "elixir-client"]
  24104. // , "exludeMergeRepos": {
  24105. // "elixir-config-development": true, "elixir-config-test": true
  24106. // , "elixir-config-production": true, "elixir-data": true
  24107. // }
  24108. // , "instanceName": "elixir", "node_env": "production"
  24109. // }
  24110. // },
  24111. // "current_run": { "instanceName": "elixir", "node_env": "production" }
  24112. // }
  24113. // ,([^\}^\S\r]*?\}) // Regexp to eliminate extra comma at the end of an array or an object...
  24114. var elxr_1 = {
  24115. };
  24116. module.exports = elxr_1;