vendor-index.ae96af6e.mjs 171 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291
  1. import require$$0 from 'readline';
  2. import require$$2 from 'events';
  3. function _mergeNamespaces(n, m) {
  4. m.forEach(function (e) {
  5. e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) {
  6. if (k !== 'default' && !(k in n)) {
  7. var d = Object.getOwnPropertyDescriptor(e, k);
  8. Object.defineProperty(n, k, d.get ? d : {
  9. enumerable: true,
  10. get: function () { return e[k]; }
  11. });
  12. }
  13. });
  14. });
  15. return Object.freeze(n);
  16. }
  17. var prompts$2 = {};
  18. var kleur;
  19. var hasRequiredKleur;
  20. function requireKleur () {
  21. if (hasRequiredKleur) return kleur;
  22. hasRequiredKleur = 1;
  23. const { FORCE_COLOR, NODE_DISABLE_COLORS, TERM } = process.env;
  24. const $ = {
  25. enabled: !NODE_DISABLE_COLORS && TERM !== 'dumb' && FORCE_COLOR !== '0',
  26. // modifiers
  27. reset: init(0, 0),
  28. bold: init(1, 22),
  29. dim: init(2, 22),
  30. italic: init(3, 23),
  31. underline: init(4, 24),
  32. inverse: init(7, 27),
  33. hidden: init(8, 28),
  34. strikethrough: init(9, 29),
  35. // colors
  36. black: init(30, 39),
  37. red: init(31, 39),
  38. green: init(32, 39),
  39. yellow: init(33, 39),
  40. blue: init(34, 39),
  41. magenta: init(35, 39),
  42. cyan: init(36, 39),
  43. white: init(37, 39),
  44. gray: init(90, 39),
  45. grey: init(90, 39),
  46. // background colors
  47. bgBlack: init(40, 49),
  48. bgRed: init(41, 49),
  49. bgGreen: init(42, 49),
  50. bgYellow: init(43, 49),
  51. bgBlue: init(44, 49),
  52. bgMagenta: init(45, 49),
  53. bgCyan: init(46, 49),
  54. bgWhite: init(47, 49)
  55. };
  56. function run(arr, str) {
  57. let i=0, tmp, beg='', end='';
  58. for (; i < arr.length; i++) {
  59. tmp = arr[i];
  60. beg += tmp.open;
  61. end += tmp.close;
  62. if (str.includes(tmp.close)) {
  63. str = str.replace(tmp.rgx, tmp.close + tmp.open);
  64. }
  65. }
  66. return beg + str + end;
  67. }
  68. function chain(has, keys) {
  69. let ctx = { has, keys };
  70. ctx.reset = $.reset.bind(ctx);
  71. ctx.bold = $.bold.bind(ctx);
  72. ctx.dim = $.dim.bind(ctx);
  73. ctx.italic = $.italic.bind(ctx);
  74. ctx.underline = $.underline.bind(ctx);
  75. ctx.inverse = $.inverse.bind(ctx);
  76. ctx.hidden = $.hidden.bind(ctx);
  77. ctx.strikethrough = $.strikethrough.bind(ctx);
  78. ctx.black = $.black.bind(ctx);
  79. ctx.red = $.red.bind(ctx);
  80. ctx.green = $.green.bind(ctx);
  81. ctx.yellow = $.yellow.bind(ctx);
  82. ctx.blue = $.blue.bind(ctx);
  83. ctx.magenta = $.magenta.bind(ctx);
  84. ctx.cyan = $.cyan.bind(ctx);
  85. ctx.white = $.white.bind(ctx);
  86. ctx.gray = $.gray.bind(ctx);
  87. ctx.grey = $.grey.bind(ctx);
  88. ctx.bgBlack = $.bgBlack.bind(ctx);
  89. ctx.bgRed = $.bgRed.bind(ctx);
  90. ctx.bgGreen = $.bgGreen.bind(ctx);
  91. ctx.bgYellow = $.bgYellow.bind(ctx);
  92. ctx.bgBlue = $.bgBlue.bind(ctx);
  93. ctx.bgMagenta = $.bgMagenta.bind(ctx);
  94. ctx.bgCyan = $.bgCyan.bind(ctx);
  95. ctx.bgWhite = $.bgWhite.bind(ctx);
  96. return ctx;
  97. }
  98. function init(open, close) {
  99. let blk = {
  100. open: `\x1b[${open}m`,
  101. close: `\x1b[${close}m`,
  102. rgx: new RegExp(`\\x1b\\[${close}m`, 'g')
  103. };
  104. return function (txt) {
  105. if (this !== void 0 && this.has !== void 0) {
  106. this.has.includes(open) || (this.has.push(open),this.keys.push(blk));
  107. return txt === void 0 ? this : $.enabled ? run(this.keys, txt+'') : txt+'';
  108. }
  109. return txt === void 0 ? chain([open], [blk]) : $.enabled ? run([blk], txt+'') : txt+'';
  110. };
  111. }
  112. kleur = $;
  113. return kleur;
  114. }
  115. var action$1;
  116. var hasRequiredAction$1;
  117. function requireAction$1 () {
  118. if (hasRequiredAction$1) return action$1;
  119. hasRequiredAction$1 = 1;
  120. action$1 = (key, isSelect) => {
  121. if (key.meta && key.name !== 'escape') return;
  122. if (key.ctrl) {
  123. if (key.name === 'a') return 'first';
  124. if (key.name === 'c') return 'abort';
  125. if (key.name === 'd') return 'abort';
  126. if (key.name === 'e') return 'last';
  127. if (key.name === 'g') return 'reset';
  128. }
  129. if (isSelect) {
  130. if (key.name === 'j') return 'down';
  131. if (key.name === 'k') return 'up';
  132. }
  133. if (key.name === 'return') return 'submit';
  134. if (key.name === 'enter') return 'submit'; // ctrl + J
  135. if (key.name === 'backspace') return 'delete';
  136. if (key.name === 'delete') return 'deleteForward';
  137. if (key.name === 'abort') return 'abort';
  138. if (key.name === 'escape') return 'exit';
  139. if (key.name === 'tab') return 'next';
  140. if (key.name === 'pagedown') return 'nextPage';
  141. if (key.name === 'pageup') return 'prevPage'; // TODO create home() in prompt types (e.g. TextPrompt)
  142. if (key.name === 'home') return 'home'; // TODO create end() in prompt types (e.g. TextPrompt)
  143. if (key.name === 'end') return 'end';
  144. if (key.name === 'up') return 'up';
  145. if (key.name === 'down') return 'down';
  146. if (key.name === 'right') return 'right';
  147. if (key.name === 'left') return 'left';
  148. return false;
  149. };
  150. return action$1;
  151. }
  152. var strip$1;
  153. var hasRequiredStrip$1;
  154. function requireStrip$1 () {
  155. if (hasRequiredStrip$1) return strip$1;
  156. hasRequiredStrip$1 = 1;
  157. strip$1 = str => {
  158. const pattern = ['[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))'].join('|');
  159. const RGX = new RegExp(pattern, 'g');
  160. return typeof str === 'string' ? str.replace(RGX, '') : str;
  161. };
  162. return strip$1;
  163. }
  164. var src;
  165. var hasRequiredSrc;
  166. function requireSrc () {
  167. if (hasRequiredSrc) return src;
  168. hasRequiredSrc = 1;
  169. const ESC = '\x1B';
  170. const CSI = `${ESC}[`;
  171. const beep = '\u0007';
  172. const cursor = {
  173. to(x, y) {
  174. if (!y) return `${CSI}${x + 1}G`;
  175. return `${CSI}${y + 1};${x + 1}H`;
  176. },
  177. move(x, y) {
  178. let ret = '';
  179. if (x < 0) ret += `${CSI}${-x}D`;
  180. else if (x > 0) ret += `${CSI}${x}C`;
  181. if (y < 0) ret += `${CSI}${-y}A`;
  182. else if (y > 0) ret += `${CSI}${y}B`;
  183. return ret;
  184. },
  185. up: (count = 1) => `${CSI}${count}A`,
  186. down: (count = 1) => `${CSI}${count}B`,
  187. forward: (count = 1) => `${CSI}${count}C`,
  188. backward: (count = 1) => `${CSI}${count}D`,
  189. nextLine: (count = 1) => `${CSI}E`.repeat(count),
  190. prevLine: (count = 1) => `${CSI}F`.repeat(count),
  191. left: `${CSI}G`,
  192. hide: `${CSI}?25l`,
  193. show: `${CSI}?25h`,
  194. save: `${ESC}7`,
  195. restore: `${ESC}8`
  196. };
  197. const scroll = {
  198. up: (count = 1) => `${CSI}S`.repeat(count),
  199. down: (count = 1) => `${CSI}T`.repeat(count)
  200. };
  201. const erase = {
  202. screen: `${CSI}2J`,
  203. up: (count = 1) => `${CSI}1J`.repeat(count),
  204. down: (count = 1) => `${CSI}J`.repeat(count),
  205. line: `${CSI}2K`,
  206. lineEnd: `${CSI}K`,
  207. lineStart: `${CSI}1K`,
  208. lines(count) {
  209. let clear = '';
  210. for (let i = 0; i < count; i++)
  211. clear += this.line + (i < count - 1 ? cursor.up() : '');
  212. if (count)
  213. clear += cursor.left;
  214. return clear;
  215. }
  216. };
  217. src = { cursor, scroll, erase, beep };
  218. return src;
  219. }
  220. var clear$1;
  221. var hasRequiredClear$1;
  222. function requireClear$1 () {
  223. if (hasRequiredClear$1) return clear$1;
  224. hasRequiredClear$1 = 1;
  225. function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
  226. function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
  227. function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
  228. const strip = requireStrip$1();
  229. const _require = requireSrc(),
  230. erase = _require.erase,
  231. cursor = _require.cursor;
  232. const width = str => [...strip(str)].length;
  233. /**
  234. * @param {string} prompt
  235. * @param {number} perLine
  236. */
  237. clear$1 = function (prompt, perLine) {
  238. if (!perLine) return erase.line + cursor.to(0);
  239. let rows = 0;
  240. const lines = prompt.split(/\r?\n/);
  241. var _iterator = _createForOfIteratorHelper(lines),
  242. _step;
  243. try {
  244. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  245. let line = _step.value;
  246. rows += 1 + Math.floor(Math.max(width(line) - 1, 0) / perLine);
  247. }
  248. } catch (err) {
  249. _iterator.e(err);
  250. } finally {
  251. _iterator.f();
  252. }
  253. return erase.lines(rows);
  254. };
  255. return clear$1;
  256. }
  257. var figures_1$1;
  258. var hasRequiredFigures$1;
  259. function requireFigures$1 () {
  260. if (hasRequiredFigures$1) return figures_1$1;
  261. hasRequiredFigures$1 = 1;
  262. const main = {
  263. arrowUp: '↑',
  264. arrowDown: '↓',
  265. arrowLeft: '←',
  266. arrowRight: '→',
  267. radioOn: '◉',
  268. radioOff: '◯',
  269. tick: '✔',
  270. cross: '✖',
  271. ellipsis: '…',
  272. pointerSmall: '›',
  273. line: '─',
  274. pointer: '❯'
  275. };
  276. const win = {
  277. arrowUp: main.arrowUp,
  278. arrowDown: main.arrowDown,
  279. arrowLeft: main.arrowLeft,
  280. arrowRight: main.arrowRight,
  281. radioOn: '(*)',
  282. radioOff: '( )',
  283. tick: '√',
  284. cross: '×',
  285. ellipsis: '...',
  286. pointerSmall: '»',
  287. line: '─',
  288. pointer: '>'
  289. };
  290. const figures = process.platform === 'win32' ? win : main;
  291. figures_1$1 = figures;
  292. return figures_1$1;
  293. }
  294. var style$1;
  295. var hasRequiredStyle$1;
  296. function requireStyle$1 () {
  297. if (hasRequiredStyle$1) return style$1;
  298. hasRequiredStyle$1 = 1;
  299. const c = requireKleur();
  300. const figures = requireFigures$1(); // rendering user input.
  301. const styles = Object.freeze({
  302. password: {
  303. scale: 1,
  304. render: input => '*'.repeat(input.length)
  305. },
  306. emoji: {
  307. scale: 2,
  308. render: input => '😃'.repeat(input.length)
  309. },
  310. invisible: {
  311. scale: 0,
  312. render: input => ''
  313. },
  314. default: {
  315. scale: 1,
  316. render: input => `${input}`
  317. }
  318. });
  319. const render = type => styles[type] || styles.default; // icon to signalize a prompt.
  320. const symbols = Object.freeze({
  321. aborted: c.red(figures.cross),
  322. done: c.green(figures.tick),
  323. exited: c.yellow(figures.cross),
  324. default: c.cyan('?')
  325. });
  326. const symbol = (done, aborted, exited) => aborted ? symbols.aborted : exited ? symbols.exited : done ? symbols.done : symbols.default; // between the question and the user's input.
  327. const delimiter = completing => c.gray(completing ? figures.ellipsis : figures.pointerSmall);
  328. const item = (expandable, expanded) => c.gray(expandable ? expanded ? figures.pointerSmall : '+' : figures.line);
  329. style$1 = {
  330. styles,
  331. render,
  332. symbols,
  333. symbol,
  334. delimiter,
  335. item
  336. };
  337. return style$1;
  338. }
  339. var lines$1;
  340. var hasRequiredLines$1;
  341. function requireLines$1 () {
  342. if (hasRequiredLines$1) return lines$1;
  343. hasRequiredLines$1 = 1;
  344. const strip = requireStrip$1();
  345. /**
  346. * @param {string} msg
  347. * @param {number} perLine
  348. */
  349. lines$1 = function (msg, perLine) {
  350. let lines = String(strip(msg) || '').split(/\r?\n/);
  351. if (!perLine) return lines.length;
  352. return lines.map(l => Math.ceil(l.length / perLine)).reduce((a, b) => a + b);
  353. };
  354. return lines$1;
  355. }
  356. var wrap$1;
  357. var hasRequiredWrap$1;
  358. function requireWrap$1 () {
  359. if (hasRequiredWrap$1) return wrap$1;
  360. hasRequiredWrap$1 = 1;
  361. /**
  362. * @param {string} msg The message to wrap
  363. * @param {object} opts
  364. * @param {number|string} [opts.margin] Left margin
  365. * @param {number} opts.width Maximum characters per line including the margin
  366. */
  367. wrap$1 = (msg, opts = {}) => {
  368. const tab = Number.isSafeInteger(parseInt(opts.margin)) ? new Array(parseInt(opts.margin)).fill(' ').join('') : opts.margin || '';
  369. const width = opts.width;
  370. return (msg || '').split(/\r?\n/g).map(line => line.split(/\s+/g).reduce((arr, w) => {
  371. if (w.length + tab.length >= width || arr[arr.length - 1].length + w.length + 1 < width) arr[arr.length - 1] += ` ${w}`;else arr.push(`${tab}${w}`);
  372. return arr;
  373. }, [tab]).join('\n')).join('\n');
  374. };
  375. return wrap$1;
  376. }
  377. var entriesToDisplay$1;
  378. var hasRequiredEntriesToDisplay$1;
  379. function requireEntriesToDisplay$1 () {
  380. if (hasRequiredEntriesToDisplay$1) return entriesToDisplay$1;
  381. hasRequiredEntriesToDisplay$1 = 1;
  382. /**
  383. * Determine what entries should be displayed on the screen, based on the
  384. * currently selected index and the maximum visible. Used in list-based
  385. * prompts like `select` and `multiselect`.
  386. *
  387. * @param {number} cursor the currently selected entry
  388. * @param {number} total the total entries available to display
  389. * @param {number} [maxVisible] the number of entries that can be displayed
  390. */
  391. entriesToDisplay$1 = (cursor, total, maxVisible) => {
  392. maxVisible = maxVisible || total;
  393. let startIndex = Math.min(total - maxVisible, cursor - Math.floor(maxVisible / 2));
  394. if (startIndex < 0) startIndex = 0;
  395. let endIndex = Math.min(startIndex + maxVisible, total);
  396. return {
  397. startIndex,
  398. endIndex
  399. };
  400. };
  401. return entriesToDisplay$1;
  402. }
  403. var util$1;
  404. var hasRequiredUtil$1;
  405. function requireUtil$1 () {
  406. if (hasRequiredUtil$1) return util$1;
  407. hasRequiredUtil$1 = 1;
  408. util$1 = {
  409. action: requireAction$1(),
  410. clear: requireClear$1(),
  411. style: requireStyle$1(),
  412. strip: requireStrip$1(),
  413. figures: requireFigures$1(),
  414. lines: requireLines$1(),
  415. wrap: requireWrap$1(),
  416. entriesToDisplay: requireEntriesToDisplay$1()
  417. };
  418. return util$1;
  419. }
  420. var prompt$1;
  421. var hasRequiredPrompt$1;
  422. function requirePrompt$1 () {
  423. if (hasRequiredPrompt$1) return prompt$1;
  424. hasRequiredPrompt$1 = 1;
  425. const readline = require$$0;
  426. const _require = requireUtil$1(),
  427. action = _require.action;
  428. const EventEmitter = require$$2;
  429. const _require2 = requireSrc(),
  430. beep = _require2.beep,
  431. cursor = _require2.cursor;
  432. const color = requireKleur();
  433. /**
  434. * Base prompt skeleton
  435. * @param {Stream} [opts.stdin] The Readable stream to listen to
  436. * @param {Stream} [opts.stdout] The Writable stream to write readline data to
  437. */
  438. class Prompt extends EventEmitter {
  439. constructor(opts = {}) {
  440. super();
  441. this.firstRender = true;
  442. this.in = opts.stdin || process.stdin;
  443. this.out = opts.stdout || process.stdout;
  444. this.onRender = (opts.onRender || (() => void 0)).bind(this);
  445. const rl = readline.createInterface({
  446. input: this.in,
  447. escapeCodeTimeout: 50
  448. });
  449. readline.emitKeypressEvents(this.in, rl);
  450. if (this.in.isTTY) this.in.setRawMode(true);
  451. const isSelect = ['SelectPrompt', 'MultiselectPrompt'].indexOf(this.constructor.name) > -1;
  452. const keypress = (str, key) => {
  453. let a = action(key, isSelect);
  454. if (a === false) {
  455. this._ && this._(str, key);
  456. } else if (typeof this[a] === 'function') {
  457. this[a](key);
  458. } else {
  459. this.bell();
  460. }
  461. };
  462. this.close = () => {
  463. this.out.write(cursor.show);
  464. this.in.removeListener('keypress', keypress);
  465. if (this.in.isTTY) this.in.setRawMode(false);
  466. rl.close();
  467. this.emit(this.aborted ? 'abort' : this.exited ? 'exit' : 'submit', this.value);
  468. this.closed = true;
  469. };
  470. this.in.on('keypress', keypress);
  471. }
  472. fire() {
  473. this.emit('state', {
  474. value: this.value,
  475. aborted: !!this.aborted,
  476. exited: !!this.exited
  477. });
  478. }
  479. bell() {
  480. this.out.write(beep);
  481. }
  482. render() {
  483. this.onRender(color);
  484. if (this.firstRender) this.firstRender = false;
  485. }
  486. }
  487. prompt$1 = Prompt;
  488. return prompt$1;
  489. }
  490. var text$1;
  491. var hasRequiredText$1;
  492. function requireText$1 () {
  493. if (hasRequiredText$1) return text$1;
  494. hasRequiredText$1 = 1;
  495. function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
  496. function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
  497. const color = requireKleur();
  498. const Prompt = requirePrompt$1();
  499. const _require = requireSrc(),
  500. erase = _require.erase,
  501. cursor = _require.cursor;
  502. const _require2 = requireUtil$1(),
  503. style = _require2.style,
  504. clear = _require2.clear,
  505. lines = _require2.lines,
  506. figures = _require2.figures;
  507. /**
  508. * TextPrompt Base Element
  509. * @param {Object} opts Options
  510. * @param {String} opts.message Message
  511. * @param {String} [opts.style='default'] Render style
  512. * @param {String} [opts.initial] Default value
  513. * @param {Function} [opts.validate] Validate function
  514. * @param {Stream} [opts.stdin] The Readable stream to listen to
  515. * @param {Stream} [opts.stdout] The Writable stream to write readline data to
  516. * @param {String} [opts.error] The invalid error label
  517. */
  518. class TextPrompt extends Prompt {
  519. constructor(opts = {}) {
  520. super(opts);
  521. this.transform = style.render(opts.style);
  522. this.scale = this.transform.scale;
  523. this.msg = opts.message;
  524. this.initial = opts.initial || ``;
  525. this.validator = opts.validate || (() => true);
  526. this.value = ``;
  527. this.errorMsg = opts.error || `Please Enter A Valid Value`;
  528. this.cursor = Number(!!this.initial);
  529. this.cursorOffset = 0;
  530. this.clear = clear(``, this.out.columns);
  531. this.render();
  532. }
  533. set value(v) {
  534. if (!v && this.initial) {
  535. this.placeholder = true;
  536. this.rendered = color.gray(this.transform.render(this.initial));
  537. } else {
  538. this.placeholder = false;
  539. this.rendered = this.transform.render(v);
  540. }
  541. this._value = v;
  542. this.fire();
  543. }
  544. get value() {
  545. return this._value;
  546. }
  547. reset() {
  548. this.value = ``;
  549. this.cursor = Number(!!this.initial);
  550. this.cursorOffset = 0;
  551. this.fire();
  552. this.render();
  553. }
  554. exit() {
  555. this.abort();
  556. }
  557. abort() {
  558. this.value = this.value || this.initial;
  559. this.done = this.aborted = true;
  560. this.error = false;
  561. this.red = false;
  562. this.fire();
  563. this.render();
  564. this.out.write('\n');
  565. this.close();
  566. }
  567. validate() {
  568. var _this = this;
  569. return _asyncToGenerator(function* () {
  570. let valid = yield _this.validator(_this.value);
  571. if (typeof valid === `string`) {
  572. _this.errorMsg = valid;
  573. valid = false;
  574. }
  575. _this.error = !valid;
  576. })();
  577. }
  578. submit() {
  579. var _this2 = this;
  580. return _asyncToGenerator(function* () {
  581. _this2.value = _this2.value || _this2.initial;
  582. _this2.cursorOffset = 0;
  583. _this2.cursor = _this2.rendered.length;
  584. yield _this2.validate();
  585. if (_this2.error) {
  586. _this2.red = true;
  587. _this2.fire();
  588. _this2.render();
  589. return;
  590. }
  591. _this2.done = true;
  592. _this2.aborted = false;
  593. _this2.fire();
  594. _this2.render();
  595. _this2.out.write('\n');
  596. _this2.close();
  597. })();
  598. }
  599. next() {
  600. if (!this.placeholder) return this.bell();
  601. this.value = this.initial;
  602. this.cursor = this.rendered.length;
  603. this.fire();
  604. this.render();
  605. }
  606. moveCursor(n) {
  607. if (this.placeholder) return;
  608. this.cursor = this.cursor + n;
  609. this.cursorOffset += n;
  610. }
  611. _(c, key) {
  612. let s1 = this.value.slice(0, this.cursor);
  613. let s2 = this.value.slice(this.cursor);
  614. this.value = `${s1}${c}${s2}`;
  615. this.red = false;
  616. this.cursor = this.placeholder ? 0 : s1.length + 1;
  617. this.render();
  618. }
  619. delete() {
  620. if (this.isCursorAtStart()) return this.bell();
  621. let s1 = this.value.slice(0, this.cursor - 1);
  622. let s2 = this.value.slice(this.cursor);
  623. this.value = `${s1}${s2}`;
  624. this.red = false;
  625. if (this.isCursorAtStart()) {
  626. this.cursorOffset = 0;
  627. } else {
  628. this.cursorOffset++;
  629. this.moveCursor(-1);
  630. }
  631. this.render();
  632. }
  633. deleteForward() {
  634. if (this.cursor * this.scale >= this.rendered.length || this.placeholder) return this.bell();
  635. let s1 = this.value.slice(0, this.cursor);
  636. let s2 = this.value.slice(this.cursor + 1);
  637. this.value = `${s1}${s2}`;
  638. this.red = false;
  639. if (this.isCursorAtEnd()) {
  640. this.cursorOffset = 0;
  641. } else {
  642. this.cursorOffset++;
  643. }
  644. this.render();
  645. }
  646. first() {
  647. this.cursor = 0;
  648. this.render();
  649. }
  650. last() {
  651. this.cursor = this.value.length;
  652. this.render();
  653. }
  654. left() {
  655. if (this.cursor <= 0 || this.placeholder) return this.bell();
  656. this.moveCursor(-1);
  657. this.render();
  658. }
  659. right() {
  660. if (this.cursor * this.scale >= this.rendered.length || this.placeholder) return this.bell();
  661. this.moveCursor(1);
  662. this.render();
  663. }
  664. isCursorAtStart() {
  665. return this.cursor === 0 || this.placeholder && this.cursor === 1;
  666. }
  667. isCursorAtEnd() {
  668. return this.cursor === this.rendered.length || this.placeholder && this.cursor === this.rendered.length + 1;
  669. }
  670. render() {
  671. if (this.closed) return;
  672. if (!this.firstRender) {
  673. if (this.outputError) this.out.write(cursor.down(lines(this.outputError, this.out.columns) - 1) + clear(this.outputError, this.out.columns));
  674. this.out.write(clear(this.outputText, this.out.columns));
  675. }
  676. super.render();
  677. this.outputError = '';
  678. this.outputText = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(this.done), this.red ? color.red(this.rendered) : this.rendered].join(` `);
  679. if (this.error) {
  680. this.outputError += this.errorMsg.split(`\n`).reduce((a, l, i) => a + `\n${i ? ' ' : figures.pointerSmall} ${color.red().italic(l)}`, ``);
  681. }
  682. this.out.write(erase.line + cursor.to(0) + this.outputText + cursor.save + this.outputError + cursor.restore + cursor.move(this.cursorOffset, 0));
  683. }
  684. }
  685. text$1 = TextPrompt;
  686. return text$1;
  687. }
  688. var select$1;
  689. var hasRequiredSelect$1;
  690. function requireSelect$1 () {
  691. if (hasRequiredSelect$1) return select$1;
  692. hasRequiredSelect$1 = 1;
  693. const color = requireKleur();
  694. const Prompt = requirePrompt$1();
  695. const _require = requireUtil$1(),
  696. style = _require.style,
  697. clear = _require.clear,
  698. figures = _require.figures,
  699. wrap = _require.wrap,
  700. entriesToDisplay = _require.entriesToDisplay;
  701. const _require2 = requireSrc(),
  702. cursor = _require2.cursor;
  703. /**
  704. * SelectPrompt Base Element
  705. * @param {Object} opts Options
  706. * @param {String} opts.message Message
  707. * @param {Array} opts.choices Array of choice objects
  708. * @param {String} [opts.hint] Hint to display
  709. * @param {Number} [opts.initial] Index of default value
  710. * @param {Stream} [opts.stdin] The Readable stream to listen to
  711. * @param {Stream} [opts.stdout] The Writable stream to write readline data to
  712. * @param {Number} [opts.optionsPerPage=10] Max options to display at once
  713. */
  714. class SelectPrompt extends Prompt {
  715. constructor(opts = {}) {
  716. super(opts);
  717. this.msg = opts.message;
  718. this.hint = opts.hint || '- Use arrow-keys. Return to submit.';
  719. this.warn = opts.warn || '- This option is disabled';
  720. this.cursor = opts.initial || 0;
  721. this.choices = opts.choices.map((ch, idx) => {
  722. if (typeof ch === 'string') ch = {
  723. title: ch,
  724. value: idx
  725. };
  726. return {
  727. title: ch && (ch.title || ch.value || ch),
  728. value: ch && (ch.value === undefined ? idx : ch.value),
  729. description: ch && ch.description,
  730. selected: ch && ch.selected,
  731. disabled: ch && ch.disabled
  732. };
  733. });
  734. this.optionsPerPage = opts.optionsPerPage || 10;
  735. this.value = (this.choices[this.cursor] || {}).value;
  736. this.clear = clear('', this.out.columns);
  737. this.render();
  738. }
  739. moveCursor(n) {
  740. this.cursor = n;
  741. this.value = this.choices[n].value;
  742. this.fire();
  743. }
  744. reset() {
  745. this.moveCursor(0);
  746. this.fire();
  747. this.render();
  748. }
  749. exit() {
  750. this.abort();
  751. }
  752. abort() {
  753. this.done = this.aborted = true;
  754. this.fire();
  755. this.render();
  756. this.out.write('\n');
  757. this.close();
  758. }
  759. submit() {
  760. if (!this.selection.disabled) {
  761. this.done = true;
  762. this.aborted = false;
  763. this.fire();
  764. this.render();
  765. this.out.write('\n');
  766. this.close();
  767. } else this.bell();
  768. }
  769. first() {
  770. this.moveCursor(0);
  771. this.render();
  772. }
  773. last() {
  774. this.moveCursor(this.choices.length - 1);
  775. this.render();
  776. }
  777. up() {
  778. if (this.cursor === 0) {
  779. this.moveCursor(this.choices.length - 1);
  780. } else {
  781. this.moveCursor(this.cursor - 1);
  782. }
  783. this.render();
  784. }
  785. down() {
  786. if (this.cursor === this.choices.length - 1) {
  787. this.moveCursor(0);
  788. } else {
  789. this.moveCursor(this.cursor + 1);
  790. }
  791. this.render();
  792. }
  793. next() {
  794. this.moveCursor((this.cursor + 1) % this.choices.length);
  795. this.render();
  796. }
  797. _(c, key) {
  798. if (c === ' ') return this.submit();
  799. }
  800. get selection() {
  801. return this.choices[this.cursor];
  802. }
  803. render() {
  804. if (this.closed) return;
  805. if (this.firstRender) this.out.write(cursor.hide);else this.out.write(clear(this.outputText, this.out.columns));
  806. super.render();
  807. let _entriesToDisplay = entriesToDisplay(this.cursor, this.choices.length, this.optionsPerPage),
  808. startIndex = _entriesToDisplay.startIndex,
  809. endIndex = _entriesToDisplay.endIndex; // Print prompt
  810. this.outputText = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(false), this.done ? this.selection.title : this.selection.disabled ? color.yellow(this.warn) : color.gray(this.hint)].join(' '); // Print choices
  811. if (!this.done) {
  812. this.outputText += '\n';
  813. for (let i = startIndex; i < endIndex; i++) {
  814. let title,
  815. prefix,
  816. desc = '',
  817. v = this.choices[i]; // Determine whether to display "more choices" indicators
  818. if (i === startIndex && startIndex > 0) {
  819. prefix = figures.arrowUp;
  820. } else if (i === endIndex - 1 && endIndex < this.choices.length) {
  821. prefix = figures.arrowDown;
  822. } else {
  823. prefix = ' ';
  824. }
  825. if (v.disabled) {
  826. title = this.cursor === i ? color.gray().underline(v.title) : color.strikethrough().gray(v.title);
  827. prefix = (this.cursor === i ? color.bold().gray(figures.pointer) + ' ' : ' ') + prefix;
  828. } else {
  829. title = this.cursor === i ? color.cyan().underline(v.title) : v.title;
  830. prefix = (this.cursor === i ? color.cyan(figures.pointer) + ' ' : ' ') + prefix;
  831. if (v.description && this.cursor === i) {
  832. desc = ` - ${v.description}`;
  833. if (prefix.length + title.length + desc.length >= this.out.columns || v.description.split(/\r?\n/).length > 1) {
  834. desc = '\n' + wrap(v.description, {
  835. margin: 3,
  836. width: this.out.columns
  837. });
  838. }
  839. }
  840. }
  841. this.outputText += `${prefix} ${title}${color.gray(desc)}\n`;
  842. }
  843. }
  844. this.out.write(this.outputText);
  845. }
  846. }
  847. select$1 = SelectPrompt;
  848. return select$1;
  849. }
  850. var toggle$1;
  851. var hasRequiredToggle$1;
  852. function requireToggle$1 () {
  853. if (hasRequiredToggle$1) return toggle$1;
  854. hasRequiredToggle$1 = 1;
  855. const color = requireKleur();
  856. const Prompt = requirePrompt$1();
  857. const _require = requireUtil$1(),
  858. style = _require.style,
  859. clear = _require.clear;
  860. const _require2 = requireSrc(),
  861. cursor = _require2.cursor,
  862. erase = _require2.erase;
  863. /**
  864. * TogglePrompt Base Element
  865. * @param {Object} opts Options
  866. * @param {String} opts.message Message
  867. * @param {Boolean} [opts.initial=false] Default value
  868. * @param {String} [opts.active='no'] Active label
  869. * @param {String} [opts.inactive='off'] Inactive label
  870. * @param {Stream} [opts.stdin] The Readable stream to listen to
  871. * @param {Stream} [opts.stdout] The Writable stream to write readline data to
  872. */
  873. class TogglePrompt extends Prompt {
  874. constructor(opts = {}) {
  875. super(opts);
  876. this.msg = opts.message;
  877. this.value = !!opts.initial;
  878. this.active = opts.active || 'on';
  879. this.inactive = opts.inactive || 'off';
  880. this.initialValue = this.value;
  881. this.render();
  882. }
  883. reset() {
  884. this.value = this.initialValue;
  885. this.fire();
  886. this.render();
  887. }
  888. exit() {
  889. this.abort();
  890. }
  891. abort() {
  892. this.done = this.aborted = true;
  893. this.fire();
  894. this.render();
  895. this.out.write('\n');
  896. this.close();
  897. }
  898. submit() {
  899. this.done = true;
  900. this.aborted = false;
  901. this.fire();
  902. this.render();
  903. this.out.write('\n');
  904. this.close();
  905. }
  906. deactivate() {
  907. if (this.value === false) return this.bell();
  908. this.value = false;
  909. this.render();
  910. }
  911. activate() {
  912. if (this.value === true) return this.bell();
  913. this.value = true;
  914. this.render();
  915. }
  916. delete() {
  917. this.deactivate();
  918. }
  919. left() {
  920. this.deactivate();
  921. }
  922. right() {
  923. this.activate();
  924. }
  925. down() {
  926. this.deactivate();
  927. }
  928. up() {
  929. this.activate();
  930. }
  931. next() {
  932. this.value = !this.value;
  933. this.fire();
  934. this.render();
  935. }
  936. _(c, key) {
  937. if (c === ' ') {
  938. this.value = !this.value;
  939. } else if (c === '1') {
  940. this.value = true;
  941. } else if (c === '0') {
  942. this.value = false;
  943. } else return this.bell();
  944. this.render();
  945. }
  946. render() {
  947. if (this.closed) return;
  948. if (this.firstRender) this.out.write(cursor.hide);else this.out.write(clear(this.outputText, this.out.columns));
  949. super.render();
  950. this.outputText = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(this.done), this.value ? this.inactive : color.cyan().underline(this.inactive), color.gray('/'), this.value ? color.cyan().underline(this.active) : this.active].join(' ');
  951. this.out.write(erase.line + cursor.to(0) + this.outputText);
  952. }
  953. }
  954. toggle$1 = TogglePrompt;
  955. return toggle$1;
  956. }
  957. var datepart$1;
  958. var hasRequiredDatepart$1;
  959. function requireDatepart$1 () {
  960. if (hasRequiredDatepart$1) return datepart$1;
  961. hasRequiredDatepart$1 = 1;
  962. class DatePart {
  963. constructor({
  964. token,
  965. date,
  966. parts,
  967. locales
  968. }) {
  969. this.token = token;
  970. this.date = date || new Date();
  971. this.parts = parts || [this];
  972. this.locales = locales || {};
  973. }
  974. up() {}
  975. down() {}
  976. next() {
  977. const currentIdx = this.parts.indexOf(this);
  978. return this.parts.find((part, idx) => idx > currentIdx && part instanceof DatePart);
  979. }
  980. setTo(val) {}
  981. prev() {
  982. let parts = [].concat(this.parts).reverse();
  983. const currentIdx = parts.indexOf(this);
  984. return parts.find((part, idx) => idx > currentIdx && part instanceof DatePart);
  985. }
  986. toString() {
  987. return String(this.date);
  988. }
  989. }
  990. datepart$1 = DatePart;
  991. return datepart$1;
  992. }
  993. var meridiem$1;
  994. var hasRequiredMeridiem$1;
  995. function requireMeridiem$1 () {
  996. if (hasRequiredMeridiem$1) return meridiem$1;
  997. hasRequiredMeridiem$1 = 1;
  998. const DatePart = requireDatepart$1();
  999. class Meridiem extends DatePart {
  1000. constructor(opts = {}) {
  1001. super(opts);
  1002. }
  1003. up() {
  1004. this.date.setHours((this.date.getHours() + 12) % 24);
  1005. }
  1006. down() {
  1007. this.up();
  1008. }
  1009. toString() {
  1010. let meridiem = this.date.getHours() > 12 ? 'pm' : 'am';
  1011. return /\A/.test(this.token) ? meridiem.toUpperCase() : meridiem;
  1012. }
  1013. }
  1014. meridiem$1 = Meridiem;
  1015. return meridiem$1;
  1016. }
  1017. var day$1;
  1018. var hasRequiredDay$1;
  1019. function requireDay$1 () {
  1020. if (hasRequiredDay$1) return day$1;
  1021. hasRequiredDay$1 = 1;
  1022. const DatePart = requireDatepart$1();
  1023. const pos = n => {
  1024. n = n % 10;
  1025. return n === 1 ? 'st' : n === 2 ? 'nd' : n === 3 ? 'rd' : 'th';
  1026. };
  1027. class Day extends DatePart {
  1028. constructor(opts = {}) {
  1029. super(opts);
  1030. }
  1031. up() {
  1032. this.date.setDate(this.date.getDate() + 1);
  1033. }
  1034. down() {
  1035. this.date.setDate(this.date.getDate() - 1);
  1036. }
  1037. setTo(val) {
  1038. this.date.setDate(parseInt(val.substr(-2)));
  1039. }
  1040. toString() {
  1041. let date = this.date.getDate();
  1042. let day = this.date.getDay();
  1043. return this.token === 'DD' ? String(date).padStart(2, '0') : this.token === 'Do' ? date + pos(date) : this.token === 'd' ? day + 1 : this.token === 'ddd' ? this.locales.weekdaysShort[day] : this.token === 'dddd' ? this.locales.weekdays[day] : date;
  1044. }
  1045. }
  1046. day$1 = Day;
  1047. return day$1;
  1048. }
  1049. var hours$1;
  1050. var hasRequiredHours$1;
  1051. function requireHours$1 () {
  1052. if (hasRequiredHours$1) return hours$1;
  1053. hasRequiredHours$1 = 1;
  1054. const DatePart = requireDatepart$1();
  1055. class Hours extends DatePart {
  1056. constructor(opts = {}) {
  1057. super(opts);
  1058. }
  1059. up() {
  1060. this.date.setHours(this.date.getHours() + 1);
  1061. }
  1062. down() {
  1063. this.date.setHours(this.date.getHours() - 1);
  1064. }
  1065. setTo(val) {
  1066. this.date.setHours(parseInt(val.substr(-2)));
  1067. }
  1068. toString() {
  1069. let hours = this.date.getHours();
  1070. if (/h/.test(this.token)) hours = hours % 12 || 12;
  1071. return this.token.length > 1 ? String(hours).padStart(2, '0') : hours;
  1072. }
  1073. }
  1074. hours$1 = Hours;
  1075. return hours$1;
  1076. }
  1077. var milliseconds$1;
  1078. var hasRequiredMilliseconds$1;
  1079. function requireMilliseconds$1 () {
  1080. if (hasRequiredMilliseconds$1) return milliseconds$1;
  1081. hasRequiredMilliseconds$1 = 1;
  1082. const DatePart = requireDatepart$1();
  1083. class Milliseconds extends DatePart {
  1084. constructor(opts = {}) {
  1085. super(opts);
  1086. }
  1087. up() {
  1088. this.date.setMilliseconds(this.date.getMilliseconds() + 1);
  1089. }
  1090. down() {
  1091. this.date.setMilliseconds(this.date.getMilliseconds() - 1);
  1092. }
  1093. setTo(val) {
  1094. this.date.setMilliseconds(parseInt(val.substr(-this.token.length)));
  1095. }
  1096. toString() {
  1097. return String(this.date.getMilliseconds()).padStart(4, '0').substr(0, this.token.length);
  1098. }
  1099. }
  1100. milliseconds$1 = Milliseconds;
  1101. return milliseconds$1;
  1102. }
  1103. var minutes$1;
  1104. var hasRequiredMinutes$1;
  1105. function requireMinutes$1 () {
  1106. if (hasRequiredMinutes$1) return minutes$1;
  1107. hasRequiredMinutes$1 = 1;
  1108. const DatePart = requireDatepart$1();
  1109. class Minutes extends DatePart {
  1110. constructor(opts = {}) {
  1111. super(opts);
  1112. }
  1113. up() {
  1114. this.date.setMinutes(this.date.getMinutes() + 1);
  1115. }
  1116. down() {
  1117. this.date.setMinutes(this.date.getMinutes() - 1);
  1118. }
  1119. setTo(val) {
  1120. this.date.setMinutes(parseInt(val.substr(-2)));
  1121. }
  1122. toString() {
  1123. let m = this.date.getMinutes();
  1124. return this.token.length > 1 ? String(m).padStart(2, '0') : m;
  1125. }
  1126. }
  1127. minutes$1 = Minutes;
  1128. return minutes$1;
  1129. }
  1130. var month$1;
  1131. var hasRequiredMonth$1;
  1132. function requireMonth$1 () {
  1133. if (hasRequiredMonth$1) return month$1;
  1134. hasRequiredMonth$1 = 1;
  1135. const DatePart = requireDatepart$1();
  1136. class Month extends DatePart {
  1137. constructor(opts = {}) {
  1138. super(opts);
  1139. }
  1140. up() {
  1141. this.date.setMonth(this.date.getMonth() + 1);
  1142. }
  1143. down() {
  1144. this.date.setMonth(this.date.getMonth() - 1);
  1145. }
  1146. setTo(val) {
  1147. val = parseInt(val.substr(-2)) - 1;
  1148. this.date.setMonth(val < 0 ? 0 : val);
  1149. }
  1150. toString() {
  1151. let month = this.date.getMonth();
  1152. let tl = this.token.length;
  1153. return tl === 2 ? String(month + 1).padStart(2, '0') : tl === 3 ? this.locales.monthsShort[month] : tl === 4 ? this.locales.months[month] : String(month + 1);
  1154. }
  1155. }
  1156. month$1 = Month;
  1157. return month$1;
  1158. }
  1159. var seconds$1;
  1160. var hasRequiredSeconds$1;
  1161. function requireSeconds$1 () {
  1162. if (hasRequiredSeconds$1) return seconds$1;
  1163. hasRequiredSeconds$1 = 1;
  1164. const DatePart = requireDatepart$1();
  1165. class Seconds extends DatePart {
  1166. constructor(opts = {}) {
  1167. super(opts);
  1168. }
  1169. up() {
  1170. this.date.setSeconds(this.date.getSeconds() + 1);
  1171. }
  1172. down() {
  1173. this.date.setSeconds(this.date.getSeconds() - 1);
  1174. }
  1175. setTo(val) {
  1176. this.date.setSeconds(parseInt(val.substr(-2)));
  1177. }
  1178. toString() {
  1179. let s = this.date.getSeconds();
  1180. return this.token.length > 1 ? String(s).padStart(2, '0') : s;
  1181. }
  1182. }
  1183. seconds$1 = Seconds;
  1184. return seconds$1;
  1185. }
  1186. var year$1;
  1187. var hasRequiredYear$1;
  1188. function requireYear$1 () {
  1189. if (hasRequiredYear$1) return year$1;
  1190. hasRequiredYear$1 = 1;
  1191. const DatePart = requireDatepart$1();
  1192. class Year extends DatePart {
  1193. constructor(opts = {}) {
  1194. super(opts);
  1195. }
  1196. up() {
  1197. this.date.setFullYear(this.date.getFullYear() + 1);
  1198. }
  1199. down() {
  1200. this.date.setFullYear(this.date.getFullYear() - 1);
  1201. }
  1202. setTo(val) {
  1203. this.date.setFullYear(val.substr(-4));
  1204. }
  1205. toString() {
  1206. let year = String(this.date.getFullYear()).padStart(4, '0');
  1207. return this.token.length === 2 ? year.substr(-2) : year;
  1208. }
  1209. }
  1210. year$1 = Year;
  1211. return year$1;
  1212. }
  1213. var dateparts$1;
  1214. var hasRequiredDateparts$1;
  1215. function requireDateparts$1 () {
  1216. if (hasRequiredDateparts$1) return dateparts$1;
  1217. hasRequiredDateparts$1 = 1;
  1218. dateparts$1 = {
  1219. DatePart: requireDatepart$1(),
  1220. Meridiem: requireMeridiem$1(),
  1221. Day: requireDay$1(),
  1222. Hours: requireHours$1(),
  1223. Milliseconds: requireMilliseconds$1(),
  1224. Minutes: requireMinutes$1(),
  1225. Month: requireMonth$1(),
  1226. Seconds: requireSeconds$1(),
  1227. Year: requireYear$1()
  1228. };
  1229. return dateparts$1;
  1230. }
  1231. var date$1;
  1232. var hasRequiredDate$1;
  1233. function requireDate$1 () {
  1234. if (hasRequiredDate$1) return date$1;
  1235. hasRequiredDate$1 = 1;
  1236. function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
  1237. function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
  1238. const color = requireKleur();
  1239. const Prompt = requirePrompt$1();
  1240. const _require = requireUtil$1(),
  1241. style = _require.style,
  1242. clear = _require.clear,
  1243. figures = _require.figures;
  1244. const _require2 = requireSrc(),
  1245. erase = _require2.erase,
  1246. cursor = _require2.cursor;
  1247. const _require3 = requireDateparts$1(),
  1248. DatePart = _require3.DatePart,
  1249. Meridiem = _require3.Meridiem,
  1250. Day = _require3.Day,
  1251. Hours = _require3.Hours,
  1252. Milliseconds = _require3.Milliseconds,
  1253. Minutes = _require3.Minutes,
  1254. Month = _require3.Month,
  1255. Seconds = _require3.Seconds,
  1256. Year = _require3.Year;
  1257. const regex = /\\(.)|"((?:\\["\\]|[^"])+)"|(D[Do]?|d{3,4}|d)|(M{1,4})|(YY(?:YY)?)|([aA])|([Hh]{1,2})|(m{1,2})|(s{1,2})|(S{1,4})|./g;
  1258. const regexGroups = {
  1259. 1: ({
  1260. token
  1261. }) => token.replace(/\\(.)/g, '$1'),
  1262. 2: opts => new Day(opts),
  1263. // Day // TODO
  1264. 3: opts => new Month(opts),
  1265. // Month
  1266. 4: opts => new Year(opts),
  1267. // Year
  1268. 5: opts => new Meridiem(opts),
  1269. // AM/PM // TODO (special)
  1270. 6: opts => new Hours(opts),
  1271. // Hours
  1272. 7: opts => new Minutes(opts),
  1273. // Minutes
  1274. 8: opts => new Seconds(opts),
  1275. // Seconds
  1276. 9: opts => new Milliseconds(opts) // Fractional seconds
  1277. };
  1278. const dfltLocales = {
  1279. months: 'January,February,March,April,May,June,July,August,September,October,November,December'.split(','),
  1280. monthsShort: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','),
  1281. weekdays: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','),
  1282. weekdaysShort: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(',')
  1283. };
  1284. /**
  1285. * DatePrompt Base Element
  1286. * @param {Object} opts Options
  1287. * @param {String} opts.message Message
  1288. * @param {Number} [opts.initial] Index of default value
  1289. * @param {String} [opts.mask] The format mask
  1290. * @param {object} [opts.locales] The date locales
  1291. * @param {String} [opts.error] The error message shown on invalid value
  1292. * @param {Function} [opts.validate] Function to validate the submitted value
  1293. * @param {Stream} [opts.stdin] The Readable stream to listen to
  1294. * @param {Stream} [opts.stdout] The Writable stream to write readline data to
  1295. */
  1296. class DatePrompt extends Prompt {
  1297. constructor(opts = {}) {
  1298. super(opts);
  1299. this.msg = opts.message;
  1300. this.cursor = 0;
  1301. this.typed = '';
  1302. this.locales = Object.assign(dfltLocales, opts.locales);
  1303. this._date = opts.initial || new Date();
  1304. this.errorMsg = opts.error || 'Please Enter A Valid Value';
  1305. this.validator = opts.validate || (() => true);
  1306. this.mask = opts.mask || 'YYYY-MM-DD HH:mm:ss';
  1307. this.clear = clear('', this.out.columns);
  1308. this.render();
  1309. }
  1310. get value() {
  1311. return this.date;
  1312. }
  1313. get date() {
  1314. return this._date;
  1315. }
  1316. set date(date) {
  1317. if (date) this._date.setTime(date.getTime());
  1318. }
  1319. set mask(mask) {
  1320. let result;
  1321. this.parts = [];
  1322. while (result = regex.exec(mask)) {
  1323. let match = result.shift();
  1324. let idx = result.findIndex(gr => gr != null);
  1325. this.parts.push(idx in regexGroups ? regexGroups[idx]({
  1326. token: result[idx] || match,
  1327. date: this.date,
  1328. parts: this.parts,
  1329. locales: this.locales
  1330. }) : result[idx] || match);
  1331. }
  1332. let parts = this.parts.reduce((arr, i) => {
  1333. if (typeof i === 'string' && typeof arr[arr.length - 1] === 'string') arr[arr.length - 1] += i;else arr.push(i);
  1334. return arr;
  1335. }, []);
  1336. this.parts.splice(0);
  1337. this.parts.push(...parts);
  1338. this.reset();
  1339. }
  1340. moveCursor(n) {
  1341. this.typed = '';
  1342. this.cursor = n;
  1343. this.fire();
  1344. }
  1345. reset() {
  1346. this.moveCursor(this.parts.findIndex(p => p instanceof DatePart));
  1347. this.fire();
  1348. this.render();
  1349. }
  1350. exit() {
  1351. this.abort();
  1352. }
  1353. abort() {
  1354. this.done = this.aborted = true;
  1355. this.error = false;
  1356. this.fire();
  1357. this.render();
  1358. this.out.write('\n');
  1359. this.close();
  1360. }
  1361. validate() {
  1362. var _this = this;
  1363. return _asyncToGenerator(function* () {
  1364. let valid = yield _this.validator(_this.value);
  1365. if (typeof valid === 'string') {
  1366. _this.errorMsg = valid;
  1367. valid = false;
  1368. }
  1369. _this.error = !valid;
  1370. })();
  1371. }
  1372. submit() {
  1373. var _this2 = this;
  1374. return _asyncToGenerator(function* () {
  1375. yield _this2.validate();
  1376. if (_this2.error) {
  1377. _this2.color = 'red';
  1378. _this2.fire();
  1379. _this2.render();
  1380. return;
  1381. }
  1382. _this2.done = true;
  1383. _this2.aborted = false;
  1384. _this2.fire();
  1385. _this2.render();
  1386. _this2.out.write('\n');
  1387. _this2.close();
  1388. })();
  1389. }
  1390. up() {
  1391. this.typed = '';
  1392. this.parts[this.cursor].up();
  1393. this.render();
  1394. }
  1395. down() {
  1396. this.typed = '';
  1397. this.parts[this.cursor].down();
  1398. this.render();
  1399. }
  1400. left() {
  1401. let prev = this.parts[this.cursor].prev();
  1402. if (prev == null) return this.bell();
  1403. this.moveCursor(this.parts.indexOf(prev));
  1404. this.render();
  1405. }
  1406. right() {
  1407. let next = this.parts[this.cursor].next();
  1408. if (next == null) return this.bell();
  1409. this.moveCursor(this.parts.indexOf(next));
  1410. this.render();
  1411. }
  1412. next() {
  1413. let next = this.parts[this.cursor].next();
  1414. this.moveCursor(next ? this.parts.indexOf(next) : this.parts.findIndex(part => part instanceof DatePart));
  1415. this.render();
  1416. }
  1417. _(c) {
  1418. if (/\d/.test(c)) {
  1419. this.typed += c;
  1420. this.parts[this.cursor].setTo(this.typed);
  1421. this.render();
  1422. }
  1423. }
  1424. render() {
  1425. if (this.closed) return;
  1426. if (this.firstRender) this.out.write(cursor.hide);else this.out.write(clear(this.outputText, this.out.columns));
  1427. super.render(); // Print prompt
  1428. this.outputText = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(false), this.parts.reduce((arr, p, idx) => arr.concat(idx === this.cursor && !this.done ? color.cyan().underline(p.toString()) : p), []).join('')].join(' '); // Print error
  1429. if (this.error) {
  1430. this.outputText += this.errorMsg.split('\n').reduce((a, l, i) => a + `\n${i ? ` ` : figures.pointerSmall} ${color.red().italic(l)}`, ``);
  1431. }
  1432. this.out.write(erase.line + cursor.to(0) + this.outputText);
  1433. }
  1434. }
  1435. date$1 = DatePrompt;
  1436. return date$1;
  1437. }
  1438. var number$1;
  1439. var hasRequiredNumber$1;
  1440. function requireNumber$1 () {
  1441. if (hasRequiredNumber$1) return number$1;
  1442. hasRequiredNumber$1 = 1;
  1443. function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
  1444. function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
  1445. const color = requireKleur();
  1446. const Prompt = requirePrompt$1();
  1447. const _require = requireSrc(),
  1448. cursor = _require.cursor,
  1449. erase = _require.erase;
  1450. const _require2 = requireUtil$1(),
  1451. style = _require2.style,
  1452. figures = _require2.figures,
  1453. clear = _require2.clear,
  1454. lines = _require2.lines;
  1455. const isNumber = /[0-9]/;
  1456. const isDef = any => any !== undefined;
  1457. const round = (number, precision) => {
  1458. let factor = Math.pow(10, precision);
  1459. return Math.round(number * factor) / factor;
  1460. };
  1461. /**
  1462. * NumberPrompt Base Element
  1463. * @param {Object} opts Options
  1464. * @param {String} opts.message Message
  1465. * @param {String} [opts.style='default'] Render style
  1466. * @param {Number} [opts.initial] Default value
  1467. * @param {Number} [opts.max=+Infinity] Max value
  1468. * @param {Number} [opts.min=-Infinity] Min value
  1469. * @param {Boolean} [opts.float=false] Parse input as floats
  1470. * @param {Number} [opts.round=2] Round floats to x decimals
  1471. * @param {Number} [opts.increment=1] Number to increment by when using arrow-keys
  1472. * @param {Function} [opts.validate] Validate function
  1473. * @param {Stream} [opts.stdin] The Readable stream to listen to
  1474. * @param {Stream} [opts.stdout] The Writable stream to write readline data to
  1475. * @param {String} [opts.error] The invalid error label
  1476. */
  1477. class NumberPrompt extends Prompt {
  1478. constructor(opts = {}) {
  1479. super(opts);
  1480. this.transform = style.render(opts.style);
  1481. this.msg = opts.message;
  1482. this.initial = isDef(opts.initial) ? opts.initial : '';
  1483. this.float = !!opts.float;
  1484. this.round = opts.round || 2;
  1485. this.inc = opts.increment || 1;
  1486. this.min = isDef(opts.min) ? opts.min : -Infinity;
  1487. this.max = isDef(opts.max) ? opts.max : Infinity;
  1488. this.errorMsg = opts.error || `Please Enter A Valid Value`;
  1489. this.validator = opts.validate || (() => true);
  1490. this.color = `cyan`;
  1491. this.value = ``;
  1492. this.typed = ``;
  1493. this.lastHit = 0;
  1494. this.render();
  1495. }
  1496. set value(v) {
  1497. if (!v && v !== 0) {
  1498. this.placeholder = true;
  1499. this.rendered = color.gray(this.transform.render(`${this.initial}`));
  1500. this._value = ``;
  1501. } else {
  1502. this.placeholder = false;
  1503. this.rendered = this.transform.render(`${round(v, this.round)}`);
  1504. this._value = round(v, this.round);
  1505. }
  1506. this.fire();
  1507. }
  1508. get value() {
  1509. return this._value;
  1510. }
  1511. parse(x) {
  1512. return this.float ? parseFloat(x) : parseInt(x);
  1513. }
  1514. valid(c) {
  1515. return c === `-` || c === `.` && this.float || isNumber.test(c);
  1516. }
  1517. reset() {
  1518. this.typed = ``;
  1519. this.value = ``;
  1520. this.fire();
  1521. this.render();
  1522. }
  1523. exit() {
  1524. this.abort();
  1525. }
  1526. abort() {
  1527. let x = this.value;
  1528. this.value = x !== `` ? x : this.initial;
  1529. this.done = this.aborted = true;
  1530. this.error = false;
  1531. this.fire();
  1532. this.render();
  1533. this.out.write(`\n`);
  1534. this.close();
  1535. }
  1536. validate() {
  1537. var _this = this;
  1538. return _asyncToGenerator(function* () {
  1539. let valid = yield _this.validator(_this.value);
  1540. if (typeof valid === `string`) {
  1541. _this.errorMsg = valid;
  1542. valid = false;
  1543. }
  1544. _this.error = !valid;
  1545. })();
  1546. }
  1547. submit() {
  1548. var _this2 = this;
  1549. return _asyncToGenerator(function* () {
  1550. yield _this2.validate();
  1551. if (_this2.error) {
  1552. _this2.color = `red`;
  1553. _this2.fire();
  1554. _this2.render();
  1555. return;
  1556. }
  1557. let x = _this2.value;
  1558. _this2.value = x !== `` ? x : _this2.initial;
  1559. _this2.done = true;
  1560. _this2.aborted = false;
  1561. _this2.error = false;
  1562. _this2.fire();
  1563. _this2.render();
  1564. _this2.out.write(`\n`);
  1565. _this2.close();
  1566. })();
  1567. }
  1568. up() {
  1569. this.typed = ``;
  1570. if (this.value === '') {
  1571. this.value = this.min - this.inc;
  1572. }
  1573. if (this.value >= this.max) return this.bell();
  1574. this.value += this.inc;
  1575. this.color = `cyan`;
  1576. this.fire();
  1577. this.render();
  1578. }
  1579. down() {
  1580. this.typed = ``;
  1581. if (this.value === '') {
  1582. this.value = this.min + this.inc;
  1583. }
  1584. if (this.value <= this.min) return this.bell();
  1585. this.value -= this.inc;
  1586. this.color = `cyan`;
  1587. this.fire();
  1588. this.render();
  1589. }
  1590. delete() {
  1591. let val = this.value.toString();
  1592. if (val.length === 0) return this.bell();
  1593. this.value = this.parse(val = val.slice(0, -1)) || ``;
  1594. if (this.value !== '' && this.value < this.min) {
  1595. this.value = this.min;
  1596. }
  1597. this.color = `cyan`;
  1598. this.fire();
  1599. this.render();
  1600. }
  1601. next() {
  1602. this.value = this.initial;
  1603. this.fire();
  1604. this.render();
  1605. }
  1606. _(c, key) {
  1607. if (!this.valid(c)) return this.bell();
  1608. const now = Date.now();
  1609. if (now - this.lastHit > 1000) this.typed = ``; // 1s elapsed
  1610. this.typed += c;
  1611. this.lastHit = now;
  1612. this.color = `cyan`;
  1613. if (c === `.`) return this.fire();
  1614. this.value = Math.min(this.parse(this.typed), this.max);
  1615. if (this.value > this.max) this.value = this.max;
  1616. if (this.value < this.min) this.value = this.min;
  1617. this.fire();
  1618. this.render();
  1619. }
  1620. render() {
  1621. if (this.closed) return;
  1622. if (!this.firstRender) {
  1623. if (this.outputError) this.out.write(cursor.down(lines(this.outputError, this.out.columns) - 1) + clear(this.outputError, this.out.columns));
  1624. this.out.write(clear(this.outputText, this.out.columns));
  1625. }
  1626. super.render();
  1627. this.outputError = ''; // Print prompt
  1628. this.outputText = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(this.done), !this.done || !this.done && !this.placeholder ? color[this.color]().underline(this.rendered) : this.rendered].join(` `); // Print error
  1629. if (this.error) {
  1630. this.outputError += this.errorMsg.split(`\n`).reduce((a, l, i) => a + `\n${i ? ` ` : figures.pointerSmall} ${color.red().italic(l)}`, ``);
  1631. }
  1632. this.out.write(erase.line + cursor.to(0) + this.outputText + cursor.save + this.outputError + cursor.restore);
  1633. }
  1634. }
  1635. number$1 = NumberPrompt;
  1636. return number$1;
  1637. }
  1638. var multiselect$1;
  1639. var hasRequiredMultiselect$1;
  1640. function requireMultiselect$1 () {
  1641. if (hasRequiredMultiselect$1) return multiselect$1;
  1642. hasRequiredMultiselect$1 = 1;
  1643. const color = requireKleur();
  1644. const _require = requireSrc(),
  1645. cursor = _require.cursor;
  1646. const Prompt = requirePrompt$1();
  1647. const _require2 = requireUtil$1(),
  1648. clear = _require2.clear,
  1649. figures = _require2.figures,
  1650. style = _require2.style,
  1651. wrap = _require2.wrap,
  1652. entriesToDisplay = _require2.entriesToDisplay;
  1653. /**
  1654. * MultiselectPrompt Base Element
  1655. * @param {Object} opts Options
  1656. * @param {String} opts.message Message
  1657. * @param {Array} opts.choices Array of choice objects
  1658. * @param {String} [opts.hint] Hint to display
  1659. * @param {String} [opts.warn] Hint shown for disabled choices
  1660. * @param {Number} [opts.max] Max choices
  1661. * @param {Number} [opts.cursor=0] Cursor start position
  1662. * @param {Number} [opts.optionsPerPage=10] Max options to display at once
  1663. * @param {Stream} [opts.stdin] The Readable stream to listen to
  1664. * @param {Stream} [opts.stdout] The Writable stream to write readline data to
  1665. */
  1666. class MultiselectPrompt extends Prompt {
  1667. constructor(opts = {}) {
  1668. super(opts);
  1669. this.msg = opts.message;
  1670. this.cursor = opts.cursor || 0;
  1671. this.scrollIndex = opts.cursor || 0;
  1672. this.hint = opts.hint || '';
  1673. this.warn = opts.warn || '- This option is disabled -';
  1674. this.minSelected = opts.min;
  1675. this.showMinError = false;
  1676. this.maxChoices = opts.max;
  1677. this.instructions = opts.instructions;
  1678. this.optionsPerPage = opts.optionsPerPage || 10;
  1679. this.value = opts.choices.map((ch, idx) => {
  1680. if (typeof ch === 'string') ch = {
  1681. title: ch,
  1682. value: idx
  1683. };
  1684. return {
  1685. title: ch && (ch.title || ch.value || ch),
  1686. description: ch && ch.description,
  1687. value: ch && (ch.value === undefined ? idx : ch.value),
  1688. selected: ch && ch.selected,
  1689. disabled: ch && ch.disabled
  1690. };
  1691. });
  1692. this.clear = clear('', this.out.columns);
  1693. if (!opts.overrideRender) {
  1694. this.render();
  1695. }
  1696. }
  1697. reset() {
  1698. this.value.map(v => !v.selected);
  1699. this.cursor = 0;
  1700. this.fire();
  1701. this.render();
  1702. }
  1703. selected() {
  1704. return this.value.filter(v => v.selected);
  1705. }
  1706. exit() {
  1707. this.abort();
  1708. }
  1709. abort() {
  1710. this.done = this.aborted = true;
  1711. this.fire();
  1712. this.render();
  1713. this.out.write('\n');
  1714. this.close();
  1715. }
  1716. submit() {
  1717. const selected = this.value.filter(e => e.selected);
  1718. if (this.minSelected && selected.length < this.minSelected) {
  1719. this.showMinError = true;
  1720. this.render();
  1721. } else {
  1722. this.done = true;
  1723. this.aborted = false;
  1724. this.fire();
  1725. this.render();
  1726. this.out.write('\n');
  1727. this.close();
  1728. }
  1729. }
  1730. first() {
  1731. this.cursor = 0;
  1732. this.render();
  1733. }
  1734. last() {
  1735. this.cursor = this.value.length - 1;
  1736. this.render();
  1737. }
  1738. next() {
  1739. this.cursor = (this.cursor + 1) % this.value.length;
  1740. this.render();
  1741. }
  1742. up() {
  1743. if (this.cursor === 0) {
  1744. this.cursor = this.value.length - 1;
  1745. } else {
  1746. this.cursor--;
  1747. }
  1748. this.render();
  1749. }
  1750. down() {
  1751. if (this.cursor === this.value.length - 1) {
  1752. this.cursor = 0;
  1753. } else {
  1754. this.cursor++;
  1755. }
  1756. this.render();
  1757. }
  1758. left() {
  1759. this.value[this.cursor].selected = false;
  1760. this.render();
  1761. }
  1762. right() {
  1763. if (this.value.filter(e => e.selected).length >= this.maxChoices) return this.bell();
  1764. this.value[this.cursor].selected = true;
  1765. this.render();
  1766. }
  1767. handleSpaceToggle() {
  1768. const v = this.value[this.cursor];
  1769. if (v.selected) {
  1770. v.selected = false;
  1771. this.render();
  1772. } else if (v.disabled || this.value.filter(e => e.selected).length >= this.maxChoices) {
  1773. return this.bell();
  1774. } else {
  1775. v.selected = true;
  1776. this.render();
  1777. }
  1778. }
  1779. toggleAll() {
  1780. if (this.maxChoices !== undefined || this.value[this.cursor].disabled) {
  1781. return this.bell();
  1782. }
  1783. const newSelected = !this.value[this.cursor].selected;
  1784. this.value.filter(v => !v.disabled).forEach(v => v.selected = newSelected);
  1785. this.render();
  1786. }
  1787. _(c, key) {
  1788. if (c === ' ') {
  1789. this.handleSpaceToggle();
  1790. } else if (c === 'a') {
  1791. this.toggleAll();
  1792. } else {
  1793. return this.bell();
  1794. }
  1795. }
  1796. renderInstructions() {
  1797. if (this.instructions === undefined || this.instructions) {
  1798. if (typeof this.instructions === 'string') {
  1799. return this.instructions;
  1800. }
  1801. return '\nInstructions:\n' + ` ${figures.arrowUp}/${figures.arrowDown}: Highlight option\n` + ` ${figures.arrowLeft}/${figures.arrowRight}/[space]: Toggle selection\n` + (this.maxChoices === undefined ? ` a: Toggle all\n` : '') + ` enter/return: Complete answer`;
  1802. }
  1803. return '';
  1804. }
  1805. renderOption(cursor, v, i, arrowIndicator) {
  1806. const prefix = (v.selected ? color.green(figures.radioOn) : figures.radioOff) + ' ' + arrowIndicator + ' ';
  1807. let title, desc;
  1808. if (v.disabled) {
  1809. title = cursor === i ? color.gray().underline(v.title) : color.strikethrough().gray(v.title);
  1810. } else {
  1811. title = cursor === i ? color.cyan().underline(v.title) : v.title;
  1812. if (cursor === i && v.description) {
  1813. desc = ` - ${v.description}`;
  1814. if (prefix.length + title.length + desc.length >= this.out.columns || v.description.split(/\r?\n/).length > 1) {
  1815. desc = '\n' + wrap(v.description, {
  1816. margin: prefix.length,
  1817. width: this.out.columns
  1818. });
  1819. }
  1820. }
  1821. }
  1822. return prefix + title + color.gray(desc || '');
  1823. } // shared with autocompleteMultiselect
  1824. paginateOptions(options) {
  1825. if (options.length === 0) {
  1826. return color.red('No matches for this query.');
  1827. }
  1828. let _entriesToDisplay = entriesToDisplay(this.cursor, options.length, this.optionsPerPage),
  1829. startIndex = _entriesToDisplay.startIndex,
  1830. endIndex = _entriesToDisplay.endIndex;
  1831. let prefix,
  1832. styledOptions = [];
  1833. for (let i = startIndex; i < endIndex; i++) {
  1834. if (i === startIndex && startIndex > 0) {
  1835. prefix = figures.arrowUp;
  1836. } else if (i === endIndex - 1 && endIndex < options.length) {
  1837. prefix = figures.arrowDown;
  1838. } else {
  1839. prefix = ' ';
  1840. }
  1841. styledOptions.push(this.renderOption(this.cursor, options[i], i, prefix));
  1842. }
  1843. return '\n' + styledOptions.join('\n');
  1844. } // shared with autocomleteMultiselect
  1845. renderOptions(options) {
  1846. if (!this.done) {
  1847. return this.paginateOptions(options);
  1848. }
  1849. return '';
  1850. }
  1851. renderDoneOrInstructions() {
  1852. if (this.done) {
  1853. return this.value.filter(e => e.selected).map(v => v.title).join(', ');
  1854. }
  1855. const output = [color.gray(this.hint), this.renderInstructions()];
  1856. if (this.value[this.cursor].disabled) {
  1857. output.push(color.yellow(this.warn));
  1858. }
  1859. return output.join(' ');
  1860. }
  1861. render() {
  1862. if (this.closed) return;
  1863. if (this.firstRender) this.out.write(cursor.hide);
  1864. super.render(); // print prompt
  1865. let prompt = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(false), this.renderDoneOrInstructions()].join(' ');
  1866. if (this.showMinError) {
  1867. prompt += color.red(`You must select a minimum of ${this.minSelected} choices.`);
  1868. this.showMinError = false;
  1869. }
  1870. prompt += this.renderOptions(this.value);
  1871. this.out.write(this.clear + prompt);
  1872. this.clear = clear(prompt, this.out.columns);
  1873. }
  1874. }
  1875. multiselect$1 = MultiselectPrompt;
  1876. return multiselect$1;
  1877. }
  1878. var autocomplete$1;
  1879. var hasRequiredAutocomplete$1;
  1880. function requireAutocomplete$1 () {
  1881. if (hasRequiredAutocomplete$1) return autocomplete$1;
  1882. hasRequiredAutocomplete$1 = 1;
  1883. function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
  1884. function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
  1885. const color = requireKleur();
  1886. const Prompt = requirePrompt$1();
  1887. const _require = requireSrc(),
  1888. erase = _require.erase,
  1889. cursor = _require.cursor;
  1890. const _require2 = requireUtil$1(),
  1891. style = _require2.style,
  1892. clear = _require2.clear,
  1893. figures = _require2.figures,
  1894. wrap = _require2.wrap,
  1895. entriesToDisplay = _require2.entriesToDisplay;
  1896. const getVal = (arr, i) => arr[i] && (arr[i].value || arr[i].title || arr[i]);
  1897. const getTitle = (arr, i) => arr[i] && (arr[i].title || arr[i].value || arr[i]);
  1898. const getIndex = (arr, valOrTitle) => {
  1899. const index = arr.findIndex(el => el.value === valOrTitle || el.title === valOrTitle);
  1900. return index > -1 ? index : undefined;
  1901. };
  1902. /**
  1903. * TextPrompt Base Element
  1904. * @param {Object} opts Options
  1905. * @param {String} opts.message Message
  1906. * @param {Array} opts.choices Array of auto-complete choices objects
  1907. * @param {Function} [opts.suggest] Filter function. Defaults to sort by title
  1908. * @param {Number} [opts.limit=10] Max number of results to show
  1909. * @param {Number} [opts.cursor=0] Cursor start position
  1910. * @param {String} [opts.style='default'] Render style
  1911. * @param {String} [opts.fallback] Fallback message - initial to default value
  1912. * @param {String} [opts.initial] Index of the default value
  1913. * @param {Boolean} [opts.clearFirst] The first ESCAPE keypress will clear the input
  1914. * @param {Stream} [opts.stdin] The Readable stream to listen to
  1915. * @param {Stream} [opts.stdout] The Writable stream to write readline data to
  1916. * @param {String} [opts.noMatches] The no matches found label
  1917. */
  1918. class AutocompletePrompt extends Prompt {
  1919. constructor(opts = {}) {
  1920. super(opts);
  1921. this.msg = opts.message;
  1922. this.suggest = opts.suggest;
  1923. this.choices = opts.choices;
  1924. this.initial = typeof opts.initial === 'number' ? opts.initial : getIndex(opts.choices, opts.initial);
  1925. this.select = this.initial || opts.cursor || 0;
  1926. this.i18n = {
  1927. noMatches: opts.noMatches || 'no matches found'
  1928. };
  1929. this.fallback = opts.fallback || this.initial;
  1930. this.clearFirst = opts.clearFirst || false;
  1931. this.suggestions = [];
  1932. this.input = '';
  1933. this.limit = opts.limit || 10;
  1934. this.cursor = 0;
  1935. this.transform = style.render(opts.style);
  1936. this.scale = this.transform.scale;
  1937. this.render = this.render.bind(this);
  1938. this.complete = this.complete.bind(this);
  1939. this.clear = clear('', this.out.columns);
  1940. this.complete(this.render);
  1941. this.render();
  1942. }
  1943. set fallback(fb) {
  1944. this._fb = Number.isSafeInteger(parseInt(fb)) ? parseInt(fb) : fb;
  1945. }
  1946. get fallback() {
  1947. let choice;
  1948. if (typeof this._fb === 'number') choice = this.choices[this._fb];else if (typeof this._fb === 'string') choice = {
  1949. title: this._fb
  1950. };
  1951. return choice || this._fb || {
  1952. title: this.i18n.noMatches
  1953. };
  1954. }
  1955. moveSelect(i) {
  1956. this.select = i;
  1957. if (this.suggestions.length > 0) this.value = getVal(this.suggestions, i);else this.value = this.fallback.value;
  1958. this.fire();
  1959. }
  1960. complete(cb) {
  1961. var _this = this;
  1962. return _asyncToGenerator(function* () {
  1963. const p = _this.completing = _this.suggest(_this.input, _this.choices);
  1964. const suggestions = yield p;
  1965. if (_this.completing !== p) return;
  1966. _this.suggestions = suggestions.map((s, i, arr) => ({
  1967. title: getTitle(arr, i),
  1968. value: getVal(arr, i),
  1969. description: s.description
  1970. }));
  1971. _this.completing = false;
  1972. const l = Math.max(suggestions.length - 1, 0);
  1973. _this.moveSelect(Math.min(l, _this.select));
  1974. cb && cb();
  1975. })();
  1976. }
  1977. reset() {
  1978. this.input = '';
  1979. this.complete(() => {
  1980. this.moveSelect(this.initial !== void 0 ? this.initial : 0);
  1981. this.render();
  1982. });
  1983. this.render();
  1984. }
  1985. exit() {
  1986. if (this.clearFirst && this.input.length > 0) {
  1987. this.reset();
  1988. } else {
  1989. this.done = this.exited = true;
  1990. this.aborted = false;
  1991. this.fire();
  1992. this.render();
  1993. this.out.write('\n');
  1994. this.close();
  1995. }
  1996. }
  1997. abort() {
  1998. this.done = this.aborted = true;
  1999. this.exited = false;
  2000. this.fire();
  2001. this.render();
  2002. this.out.write('\n');
  2003. this.close();
  2004. }
  2005. submit() {
  2006. this.done = true;
  2007. this.aborted = this.exited = false;
  2008. this.fire();
  2009. this.render();
  2010. this.out.write('\n');
  2011. this.close();
  2012. }
  2013. _(c, key) {
  2014. let s1 = this.input.slice(0, this.cursor);
  2015. let s2 = this.input.slice(this.cursor);
  2016. this.input = `${s1}${c}${s2}`;
  2017. this.cursor = s1.length + 1;
  2018. this.complete(this.render);
  2019. this.render();
  2020. }
  2021. delete() {
  2022. if (this.cursor === 0) return this.bell();
  2023. let s1 = this.input.slice(0, this.cursor - 1);
  2024. let s2 = this.input.slice(this.cursor);
  2025. this.input = `${s1}${s2}`;
  2026. this.complete(this.render);
  2027. this.cursor = this.cursor - 1;
  2028. this.render();
  2029. }
  2030. deleteForward() {
  2031. if (this.cursor * this.scale >= this.rendered.length) return this.bell();
  2032. let s1 = this.input.slice(0, this.cursor);
  2033. let s2 = this.input.slice(this.cursor + 1);
  2034. this.input = `${s1}${s2}`;
  2035. this.complete(this.render);
  2036. this.render();
  2037. }
  2038. first() {
  2039. this.moveSelect(0);
  2040. this.render();
  2041. }
  2042. last() {
  2043. this.moveSelect(this.suggestions.length - 1);
  2044. this.render();
  2045. }
  2046. up() {
  2047. if (this.select === 0) {
  2048. this.moveSelect(this.suggestions.length - 1);
  2049. } else {
  2050. this.moveSelect(this.select - 1);
  2051. }
  2052. this.render();
  2053. }
  2054. down() {
  2055. if (this.select === this.suggestions.length - 1) {
  2056. this.moveSelect(0);
  2057. } else {
  2058. this.moveSelect(this.select + 1);
  2059. }
  2060. this.render();
  2061. }
  2062. next() {
  2063. if (this.select === this.suggestions.length - 1) {
  2064. this.moveSelect(0);
  2065. } else this.moveSelect(this.select + 1);
  2066. this.render();
  2067. }
  2068. nextPage() {
  2069. this.moveSelect(Math.min(this.select + this.limit, this.suggestions.length - 1));
  2070. this.render();
  2071. }
  2072. prevPage() {
  2073. this.moveSelect(Math.max(this.select - this.limit, 0));
  2074. this.render();
  2075. }
  2076. left() {
  2077. if (this.cursor <= 0) return this.bell();
  2078. this.cursor = this.cursor - 1;
  2079. this.render();
  2080. }
  2081. right() {
  2082. if (this.cursor * this.scale >= this.rendered.length) return this.bell();
  2083. this.cursor = this.cursor + 1;
  2084. this.render();
  2085. }
  2086. renderOption(v, hovered, isStart, isEnd) {
  2087. let desc;
  2088. let prefix = isStart ? figures.arrowUp : isEnd ? figures.arrowDown : ' ';
  2089. let title = hovered ? color.cyan().underline(v.title) : v.title;
  2090. prefix = (hovered ? color.cyan(figures.pointer) + ' ' : ' ') + prefix;
  2091. if (v.description) {
  2092. desc = ` - ${v.description}`;
  2093. if (prefix.length + title.length + desc.length >= this.out.columns || v.description.split(/\r?\n/).length > 1) {
  2094. desc = '\n' + wrap(v.description, {
  2095. margin: 3,
  2096. width: this.out.columns
  2097. });
  2098. }
  2099. }
  2100. return prefix + ' ' + title + color.gray(desc || '');
  2101. }
  2102. render() {
  2103. if (this.closed) return;
  2104. if (this.firstRender) this.out.write(cursor.hide);else this.out.write(clear(this.outputText, this.out.columns));
  2105. super.render();
  2106. let _entriesToDisplay = entriesToDisplay(this.select, this.choices.length, this.limit),
  2107. startIndex = _entriesToDisplay.startIndex,
  2108. endIndex = _entriesToDisplay.endIndex;
  2109. this.outputText = [style.symbol(this.done, this.aborted, this.exited), color.bold(this.msg), style.delimiter(this.completing), this.done && this.suggestions[this.select] ? this.suggestions[this.select].title : this.rendered = this.transform.render(this.input)].join(' ');
  2110. if (!this.done) {
  2111. const suggestions = this.suggestions.slice(startIndex, endIndex).map((item, i) => this.renderOption(item, this.select === i + startIndex, i === 0 && startIndex > 0, i + startIndex === endIndex - 1 && endIndex < this.choices.length)).join('\n');
  2112. this.outputText += `\n` + (suggestions || color.gray(this.fallback.title));
  2113. }
  2114. this.out.write(erase.line + cursor.to(0) + this.outputText);
  2115. }
  2116. }
  2117. autocomplete$1 = AutocompletePrompt;
  2118. return autocomplete$1;
  2119. }
  2120. var autocompleteMultiselect$1;
  2121. var hasRequiredAutocompleteMultiselect$1;
  2122. function requireAutocompleteMultiselect$1 () {
  2123. if (hasRequiredAutocompleteMultiselect$1) return autocompleteMultiselect$1;
  2124. hasRequiredAutocompleteMultiselect$1 = 1;
  2125. const color = requireKleur();
  2126. const _require = requireSrc(),
  2127. cursor = _require.cursor;
  2128. const MultiselectPrompt = requireMultiselect$1();
  2129. const _require2 = requireUtil$1(),
  2130. clear = _require2.clear,
  2131. style = _require2.style,
  2132. figures = _require2.figures;
  2133. /**
  2134. * MultiselectPrompt Base Element
  2135. * @param {Object} opts Options
  2136. * @param {String} opts.message Message
  2137. * @param {Array} opts.choices Array of choice objects
  2138. * @param {String} [opts.hint] Hint to display
  2139. * @param {String} [opts.warn] Hint shown for disabled choices
  2140. * @param {Number} [opts.max] Max choices
  2141. * @param {Number} [opts.cursor=0] Cursor start position
  2142. * @param {Stream} [opts.stdin] The Readable stream to listen to
  2143. * @param {Stream} [opts.stdout] The Writable stream to write readline data to
  2144. */
  2145. class AutocompleteMultiselectPrompt extends MultiselectPrompt {
  2146. constructor(opts = {}) {
  2147. opts.overrideRender = true;
  2148. super(opts);
  2149. this.inputValue = '';
  2150. this.clear = clear('', this.out.columns);
  2151. this.filteredOptions = this.value;
  2152. this.render();
  2153. }
  2154. last() {
  2155. this.cursor = this.filteredOptions.length - 1;
  2156. this.render();
  2157. }
  2158. next() {
  2159. this.cursor = (this.cursor + 1) % this.filteredOptions.length;
  2160. this.render();
  2161. }
  2162. up() {
  2163. if (this.cursor === 0) {
  2164. this.cursor = this.filteredOptions.length - 1;
  2165. } else {
  2166. this.cursor--;
  2167. }
  2168. this.render();
  2169. }
  2170. down() {
  2171. if (this.cursor === this.filteredOptions.length - 1) {
  2172. this.cursor = 0;
  2173. } else {
  2174. this.cursor++;
  2175. }
  2176. this.render();
  2177. }
  2178. left() {
  2179. this.filteredOptions[this.cursor].selected = false;
  2180. this.render();
  2181. }
  2182. right() {
  2183. if (this.value.filter(e => e.selected).length >= this.maxChoices) return this.bell();
  2184. this.filteredOptions[this.cursor].selected = true;
  2185. this.render();
  2186. }
  2187. delete() {
  2188. if (this.inputValue.length) {
  2189. this.inputValue = this.inputValue.substr(0, this.inputValue.length - 1);
  2190. this.updateFilteredOptions();
  2191. }
  2192. }
  2193. updateFilteredOptions() {
  2194. const currentHighlight = this.filteredOptions[this.cursor];
  2195. this.filteredOptions = this.value.filter(v => {
  2196. if (this.inputValue) {
  2197. if (typeof v.title === 'string') {
  2198. if (v.title.toLowerCase().includes(this.inputValue.toLowerCase())) {
  2199. return true;
  2200. }
  2201. }
  2202. if (typeof v.value === 'string') {
  2203. if (v.value.toLowerCase().includes(this.inputValue.toLowerCase())) {
  2204. return true;
  2205. }
  2206. }
  2207. return false;
  2208. }
  2209. return true;
  2210. });
  2211. const newHighlightIndex = this.filteredOptions.findIndex(v => v === currentHighlight);
  2212. this.cursor = newHighlightIndex < 0 ? 0 : newHighlightIndex;
  2213. this.render();
  2214. }
  2215. handleSpaceToggle() {
  2216. const v = this.filteredOptions[this.cursor];
  2217. if (v.selected) {
  2218. v.selected = false;
  2219. this.render();
  2220. } else if (v.disabled || this.value.filter(e => e.selected).length >= this.maxChoices) {
  2221. return this.bell();
  2222. } else {
  2223. v.selected = true;
  2224. this.render();
  2225. }
  2226. }
  2227. handleInputChange(c) {
  2228. this.inputValue = this.inputValue + c;
  2229. this.updateFilteredOptions();
  2230. }
  2231. _(c, key) {
  2232. if (c === ' ') {
  2233. this.handleSpaceToggle();
  2234. } else {
  2235. this.handleInputChange(c);
  2236. }
  2237. }
  2238. renderInstructions() {
  2239. if (this.instructions === undefined || this.instructions) {
  2240. if (typeof this.instructions === 'string') {
  2241. return this.instructions;
  2242. }
  2243. return `
  2244. Instructions:
  2245. ${figures.arrowUp}/${figures.arrowDown}: Highlight option
  2246. ${figures.arrowLeft}/${figures.arrowRight}/[space]: Toggle selection
  2247. [a,b,c]/delete: Filter choices
  2248. enter/return: Complete answer
  2249. `;
  2250. }
  2251. return '';
  2252. }
  2253. renderCurrentInput() {
  2254. return `
  2255. Filtered results for: ${this.inputValue ? this.inputValue : color.gray('Enter something to filter')}\n`;
  2256. }
  2257. renderOption(cursor, v, i) {
  2258. let title;
  2259. if (v.disabled) title = cursor === i ? color.gray().underline(v.title) : color.strikethrough().gray(v.title);else title = cursor === i ? color.cyan().underline(v.title) : v.title;
  2260. return (v.selected ? color.green(figures.radioOn) : figures.radioOff) + ' ' + title;
  2261. }
  2262. renderDoneOrInstructions() {
  2263. if (this.done) {
  2264. return this.value.filter(e => e.selected).map(v => v.title).join(', ');
  2265. }
  2266. const output = [color.gray(this.hint), this.renderInstructions(), this.renderCurrentInput()];
  2267. if (this.filteredOptions.length && this.filteredOptions[this.cursor].disabled) {
  2268. output.push(color.yellow(this.warn));
  2269. }
  2270. return output.join(' ');
  2271. }
  2272. render() {
  2273. if (this.closed) return;
  2274. if (this.firstRender) this.out.write(cursor.hide);
  2275. super.render(); // print prompt
  2276. let prompt = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(false), this.renderDoneOrInstructions()].join(' ');
  2277. if (this.showMinError) {
  2278. prompt += color.red(`You must select a minimum of ${this.minSelected} choices.`);
  2279. this.showMinError = false;
  2280. }
  2281. prompt += this.renderOptions(this.filteredOptions);
  2282. this.out.write(this.clear + prompt);
  2283. this.clear = clear(prompt, this.out.columns);
  2284. }
  2285. }
  2286. autocompleteMultiselect$1 = AutocompleteMultiselectPrompt;
  2287. return autocompleteMultiselect$1;
  2288. }
  2289. var confirm$1;
  2290. var hasRequiredConfirm$1;
  2291. function requireConfirm$1 () {
  2292. if (hasRequiredConfirm$1) return confirm$1;
  2293. hasRequiredConfirm$1 = 1;
  2294. const color = requireKleur();
  2295. const Prompt = requirePrompt$1();
  2296. const _require = requireUtil$1(),
  2297. style = _require.style,
  2298. clear = _require.clear;
  2299. const _require2 = requireSrc(),
  2300. erase = _require2.erase,
  2301. cursor = _require2.cursor;
  2302. /**
  2303. * ConfirmPrompt Base Element
  2304. * @param {Object} opts Options
  2305. * @param {String} opts.message Message
  2306. * @param {Boolean} [opts.initial] Default value (true/false)
  2307. * @param {Stream} [opts.stdin] The Readable stream to listen to
  2308. * @param {Stream} [opts.stdout] The Writable stream to write readline data to
  2309. * @param {String} [opts.yes] The "Yes" label
  2310. * @param {String} [opts.yesOption] The "Yes" option when choosing between yes/no
  2311. * @param {String} [opts.no] The "No" label
  2312. * @param {String} [opts.noOption] The "No" option when choosing between yes/no
  2313. */
  2314. class ConfirmPrompt extends Prompt {
  2315. constructor(opts = {}) {
  2316. super(opts);
  2317. this.msg = opts.message;
  2318. this.value = opts.initial;
  2319. this.initialValue = !!opts.initial;
  2320. this.yesMsg = opts.yes || 'yes';
  2321. this.yesOption = opts.yesOption || '(Y/n)';
  2322. this.noMsg = opts.no || 'no';
  2323. this.noOption = opts.noOption || '(y/N)';
  2324. this.render();
  2325. }
  2326. reset() {
  2327. this.value = this.initialValue;
  2328. this.fire();
  2329. this.render();
  2330. }
  2331. exit() {
  2332. this.abort();
  2333. }
  2334. abort() {
  2335. this.done = this.aborted = true;
  2336. this.fire();
  2337. this.render();
  2338. this.out.write('\n');
  2339. this.close();
  2340. }
  2341. submit() {
  2342. this.value = this.value || false;
  2343. this.done = true;
  2344. this.aborted = false;
  2345. this.fire();
  2346. this.render();
  2347. this.out.write('\n');
  2348. this.close();
  2349. }
  2350. _(c, key) {
  2351. if (c.toLowerCase() === 'y') {
  2352. this.value = true;
  2353. return this.submit();
  2354. }
  2355. if (c.toLowerCase() === 'n') {
  2356. this.value = false;
  2357. return this.submit();
  2358. }
  2359. return this.bell();
  2360. }
  2361. render() {
  2362. if (this.closed) return;
  2363. if (this.firstRender) this.out.write(cursor.hide);else this.out.write(clear(this.outputText, this.out.columns));
  2364. super.render();
  2365. this.outputText = [style.symbol(this.done, this.aborted), color.bold(this.msg), style.delimiter(this.done), this.done ? this.value ? this.yesMsg : this.noMsg : color.gray(this.initialValue ? this.yesOption : this.noOption)].join(' ');
  2366. this.out.write(erase.line + cursor.to(0) + this.outputText);
  2367. }
  2368. }
  2369. confirm$1 = ConfirmPrompt;
  2370. return confirm$1;
  2371. }
  2372. var elements$1;
  2373. var hasRequiredElements$1;
  2374. function requireElements$1 () {
  2375. if (hasRequiredElements$1) return elements$1;
  2376. hasRequiredElements$1 = 1;
  2377. elements$1 = {
  2378. TextPrompt: requireText$1(),
  2379. SelectPrompt: requireSelect$1(),
  2380. TogglePrompt: requireToggle$1(),
  2381. DatePrompt: requireDate$1(),
  2382. NumberPrompt: requireNumber$1(),
  2383. MultiselectPrompt: requireMultiselect$1(),
  2384. AutocompletePrompt: requireAutocomplete$1(),
  2385. AutocompleteMultiselectPrompt: requireAutocompleteMultiselect$1(),
  2386. ConfirmPrompt: requireConfirm$1()
  2387. };
  2388. return elements$1;
  2389. }
  2390. var hasRequiredPrompts$1;
  2391. function requirePrompts$1 () {
  2392. if (hasRequiredPrompts$1) return prompts$2;
  2393. hasRequiredPrompts$1 = 1;
  2394. (function (exports) {
  2395. const $ = exports;
  2396. const el = requireElements$1();
  2397. const noop = v => v;
  2398. function toPrompt(type, args, opts = {}) {
  2399. return new Promise((res, rej) => {
  2400. const p = new el[type](args);
  2401. const onAbort = opts.onAbort || noop;
  2402. const onSubmit = opts.onSubmit || noop;
  2403. const onExit = opts.onExit || noop;
  2404. p.on('state', args.onState || noop);
  2405. p.on('submit', x => res(onSubmit(x)));
  2406. p.on('exit', x => res(onExit(x)));
  2407. p.on('abort', x => rej(onAbort(x)));
  2408. });
  2409. }
  2410. /**
  2411. * Text prompt
  2412. * @param {string} args.message Prompt message to display
  2413. * @param {string} [args.initial] Default string value
  2414. * @param {string} [args.style="default"] Render style ('default', 'password', 'invisible')
  2415. * @param {function} [args.onState] On state change callback
  2416. * @param {function} [args.validate] Function to validate user input
  2417. * @param {Stream} [args.stdin] The Readable stream to listen to
  2418. * @param {Stream} [args.stdout] The Writable stream to write readline data to
  2419. * @returns {Promise} Promise with user input
  2420. */
  2421. $.text = args => toPrompt('TextPrompt', args);
  2422. /**
  2423. * Password prompt with masked input
  2424. * @param {string} args.message Prompt message to display
  2425. * @param {string} [args.initial] Default string value
  2426. * @param {function} [args.onState] On state change callback
  2427. * @param {function} [args.validate] Function to validate user input
  2428. * @param {Stream} [args.stdin] The Readable stream to listen to
  2429. * @param {Stream} [args.stdout] The Writable stream to write readline data to
  2430. * @returns {Promise} Promise with user input
  2431. */
  2432. $.password = args => {
  2433. args.style = 'password';
  2434. return $.text(args);
  2435. };
  2436. /**
  2437. * Prompt where input is invisible, like sudo
  2438. * @param {string} args.message Prompt message to display
  2439. * @param {string} [args.initial] Default string value
  2440. * @param {function} [args.onState] On state change callback
  2441. * @param {function} [args.validate] Function to validate user input
  2442. * @param {Stream} [args.stdin] The Readable stream to listen to
  2443. * @param {Stream} [args.stdout] The Writable stream to write readline data to
  2444. * @returns {Promise} Promise with user input
  2445. */
  2446. $.invisible = args => {
  2447. args.style = 'invisible';
  2448. return $.text(args);
  2449. };
  2450. /**
  2451. * Number prompt
  2452. * @param {string} args.message Prompt message to display
  2453. * @param {number} args.initial Default number value
  2454. * @param {function} [args.onState] On state change callback
  2455. * @param {number} [args.max] Max value
  2456. * @param {number} [args.min] Min value
  2457. * @param {string} [args.style="default"] Render style ('default', 'password', 'invisible')
  2458. * @param {Boolean} [opts.float=false] Parse input as floats
  2459. * @param {Number} [opts.round=2] Round floats to x decimals
  2460. * @param {Number} [opts.increment=1] Number to increment by when using arrow-keys
  2461. * @param {function} [args.validate] Function to validate user input
  2462. * @param {Stream} [args.stdin] The Readable stream to listen to
  2463. * @param {Stream} [args.stdout] The Writable stream to write readline data to
  2464. * @returns {Promise} Promise with user input
  2465. */
  2466. $.number = args => toPrompt('NumberPrompt', args);
  2467. /**
  2468. * Date prompt
  2469. * @param {string} args.message Prompt message to display
  2470. * @param {number} args.initial Default number value
  2471. * @param {function} [args.onState] On state change callback
  2472. * @param {number} [args.max] Max value
  2473. * @param {number} [args.min] Min value
  2474. * @param {string} [args.style="default"] Render style ('default', 'password', 'invisible')
  2475. * @param {Boolean} [opts.float=false] Parse input as floats
  2476. * @param {Number} [opts.round=2] Round floats to x decimals
  2477. * @param {Number} [opts.increment=1] Number to increment by when using arrow-keys
  2478. * @param {function} [args.validate] Function to validate user input
  2479. * @param {Stream} [args.stdin] The Readable stream to listen to
  2480. * @param {Stream} [args.stdout] The Writable stream to write readline data to
  2481. * @returns {Promise} Promise with user input
  2482. */
  2483. $.date = args => toPrompt('DatePrompt', args);
  2484. /**
  2485. * Classic yes/no prompt
  2486. * @param {string} args.message Prompt message to display
  2487. * @param {boolean} [args.initial=false] Default value
  2488. * @param {function} [args.onState] On state change callback
  2489. * @param {Stream} [args.stdin] The Readable stream to listen to
  2490. * @param {Stream} [args.stdout] The Writable stream to write readline data to
  2491. * @returns {Promise} Promise with user input
  2492. */
  2493. $.confirm = args => toPrompt('ConfirmPrompt', args);
  2494. /**
  2495. * List prompt, split intput string by `seperator`
  2496. * @param {string} args.message Prompt message to display
  2497. * @param {string} [args.initial] Default string value
  2498. * @param {string} [args.style="default"] Render style ('default', 'password', 'invisible')
  2499. * @param {string} [args.separator] String separator
  2500. * @param {function} [args.onState] On state change callback
  2501. * @param {Stream} [args.stdin] The Readable stream to listen to
  2502. * @param {Stream} [args.stdout] The Writable stream to write readline data to
  2503. * @returns {Promise} Promise with user input, in form of an `Array`
  2504. */
  2505. $.list = args => {
  2506. const sep = args.separator || ',';
  2507. return toPrompt('TextPrompt', args, {
  2508. onSubmit: str => str.split(sep).map(s => s.trim())
  2509. });
  2510. };
  2511. /**
  2512. * Toggle/switch prompt
  2513. * @param {string} args.message Prompt message to display
  2514. * @param {boolean} [args.initial=false] Default value
  2515. * @param {string} [args.active="on"] Text for `active` state
  2516. * @param {string} [args.inactive="off"] Text for `inactive` state
  2517. * @param {function} [args.onState] On state change callback
  2518. * @param {Stream} [args.stdin] The Readable stream to listen to
  2519. * @param {Stream} [args.stdout] The Writable stream to write readline data to
  2520. * @returns {Promise} Promise with user input
  2521. */
  2522. $.toggle = args => toPrompt('TogglePrompt', args);
  2523. /**
  2524. * Interactive select prompt
  2525. * @param {string} args.message Prompt message to display
  2526. * @param {Array} args.choices Array of choices objects `[{ title, value }, ...]`
  2527. * @param {number} [args.initial] Index of default value
  2528. * @param {String} [args.hint] Hint to display
  2529. * @param {function} [args.onState] On state change callback
  2530. * @param {Stream} [args.stdin] The Readable stream to listen to
  2531. * @param {Stream} [args.stdout] The Writable stream to write readline data to
  2532. * @returns {Promise} Promise with user input
  2533. */
  2534. $.select = args => toPrompt('SelectPrompt', args);
  2535. /**
  2536. * Interactive multi-select / autocompleteMultiselect prompt
  2537. * @param {string} args.message Prompt message to display
  2538. * @param {Array} args.choices Array of choices objects `[{ title, value, [selected] }, ...]`
  2539. * @param {number} [args.max] Max select
  2540. * @param {string} [args.hint] Hint to display user
  2541. * @param {Number} [args.cursor=0] Cursor start position
  2542. * @param {function} [args.onState] On state change callback
  2543. * @param {Stream} [args.stdin] The Readable stream to listen to
  2544. * @param {Stream} [args.stdout] The Writable stream to write readline data to
  2545. * @returns {Promise} Promise with user input
  2546. */
  2547. $.multiselect = args => {
  2548. args.choices = [].concat(args.choices || []);
  2549. const toSelected = items => items.filter(item => item.selected).map(item => item.value);
  2550. return toPrompt('MultiselectPrompt', args, {
  2551. onAbort: toSelected,
  2552. onSubmit: toSelected
  2553. });
  2554. };
  2555. $.autocompleteMultiselect = args => {
  2556. args.choices = [].concat(args.choices || []);
  2557. const toSelected = items => items.filter(item => item.selected).map(item => item.value);
  2558. return toPrompt('AutocompleteMultiselectPrompt', args, {
  2559. onAbort: toSelected,
  2560. onSubmit: toSelected
  2561. });
  2562. };
  2563. const byTitle = (input, choices) => Promise.resolve(choices.filter(item => item.title.slice(0, input.length).toLowerCase() === input.toLowerCase()));
  2564. /**
  2565. * Interactive auto-complete prompt
  2566. * @param {string} args.message Prompt message to display
  2567. * @param {Array} args.choices Array of auto-complete choices objects `[{ title, value }, ...]`
  2568. * @param {Function} [args.suggest] Function to filter results based on user input. Defaults to sort by `title`
  2569. * @param {number} [args.limit=10] Max number of results to show
  2570. * @param {string} [args.style="default"] Render style ('default', 'password', 'invisible')
  2571. * @param {String} [args.initial] Index of the default value
  2572. * @param {boolean} [opts.clearFirst] The first ESCAPE keypress will clear the input
  2573. * @param {String} [args.fallback] Fallback message - defaults to initial value
  2574. * @param {function} [args.onState] On state change callback
  2575. * @param {Stream} [args.stdin] The Readable stream to listen to
  2576. * @param {Stream} [args.stdout] The Writable stream to write readline data to
  2577. * @returns {Promise} Promise with user input
  2578. */
  2579. $.autocomplete = args => {
  2580. args.suggest = args.suggest || byTitle;
  2581. args.choices = [].concat(args.choices || []);
  2582. return toPrompt('AutocompletePrompt', args);
  2583. };
  2584. } (prompts$2));
  2585. return prompts$2;
  2586. }
  2587. var dist;
  2588. var hasRequiredDist;
  2589. function requireDist () {
  2590. if (hasRequiredDist) return dist;
  2591. hasRequiredDist = 1;
  2592. function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
  2593. function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
  2594. function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
  2595. function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
  2596. function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
  2597. function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
  2598. function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
  2599. function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
  2600. const prompts = requirePrompts$1();
  2601. const passOn = ['suggest', 'format', 'onState', 'validate', 'onRender', 'type'];
  2602. const noop = () => {};
  2603. /**
  2604. * Prompt for a series of questions
  2605. * @param {Array|Object} questions Single question object or Array of question objects
  2606. * @param {Function} [onSubmit] Callback function called on prompt submit
  2607. * @param {Function} [onCancel] Callback function called on cancel/abort
  2608. * @returns {Object} Object with values from user input
  2609. */
  2610. function prompt() {
  2611. return _prompt.apply(this, arguments);
  2612. }
  2613. function _prompt() {
  2614. _prompt = _asyncToGenerator(function* (questions = [], {
  2615. onSubmit = noop,
  2616. onCancel = noop
  2617. } = {}) {
  2618. const answers = {};
  2619. const override = prompt._override || {};
  2620. questions = [].concat(questions);
  2621. let answer, question, quit, name, type, lastPrompt;
  2622. const getFormattedAnswer = /*#__PURE__*/function () {
  2623. var _ref = _asyncToGenerator(function* (question, answer, skipValidation = false) {
  2624. if (!skipValidation && question.validate && question.validate(answer) !== true) {
  2625. return;
  2626. }
  2627. return question.format ? yield question.format(answer, answers) : answer;
  2628. });
  2629. return function getFormattedAnswer(_x, _x2) {
  2630. return _ref.apply(this, arguments);
  2631. };
  2632. }();
  2633. var _iterator = _createForOfIteratorHelper(questions),
  2634. _step;
  2635. try {
  2636. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  2637. question = _step.value;
  2638. var _question = question;
  2639. name = _question.name;
  2640. type = _question.type;
  2641. // evaluate type first and skip if type is a falsy value
  2642. if (typeof type === 'function') {
  2643. type = yield type(answer, _objectSpread({}, answers), question);
  2644. question['type'] = type;
  2645. }
  2646. if (!type) continue; // if property is a function, invoke it unless it's a special function
  2647. for (let key in question) {
  2648. if (passOn.includes(key)) continue;
  2649. let value = question[key];
  2650. question[key] = typeof value === 'function' ? yield value(answer, _objectSpread({}, answers), lastPrompt) : value;
  2651. }
  2652. lastPrompt = question;
  2653. if (typeof question.message !== 'string') {
  2654. throw new Error('prompt message is required');
  2655. } // update vars in case they changed
  2656. var _question2 = question;
  2657. name = _question2.name;
  2658. type = _question2.type;
  2659. if (prompts[type] === void 0) {
  2660. throw new Error(`prompt type (${type}) is not defined`);
  2661. }
  2662. if (override[question.name] !== undefined) {
  2663. answer = yield getFormattedAnswer(question, override[question.name]);
  2664. if (answer !== undefined) {
  2665. answers[name] = answer;
  2666. continue;
  2667. }
  2668. }
  2669. try {
  2670. // Get the injected answer if there is one or prompt the user
  2671. answer = prompt._injected ? getInjectedAnswer(prompt._injected, question.initial) : yield prompts[type](question);
  2672. answers[name] = answer = yield getFormattedAnswer(question, answer, true);
  2673. quit = yield onSubmit(question, answer, answers);
  2674. } catch (err) {
  2675. quit = !(yield onCancel(question, answers));
  2676. }
  2677. if (quit) return answers;
  2678. }
  2679. } catch (err) {
  2680. _iterator.e(err);
  2681. } finally {
  2682. _iterator.f();
  2683. }
  2684. return answers;
  2685. });
  2686. return _prompt.apply(this, arguments);
  2687. }
  2688. function getInjectedAnswer(injected, deafultValue) {
  2689. const answer = injected.shift();
  2690. if (answer instanceof Error) {
  2691. throw answer;
  2692. }
  2693. return answer === undefined ? deafultValue : answer;
  2694. }
  2695. function inject(answers) {
  2696. prompt._injected = (prompt._injected || []).concat(answers);
  2697. }
  2698. function override(answers) {
  2699. prompt._override = Object.assign({}, answers);
  2700. }
  2701. dist = Object.assign(prompt, {
  2702. prompt,
  2703. prompts,
  2704. inject,
  2705. override
  2706. });
  2707. return dist;
  2708. }
  2709. var prompts$1 = {};
  2710. var action;
  2711. var hasRequiredAction;
  2712. function requireAction () {
  2713. if (hasRequiredAction) return action;
  2714. hasRequiredAction = 1;
  2715. action = (key, isSelect) => {
  2716. if (key.meta && key.name !== 'escape') return;
  2717. if (key.ctrl) {
  2718. if (key.name === 'a') return 'first';
  2719. if (key.name === 'c') return 'abort';
  2720. if (key.name === 'd') return 'abort';
  2721. if (key.name === 'e') return 'last';
  2722. if (key.name === 'g') return 'reset';
  2723. }
  2724. if (isSelect) {
  2725. if (key.name === 'j') return 'down';
  2726. if (key.name === 'k') return 'up';
  2727. }
  2728. if (key.name === 'return') return 'submit';
  2729. if (key.name === 'enter') return 'submit'; // ctrl + J
  2730. if (key.name === 'backspace') return 'delete';
  2731. if (key.name === 'delete') return 'deleteForward';
  2732. if (key.name === 'abort') return 'abort';
  2733. if (key.name === 'escape') return 'exit';
  2734. if (key.name === 'tab') return 'next';
  2735. if (key.name === 'pagedown') return 'nextPage';
  2736. if (key.name === 'pageup') return 'prevPage';
  2737. // TODO create home() in prompt types (e.g. TextPrompt)
  2738. if (key.name === 'home') return 'home';
  2739. // TODO create end() in prompt types (e.g. TextPrompt)
  2740. if (key.name === 'end') return 'end';
  2741. if (key.name === 'up') return 'up';
  2742. if (key.name === 'down') return 'down';
  2743. if (key.name === 'right') return 'right';
  2744. if (key.name === 'left') return 'left';
  2745. return false;
  2746. };
  2747. return action;
  2748. }
  2749. var strip;
  2750. var hasRequiredStrip;
  2751. function requireStrip () {
  2752. if (hasRequiredStrip) return strip;
  2753. hasRequiredStrip = 1;
  2754. strip = str => {
  2755. const pattern = [
  2756. '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)',
  2757. '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))'
  2758. ].join('|');
  2759. const RGX = new RegExp(pattern, 'g');
  2760. return typeof str === 'string' ? str.replace(RGX, '') : str;
  2761. };
  2762. return strip;
  2763. }
  2764. var clear;
  2765. var hasRequiredClear;
  2766. function requireClear () {
  2767. if (hasRequiredClear) return clear;
  2768. hasRequiredClear = 1;
  2769. const strip = requireStrip();
  2770. const { erase, cursor } = requireSrc();
  2771. const width = str => [...strip(str)].length;
  2772. /**
  2773. * @param {string} prompt
  2774. * @param {number} perLine
  2775. */
  2776. clear = function(prompt, perLine) {
  2777. if (!perLine) return erase.line + cursor.to(0);
  2778. let rows = 0;
  2779. const lines = prompt.split(/\r?\n/);
  2780. for (let line of lines) {
  2781. rows += 1 + Math.floor(Math.max(width(line) - 1, 0) / perLine);
  2782. }
  2783. return erase.lines(rows);
  2784. };
  2785. return clear;
  2786. }
  2787. var figures_1;
  2788. var hasRequiredFigures;
  2789. function requireFigures () {
  2790. if (hasRequiredFigures) return figures_1;
  2791. hasRequiredFigures = 1;
  2792. const main = {
  2793. arrowUp: '↑',
  2794. arrowDown: '↓',
  2795. arrowLeft: '←',
  2796. arrowRight: '→',
  2797. radioOn: '◉',
  2798. radioOff: '◯',
  2799. tick: '✔',
  2800. cross: '✖',
  2801. ellipsis: '…',
  2802. pointerSmall: '›',
  2803. line: '─',
  2804. pointer: '❯'
  2805. };
  2806. const win = {
  2807. arrowUp: main.arrowUp,
  2808. arrowDown: main.arrowDown,
  2809. arrowLeft: main.arrowLeft,
  2810. arrowRight: main.arrowRight,
  2811. radioOn: '(*)',
  2812. radioOff: '( )',
  2813. tick: '√',
  2814. cross: '×',
  2815. ellipsis: '...',
  2816. pointerSmall: '»',
  2817. line: '─',
  2818. pointer: '>'
  2819. };
  2820. const figures = process.platform === 'win32' ? win : main;
  2821. figures_1 = figures;
  2822. return figures_1;
  2823. }
  2824. var style;
  2825. var hasRequiredStyle;
  2826. function requireStyle () {
  2827. if (hasRequiredStyle) return style;
  2828. hasRequiredStyle = 1;
  2829. const c = requireKleur();
  2830. const figures = requireFigures();
  2831. // rendering user input.
  2832. const styles = Object.freeze({
  2833. password: { scale: 1, render: input => '*'.repeat(input.length) },
  2834. emoji: { scale: 2, render: input => '😃'.repeat(input.length) },
  2835. invisible: { scale: 0, render: input => '' },
  2836. default: { scale: 1, render: input => `${input}` }
  2837. });
  2838. const render = type => styles[type] || styles.default;
  2839. // icon to signalize a prompt.
  2840. const symbols = Object.freeze({
  2841. aborted: c.red(figures.cross),
  2842. done: c.green(figures.tick),
  2843. exited: c.yellow(figures.cross),
  2844. default: c.cyan('?')
  2845. });
  2846. const symbol = (done, aborted, exited) =>
  2847. aborted ? symbols.aborted : exited ? symbols.exited : done ? symbols.done : symbols.default;
  2848. // between the question and the user's input.
  2849. const delimiter = completing =>
  2850. c.gray(completing ? figures.ellipsis : figures.pointerSmall);
  2851. const item = (expandable, expanded) =>
  2852. c.gray(expandable ? (expanded ? figures.pointerSmall : '+') : figures.line);
  2853. style = {
  2854. styles,
  2855. render,
  2856. symbols,
  2857. symbol,
  2858. delimiter,
  2859. item
  2860. };
  2861. return style;
  2862. }
  2863. var lines;
  2864. var hasRequiredLines;
  2865. function requireLines () {
  2866. if (hasRequiredLines) return lines;
  2867. hasRequiredLines = 1;
  2868. const strip = requireStrip();
  2869. /**
  2870. * @param {string} msg
  2871. * @param {number} perLine
  2872. */
  2873. lines = function (msg, perLine) {
  2874. let lines = String(strip(msg) || '').split(/\r?\n/);
  2875. if (!perLine) return lines.length;
  2876. return lines.map(l => Math.ceil(l.length / perLine))
  2877. .reduce((a, b) => a + b);
  2878. };
  2879. return lines;
  2880. }
  2881. var wrap;
  2882. var hasRequiredWrap;
  2883. function requireWrap () {
  2884. if (hasRequiredWrap) return wrap;
  2885. hasRequiredWrap = 1;
  2886. /**
  2887. * @param {string} msg The message to wrap
  2888. * @param {object} opts
  2889. * @param {number|string} [opts.margin] Left margin
  2890. * @param {number} opts.width Maximum characters per line including the margin
  2891. */
  2892. wrap = (msg, opts = {}) => {
  2893. const tab = Number.isSafeInteger(parseInt(opts.margin))
  2894. ? new Array(parseInt(opts.margin)).fill(' ').join('')
  2895. : (opts.margin || '');
  2896. const width = opts.width;
  2897. return (msg || '').split(/\r?\n/g)
  2898. .map(line => line
  2899. .split(/\s+/g)
  2900. .reduce((arr, w) => {
  2901. if (w.length + tab.length >= width || arr[arr.length - 1].length + w.length + 1 < width)
  2902. arr[arr.length - 1] += ` ${w}`;
  2903. else arr.push(`${tab}${w}`);
  2904. return arr;
  2905. }, [ tab ])
  2906. .join('\n'))
  2907. .join('\n');
  2908. };
  2909. return wrap;
  2910. }
  2911. var entriesToDisplay;
  2912. var hasRequiredEntriesToDisplay;
  2913. function requireEntriesToDisplay () {
  2914. if (hasRequiredEntriesToDisplay) return entriesToDisplay;
  2915. hasRequiredEntriesToDisplay = 1;
  2916. /**
  2917. * Determine what entries should be displayed on the screen, based on the
  2918. * currently selected index and the maximum visible. Used in list-based
  2919. * prompts like `select` and `multiselect`.
  2920. *
  2921. * @param {number} cursor the currently selected entry
  2922. * @param {number} total the total entries available to display
  2923. * @param {number} [maxVisible] the number of entries that can be displayed
  2924. */
  2925. entriesToDisplay = (cursor, total, maxVisible) => {
  2926. maxVisible = maxVisible || total;
  2927. let startIndex = Math.min(total- maxVisible, cursor - Math.floor(maxVisible / 2));
  2928. if (startIndex < 0) startIndex = 0;
  2929. let endIndex = Math.min(startIndex + maxVisible, total);
  2930. return { startIndex, endIndex };
  2931. };
  2932. return entriesToDisplay;
  2933. }
  2934. var util;
  2935. var hasRequiredUtil;
  2936. function requireUtil () {
  2937. if (hasRequiredUtil) return util;
  2938. hasRequiredUtil = 1;
  2939. util = {
  2940. action: requireAction(),
  2941. clear: requireClear(),
  2942. style: requireStyle(),
  2943. strip: requireStrip(),
  2944. figures: requireFigures(),
  2945. lines: requireLines(),
  2946. wrap: requireWrap(),
  2947. entriesToDisplay: requireEntriesToDisplay()
  2948. };
  2949. return util;
  2950. }
  2951. var prompt;
  2952. var hasRequiredPrompt;
  2953. function requirePrompt () {
  2954. if (hasRequiredPrompt) return prompt;
  2955. hasRequiredPrompt = 1;
  2956. const readline = require$$0;
  2957. const { action } = requireUtil();
  2958. const EventEmitter = require$$2;
  2959. const { beep, cursor } = requireSrc();
  2960. const color = requireKleur();
  2961. /**
  2962. * Base prompt skeleton
  2963. * @param {Stream} [opts.stdin] The Readable stream to listen to
  2964. * @param {Stream} [opts.stdout] The Writable stream to write readline data to
  2965. */
  2966. class Prompt extends EventEmitter {
  2967. constructor(opts={}) {
  2968. super();
  2969. this.firstRender = true;
  2970. this.in = opts.stdin || process.stdin;
  2971. this.out = opts.stdout || process.stdout;
  2972. this.onRender = (opts.onRender || (() => void 0)).bind(this);
  2973. const rl = readline.createInterface({ input:this.in, escapeCodeTimeout:50 });
  2974. readline.emitKeypressEvents(this.in, rl);
  2975. if (this.in.isTTY) this.in.setRawMode(true);
  2976. const isSelect = [ 'SelectPrompt', 'MultiselectPrompt' ].indexOf(this.constructor.name) > -1;
  2977. const keypress = (str, key) => {
  2978. let a = action(key, isSelect);
  2979. if (a === false) {
  2980. this._ && this._(str, key);
  2981. } else if (typeof this[a] === 'function') {
  2982. this[a](key);
  2983. } else {
  2984. this.bell();
  2985. }
  2986. };
  2987. this.close = () => {
  2988. this.out.write(cursor.show);
  2989. this.in.removeListener('keypress', keypress);
  2990. if (this.in.isTTY) this.in.setRawMode(false);
  2991. rl.close();
  2992. this.emit(this.aborted ? 'abort' : this.exited ? 'exit' : 'submit', this.value);
  2993. this.closed = true;
  2994. };
  2995. this.in.on('keypress', keypress);
  2996. }
  2997. fire() {
  2998. this.emit('state', {
  2999. value: this.value,
  3000. aborted: !!this.aborted,
  3001. exited: !!this.exited
  3002. });
  3003. }
  3004. bell() {
  3005. this.out.write(beep);
  3006. }
  3007. render() {
  3008. this.onRender(color);
  3009. if (this.firstRender) this.firstRender = false;
  3010. }
  3011. }
  3012. prompt = Prompt;
  3013. return prompt;
  3014. }
  3015. var text;
  3016. var hasRequiredText;
  3017. function requireText () {
  3018. if (hasRequiredText) return text;
  3019. hasRequiredText = 1;
  3020. const color = requireKleur();
  3021. const Prompt = requirePrompt();
  3022. const { erase, cursor } = requireSrc();
  3023. const { style, clear, lines, figures } = requireUtil();
  3024. /**
  3025. * TextPrompt Base Element
  3026. * @param {Object} opts Options
  3027. * @param {String} opts.message Message
  3028. * @param {String} [opts.style='default'] Render style
  3029. * @param {String} [opts.initial] Default value
  3030. * @param {Function} [opts.validate] Validate function
  3031. * @param {Stream} [opts.stdin] The Readable stream to listen to
  3032. * @param {Stream} [opts.stdout] The Writable stream to write readline data to
  3033. * @param {String} [opts.error] The invalid error label
  3034. */
  3035. class TextPrompt extends Prompt {
  3036. constructor(opts={}) {
  3037. super(opts);
  3038. this.transform = style.render(opts.style);
  3039. this.scale = this.transform.scale;
  3040. this.msg = opts.message;
  3041. this.initial = opts.initial || ``;
  3042. this.validator = opts.validate || (() => true);
  3043. this.value = ``;
  3044. this.errorMsg = opts.error || `Please Enter A Valid Value`;
  3045. this.cursor = Number(!!this.initial);
  3046. this.cursorOffset = 0;
  3047. this.clear = clear(``, this.out.columns);
  3048. this.render();
  3049. }
  3050. set value(v) {
  3051. if (!v && this.initial) {
  3052. this.placeholder = true;
  3053. this.rendered = color.gray(this.transform.render(this.initial));
  3054. } else {
  3055. this.placeholder = false;
  3056. this.rendered = this.transform.render(v);
  3057. }
  3058. this._value = v;
  3059. this.fire();
  3060. }
  3061. get value() {
  3062. return this._value;
  3063. }
  3064. reset() {
  3065. this.value = ``;
  3066. this.cursor = Number(!!this.initial);
  3067. this.cursorOffset = 0;
  3068. this.fire();
  3069. this.render();
  3070. }
  3071. exit() {
  3072. this.abort();
  3073. }
  3074. abort() {
  3075. this.value = this.value || this.initial;
  3076. this.done = this.aborted = true;
  3077. this.error = false;
  3078. this.red = false;
  3079. this.fire();
  3080. this.render();
  3081. this.out.write('\n');
  3082. this.close();
  3083. }
  3084. async validate() {
  3085. let valid = await this.validator(this.value);
  3086. if (typeof valid === `string`) {
  3087. this.errorMsg = valid;
  3088. valid = false;
  3089. }
  3090. this.error = !valid;
  3091. }
  3092. async submit() {
  3093. this.value = this.value || this.initial;
  3094. this.cursorOffset = 0;
  3095. this.cursor = this.rendered.length;
  3096. await this.validate();
  3097. if (this.error) {
  3098. this.red = true;
  3099. this.fire();
  3100. this.render();
  3101. return;
  3102. }
  3103. this.done = true;
  3104. this.aborted = false;
  3105. this.fire();
  3106. this.render();
  3107. this.out.write('\n');
  3108. this.close();
  3109. }
  3110. next() {
  3111. if (!this.placeholder) return this.bell();
  3112. this.value = this.initial;
  3113. this.cursor = this.rendered.length;
  3114. this.fire();
  3115. this.render();
  3116. }
  3117. moveCursor(n) {
  3118. if (this.placeholder) return;
  3119. this.cursor = this.cursor+n;
  3120. this.cursorOffset += n;
  3121. }
  3122. _(c, key) {
  3123. let s1 = this.value.slice(0, this.cursor);
  3124. let s2 = this.value.slice(this.cursor);
  3125. this.value = `${s1}${c}${s2}`;
  3126. this.red = false;
  3127. this.cursor = this.placeholder ? 0 : s1.length+1;
  3128. this.render();
  3129. }
  3130. delete() {
  3131. if (this.isCursorAtStart()) return this.bell();
  3132. let s1 = this.value.slice(0, this.cursor-1);
  3133. let s2 = this.value.slice(this.cursor);
  3134. this.value = `${s1}${s2}`;
  3135. this.red = false;
  3136. if (this.isCursorAtStart()) {
  3137. this.cursorOffset = 0;
  3138. } else {
  3139. this.cursorOffset++;
  3140. this.moveCursor(-1);
  3141. }
  3142. this.render();
  3143. }
  3144. deleteForward() {
  3145. if(this.cursor*this.scale >= this.rendered.length || this.placeholder) return this.bell();
  3146. let s1 = this.value.slice(0, this.cursor);
  3147. let s2 = this.value.slice(this.cursor+1);
  3148. this.value = `${s1}${s2}`;
  3149. this.red = false;
  3150. if (this.isCursorAtEnd()) {
  3151. this.cursorOffset = 0;
  3152. } else {
  3153. this.cursorOffset++;
  3154. }
  3155. this.render();
  3156. }
  3157. first() {
  3158. this.cursor = 0;
  3159. this.render();
  3160. }
  3161. last() {
  3162. this.cursor = this.value.length;
  3163. this.render();
  3164. }
  3165. left() {
  3166. if (this.cursor <= 0 || this.placeholder) return this.bell();
  3167. this.moveCursor(-1);
  3168. this.render();
  3169. }
  3170. right() {
  3171. if (this.cursor*this.scale >= this.rendered.length || this.placeholder) return this.bell();
  3172. this.moveCursor(1);
  3173. this.render();
  3174. }
  3175. isCursorAtStart() {
  3176. return this.cursor === 0 || (this.placeholder && this.cursor === 1);
  3177. }
  3178. isCursorAtEnd() {
  3179. return this.cursor === this.rendered.length || (this.placeholder && this.cursor === this.rendered.length + 1)
  3180. }
  3181. render() {
  3182. if (this.closed) return;
  3183. if (!this.firstRender) {
  3184. if (this.outputError)
  3185. this.out.write(cursor.down(lines(this.outputError, this.out.columns) - 1) + clear(this.outputError, this.out.columns));
  3186. this.out.write(clear(this.outputText, this.out.columns));
  3187. }
  3188. super.render();
  3189. this.outputError = '';
  3190. this.outputText = [
  3191. style.symbol(this.done, this.aborted),
  3192. color.bold(this.msg),
  3193. style.delimiter(this.done),
  3194. this.red ? color.red(this.rendered) : this.rendered
  3195. ].join(` `);
  3196. if (this.error) {
  3197. this.outputError += this.errorMsg.split(`\n`)
  3198. .reduce((a, l, i) => a + `\n${i ? ' ' : figures.pointerSmall} ${color.red().italic(l)}`, ``);
  3199. }
  3200. this.out.write(erase.line + cursor.to(0) + this.outputText + cursor.save + this.outputError + cursor.restore + cursor.move(this.cursorOffset, 0));
  3201. }
  3202. }
  3203. text = TextPrompt;
  3204. return text;
  3205. }
  3206. var select;
  3207. var hasRequiredSelect;
  3208. function requireSelect () {
  3209. if (hasRequiredSelect) return select;
  3210. hasRequiredSelect = 1;
  3211. const color = requireKleur();
  3212. const Prompt = requirePrompt();
  3213. const { style, clear, figures, wrap, entriesToDisplay } = requireUtil();
  3214. const { cursor } = requireSrc();
  3215. /**
  3216. * SelectPrompt Base Element
  3217. * @param {Object} opts Options
  3218. * @param {String} opts.message Message
  3219. * @param {Array} opts.choices Array of choice objects
  3220. * @param {String} [opts.hint] Hint to display
  3221. * @param {Number} [opts.initial] Index of default value
  3222. * @param {Stream} [opts.stdin] The Readable stream to listen to
  3223. * @param {Stream} [opts.stdout] The Writable stream to write readline data to
  3224. * @param {Number} [opts.optionsPerPage=10] Max options to display at once
  3225. */
  3226. class SelectPrompt extends Prompt {
  3227. constructor(opts={}) {
  3228. super(opts);
  3229. this.msg = opts.message;
  3230. this.hint = opts.hint || '- Use arrow-keys. Return to submit.';
  3231. this.warn = opts.warn || '- This option is disabled';
  3232. this.cursor = opts.initial || 0;
  3233. this.choices = opts.choices.map((ch, idx) => {
  3234. if (typeof ch === 'string')
  3235. ch = {title: ch, value: idx};
  3236. return {
  3237. title: ch && (ch.title || ch.value || ch),
  3238. value: ch && (ch.value === undefined ? idx : ch.value),
  3239. description: ch && ch.description,
  3240. selected: ch && ch.selected,
  3241. disabled: ch && ch.disabled
  3242. };
  3243. });
  3244. this.optionsPerPage = opts.optionsPerPage || 10;
  3245. this.value = (this.choices[this.cursor] || {}).value;
  3246. this.clear = clear('', this.out.columns);
  3247. this.render();
  3248. }
  3249. moveCursor(n) {
  3250. this.cursor = n;
  3251. this.value = this.choices[n].value;
  3252. this.fire();
  3253. }
  3254. reset() {
  3255. this.moveCursor(0);
  3256. this.fire();
  3257. this.render();
  3258. }
  3259. exit() {
  3260. this.abort();
  3261. }
  3262. abort() {
  3263. this.done = this.aborted = true;
  3264. this.fire();
  3265. this.render();
  3266. this.out.write('\n');
  3267. this.close();
  3268. }
  3269. submit() {
  3270. if (!this.selection.disabled) {
  3271. this.done = true;
  3272. this.aborted = false;
  3273. this.fire();
  3274. this.render();
  3275. this.out.write('\n');
  3276. this.close();
  3277. } else
  3278. this.bell();
  3279. }
  3280. first() {
  3281. this.moveCursor(0);
  3282. this.render();
  3283. }
  3284. last() {
  3285. this.moveCursor(this.choices.length - 1);
  3286. this.render();
  3287. }
  3288. up() {
  3289. if (this.cursor === 0) {
  3290. this.moveCursor(this.choices.length - 1);
  3291. } else {
  3292. this.moveCursor(this.cursor - 1);
  3293. }
  3294. this.render();
  3295. }
  3296. down() {
  3297. if (this.cursor === this.choices.length - 1) {
  3298. this.moveCursor(0);
  3299. } else {
  3300. this.moveCursor(this.cursor + 1);
  3301. }
  3302. this.render();
  3303. }
  3304. next() {
  3305. this.moveCursor((this.cursor + 1) % this.choices.length);
  3306. this.render();
  3307. }
  3308. _(c, key) {
  3309. if (c === ' ') return this.submit();
  3310. }
  3311. get selection() {
  3312. return this.choices[this.cursor];
  3313. }
  3314. render() {
  3315. if (this.closed) return;
  3316. if (this.firstRender) this.out.write(cursor.hide);
  3317. else this.out.write(clear(this.outputText, this.out.columns));
  3318. super.render();
  3319. let { startIndex, endIndex } = entriesToDisplay(this.cursor, this.choices.length, this.optionsPerPage);
  3320. // Print prompt
  3321. this.outputText = [
  3322. style.symbol(this.done, this.aborted),
  3323. color.bold(this.msg),
  3324. style.delimiter(false),
  3325. this.done ? this.selection.title : this.selection.disabled
  3326. ? color.yellow(this.warn) : color.gray(this.hint)
  3327. ].join(' ');
  3328. // Print choices
  3329. if (!this.done) {
  3330. this.outputText += '\n';
  3331. for (let i = startIndex; i < endIndex; i++) {
  3332. let title, prefix, desc = '', v = this.choices[i];
  3333. // Determine whether to display "more choices" indicators
  3334. if (i === startIndex && startIndex > 0) {
  3335. prefix = figures.arrowUp;
  3336. } else if (i === endIndex - 1 && endIndex < this.choices.length) {
  3337. prefix = figures.arrowDown;
  3338. } else {
  3339. prefix = ' ';
  3340. }
  3341. if (v.disabled) {
  3342. title = this.cursor === i ? color.gray().underline(v.title) : color.strikethrough().gray(v.title);
  3343. prefix = (this.cursor === i ? color.bold().gray(figures.pointer) + ' ' : ' ') + prefix;
  3344. } else {
  3345. title = this.cursor === i ? color.cyan().underline(v.title) : v.title;
  3346. prefix = (this.cursor === i ? color.cyan(figures.pointer) + ' ' : ' ') + prefix;
  3347. if (v.description && this.cursor === i) {
  3348. desc = ` - ${v.description}`;
  3349. if (prefix.length + title.length + desc.length >= this.out.columns
  3350. || v.description.split(/\r?\n/).length > 1) {
  3351. desc = '\n' + wrap(v.description, { margin: 3, width: this.out.columns });
  3352. }
  3353. }
  3354. }
  3355. this.outputText += `${prefix} ${title}${color.gray(desc)}\n`;
  3356. }
  3357. }
  3358. this.out.write(this.outputText);
  3359. }
  3360. }
  3361. select = SelectPrompt;
  3362. return select;
  3363. }
  3364. var toggle;
  3365. var hasRequiredToggle;
  3366. function requireToggle () {
  3367. if (hasRequiredToggle) return toggle;
  3368. hasRequiredToggle = 1;
  3369. const color = requireKleur();
  3370. const Prompt = requirePrompt();
  3371. const { style, clear } = requireUtil();
  3372. const { cursor, erase } = requireSrc();
  3373. /**
  3374. * TogglePrompt Base Element
  3375. * @param {Object} opts Options
  3376. * @param {String} opts.message Message
  3377. * @param {Boolean} [opts.initial=false] Default value
  3378. * @param {String} [opts.active='no'] Active label
  3379. * @param {String} [opts.inactive='off'] Inactive label
  3380. * @param {Stream} [opts.stdin] The Readable stream to listen to
  3381. * @param {Stream} [opts.stdout] The Writable stream to write readline data to
  3382. */
  3383. class TogglePrompt extends Prompt {
  3384. constructor(opts={}) {
  3385. super(opts);
  3386. this.msg = opts.message;
  3387. this.value = !!opts.initial;
  3388. this.active = opts.active || 'on';
  3389. this.inactive = opts.inactive || 'off';
  3390. this.initialValue = this.value;
  3391. this.render();
  3392. }
  3393. reset() {
  3394. this.value = this.initialValue;
  3395. this.fire();
  3396. this.render();
  3397. }
  3398. exit() {
  3399. this.abort();
  3400. }
  3401. abort() {
  3402. this.done = this.aborted = true;
  3403. this.fire();
  3404. this.render();
  3405. this.out.write('\n');
  3406. this.close();
  3407. }
  3408. submit() {
  3409. this.done = true;
  3410. this.aborted = false;
  3411. this.fire();
  3412. this.render();
  3413. this.out.write('\n');
  3414. this.close();
  3415. }
  3416. deactivate() {
  3417. if (this.value === false) return this.bell();
  3418. this.value = false;
  3419. this.render();
  3420. }
  3421. activate() {
  3422. if (this.value === true) return this.bell();
  3423. this.value = true;
  3424. this.render();
  3425. }
  3426. delete() {
  3427. this.deactivate();
  3428. }
  3429. left() {
  3430. this.deactivate();
  3431. }
  3432. right() {
  3433. this.activate();
  3434. }
  3435. down() {
  3436. this.deactivate();
  3437. }
  3438. up() {
  3439. this.activate();
  3440. }
  3441. next() {
  3442. this.value = !this.value;
  3443. this.fire();
  3444. this.render();
  3445. }
  3446. _(c, key) {
  3447. if (c === ' ') {
  3448. this.value = !this.value;
  3449. } else if (c === '1') {
  3450. this.value = true;
  3451. } else if (c === '0') {
  3452. this.value = false;
  3453. } else return this.bell();
  3454. this.render();
  3455. }
  3456. render() {
  3457. if (this.closed) return;
  3458. if (this.firstRender) this.out.write(cursor.hide);
  3459. else this.out.write(clear(this.outputText, this.out.columns));
  3460. super.render();
  3461. this.outputText = [
  3462. style.symbol(this.done, this.aborted),
  3463. color.bold(this.msg),
  3464. style.delimiter(this.done),
  3465. this.value ? this.inactive : color.cyan().underline(this.inactive),
  3466. color.gray('/'),
  3467. this.value ? color.cyan().underline(this.active) : this.active
  3468. ].join(' ');
  3469. this.out.write(erase.line + cursor.to(0) + this.outputText);
  3470. }
  3471. }
  3472. toggle = TogglePrompt;
  3473. return toggle;
  3474. }
  3475. var datepart;
  3476. var hasRequiredDatepart;
  3477. function requireDatepart () {
  3478. if (hasRequiredDatepart) return datepart;
  3479. hasRequiredDatepart = 1;
  3480. class DatePart {
  3481. constructor({token, date, parts, locales}) {
  3482. this.token = token;
  3483. this.date = date || new Date();
  3484. this.parts = parts || [this];
  3485. this.locales = locales || {};
  3486. }
  3487. up() {}
  3488. down() {}
  3489. next() {
  3490. const currentIdx = this.parts.indexOf(this);
  3491. return this.parts.find((part, idx) => idx > currentIdx && part instanceof DatePart);
  3492. }
  3493. setTo(val) {}
  3494. prev() {
  3495. let parts = [].concat(this.parts).reverse();
  3496. const currentIdx = parts.indexOf(this);
  3497. return parts.find((part, idx) => idx > currentIdx && part instanceof DatePart);
  3498. }
  3499. toString() {
  3500. return String(this.date);
  3501. }
  3502. }
  3503. datepart = DatePart;
  3504. return datepart;
  3505. }
  3506. var meridiem;
  3507. var hasRequiredMeridiem;
  3508. function requireMeridiem () {
  3509. if (hasRequiredMeridiem) return meridiem;
  3510. hasRequiredMeridiem = 1;
  3511. const DatePart = requireDatepart();
  3512. class Meridiem extends DatePart {
  3513. constructor(opts={}) {
  3514. super(opts);
  3515. }
  3516. up() {
  3517. this.date.setHours((this.date.getHours() + 12) % 24);
  3518. }
  3519. down() {
  3520. this.up();
  3521. }
  3522. toString() {
  3523. let meridiem = this.date.getHours() > 12 ? 'pm' : 'am';
  3524. return /\A/.test(this.token) ? meridiem.toUpperCase() : meridiem;
  3525. }
  3526. }
  3527. meridiem = Meridiem;
  3528. return meridiem;
  3529. }
  3530. var day;
  3531. var hasRequiredDay;
  3532. function requireDay () {
  3533. if (hasRequiredDay) return day;
  3534. hasRequiredDay = 1;
  3535. const DatePart = requireDatepart();
  3536. const pos = n => {
  3537. n = n % 10;
  3538. return n === 1 ? 'st'
  3539. : n === 2 ? 'nd'
  3540. : n === 3 ? 'rd'
  3541. : 'th';
  3542. };
  3543. class Day extends DatePart {
  3544. constructor(opts={}) {
  3545. super(opts);
  3546. }
  3547. up() {
  3548. this.date.setDate(this.date.getDate() + 1);
  3549. }
  3550. down() {
  3551. this.date.setDate(this.date.getDate() - 1);
  3552. }
  3553. setTo(val) {
  3554. this.date.setDate(parseInt(val.substr(-2)));
  3555. }
  3556. toString() {
  3557. let date = this.date.getDate();
  3558. let day = this.date.getDay();
  3559. return this.token === 'DD' ? String(date).padStart(2, '0')
  3560. : this.token === 'Do' ? date + pos(date)
  3561. : this.token === 'd' ? day + 1
  3562. : this.token === 'ddd' ? this.locales.weekdaysShort[day]
  3563. : this.token === 'dddd' ? this.locales.weekdays[day]
  3564. : date;
  3565. }
  3566. }
  3567. day = Day;
  3568. return day;
  3569. }
  3570. var hours;
  3571. var hasRequiredHours;
  3572. function requireHours () {
  3573. if (hasRequiredHours) return hours;
  3574. hasRequiredHours = 1;
  3575. const DatePart = requireDatepart();
  3576. class Hours extends DatePart {
  3577. constructor(opts={}) {
  3578. super(opts);
  3579. }
  3580. up() {
  3581. this.date.setHours(this.date.getHours() + 1);
  3582. }
  3583. down() {
  3584. this.date.setHours(this.date.getHours() - 1);
  3585. }
  3586. setTo(val) {
  3587. this.date.setHours(parseInt(val.substr(-2)));
  3588. }
  3589. toString() {
  3590. let hours = this.date.getHours();
  3591. if (/h/.test(this.token))
  3592. hours = (hours % 12) || 12;
  3593. return this.token.length > 1 ? String(hours).padStart(2, '0') : hours;
  3594. }
  3595. }
  3596. hours = Hours;
  3597. return hours;
  3598. }
  3599. var milliseconds;
  3600. var hasRequiredMilliseconds;
  3601. function requireMilliseconds () {
  3602. if (hasRequiredMilliseconds) return milliseconds;
  3603. hasRequiredMilliseconds = 1;
  3604. const DatePart = requireDatepart();
  3605. class Milliseconds extends DatePart {
  3606. constructor(opts={}) {
  3607. super(opts);
  3608. }
  3609. up() {
  3610. this.date.setMilliseconds(this.date.getMilliseconds() + 1);
  3611. }
  3612. down() {
  3613. this.date.setMilliseconds(this.date.getMilliseconds() - 1);
  3614. }
  3615. setTo(val) {
  3616. this.date.setMilliseconds(parseInt(val.substr(-(this.token.length))));
  3617. }
  3618. toString() {
  3619. return String(this.date.getMilliseconds()).padStart(4, '0')
  3620. .substr(0, this.token.length);
  3621. }
  3622. }
  3623. milliseconds = Milliseconds;
  3624. return milliseconds;
  3625. }
  3626. var minutes;
  3627. var hasRequiredMinutes;
  3628. function requireMinutes () {
  3629. if (hasRequiredMinutes) return minutes;
  3630. hasRequiredMinutes = 1;
  3631. const DatePart = requireDatepart();
  3632. class Minutes extends DatePart {
  3633. constructor(opts={}) {
  3634. super(opts);
  3635. }
  3636. up() {
  3637. this.date.setMinutes(this.date.getMinutes() + 1);
  3638. }
  3639. down() {
  3640. this.date.setMinutes(this.date.getMinutes() - 1);
  3641. }
  3642. setTo(val) {
  3643. this.date.setMinutes(parseInt(val.substr(-2)));
  3644. }
  3645. toString() {
  3646. let m = this.date.getMinutes();
  3647. return this.token.length > 1 ? String(m).padStart(2, '0') : m;
  3648. }
  3649. }
  3650. minutes = Minutes;
  3651. return minutes;
  3652. }
  3653. var month;
  3654. var hasRequiredMonth;
  3655. function requireMonth () {
  3656. if (hasRequiredMonth) return month;
  3657. hasRequiredMonth = 1;
  3658. const DatePart = requireDatepart();
  3659. class Month extends DatePart {
  3660. constructor(opts={}) {
  3661. super(opts);
  3662. }
  3663. up() {
  3664. this.date.setMonth(this.date.getMonth() + 1);
  3665. }
  3666. down() {
  3667. this.date.setMonth(this.date.getMonth() - 1);
  3668. }
  3669. setTo(val) {
  3670. val = parseInt(val.substr(-2)) - 1;
  3671. this.date.setMonth(val < 0 ? 0 : val);
  3672. }
  3673. toString() {
  3674. let month = this.date.getMonth();
  3675. let tl = this.token.length;
  3676. return tl === 2 ? String(month + 1).padStart(2, '0')
  3677. : tl === 3 ? this.locales.monthsShort[month]
  3678. : tl === 4 ? this.locales.months[month]
  3679. : String(month + 1);
  3680. }
  3681. }
  3682. month = Month;
  3683. return month;
  3684. }
  3685. var seconds;
  3686. var hasRequiredSeconds;
  3687. function requireSeconds () {
  3688. if (hasRequiredSeconds) return seconds;
  3689. hasRequiredSeconds = 1;
  3690. const DatePart = requireDatepart();
  3691. class Seconds extends DatePart {
  3692. constructor(opts={}) {
  3693. super(opts);
  3694. }
  3695. up() {
  3696. this.date.setSeconds(this.date.getSeconds() + 1);
  3697. }
  3698. down() {
  3699. this.date.setSeconds(this.date.getSeconds() - 1);
  3700. }
  3701. setTo(val) {
  3702. this.date.setSeconds(parseInt(val.substr(-2)));
  3703. }
  3704. toString() {
  3705. let s = this.date.getSeconds();
  3706. return this.token.length > 1 ? String(s).padStart(2, '0') : s;
  3707. }
  3708. }
  3709. seconds = Seconds;
  3710. return seconds;
  3711. }
  3712. var year;
  3713. var hasRequiredYear;
  3714. function requireYear () {
  3715. if (hasRequiredYear) return year;
  3716. hasRequiredYear = 1;
  3717. const DatePart = requireDatepart();
  3718. class Year extends DatePart {
  3719. constructor(opts={}) {
  3720. super(opts);
  3721. }
  3722. up() {
  3723. this.date.setFullYear(this.date.getFullYear() + 1);
  3724. }
  3725. down() {
  3726. this.date.setFullYear(this.date.getFullYear() - 1);
  3727. }
  3728. setTo(val) {
  3729. this.date.setFullYear(val.substr(-4));
  3730. }
  3731. toString() {
  3732. let year = String(this.date.getFullYear()).padStart(4, '0');
  3733. return this.token.length === 2 ? year.substr(-2) : year;
  3734. }
  3735. }
  3736. year = Year;
  3737. return year;
  3738. }
  3739. var dateparts;
  3740. var hasRequiredDateparts;
  3741. function requireDateparts () {
  3742. if (hasRequiredDateparts) return dateparts;
  3743. hasRequiredDateparts = 1;
  3744. dateparts = {
  3745. DatePart: requireDatepart(),
  3746. Meridiem: requireMeridiem(),
  3747. Day: requireDay(),
  3748. Hours: requireHours(),
  3749. Milliseconds: requireMilliseconds(),
  3750. Minutes: requireMinutes(),
  3751. Month: requireMonth(),
  3752. Seconds: requireSeconds(),
  3753. Year: requireYear(),
  3754. };
  3755. return dateparts;
  3756. }
  3757. var date;
  3758. var hasRequiredDate;
  3759. function requireDate () {
  3760. if (hasRequiredDate) return date;
  3761. hasRequiredDate = 1;
  3762. const color = requireKleur();
  3763. const Prompt = requirePrompt();
  3764. const { style, clear, figures } = requireUtil();
  3765. const { erase, cursor } = requireSrc();
  3766. const { DatePart, Meridiem, Day, Hours, Milliseconds, Minutes, Month, Seconds, Year } = requireDateparts();
  3767. const regex = /\\(.)|"((?:\\["\\]|[^"])+)"|(D[Do]?|d{3,4}|d)|(M{1,4})|(YY(?:YY)?)|([aA])|([Hh]{1,2})|(m{1,2})|(s{1,2})|(S{1,4})|./g;
  3768. const regexGroups = {
  3769. 1: ({token}) => token.replace(/\\(.)/g, '$1'),
  3770. 2: (opts) => new Day(opts), // Day // TODO
  3771. 3: (opts) => new Month(opts), // Month
  3772. 4: (opts) => new Year(opts), // Year
  3773. 5: (opts) => new Meridiem(opts), // AM/PM // TODO (special)
  3774. 6: (opts) => new Hours(opts), // Hours
  3775. 7: (opts) => new Minutes(opts), // Minutes
  3776. 8: (opts) => new Seconds(opts), // Seconds
  3777. 9: (opts) => new Milliseconds(opts), // Fractional seconds
  3778. };
  3779. const dfltLocales = {
  3780. months: 'January,February,March,April,May,June,July,August,September,October,November,December'.split(','),
  3781. monthsShort: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','),
  3782. weekdays: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','),
  3783. weekdaysShort: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(',')
  3784. };
  3785. /**
  3786. * DatePrompt Base Element
  3787. * @param {Object} opts Options
  3788. * @param {String} opts.message Message
  3789. * @param {Number} [opts.initial] Index of default value
  3790. * @param {String} [opts.mask] The format mask
  3791. * @param {object} [opts.locales] The date locales
  3792. * @param {String} [opts.error] The error message shown on invalid value
  3793. * @param {Function} [opts.validate] Function to validate the submitted value
  3794. * @param {Stream} [opts.stdin] The Readable stream to listen to
  3795. * @param {Stream} [opts.stdout] The Writable stream to write readline data to
  3796. */
  3797. class DatePrompt extends Prompt {
  3798. constructor(opts={}) {
  3799. super(opts);
  3800. this.msg = opts.message;
  3801. this.cursor = 0;
  3802. this.typed = '';
  3803. this.locales = Object.assign(dfltLocales, opts.locales);
  3804. this._date = opts.initial || new Date();
  3805. this.errorMsg = opts.error || 'Please Enter A Valid Value';
  3806. this.validator = opts.validate || (() => true);
  3807. this.mask = opts.mask || 'YYYY-MM-DD HH:mm:ss';
  3808. this.clear = clear('', this.out.columns);
  3809. this.render();
  3810. }
  3811. get value() {
  3812. return this.date
  3813. }
  3814. get date() {
  3815. return this._date;
  3816. }
  3817. set date(date) {
  3818. if (date) this._date.setTime(date.getTime());
  3819. }
  3820. set mask(mask) {
  3821. let result;
  3822. this.parts = [];
  3823. while(result = regex.exec(mask)) {
  3824. let match = result.shift();
  3825. let idx = result.findIndex(gr => gr != null);
  3826. this.parts.push(idx in regexGroups
  3827. ? regexGroups[idx]({ token: result[idx] || match, date: this.date, parts: this.parts, locales: this.locales })
  3828. : result[idx] || match);
  3829. }
  3830. let parts = this.parts.reduce((arr, i) => {
  3831. if (typeof i === 'string' && typeof arr[arr.length - 1] === 'string')
  3832. arr[arr.length - 1] += i;
  3833. else arr.push(i);
  3834. return arr;
  3835. }, []);
  3836. this.parts.splice(0);
  3837. this.parts.push(...parts);
  3838. this.reset();
  3839. }
  3840. moveCursor(n) {
  3841. this.typed = '';
  3842. this.cursor = n;
  3843. this.fire();
  3844. }
  3845. reset() {
  3846. this.moveCursor(this.parts.findIndex(p => p instanceof DatePart));
  3847. this.fire();
  3848. this.render();
  3849. }
  3850. exit() {
  3851. this.abort();
  3852. }
  3853. abort() {
  3854. this.done = this.aborted = true;
  3855. this.error = false;
  3856. this.fire();
  3857. this.render();
  3858. this.out.write('\n');
  3859. this.close();
  3860. }
  3861. async validate() {
  3862. let valid = await this.validator(this.value);
  3863. if (typeof valid === 'string') {
  3864. this.errorMsg = valid;
  3865. valid = false;
  3866. }
  3867. this.error = !valid;
  3868. }
  3869. async submit() {
  3870. await this.validate();
  3871. if (this.error) {
  3872. this.color = 'red';
  3873. this.fire();
  3874. this.render();
  3875. return;
  3876. }
  3877. this.done = true;
  3878. this.aborted = false;
  3879. this.fire();
  3880. this.render();
  3881. this.out.write('\n');
  3882. this.close();
  3883. }
  3884. up() {
  3885. this.typed = '';
  3886. this.parts[this.cursor].up();
  3887. this.render();
  3888. }
  3889. down() {
  3890. this.typed = '';
  3891. this.parts[this.cursor].down();
  3892. this.render();
  3893. }
  3894. left() {
  3895. let prev = this.parts[this.cursor].prev();
  3896. if (prev == null) return this.bell();
  3897. this.moveCursor(this.parts.indexOf(prev));
  3898. this.render();
  3899. }
  3900. right() {
  3901. let next = this.parts[this.cursor].next();
  3902. if (next == null) return this.bell();
  3903. this.moveCursor(this.parts.indexOf(next));
  3904. this.render();
  3905. }
  3906. next() {
  3907. let next = this.parts[this.cursor].next();
  3908. this.moveCursor(next
  3909. ? this.parts.indexOf(next)
  3910. : this.parts.findIndex((part) => part instanceof DatePart));
  3911. this.render();
  3912. }
  3913. _(c) {
  3914. if (/\d/.test(c)) {
  3915. this.typed += c;
  3916. this.parts[this.cursor].setTo(this.typed);
  3917. this.render();
  3918. }
  3919. }
  3920. render() {
  3921. if (this.closed) return;
  3922. if (this.firstRender) this.out.write(cursor.hide);
  3923. else this.out.write(clear(this.outputText, this.out.columns));
  3924. super.render();
  3925. // Print prompt
  3926. this.outputText = [
  3927. style.symbol(this.done, this.aborted),
  3928. color.bold(this.msg),
  3929. style.delimiter(false),
  3930. this.parts.reduce((arr, p, idx) => arr.concat(idx === this.cursor && !this.done ? color.cyan().underline(p.toString()) : p), [])
  3931. .join('')
  3932. ].join(' ');
  3933. // Print error
  3934. if (this.error) {
  3935. this.outputText += this.errorMsg.split('\n').reduce(
  3936. (a, l, i) => a + `\n${i ? ` ` : figures.pointerSmall} ${color.red().italic(l)}`, ``);
  3937. }
  3938. this.out.write(erase.line + cursor.to(0) + this.outputText);
  3939. }
  3940. }
  3941. date = DatePrompt;
  3942. return date;
  3943. }
  3944. var number;
  3945. var hasRequiredNumber;
  3946. function requireNumber () {
  3947. if (hasRequiredNumber) return number;
  3948. hasRequiredNumber = 1;
  3949. const color = requireKleur();
  3950. const Prompt = requirePrompt();
  3951. const { cursor, erase } = requireSrc();
  3952. const { style, figures, clear, lines } = requireUtil();
  3953. const isNumber = /[0-9]/;
  3954. const isDef = any => any !== undefined;
  3955. const round = (number, precision) => {
  3956. let factor = Math.pow(10, precision);
  3957. return Math.round(number * factor) / factor;
  3958. };
  3959. /**
  3960. * NumberPrompt Base Element
  3961. * @param {Object} opts Options
  3962. * @param {String} opts.message Message
  3963. * @param {String} [opts.style='default'] Render style
  3964. * @param {Number} [opts.initial] Default value
  3965. * @param {Number} [opts.max=+Infinity] Max value
  3966. * @param {Number} [opts.min=-Infinity] Min value
  3967. * @param {Boolean} [opts.float=false] Parse input as floats
  3968. * @param {Number} [opts.round=2] Round floats to x decimals
  3969. * @param {Number} [opts.increment=1] Number to increment by when using arrow-keys
  3970. * @param {Function} [opts.validate] Validate function
  3971. * @param {Stream} [opts.stdin] The Readable stream to listen to
  3972. * @param {Stream} [opts.stdout] The Writable stream to write readline data to
  3973. * @param {String} [opts.error] The invalid error label
  3974. */
  3975. class NumberPrompt extends Prompt {
  3976. constructor(opts={}) {
  3977. super(opts);
  3978. this.transform = style.render(opts.style);
  3979. this.msg = opts.message;
  3980. this.initial = isDef(opts.initial) ? opts.initial : '';
  3981. this.float = !!opts.float;
  3982. this.round = opts.round || 2;
  3983. this.inc = opts.increment || 1;
  3984. this.min = isDef(opts.min) ? opts.min : -Infinity;
  3985. this.max = isDef(opts.max) ? opts.max : Infinity;
  3986. this.errorMsg = opts.error || `Please Enter A Valid Value`;
  3987. this.validator = opts.validate || (() => true);
  3988. this.color = `cyan`;
  3989. this.value = ``;
  3990. this.typed = ``;
  3991. this.lastHit = 0;
  3992. this.render();
  3993. }
  3994. set value(v) {
  3995. if (!v && v !== 0) {
  3996. this.placeholder = true;
  3997. this.rendered = color.gray(this.transform.render(`${this.initial}`));
  3998. this._value = ``;
  3999. } else {
  4000. this.placeholder = false;
  4001. this.rendered = this.transform.render(`${round(v, this.round)}`);
  4002. this._value = round(v, this.round);
  4003. }
  4004. this.fire();
  4005. }
  4006. get value() {
  4007. return this._value;
  4008. }
  4009. parse(x) {
  4010. return this.float ? parseFloat(x) : parseInt(x);
  4011. }
  4012. valid(c) {
  4013. return c === `-` || c === `.` && this.float || isNumber.test(c)
  4014. }
  4015. reset() {
  4016. this.typed = ``;
  4017. this.value = ``;
  4018. this.fire();
  4019. this.render();
  4020. }
  4021. exit() {
  4022. this.abort();
  4023. }
  4024. abort() {
  4025. let x = this.value;
  4026. this.value = x !== `` ? x : this.initial;
  4027. this.done = this.aborted = true;
  4028. this.error = false;
  4029. this.fire();
  4030. this.render();
  4031. this.out.write(`\n`);
  4032. this.close();
  4033. }
  4034. async validate() {
  4035. let valid = await this.validator(this.value);
  4036. if (typeof valid === `string`) {
  4037. this.errorMsg = valid;
  4038. valid = false;
  4039. }
  4040. this.error = !valid;
  4041. }
  4042. async submit() {
  4043. await this.validate();
  4044. if (this.error) {
  4045. this.color = `red`;
  4046. this.fire();
  4047. this.render();
  4048. return;
  4049. }
  4050. let x = this.value;
  4051. this.value = x !== `` ? x : this.initial;
  4052. this.done = true;
  4053. this.aborted = false;
  4054. this.error = false;
  4055. this.fire();
  4056. this.render();
  4057. this.out.write(`\n`);
  4058. this.close();
  4059. }
  4060. up() {
  4061. this.typed = ``;
  4062. if(this.value === '') {
  4063. this.value = this.min - this.inc;
  4064. }
  4065. if (this.value >= this.max) return this.bell();
  4066. this.value += this.inc;
  4067. this.color = `cyan`;
  4068. this.fire();
  4069. this.render();
  4070. }
  4071. down() {
  4072. this.typed = ``;
  4073. if(this.value === '') {
  4074. this.value = this.min + this.inc;
  4075. }
  4076. if (this.value <= this.min) return this.bell();
  4077. this.value -= this.inc;
  4078. this.color = `cyan`;
  4079. this.fire();
  4080. this.render();
  4081. }
  4082. delete() {
  4083. let val = this.value.toString();
  4084. if (val.length === 0) return this.bell();
  4085. this.value = this.parse((val = val.slice(0, -1))) || ``;
  4086. if (this.value !== '' && this.value < this.min) {
  4087. this.value = this.min;
  4088. }
  4089. this.color = `cyan`;
  4090. this.fire();
  4091. this.render();
  4092. }
  4093. next() {
  4094. this.value = this.initial;
  4095. this.fire();
  4096. this.render();
  4097. }
  4098. _(c, key) {
  4099. if (!this.valid(c)) return this.bell();
  4100. const now = Date.now();
  4101. if (now - this.lastHit > 1000) this.typed = ``; // 1s elapsed
  4102. this.typed += c;
  4103. this.lastHit = now;
  4104. this.color = `cyan`;
  4105. if (c === `.`) return this.fire();
  4106. this.value = Math.min(this.parse(this.typed), this.max);
  4107. if (this.value > this.max) this.value = this.max;
  4108. if (this.value < this.min) this.value = this.min;
  4109. this.fire();
  4110. this.render();
  4111. }
  4112. render() {
  4113. if (this.closed) return;
  4114. if (!this.firstRender) {
  4115. if (this.outputError)
  4116. this.out.write(cursor.down(lines(this.outputError, this.out.columns) - 1) + clear(this.outputError, this.out.columns));
  4117. this.out.write(clear(this.outputText, this.out.columns));
  4118. }
  4119. super.render();
  4120. this.outputError = '';
  4121. // Print prompt
  4122. this.outputText = [
  4123. style.symbol(this.done, this.aborted),
  4124. color.bold(this.msg),
  4125. style.delimiter(this.done),
  4126. !this.done || (!this.done && !this.placeholder)
  4127. ? color[this.color]().underline(this.rendered) : this.rendered
  4128. ].join(` `);
  4129. // Print error
  4130. if (this.error) {
  4131. this.outputError += this.errorMsg.split(`\n`)
  4132. .reduce((a, l, i) => a + `\n${i ? ` ` : figures.pointerSmall} ${color.red().italic(l)}`, ``);
  4133. }
  4134. this.out.write(erase.line + cursor.to(0) + this.outputText + cursor.save + this.outputError + cursor.restore);
  4135. }
  4136. }
  4137. number = NumberPrompt;
  4138. return number;
  4139. }
  4140. var multiselect;
  4141. var hasRequiredMultiselect;
  4142. function requireMultiselect () {
  4143. if (hasRequiredMultiselect) return multiselect;
  4144. hasRequiredMultiselect = 1;
  4145. const color = requireKleur();
  4146. const { cursor } = requireSrc();
  4147. const Prompt = requirePrompt();
  4148. const { clear, figures, style, wrap, entriesToDisplay } = requireUtil();
  4149. /**
  4150. * MultiselectPrompt Base Element
  4151. * @param {Object} opts Options
  4152. * @param {String} opts.message Message
  4153. * @param {Array} opts.choices Array of choice objects
  4154. * @param {String} [opts.hint] Hint to display
  4155. * @param {String} [opts.warn] Hint shown for disabled choices
  4156. * @param {Number} [opts.max] Max choices
  4157. * @param {Number} [opts.cursor=0] Cursor start position
  4158. * @param {Number} [opts.optionsPerPage=10] Max options to display at once
  4159. * @param {Stream} [opts.stdin] The Readable stream to listen to
  4160. * @param {Stream} [opts.stdout] The Writable stream to write readline data to
  4161. */
  4162. class MultiselectPrompt extends Prompt {
  4163. constructor(opts={}) {
  4164. super(opts);
  4165. this.msg = opts.message;
  4166. this.cursor = opts.cursor || 0;
  4167. this.scrollIndex = opts.cursor || 0;
  4168. this.hint = opts.hint || '';
  4169. this.warn = opts.warn || '- This option is disabled -';
  4170. this.minSelected = opts.min;
  4171. this.showMinError = false;
  4172. this.maxChoices = opts.max;
  4173. this.instructions = opts.instructions;
  4174. this.optionsPerPage = opts.optionsPerPage || 10;
  4175. this.value = opts.choices.map((ch, idx) => {
  4176. if (typeof ch === 'string')
  4177. ch = {title: ch, value: idx};
  4178. return {
  4179. title: ch && (ch.title || ch.value || ch),
  4180. description: ch && ch.description,
  4181. value: ch && (ch.value === undefined ? idx : ch.value),
  4182. selected: ch && ch.selected,
  4183. disabled: ch && ch.disabled
  4184. };
  4185. });
  4186. this.clear = clear('', this.out.columns);
  4187. if (!opts.overrideRender) {
  4188. this.render();
  4189. }
  4190. }
  4191. reset() {
  4192. this.value.map(v => !v.selected);
  4193. this.cursor = 0;
  4194. this.fire();
  4195. this.render();
  4196. }
  4197. selected() {
  4198. return this.value.filter(v => v.selected);
  4199. }
  4200. exit() {
  4201. this.abort();
  4202. }
  4203. abort() {
  4204. this.done = this.aborted = true;
  4205. this.fire();
  4206. this.render();
  4207. this.out.write('\n');
  4208. this.close();
  4209. }
  4210. submit() {
  4211. const selected = this.value
  4212. .filter(e => e.selected);
  4213. if (this.minSelected && selected.length < this.minSelected) {
  4214. this.showMinError = true;
  4215. this.render();
  4216. } else {
  4217. this.done = true;
  4218. this.aborted = false;
  4219. this.fire();
  4220. this.render();
  4221. this.out.write('\n');
  4222. this.close();
  4223. }
  4224. }
  4225. first() {
  4226. this.cursor = 0;
  4227. this.render();
  4228. }
  4229. last() {
  4230. this.cursor = this.value.length - 1;
  4231. this.render();
  4232. }
  4233. next() {
  4234. this.cursor = (this.cursor + 1) % this.value.length;
  4235. this.render();
  4236. }
  4237. up() {
  4238. if (this.cursor === 0) {
  4239. this.cursor = this.value.length - 1;
  4240. } else {
  4241. this.cursor--;
  4242. }
  4243. this.render();
  4244. }
  4245. down() {
  4246. if (this.cursor === this.value.length - 1) {
  4247. this.cursor = 0;
  4248. } else {
  4249. this.cursor++;
  4250. }
  4251. this.render();
  4252. }
  4253. left() {
  4254. this.value[this.cursor].selected = false;
  4255. this.render();
  4256. }
  4257. right() {
  4258. if (this.value.filter(e => e.selected).length >= this.maxChoices) return this.bell();
  4259. this.value[this.cursor].selected = true;
  4260. this.render();
  4261. }
  4262. handleSpaceToggle() {
  4263. const v = this.value[this.cursor];
  4264. if (v.selected) {
  4265. v.selected = false;
  4266. this.render();
  4267. } else if (v.disabled || this.value.filter(e => e.selected).length >= this.maxChoices) {
  4268. return this.bell();
  4269. } else {
  4270. v.selected = true;
  4271. this.render();
  4272. }
  4273. }
  4274. toggleAll() {
  4275. if (this.maxChoices !== undefined || this.value[this.cursor].disabled) {
  4276. return this.bell();
  4277. }
  4278. const newSelected = !this.value[this.cursor].selected;
  4279. this.value.filter(v => !v.disabled).forEach(v => v.selected = newSelected);
  4280. this.render();
  4281. }
  4282. _(c, key) {
  4283. if (c === ' ') {
  4284. this.handleSpaceToggle();
  4285. } else if (c === 'a') {
  4286. this.toggleAll();
  4287. } else {
  4288. return this.bell();
  4289. }
  4290. }
  4291. renderInstructions() {
  4292. if (this.instructions === undefined || this.instructions) {
  4293. if (typeof this.instructions === 'string') {
  4294. return this.instructions;
  4295. }
  4296. return '\nInstructions:\n'
  4297. + ` ${figures.arrowUp}/${figures.arrowDown}: Highlight option\n`
  4298. + ` ${figures.arrowLeft}/${figures.arrowRight}/[space]: Toggle selection\n`
  4299. + (this.maxChoices === undefined ? ` a: Toggle all\n` : '')
  4300. + ` enter/return: Complete answer`;
  4301. }
  4302. return '';
  4303. }
  4304. renderOption(cursor, v, i, arrowIndicator) {
  4305. const prefix = (v.selected ? color.green(figures.radioOn) : figures.radioOff) + ' ' + arrowIndicator + ' ';
  4306. let title, desc;
  4307. if (v.disabled) {
  4308. title = cursor === i ? color.gray().underline(v.title) : color.strikethrough().gray(v.title);
  4309. } else {
  4310. title = cursor === i ? color.cyan().underline(v.title) : v.title;
  4311. if (cursor === i && v.description) {
  4312. desc = ` - ${v.description}`;
  4313. if (prefix.length + title.length + desc.length >= this.out.columns
  4314. || v.description.split(/\r?\n/).length > 1) {
  4315. desc = '\n' + wrap(v.description, { margin: prefix.length, width: this.out.columns });
  4316. }
  4317. }
  4318. }
  4319. return prefix + title + color.gray(desc || '');
  4320. }
  4321. // shared with autocompleteMultiselect
  4322. paginateOptions(options) {
  4323. if (options.length === 0) {
  4324. return color.red('No matches for this query.');
  4325. }
  4326. let { startIndex, endIndex } = entriesToDisplay(this.cursor, options.length, this.optionsPerPage);
  4327. let prefix, styledOptions = [];
  4328. for (let i = startIndex; i < endIndex; i++) {
  4329. if (i === startIndex && startIndex > 0) {
  4330. prefix = figures.arrowUp;
  4331. } else if (i === endIndex - 1 && endIndex < options.length) {
  4332. prefix = figures.arrowDown;
  4333. } else {
  4334. prefix = ' ';
  4335. }
  4336. styledOptions.push(this.renderOption(this.cursor, options[i], i, prefix));
  4337. }
  4338. return '\n' + styledOptions.join('\n');
  4339. }
  4340. // shared with autocomleteMultiselect
  4341. renderOptions(options) {
  4342. if (!this.done) {
  4343. return this.paginateOptions(options);
  4344. }
  4345. return '';
  4346. }
  4347. renderDoneOrInstructions() {
  4348. if (this.done) {
  4349. return this.value
  4350. .filter(e => e.selected)
  4351. .map(v => v.title)
  4352. .join(', ');
  4353. }
  4354. const output = [color.gray(this.hint), this.renderInstructions()];
  4355. if (this.value[this.cursor].disabled) {
  4356. output.push(color.yellow(this.warn));
  4357. }
  4358. return output.join(' ');
  4359. }
  4360. render() {
  4361. if (this.closed) return;
  4362. if (this.firstRender) this.out.write(cursor.hide);
  4363. super.render();
  4364. // print prompt
  4365. let prompt = [
  4366. style.symbol(this.done, this.aborted),
  4367. color.bold(this.msg),
  4368. style.delimiter(false),
  4369. this.renderDoneOrInstructions()
  4370. ].join(' ');
  4371. if (this.showMinError) {
  4372. prompt += color.red(`You must select a minimum of ${this.minSelected} choices.`);
  4373. this.showMinError = false;
  4374. }
  4375. prompt += this.renderOptions(this.value);
  4376. this.out.write(this.clear + prompt);
  4377. this.clear = clear(prompt, this.out.columns);
  4378. }
  4379. }
  4380. multiselect = MultiselectPrompt;
  4381. return multiselect;
  4382. }
  4383. var autocomplete;
  4384. var hasRequiredAutocomplete;
  4385. function requireAutocomplete () {
  4386. if (hasRequiredAutocomplete) return autocomplete;
  4387. hasRequiredAutocomplete = 1;
  4388. const color = requireKleur();
  4389. const Prompt = requirePrompt();
  4390. const { erase, cursor } = requireSrc();
  4391. const { style, clear, figures, wrap, entriesToDisplay } = requireUtil();
  4392. const getVal = (arr, i) => arr[i] && (arr[i].value || arr[i].title || arr[i]);
  4393. const getTitle = (arr, i) => arr[i] && (arr[i].title || arr[i].value || arr[i]);
  4394. const getIndex = (arr, valOrTitle) => {
  4395. const index = arr.findIndex(el => el.value === valOrTitle || el.title === valOrTitle);
  4396. return index > -1 ? index : undefined;
  4397. };
  4398. /**
  4399. * TextPrompt Base Element
  4400. * @param {Object} opts Options
  4401. * @param {String} opts.message Message
  4402. * @param {Array} opts.choices Array of auto-complete choices objects
  4403. * @param {Function} [opts.suggest] Filter function. Defaults to sort by title
  4404. * @param {Number} [opts.limit=10] Max number of results to show
  4405. * @param {Number} [opts.cursor=0] Cursor start position
  4406. * @param {String} [opts.style='default'] Render style
  4407. * @param {String} [opts.fallback] Fallback message - initial to default value
  4408. * @param {String} [opts.initial] Index of the default value
  4409. * @param {Boolean} [opts.clearFirst] The first ESCAPE keypress will clear the input
  4410. * @param {Stream} [opts.stdin] The Readable stream to listen to
  4411. * @param {Stream} [opts.stdout] The Writable stream to write readline data to
  4412. * @param {String} [opts.noMatches] The no matches found label
  4413. */
  4414. class AutocompletePrompt extends Prompt {
  4415. constructor(opts={}) {
  4416. super(opts);
  4417. this.msg = opts.message;
  4418. this.suggest = opts.suggest;
  4419. this.choices = opts.choices;
  4420. this.initial = typeof opts.initial === 'number'
  4421. ? opts.initial
  4422. : getIndex(opts.choices, opts.initial);
  4423. this.select = this.initial || opts.cursor || 0;
  4424. this.i18n = { noMatches: opts.noMatches || 'no matches found' };
  4425. this.fallback = opts.fallback || this.initial;
  4426. this.clearFirst = opts.clearFirst || false;
  4427. this.suggestions = [];
  4428. this.input = '';
  4429. this.limit = opts.limit || 10;
  4430. this.cursor = 0;
  4431. this.transform = style.render(opts.style);
  4432. this.scale = this.transform.scale;
  4433. this.render = this.render.bind(this);
  4434. this.complete = this.complete.bind(this);
  4435. this.clear = clear('', this.out.columns);
  4436. this.complete(this.render);
  4437. this.render();
  4438. }
  4439. set fallback(fb) {
  4440. this._fb = Number.isSafeInteger(parseInt(fb)) ? parseInt(fb) : fb;
  4441. }
  4442. get fallback() {
  4443. let choice;
  4444. if (typeof this._fb === 'number')
  4445. choice = this.choices[this._fb];
  4446. else if (typeof this._fb === 'string')
  4447. choice = { title: this._fb };
  4448. return choice || this._fb || { title: this.i18n.noMatches };
  4449. }
  4450. moveSelect(i) {
  4451. this.select = i;
  4452. if (this.suggestions.length > 0)
  4453. this.value = getVal(this.suggestions, i);
  4454. else this.value = this.fallback.value;
  4455. this.fire();
  4456. }
  4457. async complete(cb) {
  4458. const p = (this.completing = this.suggest(this.input, this.choices));
  4459. const suggestions = await p;
  4460. if (this.completing !== p) return;
  4461. this.suggestions = suggestions
  4462. .map((s, i, arr) => ({ title: getTitle(arr, i), value: getVal(arr, i), description: s.description }));
  4463. this.completing = false;
  4464. const l = Math.max(suggestions.length - 1, 0);
  4465. this.moveSelect(Math.min(l, this.select));
  4466. cb && cb();
  4467. }
  4468. reset() {
  4469. this.input = '';
  4470. this.complete(() => {
  4471. this.moveSelect(this.initial !== void 0 ? this.initial : 0);
  4472. this.render();
  4473. });
  4474. this.render();
  4475. }
  4476. exit() {
  4477. if (this.clearFirst && this.input.length > 0) {
  4478. this.reset();
  4479. } else {
  4480. this.done = this.exited = true;
  4481. this.aborted = false;
  4482. this.fire();
  4483. this.render();
  4484. this.out.write('\n');
  4485. this.close();
  4486. }
  4487. }
  4488. abort() {
  4489. this.done = this.aborted = true;
  4490. this.exited = false;
  4491. this.fire();
  4492. this.render();
  4493. this.out.write('\n');
  4494. this.close();
  4495. }
  4496. submit() {
  4497. this.done = true;
  4498. this.aborted = this.exited = false;
  4499. this.fire();
  4500. this.render();
  4501. this.out.write('\n');
  4502. this.close();
  4503. }
  4504. _(c, key) {
  4505. let s1 = this.input.slice(0, this.cursor);
  4506. let s2 = this.input.slice(this.cursor);
  4507. this.input = `${s1}${c}${s2}`;
  4508. this.cursor = s1.length+1;
  4509. this.complete(this.render);
  4510. this.render();
  4511. }
  4512. delete() {
  4513. if (this.cursor === 0) return this.bell();
  4514. let s1 = this.input.slice(0, this.cursor-1);
  4515. let s2 = this.input.slice(this.cursor);
  4516. this.input = `${s1}${s2}`;
  4517. this.complete(this.render);
  4518. this.cursor = this.cursor-1;
  4519. this.render();
  4520. }
  4521. deleteForward() {
  4522. if(this.cursor*this.scale >= this.rendered.length) return this.bell();
  4523. let s1 = this.input.slice(0, this.cursor);
  4524. let s2 = this.input.slice(this.cursor+1);
  4525. this.input = `${s1}${s2}`;
  4526. this.complete(this.render);
  4527. this.render();
  4528. }
  4529. first() {
  4530. this.moveSelect(0);
  4531. this.render();
  4532. }
  4533. last() {
  4534. this.moveSelect(this.suggestions.length - 1);
  4535. this.render();
  4536. }
  4537. up() {
  4538. if (this.select === 0) {
  4539. this.moveSelect(this.suggestions.length - 1);
  4540. } else {
  4541. this.moveSelect(this.select - 1);
  4542. }
  4543. this.render();
  4544. }
  4545. down() {
  4546. if (this.select === this.suggestions.length - 1) {
  4547. this.moveSelect(0);
  4548. } else {
  4549. this.moveSelect(this.select + 1);
  4550. }
  4551. this.render();
  4552. }
  4553. next() {
  4554. if (this.select === this.suggestions.length - 1) {
  4555. this.moveSelect(0);
  4556. } else this.moveSelect(this.select + 1);
  4557. this.render();
  4558. }
  4559. nextPage() {
  4560. this.moveSelect(Math.min(this.select + this.limit, this.suggestions.length - 1));
  4561. this.render();
  4562. }
  4563. prevPage() {
  4564. this.moveSelect(Math.max(this.select - this.limit, 0));
  4565. this.render();
  4566. }
  4567. left() {
  4568. if (this.cursor <= 0) return this.bell();
  4569. this.cursor = this.cursor-1;
  4570. this.render();
  4571. }
  4572. right() {
  4573. if (this.cursor*this.scale >= this.rendered.length) return this.bell();
  4574. this.cursor = this.cursor+1;
  4575. this.render();
  4576. }
  4577. renderOption(v, hovered, isStart, isEnd) {
  4578. let desc;
  4579. let prefix = isStart ? figures.arrowUp : isEnd ? figures.arrowDown : ' ';
  4580. let title = hovered ? color.cyan().underline(v.title) : v.title;
  4581. prefix = (hovered ? color.cyan(figures.pointer) + ' ' : ' ') + prefix;
  4582. if (v.description) {
  4583. desc = ` - ${v.description}`;
  4584. if (prefix.length + title.length + desc.length >= this.out.columns
  4585. || v.description.split(/\r?\n/).length > 1) {
  4586. desc = '\n' + wrap(v.description, { margin: 3, width: this.out.columns });
  4587. }
  4588. }
  4589. return prefix + ' ' + title + color.gray(desc || '');
  4590. }
  4591. render() {
  4592. if (this.closed) return;
  4593. if (this.firstRender) this.out.write(cursor.hide);
  4594. else this.out.write(clear(this.outputText, this.out.columns));
  4595. super.render();
  4596. let { startIndex, endIndex } = entriesToDisplay(this.select, this.choices.length, this.limit);
  4597. this.outputText = [
  4598. style.symbol(this.done, this.aborted, this.exited),
  4599. color.bold(this.msg),
  4600. style.delimiter(this.completing),
  4601. this.done && this.suggestions[this.select]
  4602. ? this.suggestions[this.select].title
  4603. : this.rendered = this.transform.render(this.input)
  4604. ].join(' ');
  4605. if (!this.done) {
  4606. const suggestions = this.suggestions
  4607. .slice(startIndex, endIndex)
  4608. .map((item, i) => this.renderOption(item,
  4609. this.select === i + startIndex,
  4610. i === 0 && startIndex > 0,
  4611. i + startIndex === endIndex - 1 && endIndex < this.choices.length))
  4612. .join('\n');
  4613. this.outputText += `\n` + (suggestions || color.gray(this.fallback.title));
  4614. }
  4615. this.out.write(erase.line + cursor.to(0) + this.outputText);
  4616. }
  4617. }
  4618. autocomplete = AutocompletePrompt;
  4619. return autocomplete;
  4620. }
  4621. var autocompleteMultiselect;
  4622. var hasRequiredAutocompleteMultiselect;
  4623. function requireAutocompleteMultiselect () {
  4624. if (hasRequiredAutocompleteMultiselect) return autocompleteMultiselect;
  4625. hasRequiredAutocompleteMultiselect = 1;
  4626. const color = requireKleur();
  4627. const { cursor } = requireSrc();
  4628. const MultiselectPrompt = requireMultiselect();
  4629. const { clear, style, figures } = requireUtil();
  4630. /**
  4631. * MultiselectPrompt Base Element
  4632. * @param {Object} opts Options
  4633. * @param {String} opts.message Message
  4634. * @param {Array} opts.choices Array of choice objects
  4635. * @param {String} [opts.hint] Hint to display
  4636. * @param {String} [opts.warn] Hint shown for disabled choices
  4637. * @param {Number} [opts.max] Max choices
  4638. * @param {Number} [opts.cursor=0] Cursor start position
  4639. * @param {Stream} [opts.stdin] The Readable stream to listen to
  4640. * @param {Stream} [opts.stdout] The Writable stream to write readline data to
  4641. */
  4642. class AutocompleteMultiselectPrompt extends MultiselectPrompt {
  4643. constructor(opts={}) {
  4644. opts.overrideRender = true;
  4645. super(opts);
  4646. this.inputValue = '';
  4647. this.clear = clear('', this.out.columns);
  4648. this.filteredOptions = this.value;
  4649. this.render();
  4650. }
  4651. last() {
  4652. this.cursor = this.filteredOptions.length - 1;
  4653. this.render();
  4654. }
  4655. next() {
  4656. this.cursor = (this.cursor + 1) % this.filteredOptions.length;
  4657. this.render();
  4658. }
  4659. up() {
  4660. if (this.cursor === 0) {
  4661. this.cursor = this.filteredOptions.length - 1;
  4662. } else {
  4663. this.cursor--;
  4664. }
  4665. this.render();
  4666. }
  4667. down() {
  4668. if (this.cursor === this.filteredOptions.length - 1) {
  4669. this.cursor = 0;
  4670. } else {
  4671. this.cursor++;
  4672. }
  4673. this.render();
  4674. }
  4675. left() {
  4676. this.filteredOptions[this.cursor].selected = false;
  4677. this.render();
  4678. }
  4679. right() {
  4680. if (this.value.filter(e => e.selected).length >= this.maxChoices) return this.bell();
  4681. this.filteredOptions[this.cursor].selected = true;
  4682. this.render();
  4683. }
  4684. delete() {
  4685. if (this.inputValue.length) {
  4686. this.inputValue = this.inputValue.substr(0, this.inputValue.length - 1);
  4687. this.updateFilteredOptions();
  4688. }
  4689. }
  4690. updateFilteredOptions() {
  4691. const currentHighlight = this.filteredOptions[this.cursor];
  4692. this.filteredOptions = this.value
  4693. .filter(v => {
  4694. if (this.inputValue) {
  4695. if (typeof v.title === 'string') {
  4696. if (v.title.toLowerCase().includes(this.inputValue.toLowerCase())) {
  4697. return true;
  4698. }
  4699. }
  4700. if (typeof v.value === 'string') {
  4701. if (v.value.toLowerCase().includes(this.inputValue.toLowerCase())) {
  4702. return true;
  4703. }
  4704. }
  4705. return false;
  4706. }
  4707. return true;
  4708. });
  4709. const newHighlightIndex = this.filteredOptions.findIndex(v => v === currentHighlight);
  4710. this.cursor = newHighlightIndex < 0 ? 0 : newHighlightIndex;
  4711. this.render();
  4712. }
  4713. handleSpaceToggle() {
  4714. const v = this.filteredOptions[this.cursor];
  4715. if (v.selected) {
  4716. v.selected = false;
  4717. this.render();
  4718. } else if (v.disabled || this.value.filter(e => e.selected).length >= this.maxChoices) {
  4719. return this.bell();
  4720. } else {
  4721. v.selected = true;
  4722. this.render();
  4723. }
  4724. }
  4725. handleInputChange(c) {
  4726. this.inputValue = this.inputValue + c;
  4727. this.updateFilteredOptions();
  4728. }
  4729. _(c, key) {
  4730. if (c === ' ') {
  4731. this.handleSpaceToggle();
  4732. } else {
  4733. this.handleInputChange(c);
  4734. }
  4735. }
  4736. renderInstructions() {
  4737. if (this.instructions === undefined || this.instructions) {
  4738. if (typeof this.instructions === 'string') {
  4739. return this.instructions;
  4740. }
  4741. return `
  4742. Instructions:
  4743. ${figures.arrowUp}/${figures.arrowDown}: Highlight option
  4744. ${figures.arrowLeft}/${figures.arrowRight}/[space]: Toggle selection
  4745. [a,b,c]/delete: Filter choices
  4746. enter/return: Complete answer
  4747. `;
  4748. }
  4749. return '';
  4750. }
  4751. renderCurrentInput() {
  4752. return `
  4753. Filtered results for: ${this.inputValue ? this.inputValue : color.gray('Enter something to filter')}\n`;
  4754. }
  4755. renderOption(cursor, v, i) {
  4756. let title;
  4757. if (v.disabled) title = cursor === i ? color.gray().underline(v.title) : color.strikethrough().gray(v.title);
  4758. else title = cursor === i ? color.cyan().underline(v.title) : v.title;
  4759. return (v.selected ? color.green(figures.radioOn) : figures.radioOff) + ' ' + title
  4760. }
  4761. renderDoneOrInstructions() {
  4762. if (this.done) {
  4763. return this.value
  4764. .filter(e => e.selected)
  4765. .map(v => v.title)
  4766. .join(', ');
  4767. }
  4768. const output = [color.gray(this.hint), this.renderInstructions(), this.renderCurrentInput()];
  4769. if (this.filteredOptions.length && this.filteredOptions[this.cursor].disabled) {
  4770. output.push(color.yellow(this.warn));
  4771. }
  4772. return output.join(' ');
  4773. }
  4774. render() {
  4775. if (this.closed) return;
  4776. if (this.firstRender) this.out.write(cursor.hide);
  4777. super.render();
  4778. // print prompt
  4779. let prompt = [
  4780. style.symbol(this.done, this.aborted),
  4781. color.bold(this.msg),
  4782. style.delimiter(false),
  4783. this.renderDoneOrInstructions()
  4784. ].join(' ');
  4785. if (this.showMinError) {
  4786. prompt += color.red(`You must select a minimum of ${this.minSelected} choices.`);
  4787. this.showMinError = false;
  4788. }
  4789. prompt += this.renderOptions(this.filteredOptions);
  4790. this.out.write(this.clear + prompt);
  4791. this.clear = clear(prompt, this.out.columns);
  4792. }
  4793. }
  4794. autocompleteMultiselect = AutocompleteMultiselectPrompt;
  4795. return autocompleteMultiselect;
  4796. }
  4797. var confirm;
  4798. var hasRequiredConfirm;
  4799. function requireConfirm () {
  4800. if (hasRequiredConfirm) return confirm;
  4801. hasRequiredConfirm = 1;
  4802. const color = requireKleur();
  4803. const Prompt = requirePrompt();
  4804. const { style, clear } = requireUtil();
  4805. const { erase, cursor } = requireSrc();
  4806. /**
  4807. * ConfirmPrompt Base Element
  4808. * @param {Object} opts Options
  4809. * @param {String} opts.message Message
  4810. * @param {Boolean} [opts.initial] Default value (true/false)
  4811. * @param {Stream} [opts.stdin] The Readable stream to listen to
  4812. * @param {Stream} [opts.stdout] The Writable stream to write readline data to
  4813. * @param {String} [opts.yes] The "Yes" label
  4814. * @param {String} [opts.yesOption] The "Yes" option when choosing between yes/no
  4815. * @param {String} [opts.no] The "No" label
  4816. * @param {String} [opts.noOption] The "No" option when choosing between yes/no
  4817. */
  4818. class ConfirmPrompt extends Prompt {
  4819. constructor(opts={}) {
  4820. super(opts);
  4821. this.msg = opts.message;
  4822. this.value = opts.initial;
  4823. this.initialValue = !!opts.initial;
  4824. this.yesMsg = opts.yes || 'yes';
  4825. this.yesOption = opts.yesOption || '(Y/n)';
  4826. this.noMsg = opts.no || 'no';
  4827. this.noOption = opts.noOption || '(y/N)';
  4828. this.render();
  4829. }
  4830. reset() {
  4831. this.value = this.initialValue;
  4832. this.fire();
  4833. this.render();
  4834. }
  4835. exit() {
  4836. this.abort();
  4837. }
  4838. abort() {
  4839. this.done = this.aborted = true;
  4840. this.fire();
  4841. this.render();
  4842. this.out.write('\n');
  4843. this.close();
  4844. }
  4845. submit() {
  4846. this.value = this.value || false;
  4847. this.done = true;
  4848. this.aborted = false;
  4849. this.fire();
  4850. this.render();
  4851. this.out.write('\n');
  4852. this.close();
  4853. }
  4854. _(c, key) {
  4855. if (c.toLowerCase() === 'y') {
  4856. this.value = true;
  4857. return this.submit();
  4858. }
  4859. if (c.toLowerCase() === 'n') {
  4860. this.value = false;
  4861. return this.submit();
  4862. }
  4863. return this.bell();
  4864. }
  4865. render() {
  4866. if (this.closed) return;
  4867. if (this.firstRender) this.out.write(cursor.hide);
  4868. else this.out.write(clear(this.outputText, this.out.columns));
  4869. super.render();
  4870. this.outputText = [
  4871. style.symbol(this.done, this.aborted),
  4872. color.bold(this.msg),
  4873. style.delimiter(this.done),
  4874. this.done ? (this.value ? this.yesMsg : this.noMsg)
  4875. : color.gray(this.initialValue ? this.yesOption : this.noOption)
  4876. ].join(' ');
  4877. this.out.write(erase.line + cursor.to(0) + this.outputText);
  4878. }
  4879. }
  4880. confirm = ConfirmPrompt;
  4881. return confirm;
  4882. }
  4883. var elements;
  4884. var hasRequiredElements;
  4885. function requireElements () {
  4886. if (hasRequiredElements) return elements;
  4887. hasRequiredElements = 1;
  4888. elements = {
  4889. TextPrompt: requireText(),
  4890. SelectPrompt: requireSelect(),
  4891. TogglePrompt: requireToggle(),
  4892. DatePrompt: requireDate(),
  4893. NumberPrompt: requireNumber(),
  4894. MultiselectPrompt: requireMultiselect(),
  4895. AutocompletePrompt: requireAutocomplete(),
  4896. AutocompleteMultiselectPrompt: requireAutocompleteMultiselect(),
  4897. ConfirmPrompt: requireConfirm()
  4898. };
  4899. return elements;
  4900. }
  4901. var hasRequiredPrompts;
  4902. function requirePrompts () {
  4903. if (hasRequiredPrompts) return prompts$1;
  4904. hasRequiredPrompts = 1;
  4905. (function (exports) {
  4906. const $ = exports;
  4907. const el = requireElements();
  4908. const noop = v => v;
  4909. function toPrompt(type, args, opts={}) {
  4910. return new Promise((res, rej) => {
  4911. const p = new el[type](args);
  4912. const onAbort = opts.onAbort || noop;
  4913. const onSubmit = opts.onSubmit || noop;
  4914. const onExit = opts.onExit || noop;
  4915. p.on('state', args.onState || noop);
  4916. p.on('submit', x => res(onSubmit(x)));
  4917. p.on('exit', x => res(onExit(x)));
  4918. p.on('abort', x => rej(onAbort(x)));
  4919. });
  4920. }
  4921. /**
  4922. * Text prompt
  4923. * @param {string} args.message Prompt message to display
  4924. * @param {string} [args.initial] Default string value
  4925. * @param {string} [args.style="default"] Render style ('default', 'password', 'invisible')
  4926. * @param {function} [args.onState] On state change callback
  4927. * @param {function} [args.validate] Function to validate user input
  4928. * @param {Stream} [args.stdin] The Readable stream to listen to
  4929. * @param {Stream} [args.stdout] The Writable stream to write readline data to
  4930. * @returns {Promise} Promise with user input
  4931. */
  4932. $.text = args => toPrompt('TextPrompt', args);
  4933. /**
  4934. * Password prompt with masked input
  4935. * @param {string} args.message Prompt message to display
  4936. * @param {string} [args.initial] Default string value
  4937. * @param {function} [args.onState] On state change callback
  4938. * @param {function} [args.validate] Function to validate user input
  4939. * @param {Stream} [args.stdin] The Readable stream to listen to
  4940. * @param {Stream} [args.stdout] The Writable stream to write readline data to
  4941. * @returns {Promise} Promise with user input
  4942. */
  4943. $.password = args => {
  4944. args.style = 'password';
  4945. return $.text(args);
  4946. };
  4947. /**
  4948. * Prompt where input is invisible, like sudo
  4949. * @param {string} args.message Prompt message to display
  4950. * @param {string} [args.initial] Default string value
  4951. * @param {function} [args.onState] On state change callback
  4952. * @param {function} [args.validate] Function to validate user input
  4953. * @param {Stream} [args.stdin] The Readable stream to listen to
  4954. * @param {Stream} [args.stdout] The Writable stream to write readline data to
  4955. * @returns {Promise} Promise with user input
  4956. */
  4957. $.invisible = args => {
  4958. args.style = 'invisible';
  4959. return $.text(args);
  4960. };
  4961. /**
  4962. * Number prompt
  4963. * @param {string} args.message Prompt message to display
  4964. * @param {number} args.initial Default number value
  4965. * @param {function} [args.onState] On state change callback
  4966. * @param {number} [args.max] Max value
  4967. * @param {number} [args.min] Min value
  4968. * @param {string} [args.style="default"] Render style ('default', 'password', 'invisible')
  4969. * @param {Boolean} [opts.float=false] Parse input as floats
  4970. * @param {Number} [opts.round=2] Round floats to x decimals
  4971. * @param {Number} [opts.increment=1] Number to increment by when using arrow-keys
  4972. * @param {function} [args.validate] Function to validate user input
  4973. * @param {Stream} [args.stdin] The Readable stream to listen to
  4974. * @param {Stream} [args.stdout] The Writable stream to write readline data to
  4975. * @returns {Promise} Promise with user input
  4976. */
  4977. $.number = args => toPrompt('NumberPrompt', args);
  4978. /**
  4979. * Date prompt
  4980. * @param {string} args.message Prompt message to display
  4981. * @param {number} args.initial Default number value
  4982. * @param {function} [args.onState] On state change callback
  4983. * @param {number} [args.max] Max value
  4984. * @param {number} [args.min] Min value
  4985. * @param {string} [args.style="default"] Render style ('default', 'password', 'invisible')
  4986. * @param {Boolean} [opts.float=false] Parse input as floats
  4987. * @param {Number} [opts.round=2] Round floats to x decimals
  4988. * @param {Number} [opts.increment=1] Number to increment by when using arrow-keys
  4989. * @param {function} [args.validate] Function to validate user input
  4990. * @param {Stream} [args.stdin] The Readable stream to listen to
  4991. * @param {Stream} [args.stdout] The Writable stream to write readline data to
  4992. * @returns {Promise} Promise with user input
  4993. */
  4994. $.date = args => toPrompt('DatePrompt', args);
  4995. /**
  4996. * Classic yes/no prompt
  4997. * @param {string} args.message Prompt message to display
  4998. * @param {boolean} [args.initial=false] Default value
  4999. * @param {function} [args.onState] On state change callback
  5000. * @param {Stream} [args.stdin] The Readable stream to listen to
  5001. * @param {Stream} [args.stdout] The Writable stream to write readline data to
  5002. * @returns {Promise} Promise with user input
  5003. */
  5004. $.confirm = args => toPrompt('ConfirmPrompt', args);
  5005. /**
  5006. * List prompt, split intput string by `seperator`
  5007. * @param {string} args.message Prompt message to display
  5008. * @param {string} [args.initial] Default string value
  5009. * @param {string} [args.style="default"] Render style ('default', 'password', 'invisible')
  5010. * @param {string} [args.separator] String separator
  5011. * @param {function} [args.onState] On state change callback
  5012. * @param {Stream} [args.stdin] The Readable stream to listen to
  5013. * @param {Stream} [args.stdout] The Writable stream to write readline data to
  5014. * @returns {Promise} Promise with user input, in form of an `Array`
  5015. */
  5016. $.list = args => {
  5017. const sep = args.separator || ',';
  5018. return toPrompt('TextPrompt', args, {
  5019. onSubmit: str => str.split(sep).map(s => s.trim())
  5020. });
  5021. };
  5022. /**
  5023. * Toggle/switch prompt
  5024. * @param {string} args.message Prompt message to display
  5025. * @param {boolean} [args.initial=false] Default value
  5026. * @param {string} [args.active="on"] Text for `active` state
  5027. * @param {string} [args.inactive="off"] Text for `inactive` state
  5028. * @param {function} [args.onState] On state change callback
  5029. * @param {Stream} [args.stdin] The Readable stream to listen to
  5030. * @param {Stream} [args.stdout] The Writable stream to write readline data to
  5031. * @returns {Promise} Promise with user input
  5032. */
  5033. $.toggle = args => toPrompt('TogglePrompt', args);
  5034. /**
  5035. * Interactive select prompt
  5036. * @param {string} args.message Prompt message to display
  5037. * @param {Array} args.choices Array of choices objects `[{ title, value }, ...]`
  5038. * @param {number} [args.initial] Index of default value
  5039. * @param {String} [args.hint] Hint to display
  5040. * @param {function} [args.onState] On state change callback
  5041. * @param {Stream} [args.stdin] The Readable stream to listen to
  5042. * @param {Stream} [args.stdout] The Writable stream to write readline data to
  5043. * @returns {Promise} Promise with user input
  5044. */
  5045. $.select = args => toPrompt('SelectPrompt', args);
  5046. /**
  5047. * Interactive multi-select / autocompleteMultiselect prompt
  5048. * @param {string} args.message Prompt message to display
  5049. * @param {Array} args.choices Array of choices objects `[{ title, value, [selected] }, ...]`
  5050. * @param {number} [args.max] Max select
  5051. * @param {string} [args.hint] Hint to display user
  5052. * @param {Number} [args.cursor=0] Cursor start position
  5053. * @param {function} [args.onState] On state change callback
  5054. * @param {Stream} [args.stdin] The Readable stream to listen to
  5055. * @param {Stream} [args.stdout] The Writable stream to write readline data to
  5056. * @returns {Promise} Promise with user input
  5057. */
  5058. $.multiselect = args => {
  5059. args.choices = [].concat(args.choices || []);
  5060. const toSelected = items => items.filter(item => item.selected).map(item => item.value);
  5061. return toPrompt('MultiselectPrompt', args, {
  5062. onAbort: toSelected,
  5063. onSubmit: toSelected
  5064. });
  5065. };
  5066. $.autocompleteMultiselect = args => {
  5067. args.choices = [].concat(args.choices || []);
  5068. const toSelected = items => items.filter(item => item.selected).map(item => item.value);
  5069. return toPrompt('AutocompleteMultiselectPrompt', args, {
  5070. onAbort: toSelected,
  5071. onSubmit: toSelected
  5072. });
  5073. };
  5074. const byTitle = (input, choices) => Promise.resolve(
  5075. choices.filter(item => item.title.slice(0, input.length).toLowerCase() === input.toLowerCase())
  5076. );
  5077. /**
  5078. * Interactive auto-complete prompt
  5079. * @param {string} args.message Prompt message to display
  5080. * @param {Array} args.choices Array of auto-complete choices objects `[{ title, value }, ...]`
  5081. * @param {Function} [args.suggest] Function to filter results based on user input. Defaults to sort by `title`
  5082. * @param {number} [args.limit=10] Max number of results to show
  5083. * @param {string} [args.style="default"] Render style ('default', 'password', 'invisible')
  5084. * @param {String} [args.initial] Index of the default value
  5085. * @param {boolean} [opts.clearFirst] The first ESCAPE keypress will clear the input
  5086. * @param {String} [args.fallback] Fallback message - defaults to initial value
  5087. * @param {function} [args.onState] On state change callback
  5088. * @param {Stream} [args.stdin] The Readable stream to listen to
  5089. * @param {Stream} [args.stdout] The Writable stream to write readline data to
  5090. * @returns {Promise} Promise with user input
  5091. */
  5092. $.autocomplete = args => {
  5093. args.suggest = args.suggest || byTitle;
  5094. args.choices = [].concat(args.choices || []);
  5095. return toPrompt('AutocompletePrompt', args);
  5096. };
  5097. } (prompts$1));
  5098. return prompts$1;
  5099. }
  5100. var lib;
  5101. var hasRequiredLib;
  5102. function requireLib () {
  5103. if (hasRequiredLib) return lib;
  5104. hasRequiredLib = 1;
  5105. const prompts = requirePrompts();
  5106. const passOn = ['suggest', 'format', 'onState', 'validate', 'onRender', 'type'];
  5107. const noop = () => {};
  5108. /**
  5109. * Prompt for a series of questions
  5110. * @param {Array|Object} questions Single question object or Array of question objects
  5111. * @param {Function} [onSubmit] Callback function called on prompt submit
  5112. * @param {Function} [onCancel] Callback function called on cancel/abort
  5113. * @returns {Object} Object with values from user input
  5114. */
  5115. async function prompt(questions=[], { onSubmit=noop, onCancel=noop }={}) {
  5116. const answers = {};
  5117. const override = prompt._override || {};
  5118. questions = [].concat(questions);
  5119. let answer, question, quit, name, type, lastPrompt;
  5120. const getFormattedAnswer = async (question, answer, skipValidation = false) => {
  5121. if (!skipValidation && question.validate && question.validate(answer) !== true) {
  5122. return;
  5123. }
  5124. return question.format ? await question.format(answer, answers) : answer
  5125. };
  5126. for (question of questions) {
  5127. ({ name, type } = question);
  5128. // evaluate type first and skip if type is a falsy value
  5129. if (typeof type === 'function') {
  5130. type = await type(answer, { ...answers }, question);
  5131. question['type'] = type;
  5132. }
  5133. if (!type) continue;
  5134. // if property is a function, invoke it unless it's a special function
  5135. for (let key in question) {
  5136. if (passOn.includes(key)) continue;
  5137. let value = question[key];
  5138. question[key] = typeof value === 'function' ? await value(answer, { ...answers }, lastPrompt) : value;
  5139. }
  5140. lastPrompt = question;
  5141. if (typeof question.message !== 'string') {
  5142. throw new Error('prompt message is required');
  5143. }
  5144. // update vars in case they changed
  5145. ({ name, type } = question);
  5146. if (prompts[type] === void 0) {
  5147. throw new Error(`prompt type (${type}) is not defined`);
  5148. }
  5149. if (override[question.name] !== undefined) {
  5150. answer = await getFormattedAnswer(question, override[question.name]);
  5151. if (answer !== undefined) {
  5152. answers[name] = answer;
  5153. continue;
  5154. }
  5155. }
  5156. try {
  5157. // Get the injected answer if there is one or prompt the user
  5158. answer = prompt._injected ? getInjectedAnswer(prompt._injected, question.initial) : await prompts[type](question);
  5159. answers[name] = answer = await getFormattedAnswer(question, answer, true);
  5160. quit = await onSubmit(question, answer, answers);
  5161. } catch (err) {
  5162. quit = !(await onCancel(question, answers));
  5163. }
  5164. if (quit) return answers;
  5165. }
  5166. return answers;
  5167. }
  5168. function getInjectedAnswer(injected, deafultValue) {
  5169. const answer = injected.shift();
  5170. if (answer instanceof Error) {
  5171. throw answer;
  5172. }
  5173. return (answer === undefined) ? deafultValue : answer;
  5174. }
  5175. function inject(answers) {
  5176. prompt._injected = (prompt._injected || []).concat(answers);
  5177. }
  5178. function override(answers) {
  5179. prompt._override = Object.assign({}, answers);
  5180. }
  5181. lib = Object.assign(prompt, { prompt, prompts, inject, override });
  5182. return lib;
  5183. }
  5184. function isNodeLT(tar) {
  5185. tar = (Array.isArray(tar) ? tar : tar.split('.')).map(Number);
  5186. let i=0, src=process.versions.node.split('.').map(Number);
  5187. for (; i < tar.length; i++) {
  5188. if (src[i] > tar[i]) return false;
  5189. if (tar[i] > src[i]) return true;
  5190. }
  5191. return false;
  5192. }
  5193. var prompts =
  5194. isNodeLT('8.6.0')
  5195. ? requireDist()
  5196. : requireLib();
  5197. var index = /*#__PURE__*/_mergeNamespaces({
  5198. __proto__: null,
  5199. 'default': prompts
  5200. }, [prompts]);
  5201. export { index as i, prompts as p };