bin-prettier.js 413 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523
  1. #!/usr/bin/env node
  2. 'use strict';
  3. var path = require('path');
  4. var fs$2 = require('fs');
  5. var readline = require('readline');
  6. var os = require('os');
  7. var tty = require('tty');
  8. var util$2 = require('util');
  9. var stream$4 = require('stream');
  10. var events = require('events');
  11. function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
  12. var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
  13. var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs$2);
  14. var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);
  15. var os__default = /*#__PURE__*/_interopDefaultLegacy(os);
  16. var tty__default = /*#__PURE__*/_interopDefaultLegacy(tty);
  17. var util__default = /*#__PURE__*/_interopDefaultLegacy(util$2);
  18. var stream__default = /*#__PURE__*/_interopDefaultLegacy(stream$4);
  19. var events__default = /*#__PURE__*/_interopDefaultLegacy(events);
  20. var semverCompare = function cmp(a, b) {
  21. var pa = a.split('.');
  22. var pb = b.split('.');
  23. for (var i = 0; i < 3; i++) {
  24. var na = Number(pa[i]);
  25. var nb = Number(pb[i]);
  26. if (na > nb) return 1;
  27. if (nb > na) return -1;
  28. if (!isNaN(na) && isNaN(nb)) return 1;
  29. if (isNaN(na) && !isNaN(nb)) return -1;
  30. }
  31. return 0;
  32. };
  33. var pleaseUpgradeNode = function pleaseUpgradeNode(pkg, opts) {
  34. var opts = opts || {};
  35. var requiredVersion = pkg.engines.node.replace('>=', '');
  36. var currentVersion = process.version.replace('v', '');
  37. if (semverCompare(currentVersion, requiredVersion) === -1) {
  38. if (opts.message) {
  39. console.error(opts.message(requiredVersion));
  40. } else {
  41. console.error(pkg.name + ' requires at least version ' + requiredVersion + ' of Node, please upgrade');
  42. }
  43. if (opts.hasOwnProperty('exitCode')) {
  44. process.exit(opts.exitCode);
  45. } else {
  46. process.exit(1);
  47. }
  48. }
  49. };
  50. var name = "prettier";
  51. var version = "2.1.2";
  52. var description = "Prettier is an opinionated code formatter";
  53. var bin = "./bin/prettier.js";
  54. var repository = "prettier/prettier";
  55. var homepage = "https://prettier.io";
  56. var author = "James Long";
  57. var license = "MIT";
  58. var main = "./index.js";
  59. var browser = "./standalone.js";
  60. var unpkg = "./standalone.js";
  61. var engines = {
  62. node: ">=10.13.0"
  63. };
  64. var files = [
  65. "index.js",
  66. "standalone.js",
  67. "src",
  68. "bin"
  69. ];
  70. var dependencies = {
  71. "@angular/compiler": "10.0.12",
  72. "@babel/code-frame": "7.10.4",
  73. "@babel/parser": "7.11.2",
  74. "@glimmer/syntax": "0.59.0",
  75. "@iarna/toml": "2.2.5",
  76. "@typescript-eslint/typescript-estree": "3.10.0",
  77. "angular-estree-parser": "2.2.0",
  78. "angular-html-parser": "1.7.1",
  79. camelcase: "6.0.0",
  80. chalk: "4.1.0",
  81. "ci-info": "watson/ci-info#f43f6a1cefff47fb361c88cf4b943fdbcaafe540",
  82. "cjk-regex": "2.0.0",
  83. cosmiconfig: "7.0.0",
  84. dashify: "2.0.0",
  85. diff: "4.0.2",
  86. editorconfig: "0.15.3",
  87. "editorconfig-to-prettier": "0.1.1",
  88. "escape-string-regexp": "4.0.0",
  89. esutils: "2.0.3",
  90. "fast-glob": "3.2.4",
  91. "fast-json-stable-stringify": "2.1.0",
  92. "find-parent-dir": "0.3.0",
  93. "flow-parser": "0.132.0",
  94. "get-stream": "6.0.0",
  95. globby: "11.0.1",
  96. graphql: "15.3.0",
  97. "html-element-attributes": "2.2.1",
  98. "html-styles": "1.0.0",
  99. "html-tag-names": "1.1.5",
  100. "html-void-elements": "1.0.5",
  101. ignore: "4.0.6",
  102. "jest-docblock": "26.0.0",
  103. json5: "2.1.3",
  104. leven: "3.1.0",
  105. "lines-and-columns": "1.1.6",
  106. "linguist-languages": "7.10.0",
  107. lodash: "4.17.20",
  108. mem: "6.1.0",
  109. minimatch: "3.0.4",
  110. minimist: "1.2.5",
  111. "n-readlines": "1.0.0",
  112. outdent: "0.7.1",
  113. "parse-srcset": "ikatyang/parse-srcset#54eb9c1cb21db5c62b4d0e275d7249516df6f0ee",
  114. "please-upgrade-node": "3.2.0",
  115. "postcss-less": "3.1.4",
  116. "postcss-media-query-parser": "0.2.3",
  117. "postcss-scss": "2.1.1",
  118. "postcss-selector-parser": "2.2.3",
  119. "postcss-values-parser": "2.0.1",
  120. "regexp-util": "1.2.2",
  121. "remark-footnotes": "2.0.0",
  122. "remark-math": "1.0.6",
  123. "remark-parse": "8.0.3",
  124. resolve: "1.17.0",
  125. semver: "7.3.2",
  126. "string-width": "4.2.0",
  127. typescript: "4.0.2",
  128. "unicode-regex": "3.0.0",
  129. unified: "9.2.0",
  130. vnopts: "1.0.2",
  131. "yaml-unist-parser": "1.3.1"
  132. };
  133. var devDependencies = {
  134. "@babel/core": "7.11.4",
  135. "@babel/preset-env": "7.11.0",
  136. "@babel/types": "7.11.0",
  137. "@glimmer/reference": "0.59.0",
  138. "@rollup/plugin-alias": "3.1.1",
  139. "@rollup/plugin-babel": "5.2.0",
  140. "@rollup/plugin-commonjs": "14.0.0",
  141. "@rollup/plugin-json": "4.1.0",
  142. "@rollup/plugin-node-resolve": "9.0.0",
  143. "@rollup/plugin-replace": "2.3.3",
  144. "@types/estree": "0.0.45",
  145. "@types/node": "14.6.0",
  146. "@typescript-eslint/types": "3.10.0",
  147. "babel-loader": "8.1.0",
  148. benchmark: "2.1.4",
  149. "builtin-modules": "3.1.0",
  150. "cross-env": "7.0.2",
  151. cspell: "4.1.0",
  152. eslint: "7.7.0",
  153. "eslint-config-prettier": "6.11.0",
  154. "eslint-formatter-friendly": "7.0.0",
  155. "eslint-plugin-import": "2.22.0",
  156. "eslint-plugin-jest": "23.20.0",
  157. "eslint-plugin-prettier-internal-rules": "file:scripts/tools/eslint-plugin-prettier-internal-rules",
  158. "eslint-plugin-react": "7.20.6",
  159. "eslint-plugin-unicorn": "21.0.0",
  160. execa: "4.0.3",
  161. jest: "26.4.2",
  162. "jest-snapshot-serializer-ansi": "1.0.0",
  163. "jest-snapshot-serializer-raw": "1.1.0",
  164. "jest-watch-typeahead": "0.6.0",
  165. "npm-run-all": "4.1.5",
  166. prettier: "2.1.1",
  167. rimraf: "3.0.2",
  168. rollup: "2.26.5",
  169. "rollup-plugin-node-globals": "1.4.0",
  170. "rollup-plugin-terser": "7.0.0",
  171. shelljs: "0.8.4",
  172. "snapshot-diff": "0.8.1",
  173. "strip-ansi": "6.0.0",
  174. "synchronous-promise": "2.0.13",
  175. tempy: "0.6.0",
  176. "terser-webpack-plugin": "4.1.0",
  177. webpack: "4.44.1"
  178. };
  179. var scripts = {
  180. prepublishOnly: "echo \"Error: must publish from dist/\" && exit 1",
  181. "prepare-release": "yarn && yarn build && yarn test:dist",
  182. test: "jest",
  183. "test:dev-package": "cross-env INSTALL_PACKAGE=1 jest",
  184. "test:dist": "cross-env NODE_ENV=production jest",
  185. "test:dist-standalone": "cross-env NODE_ENV=production TEST_STANDALONE=1 jest",
  186. "test:integration": "jest tests_integration",
  187. "perf:repeat": "yarn && yarn build && cross-env NODE_ENV=production node ./dist/bin-prettier.js --debug-repeat ${PERF_REPEAT:-1000} --loglevel debug ${PERF_FILE:-./index.js} > /dev/null",
  188. "perf:repeat-inspect": "yarn && yarn build && cross-env NODE_ENV=production node --inspect-brk ./dist/bin-prettier.js --debug-repeat ${PERF_REPEAT:-1000} --loglevel debug ${PERF_FILE:-./index.js} > /dev/null",
  189. "perf:benchmark": "yarn && yarn build && cross-env NODE_ENV=production node ./dist/bin-prettier.js --debug-benchmark --loglevel debug ${PERF_FILE:-./index.js} > /dev/null",
  190. lint: "run-p lint:*",
  191. "lint:typecheck": "tsc",
  192. "lint:eslint": "cross-env EFF_NO_LINK_RULES=true eslint . --format friendly",
  193. "lint:changelog": "node ./scripts/lint-changelog.js",
  194. "lint:prettier": "prettier . \"!test*\" --check",
  195. "lint:dist": "eslint --no-eslintrc --no-ignore --env=es6,browser --parser-options=ecmaVersion:2016 \"dist/!(bin-prettier|index|third-party).js\"",
  196. "lint:spellcheck": "cspell \"**/*\" \".github/**/*\"",
  197. "lint:deps": "node ./scripts/check-deps.js",
  198. fix: "run-s fix:eslint fix:prettier",
  199. "fix:eslint": "yarn lint:eslint --fix",
  200. "fix:prettier": "yarn lint:prettier --write",
  201. build: "node ./scripts/build/build.js",
  202. "build-docs": "node ./scripts/build-docs.js"
  203. };
  204. var _package = {
  205. name: name,
  206. version: version,
  207. description: description,
  208. bin: bin,
  209. repository: repository,
  210. homepage: homepage,
  211. author: author,
  212. license: license,
  213. main: main,
  214. browser: browser,
  215. unpkg: unpkg,
  216. engines: engines,
  217. files: files,
  218. dependencies: dependencies,
  219. devDependencies: devDependencies,
  220. scripts: scripts
  221. };
  222. var _package$1 = /*#__PURE__*/Object.freeze({
  223. __proto__: null,
  224. name: name,
  225. version: version,
  226. description: description,
  227. bin: bin,
  228. repository: repository,
  229. homepage: homepage,
  230. author: author,
  231. license: license,
  232. main: main,
  233. browser: browser,
  234. unpkg: unpkg,
  235. engines: engines,
  236. files: files,
  237. dependencies: dependencies,
  238. devDependencies: devDependencies,
  239. scripts: scripts,
  240. 'default': _package
  241. });
  242. var fastJsonStableStringify = function (data, opts) {
  243. if (!opts) opts = {};
  244. if (typeof opts === 'function') opts = {
  245. cmp: opts
  246. };
  247. var cycles = typeof opts.cycles === 'boolean' ? opts.cycles : false;
  248. var cmp = opts.cmp && function (f) {
  249. return function (node) {
  250. return function (a, b) {
  251. var aobj = {
  252. key: a,
  253. value: node[a]
  254. };
  255. var bobj = {
  256. key: b,
  257. value: node[b]
  258. };
  259. return f(aobj, bobj);
  260. };
  261. };
  262. }(opts.cmp);
  263. var seen = [];
  264. return function stringify(node) {
  265. if (node && node.toJSON && typeof node.toJSON === 'function') {
  266. node = node.toJSON();
  267. }
  268. if (node === undefined) return;
  269. if (typeof node == 'number') return isFinite(node) ? '' + node : 'null';
  270. if (typeof node !== 'object') return JSON.stringify(node);
  271. var i, out;
  272. if (Array.isArray(node)) {
  273. out = '[';
  274. for (i = 0; i < node.length; i++) {
  275. if (i) out += ',';
  276. out += stringify(node[i]) || 'null';
  277. }
  278. return out + ']';
  279. }
  280. if (node === null) return 'null';
  281. if (seen.indexOf(node) !== -1) {
  282. if (cycles) return JSON.stringify('__cycle__');
  283. throw new TypeError('Converting circular structure to JSON');
  284. }
  285. var seenIndex = seen.push(node) - 1;
  286. var keys = Object.keys(node).sort(cmp && cmp(node));
  287. out = '';
  288. for (i = 0; i < keys.length; i++) {
  289. var key = keys[i];
  290. var value = stringify(node[key]);
  291. if (!value) continue;
  292. if (out) out += ',';
  293. out += JSON.stringify(key) + ':' + value;
  294. }
  295. seen.splice(seenIndex, 1);
  296. return '{' + out + '}';
  297. }(data);
  298. };
  299. var src = require("./index");
  300. const preserveCamelCase = string => {
  301. let isLastCharLower = false;
  302. let isLastCharUpper = false;
  303. let isLastLastCharUpper = false;
  304. for (let i = 0; i < string.length; i++) {
  305. const character = string[i];
  306. if (isLastCharLower && /[\p{Lu}]/u.test(character)) {
  307. string = string.slice(0, i) + '-' + string.slice(i);
  308. isLastCharLower = false;
  309. isLastLastCharUpper = isLastCharUpper;
  310. isLastCharUpper = true;
  311. i++;
  312. } else if (isLastCharUpper && isLastLastCharUpper && /[\p{Ll}]/u.test(character)) {
  313. string = string.slice(0, i - 1) + '-' + string.slice(i - 1);
  314. isLastLastCharUpper = isLastCharUpper;
  315. isLastCharUpper = false;
  316. isLastCharLower = true;
  317. } else {
  318. isLastCharLower = character.toLocaleLowerCase() === character && character.toLocaleUpperCase() !== character;
  319. isLastLastCharUpper = isLastCharUpper;
  320. isLastCharUpper = character.toLocaleUpperCase() === character && character.toLocaleLowerCase() !== character;
  321. }
  322. }
  323. return string;
  324. };
  325. const camelCase = (input, options) => {
  326. if (!(typeof input === 'string' || Array.isArray(input))) {
  327. throw new TypeError('Expected the input to be `string | string[]`');
  328. }
  329. options = Object.assign({}, {
  330. pascalCase: false
  331. }, options);
  332. const postProcess = x => options.pascalCase ? x.charAt(0).toLocaleUpperCase() + x.slice(1) : x;
  333. if (Array.isArray(input)) {
  334. input = input.map(x => x.trim()).filter(x => x.length).join('-');
  335. } else {
  336. input = input.trim();
  337. }
  338. if (input.length === 0) {
  339. return '';
  340. }
  341. if (input.length === 1) {
  342. return options.pascalCase ? input.toLocaleUpperCase() : input.toLocaleLowerCase();
  343. }
  344. const hasUpperCase = input !== input.toLocaleLowerCase();
  345. if (hasUpperCase) {
  346. input = preserveCamelCase(input);
  347. }
  348. input = input.replace(/^[_.\- ]+/, '').toLocaleLowerCase().replace(/[_.\- ]+([\p{Alpha}\p{N}_]|$)/gu, (_, p1) => p1.toLocaleUpperCase()).replace(/\d+([\p{Alpha}\p{N}_]|$)/gu, m => m.toLocaleUpperCase());
  349. return postProcess(input);
  350. };
  351. var camelcase = camelCase; // TODO: Remove this for the next major release
  352. var _default = camelCase;
  353. camelcase.default = _default;
  354. /*!
  355. * dashify <https://github.com/jonschlinkert/dashify>
  356. *
  357. * Copyright (c) 2015-2017, Jon Schlinkert.
  358. * Released under the MIT License.
  359. */
  360. var dashify = (str, options) => {
  361. if (typeof str !== 'string') throw new TypeError('expected a string');
  362. return str.trim().replace(/([a-z])([A-Z])/g, '$1-$2').replace(/\W/g, m => /[À-ž]/.test(m) ? m : '-').replace(/^-+|-+$/g, '').replace(/-{2,}/g, m => options && options.condense ? '-' : m).toLowerCase();
  363. };
  364. function createCommonjsModule(fn, basedir, module) {
  365. return module = {
  366. path: basedir,
  367. exports: {},
  368. require: function (path, base) {
  369. return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
  370. }
  371. }, fn(module, module.exports), module.exports;
  372. }
  373. function getCjsExportFromNamespace (n) {
  374. return n && n['default'] || n;
  375. }
  376. function commonjsRequire () {
  377. throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
  378. }
  379. var colorName = {
  380. "aliceblue": [240, 248, 255],
  381. "antiquewhite": [250, 235, 215],
  382. "aqua": [0, 255, 255],
  383. "aquamarine": [127, 255, 212],
  384. "azure": [240, 255, 255],
  385. "beige": [245, 245, 220],
  386. "bisque": [255, 228, 196],
  387. "black": [0, 0, 0],
  388. "blanchedalmond": [255, 235, 205],
  389. "blue": [0, 0, 255],
  390. "blueviolet": [138, 43, 226],
  391. "brown": [165, 42, 42],
  392. "burlywood": [222, 184, 135],
  393. "cadetblue": [95, 158, 160],
  394. "chartreuse": [127, 255, 0],
  395. "chocolate": [210, 105, 30],
  396. "coral": [255, 127, 80],
  397. "cornflowerblue": [100, 149, 237],
  398. "cornsilk": [255, 248, 220],
  399. "crimson": [220, 20, 60],
  400. "cyan": [0, 255, 255],
  401. "darkblue": [0, 0, 139],
  402. "darkcyan": [0, 139, 139],
  403. "darkgoldenrod": [184, 134, 11],
  404. "darkgray": [169, 169, 169],
  405. "darkgreen": [0, 100, 0],
  406. "darkgrey": [169, 169, 169],
  407. "darkkhaki": [189, 183, 107],
  408. "darkmagenta": [139, 0, 139],
  409. "darkolivegreen": [85, 107, 47],
  410. "darkorange": [255, 140, 0],
  411. "darkorchid": [153, 50, 204],
  412. "darkred": [139, 0, 0],
  413. "darksalmon": [233, 150, 122],
  414. "darkseagreen": [143, 188, 143],
  415. "darkslateblue": [72, 61, 139],
  416. "darkslategray": [47, 79, 79],
  417. "darkslategrey": [47, 79, 79],
  418. "darkturquoise": [0, 206, 209],
  419. "darkviolet": [148, 0, 211],
  420. "deeppink": [255, 20, 147],
  421. "deepskyblue": [0, 191, 255],
  422. "dimgray": [105, 105, 105],
  423. "dimgrey": [105, 105, 105],
  424. "dodgerblue": [30, 144, 255],
  425. "firebrick": [178, 34, 34],
  426. "floralwhite": [255, 250, 240],
  427. "forestgreen": [34, 139, 34],
  428. "fuchsia": [255, 0, 255],
  429. "gainsboro": [220, 220, 220],
  430. "ghostwhite": [248, 248, 255],
  431. "gold": [255, 215, 0],
  432. "goldenrod": [218, 165, 32],
  433. "gray": [128, 128, 128],
  434. "green": [0, 128, 0],
  435. "greenyellow": [173, 255, 47],
  436. "grey": [128, 128, 128],
  437. "honeydew": [240, 255, 240],
  438. "hotpink": [255, 105, 180],
  439. "indianred": [205, 92, 92],
  440. "indigo": [75, 0, 130],
  441. "ivory": [255, 255, 240],
  442. "khaki": [240, 230, 140],
  443. "lavender": [230, 230, 250],
  444. "lavenderblush": [255, 240, 245],
  445. "lawngreen": [124, 252, 0],
  446. "lemonchiffon": [255, 250, 205],
  447. "lightblue": [173, 216, 230],
  448. "lightcoral": [240, 128, 128],
  449. "lightcyan": [224, 255, 255],
  450. "lightgoldenrodyellow": [250, 250, 210],
  451. "lightgray": [211, 211, 211],
  452. "lightgreen": [144, 238, 144],
  453. "lightgrey": [211, 211, 211],
  454. "lightpink": [255, 182, 193],
  455. "lightsalmon": [255, 160, 122],
  456. "lightseagreen": [32, 178, 170],
  457. "lightskyblue": [135, 206, 250],
  458. "lightslategray": [119, 136, 153],
  459. "lightslategrey": [119, 136, 153],
  460. "lightsteelblue": [176, 196, 222],
  461. "lightyellow": [255, 255, 224],
  462. "lime": [0, 255, 0],
  463. "limegreen": [50, 205, 50],
  464. "linen": [250, 240, 230],
  465. "magenta": [255, 0, 255],
  466. "maroon": [128, 0, 0],
  467. "mediumaquamarine": [102, 205, 170],
  468. "mediumblue": [0, 0, 205],
  469. "mediumorchid": [186, 85, 211],
  470. "mediumpurple": [147, 112, 219],
  471. "mediumseagreen": [60, 179, 113],
  472. "mediumslateblue": [123, 104, 238],
  473. "mediumspringgreen": [0, 250, 154],
  474. "mediumturquoise": [72, 209, 204],
  475. "mediumvioletred": [199, 21, 133],
  476. "midnightblue": [25, 25, 112],
  477. "mintcream": [245, 255, 250],
  478. "mistyrose": [255, 228, 225],
  479. "moccasin": [255, 228, 181],
  480. "navajowhite": [255, 222, 173],
  481. "navy": [0, 0, 128],
  482. "oldlace": [253, 245, 230],
  483. "olive": [128, 128, 0],
  484. "olivedrab": [107, 142, 35],
  485. "orange": [255, 165, 0],
  486. "orangered": [255, 69, 0],
  487. "orchid": [218, 112, 214],
  488. "palegoldenrod": [238, 232, 170],
  489. "palegreen": [152, 251, 152],
  490. "paleturquoise": [175, 238, 238],
  491. "palevioletred": [219, 112, 147],
  492. "papayawhip": [255, 239, 213],
  493. "peachpuff": [255, 218, 185],
  494. "peru": [205, 133, 63],
  495. "pink": [255, 192, 203],
  496. "plum": [221, 160, 221],
  497. "powderblue": [176, 224, 230],
  498. "purple": [128, 0, 128],
  499. "rebeccapurple": [102, 51, 153],
  500. "red": [255, 0, 0],
  501. "rosybrown": [188, 143, 143],
  502. "royalblue": [65, 105, 225],
  503. "saddlebrown": [139, 69, 19],
  504. "salmon": [250, 128, 114],
  505. "sandybrown": [244, 164, 96],
  506. "seagreen": [46, 139, 87],
  507. "seashell": [255, 245, 238],
  508. "sienna": [160, 82, 45],
  509. "silver": [192, 192, 192],
  510. "skyblue": [135, 206, 235],
  511. "slateblue": [106, 90, 205],
  512. "slategray": [112, 128, 144],
  513. "slategrey": [112, 128, 144],
  514. "snow": [255, 250, 250],
  515. "springgreen": [0, 255, 127],
  516. "steelblue": [70, 130, 180],
  517. "tan": [210, 180, 140],
  518. "teal": [0, 128, 128],
  519. "thistle": [216, 191, 216],
  520. "tomato": [255, 99, 71],
  521. "turquoise": [64, 224, 208],
  522. "violet": [238, 130, 238],
  523. "wheat": [245, 222, 179],
  524. "white": [255, 255, 255],
  525. "whitesmoke": [245, 245, 245],
  526. "yellow": [255, 255, 0],
  527. "yellowgreen": [154, 205, 50]
  528. };
  529. /* MIT license */
  530. /* eslint-disable no-mixed-operators */
  531. // NOTE: conversions should only return primitive values (i.e. arrays, or
  532. // values that give correct `typeof` results).
  533. // do not use box values types (i.e. Number(), String(), etc.)
  534. const reverseKeywords = {};
  535. for (const key of Object.keys(colorName)) {
  536. reverseKeywords[colorName[key]] = key;
  537. }
  538. const convert = {
  539. rgb: {
  540. channels: 3,
  541. labels: 'rgb'
  542. },
  543. hsl: {
  544. channels: 3,
  545. labels: 'hsl'
  546. },
  547. hsv: {
  548. channels: 3,
  549. labels: 'hsv'
  550. },
  551. hwb: {
  552. channels: 3,
  553. labels: 'hwb'
  554. },
  555. cmyk: {
  556. channels: 4,
  557. labels: 'cmyk'
  558. },
  559. xyz: {
  560. channels: 3,
  561. labels: 'xyz'
  562. },
  563. lab: {
  564. channels: 3,
  565. labels: 'lab'
  566. },
  567. lch: {
  568. channels: 3,
  569. labels: 'lch'
  570. },
  571. hex: {
  572. channels: 1,
  573. labels: ['hex']
  574. },
  575. keyword: {
  576. channels: 1,
  577. labels: ['keyword']
  578. },
  579. ansi16: {
  580. channels: 1,
  581. labels: ['ansi16']
  582. },
  583. ansi256: {
  584. channels: 1,
  585. labels: ['ansi256']
  586. },
  587. hcg: {
  588. channels: 3,
  589. labels: ['h', 'c', 'g']
  590. },
  591. apple: {
  592. channels: 3,
  593. labels: ['r16', 'g16', 'b16']
  594. },
  595. gray: {
  596. channels: 1,
  597. labels: ['gray']
  598. }
  599. };
  600. var conversions = convert; // Hide .channels and .labels properties
  601. for (const model of Object.keys(convert)) {
  602. if (!('channels' in convert[model])) {
  603. throw new Error('missing channels property: ' + model);
  604. }
  605. if (!('labels' in convert[model])) {
  606. throw new Error('missing channel labels property: ' + model);
  607. }
  608. if (convert[model].labels.length !== convert[model].channels) {
  609. throw new Error('channel and label counts mismatch: ' + model);
  610. }
  611. const {
  612. channels,
  613. labels
  614. } = convert[model];
  615. delete convert[model].channels;
  616. delete convert[model].labels;
  617. Object.defineProperty(convert[model], 'channels', {
  618. value: channels
  619. });
  620. Object.defineProperty(convert[model], 'labels', {
  621. value: labels
  622. });
  623. }
  624. convert.rgb.hsl = function (rgb) {
  625. const r = rgb[0] / 255;
  626. const g = rgb[1] / 255;
  627. const b = rgb[2] / 255;
  628. const min = Math.min(r, g, b);
  629. const max = Math.max(r, g, b);
  630. const delta = max - min;
  631. let h;
  632. let s;
  633. if (max === min) {
  634. h = 0;
  635. } else if (r === max) {
  636. h = (g - b) / delta;
  637. } else if (g === max) {
  638. h = 2 + (b - r) / delta;
  639. } else if (b === max) {
  640. h = 4 + (r - g) / delta;
  641. }
  642. h = Math.min(h * 60, 360);
  643. if (h < 0) {
  644. h += 360;
  645. }
  646. const l = (min + max) / 2;
  647. if (max === min) {
  648. s = 0;
  649. } else if (l <= 0.5) {
  650. s = delta / (max + min);
  651. } else {
  652. s = delta / (2 - max - min);
  653. }
  654. return [h, s * 100, l * 100];
  655. };
  656. convert.rgb.hsv = function (rgb) {
  657. let rdif;
  658. let gdif;
  659. let bdif;
  660. let h;
  661. let s;
  662. const r = rgb[0] / 255;
  663. const g = rgb[1] / 255;
  664. const b = rgb[2] / 255;
  665. const v = Math.max(r, g, b);
  666. const diff = v - Math.min(r, g, b);
  667. const diffc = function (c) {
  668. return (v - c) / 6 / diff + 1 / 2;
  669. };
  670. if (diff === 0) {
  671. h = 0;
  672. s = 0;
  673. } else {
  674. s = diff / v;
  675. rdif = diffc(r);
  676. gdif = diffc(g);
  677. bdif = diffc(b);
  678. if (r === v) {
  679. h = bdif - gdif;
  680. } else if (g === v) {
  681. h = 1 / 3 + rdif - bdif;
  682. } else if (b === v) {
  683. h = 2 / 3 + gdif - rdif;
  684. }
  685. if (h < 0) {
  686. h += 1;
  687. } else if (h > 1) {
  688. h -= 1;
  689. }
  690. }
  691. return [h * 360, s * 100, v * 100];
  692. };
  693. convert.rgb.hwb = function (rgb) {
  694. const r = rgb[0];
  695. const g = rgb[1];
  696. let b = rgb[2];
  697. const h = convert.rgb.hsl(rgb)[0];
  698. const w = 1 / 255 * Math.min(r, Math.min(g, b));
  699. b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
  700. return [h, w * 100, b * 100];
  701. };
  702. convert.rgb.cmyk = function (rgb) {
  703. const r = rgb[0] / 255;
  704. const g = rgb[1] / 255;
  705. const b = rgb[2] / 255;
  706. const k = Math.min(1 - r, 1 - g, 1 - b);
  707. const c = (1 - r - k) / (1 - k) || 0;
  708. const m = (1 - g - k) / (1 - k) || 0;
  709. const y = (1 - b - k) / (1 - k) || 0;
  710. return [c * 100, m * 100, y * 100, k * 100];
  711. };
  712. function comparativeDistance(x, y) {
  713. /*
  714. See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
  715. */
  716. return (x[0] - y[0]) ** 2 + (x[1] - y[1]) ** 2 + (x[2] - y[2]) ** 2;
  717. }
  718. convert.rgb.keyword = function (rgb) {
  719. const reversed = reverseKeywords[rgb];
  720. if (reversed) {
  721. return reversed;
  722. }
  723. let currentClosestDistance = Infinity;
  724. let currentClosestKeyword;
  725. for (const keyword of Object.keys(colorName)) {
  726. const value = colorName[keyword]; // Compute comparative distance
  727. const distance = comparativeDistance(rgb, value); // Check if its less, if so set as closest
  728. if (distance < currentClosestDistance) {
  729. currentClosestDistance = distance;
  730. currentClosestKeyword = keyword;
  731. }
  732. }
  733. return currentClosestKeyword;
  734. };
  735. convert.keyword.rgb = function (keyword) {
  736. return colorName[keyword];
  737. };
  738. convert.rgb.xyz = function (rgb) {
  739. let r = rgb[0] / 255;
  740. let g = rgb[1] / 255;
  741. let b = rgb[2] / 255; // Assume sRGB
  742. r = r > 0.04045 ? ((r + 0.055) / 1.055) ** 2.4 : r / 12.92;
  743. g = g > 0.04045 ? ((g + 0.055) / 1.055) ** 2.4 : g / 12.92;
  744. b = b > 0.04045 ? ((b + 0.055) / 1.055) ** 2.4 : b / 12.92;
  745. const x = r * 0.4124 + g * 0.3576 + b * 0.1805;
  746. const y = r * 0.2126 + g * 0.7152 + b * 0.0722;
  747. const z = r * 0.0193 + g * 0.1192 + b * 0.9505;
  748. return [x * 100, y * 100, z * 100];
  749. };
  750. convert.rgb.lab = function (rgb) {
  751. const xyz = convert.rgb.xyz(rgb);
  752. let x = xyz[0];
  753. let y = xyz[1];
  754. let z = xyz[2];
  755. x /= 95.047;
  756. y /= 100;
  757. z /= 108.883;
  758. x = x > 0.008856 ? x ** (1 / 3) : 7.787 * x + 16 / 116;
  759. y = y > 0.008856 ? y ** (1 / 3) : 7.787 * y + 16 / 116;
  760. z = z > 0.008856 ? z ** (1 / 3) : 7.787 * z + 16 / 116;
  761. const l = 116 * y - 16;
  762. const a = 500 * (x - y);
  763. const b = 200 * (y - z);
  764. return [l, a, b];
  765. };
  766. convert.hsl.rgb = function (hsl) {
  767. const h = hsl[0] / 360;
  768. const s = hsl[1] / 100;
  769. const l = hsl[2] / 100;
  770. let t2;
  771. let t3;
  772. let val;
  773. if (s === 0) {
  774. val = l * 255;
  775. return [val, val, val];
  776. }
  777. if (l < 0.5) {
  778. t2 = l * (1 + s);
  779. } else {
  780. t2 = l + s - l * s;
  781. }
  782. const t1 = 2 * l - t2;
  783. const rgb = [0, 0, 0];
  784. for (let i = 0; i < 3; i++) {
  785. t3 = h + 1 / 3 * -(i - 1);
  786. if (t3 < 0) {
  787. t3++;
  788. }
  789. if (t3 > 1) {
  790. t3--;
  791. }
  792. if (6 * t3 < 1) {
  793. val = t1 + (t2 - t1) * 6 * t3;
  794. } else if (2 * t3 < 1) {
  795. val = t2;
  796. } else if (3 * t3 < 2) {
  797. val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
  798. } else {
  799. val = t1;
  800. }
  801. rgb[i] = val * 255;
  802. }
  803. return rgb;
  804. };
  805. convert.hsl.hsv = function (hsl) {
  806. const h = hsl[0];
  807. let s = hsl[1] / 100;
  808. let l = hsl[2] / 100;
  809. let smin = s;
  810. const lmin = Math.max(l, 0.01);
  811. l *= 2;
  812. s *= l <= 1 ? l : 2 - l;
  813. smin *= lmin <= 1 ? lmin : 2 - lmin;
  814. const v = (l + s) / 2;
  815. const sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s);
  816. return [h, sv * 100, v * 100];
  817. };
  818. convert.hsv.rgb = function (hsv) {
  819. const h = hsv[0] / 60;
  820. const s = hsv[1] / 100;
  821. let v = hsv[2] / 100;
  822. const hi = Math.floor(h) % 6;
  823. const f = h - Math.floor(h);
  824. const p = 255 * v * (1 - s);
  825. const q = 255 * v * (1 - s * f);
  826. const t = 255 * v * (1 - s * (1 - f));
  827. v *= 255;
  828. switch (hi) {
  829. case 0:
  830. return [v, t, p];
  831. case 1:
  832. return [q, v, p];
  833. case 2:
  834. return [p, v, t];
  835. case 3:
  836. return [p, q, v];
  837. case 4:
  838. return [t, p, v];
  839. case 5:
  840. return [v, p, q];
  841. }
  842. };
  843. convert.hsv.hsl = function (hsv) {
  844. const h = hsv[0];
  845. const s = hsv[1] / 100;
  846. const v = hsv[2] / 100;
  847. const vmin = Math.max(v, 0.01);
  848. let sl;
  849. let l;
  850. l = (2 - s) * v;
  851. const lmin = (2 - s) * vmin;
  852. sl = s * vmin;
  853. sl /= lmin <= 1 ? lmin : 2 - lmin;
  854. sl = sl || 0;
  855. l /= 2;
  856. return [h, sl * 100, l * 100];
  857. }; // http://dev.w3.org/csswg/css-color/#hwb-to-rgb
  858. convert.hwb.rgb = function (hwb) {
  859. const h = hwb[0] / 360;
  860. let wh = hwb[1] / 100;
  861. let bl = hwb[2] / 100;
  862. const ratio = wh + bl;
  863. let f; // Wh + bl cant be > 1
  864. if (ratio > 1) {
  865. wh /= ratio;
  866. bl /= ratio;
  867. }
  868. const i = Math.floor(6 * h);
  869. const v = 1 - bl;
  870. f = 6 * h - i;
  871. if ((i & 0x01) !== 0) {
  872. f = 1 - f;
  873. }
  874. const n = wh + f * (v - wh); // Linear interpolation
  875. let r;
  876. let g;
  877. let b;
  878. /* eslint-disable max-statements-per-line,no-multi-spaces */
  879. switch (i) {
  880. default:
  881. case 6:
  882. case 0:
  883. r = v;
  884. g = n;
  885. b = wh;
  886. break;
  887. case 1:
  888. r = n;
  889. g = v;
  890. b = wh;
  891. break;
  892. case 2:
  893. r = wh;
  894. g = v;
  895. b = n;
  896. break;
  897. case 3:
  898. r = wh;
  899. g = n;
  900. b = v;
  901. break;
  902. case 4:
  903. r = n;
  904. g = wh;
  905. b = v;
  906. break;
  907. case 5:
  908. r = v;
  909. g = wh;
  910. b = n;
  911. break;
  912. }
  913. /* eslint-enable max-statements-per-line,no-multi-spaces */
  914. return [r * 255, g * 255, b * 255];
  915. };
  916. convert.cmyk.rgb = function (cmyk) {
  917. const c = cmyk[0] / 100;
  918. const m = cmyk[1] / 100;
  919. const y = cmyk[2] / 100;
  920. const k = cmyk[3] / 100;
  921. const r = 1 - Math.min(1, c * (1 - k) + k);
  922. const g = 1 - Math.min(1, m * (1 - k) + k);
  923. const b = 1 - Math.min(1, y * (1 - k) + k);
  924. return [r * 255, g * 255, b * 255];
  925. };
  926. convert.xyz.rgb = function (xyz) {
  927. const x = xyz[0] / 100;
  928. const y = xyz[1] / 100;
  929. const z = xyz[2] / 100;
  930. let r;
  931. let g;
  932. let b;
  933. r = x * 3.2406 + y * -1.5372 + z * -0.4986;
  934. g = x * -0.9689 + y * 1.8758 + z * 0.0415;
  935. b = x * 0.0557 + y * -0.2040 + z * 1.0570; // Assume sRGB
  936. r = r > 0.0031308 ? 1.055 * r ** (1.0 / 2.4) - 0.055 : r * 12.92;
  937. g = g > 0.0031308 ? 1.055 * g ** (1.0 / 2.4) - 0.055 : g * 12.92;
  938. b = b > 0.0031308 ? 1.055 * b ** (1.0 / 2.4) - 0.055 : b * 12.92;
  939. r = Math.min(Math.max(0, r), 1);
  940. g = Math.min(Math.max(0, g), 1);
  941. b = Math.min(Math.max(0, b), 1);
  942. return [r * 255, g * 255, b * 255];
  943. };
  944. convert.xyz.lab = function (xyz) {
  945. let x = xyz[0];
  946. let y = xyz[1];
  947. let z = xyz[2];
  948. x /= 95.047;
  949. y /= 100;
  950. z /= 108.883;
  951. x = x > 0.008856 ? x ** (1 / 3) : 7.787 * x + 16 / 116;
  952. y = y > 0.008856 ? y ** (1 / 3) : 7.787 * y + 16 / 116;
  953. z = z > 0.008856 ? z ** (1 / 3) : 7.787 * z + 16 / 116;
  954. const l = 116 * y - 16;
  955. const a = 500 * (x - y);
  956. const b = 200 * (y - z);
  957. return [l, a, b];
  958. };
  959. convert.lab.xyz = function (lab) {
  960. const l = lab[0];
  961. const a = lab[1];
  962. const b = lab[2];
  963. let x;
  964. let y;
  965. let z;
  966. y = (l + 16) / 116;
  967. x = a / 500 + y;
  968. z = y - b / 200;
  969. const y2 = y ** 3;
  970. const x2 = x ** 3;
  971. const z2 = z ** 3;
  972. y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
  973. x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
  974. z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
  975. x *= 95.047;
  976. y *= 100;
  977. z *= 108.883;
  978. return [x, y, z];
  979. };
  980. convert.lab.lch = function (lab) {
  981. const l = lab[0];
  982. const a = lab[1];
  983. const b = lab[2];
  984. let h;
  985. const hr = Math.atan2(b, a);
  986. h = hr * 360 / 2 / Math.PI;
  987. if (h < 0) {
  988. h += 360;
  989. }
  990. const c = Math.sqrt(a * a + b * b);
  991. return [l, c, h];
  992. };
  993. convert.lch.lab = function (lch) {
  994. const l = lch[0];
  995. const c = lch[1];
  996. const h = lch[2];
  997. const hr = h / 360 * 2 * Math.PI;
  998. const a = c * Math.cos(hr);
  999. const b = c * Math.sin(hr);
  1000. return [l, a, b];
  1001. };
  1002. convert.rgb.ansi16 = function (args, saturation = null) {
  1003. const [r, g, b] = args;
  1004. let value = saturation === null ? convert.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization
  1005. value = Math.round(value / 50);
  1006. if (value === 0) {
  1007. return 30;
  1008. }
  1009. let ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255));
  1010. if (value === 2) {
  1011. ansi += 60;
  1012. }
  1013. return ansi;
  1014. };
  1015. convert.hsv.ansi16 = function (args) {
  1016. // Optimization here; we already know the value and don't need to get
  1017. // it converted for us.
  1018. return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);
  1019. };
  1020. convert.rgb.ansi256 = function (args) {
  1021. const r = args[0];
  1022. const g = args[1];
  1023. const b = args[2]; // We use the extended greyscale palette here, with the exception of
  1024. // black and white. normal palette only has 4 greyscale shades.
  1025. if (r === g && g === b) {
  1026. if (r < 8) {
  1027. return 16;
  1028. }
  1029. if (r > 248) {
  1030. return 231;
  1031. }
  1032. return Math.round((r - 8) / 247 * 24) + 232;
  1033. }
  1034. const ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5);
  1035. return ansi;
  1036. };
  1037. convert.ansi16.rgb = function (args) {
  1038. let color = args % 10; // Handle greyscale
  1039. if (color === 0 || color === 7) {
  1040. if (args > 50) {
  1041. color += 3.5;
  1042. }
  1043. color = color / 10.5 * 255;
  1044. return [color, color, color];
  1045. }
  1046. const mult = (~~(args > 50) + 1) * 0.5;
  1047. const r = (color & 1) * mult * 255;
  1048. const g = (color >> 1 & 1) * mult * 255;
  1049. const b = (color >> 2 & 1) * mult * 255;
  1050. return [r, g, b];
  1051. };
  1052. convert.ansi256.rgb = function (args) {
  1053. // Handle greyscale
  1054. if (args >= 232) {
  1055. const c = (args - 232) * 10 + 8;
  1056. return [c, c, c];
  1057. }
  1058. args -= 16;
  1059. let rem;
  1060. const r = Math.floor(args / 36) / 5 * 255;
  1061. const g = Math.floor((rem = args % 36) / 6) / 5 * 255;
  1062. const b = rem % 6 / 5 * 255;
  1063. return [r, g, b];
  1064. };
  1065. convert.rgb.hex = function (args) {
  1066. const integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF);
  1067. const string = integer.toString(16).toUpperCase();
  1068. return '000000'.substring(string.length) + string;
  1069. };
  1070. convert.hex.rgb = function (args) {
  1071. const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
  1072. if (!match) {
  1073. return [0, 0, 0];
  1074. }
  1075. let colorString = match[0];
  1076. if (match[0].length === 3) {
  1077. colorString = colorString.split('').map(char => {
  1078. return char + char;
  1079. }).join('');
  1080. }
  1081. const integer = parseInt(colorString, 16);
  1082. const r = integer >> 16 & 0xFF;
  1083. const g = integer >> 8 & 0xFF;
  1084. const b = integer & 0xFF;
  1085. return [r, g, b];
  1086. };
  1087. convert.rgb.hcg = function (rgb) {
  1088. const r = rgb[0] / 255;
  1089. const g = rgb[1] / 255;
  1090. const b = rgb[2] / 255;
  1091. const max = Math.max(Math.max(r, g), b);
  1092. const min = Math.min(Math.min(r, g), b);
  1093. const chroma = max - min;
  1094. let grayscale;
  1095. let hue;
  1096. if (chroma < 1) {
  1097. grayscale = min / (1 - chroma);
  1098. } else {
  1099. grayscale = 0;
  1100. }
  1101. if (chroma <= 0) {
  1102. hue = 0;
  1103. } else if (max === r) {
  1104. hue = (g - b) / chroma % 6;
  1105. } else if (max === g) {
  1106. hue = 2 + (b - r) / chroma;
  1107. } else {
  1108. hue = 4 + (r - g) / chroma;
  1109. }
  1110. hue /= 6;
  1111. hue %= 1;
  1112. return [hue * 360, chroma * 100, grayscale * 100];
  1113. };
  1114. convert.hsl.hcg = function (hsl) {
  1115. const s = hsl[1] / 100;
  1116. const l = hsl[2] / 100;
  1117. const c = l < 0.5 ? 2.0 * s * l : 2.0 * s * (1.0 - l);
  1118. let f = 0;
  1119. if (c < 1.0) {
  1120. f = (l - 0.5 * c) / (1.0 - c);
  1121. }
  1122. return [hsl[0], c * 100, f * 100];
  1123. };
  1124. convert.hsv.hcg = function (hsv) {
  1125. const s = hsv[1] / 100;
  1126. const v = hsv[2] / 100;
  1127. const c = s * v;
  1128. let f = 0;
  1129. if (c < 1.0) {
  1130. f = (v - c) / (1 - c);
  1131. }
  1132. return [hsv[0], c * 100, f * 100];
  1133. };
  1134. convert.hcg.rgb = function (hcg) {
  1135. const h = hcg[0] / 360;
  1136. const c = hcg[1] / 100;
  1137. const g = hcg[2] / 100;
  1138. if (c === 0.0) {
  1139. return [g * 255, g * 255, g * 255];
  1140. }
  1141. const pure = [0, 0, 0];
  1142. const hi = h % 1 * 6;
  1143. const v = hi % 1;
  1144. const w = 1 - v;
  1145. let mg = 0;
  1146. /* eslint-disable max-statements-per-line */
  1147. switch (Math.floor(hi)) {
  1148. case 0:
  1149. pure[0] = 1;
  1150. pure[1] = v;
  1151. pure[2] = 0;
  1152. break;
  1153. case 1:
  1154. pure[0] = w;
  1155. pure[1] = 1;
  1156. pure[2] = 0;
  1157. break;
  1158. case 2:
  1159. pure[0] = 0;
  1160. pure[1] = 1;
  1161. pure[2] = v;
  1162. break;
  1163. case 3:
  1164. pure[0] = 0;
  1165. pure[1] = w;
  1166. pure[2] = 1;
  1167. break;
  1168. case 4:
  1169. pure[0] = v;
  1170. pure[1] = 0;
  1171. pure[2] = 1;
  1172. break;
  1173. default:
  1174. pure[0] = 1;
  1175. pure[1] = 0;
  1176. pure[2] = w;
  1177. }
  1178. /* eslint-enable max-statements-per-line */
  1179. mg = (1.0 - c) * g;
  1180. return [(c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255];
  1181. };
  1182. convert.hcg.hsv = function (hcg) {
  1183. const c = hcg[1] / 100;
  1184. const g = hcg[2] / 100;
  1185. const v = c + g * (1.0 - c);
  1186. let f = 0;
  1187. if (v > 0.0) {
  1188. f = c / v;
  1189. }
  1190. return [hcg[0], f * 100, v * 100];
  1191. };
  1192. convert.hcg.hsl = function (hcg) {
  1193. const c = hcg[1] / 100;
  1194. const g = hcg[2] / 100;
  1195. const l = g * (1.0 - c) + 0.5 * c;
  1196. let s = 0;
  1197. if (l > 0.0 && l < 0.5) {
  1198. s = c / (2 * l);
  1199. } else if (l >= 0.5 && l < 1.0) {
  1200. s = c / (2 * (1 - l));
  1201. }
  1202. return [hcg[0], s * 100, l * 100];
  1203. };
  1204. convert.hcg.hwb = function (hcg) {
  1205. const c = hcg[1] / 100;
  1206. const g = hcg[2] / 100;
  1207. const v = c + g * (1.0 - c);
  1208. return [hcg[0], (v - c) * 100, (1 - v) * 100];
  1209. };
  1210. convert.hwb.hcg = function (hwb) {
  1211. const w = hwb[1] / 100;
  1212. const b = hwb[2] / 100;
  1213. const v = 1 - b;
  1214. const c = v - w;
  1215. let g = 0;
  1216. if (c < 1) {
  1217. g = (v - c) / (1 - c);
  1218. }
  1219. return [hwb[0], c * 100, g * 100];
  1220. };
  1221. convert.apple.rgb = function (apple) {
  1222. return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255];
  1223. };
  1224. convert.rgb.apple = function (rgb) {
  1225. return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535];
  1226. };
  1227. convert.gray.rgb = function (args) {
  1228. return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
  1229. };
  1230. convert.gray.hsl = function (args) {
  1231. return [0, 0, args[0]];
  1232. };
  1233. convert.gray.hsv = convert.gray.hsl;
  1234. convert.gray.hwb = function (gray) {
  1235. return [0, 100, gray[0]];
  1236. };
  1237. convert.gray.cmyk = function (gray) {
  1238. return [0, 0, 0, gray[0]];
  1239. };
  1240. convert.gray.lab = function (gray) {
  1241. return [gray[0], 0, 0];
  1242. };
  1243. convert.gray.hex = function (gray) {
  1244. const val = Math.round(gray[0] / 100 * 255) & 0xFF;
  1245. const integer = (val << 16) + (val << 8) + val;
  1246. const string = integer.toString(16).toUpperCase();
  1247. return '000000'.substring(string.length) + string;
  1248. };
  1249. convert.rgb.gray = function (rgb) {
  1250. const val = (rgb[0] + rgb[1] + rgb[2]) / 3;
  1251. return [val / 255 * 100];
  1252. };
  1253. /*
  1254. This function routes a model to all other models.
  1255. all functions that are routed have a property `.conversion` attached
  1256. to the returned synthetic function. This property is an array
  1257. of strings, each with the steps in between the 'from' and 'to'
  1258. color models (inclusive).
  1259. conversions that are not possible simply are not included.
  1260. */
  1261. function buildGraph() {
  1262. const graph = {}; // https://jsperf.com/object-keys-vs-for-in-with-closure/3
  1263. const models = Object.keys(conversions);
  1264. for (let len = models.length, i = 0; i < len; i++) {
  1265. graph[models[i]] = {
  1266. // http://jsperf.com/1-vs-infinity
  1267. // micro-opt, but this is simple.
  1268. distance: -1,
  1269. parent: null
  1270. };
  1271. }
  1272. return graph;
  1273. } // https://en.wikipedia.org/wiki/Breadth-first_search
  1274. function deriveBFS(fromModel) {
  1275. const graph = buildGraph();
  1276. const queue = [fromModel]; // Unshift -> queue -> pop
  1277. graph[fromModel].distance = 0;
  1278. while (queue.length) {
  1279. const current = queue.pop();
  1280. const adjacents = Object.keys(conversions[current]);
  1281. for (let len = adjacents.length, i = 0; i < len; i++) {
  1282. const adjacent = adjacents[i];
  1283. const node = graph[adjacent];
  1284. if (node.distance === -1) {
  1285. node.distance = graph[current].distance + 1;
  1286. node.parent = current;
  1287. queue.unshift(adjacent);
  1288. }
  1289. }
  1290. }
  1291. return graph;
  1292. }
  1293. function link(from, to) {
  1294. return function (args) {
  1295. return to(from(args));
  1296. };
  1297. }
  1298. function wrapConversion(toModel, graph) {
  1299. const path = [graph[toModel].parent, toModel];
  1300. let fn = conversions[graph[toModel].parent][toModel];
  1301. let cur = graph[toModel].parent;
  1302. while (graph[cur].parent) {
  1303. path.unshift(graph[cur].parent);
  1304. fn = link(conversions[graph[cur].parent][cur], fn);
  1305. cur = graph[cur].parent;
  1306. }
  1307. fn.conversion = path;
  1308. return fn;
  1309. }
  1310. var route = function (fromModel) {
  1311. const graph = deriveBFS(fromModel);
  1312. const conversion = {};
  1313. const models = Object.keys(graph);
  1314. for (let len = models.length, i = 0; i < len; i++) {
  1315. const toModel = models[i];
  1316. const node = graph[toModel];
  1317. if (node.parent === null) {
  1318. // No possible conversion, or this node is the source model.
  1319. continue;
  1320. }
  1321. conversion[toModel] = wrapConversion(toModel, graph);
  1322. }
  1323. return conversion;
  1324. };
  1325. const convert$1 = {};
  1326. const models = Object.keys(conversions);
  1327. function wrapRaw(fn) {
  1328. const wrappedFn = function (...args) {
  1329. const arg0 = args[0];
  1330. if (arg0 === undefined || arg0 === null) {
  1331. return arg0;
  1332. }
  1333. if (arg0.length > 1) {
  1334. args = arg0;
  1335. }
  1336. return fn(args);
  1337. }; // Preserve .conversion property if there is one
  1338. if ('conversion' in fn) {
  1339. wrappedFn.conversion = fn.conversion;
  1340. }
  1341. return wrappedFn;
  1342. }
  1343. function wrapRounded(fn) {
  1344. const wrappedFn = function (...args) {
  1345. const arg0 = args[0];
  1346. if (arg0 === undefined || arg0 === null) {
  1347. return arg0;
  1348. }
  1349. if (arg0.length > 1) {
  1350. args = arg0;
  1351. }
  1352. const result = fn(args); // We're assuming the result is an array here.
  1353. // see notice in conversions.js; don't use box types
  1354. // in conversion functions.
  1355. if (typeof result === 'object') {
  1356. for (let len = result.length, i = 0; i < len; i++) {
  1357. result[i] = Math.round(result[i]);
  1358. }
  1359. }
  1360. return result;
  1361. }; // Preserve .conversion property if there is one
  1362. if ('conversion' in fn) {
  1363. wrappedFn.conversion = fn.conversion;
  1364. }
  1365. return wrappedFn;
  1366. }
  1367. models.forEach(fromModel => {
  1368. convert$1[fromModel] = {};
  1369. Object.defineProperty(convert$1[fromModel], 'channels', {
  1370. value: conversions[fromModel].channels
  1371. });
  1372. Object.defineProperty(convert$1[fromModel], 'labels', {
  1373. value: conversions[fromModel].labels
  1374. });
  1375. const routes = route(fromModel);
  1376. const routeModels = Object.keys(routes);
  1377. routeModels.forEach(toModel => {
  1378. const fn = routes[toModel];
  1379. convert$1[fromModel][toModel] = wrapRounded(fn);
  1380. convert$1[fromModel][toModel].raw = wrapRaw(fn);
  1381. });
  1382. });
  1383. var colorConvert = convert$1;
  1384. var ansiStyles = createCommonjsModule(function (module) {
  1385. const wrapAnsi16 = (fn, offset) => (...args) => {
  1386. const code = fn(...args);
  1387. return `\u001B[${code + offset}m`;
  1388. };
  1389. const wrapAnsi256 = (fn, offset) => (...args) => {
  1390. const code = fn(...args);
  1391. return `\u001B[${38 + offset};5;${code}m`;
  1392. };
  1393. const wrapAnsi16m = (fn, offset) => (...args) => {
  1394. const rgb = fn(...args);
  1395. return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
  1396. };
  1397. const ansi2ansi = n => n;
  1398. const rgb2rgb = (r, g, b) => [r, g, b];
  1399. const setLazyProperty = (object, property, get) => {
  1400. Object.defineProperty(object, property, {
  1401. get: () => {
  1402. const value = get();
  1403. Object.defineProperty(object, property, {
  1404. value,
  1405. enumerable: true,
  1406. configurable: true
  1407. });
  1408. return value;
  1409. },
  1410. enumerable: true,
  1411. configurable: true
  1412. });
  1413. };
  1414. /** @type {typeof import('color-convert')} */
  1415. let colorConvert$1;
  1416. const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => {
  1417. if (colorConvert$1 === undefined) {
  1418. colorConvert$1 = colorConvert;
  1419. }
  1420. const offset = isBackground ? 10 : 0;
  1421. const styles = {};
  1422. for (const [sourceSpace, suite] of Object.entries(colorConvert$1)) {
  1423. const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace;
  1424. if (sourceSpace === targetSpace) {
  1425. styles[name] = wrap(identity, offset);
  1426. } else if (typeof suite === 'object') {
  1427. styles[name] = wrap(suite[targetSpace], offset);
  1428. }
  1429. }
  1430. return styles;
  1431. };
  1432. function assembleStyles() {
  1433. const codes = new Map();
  1434. const styles = {
  1435. modifier: {
  1436. reset: [0, 0],
  1437. // 21 isn't widely supported and 22 does the same thing
  1438. bold: [1, 22],
  1439. dim: [2, 22],
  1440. italic: [3, 23],
  1441. underline: [4, 24],
  1442. inverse: [7, 27],
  1443. hidden: [8, 28],
  1444. strikethrough: [9, 29]
  1445. },
  1446. color: {
  1447. black: [30, 39],
  1448. red: [31, 39],
  1449. green: [32, 39],
  1450. yellow: [33, 39],
  1451. blue: [34, 39],
  1452. magenta: [35, 39],
  1453. cyan: [36, 39],
  1454. white: [37, 39],
  1455. // Bright color
  1456. blackBright: [90, 39],
  1457. redBright: [91, 39],
  1458. greenBright: [92, 39],
  1459. yellowBright: [93, 39],
  1460. blueBright: [94, 39],
  1461. magentaBright: [95, 39],
  1462. cyanBright: [96, 39],
  1463. whiteBright: [97, 39]
  1464. },
  1465. bgColor: {
  1466. bgBlack: [40, 49],
  1467. bgRed: [41, 49],
  1468. bgGreen: [42, 49],
  1469. bgYellow: [43, 49],
  1470. bgBlue: [44, 49],
  1471. bgMagenta: [45, 49],
  1472. bgCyan: [46, 49],
  1473. bgWhite: [47, 49],
  1474. // Bright color
  1475. bgBlackBright: [100, 49],
  1476. bgRedBright: [101, 49],
  1477. bgGreenBright: [102, 49],
  1478. bgYellowBright: [103, 49],
  1479. bgBlueBright: [104, 49],
  1480. bgMagentaBright: [105, 49],
  1481. bgCyanBright: [106, 49],
  1482. bgWhiteBright: [107, 49]
  1483. }
  1484. }; // Alias bright black as gray (and grey)
  1485. styles.color.gray = styles.color.blackBright;
  1486. styles.bgColor.bgGray = styles.bgColor.bgBlackBright;
  1487. styles.color.grey = styles.color.blackBright;
  1488. styles.bgColor.bgGrey = styles.bgColor.bgBlackBright;
  1489. for (const [groupName, group] of Object.entries(styles)) {
  1490. for (const [styleName, style] of Object.entries(group)) {
  1491. styles[styleName] = {
  1492. open: `\u001B[${style[0]}m`,
  1493. close: `\u001B[${style[1]}m`
  1494. };
  1495. group[styleName] = styles[styleName];
  1496. codes.set(style[0], style[1]);
  1497. }
  1498. Object.defineProperty(styles, groupName, {
  1499. value: group,
  1500. enumerable: false
  1501. });
  1502. }
  1503. Object.defineProperty(styles, 'codes', {
  1504. value: codes,
  1505. enumerable: false
  1506. });
  1507. styles.color.close = '\u001B[39m';
  1508. styles.bgColor.close = '\u001B[49m';
  1509. setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false));
  1510. setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false));
  1511. setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false));
  1512. setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true));
  1513. setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true));
  1514. setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true));
  1515. return styles;
  1516. } // Make the export immutable
  1517. Object.defineProperty(module, 'exports', {
  1518. enumerable: true,
  1519. get: assembleStyles
  1520. });
  1521. });
  1522. var hasFlag = (flag, argv = process.argv) => {
  1523. const prefix = flag.startsWith('-') ? '' : flag.length === 1 ? '-' : '--';
  1524. const position = argv.indexOf(prefix + flag);
  1525. const terminatorPosition = argv.indexOf('--');
  1526. return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
  1527. };
  1528. const {
  1529. env
  1530. } = process;
  1531. let forceColor;
  1532. if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false') || hasFlag('color=never')) {
  1533. forceColor = 0;
  1534. } else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) {
  1535. forceColor = 1;
  1536. }
  1537. if ('FORCE_COLOR' in env) {
  1538. if (env.FORCE_COLOR === 'true') {
  1539. forceColor = 1;
  1540. } else if (env.FORCE_COLOR === 'false') {
  1541. forceColor = 0;
  1542. } else {
  1543. forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3);
  1544. }
  1545. }
  1546. function translateLevel(level) {
  1547. if (level === 0) {
  1548. return false;
  1549. }
  1550. return {
  1551. level,
  1552. hasBasic: true,
  1553. has256: level >= 2,
  1554. has16m: level >= 3
  1555. };
  1556. }
  1557. function supportsColor(haveStream, streamIsTTY) {
  1558. if (forceColor === 0) {
  1559. return 0;
  1560. }
  1561. if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) {
  1562. return 3;
  1563. }
  1564. if (hasFlag('color=256')) {
  1565. return 2;
  1566. }
  1567. if (haveStream && !streamIsTTY && forceColor === undefined) {
  1568. return 0;
  1569. }
  1570. const min = forceColor || 0;
  1571. if (env.TERM === 'dumb') {
  1572. return min;
  1573. }
  1574. if (process.platform === 'win32') {
  1575. // Windows 10 build 10586 is the first Windows release that supports 256 colors.
  1576. // Windows 10 build 14931 is the first release that supports 16m/TrueColor.
  1577. const osRelease = os__default['default'].release().split('.');
  1578. if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
  1579. return Number(osRelease[2]) >= 14931 ? 3 : 2;
  1580. }
  1581. return 1;
  1582. }
  1583. if ('CI' in env) {
  1584. if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') {
  1585. return 1;
  1586. }
  1587. return min;
  1588. }
  1589. if ('TEAMCITY_VERSION' in env) {
  1590. return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
  1591. }
  1592. if ('GITHUB_ACTIONS' in env) {
  1593. return 1;
  1594. }
  1595. if (env.COLORTERM === 'truecolor') {
  1596. return 3;
  1597. }
  1598. if ('TERM_PROGRAM' in env) {
  1599. const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
  1600. switch (env.TERM_PROGRAM) {
  1601. case 'iTerm.app':
  1602. return version >= 3 ? 3 : 2;
  1603. case 'Apple_Terminal':
  1604. return 2;
  1605. // No default
  1606. }
  1607. }
  1608. if (/-256(color)?$/i.test(env.TERM)) {
  1609. return 2;
  1610. }
  1611. if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
  1612. return 1;
  1613. }
  1614. if ('COLORTERM' in env) {
  1615. return 1;
  1616. }
  1617. return min;
  1618. }
  1619. function getSupportLevel(stream) {
  1620. const level = supportsColor(stream, stream && stream.isTTY);
  1621. return translateLevel(level);
  1622. }
  1623. var supportsColor_1 = {
  1624. supportsColor: getSupportLevel,
  1625. stdout: translateLevel(supportsColor(true, tty__default['default'].isatty(1))),
  1626. stderr: translateLevel(supportsColor(true, tty__default['default'].isatty(2)))
  1627. };
  1628. const stringReplaceAll = (string, substring, replacer) => {
  1629. let index = string.indexOf(substring);
  1630. if (index === -1) {
  1631. return string;
  1632. }
  1633. const substringLength = substring.length;
  1634. let endIndex = 0;
  1635. let returnValue = '';
  1636. do {
  1637. returnValue += string.substr(endIndex, index - endIndex) + substring + replacer;
  1638. endIndex = index + substringLength;
  1639. index = string.indexOf(substring, endIndex);
  1640. } while (index !== -1);
  1641. returnValue += string.substr(endIndex);
  1642. return returnValue;
  1643. };
  1644. const stringEncaseCRLFWithFirstIndex = (string, prefix, postfix, index) => {
  1645. let endIndex = 0;
  1646. let returnValue = '';
  1647. do {
  1648. const gotCR = string[index - 1] === '\r';
  1649. returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix;
  1650. endIndex = index + 1;
  1651. index = string.indexOf('\n', endIndex);
  1652. } while (index !== -1);
  1653. returnValue += string.substr(endIndex);
  1654. return returnValue;
  1655. };
  1656. var util = {
  1657. stringReplaceAll,
  1658. stringEncaseCRLFWithFirstIndex
  1659. };
  1660. const TEMPLATE_REGEX = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
  1661. const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
  1662. const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
  1663. const ESCAPE_REGEX = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi;
  1664. const ESCAPES = new Map([['n', '\n'], ['r', '\r'], ['t', '\t'], ['b', '\b'], ['f', '\f'], ['v', '\v'], ['0', '\0'], ['\\', '\\'], ['e', '\u001B'], ['a', '\u0007']]);
  1665. function unescape(c) {
  1666. const u = c[0] === 'u';
  1667. const bracket = c[1] === '{';
  1668. if (u && !bracket && c.length === 5 || c[0] === 'x' && c.length === 3) {
  1669. return String.fromCharCode(parseInt(c.slice(1), 16));
  1670. }
  1671. if (u && bracket) {
  1672. return String.fromCodePoint(parseInt(c.slice(2, -1), 16));
  1673. }
  1674. return ESCAPES.get(c) || c;
  1675. }
  1676. function parseArguments(name, arguments_) {
  1677. const results = [];
  1678. const chunks = arguments_.trim().split(/\s*,\s*/g);
  1679. let matches;
  1680. for (const chunk of chunks) {
  1681. const number = Number(chunk);
  1682. if (!Number.isNaN(number)) {
  1683. results.push(number);
  1684. } else if (matches = chunk.match(STRING_REGEX)) {
  1685. results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, character) => escape ? unescape(escape) : character));
  1686. } else {
  1687. throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
  1688. }
  1689. }
  1690. return results;
  1691. }
  1692. function parseStyle(style) {
  1693. STYLE_REGEX.lastIndex = 0;
  1694. const results = [];
  1695. let matches;
  1696. while ((matches = STYLE_REGEX.exec(style)) !== null) {
  1697. const name = matches[1];
  1698. if (matches[2]) {
  1699. const args = parseArguments(name, matches[2]);
  1700. results.push([name].concat(args));
  1701. } else {
  1702. results.push([name]);
  1703. }
  1704. }
  1705. return results;
  1706. }
  1707. function buildStyle(chalk, styles) {
  1708. const enabled = {};
  1709. for (const layer of styles) {
  1710. for (const style of layer.styles) {
  1711. enabled[style[0]] = layer.inverse ? null : style.slice(1);
  1712. }
  1713. }
  1714. let current = chalk;
  1715. for (const [styleName, styles] of Object.entries(enabled)) {
  1716. if (!Array.isArray(styles)) {
  1717. continue;
  1718. }
  1719. if (!(styleName in current)) {
  1720. throw new Error(`Unknown Chalk style: ${styleName}`);
  1721. }
  1722. current = styles.length > 0 ? current[styleName](...styles) : current[styleName];
  1723. }
  1724. return current;
  1725. }
  1726. var templates = (chalk, temporary) => {
  1727. const styles = [];
  1728. const chunks = [];
  1729. let chunk = []; // eslint-disable-next-line max-params
  1730. temporary.replace(TEMPLATE_REGEX, (m, escapeCharacter, inverse, style, close, character) => {
  1731. if (escapeCharacter) {
  1732. chunk.push(unescape(escapeCharacter));
  1733. } else if (style) {
  1734. const string = chunk.join('');
  1735. chunk = [];
  1736. chunks.push(styles.length === 0 ? string : buildStyle(chalk, styles)(string));
  1737. styles.push({
  1738. inverse,
  1739. styles: parseStyle(style)
  1740. });
  1741. } else if (close) {
  1742. if (styles.length === 0) {
  1743. throw new Error('Found extraneous } in Chalk template literal');
  1744. }
  1745. chunks.push(buildStyle(chalk, styles)(chunk.join('')));
  1746. chunk = [];
  1747. styles.pop();
  1748. } else {
  1749. chunk.push(character);
  1750. }
  1751. });
  1752. chunks.push(chunk.join(''));
  1753. if (styles.length > 0) {
  1754. const errMessage = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
  1755. throw new Error(errMessage);
  1756. }
  1757. return chunks.join('');
  1758. };
  1759. const {
  1760. stdout: stdoutColor,
  1761. stderr: stderrColor
  1762. } = supportsColor_1;
  1763. const {
  1764. stringReplaceAll: stringReplaceAll$1,
  1765. stringEncaseCRLFWithFirstIndex: stringEncaseCRLFWithFirstIndex$1
  1766. } = util;
  1767. const {
  1768. isArray
  1769. } = Array; // `supportsColor.level` → `ansiStyles.color[name]` mapping
  1770. const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m'];
  1771. const styles = Object.create(null);
  1772. const applyOptions = (object, options = {}) => {
  1773. if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
  1774. throw new Error('The `level` option should be an integer from 0 to 3');
  1775. } // Detect level if not set manually
  1776. const colorLevel = stdoutColor ? stdoutColor.level : 0;
  1777. object.level = options.level === undefined ? colorLevel : options.level;
  1778. };
  1779. class ChalkClass {
  1780. constructor(options) {
  1781. // eslint-disable-next-line no-constructor-return
  1782. return chalkFactory(options);
  1783. }
  1784. }
  1785. const chalkFactory = options => {
  1786. const chalk = {};
  1787. applyOptions(chalk, options);
  1788. chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_);
  1789. Object.setPrototypeOf(chalk, Chalk.prototype);
  1790. Object.setPrototypeOf(chalk.template, chalk);
  1791. chalk.template.constructor = () => {
  1792. throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.');
  1793. };
  1794. chalk.template.Instance = ChalkClass;
  1795. return chalk.template;
  1796. };
  1797. function Chalk(options) {
  1798. return chalkFactory(options);
  1799. }
  1800. for (const [styleName, style] of Object.entries(ansiStyles)) {
  1801. styles[styleName] = {
  1802. get() {
  1803. const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty);
  1804. Object.defineProperty(this, styleName, {
  1805. value: builder
  1806. });
  1807. return builder;
  1808. }
  1809. };
  1810. }
  1811. styles.visible = {
  1812. get() {
  1813. const builder = createBuilder(this, this._styler, true);
  1814. Object.defineProperty(this, 'visible', {
  1815. value: builder
  1816. });
  1817. return builder;
  1818. }
  1819. };
  1820. const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256'];
  1821. for (const model of usedModels) {
  1822. styles[model] = {
  1823. get() {
  1824. const {
  1825. level
  1826. } = this;
  1827. return function (...arguments_) {
  1828. const styler = createStyler(ansiStyles.color[levelMapping[level]][model](...arguments_), ansiStyles.color.close, this._styler);
  1829. return createBuilder(this, styler, this._isEmpty);
  1830. };
  1831. }
  1832. };
  1833. }
  1834. for (const model of usedModels) {
  1835. const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
  1836. styles[bgModel] = {
  1837. get() {
  1838. const {
  1839. level
  1840. } = this;
  1841. return function (...arguments_) {
  1842. const styler = createStyler(ansiStyles.bgColor[levelMapping[level]][model](...arguments_), ansiStyles.bgColor.close, this._styler);
  1843. return createBuilder(this, styler, this._isEmpty);
  1844. };
  1845. }
  1846. };
  1847. }
  1848. const proto = Object.defineProperties(() => {}, Object.assign({}, styles, {
  1849. level: {
  1850. enumerable: true,
  1851. get() {
  1852. return this._generator.level;
  1853. },
  1854. set(level) {
  1855. this._generator.level = level;
  1856. }
  1857. }
  1858. }));
  1859. const createStyler = (open, close, parent) => {
  1860. let openAll;
  1861. let closeAll;
  1862. if (parent === undefined) {
  1863. openAll = open;
  1864. closeAll = close;
  1865. } else {
  1866. openAll = parent.openAll + open;
  1867. closeAll = close + parent.closeAll;
  1868. }
  1869. return {
  1870. open,
  1871. close,
  1872. openAll,
  1873. closeAll,
  1874. parent
  1875. };
  1876. };
  1877. const createBuilder = (self, _styler, _isEmpty) => {
  1878. const builder = (...arguments_) => {
  1879. if (isArray(arguments_[0]) && isArray(arguments_[0].raw)) {
  1880. // Called as a template literal, for example: chalk.red`2 + 3 = {bold ${2+3}}`
  1881. return applyStyle(builder, chalkTag(builder, ...arguments_));
  1882. } // Single argument is hot path, implicit coercion is faster than anything
  1883. // eslint-disable-next-line no-implicit-coercion
  1884. return applyStyle(builder, arguments_.length === 1 ? '' + arguments_[0] : arguments_.join(' '));
  1885. }; // We alter the prototype because we must return a function, but there is
  1886. // no way to create a function with a different prototype
  1887. Object.setPrototypeOf(builder, proto);
  1888. builder._generator = self;
  1889. builder._styler = _styler;
  1890. builder._isEmpty = _isEmpty;
  1891. return builder;
  1892. };
  1893. const applyStyle = (self, string) => {
  1894. if (self.level <= 0 || !string) {
  1895. return self._isEmpty ? '' : string;
  1896. }
  1897. let styler = self._styler;
  1898. if (styler === undefined) {
  1899. return string;
  1900. }
  1901. const {
  1902. openAll,
  1903. closeAll
  1904. } = styler;
  1905. if (string.indexOf('\u001B') !== -1) {
  1906. while (styler !== undefined) {
  1907. // Replace any instances already present with a re-opening code
  1908. // otherwise only the part of the string until said closing code
  1909. // will be colored, and the rest will simply be 'plain'.
  1910. string = stringReplaceAll$1(string, styler.close, styler.open);
  1911. styler = styler.parent;
  1912. }
  1913. } // We can move both next actions out of loop, because remaining actions in loop won't have
  1914. // any/visible effect on parts we add here. Close the styling before a linebreak and reopen
  1915. // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92
  1916. const lfIndex = string.indexOf('\n');
  1917. if (lfIndex !== -1) {
  1918. string = stringEncaseCRLFWithFirstIndex$1(string, closeAll, openAll, lfIndex);
  1919. }
  1920. return openAll + string + closeAll;
  1921. };
  1922. let template;
  1923. const chalkTag = (chalk, ...strings) => {
  1924. const [firstString] = strings;
  1925. if (!isArray(firstString) || !isArray(firstString.raw)) {
  1926. // If chalk() was called by itself or with a string,
  1927. // return the string itself as a string.
  1928. return strings.join(' ');
  1929. }
  1930. const arguments_ = strings.slice(1);
  1931. const parts = [firstString.raw[0]];
  1932. for (let i = 1; i < firstString.length; i++) {
  1933. parts.push(String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'), String(firstString.raw[i]));
  1934. }
  1935. if (template === undefined) {
  1936. template = templates;
  1937. }
  1938. return template(chalk, parts.join(''));
  1939. };
  1940. Object.defineProperties(Chalk.prototype, styles);
  1941. const chalk = Chalk(); // eslint-disable-line new-cap
  1942. chalk.supportsColor = stdoutColor;
  1943. chalk.stderr = Chalk({
  1944. level: stderrColor ? stderrColor.level : 0
  1945. }); // eslint-disable-line new-cap
  1946. chalk.stderr.supportsColor = stderrColor;
  1947. var source = chalk;
  1948. /**
  1949. * The inverse of `_.toPairs`; this method returns an object composed
  1950. * from key-value `pairs`.
  1951. *
  1952. * @static
  1953. * @memberOf _
  1954. * @since 4.0.0
  1955. * @category Array
  1956. * @param {Array} pairs The key-value pairs.
  1957. * @returns {Object} Returns the new object.
  1958. * @example
  1959. *
  1960. * _.fromPairs([['a', 1], ['b', 2]]);
  1961. * // => { 'a': 1, 'b': 2 }
  1962. */
  1963. function fromPairs(pairs) {
  1964. var index = -1,
  1965. length = pairs == null ? 0 : pairs.length,
  1966. result = {};
  1967. while (++index < length) {
  1968. var pair = pairs[index];
  1969. result[pair[0]] = pair[1];
  1970. }
  1971. return result;
  1972. }
  1973. var fromPairs_1 = fromPairs;
  1974. /**
  1975. * Checks if `value` is classified as an `Array` object.
  1976. *
  1977. * @static
  1978. * @memberOf _
  1979. * @since 0.1.0
  1980. * @category Lang
  1981. * @param {*} value The value to check.
  1982. * @returns {boolean} Returns `true` if `value` is an array, else `false`.
  1983. * @example
  1984. *
  1985. * _.isArray([1, 2, 3]);
  1986. * // => true
  1987. *
  1988. * _.isArray(document.body.children);
  1989. * // => false
  1990. *
  1991. * _.isArray('abc');
  1992. * // => false
  1993. *
  1994. * _.isArray(_.noop);
  1995. * // => false
  1996. */
  1997. var isArray$1 = Array.isArray;
  1998. var isArray_1 = isArray$1;
  1999. /** Detect free variable `global` from Node.js. */
  2000. var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
  2001. var _freeGlobal = freeGlobal;
  2002. /** Detect free variable `self`. */
  2003. var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
  2004. /** Used as a reference to the global object. */
  2005. var root = _freeGlobal || freeSelf || Function('return this')();
  2006. var _root = root;
  2007. /** Built-in value references. */
  2008. var Symbol$1 = _root.Symbol;
  2009. var _Symbol = Symbol$1;
  2010. /** Used for built-in method references. */
  2011. var objectProto = Object.prototype;
  2012. /** Used to check objects for own properties. */
  2013. var hasOwnProperty = objectProto.hasOwnProperty;
  2014. /**
  2015. * Used to resolve the
  2016. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  2017. * of values.
  2018. */
  2019. var nativeObjectToString = objectProto.toString;
  2020. /** Built-in value references. */
  2021. var symToStringTag = _Symbol ? _Symbol.toStringTag : undefined;
  2022. /**
  2023. * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
  2024. *
  2025. * @private
  2026. * @param {*} value The value to query.
  2027. * @returns {string} Returns the raw `toStringTag`.
  2028. */
  2029. function getRawTag(value) {
  2030. var isOwn = hasOwnProperty.call(value, symToStringTag),
  2031. tag = value[symToStringTag];
  2032. try {
  2033. value[symToStringTag] = undefined;
  2034. var unmasked = true;
  2035. } catch (e) {}
  2036. var result = nativeObjectToString.call(value);
  2037. if (unmasked) {
  2038. if (isOwn) {
  2039. value[symToStringTag] = tag;
  2040. } else {
  2041. delete value[symToStringTag];
  2042. }
  2043. }
  2044. return result;
  2045. }
  2046. var _getRawTag = getRawTag;
  2047. /** Used for built-in method references. */
  2048. var objectProto$1 = Object.prototype;
  2049. /**
  2050. * Used to resolve the
  2051. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  2052. * of values.
  2053. */
  2054. var nativeObjectToString$1 = objectProto$1.toString;
  2055. /**
  2056. * Converts `value` to a string using `Object.prototype.toString`.
  2057. *
  2058. * @private
  2059. * @param {*} value The value to convert.
  2060. * @returns {string} Returns the converted string.
  2061. */
  2062. function objectToString(value) {
  2063. return nativeObjectToString$1.call(value);
  2064. }
  2065. var _objectToString = objectToString;
  2066. /** `Object#toString` result references. */
  2067. var nullTag = '[object Null]',
  2068. undefinedTag = '[object Undefined]';
  2069. /** Built-in value references. */
  2070. var symToStringTag$1 = _Symbol ? _Symbol.toStringTag : undefined;
  2071. /**
  2072. * The base implementation of `getTag` without fallbacks for buggy environments.
  2073. *
  2074. * @private
  2075. * @param {*} value The value to query.
  2076. * @returns {string} Returns the `toStringTag`.
  2077. */
  2078. function baseGetTag(value) {
  2079. if (value == null) {
  2080. return value === undefined ? undefinedTag : nullTag;
  2081. }
  2082. return symToStringTag$1 && symToStringTag$1 in Object(value) ? _getRawTag(value) : _objectToString(value);
  2083. }
  2084. var _baseGetTag = baseGetTag;
  2085. /**
  2086. * Checks if `value` is object-like. A value is object-like if it's not `null`
  2087. * and has a `typeof` result of "object".
  2088. *
  2089. * @static
  2090. * @memberOf _
  2091. * @since 4.0.0
  2092. * @category Lang
  2093. * @param {*} value The value to check.
  2094. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  2095. * @example
  2096. *
  2097. * _.isObjectLike({});
  2098. * // => true
  2099. *
  2100. * _.isObjectLike([1, 2, 3]);
  2101. * // => true
  2102. *
  2103. * _.isObjectLike(_.noop);
  2104. * // => false
  2105. *
  2106. * _.isObjectLike(null);
  2107. * // => false
  2108. */
  2109. function isObjectLike(value) {
  2110. return value != null && typeof value == 'object';
  2111. }
  2112. var isObjectLike_1 = isObjectLike;
  2113. /** `Object#toString` result references. */
  2114. var symbolTag = '[object Symbol]';
  2115. /**
  2116. * Checks if `value` is classified as a `Symbol` primitive or object.
  2117. *
  2118. * @static
  2119. * @memberOf _
  2120. * @since 4.0.0
  2121. * @category Lang
  2122. * @param {*} value The value to check.
  2123. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
  2124. * @example
  2125. *
  2126. * _.isSymbol(Symbol.iterator);
  2127. * // => true
  2128. *
  2129. * _.isSymbol('abc');
  2130. * // => false
  2131. */
  2132. function isSymbol(value) {
  2133. return typeof value == 'symbol' || isObjectLike_1(value) && _baseGetTag(value) == symbolTag;
  2134. }
  2135. var isSymbol_1 = isSymbol;
  2136. /** Used to match property names within property paths. */
  2137. var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
  2138. reIsPlainProp = /^\w*$/;
  2139. /**
  2140. * Checks if `value` is a property name and not a property path.
  2141. *
  2142. * @private
  2143. * @param {*} value The value to check.
  2144. * @param {Object} [object] The object to query keys on.
  2145. * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
  2146. */
  2147. function isKey(value, object) {
  2148. if (isArray_1(value)) {
  2149. return false;
  2150. }
  2151. var type = typeof value;
  2152. if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol_1(value)) {
  2153. return true;
  2154. }
  2155. return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object != null && value in Object(object);
  2156. }
  2157. var _isKey = isKey;
  2158. /**
  2159. * Checks if `value` is the
  2160. * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
  2161. * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
  2162. *
  2163. * @static
  2164. * @memberOf _
  2165. * @since 0.1.0
  2166. * @category Lang
  2167. * @param {*} value The value to check.
  2168. * @returns {boolean} Returns `true` if `value` is an object, else `false`.
  2169. * @example
  2170. *
  2171. * _.isObject({});
  2172. * // => true
  2173. *
  2174. * _.isObject([1, 2, 3]);
  2175. * // => true
  2176. *
  2177. * _.isObject(_.noop);
  2178. * // => true
  2179. *
  2180. * _.isObject(null);
  2181. * // => false
  2182. */
  2183. function isObject(value) {
  2184. var type = typeof value;
  2185. return value != null && (type == 'object' || type == 'function');
  2186. }
  2187. var isObject_1 = isObject;
  2188. /** `Object#toString` result references. */
  2189. var asyncTag = '[object AsyncFunction]',
  2190. funcTag = '[object Function]',
  2191. genTag = '[object GeneratorFunction]',
  2192. proxyTag = '[object Proxy]';
  2193. /**
  2194. * Checks if `value` is classified as a `Function` object.
  2195. *
  2196. * @static
  2197. * @memberOf _
  2198. * @since 0.1.0
  2199. * @category Lang
  2200. * @param {*} value The value to check.
  2201. * @returns {boolean} Returns `true` if `value` is a function, else `false`.
  2202. * @example
  2203. *
  2204. * _.isFunction(_);
  2205. * // => true
  2206. *
  2207. * _.isFunction(/abc/);
  2208. * // => false
  2209. */
  2210. function isFunction(value) {
  2211. if (!isObject_1(value)) {
  2212. return false;
  2213. } // The use of `Object#toString` avoids issues with the `typeof` operator
  2214. // in Safari 9 which returns 'object' for typed arrays and other constructors.
  2215. var tag = _baseGetTag(value);
  2216. return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
  2217. }
  2218. var isFunction_1 = isFunction;
  2219. /** Used to detect overreaching core-js shims. */
  2220. var coreJsData = _root['__core-js_shared__'];
  2221. var _coreJsData = coreJsData;
  2222. /** Used to detect methods masquerading as native. */
  2223. var maskSrcKey = function () {
  2224. var uid = /[^.]+$/.exec(_coreJsData && _coreJsData.keys && _coreJsData.keys.IE_PROTO || '');
  2225. return uid ? 'Symbol(src)_1.' + uid : '';
  2226. }();
  2227. /**
  2228. * Checks if `func` has its source masked.
  2229. *
  2230. * @private
  2231. * @param {Function} func The function to check.
  2232. * @returns {boolean} Returns `true` if `func` is masked, else `false`.
  2233. */
  2234. function isMasked(func) {
  2235. return !!maskSrcKey && maskSrcKey in func;
  2236. }
  2237. var _isMasked = isMasked;
  2238. /** Used for built-in method references. */
  2239. var funcProto = Function.prototype;
  2240. /** Used to resolve the decompiled source of functions. */
  2241. var funcToString = funcProto.toString;
  2242. /**
  2243. * Converts `func` to its source code.
  2244. *
  2245. * @private
  2246. * @param {Function} func The function to convert.
  2247. * @returns {string} Returns the source code.
  2248. */
  2249. function toSource(func) {
  2250. if (func != null) {
  2251. try {
  2252. return funcToString.call(func);
  2253. } catch (e) {}
  2254. try {
  2255. return func + '';
  2256. } catch (e) {}
  2257. }
  2258. return '';
  2259. }
  2260. var _toSource = toSource;
  2261. /**
  2262. * Used to match `RegExp`
  2263. * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
  2264. */
  2265. var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
  2266. /** Used to detect host constructors (Safari). */
  2267. var reIsHostCtor = /^\[object .+?Constructor\]$/;
  2268. /** Used for built-in method references. */
  2269. var funcProto$1 = Function.prototype,
  2270. objectProto$2 = Object.prototype;
  2271. /** Used to resolve the decompiled source of functions. */
  2272. var funcToString$1 = funcProto$1.toString;
  2273. /** Used to check objects for own properties. */
  2274. var hasOwnProperty$1 = objectProto$2.hasOwnProperty;
  2275. /** Used to detect if a method is native. */
  2276. var reIsNative = RegExp('^' + funcToString$1.call(hasOwnProperty$1).replace(reRegExpChar, '\\$&').replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$');
  2277. /**
  2278. * The base implementation of `_.isNative` without bad shim checks.
  2279. *
  2280. * @private
  2281. * @param {*} value The value to check.
  2282. * @returns {boolean} Returns `true` if `value` is a native function,
  2283. * else `false`.
  2284. */
  2285. function baseIsNative(value) {
  2286. if (!isObject_1(value) || _isMasked(value)) {
  2287. return false;
  2288. }
  2289. var pattern = isFunction_1(value) ? reIsNative : reIsHostCtor;
  2290. return pattern.test(_toSource(value));
  2291. }
  2292. var _baseIsNative = baseIsNative;
  2293. /**
  2294. * Gets the value at `key` of `object`.
  2295. *
  2296. * @private
  2297. * @param {Object} [object] The object to query.
  2298. * @param {string} key The key of the property to get.
  2299. * @returns {*} Returns the property value.
  2300. */
  2301. function getValue(object, key) {
  2302. return object == null ? undefined : object[key];
  2303. }
  2304. var _getValue = getValue;
  2305. /**
  2306. * Gets the native function at `key` of `object`.
  2307. *
  2308. * @private
  2309. * @param {Object} object The object to query.
  2310. * @param {string} key The key of the method to get.
  2311. * @returns {*} Returns the function if it's native, else `undefined`.
  2312. */
  2313. function getNative(object, key) {
  2314. var value = _getValue(object, key);
  2315. return _baseIsNative(value) ? value : undefined;
  2316. }
  2317. var _getNative = getNative;
  2318. /* Built-in method references that are verified to be native. */
  2319. var nativeCreate = _getNative(Object, 'create');
  2320. var _nativeCreate = nativeCreate;
  2321. /**
  2322. * Removes all key-value entries from the hash.
  2323. *
  2324. * @private
  2325. * @name clear
  2326. * @memberOf Hash
  2327. */
  2328. function hashClear() {
  2329. this.__data__ = _nativeCreate ? _nativeCreate(null) : {};
  2330. this.size = 0;
  2331. }
  2332. var _hashClear = hashClear;
  2333. /**
  2334. * Removes `key` and its value from the hash.
  2335. *
  2336. * @private
  2337. * @name delete
  2338. * @memberOf Hash
  2339. * @param {Object} hash The hash to modify.
  2340. * @param {string} key The key of the value to remove.
  2341. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  2342. */
  2343. function hashDelete(key) {
  2344. var result = this.has(key) && delete this.__data__[key];
  2345. this.size -= result ? 1 : 0;
  2346. return result;
  2347. }
  2348. var _hashDelete = hashDelete;
  2349. /** Used to stand-in for `undefined` hash values. */
  2350. var HASH_UNDEFINED = '__lodash_hash_undefined__';
  2351. /** Used for built-in method references. */
  2352. var objectProto$3 = Object.prototype;
  2353. /** Used to check objects for own properties. */
  2354. var hasOwnProperty$2 = objectProto$3.hasOwnProperty;
  2355. /**
  2356. * Gets the hash value for `key`.
  2357. *
  2358. * @private
  2359. * @name get
  2360. * @memberOf Hash
  2361. * @param {string} key The key of the value to get.
  2362. * @returns {*} Returns the entry value.
  2363. */
  2364. function hashGet(key) {
  2365. var data = this.__data__;
  2366. if (_nativeCreate) {
  2367. var result = data[key];
  2368. return result === HASH_UNDEFINED ? undefined : result;
  2369. }
  2370. return hasOwnProperty$2.call(data, key) ? data[key] : undefined;
  2371. }
  2372. var _hashGet = hashGet;
  2373. /** Used for built-in method references. */
  2374. var objectProto$4 = Object.prototype;
  2375. /** Used to check objects for own properties. */
  2376. var hasOwnProperty$3 = objectProto$4.hasOwnProperty;
  2377. /**
  2378. * Checks if a hash value for `key` exists.
  2379. *
  2380. * @private
  2381. * @name has
  2382. * @memberOf Hash
  2383. * @param {string} key The key of the entry to check.
  2384. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  2385. */
  2386. function hashHas(key) {
  2387. var data = this.__data__;
  2388. return _nativeCreate ? data[key] !== undefined : hasOwnProperty$3.call(data, key);
  2389. }
  2390. var _hashHas = hashHas;
  2391. /** Used to stand-in for `undefined` hash values. */
  2392. var HASH_UNDEFINED$1 = '__lodash_hash_undefined__';
  2393. /**
  2394. * Sets the hash `key` to `value`.
  2395. *
  2396. * @private
  2397. * @name set
  2398. * @memberOf Hash
  2399. * @param {string} key The key of the value to set.
  2400. * @param {*} value The value to set.
  2401. * @returns {Object} Returns the hash instance.
  2402. */
  2403. function hashSet(key, value) {
  2404. var data = this.__data__;
  2405. this.size += this.has(key) ? 0 : 1;
  2406. data[key] = _nativeCreate && value === undefined ? HASH_UNDEFINED$1 : value;
  2407. return this;
  2408. }
  2409. var _hashSet = hashSet;
  2410. /**
  2411. * Creates a hash object.
  2412. *
  2413. * @private
  2414. * @constructor
  2415. * @param {Array} [entries] The key-value pairs to cache.
  2416. */
  2417. function Hash(entries) {
  2418. var index = -1,
  2419. length = entries == null ? 0 : entries.length;
  2420. this.clear();
  2421. while (++index < length) {
  2422. var entry = entries[index];
  2423. this.set(entry[0], entry[1]);
  2424. }
  2425. } // Add methods to `Hash`.
  2426. Hash.prototype.clear = _hashClear;
  2427. Hash.prototype['delete'] = _hashDelete;
  2428. Hash.prototype.get = _hashGet;
  2429. Hash.prototype.has = _hashHas;
  2430. Hash.prototype.set = _hashSet;
  2431. var _Hash = Hash;
  2432. /**
  2433. * Removes all key-value entries from the list cache.
  2434. *
  2435. * @private
  2436. * @name clear
  2437. * @memberOf ListCache
  2438. */
  2439. function listCacheClear() {
  2440. this.__data__ = [];
  2441. this.size = 0;
  2442. }
  2443. var _listCacheClear = listCacheClear;
  2444. /**
  2445. * Performs a
  2446. * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
  2447. * comparison between two values to determine if they are equivalent.
  2448. *
  2449. * @static
  2450. * @memberOf _
  2451. * @since 4.0.0
  2452. * @category Lang
  2453. * @param {*} value The value to compare.
  2454. * @param {*} other The other value to compare.
  2455. * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
  2456. * @example
  2457. *
  2458. * var object = { 'a': 1 };
  2459. * var other = { 'a': 1 };
  2460. *
  2461. * _.eq(object, object);
  2462. * // => true
  2463. *
  2464. * _.eq(object, other);
  2465. * // => false
  2466. *
  2467. * _.eq('a', 'a');
  2468. * // => true
  2469. *
  2470. * _.eq('a', Object('a'));
  2471. * // => false
  2472. *
  2473. * _.eq(NaN, NaN);
  2474. * // => true
  2475. */
  2476. function eq(value, other) {
  2477. return value === other || value !== value && other !== other;
  2478. }
  2479. var eq_1 = eq;
  2480. /**
  2481. * Gets the index at which the `key` is found in `array` of key-value pairs.
  2482. *
  2483. * @private
  2484. * @param {Array} array The array to inspect.
  2485. * @param {*} key The key to search for.
  2486. * @returns {number} Returns the index of the matched value, else `-1`.
  2487. */
  2488. function assocIndexOf(array, key) {
  2489. var length = array.length;
  2490. while (length--) {
  2491. if (eq_1(array[length][0], key)) {
  2492. return length;
  2493. }
  2494. }
  2495. return -1;
  2496. }
  2497. var _assocIndexOf = assocIndexOf;
  2498. /** Used for built-in method references. */
  2499. var arrayProto = Array.prototype;
  2500. /** Built-in value references. */
  2501. var splice = arrayProto.splice;
  2502. /**
  2503. * Removes `key` and its value from the list cache.
  2504. *
  2505. * @private
  2506. * @name delete
  2507. * @memberOf ListCache
  2508. * @param {string} key The key of the value to remove.
  2509. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  2510. */
  2511. function listCacheDelete(key) {
  2512. var data = this.__data__,
  2513. index = _assocIndexOf(data, key);
  2514. if (index < 0) {
  2515. return false;
  2516. }
  2517. var lastIndex = data.length - 1;
  2518. if (index == lastIndex) {
  2519. data.pop();
  2520. } else {
  2521. splice.call(data, index, 1);
  2522. }
  2523. --this.size;
  2524. return true;
  2525. }
  2526. var _listCacheDelete = listCacheDelete;
  2527. /**
  2528. * Gets the list cache value for `key`.
  2529. *
  2530. * @private
  2531. * @name get
  2532. * @memberOf ListCache
  2533. * @param {string} key The key of the value to get.
  2534. * @returns {*} Returns the entry value.
  2535. */
  2536. function listCacheGet(key) {
  2537. var data = this.__data__,
  2538. index = _assocIndexOf(data, key);
  2539. return index < 0 ? undefined : data[index][1];
  2540. }
  2541. var _listCacheGet = listCacheGet;
  2542. /**
  2543. * Checks if a list cache value for `key` exists.
  2544. *
  2545. * @private
  2546. * @name has
  2547. * @memberOf ListCache
  2548. * @param {string} key The key of the entry to check.
  2549. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  2550. */
  2551. function listCacheHas(key) {
  2552. return _assocIndexOf(this.__data__, key) > -1;
  2553. }
  2554. var _listCacheHas = listCacheHas;
  2555. /**
  2556. * Sets the list cache `key` to `value`.
  2557. *
  2558. * @private
  2559. * @name set
  2560. * @memberOf ListCache
  2561. * @param {string} key The key of the value to set.
  2562. * @param {*} value The value to set.
  2563. * @returns {Object} Returns the list cache instance.
  2564. */
  2565. function listCacheSet(key, value) {
  2566. var data = this.__data__,
  2567. index = _assocIndexOf(data, key);
  2568. if (index < 0) {
  2569. ++this.size;
  2570. data.push([key, value]);
  2571. } else {
  2572. data[index][1] = value;
  2573. }
  2574. return this;
  2575. }
  2576. var _listCacheSet = listCacheSet;
  2577. /**
  2578. * Creates an list cache object.
  2579. *
  2580. * @private
  2581. * @constructor
  2582. * @param {Array} [entries] The key-value pairs to cache.
  2583. */
  2584. function ListCache(entries) {
  2585. var index = -1,
  2586. length = entries == null ? 0 : entries.length;
  2587. this.clear();
  2588. while (++index < length) {
  2589. var entry = entries[index];
  2590. this.set(entry[0], entry[1]);
  2591. }
  2592. } // Add methods to `ListCache`.
  2593. ListCache.prototype.clear = _listCacheClear;
  2594. ListCache.prototype['delete'] = _listCacheDelete;
  2595. ListCache.prototype.get = _listCacheGet;
  2596. ListCache.prototype.has = _listCacheHas;
  2597. ListCache.prototype.set = _listCacheSet;
  2598. var _ListCache = ListCache;
  2599. /* Built-in method references that are verified to be native. */
  2600. var Map$1 = _getNative(_root, 'Map');
  2601. var _Map = Map$1;
  2602. /**
  2603. * Removes all key-value entries from the map.
  2604. *
  2605. * @private
  2606. * @name clear
  2607. * @memberOf MapCache
  2608. */
  2609. function mapCacheClear() {
  2610. this.size = 0;
  2611. this.__data__ = {
  2612. 'hash': new _Hash(),
  2613. 'map': new (_Map || _ListCache)(),
  2614. 'string': new _Hash()
  2615. };
  2616. }
  2617. var _mapCacheClear = mapCacheClear;
  2618. /**
  2619. * Checks if `value` is suitable for use as unique object key.
  2620. *
  2621. * @private
  2622. * @param {*} value The value to check.
  2623. * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
  2624. */
  2625. function isKeyable(value) {
  2626. var type = typeof value;
  2627. return type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean' ? value !== '__proto__' : value === null;
  2628. }
  2629. var _isKeyable = isKeyable;
  2630. /**
  2631. * Gets the data for `map`.
  2632. *
  2633. * @private
  2634. * @param {Object} map The map to query.
  2635. * @param {string} key The reference key.
  2636. * @returns {*} Returns the map data.
  2637. */
  2638. function getMapData(map, key) {
  2639. var data = map.__data__;
  2640. return _isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map;
  2641. }
  2642. var _getMapData = getMapData;
  2643. /**
  2644. * Removes `key` and its value from the map.
  2645. *
  2646. * @private
  2647. * @name delete
  2648. * @memberOf MapCache
  2649. * @param {string} key The key of the value to remove.
  2650. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  2651. */
  2652. function mapCacheDelete(key) {
  2653. var result = _getMapData(this, key)['delete'](key);
  2654. this.size -= result ? 1 : 0;
  2655. return result;
  2656. }
  2657. var _mapCacheDelete = mapCacheDelete;
  2658. /**
  2659. * Gets the map value for `key`.
  2660. *
  2661. * @private
  2662. * @name get
  2663. * @memberOf MapCache
  2664. * @param {string} key The key of the value to get.
  2665. * @returns {*} Returns the entry value.
  2666. */
  2667. function mapCacheGet(key) {
  2668. return _getMapData(this, key).get(key);
  2669. }
  2670. var _mapCacheGet = mapCacheGet;
  2671. /**
  2672. * Checks if a map value for `key` exists.
  2673. *
  2674. * @private
  2675. * @name has
  2676. * @memberOf MapCache
  2677. * @param {string} key The key of the entry to check.
  2678. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  2679. */
  2680. function mapCacheHas(key) {
  2681. return _getMapData(this, key).has(key);
  2682. }
  2683. var _mapCacheHas = mapCacheHas;
  2684. /**
  2685. * Sets the map `key` to `value`.
  2686. *
  2687. * @private
  2688. * @name set
  2689. * @memberOf MapCache
  2690. * @param {string} key The key of the value to set.
  2691. * @param {*} value The value to set.
  2692. * @returns {Object} Returns the map cache instance.
  2693. */
  2694. function mapCacheSet(key, value) {
  2695. var data = _getMapData(this, key),
  2696. size = data.size;
  2697. data.set(key, value);
  2698. this.size += data.size == size ? 0 : 1;
  2699. return this;
  2700. }
  2701. var _mapCacheSet = mapCacheSet;
  2702. /**
  2703. * Creates a map cache object to store key-value pairs.
  2704. *
  2705. * @private
  2706. * @constructor
  2707. * @param {Array} [entries] The key-value pairs to cache.
  2708. */
  2709. function MapCache(entries) {
  2710. var index = -1,
  2711. length = entries == null ? 0 : entries.length;
  2712. this.clear();
  2713. while (++index < length) {
  2714. var entry = entries[index];
  2715. this.set(entry[0], entry[1]);
  2716. }
  2717. } // Add methods to `MapCache`.
  2718. MapCache.prototype.clear = _mapCacheClear;
  2719. MapCache.prototype['delete'] = _mapCacheDelete;
  2720. MapCache.prototype.get = _mapCacheGet;
  2721. MapCache.prototype.has = _mapCacheHas;
  2722. MapCache.prototype.set = _mapCacheSet;
  2723. var _MapCache = MapCache;
  2724. /** Error message constants. */
  2725. var FUNC_ERROR_TEXT = 'Expected a function';
  2726. /**
  2727. * Creates a function that memoizes the result of `func`. If `resolver` is
  2728. * provided, it determines the cache key for storing the result based on the
  2729. * arguments provided to the memoized function. By default, the first argument
  2730. * provided to the memoized function is used as the map cache key. The `func`
  2731. * is invoked with the `this` binding of the memoized function.
  2732. *
  2733. * **Note:** The cache is exposed as the `cache` property on the memoized
  2734. * function. Its creation may be customized by replacing the `_.memoize.Cache`
  2735. * constructor with one whose instances implement the
  2736. * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
  2737. * method interface of `clear`, `delete`, `get`, `has`, and `set`.
  2738. *
  2739. * @static
  2740. * @memberOf _
  2741. * @since 0.1.0
  2742. * @category Function
  2743. * @param {Function} func The function to have its output memoized.
  2744. * @param {Function} [resolver] The function to resolve the cache key.
  2745. * @returns {Function} Returns the new memoized function.
  2746. * @example
  2747. *
  2748. * var object = { 'a': 1, 'b': 2 };
  2749. * var other = { 'c': 3, 'd': 4 };
  2750. *
  2751. * var values = _.memoize(_.values);
  2752. * values(object);
  2753. * // => [1, 2]
  2754. *
  2755. * values(other);
  2756. * // => [3, 4]
  2757. *
  2758. * object.a = 2;
  2759. * values(object);
  2760. * // => [1, 2]
  2761. *
  2762. * // Modify the result cache.
  2763. * values.cache.set(object, ['a', 'b']);
  2764. * values(object);
  2765. * // => ['a', 'b']
  2766. *
  2767. * // Replace `_.memoize.Cache`.
  2768. * _.memoize.Cache = WeakMap;
  2769. */
  2770. function memoize(func, resolver) {
  2771. if (typeof func != 'function' || resolver != null && typeof resolver != 'function') {
  2772. throw new TypeError(FUNC_ERROR_TEXT);
  2773. }
  2774. var memoized = function () {
  2775. var args = arguments,
  2776. key = resolver ? resolver.apply(this, args) : args[0],
  2777. cache = memoized.cache;
  2778. if (cache.has(key)) {
  2779. return cache.get(key);
  2780. }
  2781. var result = func.apply(this, args);
  2782. memoized.cache = cache.set(key, result) || cache;
  2783. return result;
  2784. };
  2785. memoized.cache = new (memoize.Cache || _MapCache)();
  2786. return memoized;
  2787. } // Expose `MapCache`.
  2788. memoize.Cache = _MapCache;
  2789. var memoize_1 = memoize;
  2790. /** Used as the maximum memoize cache size. */
  2791. var MAX_MEMOIZE_SIZE = 500;
  2792. /**
  2793. * A specialized version of `_.memoize` which clears the memoized function's
  2794. * cache when it exceeds `MAX_MEMOIZE_SIZE`.
  2795. *
  2796. * @private
  2797. * @param {Function} func The function to have its output memoized.
  2798. * @returns {Function} Returns the new memoized function.
  2799. */
  2800. function memoizeCapped(func) {
  2801. var result = memoize_1(func, function (key) {
  2802. if (cache.size === MAX_MEMOIZE_SIZE) {
  2803. cache.clear();
  2804. }
  2805. return key;
  2806. });
  2807. var cache = result.cache;
  2808. return result;
  2809. }
  2810. var _memoizeCapped = memoizeCapped;
  2811. /** Used to match property names within property paths. */
  2812. var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
  2813. /** Used to match backslashes in property paths. */
  2814. var reEscapeChar = /\\(\\)?/g;
  2815. /**
  2816. * Converts `string` to a property path array.
  2817. *
  2818. * @private
  2819. * @param {string} string The string to convert.
  2820. * @returns {Array} Returns the property path array.
  2821. */
  2822. var stringToPath = _memoizeCapped(function (string) {
  2823. var result = [];
  2824. if (string.charCodeAt(0) === 46
  2825. /* . */
  2826. ) {
  2827. result.push('');
  2828. }
  2829. string.replace(rePropName, function (match, number, quote, subString) {
  2830. result.push(quote ? subString.replace(reEscapeChar, '$1') : number || match);
  2831. });
  2832. return result;
  2833. });
  2834. var _stringToPath = stringToPath;
  2835. /**
  2836. * A specialized version of `_.map` for arrays without support for iteratee
  2837. * shorthands.
  2838. *
  2839. * @private
  2840. * @param {Array} [array] The array to iterate over.
  2841. * @param {Function} iteratee The function invoked per iteration.
  2842. * @returns {Array} Returns the new mapped array.
  2843. */
  2844. function arrayMap(array, iteratee) {
  2845. var index = -1,
  2846. length = array == null ? 0 : array.length,
  2847. result = Array(length);
  2848. while (++index < length) {
  2849. result[index] = iteratee(array[index], index, array);
  2850. }
  2851. return result;
  2852. }
  2853. var _arrayMap = arrayMap;
  2854. /** Used as references for various `Number` constants. */
  2855. var INFINITY = 1 / 0;
  2856. /** Used to convert symbols to primitives and strings. */
  2857. var symbolProto = _Symbol ? _Symbol.prototype : undefined,
  2858. symbolToString = symbolProto ? symbolProto.toString : undefined;
  2859. /**
  2860. * The base implementation of `_.toString` which doesn't convert nullish
  2861. * values to empty strings.
  2862. *
  2863. * @private
  2864. * @param {*} value The value to process.
  2865. * @returns {string} Returns the string.
  2866. */
  2867. function baseToString(value) {
  2868. // Exit early for strings to avoid a performance hit in some environments.
  2869. if (typeof value == 'string') {
  2870. return value;
  2871. }
  2872. if (isArray_1(value)) {
  2873. // Recursively convert values (susceptible to call stack limits).
  2874. return _arrayMap(value, baseToString) + '';
  2875. }
  2876. if (isSymbol_1(value)) {
  2877. return symbolToString ? symbolToString.call(value) : '';
  2878. }
  2879. var result = value + '';
  2880. return result == '0' && 1 / value == -INFINITY ? '-0' : result;
  2881. }
  2882. var _baseToString = baseToString;
  2883. /**
  2884. * Converts `value` to a string. An empty string is returned for `null`
  2885. * and `undefined` values. The sign of `-0` is preserved.
  2886. *
  2887. * @static
  2888. * @memberOf _
  2889. * @since 4.0.0
  2890. * @category Lang
  2891. * @param {*} value The value to convert.
  2892. * @returns {string} Returns the converted string.
  2893. * @example
  2894. *
  2895. * _.toString(null);
  2896. * // => ''
  2897. *
  2898. * _.toString(-0);
  2899. * // => '-0'
  2900. *
  2901. * _.toString([1, 2, 3]);
  2902. * // => '1,2,3'
  2903. */
  2904. function toString(value) {
  2905. return value == null ? '' : _baseToString(value);
  2906. }
  2907. var toString_1 = toString;
  2908. /**
  2909. * Casts `value` to a path array if it's not one.
  2910. *
  2911. * @private
  2912. * @param {*} value The value to inspect.
  2913. * @param {Object} [object] The object to query keys on.
  2914. * @returns {Array} Returns the cast property path array.
  2915. */
  2916. function castPath(value, object) {
  2917. if (isArray_1(value)) {
  2918. return value;
  2919. }
  2920. return _isKey(value, object) ? [value] : _stringToPath(toString_1(value));
  2921. }
  2922. var _castPath = castPath;
  2923. /** Used as references for various `Number` constants. */
  2924. var INFINITY$1 = 1 / 0;
  2925. /**
  2926. * Converts `value` to a string key if it's not a string or symbol.
  2927. *
  2928. * @private
  2929. * @param {*} value The value to inspect.
  2930. * @returns {string|symbol} Returns the key.
  2931. */
  2932. function toKey(value) {
  2933. if (typeof value == 'string' || isSymbol_1(value)) {
  2934. return value;
  2935. }
  2936. var result = value + '';
  2937. return result == '0' && 1 / value == -INFINITY$1 ? '-0' : result;
  2938. }
  2939. var _toKey = toKey;
  2940. /**
  2941. * The base implementation of `_.get` without support for default values.
  2942. *
  2943. * @private
  2944. * @param {Object} object The object to query.
  2945. * @param {Array|string} path The path of the property to get.
  2946. * @returns {*} Returns the resolved value.
  2947. */
  2948. function baseGet(object, path) {
  2949. path = _castPath(path, object);
  2950. var index = 0,
  2951. length = path.length;
  2952. while (object != null && index < length) {
  2953. object = object[_toKey(path[index++])];
  2954. }
  2955. return index && index == length ? object : undefined;
  2956. }
  2957. var _baseGet = baseGet;
  2958. var defineProperty = function () {
  2959. try {
  2960. var func = _getNative(Object, 'defineProperty');
  2961. func({}, '', {});
  2962. return func;
  2963. } catch (e) {}
  2964. }();
  2965. var _defineProperty = defineProperty;
  2966. /**
  2967. * The base implementation of `assignValue` and `assignMergeValue` without
  2968. * value checks.
  2969. *
  2970. * @private
  2971. * @param {Object} object The object to modify.
  2972. * @param {string} key The key of the property to assign.
  2973. * @param {*} value The value to assign.
  2974. */
  2975. function baseAssignValue(object, key, value) {
  2976. if (key == '__proto__' && _defineProperty) {
  2977. _defineProperty(object, key, {
  2978. 'configurable': true,
  2979. 'enumerable': true,
  2980. 'value': value,
  2981. 'writable': true
  2982. });
  2983. } else {
  2984. object[key] = value;
  2985. }
  2986. }
  2987. var _baseAssignValue = baseAssignValue;
  2988. /** Used for built-in method references. */
  2989. var objectProto$5 = Object.prototype;
  2990. /** Used to check objects for own properties. */
  2991. var hasOwnProperty$4 = objectProto$5.hasOwnProperty;
  2992. /**
  2993. * Assigns `value` to `key` of `object` if the existing value is not equivalent
  2994. * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
  2995. * for equality comparisons.
  2996. *
  2997. * @private
  2998. * @param {Object} object The object to modify.
  2999. * @param {string} key The key of the property to assign.
  3000. * @param {*} value The value to assign.
  3001. */
  3002. function assignValue(object, key, value) {
  3003. var objValue = object[key];
  3004. if (!(hasOwnProperty$4.call(object, key) && eq_1(objValue, value)) || value === undefined && !(key in object)) {
  3005. _baseAssignValue(object, key, value);
  3006. }
  3007. }
  3008. var _assignValue = assignValue;
  3009. /** Used as references for various `Number` constants. */
  3010. var MAX_SAFE_INTEGER = 9007199254740991;
  3011. /** Used to detect unsigned integer values. */
  3012. var reIsUint = /^(?:0|[1-9]\d*)$/;
  3013. /**
  3014. * Checks if `value` is a valid array-like index.
  3015. *
  3016. * @private
  3017. * @param {*} value The value to check.
  3018. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
  3019. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
  3020. */
  3021. function isIndex(value, length) {
  3022. var type = typeof value;
  3023. length = length == null ? MAX_SAFE_INTEGER : length;
  3024. return !!length && (type == 'number' || type != 'symbol' && reIsUint.test(value)) && value > -1 && value % 1 == 0 && value < length;
  3025. }
  3026. var _isIndex = isIndex;
  3027. /**
  3028. * The base implementation of `_.set`.
  3029. *
  3030. * @private
  3031. * @param {Object} object The object to modify.
  3032. * @param {Array|string} path The path of the property to set.
  3033. * @param {*} value The value to set.
  3034. * @param {Function} [customizer] The function to customize path creation.
  3035. * @returns {Object} Returns `object`.
  3036. */
  3037. function baseSet(object, path, value, customizer) {
  3038. if (!isObject_1(object)) {
  3039. return object;
  3040. }
  3041. path = _castPath(path, object);
  3042. var index = -1,
  3043. length = path.length,
  3044. lastIndex = length - 1,
  3045. nested = object;
  3046. while (nested != null && ++index < length) {
  3047. var key = _toKey(path[index]),
  3048. newValue = value;
  3049. if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
  3050. return object;
  3051. }
  3052. if (index != lastIndex) {
  3053. var objValue = nested[key];
  3054. newValue = customizer ? customizer(objValue, key, nested) : undefined;
  3055. if (newValue === undefined) {
  3056. newValue = isObject_1(objValue) ? objValue : _isIndex(path[index + 1]) ? [] : {};
  3057. }
  3058. }
  3059. _assignValue(nested, key, newValue);
  3060. nested = nested[key];
  3061. }
  3062. return object;
  3063. }
  3064. var _baseSet = baseSet;
  3065. /**
  3066. * The base implementation of `_.pickBy` without support for iteratee shorthands.
  3067. *
  3068. * @private
  3069. * @param {Object} object The source object.
  3070. * @param {string[]} paths The property paths to pick.
  3071. * @param {Function} predicate The function invoked per property.
  3072. * @returns {Object} Returns the new object.
  3073. */
  3074. function basePickBy(object, paths, predicate) {
  3075. var index = -1,
  3076. length = paths.length,
  3077. result = {};
  3078. while (++index < length) {
  3079. var path = paths[index],
  3080. value = _baseGet(object, path);
  3081. if (predicate(value, path)) {
  3082. _baseSet(result, _castPath(path, object), value);
  3083. }
  3084. }
  3085. return result;
  3086. }
  3087. var _basePickBy = basePickBy;
  3088. /**
  3089. * The base implementation of `_.hasIn` without support for deep paths.
  3090. *
  3091. * @private
  3092. * @param {Object} [object] The object to query.
  3093. * @param {Array|string} key The key to check.
  3094. * @returns {boolean} Returns `true` if `key` exists, else `false`.
  3095. */
  3096. function baseHasIn(object, key) {
  3097. return object != null && key in Object(object);
  3098. }
  3099. var _baseHasIn = baseHasIn;
  3100. /** `Object#toString` result references. */
  3101. var argsTag = '[object Arguments]';
  3102. /**
  3103. * The base implementation of `_.isArguments`.
  3104. *
  3105. * @private
  3106. * @param {*} value The value to check.
  3107. * @returns {boolean} Returns `true` if `value` is an `arguments` object,
  3108. */
  3109. function baseIsArguments(value) {
  3110. return isObjectLike_1(value) && _baseGetTag(value) == argsTag;
  3111. }
  3112. var _baseIsArguments = baseIsArguments;
  3113. /** Used for built-in method references. */
  3114. var objectProto$6 = Object.prototype;
  3115. /** Used to check objects for own properties. */
  3116. var hasOwnProperty$5 = objectProto$6.hasOwnProperty;
  3117. /** Built-in value references. */
  3118. var propertyIsEnumerable = objectProto$6.propertyIsEnumerable;
  3119. /**
  3120. * Checks if `value` is likely an `arguments` object.
  3121. *
  3122. * @static
  3123. * @memberOf _
  3124. * @since 0.1.0
  3125. * @category Lang
  3126. * @param {*} value The value to check.
  3127. * @returns {boolean} Returns `true` if `value` is an `arguments` object,
  3128. * else `false`.
  3129. * @example
  3130. *
  3131. * _.isArguments(function() { return arguments; }());
  3132. * // => true
  3133. *
  3134. * _.isArguments([1, 2, 3]);
  3135. * // => false
  3136. */
  3137. var isArguments = _baseIsArguments(function () {
  3138. return arguments;
  3139. }()) ? _baseIsArguments : function (value) {
  3140. return isObjectLike_1(value) && hasOwnProperty$5.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee');
  3141. };
  3142. var isArguments_1 = isArguments;
  3143. /** Used as references for various `Number` constants. */
  3144. var MAX_SAFE_INTEGER$1 = 9007199254740991;
  3145. /**
  3146. * Checks if `value` is a valid array-like length.
  3147. *
  3148. * **Note:** This method is loosely based on
  3149. * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
  3150. *
  3151. * @static
  3152. * @memberOf _
  3153. * @since 4.0.0
  3154. * @category Lang
  3155. * @param {*} value The value to check.
  3156. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
  3157. * @example
  3158. *
  3159. * _.isLength(3);
  3160. * // => true
  3161. *
  3162. * _.isLength(Number.MIN_VALUE);
  3163. * // => false
  3164. *
  3165. * _.isLength(Infinity);
  3166. * // => false
  3167. *
  3168. * _.isLength('3');
  3169. * // => false
  3170. */
  3171. function isLength(value) {
  3172. return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER$1;
  3173. }
  3174. var isLength_1 = isLength;
  3175. /**
  3176. * Checks if `path` exists on `object`.
  3177. *
  3178. * @private
  3179. * @param {Object} object The object to query.
  3180. * @param {Array|string} path The path to check.
  3181. * @param {Function} hasFunc The function to check properties.
  3182. * @returns {boolean} Returns `true` if `path` exists, else `false`.
  3183. */
  3184. function hasPath(object, path, hasFunc) {
  3185. path = _castPath(path, object);
  3186. var index = -1,
  3187. length = path.length,
  3188. result = false;
  3189. while (++index < length) {
  3190. var key = _toKey(path[index]);
  3191. if (!(result = object != null && hasFunc(object, key))) {
  3192. break;
  3193. }
  3194. object = object[key];
  3195. }
  3196. if (result || ++index != length) {
  3197. return result;
  3198. }
  3199. length = object == null ? 0 : object.length;
  3200. return !!length && isLength_1(length) && _isIndex(key, length) && (isArray_1(object) || isArguments_1(object));
  3201. }
  3202. var _hasPath = hasPath;
  3203. /**
  3204. * Checks if `path` is a direct or inherited property of `object`.
  3205. *
  3206. * @static
  3207. * @memberOf _
  3208. * @since 4.0.0
  3209. * @category Object
  3210. * @param {Object} object The object to query.
  3211. * @param {Array|string} path The path to check.
  3212. * @returns {boolean} Returns `true` if `path` exists, else `false`.
  3213. * @example
  3214. *
  3215. * var object = _.create({ 'a': _.create({ 'b': 2 }) });
  3216. *
  3217. * _.hasIn(object, 'a');
  3218. * // => true
  3219. *
  3220. * _.hasIn(object, 'a.b');
  3221. * // => true
  3222. *
  3223. * _.hasIn(object, ['a', 'b']);
  3224. * // => true
  3225. *
  3226. * _.hasIn(object, 'b');
  3227. * // => false
  3228. */
  3229. function hasIn(object, path) {
  3230. return object != null && _hasPath(object, path, _baseHasIn);
  3231. }
  3232. var hasIn_1 = hasIn;
  3233. /**
  3234. * The base implementation of `_.pick` without support for individual
  3235. * property identifiers.
  3236. *
  3237. * @private
  3238. * @param {Object} object The source object.
  3239. * @param {string[]} paths The property paths to pick.
  3240. * @returns {Object} Returns the new object.
  3241. */
  3242. function basePick(object, paths) {
  3243. return _basePickBy(object, paths, function (value, path) {
  3244. return hasIn_1(object, path);
  3245. });
  3246. }
  3247. var _basePick = basePick;
  3248. /**
  3249. * Appends the elements of `values` to `array`.
  3250. *
  3251. * @private
  3252. * @param {Array} array The array to modify.
  3253. * @param {Array} values The values to append.
  3254. * @returns {Array} Returns `array`.
  3255. */
  3256. function arrayPush(array, values) {
  3257. var index = -1,
  3258. length = values.length,
  3259. offset = array.length;
  3260. while (++index < length) {
  3261. array[offset + index] = values[index];
  3262. }
  3263. return array;
  3264. }
  3265. var _arrayPush = arrayPush;
  3266. /** Built-in value references. */
  3267. var spreadableSymbol = _Symbol ? _Symbol.isConcatSpreadable : undefined;
  3268. /**
  3269. * Checks if `value` is a flattenable `arguments` object or array.
  3270. *
  3271. * @private
  3272. * @param {*} value The value to check.
  3273. * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
  3274. */
  3275. function isFlattenable(value) {
  3276. return isArray_1(value) || isArguments_1(value) || !!(spreadableSymbol && value && value[spreadableSymbol]);
  3277. }
  3278. var _isFlattenable = isFlattenable;
  3279. /**
  3280. * The base implementation of `_.flatten` with support for restricting flattening.
  3281. *
  3282. * @private
  3283. * @param {Array} array The array to flatten.
  3284. * @param {number} depth The maximum recursion depth.
  3285. * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
  3286. * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
  3287. * @param {Array} [result=[]] The initial result value.
  3288. * @returns {Array} Returns the new flattened array.
  3289. */
  3290. function baseFlatten(array, depth, predicate, isStrict, result) {
  3291. var index = -1,
  3292. length = array.length;
  3293. predicate || (predicate = _isFlattenable);
  3294. result || (result = []);
  3295. while (++index < length) {
  3296. var value = array[index];
  3297. if (depth > 0 && predicate(value)) {
  3298. if (depth > 1) {
  3299. // Recursively flatten arrays (susceptible to call stack limits).
  3300. baseFlatten(value, depth - 1, predicate, isStrict, result);
  3301. } else {
  3302. _arrayPush(result, value);
  3303. }
  3304. } else if (!isStrict) {
  3305. result[result.length] = value;
  3306. }
  3307. }
  3308. return result;
  3309. }
  3310. var _baseFlatten = baseFlatten;
  3311. /**
  3312. * Flattens `array` a single level deep.
  3313. *
  3314. * @static
  3315. * @memberOf _
  3316. * @since 0.1.0
  3317. * @category Array
  3318. * @param {Array} array The array to flatten.
  3319. * @returns {Array} Returns the new flattened array.
  3320. * @example
  3321. *
  3322. * _.flatten([1, [2, [3, [4]], 5]]);
  3323. * // => [1, 2, [3, [4]], 5]
  3324. */
  3325. function flatten(array) {
  3326. var length = array == null ? 0 : array.length;
  3327. return length ? _baseFlatten(array, 1) : [];
  3328. }
  3329. var flatten_1 = flatten;
  3330. /**
  3331. * A faster alternative to `Function#apply`, this function invokes `func`
  3332. * with the `this` binding of `thisArg` and the arguments of `args`.
  3333. *
  3334. * @private
  3335. * @param {Function} func The function to invoke.
  3336. * @param {*} thisArg The `this` binding of `func`.
  3337. * @param {Array} args The arguments to invoke `func` with.
  3338. * @returns {*} Returns the result of `func`.
  3339. */
  3340. function apply(func, thisArg, args) {
  3341. switch (args.length) {
  3342. case 0:
  3343. return func.call(thisArg);
  3344. case 1:
  3345. return func.call(thisArg, args[0]);
  3346. case 2:
  3347. return func.call(thisArg, args[0], args[1]);
  3348. case 3:
  3349. return func.call(thisArg, args[0], args[1], args[2]);
  3350. }
  3351. return func.apply(thisArg, args);
  3352. }
  3353. var _apply = apply;
  3354. /* Built-in method references for those with the same name as other `lodash` methods. */
  3355. var nativeMax = Math.max;
  3356. /**
  3357. * A specialized version of `baseRest` which transforms the rest array.
  3358. *
  3359. * @private
  3360. * @param {Function} func The function to apply a rest parameter to.
  3361. * @param {number} [start=func.length-1] The start position of the rest parameter.
  3362. * @param {Function} transform The rest array transform.
  3363. * @returns {Function} Returns the new function.
  3364. */
  3365. function overRest(func, start, transform) {
  3366. start = nativeMax(start === undefined ? func.length - 1 : start, 0);
  3367. return function () {
  3368. var args = arguments,
  3369. index = -1,
  3370. length = nativeMax(args.length - start, 0),
  3371. array = Array(length);
  3372. while (++index < length) {
  3373. array[index] = args[start + index];
  3374. }
  3375. index = -1;
  3376. var otherArgs = Array(start + 1);
  3377. while (++index < start) {
  3378. otherArgs[index] = args[index];
  3379. }
  3380. otherArgs[start] = transform(array);
  3381. return _apply(func, this, otherArgs);
  3382. };
  3383. }
  3384. var _overRest = overRest;
  3385. /**
  3386. * Creates a function that returns `value`.
  3387. *
  3388. * @static
  3389. * @memberOf _
  3390. * @since 2.4.0
  3391. * @category Util
  3392. * @param {*} value The value to return from the new function.
  3393. * @returns {Function} Returns the new constant function.
  3394. * @example
  3395. *
  3396. * var objects = _.times(2, _.constant({ 'a': 1 }));
  3397. *
  3398. * console.log(objects);
  3399. * // => [{ 'a': 1 }, { 'a': 1 }]
  3400. *
  3401. * console.log(objects[0] === objects[1]);
  3402. * // => true
  3403. */
  3404. function constant(value) {
  3405. return function () {
  3406. return value;
  3407. };
  3408. }
  3409. var constant_1 = constant;
  3410. /**
  3411. * This method returns the first argument it receives.
  3412. *
  3413. * @static
  3414. * @since 0.1.0
  3415. * @memberOf _
  3416. * @category Util
  3417. * @param {*} value Any value.
  3418. * @returns {*} Returns `value`.
  3419. * @example
  3420. *
  3421. * var object = { 'a': 1 };
  3422. *
  3423. * console.log(_.identity(object) === object);
  3424. * // => true
  3425. */
  3426. function identity(value) {
  3427. return value;
  3428. }
  3429. var identity_1 = identity;
  3430. /**
  3431. * The base implementation of `setToString` without support for hot loop shorting.
  3432. *
  3433. * @private
  3434. * @param {Function} func The function to modify.
  3435. * @param {Function} string The `toString` result.
  3436. * @returns {Function} Returns `func`.
  3437. */
  3438. var baseSetToString = !_defineProperty ? identity_1 : function (func, string) {
  3439. return _defineProperty(func, 'toString', {
  3440. 'configurable': true,
  3441. 'enumerable': false,
  3442. 'value': constant_1(string),
  3443. 'writable': true
  3444. });
  3445. };
  3446. var _baseSetToString = baseSetToString;
  3447. /** Used to detect hot functions by number of calls within a span of milliseconds. */
  3448. var HOT_COUNT = 800,
  3449. HOT_SPAN = 16;
  3450. /* Built-in method references for those with the same name as other `lodash` methods. */
  3451. var nativeNow = Date.now;
  3452. /**
  3453. * Creates a function that'll short out and invoke `identity` instead
  3454. * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
  3455. * milliseconds.
  3456. *
  3457. * @private
  3458. * @param {Function} func The function to restrict.
  3459. * @returns {Function} Returns the new shortable function.
  3460. */
  3461. function shortOut(func) {
  3462. var count = 0,
  3463. lastCalled = 0;
  3464. return function () {
  3465. var stamp = nativeNow(),
  3466. remaining = HOT_SPAN - (stamp - lastCalled);
  3467. lastCalled = stamp;
  3468. if (remaining > 0) {
  3469. if (++count >= HOT_COUNT) {
  3470. return arguments[0];
  3471. }
  3472. } else {
  3473. count = 0;
  3474. }
  3475. return func.apply(undefined, arguments);
  3476. };
  3477. }
  3478. var _shortOut = shortOut;
  3479. /**
  3480. * Sets the `toString` method of `func` to return `string`.
  3481. *
  3482. * @private
  3483. * @param {Function} func The function to modify.
  3484. * @param {Function} string The `toString` result.
  3485. * @returns {Function} Returns `func`.
  3486. */
  3487. var setToString = _shortOut(_baseSetToString);
  3488. var _setToString = setToString;
  3489. /**
  3490. * A specialized version of `baseRest` which flattens the rest array.
  3491. *
  3492. * @private
  3493. * @param {Function} func The function to apply a rest parameter to.
  3494. * @returns {Function} Returns the new function.
  3495. */
  3496. function flatRest(func) {
  3497. return _setToString(_overRest(func, undefined, flatten_1), func + '');
  3498. }
  3499. var _flatRest = flatRest;
  3500. /**
  3501. * Creates an object composed of the picked `object` properties.
  3502. *
  3503. * @static
  3504. * @since 0.1.0
  3505. * @memberOf _
  3506. * @category Object
  3507. * @param {Object} object The source object.
  3508. * @param {...(string|string[])} [paths] The property paths to pick.
  3509. * @returns {Object} Returns the new object.
  3510. * @example
  3511. *
  3512. * var object = { 'a': 1, 'b': '2', 'c': 3 };
  3513. *
  3514. * _.pick(object, ['a', 'c']);
  3515. * // => { 'a': 1, 'c': 3 }
  3516. */
  3517. var pick = _flatRest(function (object, paths) {
  3518. return object == null ? {} : _basePick(object, paths);
  3519. });
  3520. var pick_1 = pick;
  3521. /**
  3522. * A specialized version of `baseAggregator` for arrays.
  3523. *
  3524. * @private
  3525. * @param {Array} [array] The array to iterate over.
  3526. * @param {Function} setter The function to set `accumulator` values.
  3527. * @param {Function} iteratee The iteratee to transform keys.
  3528. * @param {Object} accumulator The initial aggregated object.
  3529. * @returns {Function} Returns `accumulator`.
  3530. */
  3531. function arrayAggregator(array, setter, iteratee, accumulator) {
  3532. var index = -1,
  3533. length = array == null ? 0 : array.length;
  3534. while (++index < length) {
  3535. var value = array[index];
  3536. setter(accumulator, value, iteratee(value), array);
  3537. }
  3538. return accumulator;
  3539. }
  3540. var _arrayAggregator = arrayAggregator;
  3541. /**
  3542. * Creates a base function for methods like `_.forIn` and `_.forOwn`.
  3543. *
  3544. * @private
  3545. * @param {boolean} [fromRight] Specify iterating from right to left.
  3546. * @returns {Function} Returns the new base function.
  3547. */
  3548. function createBaseFor(fromRight) {
  3549. return function (object, iteratee, keysFunc) {
  3550. var index = -1,
  3551. iterable = Object(object),
  3552. props = keysFunc(object),
  3553. length = props.length;
  3554. while (length--) {
  3555. var key = props[fromRight ? length : ++index];
  3556. if (iteratee(iterable[key], key, iterable) === false) {
  3557. break;
  3558. }
  3559. }
  3560. return object;
  3561. };
  3562. }
  3563. var _createBaseFor = createBaseFor;
  3564. /**
  3565. * The base implementation of `baseForOwn` which iterates over `object`
  3566. * properties returned by `keysFunc` and invokes `iteratee` for each property.
  3567. * Iteratee functions may exit iteration early by explicitly returning `false`.
  3568. *
  3569. * @private
  3570. * @param {Object} object The object to iterate over.
  3571. * @param {Function} iteratee The function invoked per iteration.
  3572. * @param {Function} keysFunc The function to get the keys of `object`.
  3573. * @returns {Object} Returns `object`.
  3574. */
  3575. var baseFor = _createBaseFor();
  3576. var _baseFor = baseFor;
  3577. /**
  3578. * The base implementation of `_.times` without support for iteratee shorthands
  3579. * or max array length checks.
  3580. *
  3581. * @private
  3582. * @param {number} n The number of times to invoke `iteratee`.
  3583. * @param {Function} iteratee The function invoked per iteration.
  3584. * @returns {Array} Returns the array of results.
  3585. */
  3586. function baseTimes(n, iteratee) {
  3587. var index = -1,
  3588. result = Array(n);
  3589. while (++index < n) {
  3590. result[index] = iteratee(index);
  3591. }
  3592. return result;
  3593. }
  3594. var _baseTimes = baseTimes;
  3595. /**
  3596. * This method returns `false`.
  3597. *
  3598. * @static
  3599. * @memberOf _
  3600. * @since 4.13.0
  3601. * @category Util
  3602. * @returns {boolean} Returns `false`.
  3603. * @example
  3604. *
  3605. * _.times(2, _.stubFalse);
  3606. * // => [false, false]
  3607. */
  3608. function stubFalse() {
  3609. return false;
  3610. }
  3611. var stubFalse_1 = stubFalse;
  3612. var isBuffer_1 = createCommonjsModule(function (module, exports) {
  3613. /** Detect free variable `exports`. */
  3614. var freeExports = exports && !exports.nodeType && exports;
  3615. /** Detect free variable `module`. */
  3616. var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
  3617. /** Detect the popular CommonJS extension `module.exports`. */
  3618. var moduleExports = freeModule && freeModule.exports === freeExports;
  3619. /** Built-in value references. */
  3620. var Buffer = moduleExports ? _root.Buffer : undefined;
  3621. /* Built-in method references for those with the same name as other `lodash` methods. */
  3622. var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
  3623. /**
  3624. * Checks if `value` is a buffer.
  3625. *
  3626. * @static
  3627. * @memberOf _
  3628. * @since 4.3.0
  3629. * @category Lang
  3630. * @param {*} value The value to check.
  3631. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
  3632. * @example
  3633. *
  3634. * _.isBuffer(new Buffer(2));
  3635. * // => true
  3636. *
  3637. * _.isBuffer(new Uint8Array(2));
  3638. * // => false
  3639. */
  3640. var isBuffer = nativeIsBuffer || stubFalse_1;
  3641. module.exports = isBuffer;
  3642. });
  3643. /** `Object#toString` result references. */
  3644. var argsTag$1 = '[object Arguments]',
  3645. arrayTag = '[object Array]',
  3646. boolTag = '[object Boolean]',
  3647. dateTag = '[object Date]',
  3648. errorTag = '[object Error]',
  3649. funcTag$1 = '[object Function]',
  3650. mapTag = '[object Map]',
  3651. numberTag = '[object Number]',
  3652. objectTag = '[object Object]',
  3653. regexpTag = '[object RegExp]',
  3654. setTag = '[object Set]',
  3655. stringTag = '[object String]',
  3656. weakMapTag = '[object WeakMap]';
  3657. var arrayBufferTag = '[object ArrayBuffer]',
  3658. dataViewTag = '[object DataView]',
  3659. float32Tag = '[object Float32Array]',
  3660. float64Tag = '[object Float64Array]',
  3661. int8Tag = '[object Int8Array]',
  3662. int16Tag = '[object Int16Array]',
  3663. int32Tag = '[object Int32Array]',
  3664. uint8Tag = '[object Uint8Array]',
  3665. uint8ClampedTag = '[object Uint8ClampedArray]',
  3666. uint16Tag = '[object Uint16Array]',
  3667. uint32Tag = '[object Uint32Array]';
  3668. /** Used to identify `toStringTag` values of typed arrays. */
  3669. var typedArrayTags = {};
  3670. typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true;
  3671. typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag$1] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;
  3672. /**
  3673. * The base implementation of `_.isTypedArray` without Node.js optimizations.
  3674. *
  3675. * @private
  3676. * @param {*} value The value to check.
  3677. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
  3678. */
  3679. function baseIsTypedArray(value) {
  3680. return isObjectLike_1(value) && isLength_1(value.length) && !!typedArrayTags[_baseGetTag(value)];
  3681. }
  3682. var _baseIsTypedArray = baseIsTypedArray;
  3683. /**
  3684. * The base implementation of `_.unary` without support for storing metadata.
  3685. *
  3686. * @private
  3687. * @param {Function} func The function to cap arguments for.
  3688. * @returns {Function} Returns the new capped function.
  3689. */
  3690. function baseUnary(func) {
  3691. return function (value) {
  3692. return func(value);
  3693. };
  3694. }
  3695. var _baseUnary = baseUnary;
  3696. var _nodeUtil = createCommonjsModule(function (module, exports) {
  3697. /** Detect free variable `exports`. */
  3698. var freeExports = exports && !exports.nodeType && exports;
  3699. /** Detect free variable `module`. */
  3700. var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
  3701. /** Detect the popular CommonJS extension `module.exports`. */
  3702. var moduleExports = freeModule && freeModule.exports === freeExports;
  3703. /** Detect free variable `process` from Node.js. */
  3704. var freeProcess = moduleExports && _freeGlobal.process;
  3705. /** Used to access faster Node.js helpers. */
  3706. var nodeUtil = function () {
  3707. try {
  3708. // Use `util.types` for Node.js 10+.
  3709. var types = freeModule && freeModule.require && freeModule.require('util').types;
  3710. if (types) {
  3711. return types;
  3712. } // Legacy `process.binding('util')` for Node.js < 10.
  3713. return freeProcess && freeProcess.binding && freeProcess.binding('util');
  3714. } catch (e) {}
  3715. }();
  3716. module.exports = nodeUtil;
  3717. });
  3718. /* Node.js helper references. */
  3719. var nodeIsTypedArray = _nodeUtil && _nodeUtil.isTypedArray;
  3720. /**
  3721. * Checks if `value` is classified as a typed array.
  3722. *
  3723. * @static
  3724. * @memberOf _
  3725. * @since 3.0.0
  3726. * @category Lang
  3727. * @param {*} value The value to check.
  3728. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
  3729. * @example
  3730. *
  3731. * _.isTypedArray(new Uint8Array);
  3732. * // => true
  3733. *
  3734. * _.isTypedArray([]);
  3735. * // => false
  3736. */
  3737. var isTypedArray = nodeIsTypedArray ? _baseUnary(nodeIsTypedArray) : _baseIsTypedArray;
  3738. var isTypedArray_1 = isTypedArray;
  3739. /** Used for built-in method references. */
  3740. var objectProto$7 = Object.prototype;
  3741. /** Used to check objects for own properties. */
  3742. var hasOwnProperty$6 = objectProto$7.hasOwnProperty;
  3743. /**
  3744. * Creates an array of the enumerable property names of the array-like `value`.
  3745. *
  3746. * @private
  3747. * @param {*} value The value to query.
  3748. * @param {boolean} inherited Specify returning inherited property names.
  3749. * @returns {Array} Returns the array of property names.
  3750. */
  3751. function arrayLikeKeys(value, inherited) {
  3752. var isArr = isArray_1(value),
  3753. isArg = !isArr && isArguments_1(value),
  3754. isBuff = !isArr && !isArg && isBuffer_1(value),
  3755. isType = !isArr && !isArg && !isBuff && isTypedArray_1(value),
  3756. skipIndexes = isArr || isArg || isBuff || isType,
  3757. result = skipIndexes ? _baseTimes(value.length, String) : [],
  3758. length = result.length;
  3759. for (var key in value) {
  3760. if ((inherited || hasOwnProperty$6.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode.
  3761. key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers.
  3762. isBuff && (key == 'offset' || key == 'parent') || // PhantomJS 2 has enumerable non-index properties on typed arrays.
  3763. isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset') || // Skip index properties.
  3764. _isIndex(key, length)))) {
  3765. result.push(key);
  3766. }
  3767. }
  3768. return result;
  3769. }
  3770. var _arrayLikeKeys = arrayLikeKeys;
  3771. /** Used for built-in method references. */
  3772. var objectProto$8 = Object.prototype;
  3773. /**
  3774. * Checks if `value` is likely a prototype object.
  3775. *
  3776. * @private
  3777. * @param {*} value The value to check.
  3778. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
  3779. */
  3780. function isPrototype(value) {
  3781. var Ctor = value && value.constructor,
  3782. proto = typeof Ctor == 'function' && Ctor.prototype || objectProto$8;
  3783. return value === proto;
  3784. }
  3785. var _isPrototype = isPrototype;
  3786. /**
  3787. * Creates a unary function that invokes `func` with its argument transformed.
  3788. *
  3789. * @private
  3790. * @param {Function} func The function to wrap.
  3791. * @param {Function} transform The argument transform.
  3792. * @returns {Function} Returns the new function.
  3793. */
  3794. function overArg(func, transform) {
  3795. return function (arg) {
  3796. return func(transform(arg));
  3797. };
  3798. }
  3799. var _overArg = overArg;
  3800. /* Built-in method references for those with the same name as other `lodash` methods. */
  3801. var nativeKeys = _overArg(Object.keys, Object);
  3802. var _nativeKeys = nativeKeys;
  3803. /** Used for built-in method references. */
  3804. var objectProto$9 = Object.prototype;
  3805. /** Used to check objects for own properties. */
  3806. var hasOwnProperty$7 = objectProto$9.hasOwnProperty;
  3807. /**
  3808. * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
  3809. *
  3810. * @private
  3811. * @param {Object} object The object to query.
  3812. * @returns {Array} Returns the array of property names.
  3813. */
  3814. function baseKeys(object) {
  3815. if (!_isPrototype(object)) {
  3816. return _nativeKeys(object);
  3817. }
  3818. var result = [];
  3819. for (var key in Object(object)) {
  3820. if (hasOwnProperty$7.call(object, key) && key != 'constructor') {
  3821. result.push(key);
  3822. }
  3823. }
  3824. return result;
  3825. }
  3826. var _baseKeys = baseKeys;
  3827. /**
  3828. * Checks if `value` is array-like. A value is considered array-like if it's
  3829. * not a function and has a `value.length` that's an integer greater than or
  3830. * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
  3831. *
  3832. * @static
  3833. * @memberOf _
  3834. * @since 4.0.0
  3835. * @category Lang
  3836. * @param {*} value The value to check.
  3837. * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
  3838. * @example
  3839. *
  3840. * _.isArrayLike([1, 2, 3]);
  3841. * // => true
  3842. *
  3843. * _.isArrayLike(document.body.children);
  3844. * // => true
  3845. *
  3846. * _.isArrayLike('abc');
  3847. * // => true
  3848. *
  3849. * _.isArrayLike(_.noop);
  3850. * // => false
  3851. */
  3852. function isArrayLike(value) {
  3853. return value != null && isLength_1(value.length) && !isFunction_1(value);
  3854. }
  3855. var isArrayLike_1 = isArrayLike;
  3856. /**
  3857. * Creates an array of the own enumerable property names of `object`.
  3858. *
  3859. * **Note:** Non-object values are coerced to objects. See the
  3860. * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
  3861. * for more details.
  3862. *
  3863. * @static
  3864. * @since 0.1.0
  3865. * @memberOf _
  3866. * @category Object
  3867. * @param {Object} object The object to query.
  3868. * @returns {Array} Returns the array of property names.
  3869. * @example
  3870. *
  3871. * function Foo() {
  3872. * this.a = 1;
  3873. * this.b = 2;
  3874. * }
  3875. *
  3876. * Foo.prototype.c = 3;
  3877. *
  3878. * _.keys(new Foo);
  3879. * // => ['a', 'b'] (iteration order is not guaranteed)
  3880. *
  3881. * _.keys('hi');
  3882. * // => ['0', '1']
  3883. */
  3884. function keys(object) {
  3885. return isArrayLike_1(object) ? _arrayLikeKeys(object) : _baseKeys(object);
  3886. }
  3887. var keys_1 = keys;
  3888. /**
  3889. * The base implementation of `_.forOwn` without support for iteratee shorthands.
  3890. *
  3891. * @private
  3892. * @param {Object} object The object to iterate over.
  3893. * @param {Function} iteratee The function invoked per iteration.
  3894. * @returns {Object} Returns `object`.
  3895. */
  3896. function baseForOwn(object, iteratee) {
  3897. return object && _baseFor(object, iteratee, keys_1);
  3898. }
  3899. var _baseForOwn = baseForOwn;
  3900. /**
  3901. * Creates a `baseEach` or `baseEachRight` function.
  3902. *
  3903. * @private
  3904. * @param {Function} eachFunc The function to iterate over a collection.
  3905. * @param {boolean} [fromRight] Specify iterating from right to left.
  3906. * @returns {Function} Returns the new base function.
  3907. */
  3908. function createBaseEach(eachFunc, fromRight) {
  3909. return function (collection, iteratee) {
  3910. if (collection == null) {
  3911. return collection;
  3912. }
  3913. if (!isArrayLike_1(collection)) {
  3914. return eachFunc(collection, iteratee);
  3915. }
  3916. var length = collection.length,
  3917. index = fromRight ? length : -1,
  3918. iterable = Object(collection);
  3919. while (fromRight ? index-- : ++index < length) {
  3920. if (iteratee(iterable[index], index, iterable) === false) {
  3921. break;
  3922. }
  3923. }
  3924. return collection;
  3925. };
  3926. }
  3927. var _createBaseEach = createBaseEach;
  3928. /**
  3929. * The base implementation of `_.forEach` without support for iteratee shorthands.
  3930. *
  3931. * @private
  3932. * @param {Array|Object} collection The collection to iterate over.
  3933. * @param {Function} iteratee The function invoked per iteration.
  3934. * @returns {Array|Object} Returns `collection`.
  3935. */
  3936. var baseEach = _createBaseEach(_baseForOwn);
  3937. var _baseEach = baseEach;
  3938. /**
  3939. * Aggregates elements of `collection` on `accumulator` with keys transformed
  3940. * by `iteratee` and values set by `setter`.
  3941. *
  3942. * @private
  3943. * @param {Array|Object} collection The collection to iterate over.
  3944. * @param {Function} setter The function to set `accumulator` values.
  3945. * @param {Function} iteratee The iteratee to transform keys.
  3946. * @param {Object} accumulator The initial aggregated object.
  3947. * @returns {Function} Returns `accumulator`.
  3948. */
  3949. function baseAggregator(collection, setter, iteratee, accumulator) {
  3950. _baseEach(collection, function (value, key, collection) {
  3951. setter(accumulator, value, iteratee(value), collection);
  3952. });
  3953. return accumulator;
  3954. }
  3955. var _baseAggregator = baseAggregator;
  3956. /**
  3957. * Removes all key-value entries from the stack.
  3958. *
  3959. * @private
  3960. * @name clear
  3961. * @memberOf Stack
  3962. */
  3963. function stackClear() {
  3964. this.__data__ = new _ListCache();
  3965. this.size = 0;
  3966. }
  3967. var _stackClear = stackClear;
  3968. /**
  3969. * Removes `key` and its value from the stack.
  3970. *
  3971. * @private
  3972. * @name delete
  3973. * @memberOf Stack
  3974. * @param {string} key The key of the value to remove.
  3975. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  3976. */
  3977. function stackDelete(key) {
  3978. var data = this.__data__,
  3979. result = data['delete'](key);
  3980. this.size = data.size;
  3981. return result;
  3982. }
  3983. var _stackDelete = stackDelete;
  3984. /**
  3985. * Gets the stack value for `key`.
  3986. *
  3987. * @private
  3988. * @name get
  3989. * @memberOf Stack
  3990. * @param {string} key The key of the value to get.
  3991. * @returns {*} Returns the entry value.
  3992. */
  3993. function stackGet(key) {
  3994. return this.__data__.get(key);
  3995. }
  3996. var _stackGet = stackGet;
  3997. /**
  3998. * Checks if a stack value for `key` exists.
  3999. *
  4000. * @private
  4001. * @name has
  4002. * @memberOf Stack
  4003. * @param {string} key The key of the entry to check.
  4004. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  4005. */
  4006. function stackHas(key) {
  4007. return this.__data__.has(key);
  4008. }
  4009. var _stackHas = stackHas;
  4010. /** Used as the size to enable large array optimizations. */
  4011. var LARGE_ARRAY_SIZE = 200;
  4012. /**
  4013. * Sets the stack `key` to `value`.
  4014. *
  4015. * @private
  4016. * @name set
  4017. * @memberOf Stack
  4018. * @param {string} key The key of the value to set.
  4019. * @param {*} value The value to set.
  4020. * @returns {Object} Returns the stack cache instance.
  4021. */
  4022. function stackSet(key, value) {
  4023. var data = this.__data__;
  4024. if (data instanceof _ListCache) {
  4025. var pairs = data.__data__;
  4026. if (!_Map || pairs.length < LARGE_ARRAY_SIZE - 1) {
  4027. pairs.push([key, value]);
  4028. this.size = ++data.size;
  4029. return this;
  4030. }
  4031. data = this.__data__ = new _MapCache(pairs);
  4032. }
  4033. data.set(key, value);
  4034. this.size = data.size;
  4035. return this;
  4036. }
  4037. var _stackSet = stackSet;
  4038. /**
  4039. * Creates a stack cache object to store key-value pairs.
  4040. *
  4041. * @private
  4042. * @constructor
  4043. * @param {Array} [entries] The key-value pairs to cache.
  4044. */
  4045. function Stack(entries) {
  4046. var data = this.__data__ = new _ListCache(entries);
  4047. this.size = data.size;
  4048. } // Add methods to `Stack`.
  4049. Stack.prototype.clear = _stackClear;
  4050. Stack.prototype['delete'] = _stackDelete;
  4051. Stack.prototype.get = _stackGet;
  4052. Stack.prototype.has = _stackHas;
  4053. Stack.prototype.set = _stackSet;
  4054. var _Stack = Stack;
  4055. /** Used to stand-in for `undefined` hash values. */
  4056. var HASH_UNDEFINED$2 = '__lodash_hash_undefined__';
  4057. /**
  4058. * Adds `value` to the array cache.
  4059. *
  4060. * @private
  4061. * @name add
  4062. * @memberOf SetCache
  4063. * @alias push
  4064. * @param {*} value The value to cache.
  4065. * @returns {Object} Returns the cache instance.
  4066. */
  4067. function setCacheAdd(value) {
  4068. this.__data__.set(value, HASH_UNDEFINED$2);
  4069. return this;
  4070. }
  4071. var _setCacheAdd = setCacheAdd;
  4072. /**
  4073. * Checks if `value` is in the array cache.
  4074. *
  4075. * @private
  4076. * @name has
  4077. * @memberOf SetCache
  4078. * @param {*} value The value to search for.
  4079. * @returns {number} Returns `true` if `value` is found, else `false`.
  4080. */
  4081. function setCacheHas(value) {
  4082. return this.__data__.has(value);
  4083. }
  4084. var _setCacheHas = setCacheHas;
  4085. /**
  4086. *
  4087. * Creates an array cache object to store unique values.
  4088. *
  4089. * @private
  4090. * @constructor
  4091. * @param {Array} [values] The values to cache.
  4092. */
  4093. function SetCache(values) {
  4094. var index = -1,
  4095. length = values == null ? 0 : values.length;
  4096. this.__data__ = new _MapCache();
  4097. while (++index < length) {
  4098. this.add(values[index]);
  4099. }
  4100. } // Add methods to `SetCache`.
  4101. SetCache.prototype.add = SetCache.prototype.push = _setCacheAdd;
  4102. SetCache.prototype.has = _setCacheHas;
  4103. var _SetCache = SetCache;
  4104. /**
  4105. * A specialized version of `_.some` for arrays without support for iteratee
  4106. * shorthands.
  4107. *
  4108. * @private
  4109. * @param {Array} [array] The array to iterate over.
  4110. * @param {Function} predicate The function invoked per iteration.
  4111. * @returns {boolean} Returns `true` if any element passes the predicate check,
  4112. * else `false`.
  4113. */
  4114. function arraySome(array, predicate) {
  4115. var index = -1,
  4116. length = array == null ? 0 : array.length;
  4117. while (++index < length) {
  4118. if (predicate(array[index], index, array)) {
  4119. return true;
  4120. }
  4121. }
  4122. return false;
  4123. }
  4124. var _arraySome = arraySome;
  4125. /**
  4126. * Checks if a `cache` value for `key` exists.
  4127. *
  4128. * @private
  4129. * @param {Object} cache The cache to query.
  4130. * @param {string} key The key of the entry to check.
  4131. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  4132. */
  4133. function cacheHas(cache, key) {
  4134. return cache.has(key);
  4135. }
  4136. var _cacheHas = cacheHas;
  4137. /** Used to compose bitmasks for value comparisons. */
  4138. var COMPARE_PARTIAL_FLAG = 1,
  4139. COMPARE_UNORDERED_FLAG = 2;
  4140. /**
  4141. * A specialized version of `baseIsEqualDeep` for arrays with support for
  4142. * partial deep comparisons.
  4143. *
  4144. * @private
  4145. * @param {Array} array The array to compare.
  4146. * @param {Array} other The other array to compare.
  4147. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
  4148. * @param {Function} customizer The function to customize comparisons.
  4149. * @param {Function} equalFunc The function to determine equivalents of values.
  4150. * @param {Object} stack Tracks traversed `array` and `other` objects.
  4151. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
  4152. */
  4153. function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
  4154. var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
  4155. arrLength = array.length,
  4156. othLength = other.length;
  4157. if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
  4158. return false;
  4159. } // Check that cyclic values are equal.
  4160. var arrStacked = stack.get(array);
  4161. var othStacked = stack.get(other);
  4162. if (arrStacked && othStacked) {
  4163. return arrStacked == other && othStacked == array;
  4164. }
  4165. var index = -1,
  4166. result = true,
  4167. seen = bitmask & COMPARE_UNORDERED_FLAG ? new _SetCache() : undefined;
  4168. stack.set(array, other);
  4169. stack.set(other, array); // Ignore non-index properties.
  4170. while (++index < arrLength) {
  4171. var arrValue = array[index],
  4172. othValue = other[index];
  4173. if (customizer) {
  4174. var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack);
  4175. }
  4176. if (compared !== undefined) {
  4177. if (compared) {
  4178. continue;
  4179. }
  4180. result = false;
  4181. break;
  4182. } // Recursively compare arrays (susceptible to call stack limits).
  4183. if (seen) {
  4184. if (!_arraySome(other, function (othValue, othIndex) {
  4185. if (!_cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
  4186. return seen.push(othIndex);
  4187. }
  4188. })) {
  4189. result = false;
  4190. break;
  4191. }
  4192. } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
  4193. result = false;
  4194. break;
  4195. }
  4196. }
  4197. stack['delete'](array);
  4198. stack['delete'](other);
  4199. return result;
  4200. }
  4201. var _equalArrays = equalArrays;
  4202. /** Built-in value references. */
  4203. var Uint8Array = _root.Uint8Array;
  4204. var _Uint8Array = Uint8Array;
  4205. /**
  4206. * Converts `map` to its key-value pairs.
  4207. *
  4208. * @private
  4209. * @param {Object} map The map to convert.
  4210. * @returns {Array} Returns the key-value pairs.
  4211. */
  4212. function mapToArray(map) {
  4213. var index = -1,
  4214. result = Array(map.size);
  4215. map.forEach(function (value, key) {
  4216. result[++index] = [key, value];
  4217. });
  4218. return result;
  4219. }
  4220. var _mapToArray = mapToArray;
  4221. /**
  4222. * Converts `set` to an array of its values.
  4223. *
  4224. * @private
  4225. * @param {Object} set The set to convert.
  4226. * @returns {Array} Returns the values.
  4227. */
  4228. function setToArray(set) {
  4229. var index = -1,
  4230. result = Array(set.size);
  4231. set.forEach(function (value) {
  4232. result[++index] = value;
  4233. });
  4234. return result;
  4235. }
  4236. var _setToArray = setToArray;
  4237. /** Used to compose bitmasks for value comparisons. */
  4238. var COMPARE_PARTIAL_FLAG$1 = 1,
  4239. COMPARE_UNORDERED_FLAG$1 = 2;
  4240. /** `Object#toString` result references. */
  4241. var boolTag$1 = '[object Boolean]',
  4242. dateTag$1 = '[object Date]',
  4243. errorTag$1 = '[object Error]',
  4244. mapTag$1 = '[object Map]',
  4245. numberTag$1 = '[object Number]',
  4246. regexpTag$1 = '[object RegExp]',
  4247. setTag$1 = '[object Set]',
  4248. stringTag$1 = '[object String]',
  4249. symbolTag$1 = '[object Symbol]';
  4250. var arrayBufferTag$1 = '[object ArrayBuffer]',
  4251. dataViewTag$1 = '[object DataView]';
  4252. /** Used to convert symbols to primitives and strings. */
  4253. var symbolProto$1 = _Symbol ? _Symbol.prototype : undefined,
  4254. symbolValueOf = symbolProto$1 ? symbolProto$1.valueOf : undefined;
  4255. /**
  4256. * A specialized version of `baseIsEqualDeep` for comparing objects of
  4257. * the same `toStringTag`.
  4258. *
  4259. * **Note:** This function only supports comparing values with tags of
  4260. * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
  4261. *
  4262. * @private
  4263. * @param {Object} object The object to compare.
  4264. * @param {Object} other The other object to compare.
  4265. * @param {string} tag The `toStringTag` of the objects to compare.
  4266. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
  4267. * @param {Function} customizer The function to customize comparisons.
  4268. * @param {Function} equalFunc The function to determine equivalents of values.
  4269. * @param {Object} stack Tracks traversed `object` and `other` objects.
  4270. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
  4271. */
  4272. function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
  4273. switch (tag) {
  4274. case dataViewTag$1:
  4275. if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) {
  4276. return false;
  4277. }
  4278. object = object.buffer;
  4279. other = other.buffer;
  4280. case arrayBufferTag$1:
  4281. if (object.byteLength != other.byteLength || !equalFunc(new _Uint8Array(object), new _Uint8Array(other))) {
  4282. return false;
  4283. }
  4284. return true;
  4285. case boolTag$1:
  4286. case dateTag$1:
  4287. case numberTag$1:
  4288. // Coerce booleans to `1` or `0` and dates to milliseconds.
  4289. // Invalid dates are coerced to `NaN`.
  4290. return eq_1(+object, +other);
  4291. case errorTag$1:
  4292. return object.name == other.name && object.message == other.message;
  4293. case regexpTag$1:
  4294. case stringTag$1:
  4295. // Coerce regexes to strings and treat strings, primitives and objects,
  4296. // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
  4297. // for more details.
  4298. return object == other + '';
  4299. case mapTag$1:
  4300. var convert = _mapToArray;
  4301. case setTag$1:
  4302. var isPartial = bitmask & COMPARE_PARTIAL_FLAG$1;
  4303. convert || (convert = _setToArray);
  4304. if (object.size != other.size && !isPartial) {
  4305. return false;
  4306. } // Assume cyclic values are equal.
  4307. var stacked = stack.get(object);
  4308. if (stacked) {
  4309. return stacked == other;
  4310. }
  4311. bitmask |= COMPARE_UNORDERED_FLAG$1; // Recursively compare objects (susceptible to call stack limits).
  4312. stack.set(object, other);
  4313. var result = _equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
  4314. stack['delete'](object);
  4315. return result;
  4316. case symbolTag$1:
  4317. if (symbolValueOf) {
  4318. return symbolValueOf.call(object) == symbolValueOf.call(other);
  4319. }
  4320. }
  4321. return false;
  4322. }
  4323. var _equalByTag = equalByTag;
  4324. /**
  4325. * The base implementation of `getAllKeys` and `getAllKeysIn` which uses
  4326. * `keysFunc` and `symbolsFunc` to get the enumerable property names and
  4327. * symbols of `object`.
  4328. *
  4329. * @private
  4330. * @param {Object} object The object to query.
  4331. * @param {Function} keysFunc The function to get the keys of `object`.
  4332. * @param {Function} symbolsFunc The function to get the symbols of `object`.
  4333. * @returns {Array} Returns the array of property names and symbols.
  4334. */
  4335. function baseGetAllKeys(object, keysFunc, symbolsFunc) {
  4336. var result = keysFunc(object);
  4337. return isArray_1(object) ? result : _arrayPush(result, symbolsFunc(object));
  4338. }
  4339. var _baseGetAllKeys = baseGetAllKeys;
  4340. /**
  4341. * A specialized version of `_.filter` for arrays without support for
  4342. * iteratee shorthands.
  4343. *
  4344. * @private
  4345. * @param {Array} [array] The array to iterate over.
  4346. * @param {Function} predicate The function invoked per iteration.
  4347. * @returns {Array} Returns the new filtered array.
  4348. */
  4349. function arrayFilter(array, predicate) {
  4350. var index = -1,
  4351. length = array == null ? 0 : array.length,
  4352. resIndex = 0,
  4353. result = [];
  4354. while (++index < length) {
  4355. var value = array[index];
  4356. if (predicate(value, index, array)) {
  4357. result[resIndex++] = value;
  4358. }
  4359. }
  4360. return result;
  4361. }
  4362. var _arrayFilter = arrayFilter;
  4363. /**
  4364. * This method returns a new empty array.
  4365. *
  4366. * @static
  4367. * @memberOf _
  4368. * @since 4.13.0
  4369. * @category Util
  4370. * @returns {Array} Returns the new empty array.
  4371. * @example
  4372. *
  4373. * var arrays = _.times(2, _.stubArray);
  4374. *
  4375. * console.log(arrays);
  4376. * // => [[], []]
  4377. *
  4378. * console.log(arrays[0] === arrays[1]);
  4379. * // => false
  4380. */
  4381. function stubArray() {
  4382. return [];
  4383. }
  4384. var stubArray_1 = stubArray;
  4385. /** Used for built-in method references. */
  4386. var objectProto$a = Object.prototype;
  4387. /** Built-in value references. */
  4388. var propertyIsEnumerable$1 = objectProto$a.propertyIsEnumerable;
  4389. /* Built-in method references for those with the same name as other `lodash` methods. */
  4390. var nativeGetSymbols = Object.getOwnPropertySymbols;
  4391. /**
  4392. * Creates an array of the own enumerable symbols of `object`.
  4393. *
  4394. * @private
  4395. * @param {Object} object The object to query.
  4396. * @returns {Array} Returns the array of symbols.
  4397. */
  4398. var getSymbols = !nativeGetSymbols ? stubArray_1 : function (object) {
  4399. if (object == null) {
  4400. return [];
  4401. }
  4402. object = Object(object);
  4403. return _arrayFilter(nativeGetSymbols(object), function (symbol) {
  4404. return propertyIsEnumerable$1.call(object, symbol);
  4405. });
  4406. };
  4407. var _getSymbols = getSymbols;
  4408. /**
  4409. * Creates an array of own enumerable property names and symbols of `object`.
  4410. *
  4411. * @private
  4412. * @param {Object} object The object to query.
  4413. * @returns {Array} Returns the array of property names and symbols.
  4414. */
  4415. function getAllKeys(object) {
  4416. return _baseGetAllKeys(object, keys_1, _getSymbols);
  4417. }
  4418. var _getAllKeys = getAllKeys;
  4419. /** Used to compose bitmasks for value comparisons. */
  4420. var COMPARE_PARTIAL_FLAG$2 = 1;
  4421. /** Used for built-in method references. */
  4422. var objectProto$b = Object.prototype;
  4423. /** Used to check objects for own properties. */
  4424. var hasOwnProperty$8 = objectProto$b.hasOwnProperty;
  4425. /**
  4426. * A specialized version of `baseIsEqualDeep` for objects with support for
  4427. * partial deep comparisons.
  4428. *
  4429. * @private
  4430. * @param {Object} object The object to compare.
  4431. * @param {Object} other The other object to compare.
  4432. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
  4433. * @param {Function} customizer The function to customize comparisons.
  4434. * @param {Function} equalFunc The function to determine equivalents of values.
  4435. * @param {Object} stack Tracks traversed `object` and `other` objects.
  4436. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
  4437. */
  4438. function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
  4439. var isPartial = bitmask & COMPARE_PARTIAL_FLAG$2,
  4440. objProps = _getAllKeys(object),
  4441. objLength = objProps.length,
  4442. othProps = _getAllKeys(other),
  4443. othLength = othProps.length;
  4444. if (objLength != othLength && !isPartial) {
  4445. return false;
  4446. }
  4447. var index = objLength;
  4448. while (index--) {
  4449. var key = objProps[index];
  4450. if (!(isPartial ? key in other : hasOwnProperty$8.call(other, key))) {
  4451. return false;
  4452. }
  4453. } // Check that cyclic values are equal.
  4454. var objStacked = stack.get(object);
  4455. var othStacked = stack.get(other);
  4456. if (objStacked && othStacked) {
  4457. return objStacked == other && othStacked == object;
  4458. }
  4459. var result = true;
  4460. stack.set(object, other);
  4461. stack.set(other, object);
  4462. var skipCtor = isPartial;
  4463. while (++index < objLength) {
  4464. key = objProps[index];
  4465. var objValue = object[key],
  4466. othValue = other[key];
  4467. if (customizer) {
  4468. var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack);
  4469. } // Recursively compare objects (susceptible to call stack limits).
  4470. if (!(compared === undefined ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack) : compared)) {
  4471. result = false;
  4472. break;
  4473. }
  4474. skipCtor || (skipCtor = key == 'constructor');
  4475. }
  4476. if (result && !skipCtor) {
  4477. var objCtor = object.constructor,
  4478. othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal.
  4479. if (objCtor != othCtor && 'constructor' in object && 'constructor' in other && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) {
  4480. result = false;
  4481. }
  4482. }
  4483. stack['delete'](object);
  4484. stack['delete'](other);
  4485. return result;
  4486. }
  4487. var _equalObjects = equalObjects;
  4488. /* Built-in method references that are verified to be native. */
  4489. var DataView = _getNative(_root, 'DataView');
  4490. var _DataView = DataView;
  4491. /* Built-in method references that are verified to be native. */
  4492. var Promise$1 = _getNative(_root, 'Promise');
  4493. var _Promise = Promise$1;
  4494. /* Built-in method references that are verified to be native. */
  4495. var Set$1 = _getNative(_root, 'Set');
  4496. var _Set = Set$1;
  4497. /* Built-in method references that are verified to be native. */
  4498. var WeakMap$1 = _getNative(_root, 'WeakMap');
  4499. var _WeakMap = WeakMap$1;
  4500. /** `Object#toString` result references. */
  4501. var mapTag$2 = '[object Map]',
  4502. objectTag$1 = '[object Object]',
  4503. promiseTag = '[object Promise]',
  4504. setTag$2 = '[object Set]',
  4505. weakMapTag$1 = '[object WeakMap]';
  4506. var dataViewTag$2 = '[object DataView]';
  4507. /** Used to detect maps, sets, and weakmaps. */
  4508. var dataViewCtorString = _toSource(_DataView),
  4509. mapCtorString = _toSource(_Map),
  4510. promiseCtorString = _toSource(_Promise),
  4511. setCtorString = _toSource(_Set),
  4512. weakMapCtorString = _toSource(_WeakMap);
  4513. /**
  4514. * Gets the `toStringTag` of `value`.
  4515. *
  4516. * @private
  4517. * @param {*} value The value to query.
  4518. * @returns {string} Returns the `toStringTag`.
  4519. */
  4520. var getTag = _baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
  4521. if (_DataView && getTag(new _DataView(new ArrayBuffer(1))) != dataViewTag$2 || _Map && getTag(new _Map()) != mapTag$2 || _Promise && getTag(_Promise.resolve()) != promiseTag || _Set && getTag(new _Set()) != setTag$2 || _WeakMap && getTag(new _WeakMap()) != weakMapTag$1) {
  4522. getTag = function (value) {
  4523. var result = _baseGetTag(value),
  4524. Ctor = result == objectTag$1 ? value.constructor : undefined,
  4525. ctorString = Ctor ? _toSource(Ctor) : '';
  4526. if (ctorString) {
  4527. switch (ctorString) {
  4528. case dataViewCtorString:
  4529. return dataViewTag$2;
  4530. case mapCtorString:
  4531. return mapTag$2;
  4532. case promiseCtorString:
  4533. return promiseTag;
  4534. case setCtorString:
  4535. return setTag$2;
  4536. case weakMapCtorString:
  4537. return weakMapTag$1;
  4538. }
  4539. }
  4540. return result;
  4541. };
  4542. }
  4543. var _getTag = getTag;
  4544. /** Used to compose bitmasks for value comparisons. */
  4545. var COMPARE_PARTIAL_FLAG$3 = 1;
  4546. /** `Object#toString` result references. */
  4547. var argsTag$2 = '[object Arguments]',
  4548. arrayTag$1 = '[object Array]',
  4549. objectTag$2 = '[object Object]';
  4550. /** Used for built-in method references. */
  4551. var objectProto$c = Object.prototype;
  4552. /** Used to check objects for own properties. */
  4553. var hasOwnProperty$9 = objectProto$c.hasOwnProperty;
  4554. /**
  4555. * A specialized version of `baseIsEqual` for arrays and objects which performs
  4556. * deep comparisons and tracks traversed objects enabling objects with circular
  4557. * references to be compared.
  4558. *
  4559. * @private
  4560. * @param {Object} object The object to compare.
  4561. * @param {Object} other The other object to compare.
  4562. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
  4563. * @param {Function} customizer The function to customize comparisons.
  4564. * @param {Function} equalFunc The function to determine equivalents of values.
  4565. * @param {Object} [stack] Tracks traversed `object` and `other` objects.
  4566. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
  4567. */
  4568. function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
  4569. var objIsArr = isArray_1(object),
  4570. othIsArr = isArray_1(other),
  4571. objTag = objIsArr ? arrayTag$1 : _getTag(object),
  4572. othTag = othIsArr ? arrayTag$1 : _getTag(other);
  4573. objTag = objTag == argsTag$2 ? objectTag$2 : objTag;
  4574. othTag = othTag == argsTag$2 ? objectTag$2 : othTag;
  4575. var objIsObj = objTag == objectTag$2,
  4576. othIsObj = othTag == objectTag$2,
  4577. isSameTag = objTag == othTag;
  4578. if (isSameTag && isBuffer_1(object)) {
  4579. if (!isBuffer_1(other)) {
  4580. return false;
  4581. }
  4582. objIsArr = true;
  4583. objIsObj = false;
  4584. }
  4585. if (isSameTag && !objIsObj) {
  4586. stack || (stack = new _Stack());
  4587. return objIsArr || isTypedArray_1(object) ? _equalArrays(object, other, bitmask, customizer, equalFunc, stack) : _equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
  4588. }
  4589. if (!(bitmask & COMPARE_PARTIAL_FLAG$3)) {
  4590. var objIsWrapped = objIsObj && hasOwnProperty$9.call(object, '__wrapped__'),
  4591. othIsWrapped = othIsObj && hasOwnProperty$9.call(other, '__wrapped__');
  4592. if (objIsWrapped || othIsWrapped) {
  4593. var objUnwrapped = objIsWrapped ? object.value() : object,
  4594. othUnwrapped = othIsWrapped ? other.value() : other;
  4595. stack || (stack = new _Stack());
  4596. return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
  4597. }
  4598. }
  4599. if (!isSameTag) {
  4600. return false;
  4601. }
  4602. stack || (stack = new _Stack());
  4603. return _equalObjects(object, other, bitmask, customizer, equalFunc, stack);
  4604. }
  4605. var _baseIsEqualDeep = baseIsEqualDeep;
  4606. /**
  4607. * The base implementation of `_.isEqual` which supports partial comparisons
  4608. * and tracks traversed objects.
  4609. *
  4610. * @private
  4611. * @param {*} value The value to compare.
  4612. * @param {*} other The other value to compare.
  4613. * @param {boolean} bitmask The bitmask flags.
  4614. * 1 - Unordered comparison
  4615. * 2 - Partial comparison
  4616. * @param {Function} [customizer] The function to customize comparisons.
  4617. * @param {Object} [stack] Tracks traversed `value` and `other` objects.
  4618. * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
  4619. */
  4620. function baseIsEqual(value, other, bitmask, customizer, stack) {
  4621. if (value === other) {
  4622. return true;
  4623. }
  4624. if (value == null || other == null || !isObjectLike_1(value) && !isObjectLike_1(other)) {
  4625. return value !== value && other !== other;
  4626. }
  4627. return _baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
  4628. }
  4629. var _baseIsEqual = baseIsEqual;
  4630. /** Used to compose bitmasks for value comparisons. */
  4631. var COMPARE_PARTIAL_FLAG$4 = 1,
  4632. COMPARE_UNORDERED_FLAG$2 = 2;
  4633. /**
  4634. * The base implementation of `_.isMatch` without support for iteratee shorthands.
  4635. *
  4636. * @private
  4637. * @param {Object} object The object to inspect.
  4638. * @param {Object} source The object of property values to match.
  4639. * @param {Array} matchData The property names, values, and compare flags to match.
  4640. * @param {Function} [customizer] The function to customize comparisons.
  4641. * @returns {boolean} Returns `true` if `object` is a match, else `false`.
  4642. */
  4643. function baseIsMatch(object, source, matchData, customizer) {
  4644. var index = matchData.length,
  4645. length = index,
  4646. noCustomizer = !customizer;
  4647. if (object == null) {
  4648. return !length;
  4649. }
  4650. object = Object(object);
  4651. while (index--) {
  4652. var data = matchData[index];
  4653. if (noCustomizer && data[2] ? data[1] !== object[data[0]] : !(data[0] in object)) {
  4654. return false;
  4655. }
  4656. }
  4657. while (++index < length) {
  4658. data = matchData[index];
  4659. var key = data[0],
  4660. objValue = object[key],
  4661. srcValue = data[1];
  4662. if (noCustomizer && data[2]) {
  4663. if (objValue === undefined && !(key in object)) {
  4664. return false;
  4665. }
  4666. } else {
  4667. var stack = new _Stack();
  4668. if (customizer) {
  4669. var result = customizer(objValue, srcValue, key, object, source, stack);
  4670. }
  4671. if (!(result === undefined ? _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$4 | COMPARE_UNORDERED_FLAG$2, customizer, stack) : result)) {
  4672. return false;
  4673. }
  4674. }
  4675. }
  4676. return true;
  4677. }
  4678. var _baseIsMatch = baseIsMatch;
  4679. /**
  4680. * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
  4681. *
  4682. * @private
  4683. * @param {*} value The value to check.
  4684. * @returns {boolean} Returns `true` if `value` if suitable for strict
  4685. * equality comparisons, else `false`.
  4686. */
  4687. function isStrictComparable(value) {
  4688. return value === value && !isObject_1(value);
  4689. }
  4690. var _isStrictComparable = isStrictComparable;
  4691. /**
  4692. * Gets the property names, values, and compare flags of `object`.
  4693. *
  4694. * @private
  4695. * @param {Object} object The object to query.
  4696. * @returns {Array} Returns the match data of `object`.
  4697. */
  4698. function getMatchData(object) {
  4699. var result = keys_1(object),
  4700. length = result.length;
  4701. while (length--) {
  4702. var key = result[length],
  4703. value = object[key];
  4704. result[length] = [key, value, _isStrictComparable(value)];
  4705. }
  4706. return result;
  4707. }
  4708. var _getMatchData = getMatchData;
  4709. /**
  4710. * A specialized version of `matchesProperty` for source values suitable
  4711. * for strict equality comparisons, i.e. `===`.
  4712. *
  4713. * @private
  4714. * @param {string} key The key of the property to get.
  4715. * @param {*} srcValue The value to match.
  4716. * @returns {Function} Returns the new spec function.
  4717. */
  4718. function matchesStrictComparable(key, srcValue) {
  4719. return function (object) {
  4720. if (object == null) {
  4721. return false;
  4722. }
  4723. return object[key] === srcValue && (srcValue !== undefined || key in Object(object));
  4724. };
  4725. }
  4726. var _matchesStrictComparable = matchesStrictComparable;
  4727. /**
  4728. * The base implementation of `_.matches` which doesn't clone `source`.
  4729. *
  4730. * @private
  4731. * @param {Object} source The object of property values to match.
  4732. * @returns {Function} Returns the new spec function.
  4733. */
  4734. function baseMatches(source) {
  4735. var matchData = _getMatchData(source);
  4736. if (matchData.length == 1 && matchData[0][2]) {
  4737. return _matchesStrictComparable(matchData[0][0], matchData[0][1]);
  4738. }
  4739. return function (object) {
  4740. return object === source || _baseIsMatch(object, source, matchData);
  4741. };
  4742. }
  4743. var _baseMatches = baseMatches;
  4744. /**
  4745. * Gets the value at `path` of `object`. If the resolved value is
  4746. * `undefined`, the `defaultValue` is returned in its place.
  4747. *
  4748. * @static
  4749. * @memberOf _
  4750. * @since 3.7.0
  4751. * @category Object
  4752. * @param {Object} object The object to query.
  4753. * @param {Array|string} path The path of the property to get.
  4754. * @param {*} [defaultValue] The value returned for `undefined` resolved values.
  4755. * @returns {*} Returns the resolved value.
  4756. * @example
  4757. *
  4758. * var object = { 'a': [{ 'b': { 'c': 3 } }] };
  4759. *
  4760. * _.get(object, 'a[0].b.c');
  4761. * // => 3
  4762. *
  4763. * _.get(object, ['a', '0', 'b', 'c']);
  4764. * // => 3
  4765. *
  4766. * _.get(object, 'a.b.c', 'default');
  4767. * // => 'default'
  4768. */
  4769. function get(object, path, defaultValue) {
  4770. var result = object == null ? undefined : _baseGet(object, path);
  4771. return result === undefined ? defaultValue : result;
  4772. }
  4773. var get_1 = get;
  4774. /** Used to compose bitmasks for value comparisons. */
  4775. var COMPARE_PARTIAL_FLAG$5 = 1,
  4776. COMPARE_UNORDERED_FLAG$3 = 2;
  4777. /**
  4778. * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
  4779. *
  4780. * @private
  4781. * @param {string} path The path of the property to get.
  4782. * @param {*} srcValue The value to match.
  4783. * @returns {Function} Returns the new spec function.
  4784. */
  4785. function baseMatchesProperty(path, srcValue) {
  4786. if (_isKey(path) && _isStrictComparable(srcValue)) {
  4787. return _matchesStrictComparable(_toKey(path), srcValue);
  4788. }
  4789. return function (object) {
  4790. var objValue = get_1(object, path);
  4791. return objValue === undefined && objValue === srcValue ? hasIn_1(object, path) : _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$5 | COMPARE_UNORDERED_FLAG$3);
  4792. };
  4793. }
  4794. var _baseMatchesProperty = baseMatchesProperty;
  4795. /**
  4796. * The base implementation of `_.property` without support for deep paths.
  4797. *
  4798. * @private
  4799. * @param {string} key The key of the property to get.
  4800. * @returns {Function} Returns the new accessor function.
  4801. */
  4802. function baseProperty(key) {
  4803. return function (object) {
  4804. return object == null ? undefined : object[key];
  4805. };
  4806. }
  4807. var _baseProperty = baseProperty;
  4808. /**
  4809. * A specialized version of `baseProperty` which supports deep paths.
  4810. *
  4811. * @private
  4812. * @param {Array|string} path The path of the property to get.
  4813. * @returns {Function} Returns the new accessor function.
  4814. */
  4815. function basePropertyDeep(path) {
  4816. return function (object) {
  4817. return _baseGet(object, path);
  4818. };
  4819. }
  4820. var _basePropertyDeep = basePropertyDeep;
  4821. /**
  4822. * Creates a function that returns the value at `path` of a given object.
  4823. *
  4824. * @static
  4825. * @memberOf _
  4826. * @since 2.4.0
  4827. * @category Util
  4828. * @param {Array|string} path The path of the property to get.
  4829. * @returns {Function} Returns the new accessor function.
  4830. * @example
  4831. *
  4832. * var objects = [
  4833. * { 'a': { 'b': 2 } },
  4834. * { 'a': { 'b': 1 } }
  4835. * ];
  4836. *
  4837. * _.map(objects, _.property('a.b'));
  4838. * // => [2, 1]
  4839. *
  4840. * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
  4841. * // => [1, 2]
  4842. */
  4843. function property(path) {
  4844. return _isKey(path) ? _baseProperty(_toKey(path)) : _basePropertyDeep(path);
  4845. }
  4846. var property_1 = property;
  4847. /**
  4848. * The base implementation of `_.iteratee`.
  4849. *
  4850. * @private
  4851. * @param {*} [value=_.identity] The value to convert to an iteratee.
  4852. * @returns {Function} Returns the iteratee.
  4853. */
  4854. function baseIteratee(value) {
  4855. // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
  4856. // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
  4857. if (typeof value == 'function') {
  4858. return value;
  4859. }
  4860. if (value == null) {
  4861. return identity_1;
  4862. }
  4863. if (typeof value == 'object') {
  4864. return isArray_1(value) ? _baseMatchesProperty(value[0], value[1]) : _baseMatches(value);
  4865. }
  4866. return property_1(value);
  4867. }
  4868. var _baseIteratee = baseIteratee;
  4869. /**
  4870. * Creates a function like `_.groupBy`.
  4871. *
  4872. * @private
  4873. * @param {Function} setter The function to set accumulator values.
  4874. * @param {Function} [initializer] The accumulator object initializer.
  4875. * @returns {Function} Returns the new aggregator function.
  4876. */
  4877. function createAggregator(setter, initializer) {
  4878. return function (collection, iteratee) {
  4879. var func = isArray_1(collection) ? _arrayAggregator : _baseAggregator,
  4880. accumulator = initializer ? initializer() : {};
  4881. return func(collection, setter, _baseIteratee(iteratee), accumulator);
  4882. };
  4883. }
  4884. var _createAggregator = createAggregator;
  4885. /** Used for built-in method references. */
  4886. var objectProto$d = Object.prototype;
  4887. /** Used to check objects for own properties. */
  4888. var hasOwnProperty$a = objectProto$d.hasOwnProperty;
  4889. /**
  4890. * Creates an object composed of keys generated from the results of running
  4891. * each element of `collection` thru `iteratee`. The order of grouped values
  4892. * is determined by the order they occur in `collection`. The corresponding
  4893. * value of each key is an array of elements responsible for generating the
  4894. * key. The iteratee is invoked with one argument: (value).
  4895. *
  4896. * @static
  4897. * @memberOf _
  4898. * @since 0.1.0
  4899. * @category Collection
  4900. * @param {Array|Object} collection The collection to iterate over.
  4901. * @param {Function} [iteratee=_.identity] The iteratee to transform keys.
  4902. * @returns {Object} Returns the composed aggregate object.
  4903. * @example
  4904. *
  4905. * _.groupBy([6.1, 4.2, 6.3], Math.floor);
  4906. * // => { '4': [4.2], '6': [6.1, 6.3] }
  4907. *
  4908. * // The `_.property` iteratee shorthand.
  4909. * _.groupBy(['one', 'two', 'three'], 'length');
  4910. * // => { '3': ['one', 'two'], '5': ['three'] }
  4911. */
  4912. var groupBy = _createAggregator(function (result, value, key) {
  4913. if (hasOwnProperty$a.call(result, key)) {
  4914. result[key].push(value);
  4915. } else {
  4916. _baseAssignValue(result, key, [value]);
  4917. }
  4918. });
  4919. var groupBy_1 = groupBy;
  4920. /**
  4921. * Creates an array of elements split into two groups, the first of which
  4922. * contains elements `predicate` returns truthy for, the second of which
  4923. * contains elements `predicate` returns falsey for. The predicate is
  4924. * invoked with one argument: (value).
  4925. *
  4926. * @static
  4927. * @memberOf _
  4928. * @since 3.0.0
  4929. * @category Collection
  4930. * @param {Array|Object} collection The collection to iterate over.
  4931. * @param {Function} [predicate=_.identity] The function invoked per iteration.
  4932. * @returns {Array} Returns the array of grouped elements.
  4933. * @example
  4934. *
  4935. * var users = [
  4936. * { 'user': 'barney', 'age': 36, 'active': false },
  4937. * { 'user': 'fred', 'age': 40, 'active': true },
  4938. * { 'user': 'pebbles', 'age': 1, 'active': false }
  4939. * ];
  4940. *
  4941. * _.partition(users, function(o) { return o.active; });
  4942. * // => objects for [['fred'], ['barney', 'pebbles']]
  4943. *
  4944. * // The `_.matches` iteratee shorthand.
  4945. * _.partition(users, { 'age': 1, 'active': false });
  4946. * // => objects for [['pebbles'], ['barney', 'fred']]
  4947. *
  4948. * // The `_.matchesProperty` iteratee shorthand.
  4949. * _.partition(users, ['active', false]);
  4950. * // => objects for [['barney', 'pebbles'], ['fred']]
  4951. *
  4952. * // The `_.property` iteratee shorthand.
  4953. * _.partition(users, 'active');
  4954. * // => objects for [['fred'], ['barney', 'pebbles']]
  4955. */
  4956. var partition = _createAggregator(function (result, value, key) {
  4957. result[key ? 0 : 1].push(value);
  4958. }, function () {
  4959. return [[], []];
  4960. });
  4961. var partition_1 = partition;
  4962. var thirdParty = require("./third-party");
  4963. var prettierInternal = src.__internal;
  4964. var minimist = function (args, opts) {
  4965. if (!opts) opts = {};
  4966. var flags = {
  4967. bools: {},
  4968. strings: {},
  4969. unknownFn: null
  4970. };
  4971. if (typeof opts['unknown'] === 'function') {
  4972. flags.unknownFn = opts['unknown'];
  4973. }
  4974. if (typeof opts['boolean'] === 'boolean' && opts['boolean']) {
  4975. flags.allBools = true;
  4976. } else {
  4977. [].concat(opts['boolean']).filter(Boolean).forEach(function (key) {
  4978. flags.bools[key] = true;
  4979. });
  4980. }
  4981. var aliases = {};
  4982. Object.keys(opts.alias || {}).forEach(function (key) {
  4983. aliases[key] = [].concat(opts.alias[key]);
  4984. aliases[key].forEach(function (x) {
  4985. aliases[x] = [key].concat(aliases[key].filter(function (y) {
  4986. return x !== y;
  4987. }));
  4988. });
  4989. });
  4990. [].concat(opts.string).filter(Boolean).forEach(function (key) {
  4991. flags.strings[key] = true;
  4992. if (aliases[key]) {
  4993. flags.strings[aliases[key]] = true;
  4994. }
  4995. });
  4996. var defaults = opts['default'] || {};
  4997. var argv = {
  4998. _: []
  4999. };
  5000. Object.keys(flags.bools).forEach(function (key) {
  5001. setArg(key, defaults[key] === undefined ? false : defaults[key]);
  5002. });
  5003. var notFlags = [];
  5004. if (args.indexOf('--') !== -1) {
  5005. notFlags = args.slice(args.indexOf('--') + 1);
  5006. args = args.slice(0, args.indexOf('--'));
  5007. }
  5008. function argDefined(key, arg) {
  5009. return flags.allBools && /^--[^=]+$/.test(arg) || flags.strings[key] || flags.bools[key] || aliases[key];
  5010. }
  5011. function setArg(key, val, arg) {
  5012. if (arg && flags.unknownFn && !argDefined(key, arg)) {
  5013. if (flags.unknownFn(arg) === false) return;
  5014. }
  5015. var value = !flags.strings[key] && isNumber(val) ? Number(val) : val;
  5016. setKey(argv, key.split('.'), value);
  5017. (aliases[key] || []).forEach(function (x) {
  5018. setKey(argv, x.split('.'), value);
  5019. });
  5020. }
  5021. function setKey(obj, keys, value) {
  5022. var o = obj;
  5023. for (var i = 0; i < keys.length - 1; i++) {
  5024. var key = keys[i];
  5025. if (key === '__proto__') return;
  5026. if (o[key] === undefined) o[key] = {};
  5027. if (o[key] === Object.prototype || o[key] === Number.prototype || o[key] === String.prototype) o[key] = {};
  5028. if (o[key] === Array.prototype) o[key] = [];
  5029. o = o[key];
  5030. }
  5031. var key = keys[keys.length - 1];
  5032. if (key === '__proto__') return;
  5033. if (o === Object.prototype || o === Number.prototype || o === String.prototype) o = {};
  5034. if (o === Array.prototype) o = [];
  5035. if (o[key] === undefined || flags.bools[key] || typeof o[key] === 'boolean') {
  5036. o[key] = value;
  5037. } else if (Array.isArray(o[key])) {
  5038. o[key].push(value);
  5039. } else {
  5040. o[key] = [o[key], value];
  5041. }
  5042. }
  5043. function aliasIsBoolean(key) {
  5044. return aliases[key].some(function (x) {
  5045. return flags.bools[x];
  5046. });
  5047. }
  5048. for (var i = 0; i < args.length; i++) {
  5049. var arg = args[i];
  5050. if (/^--.+=/.test(arg)) {
  5051. // Using [\s\S] instead of . because js doesn't support the
  5052. // 'dotall' regex modifier. See:
  5053. // http://stackoverflow.com/a/1068308/13216
  5054. var m = arg.match(/^--([^=]+)=([\s\S]*)$/);
  5055. var key = m[1];
  5056. var value = m[2];
  5057. if (flags.bools[key]) {
  5058. value = value !== 'false';
  5059. }
  5060. setArg(key, value, arg);
  5061. } else if (/^--no-.+/.test(arg)) {
  5062. var key = arg.match(/^--no-(.+)/)[1];
  5063. setArg(key, false, arg);
  5064. } else if (/^--.+/.test(arg)) {
  5065. var key = arg.match(/^--(.+)/)[1];
  5066. var next = args[i + 1];
  5067. if (next !== undefined && !/^-/.test(next) && !flags.bools[key] && !flags.allBools && (aliases[key] ? !aliasIsBoolean(key) : true)) {
  5068. setArg(key, next, arg);
  5069. i++;
  5070. } else if (/^(true|false)$/.test(next)) {
  5071. setArg(key, next === 'true', arg);
  5072. i++;
  5073. } else {
  5074. setArg(key, flags.strings[key] ? '' : true, arg);
  5075. }
  5076. } else if (/^-[^-]+/.test(arg)) {
  5077. var letters = arg.slice(1, -1).split('');
  5078. var broken = false;
  5079. for (var j = 0; j < letters.length; j++) {
  5080. var next = arg.slice(j + 2);
  5081. if (next === '-') {
  5082. setArg(letters[j], next, arg);
  5083. continue;
  5084. }
  5085. if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) {
  5086. setArg(letters[j], next.split('=')[1], arg);
  5087. broken = true;
  5088. break;
  5089. }
  5090. if (/[A-Za-z]/.test(letters[j]) && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
  5091. setArg(letters[j], next, arg);
  5092. broken = true;
  5093. break;
  5094. }
  5095. if (letters[j + 1] && letters[j + 1].match(/\W/)) {
  5096. setArg(letters[j], arg.slice(j + 2), arg);
  5097. broken = true;
  5098. break;
  5099. } else {
  5100. setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg);
  5101. }
  5102. }
  5103. var key = arg.slice(-1)[0];
  5104. if (!broken && key !== '-') {
  5105. if (args[i + 1] && !/^(-|--)[^-]/.test(args[i + 1]) && !flags.bools[key] && (aliases[key] ? !aliasIsBoolean(key) : true)) {
  5106. setArg(key, args[i + 1], arg);
  5107. i++;
  5108. } else if (args[i + 1] && /^(true|false)$/.test(args[i + 1])) {
  5109. setArg(key, args[i + 1] === 'true', arg);
  5110. i++;
  5111. } else {
  5112. setArg(key, flags.strings[key] ? '' : true, arg);
  5113. }
  5114. }
  5115. } else {
  5116. if (!flags.unknownFn || flags.unknownFn(arg) !== false) {
  5117. argv._.push(flags.strings['_'] || !isNumber(arg) ? arg : Number(arg));
  5118. }
  5119. if (opts.stopEarly) {
  5120. argv._.push.apply(argv._, args.slice(i + 1));
  5121. break;
  5122. }
  5123. }
  5124. }
  5125. Object.keys(defaults).forEach(function (key) {
  5126. if (!hasKey(argv, key.split('.'))) {
  5127. setKey(argv, key.split('.'), defaults[key]);
  5128. (aliases[key] || []).forEach(function (x) {
  5129. setKey(argv, x.split('.'), defaults[key]);
  5130. });
  5131. }
  5132. });
  5133. if (opts['--']) {
  5134. argv['--'] = new Array();
  5135. notFlags.forEach(function (key) {
  5136. argv['--'].push(key);
  5137. });
  5138. } else {
  5139. notFlags.forEach(function (key) {
  5140. argv._.push(key);
  5141. });
  5142. }
  5143. return argv;
  5144. };
  5145. function hasKey(obj, keys) {
  5146. var o = obj;
  5147. keys.slice(0, -1).forEach(function (key) {
  5148. o = o[key] || {};
  5149. });
  5150. var key = keys[keys.length - 1];
  5151. return key in o;
  5152. }
  5153. function isNumber(x) {
  5154. if (typeof x === 'number') return true;
  5155. if (/^0x[0-9a-f]+$/i.test(x)) return true;
  5156. return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
  5157. }
  5158. const PLACEHOLDER = null;
  5159. /**
  5160. * unspecified boolean flag without default value is parsed as `undefined` instead of `false`
  5161. */
  5162. var minimist_1 = function (args, options) {
  5163. const boolean = options.boolean || [];
  5164. const defaults = options.default || {};
  5165. const booleanWithoutDefault = boolean.filter(key => !(key in defaults));
  5166. const newDefaults = Object.assign({}, defaults, fromPairs_1(booleanWithoutDefault.map(key => [key, PLACEHOLDER])));
  5167. const parsed = minimist(args, Object.assign({}, options, {
  5168. default: newDefaults
  5169. }));
  5170. return fromPairs_1(Object.entries(parsed).filter(([, value]) => value !== PLACEHOLDER));
  5171. };
  5172. var array = createCommonjsModule(function (module, exports) {
  5173. Object.defineProperty(exports, "__esModule", {
  5174. value: true
  5175. });
  5176. exports.splitWhen = exports.flatten = void 0;
  5177. function flatten(items) {
  5178. return items.reduce((collection, item) => [].concat(collection, item), []);
  5179. }
  5180. exports.flatten = flatten;
  5181. function splitWhen(items, predicate) {
  5182. const result = [[]];
  5183. let groupIndex = 0;
  5184. for (const item of items) {
  5185. if (predicate(item)) {
  5186. groupIndex++;
  5187. result[groupIndex] = [];
  5188. } else {
  5189. result[groupIndex].push(item);
  5190. }
  5191. }
  5192. return result;
  5193. }
  5194. exports.splitWhen = splitWhen;
  5195. });
  5196. var errno = createCommonjsModule(function (module, exports) {
  5197. Object.defineProperty(exports, "__esModule", {
  5198. value: true
  5199. });
  5200. exports.isEnoentCodeError = void 0;
  5201. function isEnoentCodeError(error) {
  5202. return error.code === 'ENOENT';
  5203. }
  5204. exports.isEnoentCodeError = isEnoentCodeError;
  5205. });
  5206. var fs = createCommonjsModule(function (module, exports) {
  5207. Object.defineProperty(exports, "__esModule", {
  5208. value: true
  5209. });
  5210. exports.createDirentFromStats = void 0;
  5211. class DirentFromStats {
  5212. constructor(name, stats) {
  5213. this.name = name;
  5214. this.isBlockDevice = stats.isBlockDevice.bind(stats);
  5215. this.isCharacterDevice = stats.isCharacterDevice.bind(stats);
  5216. this.isDirectory = stats.isDirectory.bind(stats);
  5217. this.isFIFO = stats.isFIFO.bind(stats);
  5218. this.isFile = stats.isFile.bind(stats);
  5219. this.isSocket = stats.isSocket.bind(stats);
  5220. this.isSymbolicLink = stats.isSymbolicLink.bind(stats);
  5221. }
  5222. }
  5223. function createDirentFromStats(name, stats) {
  5224. return new DirentFromStats(name, stats);
  5225. }
  5226. exports.createDirentFromStats = createDirentFromStats;
  5227. });
  5228. var path_1 = createCommonjsModule(function (module, exports) {
  5229. Object.defineProperty(exports, "__esModule", {
  5230. value: true
  5231. });
  5232. exports.removeLeadingDotSegment = exports.escape = exports.makeAbsolute = exports.unixify = void 0;
  5233. const LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2; // ./ or .\\
  5234. const UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\())/g;
  5235. /**
  5236. * Designed to work only with simple paths: `dir\\file`.
  5237. */
  5238. function unixify(filepath) {
  5239. return filepath.replace(/\\/g, '/');
  5240. }
  5241. exports.unixify = unixify;
  5242. function makeAbsolute(cwd, filepath) {
  5243. return path__default['default'].resolve(cwd, filepath);
  5244. }
  5245. exports.makeAbsolute = makeAbsolute;
  5246. function escape(pattern) {
  5247. return pattern.replace(UNESCAPED_GLOB_SYMBOLS_RE, '\\$2');
  5248. }
  5249. exports.escape = escape;
  5250. function removeLeadingDotSegment(entry) {
  5251. // We do not use `startsWith` because this is 10x slower than current implementation for some cases.
  5252. // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with
  5253. if (entry.charAt(0) === '.') {
  5254. const secondCharactery = entry.charAt(1);
  5255. if (secondCharactery === '/' || secondCharactery === '\\') {
  5256. return entry.slice(LEADING_DOT_SEGMENT_CHARACTERS_COUNT);
  5257. }
  5258. }
  5259. return entry;
  5260. }
  5261. exports.removeLeadingDotSegment = removeLeadingDotSegment;
  5262. });
  5263. /*!
  5264. * is-extglob <https://github.com/jonschlinkert/is-extglob>
  5265. *
  5266. * Copyright (c) 2014-2016, Jon Schlinkert.
  5267. * Licensed under the MIT License.
  5268. */
  5269. var isExtglob = function isExtglob(str) {
  5270. if (typeof str !== 'string' || str === '') {
  5271. return false;
  5272. }
  5273. var match;
  5274. while (match = /(\\).|([@?!+*]\(.*\))/g.exec(str)) {
  5275. if (match[2]) return true;
  5276. str = str.slice(match.index + match[0].length);
  5277. }
  5278. return false;
  5279. };
  5280. /*!
  5281. * is-glob <https://github.com/jonschlinkert/is-glob>
  5282. *
  5283. * Copyright (c) 2014-2017, Jon Schlinkert.
  5284. * Released under the MIT License.
  5285. */
  5286. var chars = {
  5287. '{': '}',
  5288. '(': ')',
  5289. '[': ']'
  5290. };
  5291. var strictRegex = /\\(.)|(^!|\*|[\].+)]\?|\[[^\\\]]+\]|\{[^\\}]+\}|\(\?[:!=][^\\)]+\)|\([^|]+\|[^\\)]+\))/;
  5292. var relaxedRegex = /\\(.)|(^!|[*?{}()[\]]|\(\?)/;
  5293. var isGlob = function isGlob(str, options) {
  5294. if (typeof str !== 'string' || str === '') {
  5295. return false;
  5296. }
  5297. if (isExtglob(str)) {
  5298. return true;
  5299. }
  5300. var regex = strictRegex;
  5301. var match; // optionally relax regex
  5302. if (options && options.strict === false) {
  5303. regex = relaxedRegex;
  5304. }
  5305. while (match = regex.exec(str)) {
  5306. if (match[2]) return true;
  5307. var idx = match.index + match[0].length; // if an open bracket/brace/paren is escaped,
  5308. // set the index to the next closing character
  5309. var open = match[1];
  5310. var close = open ? chars[open] : null;
  5311. if (open && close) {
  5312. var n = str.indexOf(close, idx);
  5313. if (n !== -1) {
  5314. idx = n + 1;
  5315. }
  5316. }
  5317. str = str.slice(idx);
  5318. }
  5319. return false;
  5320. };
  5321. var pathPosixDirname = path__default['default'].posix.dirname;
  5322. var isWin32 = os__default['default'].platform() === 'win32';
  5323. var slash = '/';
  5324. var backslash = /\\/g;
  5325. var enclosure = /[\{\[].*[\/]*.*[\}\]]$/;
  5326. var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/;
  5327. var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g;
  5328. /**
  5329. * @param {string} str
  5330. * @param {Object} opts
  5331. * @param {boolean} [opts.flipBackslashes=true]
  5332. */
  5333. var globParent = function globParent(str, opts) {
  5334. var options = Object.assign({
  5335. flipBackslashes: true
  5336. }, opts); // flip windows path separators
  5337. if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) {
  5338. str = str.replace(backslash, slash);
  5339. } // special case for strings ending in enclosure containing path separator
  5340. if (enclosure.test(str)) {
  5341. str += slash;
  5342. } // preserves full path in case of trailing path separator
  5343. str += 'a'; // remove path parts that are globby
  5344. do {
  5345. str = pathPosixDirname(str);
  5346. } while (isGlob(str) || globby.test(str)); // remove escape chars and return result
  5347. return str.replace(escaped, '$1');
  5348. };
  5349. var utils = createCommonjsModule(function (module, exports) {
  5350. exports.isInteger = num => {
  5351. if (typeof num === 'number') {
  5352. return Number.isInteger(num);
  5353. }
  5354. if (typeof num === 'string' && num.trim() !== '') {
  5355. return Number.isInteger(Number(num));
  5356. }
  5357. return false;
  5358. };
  5359. /**
  5360. * Find a node of the given type
  5361. */
  5362. exports.find = (node, type) => node.nodes.find(node => node.type === type);
  5363. /**
  5364. * Find a node of the given type
  5365. */
  5366. exports.exceedsLimit = (min, max, step = 1, limit) => {
  5367. if (limit === false) return false;
  5368. if (!exports.isInteger(min) || !exports.isInteger(max)) return false;
  5369. return (Number(max) - Number(min)) / Number(step) >= limit;
  5370. };
  5371. /**
  5372. * Escape the given node with '\\' before node.value
  5373. */
  5374. exports.escapeNode = (block, n = 0, type) => {
  5375. let node = block.nodes[n];
  5376. if (!node) return;
  5377. if (type && node.type === type || node.type === 'open' || node.type === 'close') {
  5378. if (node.escaped !== true) {
  5379. node.value = '\\' + node.value;
  5380. node.escaped = true;
  5381. }
  5382. }
  5383. };
  5384. /**
  5385. * Returns true if the given brace node should be enclosed in literal braces
  5386. */
  5387. exports.encloseBrace = node => {
  5388. if (node.type !== 'brace') return false;
  5389. if (node.commas >> 0 + node.ranges >> 0 === 0) {
  5390. node.invalid = true;
  5391. return true;
  5392. }
  5393. return false;
  5394. };
  5395. /**
  5396. * Returns true if a brace node is invalid.
  5397. */
  5398. exports.isInvalidBrace = block => {
  5399. if (block.type !== 'brace') return false;
  5400. if (block.invalid === true || block.dollar) return true;
  5401. if (block.commas >> 0 + block.ranges >> 0 === 0) {
  5402. block.invalid = true;
  5403. return true;
  5404. }
  5405. if (block.open !== true || block.close !== true) {
  5406. block.invalid = true;
  5407. return true;
  5408. }
  5409. return false;
  5410. };
  5411. /**
  5412. * Returns true if a node is an open or close node
  5413. */
  5414. exports.isOpenOrClose = node => {
  5415. if (node.type === 'open' || node.type === 'close') {
  5416. return true;
  5417. }
  5418. return node.open === true || node.close === true;
  5419. };
  5420. /**
  5421. * Reduce an array of text nodes.
  5422. */
  5423. exports.reduce = nodes => nodes.reduce((acc, node) => {
  5424. if (node.type === 'text') acc.push(node.value);
  5425. if (node.type === 'range') node.type = 'text';
  5426. return acc;
  5427. }, []);
  5428. /**
  5429. * Flatten an array
  5430. */
  5431. exports.flatten = (...args) => {
  5432. const result = [];
  5433. const flat = arr => {
  5434. for (let i = 0; i < arr.length; i++) {
  5435. let ele = arr[i];
  5436. Array.isArray(ele) ? flat(ele) : ele !== void 0 && result.push(ele);
  5437. }
  5438. return result;
  5439. };
  5440. flat(args);
  5441. return result;
  5442. };
  5443. });
  5444. var stringify = (ast, options = {}) => {
  5445. let stringify = (node, parent = {}) => {
  5446. let invalidBlock = options.escapeInvalid && utils.isInvalidBrace(parent);
  5447. let invalidNode = node.invalid === true && options.escapeInvalid === true;
  5448. let output = '';
  5449. if (node.value) {
  5450. if ((invalidBlock || invalidNode) && utils.isOpenOrClose(node)) {
  5451. return '\\' + node.value;
  5452. }
  5453. return node.value;
  5454. }
  5455. if (node.value) {
  5456. return node.value;
  5457. }
  5458. if (node.nodes) {
  5459. for (let child of node.nodes) {
  5460. output += stringify(child);
  5461. }
  5462. }
  5463. return output;
  5464. };
  5465. return stringify(ast);
  5466. };
  5467. /*!
  5468. * is-number <https://github.com/jonschlinkert/is-number>
  5469. *
  5470. * Copyright (c) 2014-present, Jon Schlinkert.
  5471. * Released under the MIT License.
  5472. */
  5473. var isNumber$1 = function (num) {
  5474. if (typeof num === 'number') {
  5475. return num - num === 0;
  5476. }
  5477. if (typeof num === 'string' && num.trim() !== '') {
  5478. return Number.isFinite ? Number.isFinite(+num) : isFinite(+num);
  5479. }
  5480. return false;
  5481. };
  5482. const toRegexRange = (min, max, options) => {
  5483. if (isNumber$1(min) === false) {
  5484. throw new TypeError('toRegexRange: expected the first argument to be a number');
  5485. }
  5486. if (max === void 0 || min === max) {
  5487. return String(min);
  5488. }
  5489. if (isNumber$1(max) === false) {
  5490. throw new TypeError('toRegexRange: expected the second argument to be a number.');
  5491. }
  5492. let opts = Object.assign({
  5493. relaxZeros: true
  5494. }, options);
  5495. if (typeof opts.strictZeros === 'boolean') {
  5496. opts.relaxZeros = opts.strictZeros === false;
  5497. }
  5498. let relax = String(opts.relaxZeros);
  5499. let shorthand = String(opts.shorthand);
  5500. let capture = String(opts.capture);
  5501. let wrap = String(opts.wrap);
  5502. let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap;
  5503. if (toRegexRange.cache.hasOwnProperty(cacheKey)) {
  5504. return toRegexRange.cache[cacheKey].result;
  5505. }
  5506. let a = Math.min(min, max);
  5507. let b = Math.max(min, max);
  5508. if (Math.abs(a - b) === 1) {
  5509. let result = min + '|' + max;
  5510. if (opts.capture) {
  5511. return `(${result})`;
  5512. }
  5513. if (opts.wrap === false) {
  5514. return result;
  5515. }
  5516. return `(?:${result})`;
  5517. }
  5518. let isPadded = hasPadding(min) || hasPadding(max);
  5519. let state = {
  5520. min,
  5521. max,
  5522. a,
  5523. b
  5524. };
  5525. let positives = [];
  5526. let negatives = [];
  5527. if (isPadded) {
  5528. state.isPadded = isPadded;
  5529. state.maxLen = String(state.max).length;
  5530. }
  5531. if (a < 0) {
  5532. let newMin = b < 0 ? Math.abs(b) : 1;
  5533. negatives = splitToPatterns(newMin, Math.abs(a), state, opts);
  5534. a = state.a = 0;
  5535. }
  5536. if (b >= 0) {
  5537. positives = splitToPatterns(a, b, state, opts);
  5538. }
  5539. state.negatives = negatives;
  5540. state.positives = positives;
  5541. state.result = collatePatterns(negatives, positives);
  5542. if (opts.capture === true) {
  5543. state.result = `(${state.result})`;
  5544. } else if (opts.wrap !== false && positives.length + negatives.length > 1) {
  5545. state.result = `(?:${state.result})`;
  5546. }
  5547. toRegexRange.cache[cacheKey] = state;
  5548. return state.result;
  5549. };
  5550. function collatePatterns(neg, pos, options) {
  5551. let onlyNegative = filterPatterns(neg, pos, '-', false) || [];
  5552. let onlyPositive = filterPatterns(pos, neg, '', false) || [];
  5553. let intersected = filterPatterns(neg, pos, '-?', true) || [];
  5554. let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive);
  5555. return subpatterns.join('|');
  5556. }
  5557. function splitToRanges(min, max) {
  5558. let nines = 1;
  5559. let zeros = 1;
  5560. let stop = countNines(min, nines);
  5561. let stops = new Set([max]);
  5562. while (min <= stop && stop <= max) {
  5563. stops.add(stop);
  5564. nines += 1;
  5565. stop = countNines(min, nines);
  5566. }
  5567. stop = countZeros(max + 1, zeros) - 1;
  5568. while (min < stop && stop <= max) {
  5569. stops.add(stop);
  5570. zeros += 1;
  5571. stop = countZeros(max + 1, zeros) - 1;
  5572. }
  5573. stops = [...stops];
  5574. stops.sort(compare);
  5575. return stops;
  5576. }
  5577. /**
  5578. * Convert a range to a regex pattern
  5579. * @param {Number} `start`
  5580. * @param {Number} `stop`
  5581. * @return {String}
  5582. */
  5583. function rangeToPattern(start, stop, options) {
  5584. if (start === stop) {
  5585. return {
  5586. pattern: start,
  5587. count: [],
  5588. digits: 0
  5589. };
  5590. }
  5591. let zipped = zip(start, stop);
  5592. let digits = zipped.length;
  5593. let pattern = '';
  5594. let count = 0;
  5595. for (let i = 0; i < digits; i++) {
  5596. let [startDigit, stopDigit] = zipped[i];
  5597. if (startDigit === stopDigit) {
  5598. pattern += startDigit;
  5599. } else if (startDigit !== '0' || stopDigit !== '9') {
  5600. pattern += toCharacterClass(startDigit, stopDigit);
  5601. } else {
  5602. count++;
  5603. }
  5604. }
  5605. if (count) {
  5606. pattern += options.shorthand === true ? '\\d' : '[0-9]';
  5607. }
  5608. return {
  5609. pattern,
  5610. count: [count],
  5611. digits
  5612. };
  5613. }
  5614. function splitToPatterns(min, max, tok, options) {
  5615. let ranges = splitToRanges(min, max);
  5616. let tokens = [];
  5617. let start = min;
  5618. let prev;
  5619. for (let i = 0; i < ranges.length; i++) {
  5620. let max = ranges[i];
  5621. let obj = rangeToPattern(String(start), String(max), options);
  5622. let zeros = '';
  5623. if (!tok.isPadded && prev && prev.pattern === obj.pattern) {
  5624. if (prev.count.length > 1) {
  5625. prev.count.pop();
  5626. }
  5627. prev.count.push(obj.count[0]);
  5628. prev.string = prev.pattern + toQuantifier(prev.count);
  5629. start = max + 1;
  5630. continue;
  5631. }
  5632. if (tok.isPadded) {
  5633. zeros = padZeros(max, tok, options);
  5634. }
  5635. obj.string = zeros + obj.pattern + toQuantifier(obj.count);
  5636. tokens.push(obj);
  5637. start = max + 1;
  5638. prev = obj;
  5639. }
  5640. return tokens;
  5641. }
  5642. function filterPatterns(arr, comparison, prefix, intersection, options) {
  5643. let result = [];
  5644. for (let ele of arr) {
  5645. let {
  5646. string
  5647. } = ele; // only push if _both_ are negative...
  5648. if (!intersection && !contains(comparison, 'string', string)) {
  5649. result.push(prefix + string);
  5650. } // or _both_ are positive
  5651. if (intersection && contains(comparison, 'string', string)) {
  5652. result.push(prefix + string);
  5653. }
  5654. }
  5655. return result;
  5656. }
  5657. /**
  5658. * Zip strings
  5659. */
  5660. function zip(a, b) {
  5661. let arr = [];
  5662. for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]);
  5663. return arr;
  5664. }
  5665. function compare(a, b) {
  5666. return a > b ? 1 : b > a ? -1 : 0;
  5667. }
  5668. function contains(arr, key, val) {
  5669. return arr.some(ele => ele[key] === val);
  5670. }
  5671. function countNines(min, len) {
  5672. return Number(String(min).slice(0, -len) + '9'.repeat(len));
  5673. }
  5674. function countZeros(integer, zeros) {
  5675. return integer - integer % Math.pow(10, zeros);
  5676. }
  5677. function toQuantifier(digits) {
  5678. let [start = 0, stop = ''] = digits;
  5679. if (stop || start > 1) {
  5680. return `{${start + (stop ? ',' + stop : '')}}`;
  5681. }
  5682. return '';
  5683. }
  5684. function toCharacterClass(a, b, options) {
  5685. return `[${a}${b - a === 1 ? '' : '-'}${b}]`;
  5686. }
  5687. function hasPadding(str) {
  5688. return /^-?(0+)\d/.test(str);
  5689. }
  5690. function padZeros(value, tok, options) {
  5691. if (!tok.isPadded) {
  5692. return value;
  5693. }
  5694. let diff = Math.abs(tok.maxLen - String(value).length);
  5695. let relax = options.relaxZeros !== false;
  5696. switch (diff) {
  5697. case 0:
  5698. return '';
  5699. case 1:
  5700. return relax ? '0?' : '0';
  5701. case 2:
  5702. return relax ? '0{0,2}' : '00';
  5703. default:
  5704. {
  5705. return relax ? `0{0,${diff}}` : `0{${diff}}`;
  5706. }
  5707. }
  5708. }
  5709. /**
  5710. * Cache
  5711. */
  5712. toRegexRange.cache = {};
  5713. toRegexRange.clearCache = () => toRegexRange.cache = {};
  5714. /**
  5715. * Expose `toRegexRange`
  5716. */
  5717. var toRegexRange_1 = toRegexRange;
  5718. const isObject$1 = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  5719. const transform = toNumber => {
  5720. return value => toNumber === true ? Number(value) : String(value);
  5721. };
  5722. const isValidValue = value => {
  5723. return typeof value === 'number' || typeof value === 'string' && value !== '';
  5724. };
  5725. const isNumber$2 = num => Number.isInteger(+num);
  5726. const zeros = input => {
  5727. let value = `${input}`;
  5728. let index = -1;
  5729. if (value[0] === '-') value = value.slice(1);
  5730. if (value === '0') return false;
  5731. while (value[++index] === '0');
  5732. return index > 0;
  5733. };
  5734. const stringify$1 = (start, end, options) => {
  5735. if (typeof start === 'string' || typeof end === 'string') {
  5736. return true;
  5737. }
  5738. return options.stringify === true;
  5739. };
  5740. const pad = (input, maxLength, toNumber) => {
  5741. if (maxLength > 0) {
  5742. let dash = input[0] === '-' ? '-' : '';
  5743. if (dash) input = input.slice(1);
  5744. input = dash + input.padStart(dash ? maxLength - 1 : maxLength, '0');
  5745. }
  5746. if (toNumber === false) {
  5747. return String(input);
  5748. }
  5749. return input;
  5750. };
  5751. const toMaxLen = (input, maxLength) => {
  5752. let negative = input[0] === '-' ? '-' : '';
  5753. if (negative) {
  5754. input = input.slice(1);
  5755. maxLength--;
  5756. }
  5757. while (input.length < maxLength) input = '0' + input;
  5758. return negative ? '-' + input : input;
  5759. };
  5760. const toSequence = (parts, options) => {
  5761. parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
  5762. parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
  5763. let prefix = options.capture ? '' : '?:';
  5764. let positives = '';
  5765. let negatives = '';
  5766. let result;
  5767. if (parts.positives.length) {
  5768. positives = parts.positives.join('|');
  5769. }
  5770. if (parts.negatives.length) {
  5771. negatives = `-(${prefix}${parts.negatives.join('|')})`;
  5772. }
  5773. if (positives && negatives) {
  5774. result = `${positives}|${negatives}`;
  5775. } else {
  5776. result = positives || negatives;
  5777. }
  5778. if (options.wrap) {
  5779. return `(${prefix}${result})`;
  5780. }
  5781. return result;
  5782. };
  5783. const toRange = (a, b, isNumbers, options) => {
  5784. if (isNumbers) {
  5785. return toRegexRange_1(a, b, Object.assign({
  5786. wrap: false
  5787. }, options));
  5788. }
  5789. let start = String.fromCharCode(a);
  5790. if (a === b) return start;
  5791. let stop = String.fromCharCode(b);
  5792. return `[${start}-${stop}]`;
  5793. };
  5794. const toRegex = (start, end, options) => {
  5795. if (Array.isArray(start)) {
  5796. let wrap = options.wrap === true;
  5797. let prefix = options.capture ? '' : '?:';
  5798. return wrap ? `(${prefix}${start.join('|')})` : start.join('|');
  5799. }
  5800. return toRegexRange_1(start, end, options);
  5801. };
  5802. const rangeError = (...args) => {
  5803. return new RangeError('Invalid range arguments: ' + util__default['default'].inspect(...args));
  5804. };
  5805. const invalidRange = (start, end, options) => {
  5806. if (options.strictRanges === true) throw rangeError([start, end]);
  5807. return [];
  5808. };
  5809. const invalidStep = (step, options) => {
  5810. if (options.strictRanges === true) {
  5811. throw new TypeError(`Expected step "${step}" to be a number`);
  5812. }
  5813. return [];
  5814. };
  5815. const fillNumbers = (start, end, step = 1, options = {}) => {
  5816. let a = Number(start);
  5817. let b = Number(end);
  5818. if (!Number.isInteger(a) || !Number.isInteger(b)) {
  5819. if (options.strictRanges === true) throw rangeError([start, end]);
  5820. return [];
  5821. } // fix negative zero
  5822. if (a === 0) a = 0;
  5823. if (b === 0) b = 0;
  5824. let descending = a > b;
  5825. let startString = String(start);
  5826. let endString = String(end);
  5827. let stepString = String(step);
  5828. step = Math.max(Math.abs(step), 1);
  5829. let padded = zeros(startString) || zeros(endString) || zeros(stepString);
  5830. let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0;
  5831. let toNumber = padded === false && stringify$1(start, end, options) === false;
  5832. let format = options.transform || transform(toNumber);
  5833. if (options.toRegex && step === 1) {
  5834. return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options);
  5835. }
  5836. let parts = {
  5837. negatives: [],
  5838. positives: []
  5839. };
  5840. let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num));
  5841. let range = [];
  5842. let index = 0;
  5843. while (descending ? a >= b : a <= b) {
  5844. if (options.toRegex === true && step > 1) {
  5845. push(a);
  5846. } else {
  5847. range.push(pad(format(a, index), maxLen, toNumber));
  5848. }
  5849. a = descending ? a - step : a + step;
  5850. index++;
  5851. }
  5852. if (options.toRegex === true) {
  5853. return step > 1 ? toSequence(parts, options) : toRegex(range, null, Object.assign({
  5854. wrap: false
  5855. }, options));
  5856. }
  5857. return range;
  5858. };
  5859. const fillLetters = (start, end, step = 1, options = {}) => {
  5860. if (!isNumber$2(start) && start.length > 1 || !isNumber$2(end) && end.length > 1) {
  5861. return invalidRange(start, end, options);
  5862. }
  5863. let format = options.transform || (val => String.fromCharCode(val));
  5864. let a = `${start}`.charCodeAt(0);
  5865. let b = `${end}`.charCodeAt(0);
  5866. let descending = a > b;
  5867. let min = Math.min(a, b);
  5868. let max = Math.max(a, b);
  5869. if (options.toRegex && step === 1) {
  5870. return toRange(min, max, false, options);
  5871. }
  5872. let range = [];
  5873. let index = 0;
  5874. while (descending ? a >= b : a <= b) {
  5875. range.push(format(a, index));
  5876. a = descending ? a - step : a + step;
  5877. index++;
  5878. }
  5879. if (options.toRegex === true) {
  5880. return toRegex(range, null, {
  5881. wrap: false,
  5882. options
  5883. });
  5884. }
  5885. return range;
  5886. };
  5887. const fill = (start, end, step, options = {}) => {
  5888. if (end == null && isValidValue(start)) {
  5889. return [start];
  5890. }
  5891. if (!isValidValue(start) || !isValidValue(end)) {
  5892. return invalidRange(start, end, options);
  5893. }
  5894. if (typeof step === 'function') {
  5895. return fill(start, end, 1, {
  5896. transform: step
  5897. });
  5898. }
  5899. if (isObject$1(step)) {
  5900. return fill(start, end, 0, step);
  5901. }
  5902. let opts = Object.assign({}, options);
  5903. if (opts.capture === true) opts.wrap = true;
  5904. step = step || opts.step || 1;
  5905. if (!isNumber$2(step)) {
  5906. if (step != null && !isObject$1(step)) return invalidStep(step, opts);
  5907. return fill(start, end, 1, step);
  5908. }
  5909. if (isNumber$2(start) && isNumber$2(end)) {
  5910. return fillNumbers(start, end, step, opts);
  5911. }
  5912. return fillLetters(start, end, Math.max(Math.abs(step), 1), opts);
  5913. };
  5914. var fillRange = fill;
  5915. const compile = (ast, options = {}) => {
  5916. let walk = (node, parent = {}) => {
  5917. let invalidBlock = utils.isInvalidBrace(parent);
  5918. let invalidNode = node.invalid === true && options.escapeInvalid === true;
  5919. let invalid = invalidBlock === true || invalidNode === true;
  5920. let prefix = options.escapeInvalid === true ? '\\' : '';
  5921. let output = '';
  5922. if (node.isOpen === true) {
  5923. return prefix + node.value;
  5924. }
  5925. if (node.isClose === true) {
  5926. return prefix + node.value;
  5927. }
  5928. if (node.type === 'open') {
  5929. return invalid ? prefix + node.value : '(';
  5930. }
  5931. if (node.type === 'close') {
  5932. return invalid ? prefix + node.value : ')';
  5933. }
  5934. if (node.type === 'comma') {
  5935. return node.prev.type === 'comma' ? '' : invalid ? node.value : '|';
  5936. }
  5937. if (node.value) {
  5938. return node.value;
  5939. }
  5940. if (node.nodes && node.ranges > 0) {
  5941. let args = utils.reduce(node.nodes);
  5942. let range = fillRange(...args, Object.assign({}, options, {
  5943. wrap: false,
  5944. toRegex: true
  5945. }));
  5946. if (range.length !== 0) {
  5947. return args.length > 1 && range.length > 1 ? `(${range})` : range;
  5948. }
  5949. }
  5950. if (node.nodes) {
  5951. for (let child of node.nodes) {
  5952. output += walk(child, node);
  5953. }
  5954. }
  5955. return output;
  5956. };
  5957. return walk(ast);
  5958. };
  5959. var compile_1 = compile;
  5960. const append = (queue = '', stash = '', enclose = false) => {
  5961. let result = [];
  5962. queue = [].concat(queue);
  5963. stash = [].concat(stash);
  5964. if (!stash.length) return queue;
  5965. if (!queue.length) {
  5966. return enclose ? utils.flatten(stash).map(ele => `{${ele}}`) : stash;
  5967. }
  5968. for (let item of queue) {
  5969. if (Array.isArray(item)) {
  5970. for (let value of item) {
  5971. result.push(append(value, stash, enclose));
  5972. }
  5973. } else {
  5974. for (let ele of stash) {
  5975. if (enclose === true && typeof ele === 'string') ele = `{${ele}}`;
  5976. result.push(Array.isArray(ele) ? append(item, ele, enclose) : item + ele);
  5977. }
  5978. }
  5979. }
  5980. return utils.flatten(result);
  5981. };
  5982. const expand = (ast, options = {}) => {
  5983. let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit;
  5984. let walk = (node, parent = {}) => {
  5985. node.queue = [];
  5986. let p = parent;
  5987. let q = parent.queue;
  5988. while (p.type !== 'brace' && p.type !== 'root' && p.parent) {
  5989. p = p.parent;
  5990. q = p.queue;
  5991. }
  5992. if (node.invalid || node.dollar) {
  5993. q.push(append(q.pop(), stringify(node, options)));
  5994. return;
  5995. }
  5996. if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) {
  5997. q.push(append(q.pop(), ['{}']));
  5998. return;
  5999. }
  6000. if (node.nodes && node.ranges > 0) {
  6001. let args = utils.reduce(node.nodes);
  6002. if (utils.exceedsLimit(...args, options.step, rangeLimit)) {
  6003. throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.');
  6004. }
  6005. let range = fillRange(...args, options);
  6006. if (range.length === 0) {
  6007. range = stringify(node, options);
  6008. }
  6009. q.push(append(q.pop(), range));
  6010. node.nodes = [];
  6011. return;
  6012. }
  6013. let enclose = utils.encloseBrace(node);
  6014. let queue = node.queue;
  6015. let block = node;
  6016. while (block.type !== 'brace' && block.type !== 'root' && block.parent) {
  6017. block = block.parent;
  6018. queue = block.queue;
  6019. }
  6020. for (let i = 0; i < node.nodes.length; i++) {
  6021. let child = node.nodes[i];
  6022. if (child.type === 'comma' && node.type === 'brace') {
  6023. if (i === 1) queue.push('');
  6024. queue.push('');
  6025. continue;
  6026. }
  6027. if (child.type === 'close') {
  6028. q.push(append(q.pop(), queue, enclose));
  6029. continue;
  6030. }
  6031. if (child.value && child.type !== 'open') {
  6032. queue.push(append(queue.pop(), child.value));
  6033. continue;
  6034. }
  6035. if (child.nodes) {
  6036. walk(child, node);
  6037. }
  6038. }
  6039. return queue;
  6040. };
  6041. return utils.flatten(walk(ast));
  6042. };
  6043. var expand_1 = expand;
  6044. var constants = {
  6045. MAX_LENGTH: 1024 * 64,
  6046. // Digits
  6047. CHAR_0: '0',
  6048. /* 0 */
  6049. CHAR_9: '9',
  6050. /* 9 */
  6051. // Alphabet chars.
  6052. CHAR_UPPERCASE_A: 'A',
  6053. /* A */
  6054. CHAR_LOWERCASE_A: 'a',
  6055. /* a */
  6056. CHAR_UPPERCASE_Z: 'Z',
  6057. /* Z */
  6058. CHAR_LOWERCASE_Z: 'z',
  6059. /* z */
  6060. CHAR_LEFT_PARENTHESES: '(',
  6061. /* ( */
  6062. CHAR_RIGHT_PARENTHESES: ')',
  6063. /* ) */
  6064. CHAR_ASTERISK: '*',
  6065. /* * */
  6066. // Non-alphabetic chars.
  6067. CHAR_AMPERSAND: '&',
  6068. /* & */
  6069. CHAR_AT: '@',
  6070. /* @ */
  6071. CHAR_BACKSLASH: '\\',
  6072. /* \ */
  6073. CHAR_BACKTICK: '`',
  6074. /* ` */
  6075. CHAR_CARRIAGE_RETURN: '\r',
  6076. /* \r */
  6077. CHAR_CIRCUMFLEX_ACCENT: '^',
  6078. /* ^ */
  6079. CHAR_COLON: ':',
  6080. /* : */
  6081. CHAR_COMMA: ',',
  6082. /* , */
  6083. CHAR_DOLLAR: '$',
  6084. /* . */
  6085. CHAR_DOT: '.',
  6086. /* . */
  6087. CHAR_DOUBLE_QUOTE: '"',
  6088. /* " */
  6089. CHAR_EQUAL: '=',
  6090. /* = */
  6091. CHAR_EXCLAMATION_MARK: '!',
  6092. /* ! */
  6093. CHAR_FORM_FEED: '\f',
  6094. /* \f */
  6095. CHAR_FORWARD_SLASH: '/',
  6096. /* / */
  6097. CHAR_HASH: '#',
  6098. /* # */
  6099. CHAR_HYPHEN_MINUS: '-',
  6100. /* - */
  6101. CHAR_LEFT_ANGLE_BRACKET: '<',
  6102. /* < */
  6103. CHAR_LEFT_CURLY_BRACE: '{',
  6104. /* { */
  6105. CHAR_LEFT_SQUARE_BRACKET: '[',
  6106. /* [ */
  6107. CHAR_LINE_FEED: '\n',
  6108. /* \n */
  6109. CHAR_NO_BREAK_SPACE: '\u00A0',
  6110. /* \u00A0 */
  6111. CHAR_PERCENT: '%',
  6112. /* % */
  6113. CHAR_PLUS: '+',
  6114. /* + */
  6115. CHAR_QUESTION_MARK: '?',
  6116. /* ? */
  6117. CHAR_RIGHT_ANGLE_BRACKET: '>',
  6118. /* > */
  6119. CHAR_RIGHT_CURLY_BRACE: '}',
  6120. /* } */
  6121. CHAR_RIGHT_SQUARE_BRACKET: ']',
  6122. /* ] */
  6123. CHAR_SEMICOLON: ';',
  6124. /* ; */
  6125. CHAR_SINGLE_QUOTE: '\'',
  6126. /* ' */
  6127. CHAR_SPACE: ' ',
  6128. /* */
  6129. CHAR_TAB: '\t',
  6130. /* \t */
  6131. CHAR_UNDERSCORE: '_',
  6132. /* _ */
  6133. CHAR_VERTICAL_LINE: '|',
  6134. /* | */
  6135. CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF'
  6136. /* \uFEFF */
  6137. };
  6138. /**
  6139. * Constants
  6140. */
  6141. const {
  6142. MAX_LENGTH,
  6143. CHAR_BACKSLASH,
  6144. /* \ */
  6145. CHAR_BACKTICK,
  6146. /* ` */
  6147. CHAR_COMMA,
  6148. /* , */
  6149. CHAR_DOT,
  6150. /* . */
  6151. CHAR_LEFT_PARENTHESES,
  6152. /* ( */
  6153. CHAR_RIGHT_PARENTHESES,
  6154. /* ) */
  6155. CHAR_LEFT_CURLY_BRACE,
  6156. /* { */
  6157. CHAR_RIGHT_CURLY_BRACE,
  6158. /* } */
  6159. CHAR_LEFT_SQUARE_BRACKET,
  6160. /* [ */
  6161. CHAR_RIGHT_SQUARE_BRACKET,
  6162. /* ] */
  6163. CHAR_DOUBLE_QUOTE,
  6164. /* " */
  6165. CHAR_SINGLE_QUOTE,
  6166. /* ' */
  6167. CHAR_NO_BREAK_SPACE,
  6168. CHAR_ZERO_WIDTH_NOBREAK_SPACE
  6169. } = constants;
  6170. /**
  6171. * parse
  6172. */
  6173. const parse = (input, options = {}) => {
  6174. if (typeof input !== 'string') {
  6175. throw new TypeError('Expected a string');
  6176. }
  6177. let opts = options || {};
  6178. let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  6179. if (input.length > max) {
  6180. throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`);
  6181. }
  6182. let ast = {
  6183. type: 'root',
  6184. input,
  6185. nodes: []
  6186. };
  6187. let stack = [ast];
  6188. let block = ast;
  6189. let prev = ast;
  6190. let brackets = 0;
  6191. let length = input.length;
  6192. let index = 0;
  6193. let depth = 0;
  6194. let value;
  6195. /**
  6196. * Helpers
  6197. */
  6198. const advance = () => input[index++];
  6199. const push = node => {
  6200. if (node.type === 'text' && prev.type === 'dot') {
  6201. prev.type = 'text';
  6202. }
  6203. if (prev && prev.type === 'text' && node.type === 'text') {
  6204. prev.value += node.value;
  6205. return;
  6206. }
  6207. block.nodes.push(node);
  6208. node.parent = block;
  6209. node.prev = prev;
  6210. prev = node;
  6211. return node;
  6212. };
  6213. push({
  6214. type: 'bos'
  6215. });
  6216. while (index < length) {
  6217. block = stack[stack.length - 1];
  6218. value = advance();
  6219. /**
  6220. * Invalid chars
  6221. */
  6222. if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) {
  6223. continue;
  6224. }
  6225. /**
  6226. * Escaped chars
  6227. */
  6228. if (value === CHAR_BACKSLASH) {
  6229. push({
  6230. type: 'text',
  6231. value: (options.keepEscaping ? value : '') + advance()
  6232. });
  6233. continue;
  6234. }
  6235. /**
  6236. * Right square bracket (literal): ']'
  6237. */
  6238. if (value === CHAR_RIGHT_SQUARE_BRACKET) {
  6239. push({
  6240. type: 'text',
  6241. value: '\\' + value
  6242. });
  6243. continue;
  6244. }
  6245. /**
  6246. * Left square bracket: '['
  6247. */
  6248. if (value === CHAR_LEFT_SQUARE_BRACKET) {
  6249. brackets++;
  6250. let next;
  6251. while (index < length && (next = advance())) {
  6252. value += next;
  6253. if (next === CHAR_LEFT_SQUARE_BRACKET) {
  6254. brackets++;
  6255. continue;
  6256. }
  6257. if (next === CHAR_BACKSLASH) {
  6258. value += advance();
  6259. continue;
  6260. }
  6261. if (next === CHAR_RIGHT_SQUARE_BRACKET) {
  6262. brackets--;
  6263. if (brackets === 0) {
  6264. break;
  6265. }
  6266. }
  6267. }
  6268. push({
  6269. type: 'text',
  6270. value
  6271. });
  6272. continue;
  6273. }
  6274. /**
  6275. * Parentheses
  6276. */
  6277. if (value === CHAR_LEFT_PARENTHESES) {
  6278. block = push({
  6279. type: 'paren',
  6280. nodes: []
  6281. });
  6282. stack.push(block);
  6283. push({
  6284. type: 'text',
  6285. value
  6286. });
  6287. continue;
  6288. }
  6289. if (value === CHAR_RIGHT_PARENTHESES) {
  6290. if (block.type !== 'paren') {
  6291. push({
  6292. type: 'text',
  6293. value
  6294. });
  6295. continue;
  6296. }
  6297. block = stack.pop();
  6298. push({
  6299. type: 'text',
  6300. value
  6301. });
  6302. block = stack[stack.length - 1];
  6303. continue;
  6304. }
  6305. /**
  6306. * Quotes: '|"|`
  6307. */
  6308. if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) {
  6309. let open = value;
  6310. let next;
  6311. if (options.keepQuotes !== true) {
  6312. value = '';
  6313. }
  6314. while (index < length && (next = advance())) {
  6315. if (next === CHAR_BACKSLASH) {
  6316. value += next + advance();
  6317. continue;
  6318. }
  6319. if (next === open) {
  6320. if (options.keepQuotes === true) value += next;
  6321. break;
  6322. }
  6323. value += next;
  6324. }
  6325. push({
  6326. type: 'text',
  6327. value
  6328. });
  6329. continue;
  6330. }
  6331. /**
  6332. * Left curly brace: '{'
  6333. */
  6334. if (value === CHAR_LEFT_CURLY_BRACE) {
  6335. depth++;
  6336. let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true;
  6337. let brace = {
  6338. type: 'brace',
  6339. open: true,
  6340. close: false,
  6341. dollar,
  6342. depth,
  6343. commas: 0,
  6344. ranges: 0,
  6345. nodes: []
  6346. };
  6347. block = push(brace);
  6348. stack.push(block);
  6349. push({
  6350. type: 'open',
  6351. value
  6352. });
  6353. continue;
  6354. }
  6355. /**
  6356. * Right curly brace: '}'
  6357. */
  6358. if (value === CHAR_RIGHT_CURLY_BRACE) {
  6359. if (block.type !== 'brace') {
  6360. push({
  6361. type: 'text',
  6362. value
  6363. });
  6364. continue;
  6365. }
  6366. let type = 'close';
  6367. block = stack.pop();
  6368. block.close = true;
  6369. push({
  6370. type,
  6371. value
  6372. });
  6373. depth--;
  6374. block = stack[stack.length - 1];
  6375. continue;
  6376. }
  6377. /**
  6378. * Comma: ','
  6379. */
  6380. if (value === CHAR_COMMA && depth > 0) {
  6381. if (block.ranges > 0) {
  6382. block.ranges = 0;
  6383. let open = block.nodes.shift();
  6384. block.nodes = [open, {
  6385. type: 'text',
  6386. value: stringify(block)
  6387. }];
  6388. }
  6389. push({
  6390. type: 'comma',
  6391. value
  6392. });
  6393. block.commas++;
  6394. continue;
  6395. }
  6396. /**
  6397. * Dot: '.'
  6398. */
  6399. if (value === CHAR_DOT && depth > 0 && block.commas === 0) {
  6400. let siblings = block.nodes;
  6401. if (depth === 0 || siblings.length === 0) {
  6402. push({
  6403. type: 'text',
  6404. value
  6405. });
  6406. continue;
  6407. }
  6408. if (prev.type === 'dot') {
  6409. block.range = [];
  6410. prev.value += value;
  6411. prev.type = 'range';
  6412. if (block.nodes.length !== 3 && block.nodes.length !== 5) {
  6413. block.invalid = true;
  6414. block.ranges = 0;
  6415. prev.type = 'text';
  6416. continue;
  6417. }
  6418. block.ranges++;
  6419. block.args = [];
  6420. continue;
  6421. }
  6422. if (prev.type === 'range') {
  6423. siblings.pop();
  6424. let before = siblings[siblings.length - 1];
  6425. before.value += prev.value + value;
  6426. prev = before;
  6427. block.ranges--;
  6428. continue;
  6429. }
  6430. push({
  6431. type: 'dot',
  6432. value
  6433. });
  6434. continue;
  6435. }
  6436. /**
  6437. * Text
  6438. */
  6439. push({
  6440. type: 'text',
  6441. value
  6442. });
  6443. } // Mark imbalanced braces and brackets as invalid
  6444. do {
  6445. block = stack.pop();
  6446. if (block.type !== 'root') {
  6447. block.nodes.forEach(node => {
  6448. if (!node.nodes) {
  6449. if (node.type === 'open') node.isOpen = true;
  6450. if (node.type === 'close') node.isClose = true;
  6451. if (!node.nodes) node.type = 'text';
  6452. node.invalid = true;
  6453. }
  6454. }); // get the location of the block on parent.nodes (block's siblings)
  6455. let parent = stack[stack.length - 1];
  6456. let index = parent.nodes.indexOf(block); // replace the (invalid) block with it's nodes
  6457. parent.nodes.splice(index, 1, ...block.nodes);
  6458. }
  6459. } while (stack.length > 0);
  6460. push({
  6461. type: 'eos'
  6462. });
  6463. return ast;
  6464. };
  6465. var parse_1 = parse;
  6466. /**
  6467. * Expand the given pattern or create a regex-compatible string.
  6468. *
  6469. * ```js
  6470. * const braces = require('braces');
  6471. * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)']
  6472. * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c']
  6473. * ```
  6474. * @param {String} `str`
  6475. * @param {Object} `options`
  6476. * @return {String}
  6477. * @api public
  6478. */
  6479. const braces = (input, options = {}) => {
  6480. let output = [];
  6481. if (Array.isArray(input)) {
  6482. for (let pattern of input) {
  6483. let result = braces.create(pattern, options);
  6484. if (Array.isArray(result)) {
  6485. output.push(...result);
  6486. } else {
  6487. output.push(result);
  6488. }
  6489. }
  6490. } else {
  6491. output = [].concat(braces.create(input, options));
  6492. }
  6493. if (options && options.expand === true && options.nodupes === true) {
  6494. output = [...new Set(output)];
  6495. }
  6496. return output;
  6497. };
  6498. /**
  6499. * Parse the given `str` with the given `options`.
  6500. *
  6501. * ```js
  6502. * // braces.parse(pattern, [, options]);
  6503. * const ast = braces.parse('a/{b,c}/d');
  6504. * console.log(ast);
  6505. * ```
  6506. * @param {String} pattern Brace pattern to parse
  6507. * @param {Object} options
  6508. * @return {Object} Returns an AST
  6509. * @api public
  6510. */
  6511. braces.parse = (input, options = {}) => parse_1(input, options);
  6512. /**
  6513. * Creates a braces string from an AST, or an AST node.
  6514. *
  6515. * ```js
  6516. * const braces = require('braces');
  6517. * let ast = braces.parse('foo/{a,b}/bar');
  6518. * console.log(stringify(ast.nodes[2])); //=> '{a,b}'
  6519. * ```
  6520. * @param {String} `input` Brace pattern or AST.
  6521. * @param {Object} `options`
  6522. * @return {Array} Returns an array of expanded values.
  6523. * @api public
  6524. */
  6525. braces.stringify = (input, options = {}) => {
  6526. if (typeof input === 'string') {
  6527. return stringify(braces.parse(input, options), options);
  6528. }
  6529. return stringify(input, options);
  6530. };
  6531. /**
  6532. * Compiles a brace pattern into a regex-compatible, optimized string.
  6533. * This method is called by the main [braces](#braces) function by default.
  6534. *
  6535. * ```js
  6536. * const braces = require('braces');
  6537. * console.log(braces.compile('a/{b,c}/d'));
  6538. * //=> ['a/(b|c)/d']
  6539. * ```
  6540. * @param {String} `input` Brace pattern or AST.
  6541. * @param {Object} `options`
  6542. * @return {Array} Returns an array of expanded values.
  6543. * @api public
  6544. */
  6545. braces.compile = (input, options = {}) => {
  6546. if (typeof input === 'string') {
  6547. input = braces.parse(input, options);
  6548. }
  6549. return compile_1(input, options);
  6550. };
  6551. /**
  6552. * Expands a brace pattern into an array. This method is called by the
  6553. * main [braces](#braces) function when `options.expand` is true. Before
  6554. * using this method it's recommended that you read the [performance notes](#performance))
  6555. * and advantages of using [.compile](#compile) instead.
  6556. *
  6557. * ```js
  6558. * const braces = require('braces');
  6559. * console.log(braces.expand('a/{b,c}/d'));
  6560. * //=> ['a/b/d', 'a/c/d'];
  6561. * ```
  6562. * @param {String} `pattern` Brace pattern
  6563. * @param {Object} `options`
  6564. * @return {Array} Returns an array of expanded values.
  6565. * @api public
  6566. */
  6567. braces.expand = (input, options = {}) => {
  6568. if (typeof input === 'string') {
  6569. input = braces.parse(input, options);
  6570. }
  6571. let result = expand_1(input, options); // filter out empty strings if specified
  6572. if (options.noempty === true) {
  6573. result = result.filter(Boolean);
  6574. } // filter out duplicates if specified
  6575. if (options.nodupes === true) {
  6576. result = [...new Set(result)];
  6577. }
  6578. return result;
  6579. };
  6580. /**
  6581. * Processes a brace pattern and returns either an expanded array
  6582. * (if `options.expand` is true), a highly optimized regex-compatible string.
  6583. * This method is called by the main [braces](#braces) function.
  6584. *
  6585. * ```js
  6586. * const braces = require('braces');
  6587. * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}'))
  6588. * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)'
  6589. * ```
  6590. * @param {String} `pattern` Brace pattern
  6591. * @param {Object} `options`
  6592. * @return {Array} Returns an array of expanded values.
  6593. * @api public
  6594. */
  6595. braces.create = (input, options = {}) => {
  6596. if (input === '' || input.length < 3) {
  6597. return [input];
  6598. }
  6599. return options.expand !== true ? braces.compile(input, options) : braces.expand(input, options);
  6600. };
  6601. /**
  6602. * Expose "braces"
  6603. */
  6604. var braces_1 = braces;
  6605. const WIN_SLASH = '\\\\/';
  6606. const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
  6607. /**
  6608. * Posix glob regex
  6609. */
  6610. const DOT_LITERAL = '\\.';
  6611. const PLUS_LITERAL = '\\+';
  6612. const QMARK_LITERAL = '\\?';
  6613. const SLASH_LITERAL = '\\/';
  6614. const ONE_CHAR = '(?=.)';
  6615. const QMARK = '[^/]';
  6616. const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
  6617. const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
  6618. const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
  6619. const NO_DOT = `(?!${DOT_LITERAL})`;
  6620. const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
  6621. const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
  6622. const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
  6623. const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
  6624. const STAR = `${QMARK}*?`;
  6625. const POSIX_CHARS = {
  6626. DOT_LITERAL,
  6627. PLUS_LITERAL,
  6628. QMARK_LITERAL,
  6629. SLASH_LITERAL,
  6630. ONE_CHAR,
  6631. QMARK,
  6632. END_ANCHOR,
  6633. DOTS_SLASH,
  6634. NO_DOT,
  6635. NO_DOTS,
  6636. NO_DOT_SLASH,
  6637. NO_DOTS_SLASH,
  6638. QMARK_NO_DOT,
  6639. STAR,
  6640. START_ANCHOR
  6641. };
  6642. /**
  6643. * Windows glob regex
  6644. */
  6645. const WINDOWS_CHARS = Object.assign({}, POSIX_CHARS, {
  6646. SLASH_LITERAL: `[${WIN_SLASH}]`,
  6647. QMARK: WIN_NO_SLASH,
  6648. STAR: `${WIN_NO_SLASH}*?`,
  6649. DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
  6650. NO_DOT: `(?!${DOT_LITERAL})`,
  6651. NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  6652. NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
  6653. NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  6654. QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
  6655. START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
  6656. END_ANCHOR: `(?:[${WIN_SLASH}]|$)`
  6657. });
  6658. /**
  6659. * POSIX Bracket Regex
  6660. */
  6661. const POSIX_REGEX_SOURCE = {
  6662. alnum: 'a-zA-Z0-9',
  6663. alpha: 'a-zA-Z',
  6664. ascii: '\\x00-\\x7F',
  6665. blank: ' \\t',
  6666. cntrl: '\\x00-\\x1F\\x7F',
  6667. digit: '0-9',
  6668. graph: '\\x21-\\x7E',
  6669. lower: 'a-z',
  6670. print: '\\x20-\\x7E ',
  6671. punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
  6672. space: ' \\t\\r\\n\\v\\f',
  6673. upper: 'A-Z',
  6674. word: 'A-Za-z0-9_',
  6675. xdigit: 'A-Fa-f0-9'
  6676. };
  6677. var constants$1 = {
  6678. MAX_LENGTH: 1024 * 64,
  6679. POSIX_REGEX_SOURCE,
  6680. // regular expressions
  6681. REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
  6682. REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
  6683. REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
  6684. REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
  6685. REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
  6686. REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
  6687. // Replace globs with equivalent patterns to reduce parsing time.
  6688. REPLACEMENTS: {
  6689. '***': '*',
  6690. '**/**': '**',
  6691. '**/**/**': '**'
  6692. },
  6693. // Digits
  6694. CHAR_0: 48,
  6695. /* 0 */
  6696. CHAR_9: 57,
  6697. /* 9 */
  6698. // Alphabet chars.
  6699. CHAR_UPPERCASE_A: 65,
  6700. /* A */
  6701. CHAR_LOWERCASE_A: 97,
  6702. /* a */
  6703. CHAR_UPPERCASE_Z: 90,
  6704. /* Z */
  6705. CHAR_LOWERCASE_Z: 122,
  6706. /* z */
  6707. CHAR_LEFT_PARENTHESES: 40,
  6708. /* ( */
  6709. CHAR_RIGHT_PARENTHESES: 41,
  6710. /* ) */
  6711. CHAR_ASTERISK: 42,
  6712. /* * */
  6713. // Non-alphabetic chars.
  6714. CHAR_AMPERSAND: 38,
  6715. /* & */
  6716. CHAR_AT: 64,
  6717. /* @ */
  6718. CHAR_BACKWARD_SLASH: 92,
  6719. /* \ */
  6720. CHAR_CARRIAGE_RETURN: 13,
  6721. /* \r */
  6722. CHAR_CIRCUMFLEX_ACCENT: 94,
  6723. /* ^ */
  6724. CHAR_COLON: 58,
  6725. /* : */
  6726. CHAR_COMMA: 44,
  6727. /* , */
  6728. CHAR_DOT: 46,
  6729. /* . */
  6730. CHAR_DOUBLE_QUOTE: 34,
  6731. /* " */
  6732. CHAR_EQUAL: 61,
  6733. /* = */
  6734. CHAR_EXCLAMATION_MARK: 33,
  6735. /* ! */
  6736. CHAR_FORM_FEED: 12,
  6737. /* \f */
  6738. CHAR_FORWARD_SLASH: 47,
  6739. /* / */
  6740. CHAR_GRAVE_ACCENT: 96,
  6741. /* ` */
  6742. CHAR_HASH: 35,
  6743. /* # */
  6744. CHAR_HYPHEN_MINUS: 45,
  6745. /* - */
  6746. CHAR_LEFT_ANGLE_BRACKET: 60,
  6747. /* < */
  6748. CHAR_LEFT_CURLY_BRACE: 123,
  6749. /* { */
  6750. CHAR_LEFT_SQUARE_BRACKET: 91,
  6751. /* [ */
  6752. CHAR_LINE_FEED: 10,
  6753. /* \n */
  6754. CHAR_NO_BREAK_SPACE: 160,
  6755. /* \u00A0 */
  6756. CHAR_PERCENT: 37,
  6757. /* % */
  6758. CHAR_PLUS: 43,
  6759. /* + */
  6760. CHAR_QUESTION_MARK: 63,
  6761. /* ? */
  6762. CHAR_RIGHT_ANGLE_BRACKET: 62,
  6763. /* > */
  6764. CHAR_RIGHT_CURLY_BRACE: 125,
  6765. /* } */
  6766. CHAR_RIGHT_SQUARE_BRACKET: 93,
  6767. /* ] */
  6768. CHAR_SEMICOLON: 59,
  6769. /* ; */
  6770. CHAR_SINGLE_QUOTE: 39,
  6771. /* ' */
  6772. CHAR_SPACE: 32,
  6773. /* */
  6774. CHAR_TAB: 9,
  6775. /* \t */
  6776. CHAR_UNDERSCORE: 95,
  6777. /* _ */
  6778. CHAR_VERTICAL_LINE: 124,
  6779. /* | */
  6780. CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279,
  6781. /* \uFEFF */
  6782. SEP: path__default['default'].sep,
  6783. /**
  6784. * Create EXTGLOB_CHARS
  6785. */
  6786. extglobChars(chars) {
  6787. return {
  6788. '!': {
  6789. type: 'negate',
  6790. open: '(?:(?!(?:',
  6791. close: `))${chars.STAR})`
  6792. },
  6793. '?': {
  6794. type: 'qmark',
  6795. open: '(?:',
  6796. close: ')?'
  6797. },
  6798. '+': {
  6799. type: 'plus',
  6800. open: '(?:',
  6801. close: ')+'
  6802. },
  6803. '*': {
  6804. type: 'star',
  6805. open: '(?:',
  6806. close: ')*'
  6807. },
  6808. '@': {
  6809. type: 'at',
  6810. open: '(?:',
  6811. close: ')'
  6812. }
  6813. };
  6814. },
  6815. /**
  6816. * Create GLOB_CHARS
  6817. */
  6818. globChars(win32) {
  6819. return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
  6820. }
  6821. };
  6822. var utils$1 = createCommonjsModule(function (module, exports) {
  6823. const win32 = process.platform === 'win32';
  6824. const {
  6825. REGEX_BACKSLASH,
  6826. REGEX_REMOVE_BACKSLASH,
  6827. REGEX_SPECIAL_CHARS,
  6828. REGEX_SPECIAL_CHARS_GLOBAL
  6829. } = constants$1;
  6830. exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  6831. exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
  6832. exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
  6833. exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
  6834. exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
  6835. exports.removeBackslashes = str => {
  6836. return str.replace(REGEX_REMOVE_BACKSLASH, match => {
  6837. return match === '\\' ? '' : match;
  6838. });
  6839. };
  6840. exports.supportsLookbehinds = () => {
  6841. const segs = process.version.slice(1).split('.').map(Number);
  6842. if (segs.length === 3 && segs[0] >= 9 || segs[0] === 8 && segs[1] >= 10) {
  6843. return true;
  6844. }
  6845. return false;
  6846. };
  6847. exports.isWindows = options => {
  6848. if (options && typeof options.windows === 'boolean') {
  6849. return options.windows;
  6850. }
  6851. return win32 === true || path__default['default'].sep === '\\';
  6852. };
  6853. exports.escapeLast = (input, char, lastIdx) => {
  6854. const idx = input.lastIndexOf(char, lastIdx);
  6855. if (idx === -1) return input;
  6856. if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
  6857. return `${input.slice(0, idx)}\\${input.slice(idx)}`;
  6858. };
  6859. exports.removePrefix = (input, state = {}) => {
  6860. let output = input;
  6861. if (output.startsWith('./')) {
  6862. output = output.slice(2);
  6863. state.prefix = './';
  6864. }
  6865. return output;
  6866. };
  6867. exports.wrapOutput = (input, state = {}, options = {}) => {
  6868. const prepend = options.contains ? '' : '^';
  6869. const append = options.contains ? '' : '$';
  6870. let output = `${prepend}(?:${input})${append}`;
  6871. if (state.negated === true) {
  6872. output = `(?:^(?!${output}).*$)`;
  6873. }
  6874. return output;
  6875. };
  6876. });
  6877. const {
  6878. CHAR_ASTERISK,
  6879. /* * */
  6880. CHAR_AT,
  6881. /* @ */
  6882. CHAR_BACKWARD_SLASH,
  6883. /* \ */
  6884. CHAR_COMMA: CHAR_COMMA$1,
  6885. /* , */
  6886. CHAR_DOT: CHAR_DOT$1,
  6887. /* . */
  6888. CHAR_EXCLAMATION_MARK,
  6889. /* ! */
  6890. CHAR_FORWARD_SLASH,
  6891. /* / */
  6892. CHAR_LEFT_CURLY_BRACE: CHAR_LEFT_CURLY_BRACE$1,
  6893. /* { */
  6894. CHAR_LEFT_PARENTHESES: CHAR_LEFT_PARENTHESES$1,
  6895. /* ( */
  6896. CHAR_LEFT_SQUARE_BRACKET: CHAR_LEFT_SQUARE_BRACKET$1,
  6897. /* [ */
  6898. CHAR_PLUS,
  6899. /* + */
  6900. CHAR_QUESTION_MARK,
  6901. /* ? */
  6902. CHAR_RIGHT_CURLY_BRACE: CHAR_RIGHT_CURLY_BRACE$1,
  6903. /* } */
  6904. CHAR_RIGHT_PARENTHESES: CHAR_RIGHT_PARENTHESES$1,
  6905. /* ) */
  6906. CHAR_RIGHT_SQUARE_BRACKET: CHAR_RIGHT_SQUARE_BRACKET$1
  6907. /* ] */
  6908. } = constants$1;
  6909. const isPathSeparator = code => {
  6910. return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
  6911. };
  6912. const depth = token => {
  6913. if (token.isPrefix !== true) {
  6914. token.depth = token.isGlobstar ? Infinity : 1;
  6915. }
  6916. };
  6917. /**
  6918. * Quickly scans a glob pattern and returns an object with a handful of
  6919. * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
  6920. * `glob` (the actual pattern), and `negated` (true if the path starts with `!`).
  6921. *
  6922. * ```js
  6923. * const pm = require('picomatch');
  6924. * console.log(pm.scan('foo/bar/*.js'));
  6925. * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
  6926. * ```
  6927. * @param {String} `str`
  6928. * @param {Object} `options`
  6929. * @return {Object} Returns an object with tokens and regex source string.
  6930. * @api public
  6931. */
  6932. const scan = (input, options) => {
  6933. const opts = options || {};
  6934. const length = input.length - 1;
  6935. const scanToEnd = opts.parts === true || opts.scanToEnd === true;
  6936. const slashes = [];
  6937. const tokens = [];
  6938. const parts = [];
  6939. let str = input;
  6940. let index = -1;
  6941. let start = 0;
  6942. let lastIndex = 0;
  6943. let isBrace = false;
  6944. let isBracket = false;
  6945. let isGlob = false;
  6946. let isExtglob = false;
  6947. let isGlobstar = false;
  6948. let braceEscaped = false;
  6949. let backslashes = false;
  6950. let negated = false;
  6951. let finished = false;
  6952. let braces = 0;
  6953. let prev;
  6954. let code;
  6955. let token = {
  6956. value: '',
  6957. depth: 0,
  6958. isGlob: false
  6959. };
  6960. const eos = () => index >= length;
  6961. const peek = () => str.charCodeAt(index + 1);
  6962. const advance = () => {
  6963. prev = code;
  6964. return str.charCodeAt(++index);
  6965. };
  6966. while (index < length) {
  6967. code = advance();
  6968. let next;
  6969. if (code === CHAR_BACKWARD_SLASH) {
  6970. backslashes = token.backslashes = true;
  6971. code = advance();
  6972. if (code === CHAR_LEFT_CURLY_BRACE$1) {
  6973. braceEscaped = true;
  6974. }
  6975. continue;
  6976. }
  6977. if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE$1) {
  6978. braces++;
  6979. while (eos() !== true && (code = advance())) {
  6980. if (code === CHAR_BACKWARD_SLASH) {
  6981. backslashes = token.backslashes = true;
  6982. advance();
  6983. continue;
  6984. }
  6985. if (code === CHAR_LEFT_CURLY_BRACE$1) {
  6986. braces++;
  6987. continue;
  6988. }
  6989. if (braceEscaped !== true && code === CHAR_DOT$1 && (code = advance()) === CHAR_DOT$1) {
  6990. isBrace = token.isBrace = true;
  6991. isGlob = token.isGlob = true;
  6992. finished = true;
  6993. if (scanToEnd === true) {
  6994. continue;
  6995. }
  6996. break;
  6997. }
  6998. if (braceEscaped !== true && code === CHAR_COMMA$1) {
  6999. isBrace = token.isBrace = true;
  7000. isGlob = token.isGlob = true;
  7001. finished = true;
  7002. if (scanToEnd === true) {
  7003. continue;
  7004. }
  7005. break;
  7006. }
  7007. if (code === CHAR_RIGHT_CURLY_BRACE$1) {
  7008. braces--;
  7009. if (braces === 0) {
  7010. braceEscaped = false;
  7011. isBrace = token.isBrace = true;
  7012. finished = true;
  7013. break;
  7014. }
  7015. }
  7016. }
  7017. if (scanToEnd === true) {
  7018. continue;
  7019. }
  7020. break;
  7021. }
  7022. if (code === CHAR_FORWARD_SLASH) {
  7023. slashes.push(index);
  7024. tokens.push(token);
  7025. token = {
  7026. value: '',
  7027. depth: 0,
  7028. isGlob: false
  7029. };
  7030. if (finished === true) continue;
  7031. if (prev === CHAR_DOT$1 && index === start + 1) {
  7032. start += 2;
  7033. continue;
  7034. }
  7035. lastIndex = index + 1;
  7036. continue;
  7037. }
  7038. if (opts.noext !== true) {
  7039. const isExtglobChar = code === CHAR_PLUS || code === CHAR_AT || code === CHAR_ASTERISK || code === CHAR_QUESTION_MARK || code === CHAR_EXCLAMATION_MARK;
  7040. if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES$1) {
  7041. isGlob = token.isGlob = true;
  7042. isExtglob = token.isExtglob = true;
  7043. finished = true;
  7044. if (scanToEnd === true) {
  7045. while (eos() !== true && (code = advance())) {
  7046. if (code === CHAR_BACKWARD_SLASH) {
  7047. backslashes = token.backslashes = true;
  7048. code = advance();
  7049. continue;
  7050. }
  7051. if (code === CHAR_RIGHT_PARENTHESES$1) {
  7052. isGlob = token.isGlob = true;
  7053. finished = true;
  7054. break;
  7055. }
  7056. }
  7057. continue;
  7058. }
  7059. break;
  7060. }
  7061. }
  7062. if (code === CHAR_ASTERISK) {
  7063. if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
  7064. isGlob = token.isGlob = true;
  7065. finished = true;
  7066. if (scanToEnd === true) {
  7067. continue;
  7068. }
  7069. break;
  7070. }
  7071. if (code === CHAR_QUESTION_MARK) {
  7072. isGlob = token.isGlob = true;
  7073. finished = true;
  7074. if (scanToEnd === true) {
  7075. continue;
  7076. }
  7077. break;
  7078. }
  7079. if (code === CHAR_LEFT_SQUARE_BRACKET$1) {
  7080. while (eos() !== true && (next = advance())) {
  7081. if (next === CHAR_BACKWARD_SLASH) {
  7082. backslashes = token.backslashes = true;
  7083. advance();
  7084. continue;
  7085. }
  7086. if (next === CHAR_RIGHT_SQUARE_BRACKET$1) {
  7087. isBracket = token.isBracket = true;
  7088. isGlob = token.isGlob = true;
  7089. finished = true;
  7090. if (scanToEnd === true) {
  7091. continue;
  7092. }
  7093. break;
  7094. }
  7095. }
  7096. }
  7097. if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
  7098. negated = token.negated = true;
  7099. start++;
  7100. continue;
  7101. }
  7102. if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES$1) {
  7103. isGlob = token.isGlob = true;
  7104. if (scanToEnd === true) {
  7105. while (eos() !== true && (code = advance())) {
  7106. if (code === CHAR_LEFT_PARENTHESES$1) {
  7107. backslashes = token.backslashes = true;
  7108. code = advance();
  7109. continue;
  7110. }
  7111. if (code === CHAR_RIGHT_PARENTHESES$1) {
  7112. finished = true;
  7113. break;
  7114. }
  7115. }
  7116. continue;
  7117. }
  7118. break;
  7119. }
  7120. if (isGlob === true) {
  7121. finished = true;
  7122. if (scanToEnd === true) {
  7123. continue;
  7124. }
  7125. break;
  7126. }
  7127. }
  7128. if (opts.noext === true) {
  7129. isExtglob = false;
  7130. isGlob = false;
  7131. }
  7132. let base = str;
  7133. let prefix = '';
  7134. let glob = '';
  7135. if (start > 0) {
  7136. prefix = str.slice(0, start);
  7137. str = str.slice(start);
  7138. lastIndex -= start;
  7139. }
  7140. if (base && isGlob === true && lastIndex > 0) {
  7141. base = str.slice(0, lastIndex);
  7142. glob = str.slice(lastIndex);
  7143. } else if (isGlob === true) {
  7144. base = '';
  7145. glob = str;
  7146. } else {
  7147. base = str;
  7148. }
  7149. if (base && base !== '' && base !== '/' && base !== str) {
  7150. if (isPathSeparator(base.charCodeAt(base.length - 1))) {
  7151. base = base.slice(0, -1);
  7152. }
  7153. }
  7154. if (opts.unescape === true) {
  7155. if (glob) glob = utils$1.removeBackslashes(glob);
  7156. if (base && backslashes === true) {
  7157. base = utils$1.removeBackslashes(base);
  7158. }
  7159. }
  7160. const state = {
  7161. prefix,
  7162. input,
  7163. start,
  7164. base,
  7165. glob,
  7166. isBrace,
  7167. isBracket,
  7168. isGlob,
  7169. isExtglob,
  7170. isGlobstar,
  7171. negated
  7172. };
  7173. if (opts.tokens === true) {
  7174. state.maxDepth = 0;
  7175. if (!isPathSeparator(code)) {
  7176. tokens.push(token);
  7177. }
  7178. state.tokens = tokens;
  7179. }
  7180. if (opts.parts === true || opts.tokens === true) {
  7181. let prevIndex;
  7182. for (let idx = 0; idx < slashes.length; idx++) {
  7183. const n = prevIndex ? prevIndex + 1 : start;
  7184. const i = slashes[idx];
  7185. const value = input.slice(n, i);
  7186. if (opts.tokens) {
  7187. if (idx === 0 && start !== 0) {
  7188. tokens[idx].isPrefix = true;
  7189. tokens[idx].value = prefix;
  7190. } else {
  7191. tokens[idx].value = value;
  7192. }
  7193. depth(tokens[idx]);
  7194. state.maxDepth += tokens[idx].depth;
  7195. }
  7196. if (idx !== 0 || value !== '') {
  7197. parts.push(value);
  7198. }
  7199. prevIndex = i;
  7200. }
  7201. if (prevIndex && prevIndex + 1 < input.length) {
  7202. const value = input.slice(prevIndex + 1);
  7203. parts.push(value);
  7204. if (opts.tokens) {
  7205. tokens[tokens.length - 1].value = value;
  7206. depth(tokens[tokens.length - 1]);
  7207. state.maxDepth += tokens[tokens.length - 1].depth;
  7208. }
  7209. }
  7210. state.slashes = slashes;
  7211. state.parts = parts;
  7212. }
  7213. return state;
  7214. };
  7215. var scan_1 = scan;
  7216. /**
  7217. * Constants
  7218. */
  7219. const {
  7220. MAX_LENGTH: MAX_LENGTH$1,
  7221. POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1,
  7222. REGEX_NON_SPECIAL_CHARS,
  7223. REGEX_SPECIAL_CHARS_BACKREF,
  7224. REPLACEMENTS
  7225. } = constants$1;
  7226. /**
  7227. * Helpers
  7228. */
  7229. const expandRange = (args, options) => {
  7230. if (typeof options.expandRange === 'function') {
  7231. return options.expandRange(...args, options);
  7232. }
  7233. args.sort();
  7234. const value = `[${args.join('-')}]`;
  7235. try {
  7236. /* eslint-disable-next-line no-new */
  7237. new RegExp(value);
  7238. } catch (ex) {
  7239. return args.map(v => utils$1.escapeRegex(v)).join('..');
  7240. }
  7241. return value;
  7242. };
  7243. /**
  7244. * Create the message for a syntax error
  7245. */
  7246. const syntaxError = (type, char) => {
  7247. return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
  7248. };
  7249. /**
  7250. * Parse the given input string.
  7251. * @param {String} input
  7252. * @param {Object} options
  7253. * @return {Object}
  7254. */
  7255. const parse$1 = (input, options) => {
  7256. if (typeof input !== 'string') {
  7257. throw new TypeError('Expected a string');
  7258. }
  7259. input = REPLACEMENTS[input] || input;
  7260. const opts = Object.assign({}, options);
  7261. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1;
  7262. let len = input.length;
  7263. if (len > max) {
  7264. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  7265. }
  7266. const bos = {
  7267. type: 'bos',
  7268. value: '',
  7269. output: opts.prepend || ''
  7270. };
  7271. const tokens = [bos];
  7272. const capture = opts.capture ? '' : '?:';
  7273. const win32 = utils$1.isWindows(options); // create constants based on platform, for windows or posix
  7274. const PLATFORM_CHARS = constants$1.globChars(win32);
  7275. const EXTGLOB_CHARS = constants$1.extglobChars(PLATFORM_CHARS);
  7276. const {
  7277. DOT_LITERAL,
  7278. PLUS_LITERAL,
  7279. SLASH_LITERAL,
  7280. ONE_CHAR,
  7281. DOTS_SLASH,
  7282. NO_DOT,
  7283. NO_DOT_SLASH,
  7284. NO_DOTS_SLASH,
  7285. QMARK,
  7286. QMARK_NO_DOT,
  7287. STAR,
  7288. START_ANCHOR
  7289. } = PLATFORM_CHARS;
  7290. const globstar = opts => {
  7291. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  7292. };
  7293. const nodot = opts.dot ? '' : NO_DOT;
  7294. const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
  7295. let star = opts.bash === true ? globstar(opts) : STAR;
  7296. if (opts.capture) {
  7297. star = `(${star})`;
  7298. } // minimatch options support
  7299. if (typeof opts.noext === 'boolean') {
  7300. opts.noextglob = opts.noext;
  7301. }
  7302. const state = {
  7303. input,
  7304. index: -1,
  7305. start: 0,
  7306. dot: opts.dot === true,
  7307. consumed: '',
  7308. output: '',
  7309. prefix: '',
  7310. backtrack: false,
  7311. negated: false,
  7312. brackets: 0,
  7313. braces: 0,
  7314. parens: 0,
  7315. quotes: 0,
  7316. globstar: false,
  7317. tokens
  7318. };
  7319. input = utils$1.removePrefix(input, state);
  7320. len = input.length;
  7321. const extglobs = [];
  7322. const braces = [];
  7323. const stack = [];
  7324. let prev = bos;
  7325. let value;
  7326. /**
  7327. * Tokenizing helpers
  7328. */
  7329. const eos = () => state.index === len - 1;
  7330. const peek = state.peek = (n = 1) => input[state.index + n];
  7331. const advance = state.advance = () => input[++state.index];
  7332. const remaining = () => input.slice(state.index + 1);
  7333. const consume = (value = '', num = 0) => {
  7334. state.consumed += value;
  7335. state.index += num;
  7336. };
  7337. const append = token => {
  7338. state.output += token.output != null ? token.output : token.value;
  7339. consume(token.value);
  7340. };
  7341. const negate = () => {
  7342. let count = 1;
  7343. while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
  7344. advance();
  7345. state.start++;
  7346. count++;
  7347. }
  7348. if (count % 2 === 0) {
  7349. return false;
  7350. }
  7351. state.negated = true;
  7352. state.start++;
  7353. return true;
  7354. };
  7355. const increment = type => {
  7356. state[type]++;
  7357. stack.push(type);
  7358. };
  7359. const decrement = type => {
  7360. state[type]--;
  7361. stack.pop();
  7362. };
  7363. /**
  7364. * Push tokens onto the tokens array. This helper speeds up
  7365. * tokenizing by 1) helping us avoid backtracking as much as possible,
  7366. * and 2) helping us avoid creating extra tokens when consecutive
  7367. * characters are plain text. This improves performance and simplifies
  7368. * lookbehinds.
  7369. */
  7370. const push = tok => {
  7371. if (prev.type === 'globstar') {
  7372. const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
  7373. const isExtglob = tok.extglob === true || extglobs.length && (tok.type === 'pipe' || tok.type === 'paren');
  7374. if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
  7375. state.output = state.output.slice(0, -prev.output.length);
  7376. prev.type = 'star';
  7377. prev.value = '*';
  7378. prev.output = star;
  7379. state.output += prev.output;
  7380. }
  7381. }
  7382. if (extglobs.length && tok.type !== 'paren' && !EXTGLOB_CHARS[tok.value]) {
  7383. extglobs[extglobs.length - 1].inner += tok.value;
  7384. }
  7385. if (tok.value || tok.output) append(tok);
  7386. if (prev && prev.type === 'text' && tok.type === 'text') {
  7387. prev.value += tok.value;
  7388. prev.output = (prev.output || '') + tok.value;
  7389. return;
  7390. }
  7391. tok.prev = prev;
  7392. tokens.push(tok);
  7393. prev = tok;
  7394. };
  7395. const extglobOpen = (type, value) => {
  7396. const token = Object.assign({}, EXTGLOB_CHARS[value], {
  7397. conditions: 1,
  7398. inner: ''
  7399. });
  7400. token.prev = prev;
  7401. token.parens = state.parens;
  7402. token.output = state.output;
  7403. const output = (opts.capture ? '(' : '') + token.open;
  7404. increment('parens');
  7405. push({
  7406. type,
  7407. value,
  7408. output: state.output ? '' : ONE_CHAR
  7409. });
  7410. push({
  7411. type: 'paren',
  7412. extglob: true,
  7413. value: advance(),
  7414. output
  7415. });
  7416. extglobs.push(token);
  7417. };
  7418. const extglobClose = token => {
  7419. let output = token.close + (opts.capture ? ')' : '');
  7420. if (token.type === 'negate') {
  7421. let extglobStar = star;
  7422. if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
  7423. extglobStar = globstar(opts);
  7424. }
  7425. if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
  7426. output = token.close = `)$))${extglobStar}`;
  7427. }
  7428. if (token.prev.type === 'bos' && eos()) {
  7429. state.negatedExtglob = true;
  7430. }
  7431. }
  7432. push({
  7433. type: 'paren',
  7434. extglob: true,
  7435. value,
  7436. output
  7437. });
  7438. decrement('parens');
  7439. };
  7440. /**
  7441. * Fast paths
  7442. */
  7443. if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
  7444. let backslashes = false;
  7445. let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
  7446. if (first === '\\') {
  7447. backslashes = true;
  7448. return m;
  7449. }
  7450. if (first === '?') {
  7451. if (esc) {
  7452. return esc + first + (rest ? QMARK.repeat(rest.length) : '');
  7453. }
  7454. if (index === 0) {
  7455. return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
  7456. }
  7457. return QMARK.repeat(chars.length);
  7458. }
  7459. if (first === '.') {
  7460. return DOT_LITERAL.repeat(chars.length);
  7461. }
  7462. if (first === '*') {
  7463. if (esc) {
  7464. return esc + first + (rest ? star : '');
  7465. }
  7466. return star;
  7467. }
  7468. return esc ? m : `\\${m}`;
  7469. });
  7470. if (backslashes === true) {
  7471. if (opts.unescape === true) {
  7472. output = output.replace(/\\/g, '');
  7473. } else {
  7474. output = output.replace(/\\+/g, m => {
  7475. return m.length % 2 === 0 ? '\\\\' : m ? '\\' : '';
  7476. });
  7477. }
  7478. }
  7479. if (output === input && opts.contains === true) {
  7480. state.output = input;
  7481. return state;
  7482. }
  7483. state.output = utils$1.wrapOutput(output, state, options);
  7484. return state;
  7485. }
  7486. /**
  7487. * Tokenize input until we reach end-of-string
  7488. */
  7489. while (!eos()) {
  7490. value = advance();
  7491. if (value === '\u0000') {
  7492. continue;
  7493. }
  7494. /**
  7495. * Escaped characters
  7496. */
  7497. if (value === '\\') {
  7498. const next = peek();
  7499. if (next === '/' && opts.bash !== true) {
  7500. continue;
  7501. }
  7502. if (next === '.' || next === ';') {
  7503. continue;
  7504. }
  7505. if (!next) {
  7506. value += '\\';
  7507. push({
  7508. type: 'text',
  7509. value
  7510. });
  7511. continue;
  7512. } // collapse slashes to reduce potential for exploits
  7513. const match = /^\\+/.exec(remaining());
  7514. let slashes = 0;
  7515. if (match && match[0].length > 2) {
  7516. slashes = match[0].length;
  7517. state.index += slashes;
  7518. if (slashes % 2 !== 0) {
  7519. value += '\\';
  7520. }
  7521. }
  7522. if (opts.unescape === true) {
  7523. value = advance() || '';
  7524. } else {
  7525. value += advance() || '';
  7526. }
  7527. if (state.brackets === 0) {
  7528. push({
  7529. type: 'text',
  7530. value
  7531. });
  7532. continue;
  7533. }
  7534. }
  7535. /**
  7536. * If we're inside a regex character class, continue
  7537. * until we reach the closing bracket.
  7538. */
  7539. if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
  7540. if (opts.posix !== false && value === ':') {
  7541. const inner = prev.value.slice(1);
  7542. if (inner.includes('[')) {
  7543. prev.posix = true;
  7544. if (inner.includes(':')) {
  7545. const idx = prev.value.lastIndexOf('[');
  7546. const pre = prev.value.slice(0, idx);
  7547. const rest = prev.value.slice(idx + 2);
  7548. const posix = POSIX_REGEX_SOURCE$1[rest];
  7549. if (posix) {
  7550. prev.value = pre + posix;
  7551. state.backtrack = true;
  7552. advance();
  7553. if (!bos.output && tokens.indexOf(prev) === 1) {
  7554. bos.output = ONE_CHAR;
  7555. }
  7556. continue;
  7557. }
  7558. }
  7559. }
  7560. }
  7561. if (value === '[' && peek() !== ':' || value === '-' && peek() === ']') {
  7562. value = `\\${value}`;
  7563. }
  7564. if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
  7565. value = `\\${value}`;
  7566. }
  7567. if (opts.posix === true && value === '!' && prev.value === '[') {
  7568. value = '^';
  7569. }
  7570. prev.value += value;
  7571. append({
  7572. value
  7573. });
  7574. continue;
  7575. }
  7576. /**
  7577. * If we're inside a quoted string, continue
  7578. * until we reach the closing double quote.
  7579. */
  7580. if (state.quotes === 1 && value !== '"') {
  7581. value = utils$1.escapeRegex(value);
  7582. prev.value += value;
  7583. append({
  7584. value
  7585. });
  7586. continue;
  7587. }
  7588. /**
  7589. * Double quotes
  7590. */
  7591. if (value === '"') {
  7592. state.quotes = state.quotes === 1 ? 0 : 1;
  7593. if (opts.keepQuotes === true) {
  7594. push({
  7595. type: 'text',
  7596. value
  7597. });
  7598. }
  7599. continue;
  7600. }
  7601. /**
  7602. * Parentheses
  7603. */
  7604. if (value === '(') {
  7605. increment('parens');
  7606. push({
  7607. type: 'paren',
  7608. value
  7609. });
  7610. continue;
  7611. }
  7612. if (value === ')') {
  7613. if (state.parens === 0 && opts.strictBrackets === true) {
  7614. throw new SyntaxError(syntaxError('opening', '('));
  7615. }
  7616. const extglob = extglobs[extglobs.length - 1];
  7617. if (extglob && state.parens === extglob.parens + 1) {
  7618. extglobClose(extglobs.pop());
  7619. continue;
  7620. }
  7621. push({
  7622. type: 'paren',
  7623. value,
  7624. output: state.parens ? ')' : '\\)'
  7625. });
  7626. decrement('parens');
  7627. continue;
  7628. }
  7629. /**
  7630. * Square brackets
  7631. */
  7632. if (value === '[') {
  7633. if (opts.nobracket === true || !remaining().includes(']')) {
  7634. if (opts.nobracket !== true && opts.strictBrackets === true) {
  7635. throw new SyntaxError(syntaxError('closing', ']'));
  7636. }
  7637. value = `\\${value}`;
  7638. } else {
  7639. increment('brackets');
  7640. }
  7641. push({
  7642. type: 'bracket',
  7643. value
  7644. });
  7645. continue;
  7646. }
  7647. if (value === ']') {
  7648. if (opts.nobracket === true || prev && prev.type === 'bracket' && prev.value.length === 1) {
  7649. push({
  7650. type: 'text',
  7651. value,
  7652. output: `\\${value}`
  7653. });
  7654. continue;
  7655. }
  7656. if (state.brackets === 0) {
  7657. if (opts.strictBrackets === true) {
  7658. throw new SyntaxError(syntaxError('opening', '['));
  7659. }
  7660. push({
  7661. type: 'text',
  7662. value,
  7663. output: `\\${value}`
  7664. });
  7665. continue;
  7666. }
  7667. decrement('brackets');
  7668. const prevValue = prev.value.slice(1);
  7669. if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
  7670. value = `/${value}`;
  7671. }
  7672. prev.value += value;
  7673. append({
  7674. value
  7675. }); // when literal brackets are explicitly disabled
  7676. // assume we should match with a regex character class
  7677. if (opts.literalBrackets === false || utils$1.hasRegexChars(prevValue)) {
  7678. continue;
  7679. }
  7680. const escaped = utils$1.escapeRegex(prev.value);
  7681. state.output = state.output.slice(0, -prev.value.length); // when literal brackets are explicitly enabled
  7682. // assume we should escape the brackets to match literal characters
  7683. if (opts.literalBrackets === true) {
  7684. state.output += escaped;
  7685. prev.value = escaped;
  7686. continue;
  7687. } // when the user specifies nothing, try to match both
  7688. prev.value = `(${capture}${escaped}|${prev.value})`;
  7689. state.output += prev.value;
  7690. continue;
  7691. }
  7692. /**
  7693. * Braces
  7694. */
  7695. if (value === '{' && opts.nobrace !== true) {
  7696. increment('braces');
  7697. const open = {
  7698. type: 'brace',
  7699. value,
  7700. output: '(',
  7701. outputIndex: state.output.length,
  7702. tokensIndex: state.tokens.length
  7703. };
  7704. braces.push(open);
  7705. push(open);
  7706. continue;
  7707. }
  7708. if (value === '}') {
  7709. const brace = braces[braces.length - 1];
  7710. if (opts.nobrace === true || !brace) {
  7711. push({
  7712. type: 'text',
  7713. value,
  7714. output: value
  7715. });
  7716. continue;
  7717. }
  7718. let output = ')';
  7719. if (brace.dots === true) {
  7720. const arr = tokens.slice();
  7721. const range = [];
  7722. for (let i = arr.length - 1; i >= 0; i--) {
  7723. tokens.pop();
  7724. if (arr[i].type === 'brace') {
  7725. break;
  7726. }
  7727. if (arr[i].type !== 'dots') {
  7728. range.unshift(arr[i].value);
  7729. }
  7730. }
  7731. output = expandRange(range, opts);
  7732. state.backtrack = true;
  7733. }
  7734. if (brace.comma !== true && brace.dots !== true) {
  7735. const out = state.output.slice(0, brace.outputIndex);
  7736. const toks = state.tokens.slice(brace.tokensIndex);
  7737. brace.value = brace.output = '\\{';
  7738. value = output = '\\}';
  7739. state.output = out;
  7740. for (const t of toks) {
  7741. state.output += t.output || t.value;
  7742. }
  7743. }
  7744. push({
  7745. type: 'brace',
  7746. value,
  7747. output
  7748. });
  7749. decrement('braces');
  7750. braces.pop();
  7751. continue;
  7752. }
  7753. /**
  7754. * Pipes
  7755. */
  7756. if (value === '|') {
  7757. if (extglobs.length > 0) {
  7758. extglobs[extglobs.length - 1].conditions++;
  7759. }
  7760. push({
  7761. type: 'text',
  7762. value
  7763. });
  7764. continue;
  7765. }
  7766. /**
  7767. * Commas
  7768. */
  7769. if (value === ',') {
  7770. let output = value;
  7771. const brace = braces[braces.length - 1];
  7772. if (brace && stack[stack.length - 1] === 'braces') {
  7773. brace.comma = true;
  7774. output = '|';
  7775. }
  7776. push({
  7777. type: 'comma',
  7778. value,
  7779. output
  7780. });
  7781. continue;
  7782. }
  7783. /**
  7784. * Slashes
  7785. */
  7786. if (value === '/') {
  7787. // if the beginning of the glob is "./", advance the start
  7788. // to the current index, and don't add the "./" characters
  7789. // to the state. This greatly simplifies lookbehinds when
  7790. // checking for BOS characters like "!" and "." (not "./")
  7791. if (prev.type === 'dot' && state.index === state.start + 1) {
  7792. state.start = state.index + 1;
  7793. state.consumed = '';
  7794. state.output = '';
  7795. tokens.pop();
  7796. prev = bos; // reset "prev" to the first token
  7797. continue;
  7798. }
  7799. push({
  7800. type: 'slash',
  7801. value,
  7802. output: SLASH_LITERAL
  7803. });
  7804. continue;
  7805. }
  7806. /**
  7807. * Dots
  7808. */
  7809. if (value === '.') {
  7810. if (state.braces > 0 && prev.type === 'dot') {
  7811. if (prev.value === '.') prev.output = DOT_LITERAL;
  7812. const brace = braces[braces.length - 1];
  7813. prev.type = 'dots';
  7814. prev.output += value;
  7815. prev.value += value;
  7816. brace.dots = true;
  7817. continue;
  7818. }
  7819. if (state.braces + state.parens === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
  7820. push({
  7821. type: 'text',
  7822. value,
  7823. output: DOT_LITERAL
  7824. });
  7825. continue;
  7826. }
  7827. push({
  7828. type: 'dot',
  7829. value,
  7830. output: DOT_LITERAL
  7831. });
  7832. continue;
  7833. }
  7834. /**
  7835. * Question marks
  7836. */
  7837. if (value === '?') {
  7838. const isGroup = prev && prev.value === '(';
  7839. if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  7840. extglobOpen('qmark', value);
  7841. continue;
  7842. }
  7843. if (prev && prev.type === 'paren') {
  7844. const next = peek();
  7845. let output = value;
  7846. if (next === '<' && !utils$1.supportsLookbehinds()) {
  7847. throw new Error('Node.js v10 or higher is required for regex lookbehinds');
  7848. }
  7849. if (prev.value === '(' && !/[!=<:]/.test(next) || next === '<' && !/<([!=]|\w+>)/.test(remaining())) {
  7850. output = `\\${value}`;
  7851. }
  7852. push({
  7853. type: 'text',
  7854. value,
  7855. output
  7856. });
  7857. continue;
  7858. }
  7859. if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
  7860. push({
  7861. type: 'qmark',
  7862. value,
  7863. output: QMARK_NO_DOT
  7864. });
  7865. continue;
  7866. }
  7867. push({
  7868. type: 'qmark',
  7869. value,
  7870. output: QMARK
  7871. });
  7872. continue;
  7873. }
  7874. /**
  7875. * Exclamation
  7876. */
  7877. if (value === '!') {
  7878. if (opts.noextglob !== true && peek() === '(') {
  7879. if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
  7880. extglobOpen('negate', value);
  7881. continue;
  7882. }
  7883. }
  7884. if (opts.nonegate !== true && state.index === 0) {
  7885. negate();
  7886. continue;
  7887. }
  7888. }
  7889. /**
  7890. * Plus
  7891. */
  7892. if (value === '+') {
  7893. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  7894. extglobOpen('plus', value);
  7895. continue;
  7896. }
  7897. if (prev && prev.value === '(' || opts.regex === false) {
  7898. push({
  7899. type: 'plus',
  7900. value,
  7901. output: PLUS_LITERAL
  7902. });
  7903. continue;
  7904. }
  7905. if (prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace') || state.parens > 0) {
  7906. push({
  7907. type: 'plus',
  7908. value
  7909. });
  7910. continue;
  7911. }
  7912. push({
  7913. type: 'plus',
  7914. value: PLUS_LITERAL
  7915. });
  7916. continue;
  7917. }
  7918. /**
  7919. * Plain text
  7920. */
  7921. if (value === '@') {
  7922. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  7923. push({
  7924. type: 'at',
  7925. extglob: true,
  7926. value,
  7927. output: ''
  7928. });
  7929. continue;
  7930. }
  7931. push({
  7932. type: 'text',
  7933. value
  7934. });
  7935. continue;
  7936. }
  7937. /**
  7938. * Plain text
  7939. */
  7940. if (value !== '*') {
  7941. if (value === '$' || value === '^') {
  7942. value = `\\${value}`;
  7943. }
  7944. const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
  7945. if (match) {
  7946. value += match[0];
  7947. state.index += match[0].length;
  7948. }
  7949. push({
  7950. type: 'text',
  7951. value
  7952. });
  7953. continue;
  7954. }
  7955. /**
  7956. * Stars
  7957. */
  7958. if (prev && (prev.type === 'globstar' || prev.star === true)) {
  7959. prev.type = 'star';
  7960. prev.star = true;
  7961. prev.value += value;
  7962. prev.output = star;
  7963. state.backtrack = true;
  7964. state.globstar = true;
  7965. consume(value);
  7966. continue;
  7967. }
  7968. let rest = remaining();
  7969. if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
  7970. extglobOpen('star', value);
  7971. continue;
  7972. }
  7973. if (prev.type === 'star') {
  7974. if (opts.noglobstar === true) {
  7975. consume(value);
  7976. continue;
  7977. }
  7978. const prior = prev.prev;
  7979. const before = prior.prev;
  7980. const isStart = prior.type === 'slash' || prior.type === 'bos';
  7981. const afterStar = before && (before.type === 'star' || before.type === 'globstar');
  7982. if (opts.bash === true && (!isStart || rest[0] && rest[0] !== '/')) {
  7983. push({
  7984. type: 'star',
  7985. value,
  7986. output: ''
  7987. });
  7988. continue;
  7989. }
  7990. const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
  7991. const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
  7992. if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
  7993. push({
  7994. type: 'star',
  7995. value,
  7996. output: ''
  7997. });
  7998. continue;
  7999. } // strip consecutive `/**/`
  8000. while (rest.slice(0, 3) === '/**') {
  8001. const after = input[state.index + 4];
  8002. if (after && after !== '/') {
  8003. break;
  8004. }
  8005. rest = rest.slice(3);
  8006. consume('/**', 3);
  8007. }
  8008. if (prior.type === 'bos' && eos()) {
  8009. prev.type = 'globstar';
  8010. prev.value += value;
  8011. prev.output = globstar(opts);
  8012. state.output = prev.output;
  8013. state.globstar = true;
  8014. consume(value);
  8015. continue;
  8016. }
  8017. if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
  8018. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  8019. prior.output = `(?:${prior.output}`;
  8020. prev.type = 'globstar';
  8021. prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
  8022. prev.value += value;
  8023. state.globstar = true;
  8024. state.output += prior.output + prev.output;
  8025. consume(value);
  8026. continue;
  8027. }
  8028. if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
  8029. const end = rest[1] !== void 0 ? '|$' : '';
  8030. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  8031. prior.output = `(?:${prior.output}`;
  8032. prev.type = 'globstar';
  8033. prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
  8034. prev.value += value;
  8035. state.output += prior.output + prev.output;
  8036. state.globstar = true;
  8037. consume(value + advance());
  8038. push({
  8039. type: 'slash',
  8040. value: '/',
  8041. output: ''
  8042. });
  8043. continue;
  8044. }
  8045. if (prior.type === 'bos' && rest[0] === '/') {
  8046. prev.type = 'globstar';
  8047. prev.value += value;
  8048. prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
  8049. state.output = prev.output;
  8050. state.globstar = true;
  8051. consume(value + advance());
  8052. push({
  8053. type: 'slash',
  8054. value: '/',
  8055. output: ''
  8056. });
  8057. continue;
  8058. } // remove single star from output
  8059. state.output = state.output.slice(0, -prev.output.length); // reset previous token to globstar
  8060. prev.type = 'globstar';
  8061. prev.output = globstar(opts);
  8062. prev.value += value; // reset output with globstar
  8063. state.output += prev.output;
  8064. state.globstar = true;
  8065. consume(value);
  8066. continue;
  8067. }
  8068. const token = {
  8069. type: 'star',
  8070. value,
  8071. output: star
  8072. };
  8073. if (opts.bash === true) {
  8074. token.output = '.*?';
  8075. if (prev.type === 'bos' || prev.type === 'slash') {
  8076. token.output = nodot + token.output;
  8077. }
  8078. push(token);
  8079. continue;
  8080. }
  8081. if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
  8082. token.output = value;
  8083. push(token);
  8084. continue;
  8085. }
  8086. if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
  8087. if (prev.type === 'dot') {
  8088. state.output += NO_DOT_SLASH;
  8089. prev.output += NO_DOT_SLASH;
  8090. } else if (opts.dot === true) {
  8091. state.output += NO_DOTS_SLASH;
  8092. prev.output += NO_DOTS_SLASH;
  8093. } else {
  8094. state.output += nodot;
  8095. prev.output += nodot;
  8096. }
  8097. if (peek() !== '*') {
  8098. state.output += ONE_CHAR;
  8099. prev.output += ONE_CHAR;
  8100. }
  8101. }
  8102. push(token);
  8103. }
  8104. while (state.brackets > 0) {
  8105. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
  8106. state.output = utils$1.escapeLast(state.output, '[');
  8107. decrement('brackets');
  8108. }
  8109. while (state.parens > 0) {
  8110. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
  8111. state.output = utils$1.escapeLast(state.output, '(');
  8112. decrement('parens');
  8113. }
  8114. while (state.braces > 0) {
  8115. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
  8116. state.output = utils$1.escapeLast(state.output, '{');
  8117. decrement('braces');
  8118. }
  8119. if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
  8120. push({
  8121. type: 'maybe_slash',
  8122. value: '',
  8123. output: `${SLASH_LITERAL}?`
  8124. });
  8125. } // rebuild the output if we had to backtrack at any point
  8126. if (state.backtrack === true) {
  8127. state.output = '';
  8128. for (const token of state.tokens) {
  8129. state.output += token.output != null ? token.output : token.value;
  8130. if (token.suffix) {
  8131. state.output += token.suffix;
  8132. }
  8133. }
  8134. }
  8135. return state;
  8136. };
  8137. /**
  8138. * Fast paths for creating regular expressions for common glob patterns.
  8139. * This can significantly speed up processing and has very little downside
  8140. * impact when none of the fast paths match.
  8141. */
  8142. parse$1.fastpaths = (input, options) => {
  8143. const opts = Object.assign({}, options);
  8144. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1;
  8145. const len = input.length;
  8146. if (len > max) {
  8147. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  8148. }
  8149. input = REPLACEMENTS[input] || input;
  8150. const win32 = utils$1.isWindows(options); // create constants based on platform, for windows or posix
  8151. const {
  8152. DOT_LITERAL,
  8153. SLASH_LITERAL,
  8154. ONE_CHAR,
  8155. DOTS_SLASH,
  8156. NO_DOT,
  8157. NO_DOTS,
  8158. NO_DOTS_SLASH,
  8159. STAR,
  8160. START_ANCHOR
  8161. } = constants$1.globChars(win32);
  8162. const nodot = opts.dot ? NO_DOTS : NO_DOT;
  8163. const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
  8164. const capture = opts.capture ? '' : '?:';
  8165. const state = {
  8166. negated: false,
  8167. prefix: ''
  8168. };
  8169. let star = opts.bash === true ? '.*?' : STAR;
  8170. if (opts.capture) {
  8171. star = `(${star})`;
  8172. }
  8173. const globstar = opts => {
  8174. if (opts.noglobstar === true) return star;
  8175. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  8176. };
  8177. const create = str => {
  8178. switch (str) {
  8179. case '*':
  8180. return `${nodot}${ONE_CHAR}${star}`;
  8181. case '.*':
  8182. return `${DOT_LITERAL}${ONE_CHAR}${star}`;
  8183. case '*.*':
  8184. return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  8185. case '*/*':
  8186. return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
  8187. case '**':
  8188. return nodot + globstar(opts);
  8189. case '**/*':
  8190. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
  8191. case '**/*.*':
  8192. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  8193. case '**/.*':
  8194. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
  8195. default:
  8196. {
  8197. const match = /^(.*?)\.(\w+)$/.exec(str);
  8198. if (!match) return;
  8199. const source = create(match[1]);
  8200. if (!source) return;
  8201. return source + DOT_LITERAL + match[2];
  8202. }
  8203. }
  8204. };
  8205. const output = utils$1.removePrefix(input, state);
  8206. let source = create(output);
  8207. if (source && opts.strictSlashes !== true) {
  8208. source += `${SLASH_LITERAL}?`;
  8209. }
  8210. return source;
  8211. };
  8212. var parse_1$1 = parse$1;
  8213. const isObject$2 = val => val && typeof val === 'object' && !Array.isArray(val);
  8214. /**
  8215. * Creates a matcher function from one or more glob patterns. The
  8216. * returned function takes a string to match as its first argument,
  8217. * and returns true if the string is a match. The returned matcher
  8218. * function also takes a boolean as the second argument that, when true,
  8219. * returns an object with additional information.
  8220. *
  8221. * ```js
  8222. * const picomatch = require('picomatch');
  8223. * // picomatch(glob[, options]);
  8224. *
  8225. * const isMatch = picomatch('*.!(*a)');
  8226. * console.log(isMatch('a.a')); //=> false
  8227. * console.log(isMatch('a.b')); //=> true
  8228. * ```
  8229. * @name picomatch
  8230. * @param {String|Array} `globs` One or more glob patterns.
  8231. * @param {Object=} `options`
  8232. * @return {Function=} Returns a matcher function.
  8233. * @api public
  8234. */
  8235. const picomatch = (glob, options, returnState = false) => {
  8236. if (Array.isArray(glob)) {
  8237. const fns = glob.map(input => picomatch(input, options, returnState));
  8238. const arrayMatcher = str => {
  8239. for (const isMatch of fns) {
  8240. const state = isMatch(str);
  8241. if (state) return state;
  8242. }
  8243. return false;
  8244. };
  8245. return arrayMatcher;
  8246. }
  8247. const isState = isObject$2(glob) && glob.tokens && glob.input;
  8248. if (glob === '' || typeof glob !== 'string' && !isState) {
  8249. throw new TypeError('Expected pattern to be a non-empty string');
  8250. }
  8251. const opts = options || {};
  8252. const posix = utils$1.isWindows(options);
  8253. const regex = isState ? picomatch.compileRe(glob, options) : picomatch.makeRe(glob, options, false, true);
  8254. const state = regex.state;
  8255. delete regex.state;
  8256. let isIgnored = () => false;
  8257. if (opts.ignore) {
  8258. const ignoreOpts = Object.assign({}, options, {
  8259. ignore: null,
  8260. onMatch: null,
  8261. onResult: null
  8262. });
  8263. isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
  8264. }
  8265. const matcher = (input, returnObject = false) => {
  8266. const {
  8267. isMatch,
  8268. match,
  8269. output
  8270. } = picomatch.test(input, regex, options, {
  8271. glob,
  8272. posix
  8273. });
  8274. const result = {
  8275. glob,
  8276. state,
  8277. regex,
  8278. posix,
  8279. input,
  8280. output,
  8281. match,
  8282. isMatch
  8283. };
  8284. if (typeof opts.onResult === 'function') {
  8285. opts.onResult(result);
  8286. }
  8287. if (isMatch === false) {
  8288. result.isMatch = false;
  8289. return returnObject ? result : false;
  8290. }
  8291. if (isIgnored(input)) {
  8292. if (typeof opts.onIgnore === 'function') {
  8293. opts.onIgnore(result);
  8294. }
  8295. result.isMatch = false;
  8296. return returnObject ? result : false;
  8297. }
  8298. if (typeof opts.onMatch === 'function') {
  8299. opts.onMatch(result);
  8300. }
  8301. return returnObject ? result : true;
  8302. };
  8303. if (returnState) {
  8304. matcher.state = state;
  8305. }
  8306. return matcher;
  8307. };
  8308. /**
  8309. * Test `input` with the given `regex`. This is used by the main
  8310. * `picomatch()` function to test the input string.
  8311. *
  8312. * ```js
  8313. * const picomatch = require('picomatch');
  8314. * // picomatch.test(input, regex[, options]);
  8315. *
  8316. * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
  8317. * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
  8318. * ```
  8319. * @param {String} `input` String to test.
  8320. * @param {RegExp} `regex`
  8321. * @return {Object} Returns an object with matching info.
  8322. * @api public
  8323. */
  8324. picomatch.test = (input, regex, options, {
  8325. glob,
  8326. posix
  8327. } = {}) => {
  8328. if (typeof input !== 'string') {
  8329. throw new TypeError('Expected input to be a string');
  8330. }
  8331. if (input === '') {
  8332. return {
  8333. isMatch: false,
  8334. output: ''
  8335. };
  8336. }
  8337. const opts = options || {};
  8338. const format = opts.format || (posix ? utils$1.toPosixSlashes : null);
  8339. let match = input === glob;
  8340. let output = match && format ? format(input) : input;
  8341. if (match === false) {
  8342. output = format ? format(input) : input;
  8343. match = output === glob;
  8344. }
  8345. if (match === false || opts.capture === true) {
  8346. if (opts.matchBase === true || opts.basename === true) {
  8347. match = picomatch.matchBase(input, regex, options, posix);
  8348. } else {
  8349. match = regex.exec(output);
  8350. }
  8351. }
  8352. return {
  8353. isMatch: Boolean(match),
  8354. match,
  8355. output
  8356. };
  8357. };
  8358. /**
  8359. * Match the basename of a filepath.
  8360. *
  8361. * ```js
  8362. * const picomatch = require('picomatch');
  8363. * // picomatch.matchBase(input, glob[, options]);
  8364. * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
  8365. * ```
  8366. * @param {String} `input` String to test.
  8367. * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
  8368. * @return {Boolean}
  8369. * @api public
  8370. */
  8371. picomatch.matchBase = (input, glob, options, posix = utils$1.isWindows(options)) => {
  8372. const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
  8373. return regex.test(path__default['default'].basename(input));
  8374. };
  8375. /**
  8376. * Returns true if **any** of the given glob `patterns` match the specified `string`.
  8377. *
  8378. * ```js
  8379. * const picomatch = require('picomatch');
  8380. * // picomatch.isMatch(string, patterns[, options]);
  8381. *
  8382. * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
  8383. * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
  8384. * ```
  8385. * @param {String|Array} str The string to test.
  8386. * @param {String|Array} patterns One or more glob patterns to use for matching.
  8387. * @param {Object} [options] See available [options](#options).
  8388. * @return {Boolean} Returns true if any patterns match `str`
  8389. * @api public
  8390. */
  8391. picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
  8392. /**
  8393. * Parse a glob pattern to create the source string for a regular
  8394. * expression.
  8395. *
  8396. * ```js
  8397. * const picomatch = require('picomatch');
  8398. * const result = picomatch.parse(pattern[, options]);
  8399. * ```
  8400. * @param {String} `pattern`
  8401. * @param {Object} `options`
  8402. * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
  8403. * @api public
  8404. */
  8405. picomatch.parse = (pattern, options) => {
  8406. if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options));
  8407. return parse_1$1(pattern, Object.assign({}, options, {
  8408. fastpaths: false
  8409. }));
  8410. };
  8411. /**
  8412. * Scan a glob pattern to separate the pattern into segments.
  8413. *
  8414. * ```js
  8415. * const picomatch = require('picomatch');
  8416. * // picomatch.scan(input[, options]);
  8417. *
  8418. * const result = picomatch.scan('!./foo/*.js');
  8419. * console.log(result);
  8420. * { prefix: '!./',
  8421. * input: '!./foo/*.js',
  8422. * start: 3,
  8423. * base: 'foo',
  8424. * glob: '*.js',
  8425. * isBrace: false,
  8426. * isBracket: false,
  8427. * isGlob: true,
  8428. * isExtglob: false,
  8429. * isGlobstar: false,
  8430. * negated: true }
  8431. * ```
  8432. * @param {String} `input` Glob pattern to scan.
  8433. * @param {Object} `options`
  8434. * @return {Object} Returns an object with
  8435. * @api public
  8436. */
  8437. picomatch.scan = (input, options) => scan_1(input, options);
  8438. /**
  8439. * Create a regular expression from a parsed glob pattern.
  8440. *
  8441. * ```js
  8442. * const picomatch = require('picomatch');
  8443. * const state = picomatch.parse('*.js');
  8444. * // picomatch.compileRe(state[, options]);
  8445. *
  8446. * console.log(picomatch.compileRe(state));
  8447. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  8448. * ```
  8449. * @param {String} `state` The object returned from the `.parse` method.
  8450. * @param {Object} `options`
  8451. * @return {RegExp} Returns a regex created from the given pattern.
  8452. * @api public
  8453. */
  8454. picomatch.compileRe = (parsed, options, returnOutput = false, returnState = false) => {
  8455. if (returnOutput === true) {
  8456. return parsed.output;
  8457. }
  8458. const opts = options || {};
  8459. const prepend = opts.contains ? '' : '^';
  8460. const append = opts.contains ? '' : '$';
  8461. let source = `${prepend}(?:${parsed.output})${append}`;
  8462. if (parsed && parsed.negated === true) {
  8463. source = `^(?!${source}).*$`;
  8464. }
  8465. const regex = picomatch.toRegex(source, options);
  8466. if (returnState === true) {
  8467. regex.state = parsed;
  8468. }
  8469. return regex;
  8470. };
  8471. picomatch.makeRe = (input, options, returnOutput = false, returnState = false) => {
  8472. if (!input || typeof input !== 'string') {
  8473. throw new TypeError('Expected a non-empty string');
  8474. }
  8475. const opts = options || {};
  8476. let parsed = {
  8477. negated: false,
  8478. fastpaths: true
  8479. };
  8480. let prefix = '';
  8481. let output;
  8482. if (input.startsWith('./')) {
  8483. input = input.slice(2);
  8484. prefix = parsed.prefix = './';
  8485. }
  8486. if (opts.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
  8487. output = parse_1$1.fastpaths(input, options);
  8488. }
  8489. if (output === undefined) {
  8490. parsed = parse_1$1(input, options);
  8491. parsed.prefix = prefix + (parsed.prefix || '');
  8492. } else {
  8493. parsed.output = output;
  8494. }
  8495. return picomatch.compileRe(parsed, options, returnOutput, returnState);
  8496. };
  8497. /**
  8498. * Create a regular expression from the given regex source string.
  8499. *
  8500. * ```js
  8501. * const picomatch = require('picomatch');
  8502. * // picomatch.toRegex(source[, options]);
  8503. *
  8504. * const { output } = picomatch.parse('*.js');
  8505. * console.log(picomatch.toRegex(output));
  8506. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  8507. * ```
  8508. * @param {String} `source` Regular expression source string.
  8509. * @param {Object} `options`
  8510. * @return {RegExp}
  8511. * @api public
  8512. */
  8513. picomatch.toRegex = (source, options) => {
  8514. try {
  8515. const opts = options || {};
  8516. return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
  8517. } catch (err) {
  8518. if (options && options.debug === true) throw err;
  8519. return /$^/;
  8520. }
  8521. };
  8522. /**
  8523. * Picomatch constants.
  8524. * @return {Object}
  8525. */
  8526. picomatch.constants = constants$1;
  8527. /**
  8528. * Expose "picomatch"
  8529. */
  8530. var picomatch_1 = picomatch;
  8531. var picomatch$1 = picomatch_1;
  8532. const isEmptyString = val => typeof val === 'string' && (val === '' || val === './');
  8533. /**
  8534. * Returns an array of strings that match one or more glob patterns.
  8535. *
  8536. * ```js
  8537. * const mm = require('micromatch');
  8538. * // mm(list, patterns[, options]);
  8539. *
  8540. * console.log(mm(['a.js', 'a.txt'], ['*.js']));
  8541. * //=> [ 'a.js' ]
  8542. * ```
  8543. * @param {String|Array<string>} list List of strings to match.
  8544. * @param {String|Array<string>} patterns One or more glob patterns to use for matching.
  8545. * @param {Object} options See available [options](#options)
  8546. * @return {Array} Returns an array of matches
  8547. * @summary false
  8548. * @api public
  8549. */
  8550. const micromatch = (list, patterns, options) => {
  8551. patterns = [].concat(patterns);
  8552. list = [].concat(list);
  8553. let omit = new Set();
  8554. let keep = new Set();
  8555. let items = new Set();
  8556. let negatives = 0;
  8557. let onResult = state => {
  8558. items.add(state.output);
  8559. if (options && options.onResult) {
  8560. options.onResult(state);
  8561. }
  8562. };
  8563. for (let i = 0; i < patterns.length; i++) {
  8564. let isMatch = picomatch$1(String(patterns[i]), Object.assign({}, options, {
  8565. onResult
  8566. }), true);
  8567. let negated = isMatch.state.negated || isMatch.state.negatedExtglob;
  8568. if (negated) negatives++;
  8569. for (let item of list) {
  8570. let matched = isMatch(item, true);
  8571. let match = negated ? !matched.isMatch : matched.isMatch;
  8572. if (!match) continue;
  8573. if (negated) {
  8574. omit.add(matched.output);
  8575. } else {
  8576. omit.delete(matched.output);
  8577. keep.add(matched.output);
  8578. }
  8579. }
  8580. }
  8581. let result = negatives === patterns.length ? [...items] : [...keep];
  8582. let matches = result.filter(item => !omit.has(item));
  8583. if (options && matches.length === 0) {
  8584. if (options.failglob === true) {
  8585. throw new Error(`No matches found for "${patterns.join(', ')}"`);
  8586. }
  8587. if (options.nonull === true || options.nullglob === true) {
  8588. return options.unescape ? patterns.map(p => p.replace(/\\/g, '')) : patterns;
  8589. }
  8590. }
  8591. return matches;
  8592. };
  8593. /**
  8594. * Backwards compatibility
  8595. */
  8596. micromatch.match = micromatch;
  8597. /**
  8598. * Returns a matcher function from the given glob `pattern` and `options`.
  8599. * The returned function takes a string to match as its only argument and returns
  8600. * true if the string is a match.
  8601. *
  8602. * ```js
  8603. * const mm = require('micromatch');
  8604. * // mm.matcher(pattern[, options]);
  8605. *
  8606. * const isMatch = mm.matcher('*.!(*a)');
  8607. * console.log(isMatch('a.a')); //=> false
  8608. * console.log(isMatch('a.b')); //=> true
  8609. * ```
  8610. * @param {String} `pattern` Glob pattern
  8611. * @param {Object} `options`
  8612. * @return {Function} Returns a matcher function.
  8613. * @api public
  8614. */
  8615. micromatch.matcher = (pattern, options) => picomatch$1(pattern, options);
  8616. /**
  8617. * Returns true if **any** of the given glob `patterns` match the specified `string`.
  8618. *
  8619. * ```js
  8620. * const mm = require('micromatch');
  8621. * // mm.isMatch(string, patterns[, options]);
  8622. *
  8623. * console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true
  8624. * console.log(mm.isMatch('a.a', 'b.*')); //=> false
  8625. * ```
  8626. * @param {String} str The string to test.
  8627. * @param {String|Array} patterns One or more glob patterns to use for matching.
  8628. * @param {Object} [options] See available [options](#options).
  8629. * @return {Boolean} Returns true if any patterns match `str`
  8630. * @api public
  8631. */
  8632. micromatch.isMatch = (str, patterns, options) => picomatch$1(patterns, options)(str);
  8633. /**
  8634. * Backwards compatibility
  8635. */
  8636. micromatch.any = micromatch.isMatch;
  8637. /**
  8638. * Returns a list of strings that _**do not match any**_ of the given `patterns`.
  8639. *
  8640. * ```js
  8641. * const mm = require('micromatch');
  8642. * // mm.not(list, patterns[, options]);
  8643. *
  8644. * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a'));
  8645. * //=> ['b.b', 'c.c']
  8646. * ```
  8647. * @param {Array} `list` Array of strings to match.
  8648. * @param {String|Array} `patterns` One or more glob pattern to use for matching.
  8649. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  8650. * @return {Array} Returns an array of strings that **do not match** the given patterns.
  8651. * @api public
  8652. */
  8653. micromatch.not = (list, patterns, options = {}) => {
  8654. patterns = [].concat(patterns).map(String);
  8655. let result = new Set();
  8656. let items = [];
  8657. let onResult = state => {
  8658. if (options.onResult) options.onResult(state);
  8659. items.push(state.output);
  8660. };
  8661. let matches = micromatch(list, patterns, Object.assign({}, options, {
  8662. onResult
  8663. }));
  8664. for (let item of items) {
  8665. if (!matches.includes(item)) {
  8666. result.add(item);
  8667. }
  8668. }
  8669. return [...result];
  8670. };
  8671. /**
  8672. * Returns true if the given `string` contains the given pattern. Similar
  8673. * to [.isMatch](#isMatch) but the pattern can match any part of the string.
  8674. *
  8675. * ```js
  8676. * var mm = require('micromatch');
  8677. * // mm.contains(string, pattern[, options]);
  8678. *
  8679. * console.log(mm.contains('aa/bb/cc', '*b'));
  8680. * //=> true
  8681. * console.log(mm.contains('aa/bb/cc', '*d'));
  8682. * //=> false
  8683. * ```
  8684. * @param {String} `str` The string to match.
  8685. * @param {String|Array} `patterns` Glob pattern to use for matching.
  8686. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  8687. * @return {Boolean} Returns true if the patter matches any part of `str`.
  8688. * @api public
  8689. */
  8690. micromatch.contains = (str, pattern, options) => {
  8691. if (typeof str !== 'string') {
  8692. throw new TypeError(`Expected a string: "${util__default['default'].inspect(str)}"`);
  8693. }
  8694. if (Array.isArray(pattern)) {
  8695. return pattern.some(p => micromatch.contains(str, p, options));
  8696. }
  8697. if (typeof pattern === 'string') {
  8698. if (isEmptyString(str) || isEmptyString(pattern)) {
  8699. return false;
  8700. }
  8701. if (str.includes(pattern) || str.startsWith('./') && str.slice(2).includes(pattern)) {
  8702. return true;
  8703. }
  8704. }
  8705. return micromatch.isMatch(str, pattern, Object.assign({}, options, {
  8706. contains: true
  8707. }));
  8708. };
  8709. /**
  8710. * Filter the keys of the given object with the given `glob` pattern
  8711. * and `options`. Does not attempt to match nested keys. If you need this feature,
  8712. * use [glob-object][] instead.
  8713. *
  8714. * ```js
  8715. * const mm = require('micromatch');
  8716. * // mm.matchKeys(object, patterns[, options]);
  8717. *
  8718. * const obj = { aa: 'a', ab: 'b', ac: 'c' };
  8719. * console.log(mm.matchKeys(obj, '*b'));
  8720. * //=> { ab: 'b' }
  8721. * ```
  8722. * @param {Object} `object` The object with keys to filter.
  8723. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  8724. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  8725. * @return {Object} Returns an object with only keys that match the given patterns.
  8726. * @api public
  8727. */
  8728. micromatch.matchKeys = (obj, patterns, options) => {
  8729. if (!utils$1.isObject(obj)) {
  8730. throw new TypeError('Expected the first argument to be an object');
  8731. }
  8732. let keys = micromatch(Object.keys(obj), patterns, options);
  8733. let res = {};
  8734. for (let key of keys) res[key] = obj[key];
  8735. return res;
  8736. };
  8737. /**
  8738. * Returns true if some of the strings in the given `list` match any of the given glob `patterns`.
  8739. *
  8740. * ```js
  8741. * const mm = require('micromatch');
  8742. * // mm.some(list, patterns[, options]);
  8743. *
  8744. * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
  8745. * // true
  8746. * console.log(mm.some(['foo.js'], ['*.js', '!foo.js']));
  8747. * // false
  8748. * ```
  8749. * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found.
  8750. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  8751. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  8752. * @return {Boolean} Returns true if any patterns match `str`
  8753. * @api public
  8754. */
  8755. micromatch.some = (list, patterns, options) => {
  8756. let items = [].concat(list);
  8757. for (let pattern of [].concat(patterns)) {
  8758. let isMatch = picomatch$1(String(pattern), options);
  8759. if (items.some(item => isMatch(item))) {
  8760. return true;
  8761. }
  8762. }
  8763. return false;
  8764. };
  8765. /**
  8766. * Returns true if every string in the given `list` matches
  8767. * any of the given glob `patterns`.
  8768. *
  8769. * ```js
  8770. * const mm = require('micromatch');
  8771. * // mm.every(list, patterns[, options]);
  8772. *
  8773. * console.log(mm.every('foo.js', ['foo.js']));
  8774. * // true
  8775. * console.log(mm.every(['foo.js', 'bar.js'], ['*.js']));
  8776. * // true
  8777. * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
  8778. * // false
  8779. * console.log(mm.every(['foo.js'], ['*.js', '!foo.js']));
  8780. * // false
  8781. * ```
  8782. * @param {String|Array} `list` The string or array of strings to test.
  8783. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  8784. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  8785. * @return {Boolean} Returns true if any patterns match `str`
  8786. * @api public
  8787. */
  8788. micromatch.every = (list, patterns, options) => {
  8789. let items = [].concat(list);
  8790. for (let pattern of [].concat(patterns)) {
  8791. let isMatch = picomatch$1(String(pattern), options);
  8792. if (!items.every(item => isMatch(item))) {
  8793. return false;
  8794. }
  8795. }
  8796. return true;
  8797. };
  8798. /**
  8799. * Returns true if **all** of the given `patterns` match
  8800. * the specified string.
  8801. *
  8802. * ```js
  8803. * const mm = require('micromatch');
  8804. * // mm.all(string, patterns[, options]);
  8805. *
  8806. * console.log(mm.all('foo.js', ['foo.js']));
  8807. * // true
  8808. *
  8809. * console.log(mm.all('foo.js', ['*.js', '!foo.js']));
  8810. * // false
  8811. *
  8812. * console.log(mm.all('foo.js', ['*.js', 'foo.js']));
  8813. * // true
  8814. *
  8815. * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js']));
  8816. * // true
  8817. * ```
  8818. * @param {String|Array} `str` The string to test.
  8819. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  8820. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  8821. * @return {Boolean} Returns true if any patterns match `str`
  8822. * @api public
  8823. */
  8824. micromatch.all = (str, patterns, options) => {
  8825. if (typeof str !== 'string') {
  8826. throw new TypeError(`Expected a string: "${util__default['default'].inspect(str)}"`);
  8827. }
  8828. return [].concat(patterns).every(p => picomatch$1(p, options)(str));
  8829. };
  8830. /**
  8831. * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match.
  8832. *
  8833. * ```js
  8834. * const mm = require('micromatch');
  8835. * // mm.capture(pattern, string[, options]);
  8836. *
  8837. * console.log(mm.capture('test/*.js', 'test/foo.js'));
  8838. * //=> ['foo']
  8839. * console.log(mm.capture('test/*.js', 'foo/bar.css'));
  8840. * //=> null
  8841. * ```
  8842. * @param {String} `glob` Glob pattern to use for matching.
  8843. * @param {String} `input` String to match
  8844. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  8845. * @return {Boolean} Returns an array of captures if the input matches the glob pattern, otherwise `null`.
  8846. * @api public
  8847. */
  8848. micromatch.capture = (glob, input, options) => {
  8849. let posix = utils$1.isWindows(options);
  8850. let regex = picomatch$1.makeRe(String(glob), Object.assign({}, options, {
  8851. capture: true
  8852. }));
  8853. let match = regex.exec(posix ? utils$1.toPosixSlashes(input) : input);
  8854. if (match) {
  8855. return match.slice(1).map(v => v === void 0 ? '' : v);
  8856. }
  8857. };
  8858. /**
  8859. * Create a regular expression from the given glob `pattern`.
  8860. *
  8861. * ```js
  8862. * const mm = require('micromatch');
  8863. * // mm.makeRe(pattern[, options]);
  8864. *
  8865. * console.log(mm.makeRe('*.js'));
  8866. * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/
  8867. * ```
  8868. * @param {String} `pattern` A glob pattern to convert to regex.
  8869. * @param {Object} `options`
  8870. * @return {RegExp} Returns a regex created from the given pattern.
  8871. * @api public
  8872. */
  8873. micromatch.makeRe = (...args) => picomatch$1.makeRe(...args);
  8874. /**
  8875. * Scan a glob pattern to separate the pattern into segments. Used
  8876. * by the [split](#split) method.
  8877. *
  8878. * ```js
  8879. * const mm = require('micromatch');
  8880. * const state = mm.scan(pattern[, options]);
  8881. * ```
  8882. * @param {String} `pattern`
  8883. * @param {Object} `options`
  8884. * @return {Object} Returns an object with
  8885. * @api public
  8886. */
  8887. micromatch.scan = (...args) => picomatch$1.scan(...args);
  8888. /**
  8889. * Parse a glob pattern to create the source string for a regular
  8890. * expression.
  8891. *
  8892. * ```js
  8893. * const mm = require('micromatch');
  8894. * const state = mm(pattern[, options]);
  8895. * ```
  8896. * @param {String} `glob`
  8897. * @param {Object} `options`
  8898. * @return {Object} Returns an object with useful properties and output to be used as regex source string.
  8899. * @api public
  8900. */
  8901. micromatch.parse = (patterns, options) => {
  8902. let res = [];
  8903. for (let pattern of [].concat(patterns || [])) {
  8904. for (let str of braces_1(String(pattern), options)) {
  8905. res.push(picomatch$1.parse(str, options));
  8906. }
  8907. }
  8908. return res;
  8909. };
  8910. /**
  8911. * Process the given brace `pattern`.
  8912. *
  8913. * ```js
  8914. * const { braces } = require('micromatch');
  8915. * console.log(braces('foo/{a,b,c}/bar'));
  8916. * //=> [ 'foo/(a|b|c)/bar' ]
  8917. *
  8918. * console.log(braces('foo/{a,b,c}/bar', { expand: true }));
  8919. * //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ]
  8920. * ```
  8921. * @param {String} `pattern` String with brace pattern to process.
  8922. * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options.
  8923. * @return {Array}
  8924. * @api public
  8925. */
  8926. micromatch.braces = (pattern, options) => {
  8927. if (typeof pattern !== 'string') throw new TypeError('Expected a string');
  8928. if (options && options.nobrace === true || !/\{.*\}/.test(pattern)) {
  8929. return [pattern];
  8930. }
  8931. return braces_1(pattern, options);
  8932. };
  8933. /**
  8934. * Expand braces
  8935. */
  8936. micromatch.braceExpand = (pattern, options) => {
  8937. if (typeof pattern !== 'string') throw new TypeError('Expected a string');
  8938. return micromatch.braces(pattern, Object.assign({}, options, {
  8939. expand: true
  8940. }));
  8941. };
  8942. /**
  8943. * Expose micromatch
  8944. */
  8945. var micromatch_1 = micromatch;
  8946. var pattern = createCommonjsModule(function (module, exports) {
  8947. Object.defineProperty(exports, "__esModule", {
  8948. value: true
  8949. });
  8950. exports.matchAny = exports.convertPatternsToRe = exports.makeRe = exports.getPatternParts = exports.expandBraceExpansion = exports.expandPatternsWithBraceExpansion = exports.isAffectDepthOfReadingPattern = exports.endsWithSlashGlobStar = exports.hasGlobStar = exports.getBaseDirectory = exports.getPositivePatterns = exports.getNegativePatterns = exports.isPositivePattern = exports.isNegativePattern = exports.convertToNegativePattern = exports.convertToPositivePattern = exports.isDynamicPattern = exports.isStaticPattern = void 0;
  8951. const GLOBSTAR = '**';
  8952. const ESCAPE_SYMBOL = '\\';
  8953. const COMMON_GLOB_SYMBOLS_RE = /[*?]|^!/;
  8954. const REGEX_CHARACTER_CLASS_SYMBOLS_RE = /\[.*]/;
  8955. const REGEX_GROUP_SYMBOLS_RE = /(?:^|[^!*+?@])\(.*\|.*\)/;
  8956. const GLOB_EXTENSION_SYMBOLS_RE = /[!*+?@]\(.*\)/;
  8957. const BRACE_EXPANSIONS_SYMBOLS_RE = /{.*(?:,|\.\.).*}/;
  8958. function isStaticPattern(pattern, options = {}) {
  8959. return !isDynamicPattern(pattern, options);
  8960. }
  8961. exports.isStaticPattern = isStaticPattern;
  8962. function isDynamicPattern(pattern, options = {}) {
  8963. /**
  8964. * A special case with an empty string is necessary for matching patterns that start with a forward slash.
  8965. * An empty string cannot be a dynamic pattern.
  8966. * For example, the pattern `/lib/*` will be spread into parts: '', 'lib', '*'.
  8967. */
  8968. if (pattern === '') {
  8969. return false;
  8970. }
  8971. /**
  8972. * When the `caseSensitiveMatch` option is disabled, all patterns must be marked as dynamic, because we cannot check
  8973. * filepath directly (without read directory).
  8974. */
  8975. if (options.caseSensitiveMatch === false || pattern.includes(ESCAPE_SYMBOL)) {
  8976. return true;
  8977. }
  8978. if (COMMON_GLOB_SYMBOLS_RE.test(pattern) || REGEX_CHARACTER_CLASS_SYMBOLS_RE.test(pattern) || REGEX_GROUP_SYMBOLS_RE.test(pattern)) {
  8979. return true;
  8980. }
  8981. if (options.extglob !== false && GLOB_EXTENSION_SYMBOLS_RE.test(pattern)) {
  8982. return true;
  8983. }
  8984. if (options.braceExpansion !== false && BRACE_EXPANSIONS_SYMBOLS_RE.test(pattern)) {
  8985. return true;
  8986. }
  8987. return false;
  8988. }
  8989. exports.isDynamicPattern = isDynamicPattern;
  8990. function convertToPositivePattern(pattern) {
  8991. return isNegativePattern(pattern) ? pattern.slice(1) : pattern;
  8992. }
  8993. exports.convertToPositivePattern = convertToPositivePattern;
  8994. function convertToNegativePattern(pattern) {
  8995. return '!' + pattern;
  8996. }
  8997. exports.convertToNegativePattern = convertToNegativePattern;
  8998. function isNegativePattern(pattern) {
  8999. return pattern.startsWith('!') && pattern[1] !== '(';
  9000. }
  9001. exports.isNegativePattern = isNegativePattern;
  9002. function isPositivePattern(pattern) {
  9003. return !isNegativePattern(pattern);
  9004. }
  9005. exports.isPositivePattern = isPositivePattern;
  9006. function getNegativePatterns(patterns) {
  9007. return patterns.filter(isNegativePattern);
  9008. }
  9009. exports.getNegativePatterns = getNegativePatterns;
  9010. function getPositivePatterns(patterns) {
  9011. return patterns.filter(isPositivePattern);
  9012. }
  9013. exports.getPositivePatterns = getPositivePatterns;
  9014. function getBaseDirectory(pattern) {
  9015. return globParent(pattern, {
  9016. flipBackslashes: false
  9017. });
  9018. }
  9019. exports.getBaseDirectory = getBaseDirectory;
  9020. function hasGlobStar(pattern) {
  9021. return pattern.includes(GLOBSTAR);
  9022. }
  9023. exports.hasGlobStar = hasGlobStar;
  9024. function endsWithSlashGlobStar(pattern) {
  9025. return pattern.endsWith('/' + GLOBSTAR);
  9026. }
  9027. exports.endsWithSlashGlobStar = endsWithSlashGlobStar;
  9028. function isAffectDepthOfReadingPattern(pattern) {
  9029. const basename = path__default['default'].basename(pattern);
  9030. return endsWithSlashGlobStar(pattern) || isStaticPattern(basename);
  9031. }
  9032. exports.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern;
  9033. function expandPatternsWithBraceExpansion(patterns) {
  9034. return patterns.reduce((collection, pattern) => {
  9035. return collection.concat(expandBraceExpansion(pattern));
  9036. }, []);
  9037. }
  9038. exports.expandPatternsWithBraceExpansion = expandPatternsWithBraceExpansion;
  9039. function expandBraceExpansion(pattern) {
  9040. return micromatch_1.braces(pattern, {
  9041. expand: true,
  9042. nodupes: true
  9043. });
  9044. }
  9045. exports.expandBraceExpansion = expandBraceExpansion;
  9046. function getPatternParts(pattern, options) {
  9047. let {
  9048. parts
  9049. } = picomatch$1.scan(pattern, Object.assign(Object.assign({}, options), {
  9050. parts: true
  9051. }));
  9052. /**
  9053. * The scan method returns an empty array in some cases.
  9054. * See micromatch/picomatch#58 for more details.
  9055. */
  9056. if (parts.length === 0) {
  9057. parts = [pattern];
  9058. }
  9059. /**
  9060. * The scan method does not return an empty part for the pattern with a forward slash.
  9061. * This is another part of micromatch/picomatch#58.
  9062. */
  9063. if (parts[0].startsWith('/')) {
  9064. parts[0] = parts[0].slice(1);
  9065. parts.unshift('');
  9066. }
  9067. return parts;
  9068. }
  9069. exports.getPatternParts = getPatternParts;
  9070. function makeRe(pattern, options) {
  9071. return micromatch_1.makeRe(pattern, options);
  9072. }
  9073. exports.makeRe = makeRe;
  9074. function convertPatternsToRe(patterns, options) {
  9075. return patterns.map(pattern => makeRe(pattern, options));
  9076. }
  9077. exports.convertPatternsToRe = convertPatternsToRe;
  9078. function matchAny(entry, patternsRe) {
  9079. return patternsRe.some(patternRe => patternRe.test(entry));
  9080. }
  9081. exports.matchAny = matchAny;
  9082. });
  9083. /*
  9084. * merge2
  9085. * https://github.com/teambition/merge2
  9086. *
  9087. * Copyright (c) 2014-2020 Teambition
  9088. * Licensed under the MIT license.
  9089. */
  9090. const PassThrough = stream__default['default'].PassThrough;
  9091. const slice = Array.prototype.slice;
  9092. var merge2_1 = merge2;
  9093. function merge2() {
  9094. const streamsQueue = [];
  9095. const args = slice.call(arguments);
  9096. let merging = false;
  9097. let options = args[args.length - 1];
  9098. if (options && !Array.isArray(options) && options.pipe == null) {
  9099. args.pop();
  9100. } else {
  9101. options = {};
  9102. }
  9103. const doEnd = options.end !== false;
  9104. const doPipeError = options.pipeError === true;
  9105. if (options.objectMode == null) {
  9106. options.objectMode = true;
  9107. }
  9108. if (options.highWaterMark == null) {
  9109. options.highWaterMark = 64 * 1024;
  9110. }
  9111. const mergedStream = PassThrough(options);
  9112. function addStream() {
  9113. for (let i = 0, len = arguments.length; i < len; i++) {
  9114. streamsQueue.push(pauseStreams(arguments[i], options));
  9115. }
  9116. mergeStream();
  9117. return this;
  9118. }
  9119. function mergeStream() {
  9120. if (merging) {
  9121. return;
  9122. }
  9123. merging = true;
  9124. let streams = streamsQueue.shift();
  9125. if (!streams) {
  9126. process.nextTick(endStream);
  9127. return;
  9128. }
  9129. if (!Array.isArray(streams)) {
  9130. streams = [streams];
  9131. }
  9132. let pipesCount = streams.length + 1;
  9133. function next() {
  9134. if (--pipesCount > 0) {
  9135. return;
  9136. }
  9137. merging = false;
  9138. mergeStream();
  9139. }
  9140. function pipe(stream) {
  9141. function onend() {
  9142. stream.removeListener('merge2UnpipeEnd', onend);
  9143. stream.removeListener('end', onend);
  9144. if (doPipeError) {
  9145. stream.removeListener('error', onerror);
  9146. }
  9147. next();
  9148. }
  9149. function onerror(err) {
  9150. mergedStream.emit('error', err);
  9151. } // skip ended stream
  9152. if (stream._readableState.endEmitted) {
  9153. return next();
  9154. }
  9155. stream.on('merge2UnpipeEnd', onend);
  9156. stream.on('end', onend);
  9157. if (doPipeError) {
  9158. stream.on('error', onerror);
  9159. }
  9160. stream.pipe(mergedStream, {
  9161. end: false
  9162. }); // compatible for old stream
  9163. stream.resume();
  9164. }
  9165. for (let i = 0; i < streams.length; i++) {
  9166. pipe(streams[i]);
  9167. }
  9168. next();
  9169. }
  9170. function endStream() {
  9171. merging = false; // emit 'queueDrain' when all streams merged.
  9172. mergedStream.emit('queueDrain');
  9173. if (doEnd) {
  9174. mergedStream.end();
  9175. }
  9176. }
  9177. mergedStream.setMaxListeners(0);
  9178. mergedStream.add = addStream;
  9179. mergedStream.on('unpipe', function (stream) {
  9180. stream.emit('merge2UnpipeEnd');
  9181. });
  9182. if (args.length) {
  9183. addStream.apply(null, args);
  9184. }
  9185. return mergedStream;
  9186. } // check and pause streams for pipe.
  9187. function pauseStreams(streams, options) {
  9188. if (!Array.isArray(streams)) {
  9189. // Backwards-compat with old-style streams
  9190. if (!streams._readableState && streams.pipe) {
  9191. streams = streams.pipe(PassThrough(options));
  9192. }
  9193. if (!streams._readableState || !streams.pause || !streams.pipe) {
  9194. throw new Error('Only readable stream can be merged.');
  9195. }
  9196. streams.pause();
  9197. } else {
  9198. for (let i = 0, len = streams.length; i < len; i++) {
  9199. streams[i] = pauseStreams(streams[i], options);
  9200. }
  9201. }
  9202. return streams;
  9203. }
  9204. var stream = createCommonjsModule(function (module, exports) {
  9205. Object.defineProperty(exports, "__esModule", {
  9206. value: true
  9207. });
  9208. exports.merge = void 0;
  9209. function merge(streams) {
  9210. const mergedStream = merge2_1(streams);
  9211. streams.forEach(stream => {
  9212. stream.once('error', error => mergedStream.emit('error', error));
  9213. });
  9214. mergedStream.once('close', () => propagateCloseEventToSources(streams));
  9215. mergedStream.once('end', () => propagateCloseEventToSources(streams));
  9216. return mergedStream;
  9217. }
  9218. exports.merge = merge;
  9219. function propagateCloseEventToSources(streams) {
  9220. streams.forEach(stream => stream.emit('close'));
  9221. }
  9222. });
  9223. var string = createCommonjsModule(function (module, exports) {
  9224. Object.defineProperty(exports, "__esModule", {
  9225. value: true
  9226. });
  9227. exports.isEmpty = exports.isString = void 0;
  9228. function isString(input) {
  9229. return typeof input === 'string';
  9230. }
  9231. exports.isString = isString;
  9232. function isEmpty(input) {
  9233. return input === '';
  9234. }
  9235. exports.isEmpty = isEmpty;
  9236. });
  9237. var utils$2 = createCommonjsModule(function (module, exports) {
  9238. Object.defineProperty(exports, "__esModule", {
  9239. value: true
  9240. });
  9241. exports.string = exports.stream = exports.pattern = exports.path = exports.fs = exports.errno = exports.array = void 0;
  9242. exports.array = array;
  9243. exports.errno = errno;
  9244. exports.fs = fs;
  9245. exports.path = path_1;
  9246. exports.pattern = pattern;
  9247. exports.stream = stream;
  9248. exports.string = string;
  9249. });
  9250. var tasks = createCommonjsModule(function (module, exports) {
  9251. Object.defineProperty(exports, "__esModule", {
  9252. value: true
  9253. });
  9254. exports.convertPatternGroupToTask = exports.convertPatternGroupsToTasks = exports.groupPatternsByBaseDirectory = exports.getNegativePatternsAsPositive = exports.getPositivePatterns = exports.convertPatternsToTasks = exports.generate = void 0;
  9255. function generate(patterns, settings) {
  9256. const positivePatterns = getPositivePatterns(patterns);
  9257. const negativePatterns = getNegativePatternsAsPositive(patterns, settings.ignore);
  9258. const staticPatterns = positivePatterns.filter(pattern => utils$2.pattern.isStaticPattern(pattern, settings));
  9259. const dynamicPatterns = positivePatterns.filter(pattern => utils$2.pattern.isDynamicPattern(pattern, settings));
  9260. const staticTasks = convertPatternsToTasks(staticPatterns, negativePatterns,
  9261. /* dynamic */
  9262. false);
  9263. const dynamicTasks = convertPatternsToTasks(dynamicPatterns, negativePatterns,
  9264. /* dynamic */
  9265. true);
  9266. return staticTasks.concat(dynamicTasks);
  9267. }
  9268. exports.generate = generate;
  9269. function convertPatternsToTasks(positive, negative, dynamic) {
  9270. const positivePatternsGroup = groupPatternsByBaseDirectory(positive); // When we have a global group – there is no reason to divide the patterns into independent tasks.
  9271. // In this case, the global task covers the rest.
  9272. if ('.' in positivePatternsGroup) {
  9273. const task = convertPatternGroupToTask('.', positive, negative, dynamic);
  9274. return [task];
  9275. }
  9276. return convertPatternGroupsToTasks(positivePatternsGroup, negative, dynamic);
  9277. }
  9278. exports.convertPatternsToTasks = convertPatternsToTasks;
  9279. function getPositivePatterns(patterns) {
  9280. return utils$2.pattern.getPositivePatterns(patterns);
  9281. }
  9282. exports.getPositivePatterns = getPositivePatterns;
  9283. function getNegativePatternsAsPositive(patterns, ignore) {
  9284. const negative = utils$2.pattern.getNegativePatterns(patterns).concat(ignore);
  9285. const positive = negative.map(utils$2.pattern.convertToPositivePattern);
  9286. return positive;
  9287. }
  9288. exports.getNegativePatternsAsPositive = getNegativePatternsAsPositive;
  9289. function groupPatternsByBaseDirectory(patterns) {
  9290. const group = {};
  9291. return patterns.reduce((collection, pattern) => {
  9292. const base = utils$2.pattern.getBaseDirectory(pattern);
  9293. if (base in collection) {
  9294. collection[base].push(pattern);
  9295. } else {
  9296. collection[base] = [pattern];
  9297. }
  9298. return collection;
  9299. }, group);
  9300. }
  9301. exports.groupPatternsByBaseDirectory = groupPatternsByBaseDirectory;
  9302. function convertPatternGroupsToTasks(positive, negative, dynamic) {
  9303. return Object.keys(positive).map(base => {
  9304. return convertPatternGroupToTask(base, positive[base], negative, dynamic);
  9305. });
  9306. }
  9307. exports.convertPatternGroupsToTasks = convertPatternGroupsToTasks;
  9308. function convertPatternGroupToTask(base, positive, negative, dynamic) {
  9309. return {
  9310. dynamic,
  9311. positive,
  9312. negative,
  9313. base,
  9314. patterns: [].concat(positive, negative.map(utils$2.pattern.convertToNegativePattern))
  9315. };
  9316. }
  9317. exports.convertPatternGroupToTask = convertPatternGroupToTask;
  9318. });
  9319. var async = createCommonjsModule(function (module, exports) {
  9320. Object.defineProperty(exports, "__esModule", {
  9321. value: true
  9322. });
  9323. function read(path, settings, callback) {
  9324. settings.fs.lstat(path, (lstatError, lstat) => {
  9325. if (lstatError !== null) {
  9326. return callFailureCallback(callback, lstatError);
  9327. }
  9328. if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) {
  9329. return callSuccessCallback(callback, lstat);
  9330. }
  9331. settings.fs.stat(path, (statError, stat) => {
  9332. if (statError !== null) {
  9333. if (settings.throwErrorOnBrokenSymbolicLink) {
  9334. return callFailureCallback(callback, statError);
  9335. }
  9336. return callSuccessCallback(callback, lstat);
  9337. }
  9338. if (settings.markSymbolicLink) {
  9339. stat.isSymbolicLink = () => true;
  9340. }
  9341. callSuccessCallback(callback, stat);
  9342. });
  9343. });
  9344. }
  9345. exports.read = read;
  9346. function callFailureCallback(callback, error) {
  9347. callback(error);
  9348. }
  9349. function callSuccessCallback(callback, result) {
  9350. callback(null, result);
  9351. }
  9352. });
  9353. var sync = createCommonjsModule(function (module, exports) {
  9354. Object.defineProperty(exports, "__esModule", {
  9355. value: true
  9356. });
  9357. function read(path, settings) {
  9358. const lstat = settings.fs.lstatSync(path);
  9359. if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) {
  9360. return lstat;
  9361. }
  9362. try {
  9363. const stat = settings.fs.statSync(path);
  9364. if (settings.markSymbolicLink) {
  9365. stat.isSymbolicLink = () => true;
  9366. }
  9367. return stat;
  9368. } catch (error) {
  9369. if (!settings.throwErrorOnBrokenSymbolicLink) {
  9370. return lstat;
  9371. }
  9372. throw error;
  9373. }
  9374. }
  9375. exports.read = read;
  9376. });
  9377. var fs_1 = createCommonjsModule(function (module, exports) {
  9378. Object.defineProperty(exports, "__esModule", {
  9379. value: true
  9380. });
  9381. exports.FILE_SYSTEM_ADAPTER = {
  9382. lstat: fs__default['default'].lstat,
  9383. stat: fs__default['default'].stat,
  9384. lstatSync: fs__default['default'].lstatSync,
  9385. statSync: fs__default['default'].statSync
  9386. };
  9387. function createFileSystemAdapter(fsMethods) {
  9388. if (fsMethods === undefined) {
  9389. return exports.FILE_SYSTEM_ADAPTER;
  9390. }
  9391. return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods);
  9392. }
  9393. exports.createFileSystemAdapter = createFileSystemAdapter;
  9394. });
  9395. var settings = createCommonjsModule(function (module, exports) {
  9396. Object.defineProperty(exports, "__esModule", {
  9397. value: true
  9398. });
  9399. class Settings {
  9400. constructor(_options = {}) {
  9401. this._options = _options;
  9402. this.followSymbolicLink = this._getValue(this._options.followSymbolicLink, true);
  9403. this.fs = fs_1.createFileSystemAdapter(this._options.fs);
  9404. this.markSymbolicLink = this._getValue(this._options.markSymbolicLink, false);
  9405. this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true);
  9406. }
  9407. _getValue(option, value) {
  9408. return option === undefined ? value : option;
  9409. }
  9410. }
  9411. exports.default = Settings;
  9412. });
  9413. var out = createCommonjsModule(function (module, exports) {
  9414. Object.defineProperty(exports, "__esModule", {
  9415. value: true
  9416. });
  9417. exports.Settings = settings.default;
  9418. function stat(path, optionsOrSettingsOrCallback, callback) {
  9419. if (typeof optionsOrSettingsOrCallback === 'function') {
  9420. return async.read(path, getSettings(), optionsOrSettingsOrCallback);
  9421. }
  9422. async.read(path, getSettings(optionsOrSettingsOrCallback), callback);
  9423. }
  9424. exports.stat = stat;
  9425. function statSync(path, optionsOrSettings) {
  9426. const settings = getSettings(optionsOrSettings);
  9427. return sync.read(path, settings);
  9428. }
  9429. exports.statSync = statSync;
  9430. function getSettings(settingsOrOptions = {}) {
  9431. if (settingsOrOptions instanceof settings.default) {
  9432. return settingsOrOptions;
  9433. }
  9434. return new settings.default(settingsOrOptions);
  9435. }
  9436. });
  9437. var runParallel_1 = runParallel;
  9438. function runParallel(tasks, cb) {
  9439. var results, pending, keys;
  9440. var isSync = true;
  9441. if (Array.isArray(tasks)) {
  9442. results = [];
  9443. pending = tasks.length;
  9444. } else {
  9445. keys = Object.keys(tasks);
  9446. results = {};
  9447. pending = keys.length;
  9448. }
  9449. function done(err) {
  9450. function end() {
  9451. if (cb) cb(err, results);
  9452. cb = null;
  9453. }
  9454. if (isSync) process.nextTick(end);else end();
  9455. }
  9456. function each(i, err, result) {
  9457. results[i] = result;
  9458. if (--pending === 0 || err) {
  9459. done(err);
  9460. }
  9461. }
  9462. if (!pending) {
  9463. // empty
  9464. done(null);
  9465. } else if (keys) {
  9466. // object
  9467. keys.forEach(function (key) {
  9468. tasks[key](function (err, result) {
  9469. each(key, err, result);
  9470. });
  9471. });
  9472. } else {
  9473. // array
  9474. tasks.forEach(function (task, i) {
  9475. task(function (err, result) {
  9476. each(i, err, result);
  9477. });
  9478. });
  9479. }
  9480. isSync = false;
  9481. }
  9482. var constants$2 = createCommonjsModule(function (module, exports) {
  9483. Object.defineProperty(exports, "__esModule", {
  9484. value: true
  9485. });
  9486. const NODE_PROCESS_VERSION_PARTS = process.versions.node.split('.');
  9487. const MAJOR_VERSION = parseInt(NODE_PROCESS_VERSION_PARTS[0], 10);
  9488. const MINOR_VERSION = parseInt(NODE_PROCESS_VERSION_PARTS[1], 10);
  9489. const SUPPORTED_MAJOR_VERSION = 10;
  9490. const SUPPORTED_MINOR_VERSION = 10;
  9491. const IS_MATCHED_BY_MAJOR = MAJOR_VERSION > SUPPORTED_MAJOR_VERSION;
  9492. const IS_MATCHED_BY_MAJOR_AND_MINOR = MAJOR_VERSION === SUPPORTED_MAJOR_VERSION && MINOR_VERSION >= SUPPORTED_MINOR_VERSION;
  9493. /**
  9494. * IS `true` for Node.js 10.10 and greater.
  9495. */
  9496. exports.IS_SUPPORT_READDIR_WITH_FILE_TYPES = IS_MATCHED_BY_MAJOR || IS_MATCHED_BY_MAJOR_AND_MINOR;
  9497. });
  9498. var fs$1 = createCommonjsModule(function (module, exports) {
  9499. Object.defineProperty(exports, "__esModule", {
  9500. value: true
  9501. });
  9502. class DirentFromStats {
  9503. constructor(name, stats) {
  9504. this.name = name;
  9505. this.isBlockDevice = stats.isBlockDevice.bind(stats);
  9506. this.isCharacterDevice = stats.isCharacterDevice.bind(stats);
  9507. this.isDirectory = stats.isDirectory.bind(stats);
  9508. this.isFIFO = stats.isFIFO.bind(stats);
  9509. this.isFile = stats.isFile.bind(stats);
  9510. this.isSocket = stats.isSocket.bind(stats);
  9511. this.isSymbolicLink = stats.isSymbolicLink.bind(stats);
  9512. }
  9513. }
  9514. function createDirentFromStats(name, stats) {
  9515. return new DirentFromStats(name, stats);
  9516. }
  9517. exports.createDirentFromStats = createDirentFromStats;
  9518. });
  9519. var utils$3 = createCommonjsModule(function (module, exports) {
  9520. Object.defineProperty(exports, "__esModule", {
  9521. value: true
  9522. });
  9523. exports.fs = fs$1;
  9524. });
  9525. var async$1 = createCommonjsModule(function (module, exports) {
  9526. Object.defineProperty(exports, "__esModule", {
  9527. value: true
  9528. });
  9529. function read(directory, settings, callback) {
  9530. if (!settings.stats && constants$2.IS_SUPPORT_READDIR_WITH_FILE_TYPES) {
  9531. return readdirWithFileTypes(directory, settings, callback);
  9532. }
  9533. return readdir(directory, settings, callback);
  9534. }
  9535. exports.read = read;
  9536. function readdirWithFileTypes(directory, settings, callback) {
  9537. settings.fs.readdir(directory, {
  9538. withFileTypes: true
  9539. }, (readdirError, dirents) => {
  9540. if (readdirError !== null) {
  9541. return callFailureCallback(callback, readdirError);
  9542. }
  9543. const entries = dirents.map(dirent => ({
  9544. dirent,
  9545. name: dirent.name,
  9546. path: `${directory}${settings.pathSegmentSeparator}${dirent.name}`
  9547. }));
  9548. if (!settings.followSymbolicLinks) {
  9549. return callSuccessCallback(callback, entries);
  9550. }
  9551. const tasks = entries.map(entry => makeRplTaskEntry(entry, settings));
  9552. runParallel_1(tasks, (rplError, rplEntries) => {
  9553. if (rplError !== null) {
  9554. return callFailureCallback(callback, rplError);
  9555. }
  9556. callSuccessCallback(callback, rplEntries);
  9557. });
  9558. });
  9559. }
  9560. exports.readdirWithFileTypes = readdirWithFileTypes;
  9561. function makeRplTaskEntry(entry, settings) {
  9562. return done => {
  9563. if (!entry.dirent.isSymbolicLink()) {
  9564. return done(null, entry);
  9565. }
  9566. settings.fs.stat(entry.path, (statError, stats) => {
  9567. if (statError !== null) {
  9568. if (settings.throwErrorOnBrokenSymbolicLink) {
  9569. return done(statError);
  9570. }
  9571. return done(null, entry);
  9572. }
  9573. entry.dirent = utils$3.fs.createDirentFromStats(entry.name, stats);
  9574. return done(null, entry);
  9575. });
  9576. };
  9577. }
  9578. function readdir(directory, settings, callback) {
  9579. settings.fs.readdir(directory, (readdirError, names) => {
  9580. if (readdirError !== null) {
  9581. return callFailureCallback(callback, readdirError);
  9582. }
  9583. const filepaths = names.map(name => `${directory}${settings.pathSegmentSeparator}${name}`);
  9584. const tasks = filepaths.map(filepath => {
  9585. return done => out.stat(filepath, settings.fsStatSettings, done);
  9586. });
  9587. runParallel_1(tasks, (rplError, results) => {
  9588. if (rplError !== null) {
  9589. return callFailureCallback(callback, rplError);
  9590. }
  9591. const entries = [];
  9592. names.forEach((name, index) => {
  9593. const stats = results[index];
  9594. const entry = {
  9595. name,
  9596. path: filepaths[index],
  9597. dirent: utils$3.fs.createDirentFromStats(name, stats)
  9598. };
  9599. if (settings.stats) {
  9600. entry.stats = stats;
  9601. }
  9602. entries.push(entry);
  9603. });
  9604. callSuccessCallback(callback, entries);
  9605. });
  9606. });
  9607. }
  9608. exports.readdir = readdir;
  9609. function callFailureCallback(callback, error) {
  9610. callback(error);
  9611. }
  9612. function callSuccessCallback(callback, result) {
  9613. callback(null, result);
  9614. }
  9615. });
  9616. var sync$1 = createCommonjsModule(function (module, exports) {
  9617. Object.defineProperty(exports, "__esModule", {
  9618. value: true
  9619. });
  9620. function read(directory, settings) {
  9621. if (!settings.stats && constants$2.IS_SUPPORT_READDIR_WITH_FILE_TYPES) {
  9622. return readdirWithFileTypes(directory, settings);
  9623. }
  9624. return readdir(directory, settings);
  9625. }
  9626. exports.read = read;
  9627. function readdirWithFileTypes(directory, settings) {
  9628. const dirents = settings.fs.readdirSync(directory, {
  9629. withFileTypes: true
  9630. });
  9631. return dirents.map(dirent => {
  9632. const entry = {
  9633. dirent,
  9634. name: dirent.name,
  9635. path: `${directory}${settings.pathSegmentSeparator}${dirent.name}`
  9636. };
  9637. if (entry.dirent.isSymbolicLink() && settings.followSymbolicLinks) {
  9638. try {
  9639. const stats = settings.fs.statSync(entry.path);
  9640. entry.dirent = utils$3.fs.createDirentFromStats(entry.name, stats);
  9641. } catch (error) {
  9642. if (settings.throwErrorOnBrokenSymbolicLink) {
  9643. throw error;
  9644. }
  9645. }
  9646. }
  9647. return entry;
  9648. });
  9649. }
  9650. exports.readdirWithFileTypes = readdirWithFileTypes;
  9651. function readdir(directory, settings) {
  9652. const names = settings.fs.readdirSync(directory);
  9653. return names.map(name => {
  9654. const entryPath = `${directory}${settings.pathSegmentSeparator}${name}`;
  9655. const stats = out.statSync(entryPath, settings.fsStatSettings);
  9656. const entry = {
  9657. name,
  9658. path: entryPath,
  9659. dirent: utils$3.fs.createDirentFromStats(name, stats)
  9660. };
  9661. if (settings.stats) {
  9662. entry.stats = stats;
  9663. }
  9664. return entry;
  9665. });
  9666. }
  9667. exports.readdir = readdir;
  9668. });
  9669. var fs_1$1 = createCommonjsModule(function (module, exports) {
  9670. Object.defineProperty(exports, "__esModule", {
  9671. value: true
  9672. });
  9673. exports.FILE_SYSTEM_ADAPTER = {
  9674. lstat: fs__default['default'].lstat,
  9675. stat: fs__default['default'].stat,
  9676. lstatSync: fs__default['default'].lstatSync,
  9677. statSync: fs__default['default'].statSync,
  9678. readdir: fs__default['default'].readdir,
  9679. readdirSync: fs__default['default'].readdirSync
  9680. };
  9681. function createFileSystemAdapter(fsMethods) {
  9682. if (fsMethods === undefined) {
  9683. return exports.FILE_SYSTEM_ADAPTER;
  9684. }
  9685. return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods);
  9686. }
  9687. exports.createFileSystemAdapter = createFileSystemAdapter;
  9688. });
  9689. var settings$1 = createCommonjsModule(function (module, exports) {
  9690. Object.defineProperty(exports, "__esModule", {
  9691. value: true
  9692. });
  9693. class Settings {
  9694. constructor(_options = {}) {
  9695. this._options = _options;
  9696. this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, false);
  9697. this.fs = fs_1$1.createFileSystemAdapter(this._options.fs);
  9698. this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path__default['default'].sep);
  9699. this.stats = this._getValue(this._options.stats, false);
  9700. this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true);
  9701. this.fsStatSettings = new out.Settings({
  9702. followSymbolicLink: this.followSymbolicLinks,
  9703. fs: this.fs,
  9704. throwErrorOnBrokenSymbolicLink: this.throwErrorOnBrokenSymbolicLink
  9705. });
  9706. }
  9707. _getValue(option, value) {
  9708. return option === undefined ? value : option;
  9709. }
  9710. }
  9711. exports.default = Settings;
  9712. });
  9713. var out$1 = createCommonjsModule(function (module, exports) {
  9714. Object.defineProperty(exports, "__esModule", {
  9715. value: true
  9716. });
  9717. exports.Settings = settings$1.default;
  9718. function scandir(path, optionsOrSettingsOrCallback, callback) {
  9719. if (typeof optionsOrSettingsOrCallback === 'function') {
  9720. return async$1.read(path, getSettings(), optionsOrSettingsOrCallback);
  9721. }
  9722. async$1.read(path, getSettings(optionsOrSettingsOrCallback), callback);
  9723. }
  9724. exports.scandir = scandir;
  9725. function scandirSync(path, optionsOrSettings) {
  9726. const settings = getSettings(optionsOrSettings);
  9727. return sync$1.read(path, settings);
  9728. }
  9729. exports.scandirSync = scandirSync;
  9730. function getSettings(settingsOrOptions = {}) {
  9731. if (settingsOrOptions instanceof settings$1.default) {
  9732. return settingsOrOptions;
  9733. }
  9734. return new settings$1.default(settingsOrOptions);
  9735. }
  9736. });
  9737. function reusify(Constructor) {
  9738. var head = new Constructor();
  9739. var tail = head;
  9740. function get() {
  9741. var current = head;
  9742. if (current.next) {
  9743. head = current.next;
  9744. } else {
  9745. head = new Constructor();
  9746. tail = head;
  9747. }
  9748. current.next = null;
  9749. return current;
  9750. }
  9751. function release(obj) {
  9752. tail.next = obj;
  9753. tail = obj;
  9754. }
  9755. return {
  9756. get: get,
  9757. release: release
  9758. };
  9759. }
  9760. var reusify_1 = reusify;
  9761. function fastqueue(context, worker, concurrency) {
  9762. if (typeof context === 'function') {
  9763. concurrency = worker;
  9764. worker = context;
  9765. context = null;
  9766. }
  9767. var cache = reusify_1(Task);
  9768. var queueHead = null;
  9769. var queueTail = null;
  9770. var _running = 0;
  9771. var self = {
  9772. push: push,
  9773. drain: noop,
  9774. saturated: noop,
  9775. pause: pause,
  9776. paused: false,
  9777. concurrency: concurrency,
  9778. running: running,
  9779. resume: resume,
  9780. idle: idle,
  9781. length: length,
  9782. getQueue: getQueue,
  9783. unshift: unshift,
  9784. empty: noop,
  9785. kill: kill,
  9786. killAndDrain: killAndDrain
  9787. };
  9788. return self;
  9789. function running() {
  9790. return _running;
  9791. }
  9792. function pause() {
  9793. self.paused = true;
  9794. }
  9795. function length() {
  9796. var current = queueHead;
  9797. var counter = 0;
  9798. while (current) {
  9799. current = current.next;
  9800. counter++;
  9801. }
  9802. return counter;
  9803. }
  9804. function getQueue() {
  9805. var current = queueHead;
  9806. var tasks = [];
  9807. while (current) {
  9808. tasks.push(current.value);
  9809. current = current.next;
  9810. }
  9811. return tasks;
  9812. }
  9813. function resume() {
  9814. if (!self.paused) return;
  9815. self.paused = false;
  9816. for (var i = 0; i < self.concurrency; i++) {
  9817. _running++;
  9818. release();
  9819. }
  9820. }
  9821. function idle() {
  9822. return _running === 0 && self.length() === 0;
  9823. }
  9824. function push(value, done) {
  9825. var current = cache.get();
  9826. current.context = context;
  9827. current.release = release;
  9828. current.value = value;
  9829. current.callback = done || noop;
  9830. if (_running === self.concurrency || self.paused) {
  9831. if (queueTail) {
  9832. queueTail.next = current;
  9833. queueTail = current;
  9834. } else {
  9835. queueHead = current;
  9836. queueTail = current;
  9837. self.saturated();
  9838. }
  9839. } else {
  9840. _running++;
  9841. worker.call(context, current.value, current.worked);
  9842. }
  9843. }
  9844. function unshift(value, done) {
  9845. var current = cache.get();
  9846. current.context = context;
  9847. current.release = release;
  9848. current.value = value;
  9849. current.callback = done || noop;
  9850. if (_running === self.concurrency || self.paused) {
  9851. if (queueHead) {
  9852. current.next = queueHead;
  9853. queueHead = current;
  9854. } else {
  9855. queueHead = current;
  9856. queueTail = current;
  9857. self.saturated();
  9858. }
  9859. } else {
  9860. _running++;
  9861. worker.call(context, current.value, current.worked);
  9862. }
  9863. }
  9864. function release(holder) {
  9865. if (holder) {
  9866. cache.release(holder);
  9867. }
  9868. var next = queueHead;
  9869. if (next) {
  9870. if (!self.paused) {
  9871. if (queueTail === queueHead) {
  9872. queueTail = null;
  9873. }
  9874. queueHead = next.next;
  9875. next.next = null;
  9876. worker.call(context, next.value, next.worked);
  9877. if (queueTail === null) {
  9878. self.empty();
  9879. }
  9880. } else {
  9881. _running--;
  9882. }
  9883. } else if (--_running === 0) {
  9884. self.drain();
  9885. }
  9886. }
  9887. function kill() {
  9888. queueHead = null;
  9889. queueTail = null;
  9890. self.drain = noop;
  9891. }
  9892. function killAndDrain() {
  9893. queueHead = null;
  9894. queueTail = null;
  9895. self.drain();
  9896. self.drain = noop;
  9897. }
  9898. }
  9899. function noop() {}
  9900. function Task() {
  9901. this.value = null;
  9902. this.callback = noop;
  9903. this.next = null;
  9904. this.release = noop;
  9905. this.context = null;
  9906. var self = this;
  9907. this.worked = function worked(err, result) {
  9908. var callback = self.callback;
  9909. self.value = null;
  9910. self.callback = noop;
  9911. callback.call(self.context, err, result);
  9912. self.release(self);
  9913. };
  9914. }
  9915. var queue = fastqueue;
  9916. var common = createCommonjsModule(function (module, exports) {
  9917. Object.defineProperty(exports, "__esModule", {
  9918. value: true
  9919. });
  9920. function isFatalError(settings, error) {
  9921. if (settings.errorFilter === null) {
  9922. return true;
  9923. }
  9924. return !settings.errorFilter(error);
  9925. }
  9926. exports.isFatalError = isFatalError;
  9927. function isAppliedFilter(filter, value) {
  9928. return filter === null || filter(value);
  9929. }
  9930. exports.isAppliedFilter = isAppliedFilter;
  9931. function replacePathSegmentSeparator(filepath, separator) {
  9932. return filepath.split(/[\\/]/).join(separator);
  9933. }
  9934. exports.replacePathSegmentSeparator = replacePathSegmentSeparator;
  9935. function joinPathSegments(a, b, separator) {
  9936. if (a === '') {
  9937. return b;
  9938. }
  9939. return a + separator + b;
  9940. }
  9941. exports.joinPathSegments = joinPathSegments;
  9942. });
  9943. var reader = createCommonjsModule(function (module, exports) {
  9944. Object.defineProperty(exports, "__esModule", {
  9945. value: true
  9946. });
  9947. class Reader {
  9948. constructor(_root, _settings) {
  9949. this._root = _root;
  9950. this._settings = _settings;
  9951. this._root = common.replacePathSegmentSeparator(_root, _settings.pathSegmentSeparator);
  9952. }
  9953. }
  9954. exports.default = Reader;
  9955. });
  9956. var async$2 = createCommonjsModule(function (module, exports) {
  9957. Object.defineProperty(exports, "__esModule", {
  9958. value: true
  9959. });
  9960. class AsyncReader extends reader.default {
  9961. constructor(_root, _settings) {
  9962. super(_root, _settings);
  9963. this._settings = _settings;
  9964. this._scandir = out$1.scandir;
  9965. this._emitter = new events__default['default'].EventEmitter();
  9966. this._queue = queue(this._worker.bind(this), this._settings.concurrency);
  9967. this._isFatalError = false;
  9968. this._isDestroyed = false;
  9969. this._queue.drain = () => {
  9970. if (!this._isFatalError) {
  9971. this._emitter.emit('end');
  9972. }
  9973. };
  9974. }
  9975. read() {
  9976. this._isFatalError = false;
  9977. this._isDestroyed = false;
  9978. setImmediate(() => {
  9979. this._pushToQueue(this._root, this._settings.basePath);
  9980. });
  9981. return this._emitter;
  9982. }
  9983. destroy() {
  9984. if (this._isDestroyed) {
  9985. throw new Error('The reader is already destroyed');
  9986. }
  9987. this._isDestroyed = true;
  9988. this._queue.killAndDrain();
  9989. }
  9990. onEntry(callback) {
  9991. this._emitter.on('entry', callback);
  9992. }
  9993. onError(callback) {
  9994. this._emitter.once('error', callback);
  9995. }
  9996. onEnd(callback) {
  9997. this._emitter.once('end', callback);
  9998. }
  9999. _pushToQueue(directory, base) {
  10000. const queueItem = {
  10001. directory,
  10002. base
  10003. };
  10004. this._queue.push(queueItem, error => {
  10005. if (error !== null) {
  10006. this._handleError(error);
  10007. }
  10008. });
  10009. }
  10010. _worker(item, done) {
  10011. this._scandir(item.directory, this._settings.fsScandirSettings, (error, entries) => {
  10012. if (error !== null) {
  10013. return done(error, undefined);
  10014. }
  10015. for (const entry of entries) {
  10016. this._handleEntry(entry, item.base);
  10017. }
  10018. done(null, undefined);
  10019. });
  10020. }
  10021. _handleError(error) {
  10022. if (!common.isFatalError(this._settings, error)) {
  10023. return;
  10024. }
  10025. this._isFatalError = true;
  10026. this._isDestroyed = true;
  10027. this._emitter.emit('error', error);
  10028. }
  10029. _handleEntry(entry, base) {
  10030. if (this._isDestroyed || this._isFatalError) {
  10031. return;
  10032. }
  10033. const fullpath = entry.path;
  10034. if (base !== undefined) {
  10035. entry.path = common.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator);
  10036. }
  10037. if (common.isAppliedFilter(this._settings.entryFilter, entry)) {
  10038. this._emitEntry(entry);
  10039. }
  10040. if (entry.dirent.isDirectory() && common.isAppliedFilter(this._settings.deepFilter, entry)) {
  10041. this._pushToQueue(fullpath, entry.path);
  10042. }
  10043. }
  10044. _emitEntry(entry) {
  10045. this._emitter.emit('entry', entry);
  10046. }
  10047. }
  10048. exports.default = AsyncReader;
  10049. });
  10050. var async$3 = createCommonjsModule(function (module, exports) {
  10051. Object.defineProperty(exports, "__esModule", {
  10052. value: true
  10053. });
  10054. class AsyncProvider {
  10055. constructor(_root, _settings) {
  10056. this._root = _root;
  10057. this._settings = _settings;
  10058. this._reader = new async$2.default(this._root, this._settings);
  10059. this._storage = new Set();
  10060. }
  10061. read(callback) {
  10062. this._reader.onError(error => {
  10063. callFailureCallback(callback, error);
  10064. });
  10065. this._reader.onEntry(entry => {
  10066. this._storage.add(entry);
  10067. });
  10068. this._reader.onEnd(() => {
  10069. callSuccessCallback(callback, [...this._storage]);
  10070. });
  10071. this._reader.read();
  10072. }
  10073. }
  10074. exports.default = AsyncProvider;
  10075. function callFailureCallback(callback, error) {
  10076. callback(error);
  10077. }
  10078. function callSuccessCallback(callback, entries) {
  10079. callback(null, entries);
  10080. }
  10081. });
  10082. var stream$1 = createCommonjsModule(function (module, exports) {
  10083. Object.defineProperty(exports, "__esModule", {
  10084. value: true
  10085. });
  10086. class StreamProvider {
  10087. constructor(_root, _settings) {
  10088. this._root = _root;
  10089. this._settings = _settings;
  10090. this._reader = new async$2.default(this._root, this._settings);
  10091. this._stream = new stream__default['default'].Readable({
  10092. objectMode: true,
  10093. read: () => {},
  10094. destroy: this._reader.destroy.bind(this._reader)
  10095. });
  10096. }
  10097. read() {
  10098. this._reader.onError(error => {
  10099. this._stream.emit('error', error);
  10100. });
  10101. this._reader.onEntry(entry => {
  10102. this._stream.push(entry);
  10103. });
  10104. this._reader.onEnd(() => {
  10105. this._stream.push(null);
  10106. });
  10107. this._reader.read();
  10108. return this._stream;
  10109. }
  10110. }
  10111. exports.default = StreamProvider;
  10112. });
  10113. var sync$2 = createCommonjsModule(function (module, exports) {
  10114. Object.defineProperty(exports, "__esModule", {
  10115. value: true
  10116. });
  10117. class SyncReader extends reader.default {
  10118. constructor() {
  10119. super(...arguments);
  10120. this._scandir = out$1.scandirSync;
  10121. this._storage = new Set();
  10122. this._queue = new Set();
  10123. }
  10124. read() {
  10125. this._pushToQueue(this._root, this._settings.basePath);
  10126. this._handleQueue();
  10127. return [...this._storage];
  10128. }
  10129. _pushToQueue(directory, base) {
  10130. this._queue.add({
  10131. directory,
  10132. base
  10133. });
  10134. }
  10135. _handleQueue() {
  10136. for (const item of this._queue.values()) {
  10137. this._handleDirectory(item.directory, item.base);
  10138. }
  10139. }
  10140. _handleDirectory(directory, base) {
  10141. try {
  10142. const entries = this._scandir(directory, this._settings.fsScandirSettings);
  10143. for (const entry of entries) {
  10144. this._handleEntry(entry, base);
  10145. }
  10146. } catch (error) {
  10147. this._handleError(error);
  10148. }
  10149. }
  10150. _handleError(error) {
  10151. if (!common.isFatalError(this._settings, error)) {
  10152. return;
  10153. }
  10154. throw error;
  10155. }
  10156. _handleEntry(entry, base) {
  10157. const fullpath = entry.path;
  10158. if (base !== undefined) {
  10159. entry.path = common.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator);
  10160. }
  10161. if (common.isAppliedFilter(this._settings.entryFilter, entry)) {
  10162. this._pushToStorage(entry);
  10163. }
  10164. if (entry.dirent.isDirectory() && common.isAppliedFilter(this._settings.deepFilter, entry)) {
  10165. this._pushToQueue(fullpath, entry.path);
  10166. }
  10167. }
  10168. _pushToStorage(entry) {
  10169. this._storage.add(entry);
  10170. }
  10171. }
  10172. exports.default = SyncReader;
  10173. });
  10174. var sync$3 = createCommonjsModule(function (module, exports) {
  10175. Object.defineProperty(exports, "__esModule", {
  10176. value: true
  10177. });
  10178. class SyncProvider {
  10179. constructor(_root, _settings) {
  10180. this._root = _root;
  10181. this._settings = _settings;
  10182. this._reader = new sync$2.default(this._root, this._settings);
  10183. }
  10184. read() {
  10185. return this._reader.read();
  10186. }
  10187. }
  10188. exports.default = SyncProvider;
  10189. });
  10190. var settings$2 = createCommonjsModule(function (module, exports) {
  10191. Object.defineProperty(exports, "__esModule", {
  10192. value: true
  10193. });
  10194. class Settings {
  10195. constructor(_options = {}) {
  10196. this._options = _options;
  10197. this.basePath = this._getValue(this._options.basePath, undefined);
  10198. this.concurrency = this._getValue(this._options.concurrency, Infinity);
  10199. this.deepFilter = this._getValue(this._options.deepFilter, null);
  10200. this.entryFilter = this._getValue(this._options.entryFilter, null);
  10201. this.errorFilter = this._getValue(this._options.errorFilter, null);
  10202. this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path__default['default'].sep);
  10203. this.fsScandirSettings = new out$1.Settings({
  10204. followSymbolicLinks: this._options.followSymbolicLinks,
  10205. fs: this._options.fs,
  10206. pathSegmentSeparator: this._options.pathSegmentSeparator,
  10207. stats: this._options.stats,
  10208. throwErrorOnBrokenSymbolicLink: this._options.throwErrorOnBrokenSymbolicLink
  10209. });
  10210. }
  10211. _getValue(option, value) {
  10212. return option === undefined ? value : option;
  10213. }
  10214. }
  10215. exports.default = Settings;
  10216. });
  10217. var out$2 = createCommonjsModule(function (module, exports) {
  10218. Object.defineProperty(exports, "__esModule", {
  10219. value: true
  10220. });
  10221. exports.Settings = settings$2.default;
  10222. function walk(directory, optionsOrSettingsOrCallback, callback) {
  10223. if (typeof optionsOrSettingsOrCallback === 'function') {
  10224. return new async$3.default(directory, getSettings()).read(optionsOrSettingsOrCallback);
  10225. }
  10226. new async$3.default(directory, getSettings(optionsOrSettingsOrCallback)).read(callback);
  10227. }
  10228. exports.walk = walk;
  10229. function walkSync(directory, optionsOrSettings) {
  10230. const settings = getSettings(optionsOrSettings);
  10231. const provider = new sync$3.default(directory, settings);
  10232. return provider.read();
  10233. }
  10234. exports.walkSync = walkSync;
  10235. function walkStream(directory, optionsOrSettings) {
  10236. const settings = getSettings(optionsOrSettings);
  10237. const provider = new stream$1.default(directory, settings);
  10238. return provider.read();
  10239. }
  10240. exports.walkStream = walkStream;
  10241. function getSettings(settingsOrOptions = {}) {
  10242. if (settingsOrOptions instanceof settings$2.default) {
  10243. return settingsOrOptions;
  10244. }
  10245. return new settings$2.default(settingsOrOptions);
  10246. }
  10247. });
  10248. var reader$1 = createCommonjsModule(function (module, exports) {
  10249. Object.defineProperty(exports, "__esModule", {
  10250. value: true
  10251. });
  10252. class Reader {
  10253. constructor(_settings) {
  10254. this._settings = _settings;
  10255. this._fsStatSettings = new out.Settings({
  10256. followSymbolicLink: this._settings.followSymbolicLinks,
  10257. fs: this._settings.fs,
  10258. throwErrorOnBrokenSymbolicLink: this._settings.followSymbolicLinks
  10259. });
  10260. }
  10261. _getFullEntryPath(filepath) {
  10262. return path__default['default'].resolve(this._settings.cwd, filepath);
  10263. }
  10264. _makeEntry(stats, pattern) {
  10265. const entry = {
  10266. name: pattern,
  10267. path: pattern,
  10268. dirent: utils$2.fs.createDirentFromStats(pattern, stats)
  10269. };
  10270. if (this._settings.stats) {
  10271. entry.stats = stats;
  10272. }
  10273. return entry;
  10274. }
  10275. _isFatalError(error) {
  10276. return !utils$2.errno.isEnoentCodeError(error) && !this._settings.suppressErrors;
  10277. }
  10278. }
  10279. exports.default = Reader;
  10280. });
  10281. var stream$2 = createCommonjsModule(function (module, exports) {
  10282. Object.defineProperty(exports, "__esModule", {
  10283. value: true
  10284. });
  10285. class ReaderStream extends reader$1.default {
  10286. constructor() {
  10287. super(...arguments);
  10288. this._walkStream = out$2.walkStream;
  10289. this._stat = out.stat;
  10290. }
  10291. dynamic(root, options) {
  10292. return this._walkStream(root, options);
  10293. }
  10294. static(patterns, options) {
  10295. const filepaths = patterns.map(this._getFullEntryPath, this);
  10296. const stream = new stream__default['default'].PassThrough({
  10297. objectMode: true
  10298. });
  10299. stream._write = (index, _enc, done) => {
  10300. return this._getEntry(filepaths[index], patterns[index], options).then(entry => {
  10301. if (entry !== null && options.entryFilter(entry)) {
  10302. stream.push(entry);
  10303. }
  10304. if (index === filepaths.length - 1) {
  10305. stream.end();
  10306. }
  10307. done();
  10308. }).catch(done);
  10309. };
  10310. for (let i = 0; i < filepaths.length; i++) {
  10311. stream.write(i);
  10312. }
  10313. return stream;
  10314. }
  10315. _getEntry(filepath, pattern, options) {
  10316. return this._getStat(filepath).then(stats => this._makeEntry(stats, pattern)).catch(error => {
  10317. if (options.errorFilter(error)) {
  10318. return null;
  10319. }
  10320. throw error;
  10321. });
  10322. }
  10323. _getStat(filepath) {
  10324. return new Promise((resolve, reject) => {
  10325. this._stat(filepath, this._fsStatSettings, (error, stats) => {
  10326. return error === null ? resolve(stats) : reject(error);
  10327. });
  10328. });
  10329. }
  10330. }
  10331. exports.default = ReaderStream;
  10332. });
  10333. var matcher = createCommonjsModule(function (module, exports) {
  10334. Object.defineProperty(exports, "__esModule", {
  10335. value: true
  10336. });
  10337. class Matcher {
  10338. constructor(_patterns, _settings, _micromatchOptions) {
  10339. this._patterns = _patterns;
  10340. this._settings = _settings;
  10341. this._micromatchOptions = _micromatchOptions;
  10342. this._storage = [];
  10343. this._fillStorage();
  10344. }
  10345. _fillStorage() {
  10346. /**
  10347. * The original pattern may include `{,*,**,a/*}`, which will lead to problems with matching (unresolved level).
  10348. * So, before expand patterns with brace expansion into separated patterns.
  10349. */
  10350. const patterns = utils$2.pattern.expandPatternsWithBraceExpansion(this._patterns);
  10351. for (const pattern of patterns) {
  10352. const segments = this._getPatternSegments(pattern);
  10353. const sections = this._splitSegmentsIntoSections(segments);
  10354. this._storage.push({
  10355. complete: sections.length <= 1,
  10356. pattern,
  10357. segments,
  10358. sections
  10359. });
  10360. }
  10361. }
  10362. _getPatternSegments(pattern) {
  10363. const parts = utils$2.pattern.getPatternParts(pattern, this._micromatchOptions);
  10364. return parts.map(part => {
  10365. const dynamic = utils$2.pattern.isDynamicPattern(part, this._settings);
  10366. if (!dynamic) {
  10367. return {
  10368. dynamic: false,
  10369. pattern: part
  10370. };
  10371. }
  10372. return {
  10373. dynamic: true,
  10374. pattern: part,
  10375. patternRe: utils$2.pattern.makeRe(part, this._micromatchOptions)
  10376. };
  10377. });
  10378. }
  10379. _splitSegmentsIntoSections(segments) {
  10380. return utils$2.array.splitWhen(segments, segment => segment.dynamic && utils$2.pattern.hasGlobStar(segment.pattern));
  10381. }
  10382. }
  10383. exports.default = Matcher;
  10384. });
  10385. var partial = createCommonjsModule(function (module, exports) {
  10386. Object.defineProperty(exports, "__esModule", {
  10387. value: true
  10388. });
  10389. class PartialMatcher extends matcher.default {
  10390. match(filepath) {
  10391. const parts = filepath.split('/');
  10392. const levels = parts.length;
  10393. const patterns = this._storage.filter(info => !info.complete || info.segments.length > levels);
  10394. for (const pattern of patterns) {
  10395. const section = pattern.sections[0];
  10396. /**
  10397. * In this case, the pattern has a globstar and we must read all directories unconditionally,
  10398. * but only if the level has reached the end of the first group.
  10399. *
  10400. * fixtures/{a,b}/**
  10401. * ^ true/false ^ always true
  10402. */
  10403. if (!pattern.complete && levels > section.length) {
  10404. return true;
  10405. }
  10406. const match = parts.every((part, index) => {
  10407. const segment = pattern.segments[index];
  10408. if (segment.dynamic && segment.patternRe.test(part)) {
  10409. return true;
  10410. }
  10411. if (!segment.dynamic && segment.pattern === part) {
  10412. return true;
  10413. }
  10414. return false;
  10415. });
  10416. if (match) {
  10417. return true;
  10418. }
  10419. }
  10420. return false;
  10421. }
  10422. }
  10423. exports.default = PartialMatcher;
  10424. });
  10425. var deep = createCommonjsModule(function (module, exports) {
  10426. Object.defineProperty(exports, "__esModule", {
  10427. value: true
  10428. });
  10429. class DeepFilter {
  10430. constructor(_settings, _micromatchOptions) {
  10431. this._settings = _settings;
  10432. this._micromatchOptions = _micromatchOptions;
  10433. }
  10434. getFilter(basePath, positive, negative) {
  10435. const matcher = this._getMatcher(positive);
  10436. const negativeRe = this._getNegativePatternsRe(negative);
  10437. return entry => this._filter(basePath, entry, matcher, negativeRe);
  10438. }
  10439. _getMatcher(patterns) {
  10440. return new partial.default(patterns, this._settings, this._micromatchOptions);
  10441. }
  10442. _getNegativePatternsRe(patterns) {
  10443. const affectDepthOfReadingPatterns = patterns.filter(utils$2.pattern.isAffectDepthOfReadingPattern);
  10444. return utils$2.pattern.convertPatternsToRe(affectDepthOfReadingPatterns, this._micromatchOptions);
  10445. }
  10446. _filter(basePath, entry, matcher, negativeRe) {
  10447. if (this._isSkippedByDeep(basePath, entry.path)) {
  10448. return false;
  10449. }
  10450. if (this._isSkippedSymbolicLink(entry)) {
  10451. return false;
  10452. }
  10453. const filepath = utils$2.path.removeLeadingDotSegment(entry.path);
  10454. if (this._isSkippedByPositivePatterns(filepath, matcher)) {
  10455. return false;
  10456. }
  10457. return this._isSkippedByNegativePatterns(filepath, negativeRe);
  10458. }
  10459. _isSkippedByDeep(basePath, entryPath) {
  10460. /**
  10461. * Avoid unnecessary depth calculations when it doesn't matter.
  10462. */
  10463. if (this._settings.deep === Infinity) {
  10464. return false;
  10465. }
  10466. return this._getEntryLevel(basePath, entryPath) >= this._settings.deep;
  10467. }
  10468. _getEntryLevel(basePath, entryPath) {
  10469. const entryPathDepth = entryPath.split('/').length;
  10470. if (basePath === '') {
  10471. return entryPathDepth;
  10472. }
  10473. const basePathDepth = basePath.split('/').length;
  10474. return entryPathDepth - basePathDepth;
  10475. }
  10476. _isSkippedSymbolicLink(entry) {
  10477. return !this._settings.followSymbolicLinks && entry.dirent.isSymbolicLink();
  10478. }
  10479. _isSkippedByPositivePatterns(entryPath, matcher) {
  10480. return !this._settings.baseNameMatch && !matcher.match(entryPath);
  10481. }
  10482. _isSkippedByNegativePatterns(entryPath, patternsRe) {
  10483. return !utils$2.pattern.matchAny(entryPath, patternsRe);
  10484. }
  10485. }
  10486. exports.default = DeepFilter;
  10487. });
  10488. var entry = createCommonjsModule(function (module, exports) {
  10489. Object.defineProperty(exports, "__esModule", {
  10490. value: true
  10491. });
  10492. class EntryFilter {
  10493. constructor(_settings, _micromatchOptions) {
  10494. this._settings = _settings;
  10495. this._micromatchOptions = _micromatchOptions;
  10496. this.index = new Map();
  10497. }
  10498. getFilter(positive, negative) {
  10499. const positiveRe = utils$2.pattern.convertPatternsToRe(positive, this._micromatchOptions);
  10500. const negativeRe = utils$2.pattern.convertPatternsToRe(negative, this._micromatchOptions);
  10501. return entry => this._filter(entry, positiveRe, negativeRe);
  10502. }
  10503. _filter(entry, positiveRe, negativeRe) {
  10504. if (this._settings.unique && this._isDuplicateEntry(entry)) {
  10505. return false;
  10506. }
  10507. if (this._onlyFileFilter(entry) || this._onlyDirectoryFilter(entry)) {
  10508. return false;
  10509. }
  10510. if (this._isSkippedByAbsoluteNegativePatterns(entry.path, negativeRe)) {
  10511. return false;
  10512. }
  10513. const filepath = this._settings.baseNameMatch ? entry.name : entry.path;
  10514. const isMatched = this._isMatchToPatterns(filepath, positiveRe) && !this._isMatchToPatterns(entry.path, negativeRe);
  10515. if (this._settings.unique && isMatched) {
  10516. this._createIndexRecord(entry);
  10517. }
  10518. return isMatched;
  10519. }
  10520. _isDuplicateEntry(entry) {
  10521. return this.index.has(entry.path);
  10522. }
  10523. _createIndexRecord(entry) {
  10524. this.index.set(entry.path, undefined);
  10525. }
  10526. _onlyFileFilter(entry) {
  10527. return this._settings.onlyFiles && !entry.dirent.isFile();
  10528. }
  10529. _onlyDirectoryFilter(entry) {
  10530. return this._settings.onlyDirectories && !entry.dirent.isDirectory();
  10531. }
  10532. _isSkippedByAbsoluteNegativePatterns(entryPath, patternsRe) {
  10533. if (!this._settings.absolute) {
  10534. return false;
  10535. }
  10536. const fullpath = utils$2.path.makeAbsolute(this._settings.cwd, entryPath);
  10537. return utils$2.pattern.matchAny(fullpath, patternsRe);
  10538. }
  10539. _isMatchToPatterns(entryPath, patternsRe) {
  10540. const filepath = utils$2.path.removeLeadingDotSegment(entryPath);
  10541. return utils$2.pattern.matchAny(filepath, patternsRe);
  10542. }
  10543. }
  10544. exports.default = EntryFilter;
  10545. });
  10546. var error = createCommonjsModule(function (module, exports) {
  10547. Object.defineProperty(exports, "__esModule", {
  10548. value: true
  10549. });
  10550. class ErrorFilter {
  10551. constructor(_settings) {
  10552. this._settings = _settings;
  10553. }
  10554. getFilter() {
  10555. return error => this._isNonFatalError(error);
  10556. }
  10557. _isNonFatalError(error) {
  10558. return utils$2.errno.isEnoentCodeError(error) || this._settings.suppressErrors;
  10559. }
  10560. }
  10561. exports.default = ErrorFilter;
  10562. });
  10563. var entry$1 = createCommonjsModule(function (module, exports) {
  10564. Object.defineProperty(exports, "__esModule", {
  10565. value: true
  10566. });
  10567. class EntryTransformer {
  10568. constructor(_settings) {
  10569. this._settings = _settings;
  10570. }
  10571. getTransformer() {
  10572. return entry => this._transform(entry);
  10573. }
  10574. _transform(entry) {
  10575. let filepath = entry.path;
  10576. if (this._settings.absolute) {
  10577. filepath = utils$2.path.makeAbsolute(this._settings.cwd, filepath);
  10578. filepath = utils$2.path.unixify(filepath);
  10579. }
  10580. if (this._settings.markDirectories && entry.dirent.isDirectory()) {
  10581. filepath += '/';
  10582. }
  10583. if (!this._settings.objectMode) {
  10584. return filepath;
  10585. }
  10586. return Object.assign(Object.assign({}, entry), {
  10587. path: filepath
  10588. });
  10589. }
  10590. }
  10591. exports.default = EntryTransformer;
  10592. });
  10593. var provider = createCommonjsModule(function (module, exports) {
  10594. Object.defineProperty(exports, "__esModule", {
  10595. value: true
  10596. });
  10597. class Provider {
  10598. constructor(_settings) {
  10599. this._settings = _settings;
  10600. this.errorFilter = new error.default(this._settings);
  10601. this.entryFilter = new entry.default(this._settings, this._getMicromatchOptions());
  10602. this.deepFilter = new deep.default(this._settings, this._getMicromatchOptions());
  10603. this.entryTransformer = new entry$1.default(this._settings);
  10604. }
  10605. _getRootDirectory(task) {
  10606. return path__default['default'].resolve(this._settings.cwd, task.base);
  10607. }
  10608. _getReaderOptions(task) {
  10609. const basePath = task.base === '.' ? '' : task.base;
  10610. return {
  10611. basePath,
  10612. pathSegmentSeparator: '/',
  10613. concurrency: this._settings.concurrency,
  10614. deepFilter: this.deepFilter.getFilter(basePath, task.positive, task.negative),
  10615. entryFilter: this.entryFilter.getFilter(task.positive, task.negative),
  10616. errorFilter: this.errorFilter.getFilter(),
  10617. followSymbolicLinks: this._settings.followSymbolicLinks,
  10618. fs: this._settings.fs,
  10619. stats: this._settings.stats,
  10620. throwErrorOnBrokenSymbolicLink: this._settings.throwErrorOnBrokenSymbolicLink,
  10621. transform: this.entryTransformer.getTransformer()
  10622. };
  10623. }
  10624. _getMicromatchOptions() {
  10625. return {
  10626. dot: this._settings.dot,
  10627. matchBase: this._settings.baseNameMatch,
  10628. nobrace: !this._settings.braceExpansion,
  10629. nocase: !this._settings.caseSensitiveMatch,
  10630. noext: !this._settings.extglob,
  10631. noglobstar: !this._settings.globstar,
  10632. posix: true,
  10633. strictSlashes: false
  10634. };
  10635. }
  10636. }
  10637. exports.default = Provider;
  10638. });
  10639. var async$4 = createCommonjsModule(function (module, exports) {
  10640. Object.defineProperty(exports, "__esModule", {
  10641. value: true
  10642. });
  10643. class ProviderAsync extends provider.default {
  10644. constructor() {
  10645. super(...arguments);
  10646. this._reader = new stream$2.default(this._settings);
  10647. }
  10648. read(task) {
  10649. const root = this._getRootDirectory(task);
  10650. const options = this._getReaderOptions(task);
  10651. const entries = [];
  10652. return new Promise((resolve, reject) => {
  10653. const stream = this.api(root, task, options);
  10654. stream.once('error', reject);
  10655. stream.on('data', entry => entries.push(options.transform(entry)));
  10656. stream.once('end', () => resolve(entries));
  10657. });
  10658. }
  10659. api(root, task, options) {
  10660. if (task.dynamic) {
  10661. return this._reader.dynamic(root, options);
  10662. }
  10663. return this._reader.static(task.patterns, options);
  10664. }
  10665. }
  10666. exports.default = ProviderAsync;
  10667. });
  10668. var stream$3 = createCommonjsModule(function (module, exports) {
  10669. Object.defineProperty(exports, "__esModule", {
  10670. value: true
  10671. });
  10672. class ProviderStream extends provider.default {
  10673. constructor() {
  10674. super(...arguments);
  10675. this._reader = new stream$2.default(this._settings);
  10676. }
  10677. read(task) {
  10678. const root = this._getRootDirectory(task);
  10679. const options = this._getReaderOptions(task);
  10680. const source = this.api(root, task, options);
  10681. const destination = new stream__default['default'].Readable({
  10682. objectMode: true,
  10683. read: () => {}
  10684. });
  10685. source.once('error', error => destination.emit('error', error)).on('data', entry => destination.emit('data', options.transform(entry))).once('end', () => destination.emit('end'));
  10686. destination.once('close', () => source.destroy());
  10687. return destination;
  10688. }
  10689. api(root, task, options) {
  10690. if (task.dynamic) {
  10691. return this._reader.dynamic(root, options);
  10692. }
  10693. return this._reader.static(task.patterns, options);
  10694. }
  10695. }
  10696. exports.default = ProviderStream;
  10697. });
  10698. var sync$4 = createCommonjsModule(function (module, exports) {
  10699. Object.defineProperty(exports, "__esModule", {
  10700. value: true
  10701. });
  10702. class ReaderSync extends reader$1.default {
  10703. constructor() {
  10704. super(...arguments);
  10705. this._walkSync = out$2.walkSync;
  10706. this._statSync = out.statSync;
  10707. }
  10708. dynamic(root, options) {
  10709. return this._walkSync(root, options);
  10710. }
  10711. static(patterns, options) {
  10712. const entries = [];
  10713. for (const pattern of patterns) {
  10714. const filepath = this._getFullEntryPath(pattern);
  10715. const entry = this._getEntry(filepath, pattern, options);
  10716. if (entry === null || !options.entryFilter(entry)) {
  10717. continue;
  10718. }
  10719. entries.push(entry);
  10720. }
  10721. return entries;
  10722. }
  10723. _getEntry(filepath, pattern, options) {
  10724. try {
  10725. const stats = this._getStat(filepath);
  10726. return this._makeEntry(stats, pattern);
  10727. } catch (error) {
  10728. if (options.errorFilter(error)) {
  10729. return null;
  10730. }
  10731. throw error;
  10732. }
  10733. }
  10734. _getStat(filepath) {
  10735. return this._statSync(filepath, this._fsStatSettings);
  10736. }
  10737. }
  10738. exports.default = ReaderSync;
  10739. });
  10740. var sync$5 = createCommonjsModule(function (module, exports) {
  10741. Object.defineProperty(exports, "__esModule", {
  10742. value: true
  10743. });
  10744. class ProviderSync extends provider.default {
  10745. constructor() {
  10746. super(...arguments);
  10747. this._reader = new sync$4.default(this._settings);
  10748. }
  10749. read(task) {
  10750. const root = this._getRootDirectory(task);
  10751. const options = this._getReaderOptions(task);
  10752. const entries = this.api(root, task, options);
  10753. return entries.map(options.transform);
  10754. }
  10755. api(root, task, options) {
  10756. if (task.dynamic) {
  10757. return this._reader.dynamic(root, options);
  10758. }
  10759. return this._reader.static(task.patterns, options);
  10760. }
  10761. }
  10762. exports.default = ProviderSync;
  10763. });
  10764. var settings$3 = createCommonjsModule(function (module, exports) {
  10765. Object.defineProperty(exports, "__esModule", {
  10766. value: true
  10767. });
  10768. exports.DEFAULT_FILE_SYSTEM_ADAPTER = void 0;
  10769. const CPU_COUNT = os__default['default'].cpus().length;
  10770. exports.DEFAULT_FILE_SYSTEM_ADAPTER = {
  10771. lstat: fs__default['default'].lstat,
  10772. lstatSync: fs__default['default'].lstatSync,
  10773. stat: fs__default['default'].stat,
  10774. statSync: fs__default['default'].statSync,
  10775. readdir: fs__default['default'].readdir,
  10776. readdirSync: fs__default['default'].readdirSync
  10777. };
  10778. class Settings {
  10779. constructor(_options = {}) {
  10780. this._options = _options;
  10781. this.absolute = this._getValue(this._options.absolute, false);
  10782. this.baseNameMatch = this._getValue(this._options.baseNameMatch, false);
  10783. this.braceExpansion = this._getValue(this._options.braceExpansion, true);
  10784. this.caseSensitiveMatch = this._getValue(this._options.caseSensitiveMatch, true);
  10785. this.concurrency = this._getValue(this._options.concurrency, CPU_COUNT);
  10786. this.cwd = this._getValue(this._options.cwd, process.cwd());
  10787. this.deep = this._getValue(this._options.deep, Infinity);
  10788. this.dot = this._getValue(this._options.dot, false);
  10789. this.extglob = this._getValue(this._options.extglob, true);
  10790. this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, true);
  10791. this.fs = this._getFileSystemMethods(this._options.fs);
  10792. this.globstar = this._getValue(this._options.globstar, true);
  10793. this.ignore = this._getValue(this._options.ignore, []);
  10794. this.markDirectories = this._getValue(this._options.markDirectories, false);
  10795. this.objectMode = this._getValue(this._options.objectMode, false);
  10796. this.onlyDirectories = this._getValue(this._options.onlyDirectories, false);
  10797. this.onlyFiles = this._getValue(this._options.onlyFiles, true);
  10798. this.stats = this._getValue(this._options.stats, false);
  10799. this.suppressErrors = this._getValue(this._options.suppressErrors, false);
  10800. this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, false);
  10801. this.unique = this._getValue(this._options.unique, true);
  10802. if (this.onlyDirectories) {
  10803. this.onlyFiles = false;
  10804. }
  10805. if (this.stats) {
  10806. this.objectMode = true;
  10807. }
  10808. }
  10809. _getValue(option, value) {
  10810. return option === undefined ? value : option;
  10811. }
  10812. _getFileSystemMethods(methods = {}) {
  10813. return Object.assign(Object.assign({}, exports.DEFAULT_FILE_SYSTEM_ADAPTER), methods);
  10814. }
  10815. }
  10816. exports.default = Settings;
  10817. });
  10818. async function FastGlob(source, options) {
  10819. assertPatternsInput(source);
  10820. const works = getWorks(source, async$4.default, options);
  10821. const result = await Promise.all(works);
  10822. return utils$2.array.flatten(result);
  10823. } // https://github.com/typescript-eslint/typescript-eslint/issues/60
  10824. // eslint-disable-next-line no-redeclare
  10825. (function (FastGlob) {
  10826. function sync(source, options) {
  10827. assertPatternsInput(source);
  10828. const works = getWorks(source, sync$5.default, options);
  10829. return utils$2.array.flatten(works);
  10830. }
  10831. FastGlob.sync = sync;
  10832. function stream(source, options) {
  10833. assertPatternsInput(source);
  10834. const works = getWorks(source, stream$3.default, options);
  10835. /**
  10836. * The stream returned by the provider cannot work with an asynchronous iterator.
  10837. * To support asynchronous iterators, regardless of the number of tasks, we always multiplex streams.
  10838. * This affects performance (+25%). I don't see best solution right now.
  10839. */
  10840. return utils$2.stream.merge(works);
  10841. }
  10842. FastGlob.stream = stream;
  10843. function generateTasks(source, options) {
  10844. assertPatternsInput(source);
  10845. const patterns = [].concat(source);
  10846. const settings = new settings$3.default(options);
  10847. return tasks.generate(patterns, settings);
  10848. }
  10849. FastGlob.generateTasks = generateTasks;
  10850. function isDynamicPattern(source, options) {
  10851. assertPatternsInput(source);
  10852. const settings = new settings$3.default(options);
  10853. return utils$2.pattern.isDynamicPattern(source, settings);
  10854. }
  10855. FastGlob.isDynamicPattern = isDynamicPattern;
  10856. function escapePath(source) {
  10857. assertPatternsInput(source);
  10858. return utils$2.path.escape(source);
  10859. }
  10860. FastGlob.escapePath = escapePath;
  10861. })(FastGlob || (FastGlob = {}));
  10862. function getWorks(source, _Provider, options) {
  10863. const patterns = [].concat(source);
  10864. const settings = new settings$3.default(options);
  10865. const tasks$1 = tasks.generate(patterns, settings);
  10866. const provider = new _Provider(settings);
  10867. return tasks$1.map(provider.read, provider);
  10868. }
  10869. function assertPatternsInput(input) {
  10870. const source = [].concat(input);
  10871. const isValidSource = source.every(item => utils$2.string.isString(item) && !utils$2.string.isEmpty(item));
  10872. if (!isValidSource) {
  10873. throw new TypeError('Patterns must be a string (non empty) or an array of strings');
  10874. }
  10875. }
  10876. var out$3 = FastGlob;
  10877. /** @typedef {import('./util').Context} Context */
  10878. /**
  10879. * @param {Context} context
  10880. */
  10881. function* expandPatterns(context) {
  10882. const cwd = process.cwd();
  10883. const seen = new Set();
  10884. let noResults = true;
  10885. for (const pathOrError of expandPatternsInternal(context)) {
  10886. noResults = false;
  10887. if (typeof pathOrError !== "string") {
  10888. yield pathOrError;
  10889. continue;
  10890. }
  10891. const relativePath = path__default['default'].relative(cwd, pathOrError); // filter out duplicates
  10892. if (seen.has(relativePath)) {
  10893. continue;
  10894. }
  10895. seen.add(relativePath);
  10896. yield relativePath;
  10897. }
  10898. if (noResults) {
  10899. // If there was no files and no other errors, let's yield a general error.
  10900. yield {
  10901. error: `No matching files. Patterns: ${context.filePatterns.join(" ")}`
  10902. };
  10903. }
  10904. }
  10905. /**
  10906. * @param {Context} context
  10907. */
  10908. function* expandPatternsInternal(context) {
  10909. // Ignores files in version control systems directories and `node_modules`
  10910. const silentlyIgnoredDirs = {
  10911. ".git": true,
  10912. ".svn": true,
  10913. ".hg": true,
  10914. node_modules: context.argv["with-node-modules"] !== true
  10915. };
  10916. const globOptions = {
  10917. dot: true,
  10918. ignore: Object.keys(silentlyIgnoredDirs).filter(dir => silentlyIgnoredDirs[dir]).map(dir => "**/" + dir)
  10919. };
  10920. let supportedFilesGlob;
  10921. const cwd = process.cwd();
  10922. /** @type {Array<{ type: 'file' | 'dir' | 'glob'; glob: string; input: string; }>} */
  10923. const entries = [];
  10924. for (const pattern of context.filePatterns) {
  10925. const absolutePath = path__default['default'].resolve(cwd, pattern);
  10926. if (containsIgnoredPathSegment(absolutePath, cwd, silentlyIgnoredDirs)) {
  10927. continue;
  10928. }
  10929. const stat = statSafeSync(absolutePath);
  10930. if (stat) {
  10931. if (stat.isFile()) {
  10932. entries.push({
  10933. type: "file",
  10934. glob: escapePathForGlob(fixWindowsSlashes(pattern)),
  10935. input: pattern
  10936. });
  10937. } else if (stat.isDirectory()) {
  10938. entries.push({
  10939. type: "dir",
  10940. glob: escapePathForGlob(fixWindowsSlashes(pattern)) + "/" + getSupportedFilesGlob(),
  10941. input: pattern
  10942. });
  10943. }
  10944. } else if (pattern[0] === "!") {
  10945. // convert negative patterns to `ignore` entries
  10946. globOptions.ignore.push(fixWindowsSlashes(pattern.slice(1)));
  10947. } else {
  10948. entries.push({
  10949. type: "glob",
  10950. glob: fixWindowsSlashes(pattern),
  10951. input: pattern
  10952. });
  10953. }
  10954. }
  10955. for (const {
  10956. type,
  10957. glob,
  10958. input
  10959. } of entries) {
  10960. let result;
  10961. try {
  10962. result = out$3.sync(glob, globOptions);
  10963. } catch ({
  10964. message
  10965. }) {
  10966. /* istanbul ignore next */
  10967. yield {
  10968. error: `${errorMessages.globError[type]}: ${input}\n${message}`
  10969. };
  10970. /* istanbul ignore next */
  10971. continue;
  10972. }
  10973. if (result.length === 0) {
  10974. yield {
  10975. error: `${errorMessages.emptyResults[type]}: "${input}".`
  10976. };
  10977. } else {
  10978. yield* sortPaths(result);
  10979. }
  10980. }
  10981. function getSupportedFilesGlob() {
  10982. if (!supportedFilesGlob) {
  10983. const extensions = flatten_1(context.languages.map(lang => lang.extensions || []));
  10984. const filenames = flatten_1(context.languages.map(lang => lang.filenames || []));
  10985. supportedFilesGlob = `**/{${extensions.map(ext => "*" + (ext[0] === "." ? ext : "." + ext)).concat(filenames)}}`;
  10986. }
  10987. return supportedFilesGlob;
  10988. }
  10989. }
  10990. const errorMessages = {
  10991. globError: {
  10992. file: "Unable to resolve file",
  10993. dir: "Unable to expand directory",
  10994. glob: "Unable to expand glob pattern"
  10995. },
  10996. emptyResults: {
  10997. file: "Explicitly specified file was ignored due to negative glob patterns",
  10998. dir: "No supported files were found in the directory",
  10999. glob: "No files matching the pattern were found"
  11000. }
  11001. };
  11002. /**
  11003. * @param {string} absolutePath
  11004. * @param {string} cwd
  11005. * @param {Record<string, boolean>} ignoredDirectories
  11006. */
  11007. function containsIgnoredPathSegment(absolutePath, cwd, ignoredDirectories) {
  11008. return path__default['default'].relative(cwd, absolutePath).split(path__default['default'].sep).some(dir => ignoredDirectories[dir]);
  11009. }
  11010. /**
  11011. * @param {string[]} paths
  11012. */
  11013. function sortPaths(paths) {
  11014. return paths.sort((a, b) => a.localeCompare(b));
  11015. }
  11016. /**
  11017. * Get stats of a given path.
  11018. * @param {string} filePath The path to target file.
  11019. * @returns {fs.Stats | undefined} The stats.
  11020. */
  11021. function statSafeSync(filePath) {
  11022. try {
  11023. return fs__default['default'].statSync(filePath);
  11024. } catch (error) {
  11025. /* istanbul ignore next */
  11026. if (error.code !== "ENOENT") {
  11027. throw error;
  11028. }
  11029. }
  11030. }
  11031. /**
  11032. * This function should be replaced with `fastGlob.escapePath` when these issues are fixed:
  11033. * - https://github.com/mrmlnc/fast-glob/issues/261
  11034. * - https://github.com/mrmlnc/fast-glob/issues/262
  11035. * @param {string} path
  11036. */
  11037. function escapePathForGlob(path) {
  11038. return out$3.escapePath(path.replace(/\\/g, "\0") // Workaround for fast-glob#262 (part 1)
  11039. ).replace(/\\!/g, "@(!)") // Workaround for fast-glob#261
  11040. .replace(/\0/g, "@(\\\\)"); // Workaround for fast-glob#262 (part 2)
  11041. }
  11042. const isWindows = path__default['default'].sep === "\\";
  11043. /**
  11044. * Using backslashes in globs is probably not okay, but not accepting
  11045. * backslashes as path separators on Windows is even more not okay.
  11046. * https://github.com/prettier/prettier/pull/6776#discussion_r380723717
  11047. * https://github.com/mrmlnc/fast-glob#how-to-write-patterns-on-windows
  11048. * @param {string} pattern
  11049. */
  11050. function fixWindowsSlashes(pattern) {
  11051. return isWindows ? pattern.replace(/\\/g, "/") : pattern;
  11052. }
  11053. var expandPatterns_1 = {
  11054. expandPatterns,
  11055. fixWindowsSlashes
  11056. };
  11057. var lib = createCommonjsModule(function (module, exports) {
  11058. Object.defineProperty(exports, "__esModule", {
  11059. value: true
  11060. }); // In the absence of a WeakSet or WeakMap implementation, don't break, but don't cache either.
  11061. function noop() {
  11062. var args = [];
  11063. for (var _i = 0; _i < arguments.length; _i++) {
  11064. args[_i] = arguments[_i];
  11065. }
  11066. }
  11067. function createWeakMap() {
  11068. if (typeof WeakMap !== 'undefined') {
  11069. return new WeakMap();
  11070. } else {
  11071. return fakeSetOrMap();
  11072. }
  11073. }
  11074. /**
  11075. * Creates and returns a no-op implementation of a WeakMap / WeakSet that never stores anything.
  11076. */
  11077. function fakeSetOrMap() {
  11078. return {
  11079. add: noop,
  11080. delete: noop,
  11081. get: noop,
  11082. set: noop,
  11083. has: function (k) {
  11084. return false;
  11085. }
  11086. };
  11087. } // Safe hasOwnProperty
  11088. var hop = Object.prototype.hasOwnProperty;
  11089. var has = function (obj, prop) {
  11090. return hop.call(obj, prop);
  11091. }; // Copy all own enumerable properties from source to target
  11092. function extend(target, source) {
  11093. for (var prop in source) {
  11094. if (has(source, prop)) {
  11095. target[prop] = source[prop];
  11096. }
  11097. }
  11098. return target;
  11099. }
  11100. var reLeadingNewline = /^[ \t]*(?:\r\n|\r|\n)/;
  11101. var reTrailingNewline = /(?:\r\n|\r|\n)[ \t]*$/;
  11102. var reStartsWithNewlineOrIsEmpty = /^(?:[\r\n]|$)/;
  11103. var reDetectIndentation = /(?:\r\n|\r|\n)([ \t]*)(?:[^ \t\r\n]|$)/;
  11104. var reOnlyWhitespaceWithAtLeastOneNewline = /^[ \t]*[\r\n][ \t\r\n]*$/;
  11105. function _outdentArray(strings, firstInterpolatedValueSetsIndentationLevel, options) {
  11106. // If first interpolated value is a reference to outdent,
  11107. // determine indentation level from the indentation of the interpolated value.
  11108. var indentationLevel = 0;
  11109. var match = strings[0].match(reDetectIndentation);
  11110. if (match) {
  11111. indentationLevel = match[1].length;
  11112. }
  11113. var reSource = "(\\r\\n|\\r|\\n).{0," + indentationLevel + "}";
  11114. var reMatchIndent = new RegExp(reSource, 'g');
  11115. if (firstInterpolatedValueSetsIndentationLevel) {
  11116. strings = strings.slice(1);
  11117. }
  11118. var newline = options.newline,
  11119. trimLeadingNewline = options.trimLeadingNewline,
  11120. trimTrailingNewline = options.trimTrailingNewline;
  11121. var normalizeNewlines = typeof newline === 'string';
  11122. var l = strings.length;
  11123. var outdentedStrings = strings.map(function (v, i) {
  11124. // Remove leading indentation from all lines
  11125. v = v.replace(reMatchIndent, '$1'); // Trim a leading newline from the first string
  11126. if (i === 0 && trimLeadingNewline) {
  11127. v = v.replace(reLeadingNewline, '');
  11128. } // Trim a trailing newline from the last string
  11129. if (i === l - 1 && trimTrailingNewline) {
  11130. v = v.replace(reTrailingNewline, '');
  11131. } // Normalize newlines
  11132. if (normalizeNewlines) {
  11133. v = v.replace(/\r\n|\n|\r/g, function (_) {
  11134. return newline;
  11135. });
  11136. }
  11137. return v;
  11138. });
  11139. return outdentedStrings;
  11140. }
  11141. function concatStringsAndValues(strings, values) {
  11142. var ret = '';
  11143. for (var i = 0, l = strings.length; i < l; i++) {
  11144. ret += strings[i];
  11145. if (i < l - 1) {
  11146. ret += values[i];
  11147. }
  11148. }
  11149. return ret;
  11150. }
  11151. function isTemplateStringsArray(v) {
  11152. return has(v, 'raw') && has(v, 'length');
  11153. }
  11154. /**
  11155. * It is assumed that opts will not change. If this is a problem, clone your options object and pass the clone to
  11156. * makeInstance
  11157. * @param options
  11158. * @return {outdent}
  11159. */
  11160. function createInstance(options) {
  11161. /** Cache of pre-processed template literal arrays */
  11162. var arrayAutoIndentCache = createWeakMap();
  11163. /**
  11164. * Cache of pre-processed template literal arrays, where first interpolated value is a reference to outdent,
  11165. * before interpolated values are injected.
  11166. */
  11167. var arrayFirstInterpSetsIndentCache = createWeakMap();
  11168. function outdent(stringsOrOptions) {
  11169. var values = [];
  11170. for (var _i = 1; _i < arguments.length; _i++) {
  11171. values[_i - 1] = arguments[_i];
  11172. }
  11173. /* tslint:enable:no-shadowed-variable */
  11174. if (isTemplateStringsArray(stringsOrOptions)) {
  11175. var strings = stringsOrOptions; // Is first interpolated value a reference to outdent, alone on its own line, without any preceding non-whitespace?
  11176. var firstInterpolatedValueSetsIndentationLevel = (values[0] === outdent || values[0] === defaultOutdent) && reOnlyWhitespaceWithAtLeastOneNewline.test(strings[0]) && reStartsWithNewlineOrIsEmpty.test(strings[1]); // Perform outdentation
  11177. var cache = firstInterpolatedValueSetsIndentationLevel ? arrayFirstInterpSetsIndentCache : arrayAutoIndentCache;
  11178. var renderedArray = cache.get(strings);
  11179. if (!renderedArray) {
  11180. renderedArray = _outdentArray(strings, firstInterpolatedValueSetsIndentationLevel, options);
  11181. cache.set(strings, renderedArray);
  11182. }
  11183. /** If no interpolated values, skip concatenation step */
  11184. if (values.length === 0) {
  11185. return renderedArray[0];
  11186. }
  11187. /** Concatenate string literals with interpolated values */
  11188. var rendered = concatStringsAndValues(renderedArray, firstInterpolatedValueSetsIndentationLevel ? values.slice(1) : values);
  11189. return rendered;
  11190. } else {
  11191. // Create and return a new instance of outdent with the given options
  11192. return createInstance(extend(extend({}, options), stringsOrOptions || {}));
  11193. }
  11194. }
  11195. var fullOutdent = extend(outdent, {
  11196. string: function (str) {
  11197. return _outdentArray([str], false, options)[0];
  11198. }
  11199. });
  11200. return fullOutdent;
  11201. }
  11202. var defaultOutdent = createInstance({
  11203. trimLeadingNewline: true,
  11204. trimTrailingNewline: true
  11205. });
  11206. exports.outdent = defaultOutdent; // Named exports. Simple and preferred.
  11207. // import outdent from 'outdent';
  11208. exports.default = defaultOutdent;
  11209. {
  11210. // In webpack harmony-modules environments, module.exports is read-only,
  11211. // so we fail gracefully.
  11212. try {
  11213. module.exports = defaultOutdent;
  11214. Object.defineProperty(defaultOutdent, '__esModule', {
  11215. value: true
  11216. });
  11217. defaultOutdent.default = defaultOutdent;
  11218. defaultOutdent.outdent = defaultOutdent;
  11219. } catch (e) {}
  11220. }
  11221. });
  11222. const {
  11223. outdent
  11224. } = lib;
  11225. const {
  11226. coreOptions
  11227. } = prettierInternal;
  11228. const categoryOrder = [coreOptions.CATEGORY_OUTPUT, coreOptions.CATEGORY_FORMAT, coreOptions.CATEGORY_CONFIG, coreOptions.CATEGORY_EDITOR, coreOptions.CATEGORY_OTHER];
  11229. /**
  11230. * {
  11231. * [optionName]: {
  11232. * // The type of the option. For 'choice', see also `choices` below.
  11233. * // When passing a type other than the ones listed below, the option is
  11234. * // treated as taking any string as argument, and `--option <${type}>` will
  11235. * // be displayed in --help.
  11236. * type: "boolean" | "choice" | "int" | string;
  11237. *
  11238. * // Default value to be passed to the minimist option `default`.
  11239. * default?: any;
  11240. *
  11241. * // Alias name to be passed to the minimist option `alias`.
  11242. * alias?: string;
  11243. *
  11244. * // For grouping options by category in --help.
  11245. * category?: string;
  11246. *
  11247. * // Description to be displayed in --help. If omitted, the option won't be
  11248. * // shown at all in --help (but see also `oppositeDescription` below).
  11249. * description?: string;
  11250. *
  11251. * // Description for `--no-${name}` to be displayed in --help. If omitted,
  11252. * // `--no-${name}` won't be shown.
  11253. * oppositeDescription?: string;
  11254. *
  11255. * // Indicate if this option is simply passed to the API.
  11256. * // true: use camelified name as the API option name.
  11257. * // string: use this value as the API option name.
  11258. * forwardToApi?: boolean | string;
  11259. *
  11260. * // Indicate that a CLI flag should be an array when forwarded to the API.
  11261. * array?: boolean;
  11262. *
  11263. * // Specify available choices for validation. They will also be displayed
  11264. * // in --help as <a|b|c>.
  11265. * // Use an object instead of a string if a choice is deprecated and should
  11266. * // be treated as `redirect` instead, or if you'd like to add description for
  11267. * // the choice.
  11268. * choices?: Array<
  11269. * | string
  11270. * | { value: string, description?: string, deprecated?: boolean, redirect?: string }
  11271. * >;
  11272. *
  11273. * // If the option has a value that is an exception to the regular value
  11274. * // constraints, indicate that value here (or use a function for more
  11275. * // flexibility).
  11276. * exception?: ((value: any) => boolean);
  11277. *
  11278. * // Indicate that the option is deprecated. Use a string to add an extra
  11279. * // message to --help for the option, for example to suggest a replacement
  11280. * // option.
  11281. * deprecated?: true | string;
  11282. * }
  11283. * }
  11284. *
  11285. * Note: The options below are sorted alphabetically.
  11286. */
  11287. const options = {
  11288. check: {
  11289. type: "boolean",
  11290. category: coreOptions.CATEGORY_OUTPUT,
  11291. alias: "c",
  11292. description: outdent`
  11293. Check if the given files are formatted, print a human-friendly summary
  11294. message and paths to unformatted files (see also --list-different).
  11295. `
  11296. },
  11297. color: {
  11298. // The supports-color package (a sub sub dependency) looks directly at
  11299. // `process.argv` for `--no-color` and such-like options. The reason it is
  11300. // listed here is to avoid "Ignored unknown option: --no-color" warnings.
  11301. // See https://github.com/chalk/supports-color/#info for more information.
  11302. type: "boolean",
  11303. default: true,
  11304. description: "Colorize error messages.",
  11305. oppositeDescription: "Do not colorize error messages."
  11306. },
  11307. config: {
  11308. type: "path",
  11309. category: coreOptions.CATEGORY_CONFIG,
  11310. description: "Path to a Prettier configuration file (.prettierrc, package.json, prettier.config.js).",
  11311. oppositeDescription: "Do not look for a configuration file.",
  11312. exception: value => value === false
  11313. },
  11314. "config-precedence": {
  11315. type: "choice",
  11316. category: coreOptions.CATEGORY_CONFIG,
  11317. default: "cli-override",
  11318. choices: [{
  11319. value: "cli-override",
  11320. description: "CLI options take precedence over config file"
  11321. }, {
  11322. value: "file-override",
  11323. description: "Config file take precedence over CLI options"
  11324. }, {
  11325. value: "prefer-file",
  11326. description: outdent`
  11327. If a config file is found will evaluate it and ignore other CLI options.
  11328. If no config file is found CLI options will evaluate as normal.
  11329. `
  11330. }],
  11331. description: "Define in which order config files and CLI options should be evaluated."
  11332. },
  11333. "debug-benchmark": {
  11334. // Run the formatting benchmarks. Requires 'benchmark' module to be installed.
  11335. type: "boolean"
  11336. },
  11337. "debug-check": {
  11338. // Run the formatting once again on the formatted output, throw if different.
  11339. type: "boolean"
  11340. },
  11341. "debug-print-doc": {
  11342. type: "boolean"
  11343. },
  11344. "debug-repeat": {
  11345. // Repeat the formatting a few times and measure the average duration.
  11346. type: "int",
  11347. default: 0
  11348. },
  11349. editorconfig: {
  11350. type: "boolean",
  11351. category: coreOptions.CATEGORY_CONFIG,
  11352. description: "Take .editorconfig into account when parsing configuration.",
  11353. oppositeDescription: "Don't take .editorconfig into account when parsing configuration.",
  11354. default: true
  11355. },
  11356. "find-config-path": {
  11357. type: "path",
  11358. category: coreOptions.CATEGORY_CONFIG,
  11359. description: "Find and print the path to a configuration file for the given input file."
  11360. },
  11361. "file-info": {
  11362. type: "path",
  11363. description: outdent`
  11364. Extract the following info (as JSON) for a given file path. Reported fields:
  11365. * ignored (boolean) - true if file path is filtered by --ignore-path
  11366. * inferredParser (string | null) - name of parser inferred from file path
  11367. `
  11368. },
  11369. help: {
  11370. type: "flag",
  11371. alias: "h",
  11372. description: outdent`
  11373. Show CLI usage, or details about the given flag.
  11374. Example: --help write
  11375. `,
  11376. exception: value => value === ""
  11377. },
  11378. "ignore-path": {
  11379. type: "path",
  11380. category: coreOptions.CATEGORY_CONFIG,
  11381. default: ".prettierignore",
  11382. description: "Path to a file with patterns describing files to ignore."
  11383. },
  11384. "ignore-unknown": {
  11385. type: "boolean",
  11386. alias: "u",
  11387. description: "Ignore unknown files."
  11388. },
  11389. "list-different": {
  11390. type: "boolean",
  11391. category: coreOptions.CATEGORY_OUTPUT,
  11392. alias: "l",
  11393. description: "Print the names of files that are different from Prettier's formatting (see also --check)."
  11394. },
  11395. loglevel: {
  11396. type: "choice",
  11397. description: "What level of logs to report.",
  11398. default: "log",
  11399. choices: ["silent", "error", "warn", "log", "debug"]
  11400. },
  11401. "support-info": {
  11402. type: "boolean",
  11403. description: "Print support information as JSON."
  11404. },
  11405. version: {
  11406. type: "boolean",
  11407. alias: "v",
  11408. description: "Print Prettier version."
  11409. },
  11410. "with-node-modules": {
  11411. type: "boolean",
  11412. category: coreOptions.CATEGORY_CONFIG,
  11413. description: "Process files inside 'node_modules' directory."
  11414. },
  11415. write: {
  11416. type: "boolean",
  11417. alias: "w",
  11418. category: coreOptions.CATEGORY_OUTPUT,
  11419. description: "Edit files in-place. (Beware!)"
  11420. }
  11421. };
  11422. const usageSummary = outdent`
  11423. Usage: prettier [options] [file/dir/glob ...]
  11424. By default, output is written to stdout.
  11425. Stdin is read if it is piped to Prettier and no files are given.
  11426. `;
  11427. var constant$1 = {
  11428. categoryOrder,
  11429. options,
  11430. usageSummary
  11431. };
  11432. const {
  11433. isCI
  11434. } = thirdParty; // Some CI pipelines incorrectly report process.stdout.isTTY status,
  11435. // which causes unwanted lines in the output. An additional check for isCI() helps.
  11436. // See https://github.com/prettier/prettier/issues/5801
  11437. var isTty = function isTTY() {
  11438. return process.stdout.isTTY && !isCI();
  11439. };
  11440. function Diff() {}
  11441. Diff.prototype = {
  11442. diff: function diff(oldString, newString) {
  11443. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  11444. var callback = options.callback;
  11445. if (typeof options === 'function') {
  11446. callback = options;
  11447. options = {};
  11448. }
  11449. this.options = options;
  11450. var self = this;
  11451. function done(value) {
  11452. if (callback) {
  11453. setTimeout(function () {
  11454. callback(undefined, value);
  11455. }, 0);
  11456. return true;
  11457. } else {
  11458. return value;
  11459. }
  11460. } // Allow subclasses to massage the input prior to running
  11461. oldString = this.castInput(oldString);
  11462. newString = this.castInput(newString);
  11463. oldString = this.removeEmpty(this.tokenize(oldString));
  11464. newString = this.removeEmpty(this.tokenize(newString));
  11465. var newLen = newString.length,
  11466. oldLen = oldString.length;
  11467. var editLength = 1;
  11468. var maxEditLength = newLen + oldLen;
  11469. var bestPath = [{
  11470. newPos: -1,
  11471. components: []
  11472. }]; // Seed editLength = 0, i.e. the content starts with the same values
  11473. var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
  11474. if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  11475. // Identity per the equality and tokenizer
  11476. return done([{
  11477. value: this.join(newString),
  11478. count: newString.length
  11479. }]);
  11480. } // Main worker method. checks all permutations of a given edit length for acceptance.
  11481. function execEditLength() {
  11482. for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
  11483. var basePath = void 0;
  11484. var addPath = bestPath[diagonalPath - 1],
  11485. removePath = bestPath[diagonalPath + 1],
  11486. _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
  11487. if (addPath) {
  11488. // No one else is going to attempt to use this value, clear it
  11489. bestPath[diagonalPath - 1] = undefined;
  11490. }
  11491. var canAdd = addPath && addPath.newPos + 1 < newLen,
  11492. canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen;
  11493. if (!canAdd && !canRemove) {
  11494. // If this path is a terminal then prune
  11495. bestPath[diagonalPath] = undefined;
  11496. continue;
  11497. } // Select the diagonal that we want to branch from. We select the prior
  11498. // path whose position in the new string is the farthest from the origin
  11499. // and does not pass the bounds of the diff graph
  11500. if (!canAdd || canRemove && addPath.newPos < removePath.newPos) {
  11501. basePath = clonePath(removePath);
  11502. self.pushComponent(basePath.components, undefined, true);
  11503. } else {
  11504. basePath = addPath; // No need to clone, we've pulled it from the list
  11505. basePath.newPos++;
  11506. self.pushComponent(basePath.components, true, undefined);
  11507. }
  11508. _oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath); // If we have hit the end of both strings, then we are done
  11509. if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) {
  11510. return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken));
  11511. } else {
  11512. // Otherwise track this path as a potential candidate and continue.
  11513. bestPath[diagonalPath] = basePath;
  11514. }
  11515. }
  11516. editLength++;
  11517. } // Performs the length of edit iteration. Is a bit fugly as this has to support the
  11518. // sync and async mode which is never fun. Loops over execEditLength until a value
  11519. // is produced.
  11520. if (callback) {
  11521. (function exec() {
  11522. setTimeout(function () {
  11523. // This should not happen, but we want to be safe.
  11524. /* istanbul ignore next */
  11525. if (editLength > maxEditLength) {
  11526. return callback();
  11527. }
  11528. if (!execEditLength()) {
  11529. exec();
  11530. }
  11531. }, 0);
  11532. })();
  11533. } else {
  11534. while (editLength <= maxEditLength) {
  11535. var ret = execEditLength();
  11536. if (ret) {
  11537. return ret;
  11538. }
  11539. }
  11540. }
  11541. },
  11542. pushComponent: function pushComponent(components, added, removed) {
  11543. var last = components[components.length - 1];
  11544. if (last && last.added === added && last.removed === removed) {
  11545. // We need to clone here as the component clone operation is just
  11546. // as shallow array clone
  11547. components[components.length - 1] = {
  11548. count: last.count + 1,
  11549. added: added,
  11550. removed: removed
  11551. };
  11552. } else {
  11553. components.push({
  11554. count: 1,
  11555. added: added,
  11556. removed: removed
  11557. });
  11558. }
  11559. },
  11560. extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) {
  11561. var newLen = newString.length,
  11562. oldLen = oldString.length,
  11563. newPos = basePath.newPos,
  11564. oldPos = newPos - diagonalPath,
  11565. commonCount = 0;
  11566. while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) {
  11567. newPos++;
  11568. oldPos++;
  11569. commonCount++;
  11570. }
  11571. if (commonCount) {
  11572. basePath.components.push({
  11573. count: commonCount
  11574. });
  11575. }
  11576. basePath.newPos = newPos;
  11577. return oldPos;
  11578. },
  11579. equals: function equals(left, right) {
  11580. if (this.options.comparator) {
  11581. return this.options.comparator(left, right);
  11582. } else {
  11583. return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase();
  11584. }
  11585. },
  11586. removeEmpty: function removeEmpty(array) {
  11587. var ret = [];
  11588. for (var i = 0; i < array.length; i++) {
  11589. if (array[i]) {
  11590. ret.push(array[i]);
  11591. }
  11592. }
  11593. return ret;
  11594. },
  11595. castInput: function castInput(value) {
  11596. return value;
  11597. },
  11598. tokenize: function tokenize(value) {
  11599. return value.split('');
  11600. },
  11601. join: function join(chars) {
  11602. return chars.join('');
  11603. }
  11604. };
  11605. function buildValues(diff, components, newString, oldString, useLongestToken) {
  11606. var componentPos = 0,
  11607. componentLen = components.length,
  11608. newPos = 0,
  11609. oldPos = 0;
  11610. for (; componentPos < componentLen; componentPos++) {
  11611. var component = components[componentPos];
  11612. if (!component.removed) {
  11613. if (!component.added && useLongestToken) {
  11614. var value = newString.slice(newPos, newPos + component.count);
  11615. value = value.map(function (value, i) {
  11616. var oldValue = oldString[oldPos + i];
  11617. return oldValue.length > value.length ? oldValue : value;
  11618. });
  11619. component.value = diff.join(value);
  11620. } else {
  11621. component.value = diff.join(newString.slice(newPos, newPos + component.count));
  11622. }
  11623. newPos += component.count; // Common case
  11624. if (!component.added) {
  11625. oldPos += component.count;
  11626. }
  11627. } else {
  11628. component.value = diff.join(oldString.slice(oldPos, oldPos + component.count));
  11629. oldPos += component.count; // Reverse add and remove so removes are output first to match common convention
  11630. // The diffing algorithm is tied to add then remove output and this is the simplest
  11631. // route to get the desired output with minimal overhead.
  11632. if (componentPos && components[componentPos - 1].added) {
  11633. var tmp = components[componentPos - 1];
  11634. components[componentPos - 1] = components[componentPos];
  11635. components[componentPos] = tmp;
  11636. }
  11637. }
  11638. } // Special case handle for when one terminal is ignored (i.e. whitespace).
  11639. // For this case we merge the terminal into the prior string and drop the change.
  11640. // This is only available for string mode.
  11641. var lastComponent = components[componentLen - 1];
  11642. if (componentLen > 1 && typeof lastComponent.value === 'string' && (lastComponent.added || lastComponent.removed) && diff.equals('', lastComponent.value)) {
  11643. components[componentLen - 2].value += lastComponent.value;
  11644. components.pop();
  11645. }
  11646. return components;
  11647. }
  11648. function clonePath(path) {
  11649. return {
  11650. newPos: path.newPos,
  11651. components: path.components.slice(0)
  11652. };
  11653. }
  11654. var characterDiff = new Diff();
  11655. function diffChars(oldStr, newStr, options) {
  11656. return characterDiff.diff(oldStr, newStr, options);
  11657. }
  11658. function generateOptions(options, defaults) {
  11659. if (typeof options === 'function') {
  11660. defaults.callback = options;
  11661. } else if (options) {
  11662. for (var name in options) {
  11663. /* istanbul ignore else */
  11664. if (options.hasOwnProperty(name)) {
  11665. defaults[name] = options[name];
  11666. }
  11667. }
  11668. }
  11669. return defaults;
  11670. } //
  11671. // Ranges and exceptions:
  11672. // Latin-1 Supplement, 0080–00FF
  11673. // - U+00D7 × Multiplication sign
  11674. // - U+00F7 ÷ Division sign
  11675. // Latin Extended-A, 0100–017F
  11676. // Latin Extended-B, 0180–024F
  11677. // IPA Extensions, 0250–02AF
  11678. // Spacing Modifier Letters, 02B0–02FF
  11679. // - U+02C7 ˇ &#711; Caron
  11680. // - U+02D8 ˘ &#728; Breve
  11681. // - U+02D9 ˙ &#729; Dot Above
  11682. // - U+02DA ˚ &#730; Ring Above
  11683. // - U+02DB ˛ &#731; Ogonek
  11684. // - U+02DC ˜ &#732; Small Tilde
  11685. // - U+02DD ˝ &#733; Double Acute Accent
  11686. // Latin Extended Additional, 1E00–1EFF
  11687. var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/;
  11688. var reWhitespace = /\S/;
  11689. var wordDiff = new Diff();
  11690. wordDiff.equals = function (left, right) {
  11691. if (this.options.ignoreCase) {
  11692. left = left.toLowerCase();
  11693. right = right.toLowerCase();
  11694. }
  11695. return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right);
  11696. };
  11697. wordDiff.tokenize = function (value) {
  11698. var tokens = value.split(/(\s+|[()[\]{}'"]|\b)/); // Join the boundary splits that we do not consider to be boundaries. This is primarily the extended Latin character set.
  11699. for (var i = 0; i < tokens.length - 1; i++) {
  11700. // If we have an empty string in the next field and we have only word chars before and after, merge
  11701. if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) {
  11702. tokens[i] += tokens[i + 2];
  11703. tokens.splice(i + 1, 2);
  11704. i--;
  11705. }
  11706. }
  11707. return tokens;
  11708. };
  11709. function diffWords(oldStr, newStr, options) {
  11710. options = generateOptions(options, {
  11711. ignoreWhitespace: true
  11712. });
  11713. return wordDiff.diff(oldStr, newStr, options);
  11714. }
  11715. function diffWordsWithSpace(oldStr, newStr, options) {
  11716. return wordDiff.diff(oldStr, newStr, options);
  11717. }
  11718. var lineDiff = new Diff();
  11719. lineDiff.tokenize = function (value) {
  11720. var retLines = [],
  11721. linesAndNewlines = value.split(/(\n|\r\n)/); // Ignore the final empty token that occurs if the string ends with a new line
  11722. if (!linesAndNewlines[linesAndNewlines.length - 1]) {
  11723. linesAndNewlines.pop();
  11724. } // Merge the content and line separators into single tokens
  11725. for (var i = 0; i < linesAndNewlines.length; i++) {
  11726. var line = linesAndNewlines[i];
  11727. if (i % 2 && !this.options.newlineIsToken) {
  11728. retLines[retLines.length - 1] += line;
  11729. } else {
  11730. if (this.options.ignoreWhitespace) {
  11731. line = line.trim();
  11732. }
  11733. retLines.push(line);
  11734. }
  11735. }
  11736. return retLines;
  11737. };
  11738. function diffLines(oldStr, newStr, callback) {
  11739. return lineDiff.diff(oldStr, newStr, callback);
  11740. }
  11741. function diffTrimmedLines(oldStr, newStr, callback) {
  11742. var options = generateOptions(callback, {
  11743. ignoreWhitespace: true
  11744. });
  11745. return lineDiff.diff(oldStr, newStr, options);
  11746. }
  11747. var sentenceDiff = new Diff();
  11748. sentenceDiff.tokenize = function (value) {
  11749. return value.split(/(\S.+?[.!?])(?=\s+|$)/);
  11750. };
  11751. function diffSentences(oldStr, newStr, callback) {
  11752. return sentenceDiff.diff(oldStr, newStr, callback);
  11753. }
  11754. var cssDiff = new Diff();
  11755. cssDiff.tokenize = function (value) {
  11756. return value.split(/([{}:;,]|\s+)/);
  11757. };
  11758. function diffCss(oldStr, newStr, callback) {
  11759. return cssDiff.diff(oldStr, newStr, callback);
  11760. }
  11761. function _typeof(obj) {
  11762. if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
  11763. _typeof = function (obj) {
  11764. return typeof obj;
  11765. };
  11766. } else {
  11767. _typeof = function (obj) {
  11768. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  11769. };
  11770. }
  11771. return _typeof(obj);
  11772. }
  11773. function _toConsumableArray(arr) {
  11774. return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
  11775. }
  11776. function _arrayWithoutHoles(arr) {
  11777. if (Array.isArray(arr)) {
  11778. for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
  11779. return arr2;
  11780. }
  11781. }
  11782. function _iterableToArray(iter) {
  11783. if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
  11784. }
  11785. function _nonIterableSpread() {
  11786. throw new TypeError("Invalid attempt to spread non-iterable instance");
  11787. }
  11788. var objectPrototypeToString = Object.prototype.toString;
  11789. var jsonDiff = new Diff(); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a
  11790. // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output:
  11791. jsonDiff.useLongestToken = true;
  11792. jsonDiff.tokenize = lineDiff.tokenize;
  11793. jsonDiff.castInput = function (value) {
  11794. var _this$options = this.options,
  11795. undefinedReplacement = _this$options.undefinedReplacement,
  11796. _this$options$stringi = _this$options.stringifyReplacer,
  11797. stringifyReplacer = _this$options$stringi === void 0 ? function (k, v) {
  11798. return typeof v === 'undefined' ? undefinedReplacement : v;
  11799. } : _this$options$stringi;
  11800. return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' ');
  11801. };
  11802. jsonDiff.equals = function (left, right) {
  11803. return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1'));
  11804. };
  11805. function diffJson(oldObj, newObj, options) {
  11806. return jsonDiff.diff(oldObj, newObj, options);
  11807. } // This function handles the presence of circular references by bailing out when encountering an
  11808. // object that is already on the "stack" of items being processed. Accepts an optional replacer
  11809. function canonicalize(obj, stack, replacementStack, replacer, key) {
  11810. stack = stack || [];
  11811. replacementStack = replacementStack || [];
  11812. if (replacer) {
  11813. obj = replacer(key, obj);
  11814. }
  11815. var i;
  11816. for (i = 0; i < stack.length; i += 1) {
  11817. if (stack[i] === obj) {
  11818. return replacementStack[i];
  11819. }
  11820. }
  11821. var canonicalizedObj;
  11822. if ('[object Array]' === objectPrototypeToString.call(obj)) {
  11823. stack.push(obj);
  11824. canonicalizedObj = new Array(obj.length);
  11825. replacementStack.push(canonicalizedObj);
  11826. for (i = 0; i < obj.length; i += 1) {
  11827. canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key);
  11828. }
  11829. stack.pop();
  11830. replacementStack.pop();
  11831. return canonicalizedObj;
  11832. }
  11833. if (obj && obj.toJSON) {
  11834. obj = obj.toJSON();
  11835. }
  11836. if (_typeof(obj) === 'object' && obj !== null) {
  11837. stack.push(obj);
  11838. canonicalizedObj = {};
  11839. replacementStack.push(canonicalizedObj);
  11840. var sortedKeys = [],
  11841. _key;
  11842. for (_key in obj) {
  11843. /* istanbul ignore else */
  11844. if (obj.hasOwnProperty(_key)) {
  11845. sortedKeys.push(_key);
  11846. }
  11847. }
  11848. sortedKeys.sort();
  11849. for (i = 0; i < sortedKeys.length; i += 1) {
  11850. _key = sortedKeys[i];
  11851. canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key);
  11852. }
  11853. stack.pop();
  11854. replacementStack.pop();
  11855. } else {
  11856. canonicalizedObj = obj;
  11857. }
  11858. return canonicalizedObj;
  11859. }
  11860. var arrayDiff = new Diff();
  11861. arrayDiff.tokenize = function (value) {
  11862. return value.slice();
  11863. };
  11864. arrayDiff.join = arrayDiff.removeEmpty = function (value) {
  11865. return value;
  11866. };
  11867. function diffArrays(oldArr, newArr, callback) {
  11868. return arrayDiff.diff(oldArr, newArr, callback);
  11869. }
  11870. function parsePatch(uniDiff) {
  11871. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  11872. var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/),
  11873. delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [],
  11874. list = [],
  11875. i = 0;
  11876. function parseIndex() {
  11877. var index = {};
  11878. list.push(index); // Parse diff metadata
  11879. while (i < diffstr.length) {
  11880. var line = diffstr[i]; // File header found, end parsing diff metadata
  11881. if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) {
  11882. break;
  11883. } // Diff index
  11884. var header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line);
  11885. if (header) {
  11886. index.index = header[1];
  11887. }
  11888. i++;
  11889. } // Parse file headers if they are defined. Unified diff requires them, but
  11890. // there's no technical issues to have an isolated hunk without file header
  11891. parseFileHeader(index);
  11892. parseFileHeader(index); // Parse hunks
  11893. index.hunks = [];
  11894. while (i < diffstr.length) {
  11895. var _line = diffstr[i];
  11896. if (/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(_line)) {
  11897. break;
  11898. } else if (/^@@/.test(_line)) {
  11899. index.hunks.push(parseHunk());
  11900. } else if (_line && options.strict) {
  11901. // Ignore unexpected content unless in strict mode
  11902. throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line));
  11903. } else {
  11904. i++;
  11905. }
  11906. }
  11907. } // Parses the --- and +++ headers, if none are found, no lines
  11908. // are consumed.
  11909. function parseFileHeader(index) {
  11910. var fileHeader = /^(---|\+\+\+)\s+(.*)$/.exec(diffstr[i]);
  11911. if (fileHeader) {
  11912. var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new';
  11913. var data = fileHeader[2].split('\t', 2);
  11914. var fileName = data[0].replace(/\\\\/g, '\\');
  11915. if (/^".*"$/.test(fileName)) {
  11916. fileName = fileName.substr(1, fileName.length - 2);
  11917. }
  11918. index[keyPrefix + 'FileName'] = fileName;
  11919. index[keyPrefix + 'Header'] = (data[1] || '').trim();
  11920. i++;
  11921. }
  11922. } // Parses a hunk
  11923. // This assumes that we are at the start of a hunk.
  11924. function parseHunk() {
  11925. var chunkHeaderIndex = i,
  11926. chunkHeaderLine = diffstr[i++],
  11927. chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);
  11928. var hunk = {
  11929. oldStart: +chunkHeader[1],
  11930. oldLines: +chunkHeader[2] || 1,
  11931. newStart: +chunkHeader[3],
  11932. newLines: +chunkHeader[4] || 1,
  11933. lines: [],
  11934. linedelimiters: []
  11935. };
  11936. var addCount = 0,
  11937. removeCount = 0;
  11938. for (; i < diffstr.length; i++) {
  11939. // Lines starting with '---' could be mistaken for the "remove line" operation
  11940. // But they could be the header for the next file. Therefore prune such cases out.
  11941. if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) {
  11942. break;
  11943. }
  11944. var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0];
  11945. if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') {
  11946. hunk.lines.push(diffstr[i]);
  11947. hunk.linedelimiters.push(delimiters[i] || '\n');
  11948. if (operation === '+') {
  11949. addCount++;
  11950. } else if (operation === '-') {
  11951. removeCount++;
  11952. } else if (operation === ' ') {
  11953. addCount++;
  11954. removeCount++;
  11955. }
  11956. } else {
  11957. break;
  11958. }
  11959. } // Handle the empty block count case
  11960. if (!addCount && hunk.newLines === 1) {
  11961. hunk.newLines = 0;
  11962. }
  11963. if (!removeCount && hunk.oldLines === 1) {
  11964. hunk.oldLines = 0;
  11965. } // Perform optional sanity checking
  11966. if (options.strict) {
  11967. if (addCount !== hunk.newLines) {
  11968. throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1));
  11969. }
  11970. if (removeCount !== hunk.oldLines) {
  11971. throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1));
  11972. }
  11973. }
  11974. return hunk;
  11975. }
  11976. while (i < diffstr.length) {
  11977. parseIndex();
  11978. }
  11979. return list;
  11980. } // Iterator that traverses in the range of [min, max], stepping
  11981. // by distance from a given start position. I.e. for [0, 4], with
  11982. // start of 2, this will iterate 2, 3, 1, 4, 0.
  11983. function distanceIterator(start, minLine, maxLine) {
  11984. var wantForward = true,
  11985. backwardExhausted = false,
  11986. forwardExhausted = false,
  11987. localOffset = 1;
  11988. return function iterator() {
  11989. if (wantForward && !forwardExhausted) {
  11990. if (backwardExhausted) {
  11991. localOffset++;
  11992. } else {
  11993. wantForward = false;
  11994. } // Check if trying to fit beyond text length, and if not, check it fits
  11995. // after offset location (or desired location on first iteration)
  11996. if (start + localOffset <= maxLine) {
  11997. return localOffset;
  11998. }
  11999. forwardExhausted = true;
  12000. }
  12001. if (!backwardExhausted) {
  12002. if (!forwardExhausted) {
  12003. wantForward = true;
  12004. } // Check if trying to fit before text beginning, and if not, check it fits
  12005. // before offset location
  12006. if (minLine <= start - localOffset) {
  12007. return -localOffset++;
  12008. }
  12009. backwardExhausted = true;
  12010. return iterator();
  12011. } // We tried to fit hunk before text beginning and beyond text length, then
  12012. // hunk can't fit on the text. Return undefined
  12013. };
  12014. }
  12015. function applyPatch(source, uniDiff) {
  12016. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  12017. if (typeof uniDiff === 'string') {
  12018. uniDiff = parsePatch(uniDiff);
  12019. }
  12020. if (Array.isArray(uniDiff)) {
  12021. if (uniDiff.length > 1) {
  12022. throw new Error('applyPatch only works with a single input.');
  12023. }
  12024. uniDiff = uniDiff[0];
  12025. } // Apply the diff to the input
  12026. var lines = source.split(/\r\n|[\n\v\f\r\x85]/),
  12027. delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [],
  12028. hunks = uniDiff.hunks,
  12029. compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) {
  12030. return line === patchContent;
  12031. },
  12032. errorCount = 0,
  12033. fuzzFactor = options.fuzzFactor || 0,
  12034. minLine = 0,
  12035. offset = 0,
  12036. removeEOFNL,
  12037. addEOFNL;
  12038. /**
  12039. * Checks if the hunk exactly fits on the provided location
  12040. */
  12041. function hunkFits(hunk, toPos) {
  12042. for (var j = 0; j < hunk.lines.length; j++) {
  12043. var line = hunk.lines[j],
  12044. operation = line.length > 0 ? line[0] : ' ',
  12045. content = line.length > 0 ? line.substr(1) : line;
  12046. if (operation === ' ' || operation === '-') {
  12047. // Context sanity check
  12048. if (!compareLine(toPos + 1, lines[toPos], operation, content)) {
  12049. errorCount++;
  12050. if (errorCount > fuzzFactor) {
  12051. return false;
  12052. }
  12053. }
  12054. toPos++;
  12055. }
  12056. }
  12057. return true;
  12058. } // Search best fit offsets for each hunk based on the previous ones
  12059. for (var i = 0; i < hunks.length; i++) {
  12060. var hunk = hunks[i],
  12061. maxLine = lines.length - hunk.oldLines,
  12062. localOffset = 0,
  12063. toPos = offset + hunk.oldStart - 1;
  12064. var iterator = distanceIterator(toPos, minLine, maxLine);
  12065. for (; localOffset !== undefined; localOffset = iterator()) {
  12066. if (hunkFits(hunk, toPos + localOffset)) {
  12067. hunk.offset = offset += localOffset;
  12068. break;
  12069. }
  12070. }
  12071. if (localOffset === undefined) {
  12072. return false;
  12073. } // Set lower text limit to end of the current hunk, so next ones don't try
  12074. // to fit over already patched text
  12075. minLine = hunk.offset + hunk.oldStart + hunk.oldLines;
  12076. } // Apply patch hunks
  12077. var diffOffset = 0;
  12078. for (var _i = 0; _i < hunks.length; _i++) {
  12079. var _hunk = hunks[_i],
  12080. _toPos = _hunk.oldStart + _hunk.offset + diffOffset - 1;
  12081. diffOffset += _hunk.newLines - _hunk.oldLines;
  12082. if (_toPos < 0) {
  12083. // Creating a new file
  12084. _toPos = 0;
  12085. }
  12086. for (var j = 0; j < _hunk.lines.length; j++) {
  12087. var line = _hunk.lines[j],
  12088. operation = line.length > 0 ? line[0] : ' ',
  12089. content = line.length > 0 ? line.substr(1) : line,
  12090. delimiter = _hunk.linedelimiters[j];
  12091. if (operation === ' ') {
  12092. _toPos++;
  12093. } else if (operation === '-') {
  12094. lines.splice(_toPos, 1);
  12095. delimiters.splice(_toPos, 1);
  12096. /* istanbul ignore else */
  12097. } else if (operation === '+') {
  12098. lines.splice(_toPos, 0, content);
  12099. delimiters.splice(_toPos, 0, delimiter);
  12100. _toPos++;
  12101. } else if (operation === '\\') {
  12102. var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null;
  12103. if (previousOperation === '+') {
  12104. removeEOFNL = true;
  12105. } else if (previousOperation === '-') {
  12106. addEOFNL = true;
  12107. }
  12108. }
  12109. }
  12110. } // Handle EOFNL insertion/removal
  12111. if (removeEOFNL) {
  12112. while (!lines[lines.length - 1]) {
  12113. lines.pop();
  12114. delimiters.pop();
  12115. }
  12116. } else if (addEOFNL) {
  12117. lines.push('');
  12118. delimiters.push('\n');
  12119. }
  12120. for (var _k = 0; _k < lines.length - 1; _k++) {
  12121. lines[_k] = lines[_k] + delimiters[_k];
  12122. }
  12123. return lines.join('');
  12124. } // Wrapper that supports multiple file patches via callbacks.
  12125. function applyPatches(uniDiff, options) {
  12126. if (typeof uniDiff === 'string') {
  12127. uniDiff = parsePatch(uniDiff);
  12128. }
  12129. var currentIndex = 0;
  12130. function processIndex() {
  12131. var index = uniDiff[currentIndex++];
  12132. if (!index) {
  12133. return options.complete();
  12134. }
  12135. options.loadFile(index, function (err, data) {
  12136. if (err) {
  12137. return options.complete(err);
  12138. }
  12139. var updatedContent = applyPatch(data, index, options);
  12140. options.patched(index, updatedContent, function (err) {
  12141. if (err) {
  12142. return options.complete(err);
  12143. }
  12144. processIndex();
  12145. });
  12146. });
  12147. }
  12148. processIndex();
  12149. }
  12150. function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
  12151. if (!options) {
  12152. options = {};
  12153. }
  12154. if (typeof options.context === 'undefined') {
  12155. options.context = 4;
  12156. }
  12157. var diff = diffLines(oldStr, newStr, options);
  12158. diff.push({
  12159. value: '',
  12160. lines: []
  12161. }); // Append an empty value to make cleanup easier
  12162. function contextLines(lines) {
  12163. return lines.map(function (entry) {
  12164. return ' ' + entry;
  12165. });
  12166. }
  12167. var hunks = [];
  12168. var oldRangeStart = 0,
  12169. newRangeStart = 0,
  12170. curRange = [],
  12171. oldLine = 1,
  12172. newLine = 1;
  12173. var _loop = function _loop(i) {
  12174. var current = diff[i],
  12175. lines = current.lines || current.value.replace(/\n$/, '').split('\n');
  12176. current.lines = lines;
  12177. if (current.added || current.removed) {
  12178. var _curRange; // If we have previous context, start with that
  12179. if (!oldRangeStart) {
  12180. var prev = diff[i - 1];
  12181. oldRangeStart = oldLine;
  12182. newRangeStart = newLine;
  12183. if (prev) {
  12184. curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : [];
  12185. oldRangeStart -= curRange.length;
  12186. newRangeStart -= curRange.length;
  12187. }
  12188. } // Output our changes
  12189. (_curRange = curRange).push.apply(_curRange, _toConsumableArray(lines.map(function (entry) {
  12190. return (current.added ? '+' : '-') + entry;
  12191. }))); // Track the updated file position
  12192. if (current.added) {
  12193. newLine += lines.length;
  12194. } else {
  12195. oldLine += lines.length;
  12196. }
  12197. } else {
  12198. // Identical context lines. Track line changes
  12199. if (oldRangeStart) {
  12200. // Close out any changes that have been output (or join overlapping)
  12201. if (lines.length <= options.context * 2 && i < diff.length - 2) {
  12202. var _curRange2; // Overlapping
  12203. (_curRange2 = curRange).push.apply(_curRange2, _toConsumableArray(contextLines(lines)));
  12204. } else {
  12205. var _curRange3; // end the range and output
  12206. var contextSize = Math.min(lines.length, options.context);
  12207. (_curRange3 = curRange).push.apply(_curRange3, _toConsumableArray(contextLines(lines.slice(0, contextSize))));
  12208. var hunk = {
  12209. oldStart: oldRangeStart,
  12210. oldLines: oldLine - oldRangeStart + contextSize,
  12211. newStart: newRangeStart,
  12212. newLines: newLine - newRangeStart + contextSize,
  12213. lines: curRange
  12214. };
  12215. if (i >= diff.length - 2 && lines.length <= options.context) {
  12216. // EOF is inside this hunk
  12217. var oldEOFNewline = /\n$/.test(oldStr);
  12218. var newEOFNewline = /\n$/.test(newStr);
  12219. var noNlBeforeAdds = lines.length == 0 && curRange.length > hunk.oldLines;
  12220. if (!oldEOFNewline && noNlBeforeAdds) {
  12221. // special case: old has no eol and no trailing context; no-nl can end up before adds
  12222. curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file');
  12223. }
  12224. if (!oldEOFNewline && !noNlBeforeAdds || !newEOFNewline) {
  12225. curRange.push('\\ No newline at end of file');
  12226. }
  12227. }
  12228. hunks.push(hunk);
  12229. oldRangeStart = 0;
  12230. newRangeStart = 0;
  12231. curRange = [];
  12232. }
  12233. }
  12234. oldLine += lines.length;
  12235. newLine += lines.length;
  12236. }
  12237. };
  12238. for (var i = 0; i < diff.length; i++) {
  12239. _loop(i);
  12240. }
  12241. return {
  12242. oldFileName: oldFileName,
  12243. newFileName: newFileName,
  12244. oldHeader: oldHeader,
  12245. newHeader: newHeader,
  12246. hunks: hunks
  12247. };
  12248. }
  12249. function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
  12250. var diff = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options);
  12251. var ret = [];
  12252. if (oldFileName == newFileName) {
  12253. ret.push('Index: ' + oldFileName);
  12254. }
  12255. ret.push('===================================================================');
  12256. ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader));
  12257. ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader));
  12258. for (var i = 0; i < diff.hunks.length; i++) {
  12259. var hunk = diff.hunks[i];
  12260. ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@');
  12261. ret.push.apply(ret, hunk.lines);
  12262. }
  12263. return ret.join('\n') + '\n';
  12264. }
  12265. function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) {
  12266. return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options);
  12267. }
  12268. function arrayEqual(a, b) {
  12269. if (a.length !== b.length) {
  12270. return false;
  12271. }
  12272. return arrayStartsWith(a, b);
  12273. }
  12274. function arrayStartsWith(array, start) {
  12275. if (start.length > array.length) {
  12276. return false;
  12277. }
  12278. for (var i = 0; i < start.length; i++) {
  12279. if (start[i] !== array[i]) {
  12280. return false;
  12281. }
  12282. }
  12283. return true;
  12284. }
  12285. function calcLineCount(hunk) {
  12286. var _calcOldNewLineCount = calcOldNewLineCount(hunk.lines),
  12287. oldLines = _calcOldNewLineCount.oldLines,
  12288. newLines = _calcOldNewLineCount.newLines;
  12289. if (oldLines !== undefined) {
  12290. hunk.oldLines = oldLines;
  12291. } else {
  12292. delete hunk.oldLines;
  12293. }
  12294. if (newLines !== undefined) {
  12295. hunk.newLines = newLines;
  12296. } else {
  12297. delete hunk.newLines;
  12298. }
  12299. }
  12300. function merge(mine, theirs, base) {
  12301. mine = loadPatch(mine, base);
  12302. theirs = loadPatch(theirs, base);
  12303. var ret = {}; // For index we just let it pass through as it doesn't have any necessary meaning.
  12304. // Leaving sanity checks on this to the API consumer that may know more about the
  12305. // meaning in their own context.
  12306. if (mine.index || theirs.index) {
  12307. ret.index = mine.index || theirs.index;
  12308. }
  12309. if (mine.newFileName || theirs.newFileName) {
  12310. if (!fileNameChanged(mine)) {
  12311. // No header or no change in ours, use theirs (and ours if theirs does not exist)
  12312. ret.oldFileName = theirs.oldFileName || mine.oldFileName;
  12313. ret.newFileName = theirs.newFileName || mine.newFileName;
  12314. ret.oldHeader = theirs.oldHeader || mine.oldHeader;
  12315. ret.newHeader = theirs.newHeader || mine.newHeader;
  12316. } else if (!fileNameChanged(theirs)) {
  12317. // No header or no change in theirs, use ours
  12318. ret.oldFileName = mine.oldFileName;
  12319. ret.newFileName = mine.newFileName;
  12320. ret.oldHeader = mine.oldHeader;
  12321. ret.newHeader = mine.newHeader;
  12322. } else {
  12323. // Both changed... figure it out
  12324. ret.oldFileName = selectField(ret, mine.oldFileName, theirs.oldFileName);
  12325. ret.newFileName = selectField(ret, mine.newFileName, theirs.newFileName);
  12326. ret.oldHeader = selectField(ret, mine.oldHeader, theirs.oldHeader);
  12327. ret.newHeader = selectField(ret, mine.newHeader, theirs.newHeader);
  12328. }
  12329. }
  12330. ret.hunks = [];
  12331. var mineIndex = 0,
  12332. theirsIndex = 0,
  12333. mineOffset = 0,
  12334. theirsOffset = 0;
  12335. while (mineIndex < mine.hunks.length || theirsIndex < theirs.hunks.length) {
  12336. var mineCurrent = mine.hunks[mineIndex] || {
  12337. oldStart: Infinity
  12338. },
  12339. theirsCurrent = theirs.hunks[theirsIndex] || {
  12340. oldStart: Infinity
  12341. };
  12342. if (hunkBefore(mineCurrent, theirsCurrent)) {
  12343. // This patch does not overlap with any of the others, yay.
  12344. ret.hunks.push(cloneHunk(mineCurrent, mineOffset));
  12345. mineIndex++;
  12346. theirsOffset += mineCurrent.newLines - mineCurrent.oldLines;
  12347. } else if (hunkBefore(theirsCurrent, mineCurrent)) {
  12348. // This patch does not overlap with any of the others, yay.
  12349. ret.hunks.push(cloneHunk(theirsCurrent, theirsOffset));
  12350. theirsIndex++;
  12351. mineOffset += theirsCurrent.newLines - theirsCurrent.oldLines;
  12352. } else {
  12353. // Overlap, merge as best we can
  12354. var mergedHunk = {
  12355. oldStart: Math.min(mineCurrent.oldStart, theirsCurrent.oldStart),
  12356. oldLines: 0,
  12357. newStart: Math.min(mineCurrent.newStart + mineOffset, theirsCurrent.oldStart + theirsOffset),
  12358. newLines: 0,
  12359. lines: []
  12360. };
  12361. mergeLines(mergedHunk, mineCurrent.oldStart, mineCurrent.lines, theirsCurrent.oldStart, theirsCurrent.lines);
  12362. theirsIndex++;
  12363. mineIndex++;
  12364. ret.hunks.push(mergedHunk);
  12365. }
  12366. }
  12367. return ret;
  12368. }
  12369. function loadPatch(param, base) {
  12370. if (typeof param === 'string') {
  12371. if (/^@@/m.test(param) || /^Index:/m.test(param)) {
  12372. return parsePatch(param)[0];
  12373. }
  12374. if (!base) {
  12375. throw new Error('Must provide a base reference or pass in a patch');
  12376. }
  12377. return structuredPatch(undefined, undefined, base, param);
  12378. }
  12379. return param;
  12380. }
  12381. function fileNameChanged(patch) {
  12382. return patch.newFileName && patch.newFileName !== patch.oldFileName;
  12383. }
  12384. function selectField(index, mine, theirs) {
  12385. if (mine === theirs) {
  12386. return mine;
  12387. } else {
  12388. index.conflict = true;
  12389. return {
  12390. mine: mine,
  12391. theirs: theirs
  12392. };
  12393. }
  12394. }
  12395. function hunkBefore(test, check) {
  12396. return test.oldStart < check.oldStart && test.oldStart + test.oldLines < check.oldStart;
  12397. }
  12398. function cloneHunk(hunk, offset) {
  12399. return {
  12400. oldStart: hunk.oldStart,
  12401. oldLines: hunk.oldLines,
  12402. newStart: hunk.newStart + offset,
  12403. newLines: hunk.newLines,
  12404. lines: hunk.lines
  12405. };
  12406. }
  12407. function mergeLines(hunk, mineOffset, mineLines, theirOffset, theirLines) {
  12408. // This will generally result in a conflicted hunk, but there are cases where the context
  12409. // is the only overlap where we can successfully merge the content here.
  12410. var mine = {
  12411. offset: mineOffset,
  12412. lines: mineLines,
  12413. index: 0
  12414. },
  12415. their = {
  12416. offset: theirOffset,
  12417. lines: theirLines,
  12418. index: 0
  12419. }; // Handle any leading content
  12420. insertLeading(hunk, mine, their);
  12421. insertLeading(hunk, their, mine); // Now in the overlap content. Scan through and select the best changes from each.
  12422. while (mine.index < mine.lines.length && their.index < their.lines.length) {
  12423. var mineCurrent = mine.lines[mine.index],
  12424. theirCurrent = their.lines[their.index];
  12425. if ((mineCurrent[0] === '-' || mineCurrent[0] === '+') && (theirCurrent[0] === '-' || theirCurrent[0] === '+')) {
  12426. // Both modified ...
  12427. mutualChange(hunk, mine, their);
  12428. } else if (mineCurrent[0] === '+' && theirCurrent[0] === ' ') {
  12429. var _hunk$lines; // Mine inserted
  12430. (_hunk$lines = hunk.lines).push.apply(_hunk$lines, _toConsumableArray(collectChange(mine)));
  12431. } else if (theirCurrent[0] === '+' && mineCurrent[0] === ' ') {
  12432. var _hunk$lines2; // Theirs inserted
  12433. (_hunk$lines2 = hunk.lines).push.apply(_hunk$lines2, _toConsumableArray(collectChange(their)));
  12434. } else if (mineCurrent[0] === '-' && theirCurrent[0] === ' ') {
  12435. // Mine removed or edited
  12436. removal(hunk, mine, their);
  12437. } else if (theirCurrent[0] === '-' && mineCurrent[0] === ' ') {
  12438. // Their removed or edited
  12439. removal(hunk, their, mine, true);
  12440. } else if (mineCurrent === theirCurrent) {
  12441. // Context identity
  12442. hunk.lines.push(mineCurrent);
  12443. mine.index++;
  12444. their.index++;
  12445. } else {
  12446. // Context mismatch
  12447. conflict(hunk, collectChange(mine), collectChange(their));
  12448. }
  12449. } // Now push anything that may be remaining
  12450. insertTrailing(hunk, mine);
  12451. insertTrailing(hunk, their);
  12452. calcLineCount(hunk);
  12453. }
  12454. function mutualChange(hunk, mine, their) {
  12455. var myChanges = collectChange(mine),
  12456. theirChanges = collectChange(their);
  12457. if (allRemoves(myChanges) && allRemoves(theirChanges)) {
  12458. // Special case for remove changes that are supersets of one another
  12459. if (arrayStartsWith(myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) {
  12460. var _hunk$lines3;
  12461. (_hunk$lines3 = hunk.lines).push.apply(_hunk$lines3, _toConsumableArray(myChanges));
  12462. return;
  12463. } else if (arrayStartsWith(theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) {
  12464. var _hunk$lines4;
  12465. (_hunk$lines4 = hunk.lines).push.apply(_hunk$lines4, _toConsumableArray(theirChanges));
  12466. return;
  12467. }
  12468. } else if (arrayEqual(myChanges, theirChanges)) {
  12469. var _hunk$lines5;
  12470. (_hunk$lines5 = hunk.lines).push.apply(_hunk$lines5, _toConsumableArray(myChanges));
  12471. return;
  12472. }
  12473. conflict(hunk, myChanges, theirChanges);
  12474. }
  12475. function removal(hunk, mine, their, swap) {
  12476. var myChanges = collectChange(mine),
  12477. theirChanges = collectContext(their, myChanges);
  12478. if (theirChanges.merged) {
  12479. var _hunk$lines6;
  12480. (_hunk$lines6 = hunk.lines).push.apply(_hunk$lines6, _toConsumableArray(theirChanges.merged));
  12481. } else {
  12482. conflict(hunk, swap ? theirChanges : myChanges, swap ? myChanges : theirChanges);
  12483. }
  12484. }
  12485. function conflict(hunk, mine, their) {
  12486. hunk.conflict = true;
  12487. hunk.lines.push({
  12488. conflict: true,
  12489. mine: mine,
  12490. theirs: their
  12491. });
  12492. }
  12493. function insertLeading(hunk, insert, their) {
  12494. while (insert.offset < their.offset && insert.index < insert.lines.length) {
  12495. var line = insert.lines[insert.index++];
  12496. hunk.lines.push(line);
  12497. insert.offset++;
  12498. }
  12499. }
  12500. function insertTrailing(hunk, insert) {
  12501. while (insert.index < insert.lines.length) {
  12502. var line = insert.lines[insert.index++];
  12503. hunk.lines.push(line);
  12504. }
  12505. }
  12506. function collectChange(state) {
  12507. var ret = [],
  12508. operation = state.lines[state.index][0];
  12509. while (state.index < state.lines.length) {
  12510. var line = state.lines[state.index]; // Group additions that are immediately after subtractions and treat them as one "atomic" modify change.
  12511. if (operation === '-' && line[0] === '+') {
  12512. operation = '+';
  12513. }
  12514. if (operation === line[0]) {
  12515. ret.push(line);
  12516. state.index++;
  12517. } else {
  12518. break;
  12519. }
  12520. }
  12521. return ret;
  12522. }
  12523. function collectContext(state, matchChanges) {
  12524. var changes = [],
  12525. merged = [],
  12526. matchIndex = 0,
  12527. contextChanges = false,
  12528. conflicted = false;
  12529. while (matchIndex < matchChanges.length && state.index < state.lines.length) {
  12530. var change = state.lines[state.index],
  12531. match = matchChanges[matchIndex]; // Once we've hit our add, then we are done
  12532. if (match[0] === '+') {
  12533. break;
  12534. }
  12535. contextChanges = contextChanges || change[0] !== ' ';
  12536. merged.push(match);
  12537. matchIndex++; // Consume any additions in the other block as a conflict to attempt
  12538. // to pull in the remaining context after this
  12539. if (change[0] === '+') {
  12540. conflicted = true;
  12541. while (change[0] === '+') {
  12542. changes.push(change);
  12543. change = state.lines[++state.index];
  12544. }
  12545. }
  12546. if (match.substr(1) === change.substr(1)) {
  12547. changes.push(change);
  12548. state.index++;
  12549. } else {
  12550. conflicted = true;
  12551. }
  12552. }
  12553. if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) {
  12554. conflicted = true;
  12555. }
  12556. if (conflicted) {
  12557. return changes;
  12558. }
  12559. while (matchIndex < matchChanges.length) {
  12560. merged.push(matchChanges[matchIndex++]);
  12561. }
  12562. return {
  12563. merged: merged,
  12564. changes: changes
  12565. };
  12566. }
  12567. function allRemoves(changes) {
  12568. return changes.reduce(function (prev, change) {
  12569. return prev && change[0] === '-';
  12570. }, true);
  12571. }
  12572. function skipRemoveSuperset(state, removeChanges, delta) {
  12573. for (var i = 0; i < delta; i++) {
  12574. var changeContent = removeChanges[removeChanges.length - delta + i].substr(1);
  12575. if (state.lines[state.index + i] !== ' ' + changeContent) {
  12576. return false;
  12577. }
  12578. }
  12579. state.index += delta;
  12580. return true;
  12581. }
  12582. function calcOldNewLineCount(lines) {
  12583. var oldLines = 0;
  12584. var newLines = 0;
  12585. lines.forEach(function (line) {
  12586. if (typeof line !== 'string') {
  12587. var myCount = calcOldNewLineCount(line.mine);
  12588. var theirCount = calcOldNewLineCount(line.theirs);
  12589. if (oldLines !== undefined) {
  12590. if (myCount.oldLines === theirCount.oldLines) {
  12591. oldLines += myCount.oldLines;
  12592. } else {
  12593. oldLines = undefined;
  12594. }
  12595. }
  12596. if (newLines !== undefined) {
  12597. if (myCount.newLines === theirCount.newLines) {
  12598. newLines += myCount.newLines;
  12599. } else {
  12600. newLines = undefined;
  12601. }
  12602. }
  12603. } else {
  12604. if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) {
  12605. newLines++;
  12606. }
  12607. if (oldLines !== undefined && (line[0] === '-' || line[0] === ' ')) {
  12608. oldLines++;
  12609. }
  12610. }
  12611. });
  12612. return {
  12613. oldLines: oldLines,
  12614. newLines: newLines
  12615. };
  12616. } // See: http://code.google.com/p/google-diff-match-patch/wiki/API
  12617. function convertChangesToDMP(changes) {
  12618. var ret = [],
  12619. change,
  12620. operation;
  12621. for (var i = 0; i < changes.length; i++) {
  12622. change = changes[i];
  12623. if (change.added) {
  12624. operation = 1;
  12625. } else if (change.removed) {
  12626. operation = -1;
  12627. } else {
  12628. operation = 0;
  12629. }
  12630. ret.push([operation, change.value]);
  12631. }
  12632. return ret;
  12633. }
  12634. function convertChangesToXML(changes) {
  12635. var ret = [];
  12636. for (var i = 0; i < changes.length; i++) {
  12637. var change = changes[i];
  12638. if (change.added) {
  12639. ret.push('<ins>');
  12640. } else if (change.removed) {
  12641. ret.push('<del>');
  12642. }
  12643. ret.push(escapeHTML(change.value));
  12644. if (change.added) {
  12645. ret.push('</ins>');
  12646. } else if (change.removed) {
  12647. ret.push('</del>');
  12648. }
  12649. }
  12650. return ret.join('');
  12651. }
  12652. function escapeHTML(s) {
  12653. var n = s;
  12654. n = n.replace(/&/g, '&amp;');
  12655. n = n.replace(/</g, '&lt;');
  12656. n = n.replace(/>/g, '&gt;');
  12657. n = n.replace(/"/g, '&quot;');
  12658. return n;
  12659. }
  12660. var index_es6 = /*#__PURE__*/Object.freeze({
  12661. __proto__: null,
  12662. Diff: Diff,
  12663. diffChars: diffChars,
  12664. diffWords: diffWords,
  12665. diffWordsWithSpace: diffWordsWithSpace,
  12666. diffLines: diffLines,
  12667. diffTrimmedLines: diffTrimmedLines,
  12668. diffSentences: diffSentences,
  12669. diffCss: diffCss,
  12670. diffJson: diffJson,
  12671. diffArrays: diffArrays,
  12672. structuredPatch: structuredPatch,
  12673. createTwoFilesPatch: createTwoFilesPatch,
  12674. createPatch: createPatch,
  12675. applyPatch: applyPatch,
  12676. applyPatches: applyPatches,
  12677. parsePatch: parsePatch,
  12678. merge: merge,
  12679. convertChangesToDMP: convertChangesToDMP,
  12680. convertChangesToXML: convertChangesToXML,
  12681. canonicalize: canonicalize
  12682. });
  12683. var require$$3 = getCjsExportFromNamespace(index_es6);
  12684. // eslint-disable-next-line no-restricted-modules
  12685. const {
  12686. getStream
  12687. } = thirdParty;
  12688. const {
  12689. createIgnorer,
  12690. errors,
  12691. coreOptions: coreOptions$1,
  12692. optionsModule,
  12693. optionsNormalizer,
  12694. utils: {
  12695. arrayify
  12696. }
  12697. } = prettierInternal;
  12698. const {
  12699. expandPatterns: expandPatterns$1,
  12700. fixWindowsSlashes: fixWindowsSlashes$1
  12701. } = expandPatterns_1;
  12702. const OPTION_USAGE_THRESHOLD = 25;
  12703. const CHOICE_USAGE_MARGIN = 3;
  12704. const CHOICE_USAGE_INDENTATION = 2;
  12705. function getOptions(argv, detailedOptions) {
  12706. return fromPairs_1(detailedOptions.filter(({
  12707. forwardToApi
  12708. }) => forwardToApi).map(({
  12709. forwardToApi,
  12710. name
  12711. }) => [forwardToApi, argv[name]]));
  12712. }
  12713. function cliifyOptions(object, apiDetailedOptionMap) {
  12714. return Object.keys(object || {}).reduce((output, key) => {
  12715. const apiOption = apiDetailedOptionMap[key];
  12716. const cliKey = apiOption ? apiOption.name : key;
  12717. output[dashify(cliKey)] = object[key];
  12718. return output;
  12719. }, {});
  12720. }
  12721. function diff(a, b) {
  12722. return require$$3.createTwoFilesPatch("", "", a, b, "", "", {
  12723. context: 2
  12724. });
  12725. }
  12726. function handleError(context, filename, error) {
  12727. if (error instanceof errors.UndefinedParserError) {
  12728. // Can't test on CI, `isTTY()` is always false, see ./is-tty.js
  12729. /* istanbul ignore next */
  12730. if ((context.argv.write || context.argv["ignore-unknown"]) && isTty()) {
  12731. readline__default['default'].clearLine(process.stdout, 0);
  12732. readline__default['default'].cursorTo(process.stdout, 0, null);
  12733. }
  12734. if (context.argv["ignore-unknown"]) {
  12735. return;
  12736. }
  12737. if (!context.argv.check && !context.argv["list-different"]) {
  12738. process.exitCode = 2;
  12739. }
  12740. context.logger.error(error.message);
  12741. return;
  12742. }
  12743. if (context.argv.write) {
  12744. // Add newline to split errors from filename line.
  12745. process.stdout.write("\n");
  12746. }
  12747. const isParseError = Boolean(error && error.loc);
  12748. const isValidationError = /^Invalid \S+ value\./.test(error && error.message);
  12749. if (isParseError) {
  12750. // `invalid.js: SyntaxError: Unexpected token (1:1)`.
  12751. context.logger.error(`${filename}: ${String(error)}`);
  12752. } else if (isValidationError || error instanceof errors.ConfigError) {
  12753. // `Invalid printWidth value. Expected an integer, but received 0.5.`
  12754. context.logger.error(error.message); // If validation fails for one file, it will fail for all of them.
  12755. process.exit(1);
  12756. } else if (error instanceof errors.DebugError) {
  12757. // `invalid.js: Some debug error message`
  12758. context.logger.error(`${filename}: ${error.message}`);
  12759. } else {
  12760. // `invalid.js: Error: Some unexpected error\n[stack trace]`
  12761. /* istanbul ignore next */
  12762. context.logger.error(filename + ": " + (error.stack || error));
  12763. } // Don't exit the process if one file failed
  12764. process.exitCode = 2;
  12765. }
  12766. function logResolvedConfigPathOrDie(context) {
  12767. const configFile = src.resolveConfigFile.sync(context.argv["find-config-path"]);
  12768. if (configFile) {
  12769. context.logger.log(path__default['default'].relative(process.cwd(), configFile));
  12770. } else {
  12771. process.exit(1);
  12772. }
  12773. }
  12774. function logFileInfoOrDie(context) {
  12775. const options = {
  12776. ignorePath: context.argv["ignore-path"],
  12777. withNodeModules: context.argv["with-node-modules"],
  12778. plugins: context.argv.plugin,
  12779. pluginSearchDirs: context.argv["plugin-search-dir"],
  12780. resolveConfig: context.argv.config !== false
  12781. };
  12782. context.logger.log(src.format(fastJsonStableStringify(src.getFileInfo.sync(context.argv["file-info"], options)), {
  12783. parser: "json"
  12784. }));
  12785. }
  12786. function writeOutput(context, result, options) {
  12787. // Don't use `console.log` here since it adds an extra newline at the end.
  12788. process.stdout.write(context.argv["debug-check"] ? result.filepath : result.formatted);
  12789. if (options && options.cursorOffset >= 0) {
  12790. process.stderr.write(result.cursorOffset + "\n");
  12791. }
  12792. }
  12793. function listDifferent(context, input, options, filename) {
  12794. if (!context.argv.check && !context.argv["list-different"]) {
  12795. return;
  12796. }
  12797. try {
  12798. if (!options.filepath && !options.parser) {
  12799. throw new errors.UndefinedParserError("No parser and no file path given, couldn't infer a parser.");
  12800. }
  12801. if (!src.check(input, options)) {
  12802. if (!context.argv.write) {
  12803. context.logger.log(filename);
  12804. process.exitCode = 1;
  12805. }
  12806. }
  12807. } catch (error) {
  12808. context.logger.error(error.message);
  12809. }
  12810. return true;
  12811. }
  12812. function format(context, input, opt) {
  12813. if (!opt.parser && !opt.filepath) {
  12814. throw new errors.UndefinedParserError("No parser and no file path given, couldn't infer a parser.");
  12815. }
  12816. if (context.argv["debug-print-doc"]) {
  12817. const doc = src.__debug.printToDoc(input, opt);
  12818. return {
  12819. formatted: src.__debug.formatDoc(doc)
  12820. };
  12821. }
  12822. if (context.argv["debug-check"]) {
  12823. const pp = src.format(input, opt);
  12824. const pppp = src.format(pp, opt);
  12825. if (pp !== pppp) {
  12826. throw new errors.DebugError("prettier(input) !== prettier(prettier(input))\n" + diff(pp, pppp));
  12827. } else {
  12828. const stringify = obj => JSON.stringify(obj, null, 2);
  12829. const ast = stringify(src.__debug.parse(input, opt,
  12830. /* massage */
  12831. true).ast);
  12832. const past = stringify(src.__debug.parse(pp, opt,
  12833. /* massage */
  12834. true).ast);
  12835. /* istanbul ignore next */
  12836. if (ast !== past) {
  12837. const MAX_AST_SIZE = 2097152; // 2MB
  12838. const astDiff = ast.length > MAX_AST_SIZE || past.length > MAX_AST_SIZE ? "AST diff too large to render" : diff(ast, past);
  12839. throw new errors.DebugError("ast(input) !== ast(prettier(input))\n" + astDiff + "\n" + diff(input, pp));
  12840. }
  12841. }
  12842. return {
  12843. formatted: pp,
  12844. filepath: opt.filepath || "(stdin)\n"
  12845. };
  12846. }
  12847. /* istanbul ignore next */
  12848. if (context.argv["debug-benchmark"]) {
  12849. let benchmark;
  12850. try {
  12851. benchmark = require("benchmark");
  12852. } catch (err) {
  12853. context.logger.debug("'--debug-benchmark' requires the 'benchmark' package to be installed.");
  12854. process.exit(2);
  12855. }
  12856. context.logger.debug("'--debug-benchmark' option found, measuring formatWithCursor with 'benchmark' module.");
  12857. const suite = new benchmark.Suite();
  12858. suite.add("format", () => {
  12859. src.formatWithCursor(input, opt);
  12860. }).on("cycle", event => {
  12861. const results = {
  12862. benchmark: String(event.target),
  12863. hz: event.target.hz,
  12864. ms: event.target.times.cycle * 1000
  12865. };
  12866. context.logger.debug("'--debug-benchmark' measurements for formatWithCursor: " + JSON.stringify(results, null, 2));
  12867. }).run({
  12868. async: false
  12869. });
  12870. } else if (context.argv["debug-repeat"] > 0) {
  12871. const repeat = context.argv["debug-repeat"];
  12872. context.logger.debug("'--debug-repeat' option found, running formatWithCursor " + repeat + " times."); // should be using `performance.now()`, but only `Date` is cross-platform enough
  12873. const now = Date.now ? () => Date.now() : () => +new Date();
  12874. let totalMs = 0;
  12875. for (let i = 0; i < repeat; ++i) {
  12876. const startMs = now();
  12877. src.formatWithCursor(input, opt);
  12878. totalMs += now() - startMs;
  12879. }
  12880. const averageMs = totalMs / repeat;
  12881. const results = {
  12882. repeat,
  12883. hz: 1000 / averageMs,
  12884. ms: averageMs
  12885. };
  12886. context.logger.debug("'--debug-repeat' measurements for formatWithCursor: " + JSON.stringify(results, null, 2));
  12887. }
  12888. return src.formatWithCursor(input, opt);
  12889. }
  12890. function getOptionsOrDie(context, filePath) {
  12891. try {
  12892. if (context.argv.config === false) {
  12893. context.logger.debug("'--no-config' option found, skip loading config file.");
  12894. return null;
  12895. }
  12896. context.logger.debug(context.argv.config ? `load config file from '${context.argv.config}'` : `resolve config from '${filePath}'`);
  12897. const options = src.resolveConfig.sync(filePath, {
  12898. editorconfig: context.argv.editorconfig,
  12899. config: context.argv.config
  12900. });
  12901. context.logger.debug("loaded options `" + JSON.stringify(options) + "`");
  12902. return options;
  12903. } catch (error) {
  12904. context.logger.error(`Invalid configuration file \`${filePath}\`: ` + error.message);
  12905. process.exit(2);
  12906. }
  12907. }
  12908. function getOptionsForFile(context, filepath) {
  12909. const options = getOptionsOrDie(context, filepath);
  12910. const hasPlugins = options && options.plugins;
  12911. if (hasPlugins) {
  12912. pushContextPlugins(context, options.plugins);
  12913. }
  12914. const appliedOptions = Object.assign({
  12915. filepath
  12916. }, applyConfigPrecedence(context, options && optionsNormalizer.normalizeApiOptions(options, context.supportOptions, {
  12917. logger: context.logger
  12918. })));
  12919. context.logger.debug(`applied config-precedence (${context.argv["config-precedence"]}): ` + `${JSON.stringify(appliedOptions)}`);
  12920. if (hasPlugins) {
  12921. popContextPlugins(context);
  12922. }
  12923. return appliedOptions;
  12924. }
  12925. function parseArgsToOptions(context, overrideDefaults) {
  12926. const minimistOptions = createMinimistOptions(context.detailedOptions);
  12927. const apiDetailedOptionMap = createApiDetailedOptionMap(context.detailedOptions);
  12928. return getOptions(optionsNormalizer.normalizeCliOptions(minimist_1(context.args, {
  12929. string: minimistOptions.string,
  12930. boolean: minimistOptions.boolean,
  12931. default: cliifyOptions(overrideDefaults, apiDetailedOptionMap)
  12932. }), context.detailedOptions, {
  12933. logger: false
  12934. }), context.detailedOptions);
  12935. }
  12936. function applyConfigPrecedence(context, options) {
  12937. try {
  12938. switch (context.argv["config-precedence"]) {
  12939. case "cli-override":
  12940. return parseArgsToOptions(context, options);
  12941. case "file-override":
  12942. return Object.assign({}, parseArgsToOptions(context), options);
  12943. case "prefer-file":
  12944. return options || parseArgsToOptions(context);
  12945. }
  12946. } catch (error) {
  12947. /* istanbul ignore next */
  12948. context.logger.error(error.toString());
  12949. /* istanbul ignore next */
  12950. process.exit(2);
  12951. }
  12952. }
  12953. function formatStdin(context) {
  12954. const filepath = context.argv["stdin-filepath"] ? path__default['default'].resolve(process.cwd(), context.argv["stdin-filepath"]) : process.cwd();
  12955. const ignorer = createIgnorerFromContextOrDie(context); // If there's an ignore-path set, the filename must be relative to the
  12956. // ignore path, not the current working directory.
  12957. const relativeFilepath = context.argv["ignore-path"] ? path__default['default'].relative(path__default['default'].dirname(context.argv["ignore-path"]), filepath) : path__default['default'].relative(process.cwd(), filepath);
  12958. getStream(process.stdin).then(input => {
  12959. if (relativeFilepath && ignorer.ignores(fixWindowsSlashes$1(relativeFilepath))) {
  12960. writeOutput(context, {
  12961. formatted: input
  12962. });
  12963. return;
  12964. }
  12965. const options = getOptionsForFile(context, filepath);
  12966. if (listDifferent(context, input, options, "(stdin)")) {
  12967. return;
  12968. }
  12969. writeOutput(context, format(context, input, options), options);
  12970. }).catch(error => {
  12971. handleError(context, relativeFilepath || "stdin", error);
  12972. });
  12973. }
  12974. function createIgnorerFromContextOrDie(context) {
  12975. try {
  12976. return createIgnorer.sync(context.argv["ignore-path"], context.argv["with-node-modules"]);
  12977. } catch (e) {
  12978. context.logger.error(e.message);
  12979. process.exit(2);
  12980. }
  12981. }
  12982. function formatFiles(context) {
  12983. // The ignorer will be used to filter file paths after the glob is checked,
  12984. // before any files are actually written
  12985. const ignorer = createIgnorerFromContextOrDie(context);
  12986. let numberOfUnformattedFilesFound = 0;
  12987. if (context.argv.check) {
  12988. context.logger.log("Checking formatting...");
  12989. }
  12990. for (const pathOrError of expandPatterns$1(context)) {
  12991. if (typeof pathOrError === "object") {
  12992. context.logger.error(pathOrError.error); // Don't exit, but set the exit code to 2
  12993. process.exitCode = 2;
  12994. continue;
  12995. }
  12996. const filename = pathOrError; // If there's an ignore-path set, the filename must be relative to the
  12997. // ignore path, not the current working directory.
  12998. const ignoreFilename = context.argv["ignore-path"] ? path__default['default'].relative(path__default['default'].dirname(context.argv["ignore-path"]), filename) : filename;
  12999. const fileIgnored = ignorer.ignores(fixWindowsSlashes$1(ignoreFilename));
  13000. if (fileIgnored && (context.argv["debug-check"] || context.argv.write || context.argv.check || context.argv["list-different"])) {
  13001. continue;
  13002. }
  13003. const options = Object.assign({}, getOptionsForFile(context, filename), {
  13004. filepath: filename
  13005. });
  13006. if (isTty()) {
  13007. context.logger.log(filename, {
  13008. newline: false
  13009. });
  13010. }
  13011. let input;
  13012. try {
  13013. input = fs__default['default'].readFileSync(filename, "utf8");
  13014. } catch (error) {
  13015. // Add newline to split errors from filename line.
  13016. /* istanbul ignore next */
  13017. context.logger.log("");
  13018. /* istanbul ignore next */
  13019. context.logger.error(`Unable to read file: ${filename}\n${error.message}`); // Don't exit the process if one file failed
  13020. /* istanbul ignore next */
  13021. process.exitCode = 2;
  13022. /* istanbul ignore next */
  13023. continue;
  13024. }
  13025. if (fileIgnored) {
  13026. writeOutput(context, {
  13027. formatted: input
  13028. }, options);
  13029. continue;
  13030. }
  13031. const start = Date.now();
  13032. let result;
  13033. let output;
  13034. try {
  13035. result = format(context, input, options);
  13036. output = result.formatted;
  13037. } catch (error) {
  13038. handleError(context, filename, error);
  13039. continue;
  13040. }
  13041. const isDifferent = output !== input;
  13042. if (isTty()) {
  13043. // Remove previously printed filename to log it with duration.
  13044. readline__default['default'].clearLine(process.stdout, 0);
  13045. readline__default['default'].cursorTo(process.stdout, 0, null);
  13046. }
  13047. if (context.argv.write) {
  13048. // Don't write the file if it won't change in order not to invalidate
  13049. // mtime based caches.
  13050. if (isDifferent) {
  13051. if (!context.argv.check && !context.argv["list-different"]) {
  13052. context.logger.log(`${filename} ${Date.now() - start}ms`);
  13053. }
  13054. try {
  13055. fs__default['default'].writeFileSync(filename, output, "utf8");
  13056. } catch (error) {
  13057. /* istanbul ignore next */
  13058. context.logger.error(`Unable to write file: ${filename}\n${error.message}`); // Don't exit the process if one file failed
  13059. /* istanbul ignore next */
  13060. process.exitCode = 2;
  13061. }
  13062. } else if (!context.argv.check && !context.argv["list-different"]) {
  13063. context.logger.log(`${source.grey(filename)} ${Date.now() - start}ms`);
  13064. }
  13065. } else if (context.argv["debug-check"]) {
  13066. /* istanbul ignore else */
  13067. if (result.filepath) {
  13068. context.logger.log(result.filepath);
  13069. } else {
  13070. process.exitCode = 2;
  13071. }
  13072. } else if (!context.argv.check && !context.argv["list-different"]) {
  13073. writeOutput(context, result, options);
  13074. }
  13075. if (isDifferent) {
  13076. if (context.argv.check) {
  13077. context.logger.warn(filename);
  13078. } else if (context.argv["list-different"]) {
  13079. context.logger.log(filename);
  13080. }
  13081. numberOfUnformattedFilesFound += 1;
  13082. }
  13083. } // Print check summary based on expected exit code
  13084. if (context.argv.check) {
  13085. if (numberOfUnformattedFilesFound === 0) {
  13086. context.logger.log("All matched files use Prettier code style!");
  13087. } else {
  13088. context.logger.warn(context.argv.write ? "Code style issues fixed in the above file(s)." : "Code style issues found in the above file(s). Forgot to run Prettier?");
  13089. }
  13090. } // Ensure non-zero exitCode when using --check/list-different is not combined with --write
  13091. if ((context.argv.check || context.argv["list-different"]) && numberOfUnformattedFilesFound > 0 && !process.exitCode && !context.argv.write) {
  13092. process.exitCode = 1;
  13093. }
  13094. }
  13095. function getOptionsWithOpposites(options) {
  13096. // Add --no-foo after --foo.
  13097. const optionsWithOpposites = options.map(option => [option.description ? option : null, option.oppositeDescription ? Object.assign({}, option, {
  13098. name: `no-${option.name}`,
  13099. type: "boolean",
  13100. description: option.oppositeDescription
  13101. }) : null]);
  13102. return flatten_1(optionsWithOpposites).filter(Boolean);
  13103. }
  13104. function createUsage(context) {
  13105. const options = getOptionsWithOpposites(context.detailedOptions).filter( // remove unnecessary option (e.g. `semi`, `color`, etc.), which is only used for --help <flag>
  13106. option => !(option.type === "boolean" && option.oppositeDescription && !option.name.startsWith("no-")));
  13107. const groupedOptions = groupBy_1(options, option => option.category);
  13108. const firstCategories = constant$1.categoryOrder.slice(0, -1);
  13109. const lastCategories = constant$1.categoryOrder.slice(-1);
  13110. const restCategories = Object.keys(groupedOptions).filter(category => !constant$1.categoryOrder.includes(category));
  13111. const allCategories = [...firstCategories, ...restCategories, ...lastCategories];
  13112. const optionsUsage = allCategories.map(category => {
  13113. const categoryOptions = groupedOptions[category].map(option => createOptionUsage(context, option, OPTION_USAGE_THRESHOLD)).join("\n");
  13114. return `${category} options:\n\n${indent(categoryOptions, 2)}`;
  13115. });
  13116. return [constant$1.usageSummary].concat(optionsUsage, [""]).join("\n\n");
  13117. }
  13118. function createOptionUsage(context, option, threshold) {
  13119. const header = createOptionUsageHeader(option);
  13120. const optionDefaultValue = getOptionDefaultValue(context, option.name);
  13121. return createOptionUsageRow(header, `${option.description}${optionDefaultValue === undefined ? "" : `\nDefaults to ${createDefaultValueDisplay(optionDefaultValue)}.`}`, threshold);
  13122. }
  13123. function createDefaultValueDisplay(value) {
  13124. return Array.isArray(value) ? `[${value.map(createDefaultValueDisplay).join(", ")}]` : value;
  13125. }
  13126. function createOptionUsageHeader(option) {
  13127. const name = `--${option.name}`;
  13128. const alias = option.alias ? `-${option.alias},` : null;
  13129. const type = createOptionUsageType(option);
  13130. return [alias, name, type].filter(Boolean).join(" ");
  13131. }
  13132. function createOptionUsageRow(header, content, threshold) {
  13133. const separator = header.length >= threshold ? `\n${" ".repeat(threshold)}` : " ".repeat(threshold - header.length);
  13134. const description = content.replace(/\n/g, `\n${" ".repeat(threshold)}`);
  13135. return `${header}${separator}${description}`;
  13136. }
  13137. function createOptionUsageType(option) {
  13138. switch (option.type) {
  13139. case "boolean":
  13140. return null;
  13141. case "choice":
  13142. return `<${option.choices.filter(choice => !choice.deprecated && choice.since !== null).map(choice => choice.value).join("|")}>`;
  13143. default:
  13144. return `<${option.type}>`;
  13145. }
  13146. }
  13147. function createChoiceUsages(choices, margin, indentation) {
  13148. const activeChoices = choices.filter(choice => !choice.deprecated && choice.since !== null);
  13149. const threshold = activeChoices.map(choice => choice.value.length).reduce((current, length) => Math.max(current, length), 0) + margin;
  13150. return activeChoices.map(choice => indent(createOptionUsageRow(choice.value, choice.description, threshold), indentation));
  13151. }
  13152. function createDetailedUsage(context, flag) {
  13153. const option = getOptionsWithOpposites(context.detailedOptions).find(option => option.name === flag || option.alias === flag);
  13154. const header = createOptionUsageHeader(option);
  13155. const description = `\n\n${indent(option.description, 2)}`;
  13156. const choices = option.type !== "choice" ? "" : `\n\nValid options:\n\n${createChoiceUsages(option.choices, CHOICE_USAGE_MARGIN, CHOICE_USAGE_INDENTATION).join("\n")}`;
  13157. const optionDefaultValue = getOptionDefaultValue(context, option.name);
  13158. const defaults = optionDefaultValue !== undefined ? `\n\nDefault: ${createDefaultValueDisplay(optionDefaultValue)}` : "";
  13159. const pluginDefaults = option.pluginDefaults && Object.keys(option.pluginDefaults).length ? `\nPlugin defaults:${Object.keys(option.pluginDefaults).map(key => `\n* ${key}: ${createDefaultValueDisplay(option.pluginDefaults[key])}`)}` : "";
  13160. return `${header}${description}${choices}${defaults}${pluginDefaults}`;
  13161. }
  13162. function getOptionDefaultValue(context, optionName) {
  13163. // --no-option
  13164. if (!(optionName in context.detailedOptionMap)) {
  13165. return;
  13166. }
  13167. const option = context.detailedOptionMap[optionName];
  13168. if (option.default !== undefined) {
  13169. return option.default;
  13170. }
  13171. const optionCamelName = camelcase(optionName);
  13172. if (optionCamelName in context.apiDefaultOptions) {
  13173. return context.apiDefaultOptions[optionCamelName];
  13174. }
  13175. }
  13176. function indent(str, spaces) {
  13177. return str.replace(/^/gm, " ".repeat(spaces));
  13178. }
  13179. function createLogger(logLevel) {
  13180. return {
  13181. warn: createLogFunc("warn", "yellow"),
  13182. error: createLogFunc("error", "red"),
  13183. debug: createLogFunc("debug", "blue"),
  13184. log: createLogFunc("log")
  13185. };
  13186. function createLogFunc(loggerName, color) {
  13187. if (!shouldLog(loggerName)) {
  13188. return () => {};
  13189. }
  13190. const prefix = color ? `[${source[color](loggerName)}] ` : "";
  13191. return function (message, opts) {
  13192. opts = Object.assign({
  13193. newline: true
  13194. }, opts);
  13195. const stream = process[loggerName === "log" ? "stdout" : "stderr"];
  13196. stream.write(message.replace(/^/gm, prefix) + (opts.newline ? "\n" : ""));
  13197. };
  13198. }
  13199. function shouldLog(loggerName) {
  13200. switch (logLevel) {
  13201. case "silent":
  13202. return false;
  13203. case "debug":
  13204. if (loggerName === "debug") {
  13205. return true;
  13206. }
  13207. // fall through
  13208. case "log":
  13209. if (loggerName === "log") {
  13210. return true;
  13211. }
  13212. // fall through
  13213. case "warn":
  13214. if (loggerName === "warn") {
  13215. return true;
  13216. }
  13217. // fall through
  13218. case "error":
  13219. return loggerName === "error";
  13220. }
  13221. }
  13222. }
  13223. function normalizeDetailedOption(name, option) {
  13224. return Object.assign({
  13225. category: coreOptions$1.CATEGORY_OTHER
  13226. }, option, {
  13227. choices: option.choices && option.choices.map(choice => {
  13228. const newChoice = Object.assign({
  13229. description: "",
  13230. deprecated: false
  13231. }, typeof choice === "object" ? choice : {
  13232. value: choice
  13233. });
  13234. /* istanbul ignore next */
  13235. if (newChoice.value === true) {
  13236. newChoice.value = ""; // backward compatibility for original boolean option
  13237. }
  13238. return newChoice;
  13239. })
  13240. });
  13241. }
  13242. function normalizeDetailedOptionMap(detailedOptionMap) {
  13243. return fromPairs_1(Object.entries(detailedOptionMap).sort(([leftName], [rightName]) => leftName.localeCompare(rightName)).map(([name, option]) => [name, normalizeDetailedOption(name, option)]));
  13244. }
  13245. function createMinimistOptions(detailedOptions) {
  13246. const [boolean, string] = partition_1(detailedOptions, ({
  13247. type
  13248. }) => type === "boolean").map(detailedOptions => flatten_1(detailedOptions.map(({
  13249. name,
  13250. alias
  13251. }) => alias ? [name, alias] : [name])));
  13252. const defaults = fromPairs_1(detailedOptions.filter(option => !option.deprecated && (!option.forwardToApi || option.name === "plugin" || option.name === "plugin-search-dir") && option.default !== undefined).map(option => [option.name, option.default]));
  13253. return {
  13254. // we use vnopts' AliasSchema to handle aliases for better error messages
  13255. alias: {},
  13256. boolean,
  13257. string,
  13258. default: defaults
  13259. };
  13260. }
  13261. function createApiDetailedOptionMap(detailedOptions) {
  13262. return fromPairs_1(detailedOptions.filter(option => option.forwardToApi && option.forwardToApi !== option.name).map(option => [option.forwardToApi, option]));
  13263. }
  13264. function createDetailedOptionMap(supportOptions) {
  13265. return fromPairs_1(supportOptions.map(option => {
  13266. const newOption = Object.assign({}, option, {
  13267. name: option.cliName || dashify(option.name),
  13268. description: option.cliDescription || option.description,
  13269. category: option.cliCategory || coreOptions$1.CATEGORY_FORMAT,
  13270. forwardToApi: option.name
  13271. });
  13272. /* istanbul ignore next */
  13273. if (option.deprecated) {
  13274. delete newOption.forwardToApi;
  13275. delete newOption.description;
  13276. delete newOption.oppositeDescription;
  13277. newOption.deprecated = true;
  13278. }
  13279. return [newOption.name, newOption];
  13280. }));
  13281. } //-----------------------------context-util-start-------------------------------
  13282. /**
  13283. * @typedef {Object} Context
  13284. * @property logger
  13285. * @property {string[]} args
  13286. * @property argv
  13287. * @property {string[]} filePatterns
  13288. * @property {any[]} supportOptions
  13289. * @property detailedOptions
  13290. * @property detailedOptionMap
  13291. * @property apiDefaultOptions
  13292. * @property languages
  13293. * @property {Partial<Context>[]} stack
  13294. */
  13295. /** @returns {Context} */
  13296. function createContext(args) {
  13297. const context = {
  13298. args,
  13299. stack: []
  13300. };
  13301. updateContextArgv(context);
  13302. normalizeContextArgv(context, ["loglevel", "plugin", "plugin-search-dir"]);
  13303. context.logger = createLogger(context.argv.loglevel);
  13304. updateContextArgv(context, context.argv.plugin, context.argv["plugin-search-dir"]);
  13305. return (
  13306. /** @type {Context} */
  13307. context
  13308. );
  13309. }
  13310. function initContext(context) {
  13311. // split into 2 step so that we could wrap this in a `try..catch` in cli/index.js
  13312. normalizeContextArgv(context);
  13313. }
  13314. /**
  13315. * @param {Context} context
  13316. * @param {string[]} plugins
  13317. * @param {string[]=} pluginSearchDirs
  13318. */
  13319. function updateContextOptions(context, plugins, pluginSearchDirs) {
  13320. const {
  13321. options: supportOptions,
  13322. languages
  13323. } = src.getSupportInfo({
  13324. showDeprecated: true,
  13325. showUnreleased: true,
  13326. showInternal: true,
  13327. plugins,
  13328. pluginSearchDirs
  13329. });
  13330. const detailedOptionMap = normalizeDetailedOptionMap(Object.assign({}, createDetailedOptionMap(supportOptions), constant$1.options));
  13331. const detailedOptions = arrayify(detailedOptionMap, "name");
  13332. const apiDefaultOptions = Object.assign({}, optionsModule.hiddenDefaults, fromPairs_1(supportOptions.filter(({
  13333. deprecated
  13334. }) => !deprecated).map(option => [option.name, option.default])));
  13335. Object.assign(context, {
  13336. supportOptions,
  13337. detailedOptions,
  13338. detailedOptionMap,
  13339. apiDefaultOptions,
  13340. languages
  13341. });
  13342. }
  13343. /**
  13344. * @param {Context} context
  13345. * @param {string[]} plugins
  13346. * @param {string[]=} pluginSearchDirs
  13347. */
  13348. function pushContextPlugins(context, plugins, pluginSearchDirs) {
  13349. context.stack.push(pick_1(context, ["supportOptions", "detailedOptions", "detailedOptionMap", "apiDefaultOptions", "languages"]));
  13350. updateContextOptions(context, plugins, pluginSearchDirs);
  13351. }
  13352. /**
  13353. * @param {Context} context
  13354. */
  13355. function popContextPlugins(context) {
  13356. Object.assign(context, context.stack.pop());
  13357. }
  13358. function updateContextArgv(context, plugins, pluginSearchDirs) {
  13359. pushContextPlugins(context, plugins, pluginSearchDirs);
  13360. const minimistOptions = createMinimistOptions(context.detailedOptions);
  13361. const argv = minimist_1(context.args, minimistOptions);
  13362. context.argv = argv;
  13363. context.filePatterns = argv._;
  13364. }
  13365. function normalizeContextArgv(context, keys) {
  13366. const detailedOptions = !keys ? context.detailedOptions : context.detailedOptions.filter(option => keys.includes(option.name));
  13367. const argv = !keys ? context.argv : pick_1(context.argv, keys);
  13368. context.argv = optionsNormalizer.normalizeCliOptions(argv, detailedOptions, {
  13369. logger: context.logger
  13370. });
  13371. } //------------------------------context-util-end--------------------------------
  13372. var util$1 = {
  13373. createContext,
  13374. createDetailedOptionMap,
  13375. createDetailedUsage,
  13376. createUsage,
  13377. format,
  13378. formatFiles,
  13379. formatStdin,
  13380. initContext,
  13381. logResolvedConfigPathOrDie,
  13382. logFileInfoOrDie,
  13383. normalizeDetailedOptionMap
  13384. };
  13385. var require$$1 = getCjsExportFromNamespace(_package$1);
  13386. pleaseUpgradeNode(require$$1); // eslint-disable-next-line no-restricted-modules
  13387. function run(args) {
  13388. const context = util$1.createContext(args);
  13389. try {
  13390. util$1.initContext(context);
  13391. context.logger.debug(`normalized argv: ${JSON.stringify(context.argv)}`);
  13392. if (context.argv.check && context.argv["list-different"]) {
  13393. context.logger.error("Cannot use --check and --list-different together.");
  13394. process.exit(1);
  13395. }
  13396. if (context.argv.write && context.argv["debug-check"]) {
  13397. context.logger.error("Cannot use --write and --debug-check together.");
  13398. process.exit(1);
  13399. }
  13400. if (context.argv["find-config-path"] && context.filePatterns.length) {
  13401. context.logger.error("Cannot use --find-config-path with multiple files");
  13402. process.exit(1);
  13403. }
  13404. if (context.argv["file-info"] && context.filePatterns.length) {
  13405. context.logger.error("Cannot use --file-info with multiple files");
  13406. process.exit(1);
  13407. }
  13408. if (context.argv.version) {
  13409. context.logger.log(src.version);
  13410. process.exit(0);
  13411. }
  13412. if (context.argv.help !== undefined) {
  13413. context.logger.log(typeof context.argv.help === "string" && context.argv.help !== "" ? util$1.createDetailedUsage(context, context.argv.help) : util$1.createUsage(context));
  13414. process.exit(0);
  13415. }
  13416. if (context.argv["support-info"]) {
  13417. context.logger.log(src.format(fastJsonStableStringify(src.getSupportInfo()), {
  13418. parser: "json"
  13419. }));
  13420. process.exit(0);
  13421. }
  13422. const hasFilePatterns = context.filePatterns.length !== 0;
  13423. const useStdin = !hasFilePatterns && (!process.stdin.isTTY || context.args["stdin-filepath"]);
  13424. if (context.argv["find-config-path"]) {
  13425. util$1.logResolvedConfigPathOrDie(context);
  13426. } else if (context.argv["file-info"]) {
  13427. util$1.logFileInfoOrDie(context);
  13428. } else if (useStdin) {
  13429. util$1.formatStdin(context);
  13430. } else if (hasFilePatterns) {
  13431. util$1.formatFiles(context);
  13432. } else {
  13433. context.logger.log(util$1.createUsage(context));
  13434. process.exit(1);
  13435. }
  13436. } catch (error) {
  13437. context.logger.error(error.message);
  13438. process.exit(1);
  13439. }
  13440. }
  13441. var cli = {
  13442. run
  13443. };
  13444. cli.run(process.argv.slice(2));