1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492 |
- #!/usr/bin/env node
- 'use strict';
- function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
- var fs = _interopDefault(require('fs'));
- var os = _interopDefault(require('os'));
- var path = _interopDefault(require('path'));
- var assert = _interopDefault(require('assert'));
- var util = _interopDefault(require('util'));
- var events = _interopDefault(require('events'));
- var thirdParty = require('./third-party');
- var thirdParty__default = thirdParty['default'];
- var readline = _interopDefault(require('readline'));
- var name = "prettier";
- var version$1 = "1.16.3";
- var description = "Prettier is an opinionated code formatter";
- var bin = {
- "prettier": "./bin/prettier.js"
- };
- var repository = "prettier/prettier";
- var homepage = "https://prettier.io";
- var author = "James Long";
- var license = "MIT";
- var main = "./index.js";
- var engines = {
- "node": ">=6"
- };
- var dependencies = {
- "@angular/compiler": "6.1.10",
- "@babel/code-frame": "7.0.0-beta.46",
- "@babel/parser": "7.2.0",
- "@glimmer/syntax": "0.30.3",
- "@iarna/toml": "2.0.0",
- "angular-estree-parser": "1.1.5",
- "angular-html-parser": "1.2.0",
- "camelcase": "4.1.0",
- "chalk": "2.1.0",
- "cjk-regex": "2.0.0",
- "cosmiconfig": "5.0.7",
- "dashify": "0.2.2",
- "dedent": "0.7.0",
- "diff": "3.2.0",
- "editorconfig": "0.15.2",
- "editorconfig-to-prettier": "0.1.1",
- "escape-string-regexp": "1.0.5",
- "esutils": "2.0.2",
- "find-parent-dir": "0.3.0",
- "find-project-root": "1.1.1",
- "flow-parser": "0.84.0",
- "get-stream": "3.0.0",
- "globby": "6.1.0",
- "graphql": "0.13.2",
- "html-element-attributes": "2.0.0",
- "html-styles": "1.0.0",
- "html-tag-names": "1.1.2",
- "ignore": "3.3.7",
- "is-ci": "2.0.0",
- "jest-docblock": "23.2.0",
- "json-stable-stringify": "1.0.1",
- "leven": "2.1.0",
- "lines-and-columns": "1.1.6",
- "linguist-languages": "6.2.1-dev.20180706",
- "lodash.uniqby": "4.7.0",
- "mem": "1.1.0",
- "minimatch": "3.0.4",
- "minimist": "1.2.0",
- "n-readlines": "1.0.0",
- "normalize-path": "3.0.0",
- "parse-srcset": "ikatyang/parse-srcset#54eb9c1cb21db5c62b4d0e275d7249516df6f0ee",
- "postcss-less": "1.1.5",
- "postcss-media-query-parser": "0.2.3",
- "postcss-scss": "2.0.0",
- "postcss-selector-parser": "2.2.3",
- "postcss-values-parser": "1.5.0",
- "regexp-util": "1.2.2",
- "remark-math": "1.0.4",
- "remark-parse": "5.0.0",
- "resolve": "1.5.0",
- "semver": "5.4.1",
- "string-width": "3.0.0",
- "typescript": "3.2.2",
- "typescript-estree": "18.0.0",
- "unicode-regex": "2.0.0",
- "unified": "6.1.6",
- "vnopts": "1.0.2",
- "yaml": "1.0.2",
- "yaml-unist-parser": "1.0.0"
- };
- var devDependencies = {
- "@babel/cli": "7.2.0",
- "@babel/core": "7.2.0",
- "@babel/preset-env": "7.2.0",
- "babel-loader": "8.0.4",
- "benchmark": "2.1.4",
- "builtin-modules": "2.0.0",
- "codecov": "codecov/codecov-node#e427d900309adb50746a39a50aa7d80071a5ddd0",
- "cross-env": "5.0.5",
- "eslint": "4.18.2",
- "eslint-config-prettier": "2.9.0",
- "eslint-friendly-formatter": "3.0.0",
- "eslint-plugin-import": "2.9.0",
- "eslint-plugin-prettier": "2.6.0",
- "eslint-plugin-react": "7.7.0",
- "execa": "0.10.0",
- "jest": "23.3.0",
- "jest-junit": "5.0.0",
- "jest-snapshot-serializer-ansi": "1.0.0",
- "jest-snapshot-serializer-raw": "1.1.0",
- "jest-watch-typeahead": "0.1.0",
- "mkdirp": "0.5.1",
- "prettier": "1.16.2",
- "prettylint": "1.0.0",
- "rimraf": "2.6.2",
- "rollup": "0.47.6",
- "rollup-plugin-alias": "1.4.0",
- "rollup-plugin-babel": "4.0.0-beta.4",
- "rollup-plugin-commonjs": "8.2.6",
- "rollup-plugin-json": "2.1.1",
- "rollup-plugin-node-builtins": "2.0.0",
- "rollup-plugin-node-globals": "1.1.0",
- "rollup-plugin-node-resolve": "2.0.0",
- "rollup-plugin-replace": "1.2.1",
- "rollup-plugin-uglify": "3.0.0",
- "shelljs": "0.8.1",
- "snapshot-diff": "0.4.0",
- "strip-ansi": "4.0.0",
- "tempy": "0.2.1",
- "webpack": "3.12.0"
- };
- var resolutions = {
- "@babel/code-frame": "7.0.0-beta.46"
- };
- var scripts = {
- "prepublishOnly": "echo \"Error: must publish from dist/\" && exit 1",
- "prepare-release": "yarn && yarn build && yarn test:dist",
- "test": "jest",
- "test:dist": "node ./scripts/test-dist.js",
- "test-integration": "jest tests_integration",
- "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",
- "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",
- "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",
- "lint": "cross-env EFF_NO_LINK_RULES=true eslint . --format node_modules/eslint-friendly-formatter",
- "lint-docs": "prettylint {.,docs,website,website/blog}/*.md",
- "lint-dist": "eslint --no-eslintrc --no-ignore --env=browser \"dist/!(bin-prettier|index|third-party).js\"",
- "build": "node --max-old-space-size=2048 ./scripts/build/build.js",
- "build-docs": "node ./scripts/build-docs.js",
- "check-deps": "node ./scripts/check-deps.js"
- };
- var _package = {
- name: name,
- version: version$1,
- description: description,
- bin: bin,
- repository: repository,
- homepage: homepage,
- author: author,
- license: license,
- main: main,
- engines: engines,
- dependencies: dependencies,
- devDependencies: devDependencies,
- resolutions: resolutions,
- scripts: scripts
- };
- var _package$1 = Object.freeze({
- name: name,
- version: version$1,
- description: description,
- bin: bin,
- repository: repository,
- homepage: homepage,
- author: author,
- license: license,
- main: main,
- engines: engines,
- dependencies: dependencies,
- devDependencies: devDependencies,
- resolutions: resolutions,
- scripts: scripts,
- default: _package
- });
- var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
- function unwrapExports (x) {
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
- }
- function createCommonjsModule(fn, module) {
- return module = { exports: {} }, fn(module, module.exports), module.exports;
- }
- var base = createCommonjsModule(function (module, exports) {
- /*istanbul ignore start*/
- 'use strict';
- exports.__esModule = true;
- exports['default'] =
- /*istanbul ignore end*/
- Diff;
- function Diff() {}
- Diff.prototype = {
- /*istanbul ignore start*/
- /*istanbul ignore end*/
- diff: function diff(oldString, newString) {
- /*istanbul ignore start*/
- var
- /*istanbul ignore end*/
- options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
- var callback = options.callback;
- if (typeof options === 'function') {
- callback = options;
- options = {};
- }
- this.options = options;
- var self = this;
- function done(value) {
- if (callback) {
- setTimeout(function () {
- callback(undefined, value);
- }, 0);
- return true;
- } else {
- return value;
- }
- } // Allow subclasses to massage the input prior to running
- oldString = this.castInput(oldString);
- newString = this.castInput(newString);
- oldString = this.removeEmpty(this.tokenize(oldString));
- newString = this.removeEmpty(this.tokenize(newString));
- var newLen = newString.length,
- oldLen = oldString.length;
- var editLength = 1;
- var maxEditLength = newLen + oldLen;
- var bestPath = [{
- newPos: -1,
- components: []
- }]; // Seed editLength = 0, i.e. the content starts with the same values
- var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
- if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
- // Identity per the equality and tokenizer
- return done([{
- value: this.join(newString),
- count: newString.length
- }]);
- } // Main worker method. checks all permutations of a given edit length for acceptance.
- function execEditLength() {
- for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
- var basePath =
- /*istanbul ignore start*/
- void 0;
- var addPath = bestPath[diagonalPath - 1],
- removePath = bestPath[diagonalPath + 1],
- _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
- if (addPath) {
- // No one else is going to attempt to use this value, clear it
- bestPath[diagonalPath - 1] = undefined;
- }
- var canAdd = addPath && addPath.newPos + 1 < newLen,
- canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen;
- if (!canAdd && !canRemove) {
- // If this path is a terminal then prune
- bestPath[diagonalPath] = undefined;
- continue;
- } // Select the diagonal that we want to branch from. We select the prior
- // path whose position in the new string is the farthest from the origin
- // and does not pass the bounds of the diff graph
- if (!canAdd || canRemove && addPath.newPos < removePath.newPos) {
- basePath = clonePath(removePath);
- self.pushComponent(basePath.components, undefined, true);
- } else {
- basePath = addPath; // No need to clone, we've pulled it from the list
- basePath.newPos++;
- self.pushComponent(basePath.components, true, undefined);
- }
- _oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath); // If we have hit the end of both strings, then we are done
- if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) {
- return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken));
- } else {
- // Otherwise track this path as a potential candidate and continue.
- bestPath[diagonalPath] = basePath;
- }
- }
- editLength++;
- } // Performs the length of edit iteration. Is a bit fugly as this has to support the
- // sync and async mode which is never fun. Loops over execEditLength until a value
- // is produced.
- if (callback) {
- (function exec() {
- setTimeout(function () {
- // This should not happen, but we want to be safe.
- /* istanbul ignore next */
- if (editLength > maxEditLength) {
- return callback();
- }
- if (!execEditLength()) {
- exec();
- }
- }, 0);
- })();
- } else {
- while (editLength <= maxEditLength) {
- var ret = execEditLength();
- if (ret) {
- return ret;
- }
- }
- }
- },
- /*istanbul ignore start*/
- /*istanbul ignore end*/
- pushComponent: function pushComponent(components, added, removed) {
- var last = components[components.length - 1];
- if (last && last.added === added && last.removed === removed) {
- // We need to clone here as the component clone operation is just
- // as shallow array clone
- components[components.length - 1] = {
- count: last.count + 1,
- added: added,
- removed: removed
- };
- } else {
- components.push({
- count: 1,
- added: added,
- removed: removed
- });
- }
- },
- /*istanbul ignore start*/
- /*istanbul ignore end*/
- extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) {
- var newLen = newString.length,
- oldLen = oldString.length,
- newPos = basePath.newPos,
- oldPos = newPos - diagonalPath,
- commonCount = 0;
- while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) {
- newPos++;
- oldPos++;
- commonCount++;
- }
- if (commonCount) {
- basePath.components.push({
- count: commonCount
- });
- }
- basePath.newPos = newPos;
- return oldPos;
- },
- /*istanbul ignore start*/
- /*istanbul ignore end*/
- equals: function equals(left, right) {
- return left === right;
- },
- /*istanbul ignore start*/
- /*istanbul ignore end*/
- removeEmpty: function removeEmpty(array) {
- var ret = [];
- for (var i = 0; i < array.length; i++) {
- if (array[i]) {
- ret.push(array[i]);
- }
- }
- return ret;
- },
- /*istanbul ignore start*/
- /*istanbul ignore end*/
- castInput: function castInput(value) {
- return value;
- },
- /*istanbul ignore start*/
- /*istanbul ignore end*/
- tokenize: function tokenize(value) {
- return value.split('');
- },
- /*istanbul ignore start*/
- /*istanbul ignore end*/
- join: function join(chars) {
- return chars.join('');
- }
- };
- function buildValues(diff, components, newString, oldString, useLongestToken) {
- var componentPos = 0,
- componentLen = components.length,
- newPos = 0,
- oldPos = 0;
- for (; componentPos < componentLen; componentPos++) {
- var component = components[componentPos];
- if (!component.removed) {
- if (!component.added && useLongestToken) {
- var value = newString.slice(newPos, newPos + component.count);
- value = value.map(function (value, i) {
- var oldValue = oldString[oldPos + i];
- return oldValue.length > value.length ? oldValue : value;
- });
- component.value = diff.join(value);
- } else {
- component.value = diff.join(newString.slice(newPos, newPos + component.count));
- }
- newPos += component.count; // Common case
- if (!component.added) {
- oldPos += component.count;
- }
- } else {
- component.value = diff.join(oldString.slice(oldPos, oldPos + component.count));
- oldPos += component.count; // Reverse add and remove so removes are output first to match common convention
- // The diffing algorithm is tied to add then remove output and this is the simplest
- // route to get the desired output with minimal overhead.
- if (componentPos && components[componentPos - 1].added) {
- var tmp = components[componentPos - 1];
- components[componentPos - 1] = components[componentPos];
- components[componentPos] = tmp;
- }
- }
- } // Special case handle for when one terminal is ignored. For this case we merge the
- // terminal into the prior string and drop the change.
- var lastComponent = components[componentLen - 1];
- if (componentLen > 1 && (lastComponent.added || lastComponent.removed) && diff.equals('', lastComponent.value)) {
- components[componentLen - 2].value += lastComponent.value;
- components.pop();
- }
- return components;
- }
- function clonePath(path$$1) {
- return {
- newPos: path$$1.newPos,
- components: path$$1.components.slice(0)
- };
- }
- });
- unwrapExports(base);
- var character = createCommonjsModule(function (module, exports) {
- /*istanbul ignore start*/
- 'use strict';
- exports.__esModule = true;
- exports.characterDiff = undefined;
- exports.
- /*istanbul ignore end*/
- diffChars = diffChars;
- /*istanbul ignore start*/
- var _base2 = _interopRequireDefault(base);
- function _interopRequireDefault(obj) {
- return obj && obj.__esModule ? obj : {
- 'default': obj
- };
- }
- /*istanbul ignore end*/
- var characterDiff =
- /*istanbul ignore start*/
- exports.
- /*istanbul ignore end*/
- characterDiff = new
- /*istanbul ignore start*/
- _base2['default']();
- function diffChars(oldStr, newStr, callback) {
- return characterDiff.diff(oldStr, newStr, callback);
- }
- });
- unwrapExports(character);
- var params = createCommonjsModule(function (module, exports) {
- /*istanbul ignore start*/
- 'use strict';
- exports.__esModule = true;
- exports.
- /*istanbul ignore end*/
- generateOptions = generateOptions;
- function generateOptions(options, defaults) {
- if (typeof options === 'function') {
- defaults.callback = options;
- } else if (options) {
- for (var name in options) {
- /* istanbul ignore else */
- if (options.hasOwnProperty(name)) {
- defaults[name] = options[name];
- }
- }
- }
- return defaults;
- }
- });
- unwrapExports(params);
- var word = createCommonjsModule(function (module, exports) {
- /*istanbul ignore start*/
- 'use strict';
- exports.__esModule = true;
- exports.wordDiff = undefined;
- exports.
- /*istanbul ignore end*/
- diffWords = diffWords;
- /*istanbul ignore start*/
- exports.
- /*istanbul ignore end*/
- diffWordsWithSpace = diffWordsWithSpace;
- /*istanbul ignore start*/
- var _base2 = _interopRequireDefault(base);
- /*istanbul ignore end*/
- /*istanbul ignore start*/
- function _interopRequireDefault(obj) {
- return obj && obj.__esModule ? obj : {
- 'default': obj
- };
- }
- /*istanbul ignore end*/
- // Based on https://en.wikipedia.org/wiki/Latin_script_in_Unicode
- //
- // Ranges and exceptions:
- // Latin-1 Supplement, 0080–00FF
- // - U+00D7 × Multiplication sign
- // - U+00F7 ÷ Division sign
- // Latin Extended-A, 0100–017F
- // Latin Extended-B, 0180–024F
- // IPA Extensions, 0250–02AF
- // Spacing Modifier Letters, 02B0–02FF
- // - U+02C7 ˇ ˇ Caron
- // - U+02D8 ˘ ˘ Breve
- // - U+02D9 ˙ ˙ Dot Above
- // - U+02DA ˚ ˚ Ring Above
- // - U+02DB ˛ ˛ Ogonek
- // - U+02DC ˜ ˜ Small Tilde
- // - U+02DD ˝ ˝ Double Acute Accent
- // Latin Extended Additional, 1E00–1EFF
- var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/;
- var reWhitespace = /\S/;
- var wordDiff =
- /*istanbul ignore start*/
- exports.
- /*istanbul ignore end*/
- wordDiff = new
- /*istanbul ignore start*/
- _base2['default']();
- wordDiff.equals = function (left, right) {
- return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right);
- };
- wordDiff.tokenize = function (value) {
- 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.
- for (var i = 0; i < tokens.length - 1; i++) {
- // If we have an empty string in the next field and we have only word chars before and after, merge
- if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) {
- tokens[i] += tokens[i + 2];
- tokens.splice(i + 1, 2);
- i--;
- }
- }
- return tokens;
- };
- function diffWords(oldStr, newStr, callback) {
- var options =
- /*istanbul ignore start*/
- (0, params.generateOptions
- /*istanbul ignore end*/
- )(callback, {
- ignoreWhitespace: true
- });
- return wordDiff.diff(oldStr, newStr, options);
- }
- function diffWordsWithSpace(oldStr, newStr, callback) {
- return wordDiff.diff(oldStr, newStr, callback);
- }
- });
- unwrapExports(word);
- var line = createCommonjsModule(function (module, exports) {
- /*istanbul ignore start*/
- 'use strict';
- exports.__esModule = true;
- exports.lineDiff = undefined;
- exports.
- /*istanbul ignore end*/
- diffLines = diffLines;
- /*istanbul ignore start*/
- exports.
- /*istanbul ignore end*/
- diffTrimmedLines = diffTrimmedLines;
- /*istanbul ignore start*/
- var _base2 = _interopRequireDefault(base);
- /*istanbul ignore end*/
- /*istanbul ignore start*/
- function _interopRequireDefault(obj) {
- return obj && obj.__esModule ? obj : {
- 'default': obj
- };
- }
- /*istanbul ignore end*/
- var lineDiff =
- /*istanbul ignore start*/
- exports.
- /*istanbul ignore end*/
- lineDiff = new
- /*istanbul ignore start*/
- _base2['default']();
- lineDiff.tokenize = function (value) {
- var retLines = [],
- linesAndNewlines = value.split(/(\n|\r\n)/); // Ignore the final empty token that occurs if the string ends with a new line
- if (!linesAndNewlines[linesAndNewlines.length - 1]) {
- linesAndNewlines.pop();
- } // Merge the content and line separators into single tokens
- for (var i = 0; i < linesAndNewlines.length; i++) {
- var line = linesAndNewlines[i];
- if (i % 2 && !this.options.newlineIsToken) {
- retLines[retLines.length - 1] += line;
- } else {
- if (this.options.ignoreWhitespace) {
- line = line.trim();
- }
- retLines.push(line);
- }
- }
- return retLines;
- };
- function diffLines(oldStr, newStr, callback) {
- return lineDiff.diff(oldStr, newStr, callback);
- }
- function diffTrimmedLines(oldStr, newStr, callback) {
- var options =
- /*istanbul ignore start*/
- (0, params.generateOptions
- /*istanbul ignore end*/
- )(callback, {
- ignoreWhitespace: true
- });
- return lineDiff.diff(oldStr, newStr, options);
- }
- });
- unwrapExports(line);
- var sentence = createCommonjsModule(function (module, exports) {
- /*istanbul ignore start*/
- 'use strict';
- exports.__esModule = true;
- exports.sentenceDiff = undefined;
- exports.
- /*istanbul ignore end*/
- diffSentences = diffSentences;
- /*istanbul ignore start*/
- var _base2 = _interopRequireDefault(base);
- function _interopRequireDefault(obj) {
- return obj && obj.__esModule ? obj : {
- 'default': obj
- };
- }
- /*istanbul ignore end*/
- var sentenceDiff =
- /*istanbul ignore start*/
- exports.
- /*istanbul ignore end*/
- sentenceDiff = new
- /*istanbul ignore start*/
- _base2['default']();
- sentenceDiff.tokenize = function (value) {
- return value.split(/(\S.+?[.!?])(?=\s+|$)/);
- };
- function diffSentences(oldStr, newStr, callback) {
- return sentenceDiff.diff(oldStr, newStr, callback);
- }
- });
- unwrapExports(sentence);
- var css = createCommonjsModule(function (module, exports) {
- /*istanbul ignore start*/
- 'use strict';
- exports.__esModule = true;
- exports.cssDiff = undefined;
- exports.
- /*istanbul ignore end*/
- diffCss = diffCss;
- /*istanbul ignore start*/
- var _base2 = _interopRequireDefault(base);
- function _interopRequireDefault(obj) {
- return obj && obj.__esModule ? obj : {
- 'default': obj
- };
- }
- /*istanbul ignore end*/
- var cssDiff =
- /*istanbul ignore start*/
- exports.
- /*istanbul ignore end*/
- cssDiff = new
- /*istanbul ignore start*/
- _base2['default']();
- cssDiff.tokenize = function (value) {
- return value.split(/([{}:;,]|\s+)/);
- };
- function diffCss(oldStr, newStr, callback) {
- return cssDiff.diff(oldStr, newStr, callback);
- }
- });
- unwrapExports(css);
- var json = createCommonjsModule(function (module, exports) {
- /*istanbul ignore start*/
- 'use strict';
- exports.__esModule = true;
- exports.jsonDiff = undefined;
- var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
- return typeof obj;
- } : function (obj) {
- return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj;
- };
- exports.
- /*istanbul ignore end*/
- diffJson = diffJson;
- /*istanbul ignore start*/
- exports.
- /*istanbul ignore end*/
- canonicalize = canonicalize;
- /*istanbul ignore start*/
- var _base2 = _interopRequireDefault(base);
- /*istanbul ignore end*/
- /*istanbul ignore start*/
- function _interopRequireDefault(obj) {
- return obj && obj.__esModule ? obj : {
- 'default': obj
- };
- }
- /*istanbul ignore end*/
- var objectPrototypeToString = Object.prototype.toString;
- var jsonDiff =
- /*istanbul ignore start*/
- exports.
- /*istanbul ignore end*/
- jsonDiff = new
- /*istanbul ignore start*/
- _base2['default'](); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a
- // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output:
- jsonDiff.useLongestToken = true;
- jsonDiff.tokenize =
- /*istanbul ignore start*/
- line.lineDiff.
- /*istanbul ignore end*/
- tokenize;
- jsonDiff.castInput = function (value) {
- /*istanbul ignore start*/
- var
- /*istanbul ignore end*/
- undefinedReplacement = this.options.undefinedReplacement;
- return typeof value === 'string' ? value : JSON.stringify(canonicalize(value), function (k, v) {
- if (typeof v === 'undefined') {
- return undefinedReplacement;
- }
- return v;
- }, ' ');
- };
- jsonDiff.equals = function (left, right) {
- return (
- /*istanbul ignore start*/
- _base2['default'].
- /*istanbul ignore end*/
- prototype.equals(left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1'))
- );
- };
- function diffJson(oldObj, newObj, options) {
- return jsonDiff.diff(oldObj, newObj, options);
- } // This function handles the presence of circular references by bailing out when encountering an
- // object that is already on the "stack" of items being processed.
- function canonicalize(obj, stack, replacementStack) {
- stack = stack || [];
- replacementStack = replacementStack || [];
- var i =
- /*istanbul ignore start*/
- void 0;
- for (i = 0; i < stack.length; i += 1) {
- if (stack[i] === obj) {
- return replacementStack[i];
- }
- }
- var canonicalizedObj =
- /*istanbul ignore start*/
- void 0;
- if ('[object Array]' === objectPrototypeToString.call(obj)) {
- stack.push(obj);
- canonicalizedObj = new Array(obj.length);
- replacementStack.push(canonicalizedObj);
- for (i = 0; i < obj.length; i += 1) {
- canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack);
- }
- stack.pop();
- replacementStack.pop();
- return canonicalizedObj;
- }
- if (obj && obj.toJSON) {
- obj = obj.toJSON();
- }
- if (
- /*istanbul ignore start*/
- (typeof
- /*istanbul ignore end*/
- obj === 'undefined' ? 'undefined' : _typeof(obj)) === 'object' && obj !== null) {
- stack.push(obj);
- canonicalizedObj = {};
- replacementStack.push(canonicalizedObj);
- var sortedKeys = [],
- key =
- /*istanbul ignore start*/
- void 0;
- for (key in obj) {
- /* istanbul ignore else */
- if (obj.hasOwnProperty(key)) {
- sortedKeys.push(key);
- }
- }
- sortedKeys.sort();
- for (i = 0; i < sortedKeys.length; i += 1) {
- key = sortedKeys[i];
- canonicalizedObj[key] = canonicalize(obj[key], stack, replacementStack);
- }
- stack.pop();
- replacementStack.pop();
- } else {
- canonicalizedObj = obj;
- }
- return canonicalizedObj;
- }
- });
- unwrapExports(json);
- var array = createCommonjsModule(function (module, exports) {
- /*istanbul ignore start*/
- 'use strict';
- exports.__esModule = true;
- exports.arrayDiff = undefined;
- exports.
- /*istanbul ignore end*/
- diffArrays = diffArrays;
- /*istanbul ignore start*/
- var _base2 = _interopRequireDefault(base);
- function _interopRequireDefault(obj) {
- return obj && obj.__esModule ? obj : {
- 'default': obj
- };
- }
- /*istanbul ignore end*/
- var arrayDiff =
- /*istanbul ignore start*/
- exports.
- /*istanbul ignore end*/
- arrayDiff = new
- /*istanbul ignore start*/
- _base2['default']();
- arrayDiff.tokenize = arrayDiff.join = function (value) {
- return value.slice();
- };
- function diffArrays(oldArr, newArr, callback) {
- return arrayDiff.diff(oldArr, newArr, callback);
- }
- });
- unwrapExports(array);
- var parse = createCommonjsModule(function (module, exports) {
- /*istanbul ignore start*/
- 'use strict';
- exports.__esModule = true;
- exports.
- /*istanbul ignore end*/
- parsePatch = parsePatch;
- function parsePatch(uniDiff) {
- /*istanbul ignore start*/
- var
- /*istanbul ignore end*/
- options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
- var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/),
- delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [],
- list = [],
- i = 0;
- function parseIndex() {
- var index = {};
- list.push(index); // Parse diff metadata
- while (i < diffstr.length) {
- var line = diffstr[i]; // File header found, end parsing diff metadata
- if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) {
- break;
- } // Diff index
- var header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line);
- if (header) {
- index.index = header[1];
- }
- i++;
- } // Parse file headers if they are defined. Unified diff requires them, but
- // there's no technical issues to have an isolated hunk without file header
- parseFileHeader(index);
- parseFileHeader(index); // Parse hunks
- index.hunks = [];
- while (i < diffstr.length) {
- var _line = diffstr[i];
- if (/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(_line)) {
- break;
- } else if (/^@@/.test(_line)) {
- index.hunks.push(parseHunk());
- } else if (_line && options.strict) {
- // Ignore unexpected content unless in strict mode
- throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line));
- } else {
- i++;
- }
- }
- } // Parses the --- and +++ headers, if none are found, no lines
- // are consumed.
- function parseFileHeader(index) {
- var headerPattern = /^(---|\+\+\+)\s+([\S ]*)(?:\t(.*?)\s*)?$/;
- var fileHeader = headerPattern.exec(diffstr[i]);
- if (fileHeader) {
- var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new';
- index[keyPrefix + 'FileName'] = fileHeader[2];
- index[keyPrefix + 'Header'] = fileHeader[3];
- i++;
- }
- } // Parses a hunk
- // This assumes that we are at the start of a hunk.
- function parseHunk() {
- var chunkHeaderIndex = i,
- chunkHeaderLine = diffstr[i++],
- chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);
- var hunk = {
- oldStart: +chunkHeader[1],
- oldLines: +chunkHeader[2] || 1,
- newStart: +chunkHeader[3],
- newLines: +chunkHeader[4] || 1,
- lines: [],
- linedelimiters: []
- };
- var addCount = 0,
- removeCount = 0;
- for (; i < diffstr.length; i++) {
- // Lines starting with '---' could be mistaken for the "remove line" operation
- // But they could be the header for the next file. Therefore prune such cases out.
- if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) {
- break;
- }
- var operation = diffstr[i][0];
- if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') {
- hunk.lines.push(diffstr[i]);
- hunk.linedelimiters.push(delimiters[i] || '\n');
- if (operation === '+') {
- addCount++;
- } else if (operation === '-') {
- removeCount++;
- } else if (operation === ' ') {
- addCount++;
- removeCount++;
- }
- } else {
- break;
- }
- } // Handle the empty block count case
- if (!addCount && hunk.newLines === 1) {
- hunk.newLines = 0;
- }
- if (!removeCount && hunk.oldLines === 1) {
- hunk.oldLines = 0;
- } // Perform optional sanity checking
- if (options.strict) {
- if (addCount !== hunk.newLines) {
- throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1));
- }
- if (removeCount !== hunk.oldLines) {
- throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1));
- }
- }
- return hunk;
- }
- while (i < diffstr.length) {
- parseIndex();
- }
- return list;
- }
- });
- unwrapExports(parse);
- var distanceIterator = createCommonjsModule(function (module, exports) {
- /*istanbul ignore start*/
- "use strict";
- exports.__esModule = true;
- exports["default"] =
- /*istanbul ignore end*/
- function (start, minLine, maxLine) {
- var wantForward = true,
- backwardExhausted = false,
- forwardExhausted = false,
- localOffset = 1;
- return function iterator() {
- if (wantForward && !forwardExhausted) {
- if (backwardExhausted) {
- localOffset++;
- } else {
- wantForward = false;
- } // Check if trying to fit beyond text length, and if not, check it fits
- // after offset location (or desired location on first iteration)
- if (start + localOffset <= maxLine) {
- return localOffset;
- }
- forwardExhausted = true;
- }
- if (!backwardExhausted) {
- if (!forwardExhausted) {
- wantForward = true;
- } // Check if trying to fit before text beginning, and if not, check it fits
- // before offset location
- if (minLine <= start - localOffset) {
- return -localOffset++;
- }
- backwardExhausted = true;
- return iterator();
- } // We tried to fit hunk before text beginning and beyond text lenght, then
- // hunk can't fit on the text. Return undefined
- };
- };
- });
- unwrapExports(distanceIterator);
- var apply = createCommonjsModule(function (module, exports) {
- /*istanbul ignore start*/
- 'use strict';
- exports.__esModule = true;
- exports.
- /*istanbul ignore end*/
- applyPatch = applyPatch;
- /*istanbul ignore start*/
- exports.
- /*istanbul ignore end*/
- applyPatches = applyPatches;
- /*istanbul ignore start*/
- var _distanceIterator2 = _interopRequireDefault(distanceIterator);
- function _interopRequireDefault(obj) {
- return obj && obj.__esModule ? obj : {
- 'default': obj
- };
- }
- /*istanbul ignore end*/
- function applyPatch(source, uniDiff) {
- /*istanbul ignore start*/
- var
- /*istanbul ignore end*/
- options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
- if (typeof uniDiff === 'string') {
- uniDiff =
- /*istanbul ignore start*/
- (0, parse.parsePatch
- /*istanbul ignore end*/
- )(uniDiff);
- }
- if (Array.isArray(uniDiff)) {
- if (uniDiff.length > 1) {
- throw new Error('applyPatch only works with a single input.');
- }
- uniDiff = uniDiff[0];
- } // Apply the diff to the input
- var lines = source.split(/\r\n|[\n\v\f\r\x85]/),
- delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [],
- hunks = uniDiff.hunks,
- compareLine = options.compareLine || function (lineNumber, line, operation, patchContent)
- /*istanbul ignore start*/
- {
- return (
- /*istanbul ignore end*/
- line === patchContent
- );
- },
- errorCount = 0,
- fuzzFactor = options.fuzzFactor || 0,
- minLine = 0,
- offset = 0,
- removeEOFNL =
- /*istanbul ignore start*/
- void 0
- /*istanbul ignore end*/
- ,
- addEOFNL =
- /*istanbul ignore start*/
- void 0;
- /**
- * Checks if the hunk exactly fits on the provided location
- */
- function hunkFits(hunk, toPos) {
- for (var j = 0; j < hunk.lines.length; j++) {
- var line = hunk.lines[j],
- operation = line[0],
- content = line.substr(1);
- if (operation === ' ' || operation === '-') {
- // Context sanity check
- if (!compareLine(toPos + 1, lines[toPos], operation, content)) {
- errorCount++;
- if (errorCount > fuzzFactor) {
- return false;
- }
- }
- toPos++;
- }
- }
- return true;
- } // Search best fit offsets for each hunk based on the previous ones
- for (var i = 0; i < hunks.length; i++) {
- var hunk = hunks[i],
- maxLine = lines.length - hunk.oldLines,
- localOffset = 0,
- toPos = offset + hunk.oldStart - 1;
- var iterator =
- /*istanbul ignore start*/
- (0, _distanceIterator2['default']
- /*istanbul ignore end*/
- )(toPos, minLine, maxLine);
- for (; localOffset !== undefined; localOffset = iterator()) {
- if (hunkFits(hunk, toPos + localOffset)) {
- hunk.offset = offset += localOffset;
- break;
- }
- }
- if (localOffset === undefined) {
- return false;
- } // Set lower text limit to end of the current hunk, so next ones don't try
- // to fit over already patched text
- minLine = hunk.offset + hunk.oldStart + hunk.oldLines;
- } // Apply patch hunks
- for (var _i = 0; _i < hunks.length; _i++) {
- var _hunk = hunks[_i],
- _toPos = _hunk.offset + _hunk.newStart - 1;
- if (_hunk.newLines == 0) {
- _toPos++;
- }
- for (var j = 0; j < _hunk.lines.length; j++) {
- var line = _hunk.lines[j],
- operation = line[0],
- content = line.substr(1),
- delimiter = _hunk.linedelimiters[j];
- if (operation === ' ') {
- _toPos++;
- } else if (operation === '-') {
- lines.splice(_toPos, 1);
- delimiters.splice(_toPos, 1);
- /* istanbul ignore else */
- } else if (operation === '+') {
- lines.splice(_toPos, 0, content);
- delimiters.splice(_toPos, 0, delimiter);
- _toPos++;
- } else if (operation === '\\') {
- var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null;
- if (previousOperation === '+') {
- removeEOFNL = true;
- } else if (previousOperation === '-') {
- addEOFNL = true;
- }
- }
- }
- } // Handle EOFNL insertion/removal
- if (removeEOFNL) {
- while (!lines[lines.length - 1]) {
- lines.pop();
- delimiters.pop();
- }
- } else if (addEOFNL) {
- lines.push('');
- delimiters.push('\n');
- }
- for (var _k = 0; _k < lines.length - 1; _k++) {
- lines[_k] = lines[_k] + delimiters[_k];
- }
- return lines.join('');
- } // Wrapper that supports multiple file patches via callbacks.
- function applyPatches(uniDiff, options) {
- if (typeof uniDiff === 'string') {
- uniDiff =
- /*istanbul ignore start*/
- (0, parse.parsePatch
- /*istanbul ignore end*/
- )(uniDiff);
- }
- var currentIndex = 0;
- function processIndex() {
- var index = uniDiff[currentIndex++];
- if (!index) {
- return options.complete();
- }
- options.loadFile(index, function (err, data) {
- if (err) {
- return options.complete(err);
- }
- var updatedContent = applyPatch(data, index, options);
- options.patched(index, updatedContent, function (err) {
- if (err) {
- return options.complete(err);
- }
- processIndex();
- });
- });
- }
- processIndex();
- }
- });
- unwrapExports(apply);
- var create = createCommonjsModule(function (module, exports) {
- /*istanbul ignore start*/
- 'use strict';
- exports.__esModule = true;
- exports.
- /*istanbul ignore end*/
- structuredPatch = structuredPatch;
- /*istanbul ignore start*/
- exports.
- /*istanbul ignore end*/
- createTwoFilesPatch = createTwoFilesPatch;
- /*istanbul ignore start*/
- exports.
- /*istanbul ignore end*/
- createPatch = createPatch;
- /*istanbul ignore start*/
- function _toConsumableArray(arr) {
- if (Array.isArray(arr)) {
- for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) {
- arr2[i] = arr[i];
- }
- return arr2;
- } else {
- return Array.from(arr);
- }
- }
- /*istanbul ignore end*/
- function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
- if (!options) {
- options = {};
- }
- if (typeof options.context === 'undefined') {
- options.context = 4;
- }
- var diff =
- /*istanbul ignore start*/
- (0, line.diffLines
- /*istanbul ignore end*/
- )(oldStr, newStr, options);
- diff.push({
- value: '',
- lines: []
- }); // Append an empty value to make cleanup easier
- function contextLines(lines) {
- return lines.map(function (entry) {
- return ' ' + entry;
- });
- }
- var hunks = [];
- var oldRangeStart = 0,
- newRangeStart = 0,
- curRange = [],
- oldLine = 1,
- newLine = 1;
- /*istanbul ignore start*/
- var _loop = function _loop(
- /*istanbul ignore end*/
- i) {
- var current = diff[i],
- lines = current.lines || current.value.replace(/\n$/, '').split('\n');
- current.lines = lines;
- if (current.added || current.removed) {
- /*istanbul ignore start*/
- var _curRange;
- /*istanbul ignore end*/
- // If we have previous context, start with that
- if (!oldRangeStart) {
- var prev = diff[i - 1];
- oldRangeStart = oldLine;
- newRangeStart = newLine;
- if (prev) {
- curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : [];
- oldRangeStart -= curRange.length;
- newRangeStart -= curRange.length;
- }
- } // Output our changes
- /*istanbul ignore start*/
- (_curRange =
- /*istanbul ignore end*/
- curRange).push.
- /*istanbul ignore start*/
- apply
- /*istanbul ignore end*/
- (
- /*istanbul ignore start*/
- _curRange
- /*istanbul ignore end*/
- ,
- /*istanbul ignore start*/
- _toConsumableArray(
- /*istanbul ignore end*/
- lines.map(function (entry) {
- return (current.added ? '+' : '-') + entry;
- }))); // Track the updated file position
- if (current.added) {
- newLine += lines.length;
- } else {
- oldLine += lines.length;
- }
- } else {
- // Identical context lines. Track line changes
- if (oldRangeStart) {
- // Close out any changes that have been output (or join overlapping)
- if (lines.length <= options.context * 2 && i < diff.length - 2) {
- /*istanbul ignore start*/
- var _curRange2;
- /*istanbul ignore end*/
- // Overlapping
- /*istanbul ignore start*/
- (_curRange2 =
- /*istanbul ignore end*/
- curRange).push.
- /*istanbul ignore start*/
- apply
- /*istanbul ignore end*/
- (
- /*istanbul ignore start*/
- _curRange2
- /*istanbul ignore end*/
- ,
- /*istanbul ignore start*/
- _toConsumableArray(
- /*istanbul ignore end*/
- contextLines(lines)));
- } else {
- /*istanbul ignore start*/
- var _curRange3;
- /*istanbul ignore end*/
- // end the range and output
- var contextSize = Math.min(lines.length, options.context);
- /*istanbul ignore start*/
- (_curRange3 =
- /*istanbul ignore end*/
- curRange).push.
- /*istanbul ignore start*/
- apply
- /*istanbul ignore end*/
- (
- /*istanbul ignore start*/
- _curRange3
- /*istanbul ignore end*/
- ,
- /*istanbul ignore start*/
- _toConsumableArray(
- /*istanbul ignore end*/
- contextLines(lines.slice(0, contextSize))));
- var hunk = {
- oldStart: oldRangeStart,
- oldLines: oldLine - oldRangeStart + contextSize,
- newStart: newRangeStart,
- newLines: newLine - newRangeStart + contextSize,
- lines: curRange
- };
- if (i >= diff.length - 2 && lines.length <= options.context) {
- // EOF is inside this hunk
- var oldEOFNewline = /\n$/.test(oldStr);
- var newEOFNewline = /\n$/.test(newStr);
- if (lines.length == 0 && !oldEOFNewline) {
- // special case: old has no eol and no trailing context; no-nl can end up before adds
- curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file');
- } else if (!oldEOFNewline || !newEOFNewline) {
- curRange.push('\\ No newline at end of file');
- }
- }
- hunks.push(hunk);
- oldRangeStart = 0;
- newRangeStart = 0;
- curRange = [];
- }
- }
- oldLine += lines.length;
- newLine += lines.length;
- }
- };
- for (var i = 0; i < diff.length; i++) {
- /*istanbul ignore start*/
- _loop(
- /*istanbul ignore end*/
- i);
- }
- return {
- oldFileName: oldFileName,
- newFileName: newFileName,
- oldHeader: oldHeader,
- newHeader: newHeader,
- hunks: hunks
- };
- }
- function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
- var diff = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options);
- var ret = [];
- if (oldFileName == newFileName) {
- ret.push('Index: ' + oldFileName);
- }
- ret.push('===================================================================');
- ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader));
- ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader));
- for (var i = 0; i < diff.hunks.length; i++) {
- var hunk = diff.hunks[i];
- ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@');
- ret.push.apply(ret, hunk.lines);
- }
- return ret.join('\n') + '\n';
- }
- function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) {
- return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options);
- }
- });
- unwrapExports(create);
- var dmp = createCommonjsModule(function (module, exports) {
- /*istanbul ignore start*/
- "use strict";
- exports.__esModule = true;
- exports.
- /*istanbul ignore end*/
- convertChangesToDMP = convertChangesToDMP; // See: http://code.google.com/p/google-diff-match-patch/wiki/API
- function convertChangesToDMP(changes) {
- var ret = [],
- change =
- /*istanbul ignore start*/
- void 0
- /*istanbul ignore end*/
- ,
- operation =
- /*istanbul ignore start*/
- void 0;
- for (var i = 0; i < changes.length; i++) {
- change = changes[i];
- if (change.added) {
- operation = 1;
- } else if (change.removed) {
- operation = -1;
- } else {
- operation = 0;
- }
- ret.push([operation, change.value]);
- }
- return ret;
- }
- });
- unwrapExports(dmp);
- var xml = createCommonjsModule(function (module, exports) {
- /*istanbul ignore start*/
- 'use strict';
- exports.__esModule = true;
- exports.
- /*istanbul ignore end*/
- convertChangesToXML = convertChangesToXML;
- function convertChangesToXML(changes) {
- var ret = [];
- for (var i = 0; i < changes.length; i++) {
- var change = changes[i];
- if (change.added) {
- ret.push('<ins>');
- } else if (change.removed) {
- ret.push('<del>');
- }
- ret.push(escapeHTML(change.value));
- if (change.added) {
- ret.push('</ins>');
- } else if (change.removed) {
- ret.push('</del>');
- }
- }
- return ret.join('');
- }
- function escapeHTML(s) {
- var n = s;
- n = n.replace(/&/g, '&');
- n = n.replace(/</g, '<');
- n = n.replace(/>/g, '>');
- n = n.replace(/"/g, '"');
- return n;
- }
- });
- unwrapExports(xml);
- var lib = createCommonjsModule(function (module, exports) {
- /*istanbul ignore start*/
- 'use strict';
- exports.__esModule = true;
- exports.canonicalize = exports.convertChangesToXML = exports.convertChangesToDMP = exports.parsePatch = exports.applyPatches = exports.applyPatch = exports.createPatch = exports.createTwoFilesPatch = exports.structuredPatch = exports.diffArrays = exports.diffJson = exports.diffCss = exports.diffSentences = exports.diffTrimmedLines = exports.diffLines = exports.diffWordsWithSpace = exports.diffWords = exports.diffChars = exports.Diff = undefined;
- /*istanbul ignore end*/
- /*istanbul ignore start*/
- var _base2 = _interopRequireDefault(base);
- /*istanbul ignore end*/
- /*istanbul ignore start*/
- function _interopRequireDefault(obj) {
- return obj && obj.__esModule ? obj : {
- 'default': obj
- };
- }
- exports.
- /*istanbul ignore end*/
- Diff = _base2['default'];
- /*istanbul ignore start*/
- exports.
- /*istanbul ignore end*/
- diffChars = character.diffChars;
- /*istanbul ignore start*/
- exports.
- /*istanbul ignore end*/
- diffWords = word.diffWords;
- /*istanbul ignore start*/
- exports.
- /*istanbul ignore end*/
- diffWordsWithSpace = word.diffWordsWithSpace;
- /*istanbul ignore start*/
- exports.
- /*istanbul ignore end*/
- diffLines = line.diffLines;
- /*istanbul ignore start*/
- exports.
- /*istanbul ignore end*/
- diffTrimmedLines = line.diffTrimmedLines;
- /*istanbul ignore start*/
- exports.
- /*istanbul ignore end*/
- diffSentences = sentence.diffSentences;
- /*istanbul ignore start*/
- exports.
- /*istanbul ignore end*/
- diffCss = css.diffCss;
- /*istanbul ignore start*/
- exports.
- /*istanbul ignore end*/
- diffJson = json.diffJson;
- /*istanbul ignore start*/
- exports.
- /*istanbul ignore end*/
- diffArrays = array.diffArrays;
- /*istanbul ignore start*/
- exports.
- /*istanbul ignore end*/
- structuredPatch = create.structuredPatch;
- /*istanbul ignore start*/
- exports.
- /*istanbul ignore end*/
- createTwoFilesPatch = create.createTwoFilesPatch;
- /*istanbul ignore start*/
- exports.
- /*istanbul ignore end*/
- createPatch = create.createPatch;
- /*istanbul ignore start*/
- exports.
- /*istanbul ignore end*/
- applyPatch = apply.applyPatch;
- /*istanbul ignore start*/
- exports.
- /*istanbul ignore end*/
- applyPatches = apply.applyPatches;
- /*istanbul ignore start*/
- exports.
- /*istanbul ignore end*/
- parsePatch = parse.parsePatch;
- /*istanbul ignore start*/
- exports.
- /*istanbul ignore end*/
- convertChangesToDMP = dmp.convertChangesToDMP;
- /*istanbul ignore start*/
- exports.
- /*istanbul ignore end*/
- convertChangesToXML = xml.convertChangesToXML;
- /*istanbul ignore start*/
- exports.
- /*istanbul ignore end*/
- canonicalize = json.canonicalize;
- /* See LICENSE file for terms of use */
- /*
- * Text diff implementation.
- *
- * This library supports the following APIS:
- * JsDiff.diffChars: Character by character diff
- * JsDiff.diffWords: Word (as defined by \b regex) diff which ignores whitespace
- * JsDiff.diffLines: Line based diff
- *
- * JsDiff.diffCss: Diff targeted at CSS content
- *
- * These methods are based on the implementation proposed in
- * "An O(ND) Difference Algorithm and its Variations" (Myers, 1986).
- * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927
- */
- });
- unwrapExports(lib);
- /*!
- * normalize-path <https://github.com/jonschlinkert/normalize-path>
- *
- * Copyright (c) 2014-2018, Jon Schlinkert.
- * Released under the MIT License.
- */
- var normalizePath = function normalizePath(path$$1, stripTrailing) {
- if (typeof path$$1 !== 'string') {
- throw new TypeError('expected path to be a string');
- }
- if (path$$1 === '\\' || path$$1 === '/') return '/';
- var len = path$$1.length;
- if (len <= 1) return path$$1; // ensure that win32 namespaces has two leading slashes, so that the path is
- // handled properly by the win32 version of path.parse() after being normalized
- // https://msdn.microsoft.com/library/windows/desktop/aa365247(v=vs.85).aspx#namespaces
- var prefix = '';
- if (len > 4 && path$$1[3] === '\\') {
- var ch = path$$1[2];
- if ((ch === '?' || ch === '.') && path$$1.slice(0, 2) === '\\\\') {
- path$$1 = path$$1.slice(2);
- prefix = '//';
- }
- }
- var segs = path$$1.split(/[/\\]+/);
- if (stripTrailing !== false && segs[segs.length - 1] === '') {
- segs.pop();
- }
- return prefix + segs.join('/');
- };
- function _classCallCheck(instance, Constructor) {
- if (!(instance instanceof Constructor)) {
- throw new TypeError("Cannot call a class as a function");
- }
- }
- function _defineProperties(target, props) {
- for (var i = 0; i < props.length; i++) {
- var descriptor = props[i];
- descriptor.enumerable = descriptor.enumerable || false;
- descriptor.configurable = true;
- if ("value" in descriptor) descriptor.writable = true;
- Object.defineProperty(target, descriptor.key, descriptor);
- }
- }
- function _createClass(Constructor, protoProps, staticProps) {
- if (protoProps) _defineProperties(Constructor.prototype, protoProps);
- if (staticProps) _defineProperties(Constructor, staticProps);
- return Constructor;
- }
- function _inherits(subClass, superClass) {
- if (typeof superClass !== "function" && superClass !== null) {
- throw new TypeError("Super expression must either be null or a function");
- }
- subClass.prototype = Object.create(superClass && superClass.prototype, {
- constructor: {
- value: subClass,
- writable: true,
- configurable: true
- }
- });
- if (superClass) _setPrototypeOf(subClass, superClass);
- }
- function _getPrototypeOf(o) {
- _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
- return o.__proto__ || Object.getPrototypeOf(o);
- };
- return _getPrototypeOf(o);
- }
- function _setPrototypeOf(o, p) {
- _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
- o.__proto__ = p;
- return o;
- };
- return _setPrototypeOf(o, p);
- }
- function isNativeReflectConstruct() {
- if (typeof Reflect === "undefined" || !Reflect.construct) return false;
- if (Reflect.construct.sham) return false;
- if (typeof Proxy === "function") return true;
- try {
- Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));
- return true;
- } catch (e) {
- return false;
- }
- }
- function _construct(Parent, args, Class) {
- if (isNativeReflectConstruct()) {
- _construct = Reflect.construct;
- } else {
- _construct = function _construct(Parent, args, Class) {
- var a = [null];
- a.push.apply(a, args);
- var Constructor = Function.bind.apply(Parent, a);
- var instance = new Constructor();
- if (Class) _setPrototypeOf(instance, Class.prototype);
- return instance;
- };
- }
- return _construct.apply(null, arguments);
- }
- function _isNativeFunction(fn) {
- return Function.toString.call(fn).indexOf("[native code]") !== -1;
- }
- function _wrapNativeSuper(Class) {
- var _cache = typeof Map === "function" ? new Map() : undefined;
- _wrapNativeSuper = function _wrapNativeSuper(Class) {
- if (Class === null || !_isNativeFunction(Class)) return Class;
- if (typeof Class !== "function") {
- throw new TypeError("Super expression must either be null or a function");
- }
- if (typeof _cache !== "undefined") {
- if (_cache.has(Class)) return _cache.get(Class);
- _cache.set(Class, Wrapper);
- }
- function Wrapper() {
- return _construct(Class, arguments, _getPrototypeOf(this).constructor);
- }
- Wrapper.prototype = Object.create(Class.prototype, {
- constructor: {
- value: Wrapper,
- enumerable: false,
- writable: true,
- configurable: true
- }
- });
- return _setPrototypeOf(Wrapper, Class);
- };
- return _wrapNativeSuper(Class);
- }
- function _assertThisInitialized(self) {
- if (self === void 0) {
- throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
- }
- return self;
- }
- function _possibleConstructorReturn(self, call) {
- if (call && (typeof call === "object" || typeof call === "function")) {
- return call;
- }
- return _assertThisInitialized(self);
- }
- function _superPropBase(object, property) {
- while (!Object.prototype.hasOwnProperty.call(object, property)) {
- object = _getPrototypeOf(object);
- if (object === null) break;
- }
- return object;
- }
- function _get(target, property, receiver) {
- if (typeof Reflect !== "undefined" && Reflect.get) {
- _get = Reflect.get;
- } else {
- _get = function _get(target, property, receiver) {
- var base = _superPropBase(target, property);
- if (!base) return;
- var desc = Object.getOwnPropertyDescriptor(base, property);
- if (desc.get) {
- return desc.get.call(receiver);
- }
- return desc.value;
- };
- }
- return _get(target, property, receiver || target);
- }
- function _slicedToArray(arr, i) {
- return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
- }
- function _toArray(arr) {
- return _arrayWithHoles(arr) || _iterableToArray(arr) || _nonIterableRest();
- }
- function _toConsumableArray(arr) {
- return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
- }
- function _arrayWithoutHoles(arr) {
- if (Array.isArray(arr)) {
- for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
- return arr2;
- }
- }
- function _arrayWithHoles(arr) {
- if (Array.isArray(arr)) return arr;
- }
- function _iterableToArray(iter) {
- if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
- }
- function _iterableToArrayLimit(arr, i) {
- var _arr = [];
- var _n = true;
- var _d = false;
- var _e = undefined;
- try {
- for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
- _arr.push(_s.value);
- if (i && _arr.length === i) break;
- }
- } catch (err) {
- _d = true;
- _e = err;
- } finally {
- try {
- if (!_n && _i["return"] != null) _i["return"]();
- } finally {
- if (_d) throw _e;
- }
- }
- return _arr;
- }
- function _nonIterableSpread() {
- throw new TypeError("Invalid attempt to spread non-iterable instance");
- }
- function _nonIterableRest() {
- throw new TypeError("Invalid attempt to destructure non-iterable instance");
- }
- function _toPrimitive(input, hint) {
- if (typeof input !== "object" || input === null) return input;
- var prim = input[Symbol.toPrimitive];
- if (prim !== undefined) {
- var res = prim.call(input, hint || "default");
- if (typeof res !== "object") return res;
- throw new TypeError("@@toPrimitive must return a primitive value.");
- }
- return (hint === "string" ? String : Number)(input);
- }
- function _toPropertyKey(arg) {
- var key = _toPrimitive(arg, "string");
- return typeof key === "symbol" ? key : String(key);
- }
- function _addElementPlacement(element, placements, silent) {
- var keys = placements[element.placement];
- if (!silent && keys.indexOf(element.key) !== -1) {
- throw new TypeError("Duplicated element (" + element.key + ")");
- }
- keys.push(element.key);
- }
- function _fromElementDescriptor(element) {
- var obj = {
- kind: element.kind,
- key: element.key,
- placement: element.placement,
- descriptor: element.descriptor
- };
- var desc = {
- value: "Descriptor",
- configurable: true
- };
- Object.defineProperty(obj, Symbol.toStringTag, desc);
- if (element.kind === "field") obj.initializer = element.initializer;
- return obj;
- }
- function _toElementDescriptors(elementObjects) {
- if (elementObjects === undefined) return;
- return _toArray(elementObjects).map(function (elementObject) {
- var element = _toElementDescriptor(elementObject);
- _disallowProperty(elementObject, "finisher", "An element descriptor");
- _disallowProperty(elementObject, "extras", "An element descriptor");
- return element;
- });
- }
- function _toElementDescriptor(elementObject) {
- var kind = String(elementObject.kind);
- if (kind !== "method" && kind !== "field") {
- throw new TypeError('An element descriptor\'s .kind property must be either "method" or' + ' "field", but a decorator created an element descriptor with' + ' .kind "' + kind + '"');
- }
- var key = _toPropertyKey(elementObject.key);
- var placement = String(elementObject.placement);
- if (placement !== "static" && placement !== "prototype" && placement !== "own") {
- throw new TypeError('An element descriptor\'s .placement property must be one of "static",' + ' "prototype" or "own", but a decorator created an element descriptor' + ' with .placement "' + placement + '"');
- }
- var descriptor = elementObject.descriptor;
- _disallowProperty(elementObject, "elements", "An element descriptor");
- var element = {
- kind: kind,
- key: key,
- placement: placement,
- descriptor: Object.assign({}, descriptor)
- };
- if (kind !== "field") {
- _disallowProperty(elementObject, "initializer", "A method descriptor");
- } else {
- _disallowProperty(descriptor, "get", "The property descriptor of a field descriptor");
- _disallowProperty(descriptor, "set", "The property descriptor of a field descriptor");
- _disallowProperty(descriptor, "value", "The property descriptor of a field descriptor");
- element.initializer = elementObject.initializer;
- }
- return element;
- }
- function _toElementFinisherExtras(elementObject) {
- var element = _toElementDescriptor(elementObject);
- var finisher = _optionalCallableProperty(elementObject, "finisher");
- var extras = _toElementDescriptors(elementObject.extras);
- return {
- element: element,
- finisher: finisher,
- extras: extras
- };
- }
- function _fromClassDescriptor(elements) {
- var obj = {
- kind: "class",
- elements: elements.map(_fromElementDescriptor)
- };
- var desc = {
- value: "Descriptor",
- configurable: true
- };
- Object.defineProperty(obj, Symbol.toStringTag, desc);
- return obj;
- }
- function _toClassDescriptor(obj) {
- var kind = String(obj.kind);
- if (kind !== "class") {
- throw new TypeError('A class descriptor\'s .kind property must be "class", but a decorator' + ' created a class descriptor with .kind "' + kind + '"');
- }
- _disallowProperty(obj, "key", "A class descriptor");
- _disallowProperty(obj, "placement", "A class descriptor");
- _disallowProperty(obj, "descriptor", "A class descriptor");
- _disallowProperty(obj, "initializer", "A class descriptor");
- _disallowProperty(obj, "extras", "A class descriptor");
- var finisher = _optionalCallableProperty(obj, "finisher");
- var elements = _toElementDescriptors(obj.elements);
- return {
- elements: elements,
- finisher: finisher
- };
- }
- function _disallowProperty(obj, name, objectType) {
- if (obj[name] !== undefined) {
- throw new TypeError(objectType + " can't have a ." + name + " property.");
- }
- }
- function _optionalCallableProperty(obj, name) {
- var value = obj[name];
- if (value !== undefined && typeof value !== "function") {
- throw new TypeError("Expected '" + name + "' to be a function");
- }
- return value;
- }
- /**
- * @class
- */
- var LineByLine =
- /*#__PURE__*/
- function () {
- function LineByLine(file, options) {
- _classCallCheck(this, LineByLine);
- options = options || {};
- if (!options.readChunk) options.readChunk = 1024;
- if (!options.newLineCharacter) {
- options.newLineCharacter = 0x0a; //linux line ending
- } else {
- options.newLineCharacter = options.newLineCharacter.charCodeAt(0);
- }
- if (typeof file === 'number') {
- this.fd = file;
- } else {
- this.fd = fs.openSync(file, 'r');
- }
- this.options = options;
- this.newLineCharacter = options.newLineCharacter;
- this.reset();
- }
- _createClass(LineByLine, [{
- key: "_searchInBuffer",
- value: function _searchInBuffer(buffer, hexNeedle) {
- var found = -1;
- for (var i = 0; i <= buffer.length; i++) {
- var b_byte = buffer[i];
- if (b_byte === hexNeedle) {
- found = i;
- break;
- }
- }
- return found;
- }
- }, {
- key: "reset",
- value: function reset() {
- this.eofReached = false;
- this.linesCache = [];
- this.fdPosition = 0;
- }
- }, {
- key: "close",
- value: function close() {
- fs.closeSync(this.fd);
- this.fd = null;
- }
- }, {
- key: "_extractLines",
- value: function _extractLines(buffer) {
- var line;
- var lines = [];
- var bufferPosition = 0;
- var lastNewLineBufferPosition = 0;
- while (true) {
- var bufferPositionValue = buffer[bufferPosition++];
- if (bufferPositionValue === this.newLineCharacter) {
- line = buffer.slice(lastNewLineBufferPosition, bufferPosition);
- lines.push(line);
- lastNewLineBufferPosition = bufferPosition;
- } else if (!bufferPositionValue) {
- break;
- }
- }
- var leftovers = buffer.slice(lastNewLineBufferPosition, bufferPosition);
- if (leftovers.length) {
- lines.push(leftovers);
- }
- return lines;
- }
- }, {
- key: "_readChunk",
- value: function _readChunk(lineLeftovers) {
- var totalBytesRead = 0;
- var bytesRead;
- var buffers = [];
- do {
- var readBuffer = new Buffer(this.options.readChunk);
- bytesRead = fs.readSync(this.fd, readBuffer, 0, this.options.readChunk, this.fdPosition);
- totalBytesRead = totalBytesRead + bytesRead;
- this.fdPosition = this.fdPosition + bytesRead;
- buffers.push(readBuffer);
- } while (bytesRead && this._searchInBuffer(buffers[buffers.length - 1], this.options.newLineCharacter) === -1);
- var bufferData = Buffer.concat(buffers);
- if (bytesRead < this.options.readChunk) {
- this.eofReached = true;
- bufferData = bufferData.slice(0, totalBytesRead);
- }
- if (totalBytesRead) {
- this.linesCache = this._extractLines(bufferData);
- if (lineLeftovers) {
- this.linesCache[0] = Buffer.concat([lineLeftovers, this.linesCache[0]]);
- }
- }
- return totalBytesRead;
- }
- }, {
- key: "next",
- value: function next() {
- if (!this.fd) return false;
- var line = false;
- if (this.eofReached && this.linesCache.length === 0) {
- return line;
- }
- var bytesRead;
- if (!this.linesCache.length) {
- bytesRead = this._readChunk();
- }
- if (this.linesCache.length) {
- line = this.linesCache.shift();
- var lastLineCharacter = line[line.length - 1];
- if (lastLineCharacter !== 0x0a) {
- bytesRead = this._readChunk(line);
- if (bytesRead) {
- line = this.linesCache.shift();
- }
- }
- }
- if (this.eofReached && this.linesCache.length === 0) {
- this.close();
- }
- if (line && line[line.length - 1] === this.newLineCharacter) {
- line = line.slice(0, line.length - 1);
- }
- return line;
- }
- }]);
- return LineByLine;
- }();
- var readlines = LineByLine;
- var ConfigError =
- /*#__PURE__*/
- function (_Error) {
- _inherits(ConfigError, _Error);
- function ConfigError() {
- _classCallCheck(this, ConfigError);
- return _possibleConstructorReturn(this, _getPrototypeOf(ConfigError).apply(this, arguments));
- }
- return ConfigError;
- }(_wrapNativeSuper(Error));
- var DebugError =
- /*#__PURE__*/
- function (_Error2) {
- _inherits(DebugError, _Error2);
- function DebugError() {
- _classCallCheck(this, DebugError);
- return _possibleConstructorReturn(this, _getPrototypeOf(DebugError).apply(this, arguments));
- }
- return DebugError;
- }(_wrapNativeSuper(Error));
- var UndefinedParserError$1 =
- /*#__PURE__*/
- function (_Error3) {
- _inherits(UndefinedParserError, _Error3);
- function UndefinedParserError() {
- _classCallCheck(this, UndefinedParserError);
- return _possibleConstructorReturn(this, _getPrototypeOf(UndefinedParserError).apply(this, arguments));
- }
- return UndefinedParserError;
- }(_wrapNativeSuper(Error));
- var errors = {
- ConfigError,
- DebugError,
- UndefinedParserError: UndefinedParserError$1
- };
- var semver = createCommonjsModule(function (module, exports) {
- exports = module.exports = SemVer; // The debug function is excluded entirely from the minified version.
- /* nomin */
- var debug;
- /* nomin */
- if (typeof process === 'object' &&
- /* nomin */
- process.env &&
- /* nomin */
- process.env.NODE_DEBUG &&
- /* nomin */
- /\bsemver\b/i.test(process.env.NODE_DEBUG))
- /* nomin */
- debug = function debug() {
- /* nomin */
- var args = Array.prototype.slice.call(arguments, 0);
- /* nomin */
- args.unshift('SEMVER');
- /* nomin */
- console.log.apply(console, args);
- /* nomin */
- };
- /* nomin */
- else
- /* nomin */
- debug = function debug() {}; // Note: this is the semver.org version of the spec that it implements
- // Not necessarily the package version of this code.
- exports.SEMVER_SPEC_VERSION = '2.0.0';
- var MAX_LENGTH = 256;
- var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; // The actual regexps go on exports.re
- var re = exports.re = [];
- var src = exports.src = [];
- var R = 0; // The following Regular Expressions can be used for tokenizing,
- // validating, and parsing SemVer version strings.
- // ## Numeric Identifier
- // A single `0`, or a non-zero digit followed by zero or more digits.
- var NUMERICIDENTIFIER = R++;
- src[NUMERICIDENTIFIER] = '0|[1-9]\\d*';
- var NUMERICIDENTIFIERLOOSE = R++;
- src[NUMERICIDENTIFIERLOOSE] = '[0-9]+'; // ## Non-numeric Identifier
- // Zero or more digits, followed by a letter or hyphen, and then zero or
- // more letters, digits, or hyphens.
- var NONNUMERICIDENTIFIER = R++;
- src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*'; // ## Main Version
- // Three dot-separated numeric identifiers.
- var MAINVERSION = R++;
- src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + '(' + src[NUMERICIDENTIFIER] + ')\\.' + '(' + src[NUMERICIDENTIFIER] + ')';
- var MAINVERSIONLOOSE = R++;
- src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[NUMERICIDENTIFIERLOOSE] + ')'; // ## Pre-release Version Identifier
- // A numeric identifier, or a non-numeric identifier.
- var PRERELEASEIDENTIFIER = R++;
- src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + '|' + src[NONNUMERICIDENTIFIER] + ')';
- var PRERELEASEIDENTIFIERLOOSE = R++;
- src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + '|' + src[NONNUMERICIDENTIFIER] + ')'; // ## Pre-release Version
- // Hyphen, followed by one or more dot-separated pre-release version
- // identifiers.
- var PRERELEASE = R++;
- src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))';
- var PRERELEASELOOSE = R++;
- src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))'; // ## Build Metadata Identifier
- // Any combination of digits, letters, or hyphens.
- var BUILDIDENTIFIER = R++;
- src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+'; // ## Build Metadata
- // Plus sign, followed by one or more period-separated build metadata
- // identifiers.
- var BUILD = R++;
- src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + '(?:\\.' + src[BUILDIDENTIFIER] + ')*))'; // ## Full Version String
- // A main version, followed optionally by a pre-release version and
- // build metadata.
- // Note that the only major, minor, patch, and pre-release sections of
- // the version string are capturing groups. The build metadata is not a
- // capturing group, because it should not ever be used in version
- // comparison.
- var FULL = R++;
- var FULLPLAIN = 'v?' + src[MAINVERSION] + src[PRERELEASE] + '?' + src[BUILD] + '?';
- src[FULL] = '^' + FULLPLAIN + '$'; // like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
- // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
- // common in the npm registry.
- var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + src[PRERELEASELOOSE] + '?' + src[BUILD] + '?';
- var LOOSE = R++;
- src[LOOSE] = '^' + LOOSEPLAIN + '$';
- var GTLT = R++;
- src[GTLT] = '((?:<|>)?=?)'; // Something like "2.*" or "1.2.x".
- // Note that "x.x" is a valid xRange identifer, meaning "any version"
- // Only the first item is strictly required.
- var XRANGEIDENTIFIERLOOSE = R++;
- src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*';
- var XRANGEIDENTIFIER = R++;
- src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*';
- var XRANGEPLAIN = R++;
- src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + '(?:' + src[PRERELEASE] + ')?' + src[BUILD] + '?' + ')?)?';
- var XRANGEPLAINLOOSE = R++;
- src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:' + src[PRERELEASELOOSE] + ')?' + src[BUILD] + '?' + ')?)?';
- var XRANGE = R++;
- src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$';
- var XRANGELOOSE = R++;
- src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$'; // Tilde ranges.
- // Meaning is "reasonably at or greater than"
- var LONETILDE = R++;
- src[LONETILDE] = '(?:~>?)';
- var TILDETRIM = R++;
- src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+';
- re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g');
- var tildeTrimReplace = '$1~';
- var TILDE = R++;
- src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$';
- var TILDELOOSE = R++;
- src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$'; // Caret ranges.
- // Meaning is "at least and backwards compatible with"
- var LONECARET = R++;
- src[LONECARET] = '(?:\\^)';
- var CARETTRIM = R++;
- src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+';
- re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g');
- var caretTrimReplace = '$1^';
- var CARET = R++;
- src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$';
- var CARETLOOSE = R++;
- src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$'; // A simple gt/lt/eq thing, or just "" to indicate "any version"
- var COMPARATORLOOSE = R++;
- src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$';
- var COMPARATOR = R++;
- src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$'; // An expression to strip any whitespace between the gtlt and the thing
- // it modifies, so that `> 1.2.3` ==> `>1.2.3`
- var COMPARATORTRIM = R++;
- src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')'; // this one has to use the /g flag
- re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g');
- var comparatorTrimReplace = '$1$2$3'; // Something like `1.2.3 - 1.2.4`
- // Note that these all use the loose form, because they'll be
- // checked against either the strict or loose comparator form
- // later.
- var HYPHENRANGE = R++;
- src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + '\\s+-\\s+' + '(' + src[XRANGEPLAIN] + ')' + '\\s*$';
- var HYPHENRANGELOOSE = R++;
- src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + '\\s+-\\s+' + '(' + src[XRANGEPLAINLOOSE] + ')' + '\\s*$'; // Star ranges basically just allow anything at all.
- var STAR = R++;
- src[STAR] = '(<|>)?=?\\s*\\*'; // Compile to actual regexp objects.
- // All are flag-free, unless they were created above with a flag.
- for (var i = 0; i < R; i++) {
- debug(i, src[i]);
- if (!re[i]) re[i] = new RegExp(src[i]);
- }
- exports.parse = parse;
- function parse(version, loose) {
- if (version instanceof SemVer) return version;
- if (typeof version !== 'string') return null;
- if (version.length > MAX_LENGTH) return null;
- var r = loose ? re[LOOSE] : re[FULL];
- if (!r.test(version)) return null;
- try {
- return new SemVer(version, loose);
- } catch (er) {
- return null;
- }
- }
- exports.valid = valid;
- function valid(version, loose) {
- var v = parse(version, loose);
- return v ? v.version : null;
- }
- exports.clean = clean;
- function clean(version, loose) {
- var s = parse(version.trim().replace(/^[=v]+/, ''), loose);
- return s ? s.version : null;
- }
- exports.SemVer = SemVer;
- function SemVer(version, loose) {
- if (version instanceof SemVer) {
- if (version.loose === loose) return version;else version = version.version;
- } else if (typeof version !== 'string') {
- throw new TypeError('Invalid Version: ' + version);
- }
- if (version.length > MAX_LENGTH) throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters');
- if (!(this instanceof SemVer)) return new SemVer(version, loose);
- debug('SemVer', version, loose);
- this.loose = loose;
- var m = version.trim().match(loose ? re[LOOSE] : re[FULL]);
- if (!m) throw new TypeError('Invalid Version: ' + version);
- this.raw = version; // these are actually numbers
- this.major = +m[1];
- this.minor = +m[2];
- this.patch = +m[3];
- if (this.major > MAX_SAFE_INTEGER || this.major < 0) throw new TypeError('Invalid major version');
- if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) throw new TypeError('Invalid minor version');
- if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) throw new TypeError('Invalid patch version'); // numberify any prerelease numeric ids
- if (!m[4]) this.prerelease = [];else this.prerelease = m[4].split('.').map(function (id) {
- if (/^[0-9]+$/.test(id)) {
- var num = +id;
- if (num >= 0 && num < MAX_SAFE_INTEGER) return num;
- }
- return id;
- });
- this.build = m[5] ? m[5].split('.') : [];
- this.format();
- }
- SemVer.prototype.format = function () {
- this.version = this.major + '.' + this.minor + '.' + this.patch;
- if (this.prerelease.length) this.version += '-' + this.prerelease.join('.');
- return this.version;
- };
- SemVer.prototype.toString = function () {
- return this.version;
- };
- SemVer.prototype.compare = function (other) {
- debug('SemVer.compare', this.version, this.loose, other);
- if (!(other instanceof SemVer)) other = new SemVer(other, this.loose);
- return this.compareMain(other) || this.comparePre(other);
- };
- SemVer.prototype.compareMain = function (other) {
- if (!(other instanceof SemVer)) other = new SemVer(other, this.loose);
- return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch);
- };
- SemVer.prototype.comparePre = function (other) {
- if (!(other instanceof SemVer)) other = new SemVer(other, this.loose); // NOT having a prerelease is > having one
- if (this.prerelease.length && !other.prerelease.length) return -1;else if (!this.prerelease.length && other.prerelease.length) return 1;else if (!this.prerelease.length && !other.prerelease.length) return 0;
- var i = 0;
- do {
- var a = this.prerelease[i];
- var b = other.prerelease[i];
- debug('prerelease compare', i, a, b);
- if (a === undefined && b === undefined) return 0;else if (b === undefined) return 1;else if (a === undefined) return -1;else if (a === b) continue;else return compareIdentifiers(a, b);
- } while (++i);
- }; // preminor will bump the version up to the next minor release, and immediately
- // down to pre-release. premajor and prepatch work the same way.
- SemVer.prototype.inc = function (release, identifier) {
- switch (release) {
- case 'premajor':
- this.prerelease.length = 0;
- this.patch = 0;
- this.minor = 0;
- this.major++;
- this.inc('pre', identifier);
- break;
- case 'preminor':
- this.prerelease.length = 0;
- this.patch = 0;
- this.minor++;
- this.inc('pre', identifier);
- break;
- case 'prepatch':
- // If this is already a prerelease, it will bump to the next version
- // drop any prereleases that might already exist, since they are not
- // relevant at this point.
- this.prerelease.length = 0;
- this.inc('patch', identifier);
- this.inc('pre', identifier);
- break;
- // If the input is a non-prerelease version, this acts the same as
- // prepatch.
- case 'prerelease':
- if (this.prerelease.length === 0) this.inc('patch', identifier);
- this.inc('pre', identifier);
- break;
- case 'major':
- // If this is a pre-major version, bump up to the same major version.
- // Otherwise increment major.
- // 1.0.0-5 bumps to 1.0.0
- // 1.1.0 bumps to 2.0.0
- if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) this.major++;
- this.minor = 0;
- this.patch = 0;
- this.prerelease = [];
- break;
- case 'minor':
- // If this is a pre-minor version, bump up to the same minor version.
- // Otherwise increment minor.
- // 1.2.0-5 bumps to 1.2.0
- // 1.2.1 bumps to 1.3.0
- if (this.patch !== 0 || this.prerelease.length === 0) this.minor++;
- this.patch = 0;
- this.prerelease = [];
- break;
- case 'patch':
- // If this is not a pre-release version, it will increment the patch.
- // If it is a pre-release it will bump up to the same patch version.
- // 1.2.0-5 patches to 1.2.0
- // 1.2.0 patches to 1.2.1
- if (this.prerelease.length === 0) this.patch++;
- this.prerelease = [];
- break;
- // This probably shouldn't be used publicly.
- // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction.
- case 'pre':
- if (this.prerelease.length === 0) this.prerelease = [0];else {
- var i = this.prerelease.length;
- while (--i >= 0) {
- if (typeof this.prerelease[i] === 'number') {
- this.prerelease[i]++;
- i = -2;
- }
- }
- if (i === -1) // didn't increment anything
- this.prerelease.push(0);
- }
- if (identifier) {
- // 1.2.0-beta.1 bumps to 1.2.0-beta.2,
- // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
- if (this.prerelease[0] === identifier) {
- if (isNaN(this.prerelease[1])) this.prerelease = [identifier, 0];
- } else this.prerelease = [identifier, 0];
- }
- break;
- default:
- throw new Error('invalid increment argument: ' + release);
- }
- this.format();
- this.raw = this.version;
- return this;
- };
- exports.inc = inc;
- function inc(version, release, loose, identifier) {
- if (typeof loose === 'string') {
- identifier = loose;
- loose = undefined;
- }
- try {
- return new SemVer(version, loose).inc(release, identifier).version;
- } catch (er) {
- return null;
- }
- }
- exports.diff = diff;
- function diff(version1, version2) {
- if (eq(version1, version2)) {
- return null;
- } else {
- var v1 = parse(version1);
- var v2 = parse(version2);
- if (v1.prerelease.length || v2.prerelease.length) {
- for (var key in v1) {
- if (key === 'major' || key === 'minor' || key === 'patch') {
- if (v1[key] !== v2[key]) {
- return 'pre' + key;
- }
- }
- }
- return 'prerelease';
- }
- for (var key in v1) {
- if (key === 'major' || key === 'minor' || key === 'patch') {
- if (v1[key] !== v2[key]) {
- return key;
- }
- }
- }
- }
- }
- exports.compareIdentifiers = compareIdentifiers;
- var numeric = /^[0-9]+$/;
- function compareIdentifiers(a, b) {
- var anum = numeric.test(a);
- var bnum = numeric.test(b);
- if (anum && bnum) {
- a = +a;
- b = +b;
- }
- return anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : a > b ? 1 : 0;
- }
- exports.rcompareIdentifiers = rcompareIdentifiers;
- function rcompareIdentifiers(a, b) {
- return compareIdentifiers(b, a);
- }
- exports.major = major;
- function major(a, loose) {
- return new SemVer(a, loose).major;
- }
- exports.minor = minor;
- function minor(a, loose) {
- return new SemVer(a, loose).minor;
- }
- exports.patch = patch;
- function patch(a, loose) {
- return new SemVer(a, loose).patch;
- }
- exports.compare = compare;
- function compare(a, b, loose) {
- return new SemVer(a, loose).compare(new SemVer(b, loose));
- }
- exports.compareLoose = compareLoose;
- function compareLoose(a, b) {
- return compare(a, b, true);
- }
- exports.rcompare = rcompare;
- function rcompare(a, b, loose) {
- return compare(b, a, loose);
- }
- exports.sort = sort;
- function sort(list, loose) {
- return list.sort(function (a, b) {
- return exports.compare(a, b, loose);
- });
- }
- exports.rsort = rsort;
- function rsort(list, loose) {
- return list.sort(function (a, b) {
- return exports.rcompare(a, b, loose);
- });
- }
- exports.gt = gt;
- function gt(a, b, loose) {
- return compare(a, b, loose) > 0;
- }
- exports.lt = lt;
- function lt(a, b, loose) {
- return compare(a, b, loose) < 0;
- }
- exports.eq = eq;
- function eq(a, b, loose) {
- return compare(a, b, loose) === 0;
- }
- exports.neq = neq;
- function neq(a, b, loose) {
- return compare(a, b, loose) !== 0;
- }
- exports.gte = gte;
- function gte(a, b, loose) {
- return compare(a, b, loose) >= 0;
- }
- exports.lte = lte;
- function lte(a, b, loose) {
- return compare(a, b, loose) <= 0;
- }
- exports.cmp = cmp;
- function cmp(a, op, b, loose) {
- var ret;
- switch (op) {
- case '===':
- if (typeof a === 'object') a = a.version;
- if (typeof b === 'object') b = b.version;
- ret = a === b;
- break;
- case '!==':
- if (typeof a === 'object') a = a.version;
- if (typeof b === 'object') b = b.version;
- ret = a !== b;
- break;
- case '':
- case '=':
- case '==':
- ret = eq(a, b, loose);
- break;
- case '!=':
- ret = neq(a, b, loose);
- break;
- case '>':
- ret = gt(a, b, loose);
- break;
- case '>=':
- ret = gte(a, b, loose);
- break;
- case '<':
- ret = lt(a, b, loose);
- break;
- case '<=':
- ret = lte(a, b, loose);
- break;
- default:
- throw new TypeError('Invalid operator: ' + op);
- }
- return ret;
- }
- exports.Comparator = Comparator;
- function Comparator(comp, loose) {
- if (comp instanceof Comparator) {
- if (comp.loose === loose) return comp;else comp = comp.value;
- }
- if (!(this instanceof Comparator)) return new Comparator(comp, loose);
- debug('comparator', comp, loose);
- this.loose = loose;
- this.parse(comp);
- if (this.semver === ANY) this.value = '';else this.value = this.operator + this.semver.version;
- debug('comp', this);
- }
- var ANY = {};
- Comparator.prototype.parse = function (comp) {
- var r = this.loose ? re[COMPARATORLOOSE] : re[COMPARATOR];
- var m = comp.match(r);
- if (!m) throw new TypeError('Invalid comparator: ' + comp);
- this.operator = m[1];
- if (this.operator === '=') this.operator = ''; // if it literally is just '>' or '' then allow anything.
- if (!m[2]) this.semver = ANY;else this.semver = new SemVer(m[2], this.loose);
- };
- Comparator.prototype.toString = function () {
- return this.value;
- };
- Comparator.prototype.test = function (version) {
- debug('Comparator.test', version, this.loose);
- if (this.semver === ANY) return true;
- if (typeof version === 'string') version = new SemVer(version, this.loose);
- return cmp(version, this.operator, this.semver, this.loose);
- };
- Comparator.prototype.intersects = function (comp, loose) {
- if (!(comp instanceof Comparator)) {
- throw new TypeError('a Comparator is required');
- }
- var rangeTmp;
- if (this.operator === '') {
- rangeTmp = new Range(comp.value, loose);
- return satisfies(this.value, rangeTmp, loose);
- } else if (comp.operator === '') {
- rangeTmp = new Range(this.value, loose);
- return satisfies(comp.semver, rangeTmp, loose);
- }
- var sameDirectionIncreasing = (this.operator === '>=' || this.operator === '>') && (comp.operator === '>=' || comp.operator === '>');
- var sameDirectionDecreasing = (this.operator === '<=' || this.operator === '<') && (comp.operator === '<=' || comp.operator === '<');
- var sameSemVer = this.semver.version === comp.semver.version;
- var differentDirectionsInclusive = (this.operator === '>=' || this.operator === '<=') && (comp.operator === '>=' || comp.operator === '<=');
- var oppositeDirectionsLessThan = cmp(this.semver, '<', comp.semver, loose) && (this.operator === '>=' || this.operator === '>') && (comp.operator === '<=' || comp.operator === '<');
- var oppositeDirectionsGreaterThan = cmp(this.semver, '>', comp.semver, loose) && (this.operator === '<=' || this.operator === '<') && (comp.operator === '>=' || comp.operator === '>');
- return sameDirectionIncreasing || sameDirectionDecreasing || sameSemVer && differentDirectionsInclusive || oppositeDirectionsLessThan || oppositeDirectionsGreaterThan;
- };
- exports.Range = Range;
- function Range(range, loose) {
- if (range instanceof Range) {
- if (range.loose === loose) {
- return range;
- } else {
- return new Range(range.raw, loose);
- }
- }
- if (range instanceof Comparator) {
- return new Range(range.value, loose);
- }
- if (!(this instanceof Range)) return new Range(range, loose);
- this.loose = loose; // First, split based on boolean or ||
- this.raw = range;
- this.set = range.split(/\s*\|\|\s*/).map(function (range) {
- return this.parseRange(range.trim());
- }, this).filter(function (c) {
- // throw out any that are not relevant for whatever reason
- return c.length;
- });
- if (!this.set.length) {
- throw new TypeError('Invalid SemVer Range: ' + range);
- }
- this.format();
- }
- Range.prototype.format = function () {
- this.range = this.set.map(function (comps) {
- return comps.join(' ').trim();
- }).join('||').trim();
- return this.range;
- };
- Range.prototype.toString = function () {
- return this.range;
- };
- Range.prototype.parseRange = function (range) {
- var loose = this.loose;
- range = range.trim();
- debug('range', range, loose); // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
- var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE];
- range = range.replace(hr, hyphenReplace);
- debug('hyphen replace', range); // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
- range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace);
- debug('comparator trim', range, re[COMPARATORTRIM]); // `~ 1.2.3` => `~1.2.3`
- range = range.replace(re[TILDETRIM], tildeTrimReplace); // `^ 1.2.3` => `^1.2.3`
- range = range.replace(re[CARETTRIM], caretTrimReplace); // normalize spaces
- range = range.split(/\s+/).join(' '); // At this point, the range is completely trimmed and
- // ready to be split into comparators.
- var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR];
- var set = range.split(' ').map(function (comp) {
- return parseComparator(comp, loose);
- }).join(' ').split(/\s+/);
- if (this.loose) {
- // in loose mode, throw out any that are not valid comparators
- set = set.filter(function (comp) {
- return !!comp.match(compRe);
- });
- }
- set = set.map(function (comp) {
- return new Comparator(comp, loose);
- });
- return set;
- };
- Range.prototype.intersects = function (range, loose) {
- if (!(range instanceof Range)) {
- throw new TypeError('a Range is required');
- }
- return this.set.some(function (thisComparators) {
- return thisComparators.every(function (thisComparator) {
- return range.set.some(function (rangeComparators) {
- return rangeComparators.every(function (rangeComparator) {
- return thisComparator.intersects(rangeComparator, loose);
- });
- });
- });
- });
- }; // Mostly just for testing and legacy API reasons
- exports.toComparators = toComparators;
- function toComparators(range, loose) {
- return new Range(range, loose).set.map(function (comp) {
- return comp.map(function (c) {
- return c.value;
- }).join(' ').trim().split(' ');
- });
- } // comprised of xranges, tildes, stars, and gtlt's at this point.
- // already replaced the hyphen ranges
- // turn into a set of JUST comparators.
- function parseComparator(comp, loose) {
- debug('comp', comp);
- comp = replaceCarets(comp, loose);
- debug('caret', comp);
- comp = replaceTildes(comp, loose);
- debug('tildes', comp);
- comp = replaceXRanges(comp, loose);
- debug('xrange', comp);
- comp = replaceStars(comp, loose);
- debug('stars', comp);
- return comp;
- }
- function isX(id) {
- return !id || id.toLowerCase() === 'x' || id === '*';
- } // ~, ~> --> * (any, kinda silly)
- // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0
- // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0
- // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0
- // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0
- // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0
- function replaceTildes(comp, loose) {
- return comp.trim().split(/\s+/).map(function (comp) {
- return replaceTilde(comp, loose);
- }).join(' ');
- }
- function replaceTilde(comp, loose) {
- var r = loose ? re[TILDELOOSE] : re[TILDE];
- return comp.replace(r, function (_, M, m, p, pr) {
- debug('tilde', comp, _, M, m, p, pr);
- var ret;
- if (isX(M)) ret = '';else if (isX(m)) ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';else if (isX(p)) // ~1.2 == >=1.2.0 <1.3.0
- ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';else if (pr) {
- debug('replaceTilde pr', pr);
- if (pr.charAt(0) !== '-') pr = '-' + pr;
- ret = '>=' + M + '.' + m + '.' + p + pr + ' <' + M + '.' + (+m + 1) + '.0';
- } else // ~1.2.3 == >=1.2.3 <1.3.0
- ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0';
- debug('tilde return', ret);
- return ret;
- });
- } // ^ --> * (any, kinda silly)
- // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0
- // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0
- // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0
- // ^1.2.3 --> >=1.2.3 <2.0.0
- // ^1.2.0 --> >=1.2.0 <2.0.0
- function replaceCarets(comp, loose) {
- return comp.trim().split(/\s+/).map(function (comp) {
- return replaceCaret(comp, loose);
- }).join(' ');
- }
- function replaceCaret(comp, loose) {
- debug('caret', comp, loose);
- var r = loose ? re[CARETLOOSE] : re[CARET];
- return comp.replace(r, function (_, M, m, p, pr) {
- debug('caret', comp, _, M, m, p, pr);
- var ret;
- if (isX(M)) ret = '';else if (isX(m)) ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';else if (isX(p)) {
- if (M === '0') ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';else ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0';
- } else if (pr) {
- debug('replaceCaret pr', pr);
- if (pr.charAt(0) !== '-') pr = '-' + pr;
- if (M === '0') {
- if (m === '0') ret = '>=' + M + '.' + m + '.' + p + pr + ' <' + M + '.' + m + '.' + (+p + 1);else ret = '>=' + M + '.' + m + '.' + p + pr + ' <' + M + '.' + (+m + 1) + '.0';
- } else ret = '>=' + M + '.' + m + '.' + p + pr + ' <' + (+M + 1) + '.0.0';
- } else {
- debug('no pr');
- if (M === '0') {
- if (m === '0') ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + m + '.' + (+p + 1);else ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0';
- } else ret = '>=' + M + '.' + m + '.' + p + ' <' + (+M + 1) + '.0.0';
- }
- debug('caret return', ret);
- return ret;
- });
- }
- function replaceXRanges(comp, loose) {
- debug('replaceXRanges', comp, loose);
- return comp.split(/\s+/).map(function (comp) {
- return replaceXRange(comp, loose);
- }).join(' ');
- }
- function replaceXRange(comp, loose) {
- comp = comp.trim();
- var r = loose ? re[XRANGELOOSE] : re[XRANGE];
- return comp.replace(r, function (ret, gtlt, M, m, p, pr) {
- debug('xRange', comp, ret, gtlt, M, m, p, pr);
- var xM = isX(M);
- var xm = xM || isX(m);
- var xp = xm || isX(p);
- var anyX = xp;
- if (gtlt === '=' && anyX) gtlt = '';
- if (xM) {
- if (gtlt === '>' || gtlt === '<') {
- // nothing is allowed
- ret = '<0.0.0';
- } else {
- // nothing is forbidden
- ret = '*';
- }
- } else if (gtlt && anyX) {
- // replace X with 0
- if (xm) m = 0;
- if (xp) p = 0;
- if (gtlt === '>') {
- // >1 => >=2.0.0
- // >1.2 => >=1.3.0
- // >1.2.3 => >= 1.2.4
- gtlt = '>=';
- if (xm) {
- M = +M + 1;
- m = 0;
- p = 0;
- } else if (xp) {
- m = +m + 1;
- p = 0;
- }
- } else if (gtlt === '<=') {
- // <=0.7.x is actually <0.8.0, since any 0.7.x should
- // pass. Similarly, <=7.x is actually <8.0.0, etc.
- gtlt = '<';
- if (xm) M = +M + 1;else m = +m + 1;
- }
- ret = gtlt + M + '.' + m + '.' + p;
- } else if (xm) {
- ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';
- } else if (xp) {
- ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';
- }
- debug('xRange return', ret);
- return ret;
- });
- } // Because * is AND-ed with everything else in the comparator,
- // and '' means "any version", just remove the *s entirely.
- function replaceStars(comp, loose) {
- debug('replaceStars', comp, loose); // Looseness is ignored here. star is always as loose as it gets!
- return comp.trim().replace(re[STAR], '');
- } // This function is passed to string.replace(re[HYPHENRANGE])
- // M, m, patch, prerelease, build
- // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5
- // 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do
- // 1.2 - 3.4 => >=1.2.0 <3.5.0
- function hyphenReplace($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) {
- if (isX(fM)) from = '';else if (isX(fm)) from = '>=' + fM + '.0.0';else if (isX(fp)) from = '>=' + fM + '.' + fm + '.0';else from = '>=' + from;
- if (isX(tM)) to = '';else if (isX(tm)) to = '<' + (+tM + 1) + '.0.0';else if (isX(tp)) to = '<' + tM + '.' + (+tm + 1) + '.0';else if (tpr) to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr;else to = '<=' + to;
- return (from + ' ' + to).trim();
- } // if ANY of the sets match ALL of its comparators, then pass
- Range.prototype.test = function (version) {
- if (!version) return false;
- if (typeof version === 'string') version = new SemVer(version, this.loose);
- for (var i = 0; i < this.set.length; i++) {
- if (testSet(this.set[i], version)) return true;
- }
- return false;
- };
- function testSet(set, version) {
- for (var i = 0; i < set.length; i++) {
- if (!set[i].test(version)) return false;
- }
- if (version.prerelease.length) {
- // Find the set of versions that are allowed to have prereleases
- // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0
- // That should allow `1.2.3-pr.2` to pass.
- // However, `1.2.4-alpha.notready` should NOT be allowed,
- // even though it's within the range set by the comparators.
- for (var i = 0; i < set.length; i++) {
- debug(set[i].semver);
- if (set[i].semver === ANY) continue;
- if (set[i].semver.prerelease.length > 0) {
- var allowed = set[i].semver;
- if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) return true;
- }
- } // Version has a -pre, but it's not one of the ones we like.
- return false;
- }
- return true;
- }
- exports.satisfies = satisfies;
- function satisfies(version, range, loose) {
- try {
- range = new Range(range, loose);
- } catch (er) {
- return false;
- }
- return range.test(version);
- }
- exports.maxSatisfying = maxSatisfying;
- function maxSatisfying(versions, range, loose) {
- var max = null;
- var maxSV = null;
- try {
- var rangeObj = new Range(range, loose);
- } catch (er) {
- return null;
- }
- versions.forEach(function (v) {
- if (rangeObj.test(v)) {
- // satisfies(v, range, loose)
- if (!max || maxSV.compare(v) === -1) {
- // compare(max, v, true)
- max = v;
- maxSV = new SemVer(max, loose);
- }
- }
- });
- return max;
- }
- exports.minSatisfying = minSatisfying;
- function minSatisfying(versions, range, loose) {
- var min = null;
- var minSV = null;
- try {
- var rangeObj = new Range(range, loose);
- } catch (er) {
- return null;
- }
- versions.forEach(function (v) {
- if (rangeObj.test(v)) {
- // satisfies(v, range, loose)
- if (!min || minSV.compare(v) === 1) {
- // compare(min, v, true)
- min = v;
- minSV = new SemVer(min, loose);
- }
- }
- });
- return min;
- }
- exports.validRange = validRange;
- function validRange(range, loose) {
- try {
- // Return '*' instead of '' so that truthiness works.
- // This will throw if it's invalid anyway
- return new Range(range, loose).range || '*';
- } catch (er) {
- return null;
- }
- } // Determine if version is less than all the versions possible in the range
- exports.ltr = ltr;
- function ltr(version, range, loose) {
- return outside(version, range, '<', loose);
- } // Determine if version is greater than all the versions possible in the range.
- exports.gtr = gtr;
- function gtr(version, range, loose) {
- return outside(version, range, '>', loose);
- }
- exports.outside = outside;
- function outside(version, range, hilo, loose) {
- version = new SemVer(version, loose);
- range = new Range(range, loose);
- var gtfn, ltefn, ltfn, comp, ecomp;
- switch (hilo) {
- case '>':
- gtfn = gt;
- ltefn = lte;
- ltfn = lt;
- comp = '>';
- ecomp = '>=';
- break;
- case '<':
- gtfn = lt;
- ltefn = gte;
- ltfn = gt;
- comp = '<';
- ecomp = '<=';
- break;
- default:
- throw new TypeError('Must provide a hilo val of "<" or ">"');
- } // If it satisifes the range it is not outside
- if (satisfies(version, range, loose)) {
- return false;
- } // From now on, variable terms are as if we're in "gtr" mode.
- // but note that everything is flipped for the "ltr" function.
- for (var i = 0; i < range.set.length; ++i) {
- var comparators = range.set[i];
- var high = null;
- var low = null;
- comparators.forEach(function (comparator) {
- if (comparator.semver === ANY) {
- comparator = new Comparator('>=0.0.0');
- }
- high = high || comparator;
- low = low || comparator;
- if (gtfn(comparator.semver, high.semver, loose)) {
- high = comparator;
- } else if (ltfn(comparator.semver, low.semver, loose)) {
- low = comparator;
- }
- }); // If the edge version comparator has a operator then our version
- // isn't outside it
- if (high.operator === comp || high.operator === ecomp) {
- return false;
- } // If the lowest version comparator has an operator and our version
- // is less than it then it isn't higher than the range
- if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) {
- return false;
- } else if (low.operator === ecomp && ltfn(version, low.semver)) {
- return false;
- }
- }
- return true;
- }
- exports.prerelease = prerelease;
- function prerelease(version, loose) {
- var parsed = parse(version, loose);
- return parsed && parsed.prerelease.length ? parsed.prerelease : null;
- }
- exports.intersects = intersects;
- function intersects(r1, r2, loose) {
- r1 = new Range(r1, loose);
- r2 = new Range(r2, loose);
- return r1.intersects(r2);
- }
- });
- var arrayify = function arrayify(object, keyName) {
- return Object.keys(object).reduce(function (array, key) {
- return array.concat(Object.assign({
- [keyName]: key
- }, object[key]));
- }, []);
- };
- var dedent_1 = createCommonjsModule(function (module) {
- "use strict";
- function dedent(strings) {
- var raw = void 0;
- if (typeof strings === "string") {
- // dedent can be used as a plain function
- raw = [strings];
- } else {
- raw = strings.raw;
- } // first, perform interpolation
- var result = "";
- for (var i = 0; i < raw.length; i++) {
- result += raw[i]. // join lines when there is a suppressed newline
- replace(/\\\n[ \t]*/g, ""). // handle escaped backticks
- replace(/\\`/g, "`");
- if (i < (arguments.length <= 1 ? 0 : arguments.length - 1)) {
- result += arguments.length <= i + 1 ? undefined : arguments[i + 1];
- }
- } // now strip indentation
- var lines = result.split("\n");
- var mindent = null;
- lines.forEach(function (l) {
- var m = l.match(/^(\s+)\S+/);
- if (m) {
- var indent = m[1].length;
- if (!mindent) {
- // this is the first indented line
- mindent = indent;
- } else {
- mindent = Math.min(mindent, indent);
- }
- }
- });
- if (mindent !== null) {
- result = lines.map(function (l) {
- return l[0] === " " ? l.slice(mindent) : l;
- }).join("\n");
- } // dedent eats leading and trailing whitespace too
- result = result.trim(); // handle escaped newlines at the end to ensure they don't get stripped too
- return result.replace(/\\n/g, "\n");
- }
- {
- module.exports = dedent;
- }
- });
- var CATEGORY_CONFIG = "Config";
- var CATEGORY_EDITOR = "Editor";
- var CATEGORY_FORMAT = "Format";
- var CATEGORY_OTHER = "Other";
- var CATEGORY_OUTPUT = "Output";
- var CATEGORY_GLOBAL = "Global";
- var CATEGORY_SPECIAL = "Special";
- /**
- * @typedef {Object} OptionInfo
- * @property {string} since - available since version
- * @property {string} category
- * @property {'int' | 'boolean' | 'choice' | 'path'} type
- * @property {boolean} array - indicate it's an array of the specified type
- * @property {boolean?} deprecated - deprecated since version
- * @property {OptionRedirectInfo?} redirect - redirect deprecated option
- * @property {string} description
- * @property {string?} oppositeDescription - for `false` option
- * @property {OptionValueInfo} default
- * @property {OptionRangeInfo?} range - for type int
- * @property {OptionChoiceInfo?} choices - for type choice
- * @property {(value: any) => boolean} exception
- *
- * @typedef {number | boolean | string} OptionValue
- * @typedef {OptionValue | [{ value: OptionValue[] }] | Array<{ since: string, value: OptionValue}>} OptionValueInfo
- *
- * @typedef {Object} OptionRedirectInfo
- * @property {string} option
- * @property {OptionValue} value
- *
- * @typedef {Object} OptionRangeInfo
- * @property {number} start - recommended range start
- * @property {number} end - recommended range end
- * @property {number} step - recommended range step
- *
- * @typedef {Object} OptionChoiceInfo
- * @property {boolean | string} value - boolean for the option that is originally boolean type
- * @property {string?} description - undefined if redirect
- * @property {string?} since - undefined if available since the first version of the option
- * @property {string?} deprecated - deprecated since version
- * @property {OptionValueInfo?} redirect - redirect deprecated value
- *
- * @property {string?} cliName
- * @property {string?} cliCategory
- * @property {string?} cliDescription
- */
- /** @type {{ [name: string]: OptionInfo } */
- var options$2 = {
- cursorOffset: {
- since: "1.4.0",
- category: CATEGORY_SPECIAL,
- type: "int",
- default: -1,
- range: {
- start: -1,
- end: Infinity,
- step: 1
- },
- description: dedent_1`
- Print (to stderr) where a cursor at the given position would move to after formatting.
- This option cannot be used with --range-start and --range-end.
- `,
- cliCategory: CATEGORY_EDITOR
- },
- endOfLine: {
- since: "1.15.0",
- category: CATEGORY_GLOBAL,
- type: "choice",
- default: "auto",
- description: "Which end of line characters to apply.",
- choices: [{
- value: "auto",
- description: dedent_1`
- Maintain existing
- (mixed values within one file are normalised by looking at what's used after the first line)
- `
- }, {
- value: "lf",
- description: "Line Feed only (\\n), common on Linux and macOS as well as inside git repos"
- }, {
- value: "crlf",
- description: "Carriage Return + Line Feed characters (\\r\\n), common on Windows"
- }, {
- value: "cr",
- description: "Carriage Return character only (\\r), used very rarely"
- }]
- },
- filepath: {
- since: "1.4.0",
- category: CATEGORY_SPECIAL,
- type: "path",
- description: "Specify the input filepath. This will be used to do parser inference.",
- cliName: "stdin-filepath",
- cliCategory: CATEGORY_OTHER,
- cliDescription: "Path to the file to pretend that stdin comes from."
- },
- insertPragma: {
- since: "1.8.0",
- category: CATEGORY_SPECIAL,
- type: "boolean",
- default: false,
- description: "Insert @format pragma into file's first docblock comment.",
- cliCategory: CATEGORY_OTHER
- },
- parser: {
- since: "0.0.10",
- category: CATEGORY_GLOBAL,
- type: "choice",
- default: [{
- since: "0.0.10",
- value: "babylon"
- }, {
- since: "1.13.0",
- value: undefined
- }],
- description: "Which parser to use.",
- exception: function exception(value) {
- return typeof value === "string" || typeof value === "function";
- },
- choices: [{
- value: "flow",
- description: "Flow"
- }, {
- value: "babylon",
- description: "JavaScript",
- deprecated: "1.16.0",
- redirect: "babel"
- }, {
- value: "babel",
- since: "1.16.0",
- description: "JavaScript"
- }, {
- value: "babel-flow",
- since: "1.16.0",
- description: "Flow"
- }, {
- value: "typescript",
- since: "1.4.0",
- description: "TypeScript"
- }, {
- value: "css",
- since: "1.7.1",
- description: "CSS"
- }, {
- value: "postcss",
- since: "1.4.0",
- description: "CSS/Less/SCSS",
- deprecated: "1.7.1",
- redirect: "css"
- }, {
- value: "less",
- since: "1.7.1",
- description: "Less"
- }, {
- value: "scss",
- since: "1.7.1",
- description: "SCSS"
- }, {
- value: "json",
- since: "1.5.0",
- description: "JSON"
- }, {
- value: "json5",
- since: "1.13.0",
- description: "JSON5"
- }, {
- value: "json-stringify",
- since: "1.13.0",
- description: "JSON.stringify"
- }, {
- value: "graphql",
- since: "1.5.0",
- description: "GraphQL"
- }, {
- value: "markdown",
- since: "1.8.0",
- description: "Markdown"
- }, {
- value: "mdx",
- since: "1.15.0",
- description: "MDX"
- }, {
- value: "vue",
- since: "1.10.0",
- description: "Vue"
- }, {
- value: "yaml",
- since: "1.14.0",
- description: "YAML"
- }, {
- value: "glimmer",
- since: null,
- description: "Handlebars"
- }, {
- value: "html",
- since: "1.15.0",
- description: "HTML"
- }, {
- value: "angular",
- since: "1.15.0",
- description: "Angular"
- }]
- },
- plugins: {
- since: "1.10.0",
- type: "path",
- array: true,
- default: [{
- value: []
- }],
- category: CATEGORY_GLOBAL,
- description: "Add a plugin. Multiple plugins can be passed as separate `--plugin`s.",
- exception: function exception(value) {
- return typeof value === "string" || typeof value === "object";
- },
- cliName: "plugin",
- cliCategory: CATEGORY_CONFIG
- },
- pluginSearchDirs: {
- since: "1.13.0",
- type: "path",
- array: true,
- default: [{
- value: []
- }],
- category: CATEGORY_GLOBAL,
- description: dedent_1`
- Custom directory that contains prettier plugins in node_modules subdirectory.
- Overrides default behavior when plugins are searched relatively to the location of Prettier.
- Multiple values are accepted.
- `,
- exception: function exception(value) {
- return typeof value === "string" || typeof value === "object";
- },
- cliName: "plugin-search-dir",
- cliCategory: CATEGORY_CONFIG
- },
- printWidth: {
- since: "0.0.0",
- category: CATEGORY_GLOBAL,
- type: "int",
- default: 80,
- description: "The line length where Prettier will try wrap.",
- range: {
- start: 0,
- end: Infinity,
- step: 1
- }
- },
- rangeEnd: {
- since: "1.4.0",
- category: CATEGORY_SPECIAL,
- type: "int",
- default: Infinity,
- range: {
- start: 0,
- end: Infinity,
- step: 1
- },
- description: dedent_1`
- Format code ending at a given character offset (exclusive).
- The range will extend forwards to the end of the selected statement.
- This option cannot be used with --cursor-offset.
- `,
- cliCategory: CATEGORY_EDITOR
- },
- rangeStart: {
- since: "1.4.0",
- category: CATEGORY_SPECIAL,
- type: "int",
- default: 0,
- range: {
- start: 0,
- end: Infinity,
- step: 1
- },
- description: dedent_1`
- Format code starting at a given character offset.
- The range will extend backwards to the start of the first line containing the selected statement.
- This option cannot be used with --cursor-offset.
- `,
- cliCategory: CATEGORY_EDITOR
- },
- requirePragma: {
- since: "1.7.0",
- category: CATEGORY_SPECIAL,
- type: "boolean",
- default: false,
- description: dedent_1`
- Require either '@prettier' or '@format' to be present in the file's first docblock comment
- in order for it to be formatted.
- `,
- cliCategory: CATEGORY_OTHER
- },
- tabWidth: {
- type: "int",
- category: CATEGORY_GLOBAL,
- default: 2,
- description: "Number of spaces per indentation level.",
- range: {
- start: 0,
- end: Infinity,
- step: 1
- }
- },
- useFlowParser: {
- since: "0.0.0",
- category: CATEGORY_GLOBAL,
- type: "boolean",
- default: [{
- since: "0.0.0",
- value: false
- }, {
- since: "1.15.0",
- value: undefined
- }],
- deprecated: "0.0.10",
- description: "Use flow parser.",
- redirect: {
- option: "parser",
- value: "flow"
- },
- cliName: "flow-parser"
- },
- useTabs: {
- since: "1.0.0",
- category: CATEGORY_GLOBAL,
- type: "boolean",
- default: false,
- description: "Indent with tabs instead of spaces."
- }
- };
- var coreOptions$1 = {
- CATEGORY_CONFIG,
- CATEGORY_EDITOR,
- CATEGORY_FORMAT,
- CATEGORY_OTHER,
- CATEGORY_OUTPUT,
- CATEGORY_GLOBAL,
- CATEGORY_SPECIAL,
- options: options$2
- };
- var require$$0 = ( _package$1 && _package ) || _package$1;
- var currentVersion = require$$0.version;
- var coreOptions = coreOptions$1.options;
- function getSupportInfo$2(version, opts) {
- opts = Object.assign({
- plugins: [],
- showUnreleased: false,
- showDeprecated: false,
- showInternal: false
- }, opts);
- if (!version) {
- // pre-release version is smaller than the normal version in semver,
- // we need to treat it as the normal one so as to test new features.
- version = currentVersion.split("-", 1)[0];
- }
- var plugins = opts.plugins;
- var options = arrayify(Object.assign(plugins.reduce(function (currentOptions, plugin) {
- return Object.assign(currentOptions, plugin.options);
- }, {}), coreOptions), "name").sort(function (a, b) {
- return a.name === b.name ? 0 : a.name < b.name ? -1 : 1;
- }).filter(filterSince).filter(filterDeprecated).map(mapDeprecated).map(mapInternal).map(function (option) {
- var newOption = Object.assign({}, option);
- if (Array.isArray(newOption.default)) {
- newOption.default = newOption.default.length === 1 ? newOption.default[0].value : newOption.default.filter(filterSince).sort(function (info1, info2) {
- return semver.compare(info2.since, info1.since);
- })[0].value;
- }
- if (Array.isArray(newOption.choices)) {
- newOption.choices = newOption.choices.filter(filterSince).filter(filterDeprecated).map(mapDeprecated);
- }
- return newOption;
- }).map(function (option) {
- var filteredPlugins = plugins.filter(function (plugin) {
- return plugin.defaultOptions && plugin.defaultOptions[option.name];
- });
- var pluginDefaults = filteredPlugins.reduce(function (reduced, plugin) {
- reduced[plugin.name] = plugin.defaultOptions[option.name];
- return reduced;
- }, {});
- return Object.assign(option, {
- pluginDefaults
- });
- });
- var usePostCssParser = semver.lt(version, "1.7.1");
- var languages = plugins.reduce(function (all, plugin) {
- return all.concat(plugin.languages || []);
- }, []).filter(filterSince).map(function (language) {
- // Prevent breaking changes
- if (language.name === "Markdown") {
- return Object.assign({}, language, {
- parsers: ["markdown"]
- });
- }
- if (language.name === "TypeScript") {
- return Object.assign({}, language, {
- parsers: ["typescript"]
- });
- }
- if (usePostCssParser && (language.name === "CSS" || language.group === "CSS")) {
- return Object.assign({}, language, {
- parsers: ["postcss"]
- });
- }
- return language;
- });
- return {
- languages,
- options
- };
- function filterSince(object) {
- return opts.showUnreleased || !("since" in object) || object.since && semver.gte(version, object.since);
- }
- function filterDeprecated(object) {
- return opts.showDeprecated || !("deprecated" in object) || object.deprecated && semver.lt(version, object.deprecated);
- }
- function mapDeprecated(object) {
- if (!object.deprecated || opts.showDeprecated) {
- return object;
- }
- var newObject = Object.assign({}, object);
- delete newObject.deprecated;
- delete newObject.redirect;
- return newObject;
- }
- function mapInternal(object) {
- if (opts.showInternal) {
- return object;
- }
- var newObject = Object.assign({}, object);
- delete newObject.cliName;
- delete newObject.cliCategory;
- delete newObject.cliDescription;
- return newObject;
- }
- }
- var support = {
- getSupportInfo: getSupportInfo$2
- };
- /*! *****************************************************************************
- Copyright (c) Microsoft Corporation. All rights reserved.
- Licensed under the Apache License, Version 2.0 (the "License"); you may not use
- this file except in compliance with the License. You may obtain a copy of the
- License at http://www.apache.org/licenses/LICENSE-2.0
-
- THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
- WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
- MERCHANTABLITY OR NON-INFRINGEMENT.
-
- See the Apache Version 2.0 License for specific language governing permissions
- and limitations under the License.
- ***************************************************************************** */
- /* global Reflect, Promise */
- var _extendStatics = function extendStatics(d, b) {
- _extendStatics = Object.setPrototypeOf || {
- __proto__: []
- } instanceof Array && function (d, b) {
- d.__proto__ = b;
- } || function (d, b) {
- for (var p in b) {
- if (b.hasOwnProperty(p)) d[p] = b[p];
- }
- };
- return _extendStatics(d, b);
- };
- function __extends(d, b) {
- _extendStatics(d, b);
- function __() {
- this.constructor = d;
- }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- }
- var _assign = function __assign() {
- _assign = Object.assign || function __assign(t) {
- for (var s, i = 1, n = arguments.length; i < n; i++) {
- s = arguments[i];
- for (var p in s) {
- if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
- }
- }
- return t;
- };
- return _assign.apply(this, arguments);
- };
- function __rest(s, e) {
- var t = {};
- for (var p in s) {
- if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
- }
- if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
- if (e.indexOf(p[i]) < 0) t[p[i]] = s[p[i]];
- }
- return t;
- }
- function __decorate(decorators, target, key, desc) {
- var c = arguments.length,
- r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc,
- d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);else for (var i = decorators.length - 1; i >= 0; i--) {
- if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- }
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- }
- function __param(paramIndex, decorator) {
- return function (target, key) {
- decorator(target, key, paramIndex);
- };
- }
- function __metadata(metadataKey, metadataValue) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
- }
- function __awaiter(thisArg, _arguments, P, generator) {
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) {
- try {
- step(generator.next(value));
- } catch (e) {
- reject(e);
- }
- }
- function rejected(value) {
- try {
- step(generator["throw"](value));
- } catch (e) {
- reject(e);
- }
- }
- function step(result) {
- result.done ? resolve(result.value) : new P(function (resolve) {
- resolve(result.value);
- }).then(fulfilled, rejected);
- }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- }
- function __generator(thisArg, body) {
- var _ = {
- label: 0,
- sent: function sent() {
- if (t[0] & 1) throw t[1];
- return t[1];
- },
- trys: [],
- ops: []
- },
- f,
- y,
- t,
- g;
- return g = {
- next: verb(0),
- "throw": verb(1),
- "return": verb(2)
- }, typeof Symbol === "function" && (g[Symbol.iterator] = function () {
- return this;
- }), g;
- function verb(n) {
- return function (v) {
- return step([n, v]);
- };
- }
- function step(op) {
- if (f) throw new TypeError("Generator is already executing.");
- while (_) {
- try {
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
- if (y = 0, t) op = [op[0] & 2, t.value];
- switch (op[0]) {
- case 0:
- case 1:
- t = op;
- break;
- case 4:
- _.label++;
- return {
- value: op[1],
- done: false
- };
- case 5:
- _.label++;
- y = op[1];
- op = [0];
- continue;
- case 7:
- op = _.ops.pop();
- _.trys.pop();
- continue;
- default:
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
- _ = 0;
- continue;
- }
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
- _.label = op[1];
- break;
- }
- if (op[0] === 6 && _.label < t[1]) {
- _.label = t[1];
- t = op;
- break;
- }
- if (t && _.label < t[2]) {
- _.label = t[2];
- _.ops.push(op);
- break;
- }
- if (t[2]) _.ops.pop();
- _.trys.pop();
- continue;
- }
- op = body.call(thisArg, _);
- } catch (e) {
- op = [6, e];
- y = 0;
- } finally {
- f = t = 0;
- }
- }
- if (op[0] & 5) throw op[1];
- return {
- value: op[0] ? op[1] : void 0,
- done: true
- };
- }
- }
- function __exportStar(m, exports) {
- for (var p in m) {
- if (!exports.hasOwnProperty(p)) exports[p] = m[p];
- }
- }
- function __values(o) {
- var m = typeof Symbol === "function" && o[Symbol.iterator],
- i = 0;
- if (m) return m.call(o);
- return {
- next: function next() {
- if (o && i >= o.length) o = void 0;
- return {
- value: o && o[i++],
- done: !o
- };
- }
- };
- }
- function __read(o, n) {
- var m = typeof Symbol === "function" && o[Symbol.iterator];
- if (!m) return o;
- var i = m.call(o),
- r,
- ar = [],
- e;
- try {
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) {
- ar.push(r.value);
- }
- } catch (error) {
- e = {
- error: error
- };
- } finally {
- try {
- if (r && !r.done && (m = i["return"])) m.call(i);
- } finally {
- if (e) throw e.error;
- }
- }
- return ar;
- }
- function __spread() {
- for (var ar = [], i = 0; i < arguments.length; i++) {
- ar = ar.concat(__read(arguments[i]));
- }
- return ar;
- }
- function __await(v) {
- return this instanceof __await ? (this.v = v, this) : new __await(v);
- }
- function __asyncGenerator(thisArg, _arguments, generator) {
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
- var g = generator.apply(thisArg, _arguments || []),
- i,
- q = [];
- return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () {
- return this;
- }, i;
- function verb(n) {
- if (g[n]) i[n] = function (v) {
- return new Promise(function (a, b) {
- q.push([n, v, a, b]) > 1 || resume(n, v);
- });
- };
- }
- function resume(n, v) {
- try {
- step(g[n](v));
- } catch (e) {
- settle(q[0][3], e);
- }
- }
- function step(r) {
- r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
- }
- function fulfill(value) {
- resume("next", value);
- }
- function reject(value) {
- resume("throw", value);
- }
- function settle(f, v) {
- if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]);
- }
- }
- function __asyncDelegator(o) {
- var i, p;
- return i = {}, verb("next"), verb("throw", function (e) {
- throw e;
- }), verb("return"), i[Symbol.iterator] = function () {
- return this;
- }, i;
- function verb(n, f) {
- i[n] = o[n] ? function (v) {
- return (p = !p) ? {
- value: __await(o[n](v)),
- done: n === "return"
- } : f ? f(v) : v;
- } : f;
- }
- }
- function __asyncValues(o) {
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
- var m = o[Symbol.asyncIterator],
- i;
- return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () {
- return this;
- }, i);
- function verb(n) {
- i[n] = o[n] && function (v) {
- return new Promise(function (resolve, reject) {
- v = o[n](v), settle(resolve, reject, v.done, v.value);
- });
- };
- }
- function settle(resolve, reject, d, v) {
- Promise.resolve(v).then(function (v) {
- resolve({
- value: v,
- done: d
- });
- }, reject);
- }
- }
- function __makeTemplateObject(cooked, raw) {
- if (Object.defineProperty) {
- Object.defineProperty(cooked, "raw", {
- value: raw
- });
- } else {
- cooked.raw = raw;
- }
- return cooked;
- }
- function __importStar(mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) {
- if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
- }
- result.default = mod;
- return result;
- }
- function __importDefault(mod) {
- return mod && mod.__esModule ? mod : {
- default: mod
- };
- }
- var tslib_1 = Object.freeze({
- __extends: __extends,
- get __assign () { return _assign; },
- __rest: __rest,
- __decorate: __decorate,
- __param: __param,
- __metadata: __metadata,
- __awaiter: __awaiter,
- __generator: __generator,
- __exportStar: __exportStar,
- __values: __values,
- __read: __read,
- __spread: __spread,
- __await: __await,
- __asyncGenerator: __asyncGenerator,
- __asyncDelegator: __asyncDelegator,
- __asyncValues: __asyncValues,
- __makeTemplateObject: __makeTemplateObject,
- __importStar: __importStar,
- __importDefault: __importDefault
- });
- var api = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.apiDescriptor = {
- key: function key(_key) {
- return /^[$_a-zA-Z][$_a-zA-Z0-9]*$/.test(_key) ? _key : JSON.stringify(_key);
- },
- value(value) {
- if (value === null || typeof value !== 'object') {
- return JSON.stringify(value);
- }
- if (Array.isArray(value)) {
- return `[${value.map(function (subValue) {
- return exports.apiDescriptor.value(subValue);
- }).join(', ')}]`;
- }
- var keys = Object.keys(value);
- return keys.length === 0 ? '{}' : `{ ${keys.map(function (key) {
- return `${exports.apiDescriptor.key(key)}: ${exports.apiDescriptor.value(value[key])}`;
- }).join(', ')} }`;
- },
- pair: function pair(_ref) {
- var key = _ref.key,
- value = _ref.value;
- return exports.apiDescriptor.value({
- [key]: value
- });
- }
- };
- });
- unwrapExports(api);
- var descriptors = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- tslib_1.__exportStar(api, exports);
- });
- unwrapExports(descriptors);
- var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
- var escapeStringRegexp = function escapeStringRegexp(str) {
- if (typeof str !== 'string') {
- throw new TypeError('Expected a string');
- }
- return str.replace(matchOperatorsRe, '\\$&');
- };
- var colorName = {
- "aliceblue": [240, 248, 255],
- "antiquewhite": [250, 235, 215],
- "aqua": [0, 255, 255],
- "aquamarine": [127, 255, 212],
- "azure": [240, 255, 255],
- "beige": [245, 245, 220],
- "bisque": [255, 228, 196],
- "black": [0, 0, 0],
- "blanchedalmond": [255, 235, 205],
- "blue": [0, 0, 255],
- "blueviolet": [138, 43, 226],
- "brown": [165, 42, 42],
- "burlywood": [222, 184, 135],
- "cadetblue": [95, 158, 160],
- "chartreuse": [127, 255, 0],
- "chocolate": [210, 105, 30],
- "coral": [255, 127, 80],
- "cornflowerblue": [100, 149, 237],
- "cornsilk": [255, 248, 220],
- "crimson": [220, 20, 60],
- "cyan": [0, 255, 255],
- "darkblue": [0, 0, 139],
- "darkcyan": [0, 139, 139],
- "darkgoldenrod": [184, 134, 11],
- "darkgray": [169, 169, 169],
- "darkgreen": [0, 100, 0],
- "darkgrey": [169, 169, 169],
- "darkkhaki": [189, 183, 107],
- "darkmagenta": [139, 0, 139],
- "darkolivegreen": [85, 107, 47],
- "darkorange": [255, 140, 0],
- "darkorchid": [153, 50, 204],
- "darkred": [139, 0, 0],
- "darksalmon": [233, 150, 122],
- "darkseagreen": [143, 188, 143],
- "darkslateblue": [72, 61, 139],
- "darkslategray": [47, 79, 79],
- "darkslategrey": [47, 79, 79],
- "darkturquoise": [0, 206, 209],
- "darkviolet": [148, 0, 211],
- "deeppink": [255, 20, 147],
- "deepskyblue": [0, 191, 255],
- "dimgray": [105, 105, 105],
- "dimgrey": [105, 105, 105],
- "dodgerblue": [30, 144, 255],
- "firebrick": [178, 34, 34],
- "floralwhite": [255, 250, 240],
- "forestgreen": [34, 139, 34],
- "fuchsia": [255, 0, 255],
- "gainsboro": [220, 220, 220],
- "ghostwhite": [248, 248, 255],
- "gold": [255, 215, 0],
- "goldenrod": [218, 165, 32],
- "gray": [128, 128, 128],
- "green": [0, 128, 0],
- "greenyellow": [173, 255, 47],
- "grey": [128, 128, 128],
- "honeydew": [240, 255, 240],
- "hotpink": [255, 105, 180],
- "indianred": [205, 92, 92],
- "indigo": [75, 0, 130],
- "ivory": [255, 255, 240],
- "khaki": [240, 230, 140],
- "lavender": [230, 230, 250],
- "lavenderblush": [255, 240, 245],
- "lawngreen": [124, 252, 0],
- "lemonchiffon": [255, 250, 205],
- "lightblue": [173, 216, 230],
- "lightcoral": [240, 128, 128],
- "lightcyan": [224, 255, 255],
- "lightgoldenrodyellow": [250, 250, 210],
- "lightgray": [211, 211, 211],
- "lightgreen": [144, 238, 144],
- "lightgrey": [211, 211, 211],
- "lightpink": [255, 182, 193],
- "lightsalmon": [255, 160, 122],
- "lightseagreen": [32, 178, 170],
- "lightskyblue": [135, 206, 250],
- "lightslategray": [119, 136, 153],
- "lightslategrey": [119, 136, 153],
- "lightsteelblue": [176, 196, 222],
- "lightyellow": [255, 255, 224],
- "lime": [0, 255, 0],
- "limegreen": [50, 205, 50],
- "linen": [250, 240, 230],
- "magenta": [255, 0, 255],
- "maroon": [128, 0, 0],
- "mediumaquamarine": [102, 205, 170],
- "mediumblue": [0, 0, 205],
- "mediumorchid": [186, 85, 211],
- "mediumpurple": [147, 112, 219],
- "mediumseagreen": [60, 179, 113],
- "mediumslateblue": [123, 104, 238],
- "mediumspringgreen": [0, 250, 154],
- "mediumturquoise": [72, 209, 204],
- "mediumvioletred": [199, 21, 133],
- "midnightblue": [25, 25, 112],
- "mintcream": [245, 255, 250],
- "mistyrose": [255, 228, 225],
- "moccasin": [255, 228, 181],
- "navajowhite": [255, 222, 173],
- "navy": [0, 0, 128],
- "oldlace": [253, 245, 230],
- "olive": [128, 128, 0],
- "olivedrab": [107, 142, 35],
- "orange": [255, 165, 0],
- "orangered": [255, 69, 0],
- "orchid": [218, 112, 214],
- "palegoldenrod": [238, 232, 170],
- "palegreen": [152, 251, 152],
- "paleturquoise": [175, 238, 238],
- "palevioletred": [219, 112, 147],
- "papayawhip": [255, 239, 213],
- "peachpuff": [255, 218, 185],
- "peru": [205, 133, 63],
- "pink": [255, 192, 203],
- "plum": [221, 160, 221],
- "powderblue": [176, 224, 230],
- "purple": [128, 0, 128],
- "rebeccapurple": [102, 51, 153],
- "red": [255, 0, 0],
- "rosybrown": [188, 143, 143],
- "royalblue": [65, 105, 225],
- "saddlebrown": [139, 69, 19],
- "salmon": [250, 128, 114],
- "sandybrown": [244, 164, 96],
- "seagreen": [46, 139, 87],
- "seashell": [255, 245, 238],
- "sienna": [160, 82, 45],
- "silver": [192, 192, 192],
- "skyblue": [135, 206, 235],
- "slateblue": [106, 90, 205],
- "slategray": [112, 128, 144],
- "slategrey": [112, 128, 144],
- "snow": [255, 250, 250],
- "springgreen": [0, 255, 127],
- "steelblue": [70, 130, 180],
- "tan": [210, 180, 140],
- "teal": [0, 128, 128],
- "thistle": [216, 191, 216],
- "tomato": [255, 99, 71],
- "turquoise": [64, 224, 208],
- "violet": [238, 130, 238],
- "wheat": [245, 222, 179],
- "white": [255, 255, 255],
- "whitesmoke": [245, 245, 245],
- "yellow": [255, 255, 0],
- "yellowgreen": [154, 205, 50]
- };
- var conversions = createCommonjsModule(function (module) {
- /* MIT license */
- // NOTE: conversions should only return primitive values (i.e. arrays, or
- // values that give correct `typeof` results).
- // do not use box values types (i.e. Number(), String(), etc.)
- var reverseKeywords = {};
- for (var key in colorName) {
- if (colorName.hasOwnProperty(key)) {
- reverseKeywords[colorName[key]] = key;
- }
- }
- var convert = module.exports = {
- rgb: {
- channels: 3,
- labels: 'rgb'
- },
- hsl: {
- channels: 3,
- labels: 'hsl'
- },
- hsv: {
- channels: 3,
- labels: 'hsv'
- },
- hwb: {
- channels: 3,
- labels: 'hwb'
- },
- cmyk: {
- channels: 4,
- labels: 'cmyk'
- },
- xyz: {
- channels: 3,
- labels: 'xyz'
- },
- lab: {
- channels: 3,
- labels: 'lab'
- },
- lch: {
- channels: 3,
- labels: 'lch'
- },
- hex: {
- channels: 1,
- labels: ['hex']
- },
- keyword: {
- channels: 1,
- labels: ['keyword']
- },
- ansi16: {
- channels: 1,
- labels: ['ansi16']
- },
- ansi256: {
- channels: 1,
- labels: ['ansi256']
- },
- hcg: {
- channels: 3,
- labels: ['h', 'c', 'g']
- },
- apple: {
- channels: 3,
- labels: ['r16', 'g16', 'b16']
- },
- gray: {
- channels: 1,
- labels: ['gray']
- }
- }; // hide .channels and .labels properties
- for (var model in convert) {
- if (convert.hasOwnProperty(model)) {
- if (!('channels' in convert[model])) {
- throw new Error('missing channels property: ' + model);
- }
- if (!('labels' in convert[model])) {
- throw new Error('missing channel labels property: ' + model);
- }
- if (convert[model].labels.length !== convert[model].channels) {
- throw new Error('channel and label counts mismatch: ' + model);
- }
- var channels = convert[model].channels;
- var labels = convert[model].labels;
- delete convert[model].channels;
- delete convert[model].labels;
- Object.defineProperty(convert[model], 'channels', {
- value: channels
- });
- Object.defineProperty(convert[model], 'labels', {
- value: labels
- });
- }
- }
- convert.rgb.hsl = function (rgb) {
- var r = rgb[0] / 255;
- var g = rgb[1] / 255;
- var b = rgb[2] / 255;
- var min = Math.min(r, g, b);
- var max = Math.max(r, g, b);
- var delta = max - min;
- var h;
- var s;
- var l;
- if (max === min) {
- h = 0;
- } else if (r === max) {
- h = (g - b) / delta;
- } else if (g === max) {
- h = 2 + (b - r) / delta;
- } else if (b === max) {
- h = 4 + (r - g) / delta;
- }
- h = Math.min(h * 60, 360);
- if (h < 0) {
- h += 360;
- }
- l = (min + max) / 2;
- if (max === min) {
- s = 0;
- } else if (l <= 0.5) {
- s = delta / (max + min);
- } else {
- s = delta / (2 - max - min);
- }
- return [h, s * 100, l * 100];
- };
- convert.rgb.hsv = function (rgb) {
- var r = rgb[0];
- var g = rgb[1];
- var b = rgb[2];
- var min = Math.min(r, g, b);
- var max = Math.max(r, g, b);
- var delta = max - min;
- var h;
- var s;
- var v;
- if (max === 0) {
- s = 0;
- } else {
- s = delta / max * 1000 / 10;
- }
- if (max === min) {
- h = 0;
- } else if (r === max) {
- h = (g - b) / delta;
- } else if (g === max) {
- h = 2 + (b - r) / delta;
- } else if (b === max) {
- h = 4 + (r - g) / delta;
- }
- h = Math.min(h * 60, 360);
- if (h < 0) {
- h += 360;
- }
- v = max / 255 * 1000 / 10;
- return [h, s, v];
- };
- convert.rgb.hwb = function (rgb) {
- var r = rgb[0];
- var g = rgb[1];
- var b = rgb[2];
- var h = convert.rgb.hsl(rgb)[0];
- var w = 1 / 255 * Math.min(r, Math.min(g, b));
- b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
- return [h, w * 100, b * 100];
- };
- convert.rgb.cmyk = function (rgb) {
- var r = rgb[0] / 255;
- var g = rgb[1] / 255;
- var b = rgb[2] / 255;
- var c;
- var m;
- var y;
- var k;
- k = Math.min(1 - r, 1 - g, 1 - b);
- c = (1 - r - k) / (1 - k) || 0;
- m = (1 - g - k) / (1 - k) || 0;
- y = (1 - b - k) / (1 - k) || 0;
- return [c * 100, m * 100, y * 100, k * 100];
- };
- /**
- * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
- * */
- function comparativeDistance(x, y) {
- return Math.pow(x[0] - y[0], 2) + Math.pow(x[1] - y[1], 2) + Math.pow(x[2] - y[2], 2);
- }
- convert.rgb.keyword = function (rgb) {
- var reversed = reverseKeywords[rgb];
- if (reversed) {
- return reversed;
- }
- var currentClosestDistance = Infinity;
- var currentClosestKeyword;
- for (var keyword in colorName) {
- if (colorName.hasOwnProperty(keyword)) {
- var value = colorName[keyword]; // Compute comparative distance
- var distance = comparativeDistance(rgb, value); // Check if its less, if so set as closest
- if (distance < currentClosestDistance) {
- currentClosestDistance = distance;
- currentClosestKeyword = keyword;
- }
- }
- }
- return currentClosestKeyword;
- };
- convert.keyword.rgb = function (keyword) {
- return colorName[keyword];
- };
- convert.rgb.xyz = function (rgb) {
- var r = rgb[0] / 255;
- var g = rgb[1] / 255;
- var b = rgb[2] / 255; // assume sRGB
- r = r > 0.04045 ? Math.pow((r + 0.055) / 1.055, 2.4) : r / 12.92;
- g = g > 0.04045 ? Math.pow((g + 0.055) / 1.055, 2.4) : g / 12.92;
- b = b > 0.04045 ? Math.pow((b + 0.055) / 1.055, 2.4) : b / 12.92;
- var x = r * 0.4124 + g * 0.3576 + b * 0.1805;
- var y = r * 0.2126 + g * 0.7152 + b * 0.0722;
- var z = r * 0.0193 + g * 0.1192 + b * 0.9505;
- return [x * 100, y * 100, z * 100];
- };
- convert.rgb.lab = function (rgb) {
- var xyz = convert.rgb.xyz(rgb);
- var x = xyz[0];
- var y = xyz[1];
- var z = xyz[2];
- var l;
- var a;
- var b;
- x /= 95.047;
- y /= 100;
- z /= 108.883;
- x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116;
- y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116;
- z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116;
- l = 116 * y - 16;
- a = 500 * (x - y);
- b = 200 * (y - z);
- return [l, a, b];
- };
- convert.hsl.rgb = function (hsl) {
- var h = hsl[0] / 360;
- var s = hsl[1] / 100;
- var l = hsl[2] / 100;
- var t1;
- var t2;
- var t3;
- var rgb;
- var val;
- if (s === 0) {
- val = l * 255;
- return [val, val, val];
- }
- if (l < 0.5) {
- t2 = l * (1 + s);
- } else {
- t2 = l + s - l * s;
- }
- t1 = 2 * l - t2;
- rgb = [0, 0, 0];
- for (var i = 0; i < 3; i++) {
- t3 = h + 1 / 3 * -(i - 1);
- if (t3 < 0) {
- t3++;
- }
- if (t3 > 1) {
- t3--;
- }
- if (6 * t3 < 1) {
- val = t1 + (t2 - t1) * 6 * t3;
- } else if (2 * t3 < 1) {
- val = t2;
- } else if (3 * t3 < 2) {
- val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
- } else {
- val = t1;
- }
- rgb[i] = val * 255;
- }
- return rgb;
- };
- convert.hsl.hsv = function (hsl) {
- var h = hsl[0];
- var s = hsl[1] / 100;
- var l = hsl[2] / 100;
- var smin = s;
- var lmin = Math.max(l, 0.01);
- var sv;
- var v;
- l *= 2;
- s *= l <= 1 ? l : 2 - l;
- smin *= lmin <= 1 ? lmin : 2 - lmin;
- v = (l + s) / 2;
- sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s);
- return [h, sv * 100, v * 100];
- };
- convert.hsv.rgb = function (hsv) {
- var h = hsv[0] / 60;
- var s = hsv[1] / 100;
- var v = hsv[2] / 100;
- var hi = Math.floor(h) % 6;
- var f = h - Math.floor(h);
- var p = 255 * v * (1 - s);
- var q = 255 * v * (1 - s * f);
- var t = 255 * v * (1 - s * (1 - f));
- v *= 255;
- switch (hi) {
- case 0:
- return [v, t, p];
- case 1:
- return [q, v, p];
- case 2:
- return [p, v, t];
- case 3:
- return [p, q, v];
- case 4:
- return [t, p, v];
- case 5:
- return [v, p, q];
- }
- };
- convert.hsv.hsl = function (hsv) {
- var h = hsv[0];
- var s = hsv[1] / 100;
- var v = hsv[2] / 100;
- var vmin = Math.max(v, 0.01);
- var lmin;
- var sl;
- var l;
- l = (2 - s) * v;
- lmin = (2 - s) * vmin;
- sl = s * vmin;
- sl /= lmin <= 1 ? lmin : 2 - lmin;
- sl = sl || 0;
- l /= 2;
- return [h, sl * 100, l * 100];
- }; // http://dev.w3.org/csswg/css-color/#hwb-to-rgb
- convert.hwb.rgb = function (hwb) {
- var h = hwb[0] / 360;
- var wh = hwb[1] / 100;
- var bl = hwb[2] / 100;
- var ratio = wh + bl;
- var i;
- var v;
- var f;
- var n; // wh + bl cant be > 1
- if (ratio > 1) {
- wh /= ratio;
- bl /= ratio;
- }
- i = Math.floor(6 * h);
- v = 1 - bl;
- f = 6 * h - i;
- if ((i & 0x01) !== 0) {
- f = 1 - f;
- }
- n = wh + f * (v - wh); // linear interpolation
- var r;
- var g;
- var b;
- switch (i) {
- default:
- case 6:
- case 0:
- r = v;
- g = n;
- b = wh;
- break;
- case 1:
- r = n;
- g = v;
- b = wh;
- break;
- case 2:
- r = wh;
- g = v;
- b = n;
- break;
- case 3:
- r = wh;
- g = n;
- b = v;
- break;
- case 4:
- r = n;
- g = wh;
- b = v;
- break;
- case 5:
- r = v;
- g = wh;
- b = n;
- break;
- }
- return [r * 255, g * 255, b * 255];
- };
- convert.cmyk.rgb = function (cmyk) {
- var c = cmyk[0] / 100;
- var m = cmyk[1] / 100;
- var y = cmyk[2] / 100;
- var k = cmyk[3] / 100;
- var r;
- var g;
- var b;
- r = 1 - Math.min(1, c * (1 - k) + k);
- g = 1 - Math.min(1, m * (1 - k) + k);
- b = 1 - Math.min(1, y * (1 - k) + k);
- return [r * 255, g * 255, b * 255];
- };
- convert.xyz.rgb = function (xyz) {
- var x = xyz[0] / 100;
- var y = xyz[1] / 100;
- var z = xyz[2] / 100;
- var r;
- var g;
- var b;
- r = x * 3.2406 + y * -1.5372 + z * -0.4986;
- g = x * -0.9689 + y * 1.8758 + z * 0.0415;
- b = x * 0.0557 + y * -0.2040 + z * 1.0570; // assume sRGB
- r = r > 0.0031308 ? 1.055 * Math.pow(r, 1.0 / 2.4) - 0.055 : r * 12.92;
- g = g > 0.0031308 ? 1.055 * Math.pow(g, 1.0 / 2.4) - 0.055 : g * 12.92;
- b = b > 0.0031308 ? 1.055 * Math.pow(b, 1.0 / 2.4) - 0.055 : b * 12.92;
- r = Math.min(Math.max(0, r), 1);
- g = Math.min(Math.max(0, g), 1);
- b = Math.min(Math.max(0, b), 1);
- return [r * 255, g * 255, b * 255];
- };
- convert.xyz.lab = function (xyz) {
- var x = xyz[0];
- var y = xyz[1];
- var z = xyz[2];
- var l;
- var a;
- var b;
- x /= 95.047;
- y /= 100;
- z /= 108.883;
- x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116;
- y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116;
- z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116;
- l = 116 * y - 16;
- a = 500 * (x - y);
- b = 200 * (y - z);
- return [l, a, b];
- };
- convert.lab.xyz = function (lab) {
- var l = lab[0];
- var a = lab[1];
- var b = lab[2];
- var x;
- var y;
- var z;
- y = (l + 16) / 116;
- x = a / 500 + y;
- z = y - b / 200;
- var y2 = Math.pow(y, 3);
- var x2 = Math.pow(x, 3);
- var z2 = Math.pow(z, 3);
- y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
- x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
- z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
- x *= 95.047;
- y *= 100;
- z *= 108.883;
- return [x, y, z];
- };
- convert.lab.lch = function (lab) {
- var l = lab[0];
- var a = lab[1];
- var b = lab[2];
- var hr;
- var h;
- var c;
- hr = Math.atan2(b, a);
- h = hr * 360 / 2 / Math.PI;
- if (h < 0) {
- h += 360;
- }
- c = Math.sqrt(a * a + b * b);
- return [l, c, h];
- };
- convert.lch.lab = function (lch) {
- var l = lch[0];
- var c = lch[1];
- var h = lch[2];
- var a;
- var b;
- var hr;
- hr = h / 360 * 2 * Math.PI;
- a = c * Math.cos(hr);
- b = c * Math.sin(hr);
- return [l, a, b];
- };
- convert.rgb.ansi16 = function (args) {
- var r = args[0];
- var g = args[1];
- var b = args[2];
- var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization
- value = Math.round(value / 50);
- if (value === 0) {
- return 30;
- }
- var ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255));
- if (value === 2) {
- ansi += 60;
- }
- return ansi;
- };
- convert.hsv.ansi16 = function (args) {
- // optimization here; we already know the value and don't need to get
- // it converted for us.
- return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);
- };
- convert.rgb.ansi256 = function (args) {
- var r = args[0];
- var g = args[1];
- var b = args[2]; // we use the extended greyscale palette here, with the exception of
- // black and white. normal palette only has 4 greyscale shades.
- if (r === g && g === b) {
- if (r < 8) {
- return 16;
- }
- if (r > 248) {
- return 231;
- }
- return Math.round((r - 8) / 247 * 24) + 232;
- }
- var ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5);
- return ansi;
- };
- convert.ansi16.rgb = function (args) {
- var color = args % 10; // handle greyscale
- if (color === 0 || color === 7) {
- if (args > 50) {
- color += 3.5;
- }
- color = color / 10.5 * 255;
- return [color, color, color];
- }
- var mult = (~~(args > 50) + 1) * 0.5;
- var r = (color & 1) * mult * 255;
- var g = (color >> 1 & 1) * mult * 255;
- var b = (color >> 2 & 1) * mult * 255;
- return [r, g, b];
- };
- convert.ansi256.rgb = function (args) {
- // handle greyscale
- if (args >= 232) {
- var c = (args - 232) * 10 + 8;
- return [c, c, c];
- }
- args -= 16;
- var rem;
- var r = Math.floor(args / 36) / 5 * 255;
- var g = Math.floor((rem = args % 36) / 6) / 5 * 255;
- var b = rem % 6 / 5 * 255;
- return [r, g, b];
- };
- convert.rgb.hex = function (args) {
- var integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF);
- var string = integer.toString(16).toUpperCase();
- return '000000'.substring(string.length) + string;
- };
- convert.hex.rgb = function (args) {
- var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
- if (!match) {
- return [0, 0, 0];
- }
- var colorString = match[0];
- if (match[0].length === 3) {
- colorString = colorString.split('').map(function (char) {
- return char + char;
- }).join('');
- }
- var integer = parseInt(colorString, 16);
- var r = integer >> 16 & 0xFF;
- var g = integer >> 8 & 0xFF;
- var b = integer & 0xFF;
- return [r, g, b];
- };
- convert.rgb.hcg = function (rgb) {
- var r = rgb[0] / 255;
- var g = rgb[1] / 255;
- var b = rgb[2] / 255;
- var max = Math.max(Math.max(r, g), b);
- var min = Math.min(Math.min(r, g), b);
- var chroma = max - min;
- var grayscale;
- var hue;
- if (chroma < 1) {
- grayscale = min / (1 - chroma);
- } else {
- grayscale = 0;
- }
- if (chroma <= 0) {
- hue = 0;
- } else if (max === r) {
- hue = (g - b) / chroma % 6;
- } else if (max === g) {
- hue = 2 + (b - r) / chroma;
- } else {
- hue = 4 + (r - g) / chroma + 4;
- }
- hue /= 6;
- hue %= 1;
- return [hue * 360, chroma * 100, grayscale * 100];
- };
- convert.hsl.hcg = function (hsl) {
- var s = hsl[1] / 100;
- var l = hsl[2] / 100;
- var c = 1;
- var f = 0;
- if (l < 0.5) {
- c = 2.0 * s * l;
- } else {
- c = 2.0 * s * (1.0 - l);
- }
- if (c < 1.0) {
- f = (l - 0.5 * c) / (1.0 - c);
- }
- return [hsl[0], c * 100, f * 100];
- };
- convert.hsv.hcg = function (hsv) {
- var s = hsv[1] / 100;
- var v = hsv[2] / 100;
- var c = s * v;
- var f = 0;
- if (c < 1.0) {
- f = (v - c) / (1 - c);
- }
- return [hsv[0], c * 100, f * 100];
- };
- convert.hcg.rgb = function (hcg) {
- var h = hcg[0] / 360;
- var c = hcg[1] / 100;
- var g = hcg[2] / 100;
- if (c === 0.0) {
- return [g * 255, g * 255, g * 255];
- }
- var pure = [0, 0, 0];
- var hi = h % 1 * 6;
- var v = hi % 1;
- var w = 1 - v;
- var mg = 0;
- switch (Math.floor(hi)) {
- case 0:
- pure[0] = 1;
- pure[1] = v;
- pure[2] = 0;
- break;
- case 1:
- pure[0] = w;
- pure[1] = 1;
- pure[2] = 0;
- break;
- case 2:
- pure[0] = 0;
- pure[1] = 1;
- pure[2] = v;
- break;
- case 3:
- pure[0] = 0;
- pure[1] = w;
- pure[2] = 1;
- break;
- case 4:
- pure[0] = v;
- pure[1] = 0;
- pure[2] = 1;
- break;
- default:
- pure[0] = 1;
- pure[1] = 0;
- pure[2] = w;
- }
- mg = (1.0 - c) * g;
- return [(c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255];
- };
- convert.hcg.hsv = function (hcg) {
- var c = hcg[1] / 100;
- var g = hcg[2] / 100;
- var v = c + g * (1.0 - c);
- var f = 0;
- if (v > 0.0) {
- f = c / v;
- }
- return [hcg[0], f * 100, v * 100];
- };
- convert.hcg.hsl = function (hcg) {
- var c = hcg[1] / 100;
- var g = hcg[2] / 100;
- var l = g * (1.0 - c) + 0.5 * c;
- var s = 0;
- if (l > 0.0 && l < 0.5) {
- s = c / (2 * l);
- } else if (l >= 0.5 && l < 1.0) {
- s = c / (2 * (1 - l));
- }
- return [hcg[0], s * 100, l * 100];
- };
- convert.hcg.hwb = function (hcg) {
- var c = hcg[1] / 100;
- var g = hcg[2] / 100;
- var v = c + g * (1.0 - c);
- return [hcg[0], (v - c) * 100, (1 - v) * 100];
- };
- convert.hwb.hcg = function (hwb) {
- var w = hwb[1] / 100;
- var b = hwb[2] / 100;
- var v = 1 - b;
- var c = v - w;
- var g = 0;
- if (c < 1) {
- g = (v - c) / (1 - c);
- }
- return [hwb[0], c * 100, g * 100];
- };
- convert.apple.rgb = function (apple) {
- return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255];
- };
- convert.rgb.apple = function (rgb) {
- return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535];
- };
- convert.gray.rgb = function (args) {
- return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
- };
- convert.gray.hsl = convert.gray.hsv = function (args) {
- return [0, 0, args[0]];
- };
- convert.gray.hwb = function (gray) {
- return [0, 100, gray[0]];
- };
- convert.gray.cmyk = function (gray) {
- return [0, 0, 0, gray[0]];
- };
- convert.gray.lab = function (gray) {
- return [gray[0], 0, 0];
- };
- convert.gray.hex = function (gray) {
- var val = Math.round(gray[0] / 100 * 255) & 0xFF;
- var integer = (val << 16) + (val << 8) + val;
- var string = integer.toString(16).toUpperCase();
- return '000000'.substring(string.length) + string;
- };
- convert.rgb.gray = function (rgb) {
- var val = (rgb[0] + rgb[1] + rgb[2]) / 3;
- return [val / 255 * 100];
- };
- });
- /*
- this function routes a model to all other models.
- all functions that are routed have a property `.conversion` attached
- to the returned synthetic function. This property is an array
- of strings, each with the steps in between the 'from' and 'to'
- color models (inclusive).
- conversions that are not possible simply are not included.
- */
- // https://jsperf.com/object-keys-vs-for-in-with-closure/3
- var models$1 = Object.keys(conversions);
- function buildGraph() {
- var graph = {};
- for (var len = models$1.length, i = 0; i < len; i++) {
- graph[models$1[i]] = {
- // http://jsperf.com/1-vs-infinity
- // micro-opt, but this is simple.
- distance: -1,
- parent: null
- };
- }
- return graph;
- } // https://en.wikipedia.org/wiki/Breadth-first_search
- function deriveBFS(fromModel) {
- var graph = buildGraph();
- var queue = [fromModel]; // unshift -> queue -> pop
- graph[fromModel].distance = 0;
- while (queue.length) {
- var current = queue.pop();
- var adjacents = Object.keys(conversions[current]);
- for (var len = adjacents.length, i = 0; i < len; i++) {
- var adjacent = adjacents[i];
- var node = graph[adjacent];
- if (node.distance === -1) {
- node.distance = graph[current].distance + 1;
- node.parent = current;
- queue.unshift(adjacent);
- }
- }
- }
- return graph;
- }
- function link(from, to) {
- return function (args) {
- return to(from(args));
- };
- }
- function wrapConversion(toModel, graph) {
- var path$$1 = [graph[toModel].parent, toModel];
- var fn = conversions[graph[toModel].parent][toModel];
- var cur = graph[toModel].parent;
- while (graph[cur].parent) {
- path$$1.unshift(graph[cur].parent);
- fn = link(conversions[graph[cur].parent][cur], fn);
- cur = graph[cur].parent;
- }
- fn.conversion = path$$1;
- return fn;
- }
- var route = function route(fromModel) {
- var graph = deriveBFS(fromModel);
- var conversion = {};
- var models = Object.keys(graph);
- for (var len = models.length, i = 0; i < len; i++) {
- var toModel = models[i];
- var node = graph[toModel];
- if (node.parent === null) {
- // no possible conversion, or this node is the source model.
- continue;
- }
- conversion[toModel] = wrapConversion(toModel, graph);
- }
- return conversion;
- };
- var convert = {};
- var models = Object.keys(conversions);
- function wrapRaw(fn) {
- var wrappedFn = function wrappedFn(args) {
- if (args === undefined || args === null) {
- return args;
- }
- if (arguments.length > 1) {
- args = Array.prototype.slice.call(arguments);
- }
- return fn(args);
- }; // preserve .conversion property if there is one
- if ('conversion' in fn) {
- wrappedFn.conversion = fn.conversion;
- }
- return wrappedFn;
- }
- function wrapRounded(fn) {
- var wrappedFn = function wrappedFn(args) {
- if (args === undefined || args === null) {
- return args;
- }
- if (arguments.length > 1) {
- args = Array.prototype.slice.call(arguments);
- }
- var result = fn(args); // we're assuming the result is an array here.
- // see notice in conversions.js; don't use box types
- // in conversion functions.
- if (typeof result === 'object') {
- for (var len = result.length, i = 0; i < len; i++) {
- result[i] = Math.round(result[i]);
- }
- }
- return result;
- }; // preserve .conversion property if there is one
- if ('conversion' in fn) {
- wrappedFn.conversion = fn.conversion;
- }
- return wrappedFn;
- }
- models.forEach(function (fromModel) {
- convert[fromModel] = {};
- Object.defineProperty(convert[fromModel], 'channels', {
- value: conversions[fromModel].channels
- });
- Object.defineProperty(convert[fromModel], 'labels', {
- value: conversions[fromModel].labels
- });
- var routes = route(fromModel);
- var routeModels = Object.keys(routes);
- routeModels.forEach(function (toModel) {
- var fn = routes[toModel];
- convert[fromModel][toModel] = wrapRounded(fn);
- convert[fromModel][toModel].raw = wrapRaw(fn);
- });
- });
- var colorConvert = convert;
- var ansiStyles = createCommonjsModule(function (module) {
- 'use strict';
- var wrapAnsi16 = function wrapAnsi16(fn, offset) {
- return function () {
- var code = fn.apply(colorConvert, arguments);
- return `\u001B[${code + offset}m`;
- };
- };
- var wrapAnsi256 = function wrapAnsi256(fn, offset) {
- return function () {
- var code = fn.apply(colorConvert, arguments);
- return `\u001B[${38 + offset};5;${code}m`;
- };
- };
- var wrapAnsi16m = function wrapAnsi16m(fn, offset) {
- return function () {
- var rgb = fn.apply(colorConvert, arguments);
- return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
- };
- };
- function assembleStyles() {
- var codes = new Map();
- var styles = {
- modifier: {
- reset: [0, 0],
- // 21 isn't widely supported and 22 does the same thing
- bold: [1, 22],
- dim: [2, 22],
- italic: [3, 23],
- underline: [4, 24],
- inverse: [7, 27],
- hidden: [8, 28],
- strikethrough: [9, 29]
- },
- color: {
- black: [30, 39],
- red: [31, 39],
- green: [32, 39],
- yellow: [33, 39],
- blue: [34, 39],
- magenta: [35, 39],
- cyan: [36, 39],
- white: [37, 39],
- gray: [90, 39],
- // Bright color
- redBright: [91, 39],
- greenBright: [92, 39],
- yellowBright: [93, 39],
- blueBright: [94, 39],
- magentaBright: [95, 39],
- cyanBright: [96, 39],
- whiteBright: [97, 39]
- },
- bgColor: {
- bgBlack: [40, 49],
- bgRed: [41, 49],
- bgGreen: [42, 49],
- bgYellow: [43, 49],
- bgBlue: [44, 49],
- bgMagenta: [45, 49],
- bgCyan: [46, 49],
- bgWhite: [47, 49],
- // Bright color
- bgBlackBright: [100, 49],
- bgRedBright: [101, 49],
- bgGreenBright: [102, 49],
- bgYellowBright: [103, 49],
- bgBlueBright: [104, 49],
- bgMagentaBright: [105, 49],
- bgCyanBright: [106, 49],
- bgWhiteBright: [107, 49]
- }
- }; // Fix humans
- styles.color.grey = styles.color.gray;
- var _arr = Object.keys(styles);
- for (var _i = 0; _i < _arr.length; _i++) {
- var groupName = _arr[_i];
- var group = styles[groupName];
- var _arr3 = Object.keys(group);
- for (var _i3 = 0; _i3 < _arr3.length; _i3++) {
- var styleName = _arr3[_i3];
- var style = group[styleName];
- styles[styleName] = {
- open: `\u001B[${style[0]}m`,
- close: `\u001B[${style[1]}m`
- };
- group[styleName] = styles[styleName];
- codes.set(style[0], style[1]);
- }
- Object.defineProperty(styles, groupName, {
- value: group,
- enumerable: false
- });
- Object.defineProperty(styles, 'codes', {
- value: codes,
- enumerable: false
- });
- }
- var ansi2ansi = function ansi2ansi(n) {
- return n;
- };
- var rgb2rgb = function rgb2rgb(r, g, b) {
- return [r, g, b];
- };
- styles.color.close = '\u001B[39m';
- styles.bgColor.close = '\u001B[49m';
- styles.color.ansi = {
- ansi: wrapAnsi16(ansi2ansi, 0)
- };
- styles.color.ansi256 = {
- ansi256: wrapAnsi256(ansi2ansi, 0)
- };
- styles.color.ansi16m = {
- rgb: wrapAnsi16m(rgb2rgb, 0)
- };
- styles.bgColor.ansi = {
- ansi: wrapAnsi16(ansi2ansi, 10)
- };
- styles.bgColor.ansi256 = {
- ansi256: wrapAnsi256(ansi2ansi, 10)
- };
- styles.bgColor.ansi16m = {
- rgb: wrapAnsi16m(rgb2rgb, 10)
- };
- var _arr2 = Object.keys(colorConvert);
- for (var _i2 = 0; _i2 < _arr2.length; _i2++) {
- var key = _arr2[_i2];
- if (typeof colorConvert[key] !== 'object') {
- continue;
- }
- var suite = colorConvert[key];
- if (key === 'ansi16') {
- key = 'ansi';
- }
- if ('ansi16' in suite) {
- styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0);
- styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10);
- }
- if ('ansi256' in suite) {
- styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0);
- styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10);
- }
- if ('rgb' in suite) {
- styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0);
- styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10);
- }
- }
- return styles;
- } // Make the export immutable
- Object.defineProperty(module, 'exports', {
- enumerable: true,
- get: assembleStyles
- });
- });
- var hasFlag = createCommonjsModule(function (module) {
- 'use strict';
- module.exports = function (flag, argv) {
- argv = argv || process.argv;
- var prefix = flag.startsWith('-') ? '' : flag.length === 1 ? '-' : '--';
- var pos = argv.indexOf(prefix + flag);
- var terminatorPos = argv.indexOf('--');
- return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos);
- };
- });
- var env = process.env;
- var forceColor;
- if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) {
- forceColor = false;
- } else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) {
- forceColor = true;
- }
- if ('FORCE_COLOR' in env) {
- forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0;
- }
- function translateLevel(level) {
- if (level === 0) {
- return false;
- }
- return {
- level,
- hasBasic: true,
- has256: level >= 2,
- has16m: level >= 3
- };
- }
- function supportsColor(stream) {
- if (forceColor === false) {
- return 0;
- }
- if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) {
- return 3;
- }
- if (hasFlag('color=256')) {
- return 2;
- }
- if (stream && !stream.isTTY && forceColor !== true) {
- return 0;
- }
- var min = forceColor ? 1 : 0;
- if (process.platform === 'win32') {
- // Node.js 7.5.0 is the first version of Node.js to include a patch to
- // libuv that enables 256 color output on Windows. Anything earlier and it
- // won't work. However, here we target Node.js 8 at minimum as it is an LTS
- // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows
- // release that supports 256 colors. Windows 10 build 14931 is the first release
- // that supports 16m/TrueColor.
- var osRelease = os.release().split('.');
- if (Number(process.versions.node.split('.')[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
- return Number(osRelease[2]) >= 14931 ? 3 : 2;
- }
- return 1;
- }
- if ('CI' in env) {
- if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(function (sign) {
- return sign in env;
- }) || env.CI_NAME === 'codeship') {
- return 1;
- }
- return min;
- }
- if ('TEAMCITY_VERSION' in env) {
- return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
- }
- if (env.COLORTERM === 'truecolor') {
- return 3;
- }
- if ('TERM_PROGRAM' in env) {
- var version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
- switch (env.TERM_PROGRAM) {
- case 'iTerm.app':
- return version >= 3 ? 3 : 2;
- case 'Apple_Terminal':
- return 2;
- // No default
- }
- }
- if (/-256(color)?$/i.test(env.TERM)) {
- return 2;
- }
- if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
- return 1;
- }
- if ('COLORTERM' in env) {
- return 1;
- }
- if (env.TERM === 'dumb') {
- return min;
- }
- return min;
- }
- function getSupportLevel(stream) {
- var level = supportsColor(stream);
- return translateLevel(level);
- }
- var supportsColor_1 = {
- supportsColor: getSupportLevel,
- stdout: getSupportLevel(process.stdout),
- stderr: getSupportLevel(process.stderr)
- };
- var templates = createCommonjsModule(function (module) {
- 'use strict';
- var TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
- var STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
- var STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
- var ESCAPE_REGEX = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi;
- var ESCAPES = new Map([['n', '\n'], ['r', '\r'], ['t', '\t'], ['b', '\b'], ['f', '\f'], ['v', '\v'], ['0', '\0'], ['\\', '\\'], ['e', '\u001B'], ['a', '\u0007']]);
- function unescape(c) {
- if (c[0] === 'u' && c.length === 5 || c[0] === 'x' && c.length === 3) {
- return String.fromCharCode(parseInt(c.slice(1), 16));
- }
- return ESCAPES.get(c) || c;
- }
- function parseArguments(name, args) {
- var results = [];
- var chunks = args.trim().split(/\s*,\s*/g);
- var matches;
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = chunks[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var chunk = _step.value;
- if (!isNaN(chunk)) {
- results.push(Number(chunk));
- } else if (matches = chunk.match(STRING_REGEX)) {
- results.push(matches[2].replace(ESCAPE_REGEX, function (m, escape, chr) {
- return escape ? unescape(escape) : chr;
- }));
- } else {
- throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
- }
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- return results;
- }
- function parseStyle(style) {
- STYLE_REGEX.lastIndex = 0;
- var results = [];
- var matches;
- while ((matches = STYLE_REGEX.exec(style)) !== null) {
- var name = matches[1];
- if (matches[2]) {
- var args = parseArguments(name, matches[2]);
- results.push([name].concat(args));
- } else {
- results.push([name]);
- }
- }
- return results;
- }
- function buildStyle(chalk, styles) {
- var enabled = {};
- var _iteratorNormalCompletion2 = true;
- var _didIteratorError2 = false;
- var _iteratorError2 = undefined;
- try {
- for (var _iterator2 = styles[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
- var layer = _step2.value;
- var _iteratorNormalCompletion3 = true;
- var _didIteratorError3 = false;
- var _iteratorError3 = undefined;
- try {
- for (var _iterator3 = layer.styles[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
- var style = _step3.value;
- enabled[style[0]] = layer.inverse ? null : style.slice(1);
- }
- } catch (err) {
- _didIteratorError3 = true;
- _iteratorError3 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
- _iterator3.return();
- }
- } finally {
- if (_didIteratorError3) {
- throw _iteratorError3;
- }
- }
- }
- }
- } catch (err) {
- _didIteratorError2 = true;
- _iteratorError2 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
- _iterator2.return();
- }
- } finally {
- if (_didIteratorError2) {
- throw _iteratorError2;
- }
- }
- }
- var current = chalk;
- var _arr = Object.keys(enabled);
- for (var _i = 0; _i < _arr.length; _i++) {
- var styleName = _arr[_i];
- if (Array.isArray(enabled[styleName])) {
- if (!(styleName in current)) {
- throw new Error(`Unknown Chalk style: ${styleName}`);
- }
- if (enabled[styleName].length > 0) {
- current = current[styleName].apply(current, enabled[styleName]);
- } else {
- current = current[styleName];
- }
- }
- }
- return current;
- }
- module.exports = function (chalk, tmp) {
- var styles = [];
- var chunks = [];
- var chunk = []; // eslint-disable-next-line max-params
- tmp.replace(TEMPLATE_REGEX, function (m, escapeChar, inverse, style, close, chr) {
- if (escapeChar) {
- chunk.push(unescape(escapeChar));
- } else if (style) {
- var str = chunk.join('');
- chunk = [];
- chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str));
- styles.push({
- inverse,
- styles: parseStyle(style)
- });
- } else if (close) {
- if (styles.length === 0) {
- throw new Error('Found extraneous } in Chalk template literal');
- }
- chunks.push(buildStyle(chalk, styles)(chunk.join('')));
- chunk = [];
- styles.pop();
- } else {
- chunk.push(chr);
- }
- });
- chunks.push(chunk.join(''));
- if (styles.length > 0) {
- var errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
- throw new Error(errMsg);
- }
- return chunks.join('');
- };
- });
- var chalk = createCommonjsModule(function (module) {
- 'use strict';
- var stdoutColor = supportsColor_1.stdout;
- var isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); // `supportsColor.level` → `ansiStyles.color[name]` mapping
- var levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; // `color-convert` models to exclude from the Chalk API due to conflicts and such
- var skipModels = new Set(['gray']);
- var styles = Object.create(null);
- function applyOptions(obj, options) {
- options = options || {}; // Detect level if not set manually
- var scLevel = stdoutColor ? stdoutColor.level : 0;
- obj.level = options.level === undefined ? scLevel : options.level;
- obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0;
- }
- function Chalk(options) {
- // We check for this.template here since calling `chalk.constructor()`
- // by itself will have a `this` of a previously constructed chalk object
- if (!this || !(this instanceof Chalk) || this.template) {
- var _chalk = {};
- applyOptions(_chalk, options);
- _chalk.template = function () {
- var args = [].slice.call(arguments);
- return chalkTag.apply(null, [_chalk.template].concat(args));
- };
- Object.setPrototypeOf(_chalk, Chalk.prototype);
- Object.setPrototypeOf(_chalk.template, _chalk);
- _chalk.template.constructor = Chalk;
- return _chalk.template;
- }
- applyOptions(this, options);
- } // Use bright blue on Windows as the normal blue color is illegible
- if (isSimpleWindowsTerm) {
- ansiStyles.blue.open = '\u001B[94m';
- }
- var _arr = Object.keys(ansiStyles);
- var _loop = function _loop() {
- var key = _arr[_i];
- ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g');
- styles[key] = {
- get() {
- var codes = ansiStyles[key];
- return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key);
- }
- };
- };
- for (var _i = 0; _i < _arr.length; _i++) {
- _loop();
- }
- styles.visible = {
- get() {
- return build.call(this, this._styles || [], true, 'visible');
- }
- };
- ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g');
- var _arr2 = Object.keys(ansiStyles.color.ansi);
- var _loop2 = function _loop2() {
- var model = _arr2[_i2];
- if (skipModels.has(model)) {
- return "continue";
- }
- styles[model] = {
- get() {
- var level = this.level;
- return function () {
- var open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments);
- var codes = {
- open,
- close: ansiStyles.color.close,
- closeRe: ansiStyles.color.closeRe
- };
- return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
- };
- }
- };
- };
- for (var _i2 = 0; _i2 < _arr2.length; _i2++) {
- var _ret = _loop2();
- if (_ret === "continue") continue;
- }
- ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g');
- var _arr3 = Object.keys(ansiStyles.bgColor.ansi);
- var _loop3 = function _loop3() {
- var model = _arr3[_i3];
- if (skipModels.has(model)) {
- return "continue";
- }
- var bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
- styles[bgModel] = {
- get() {
- var level = this.level;
- return function () {
- var open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments);
- var codes = {
- open,
- close: ansiStyles.bgColor.close,
- closeRe: ansiStyles.bgColor.closeRe
- };
- return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
- };
- }
- };
- };
- for (var _i3 = 0; _i3 < _arr3.length; _i3++) {
- var _ret2 = _loop3();
- if (_ret2 === "continue") continue;
- }
- var proto = Object.defineProperties(function () {}, styles);
- function build(_styles, _empty, key) {
- var builder = function builder() {
- return applyStyle.apply(builder, arguments);
- };
- builder._styles = _styles;
- builder._empty = _empty;
- var self = this;
- Object.defineProperty(builder, 'level', {
- enumerable: true,
- get() {
- return self.level;
- },
- set(level) {
- self.level = level;
- }
- });
- Object.defineProperty(builder, 'enabled', {
- enumerable: true,
- get() {
- return self.enabled;
- },
- set(enabled) {
- self.enabled = enabled;
- }
- }); // See below for fix regarding invisible grey/dim combination on Windows
- builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; // `__proto__` is used because we must return a function, but there is
- // no way to create a function with a different prototype
- builder.__proto__ = proto; // eslint-disable-line no-proto
- return builder;
- }
- function applyStyle() {
- // Support varags, but simply cast to string in case there's only one arg
- var args = arguments;
- var argsLen = args.length;
- var str = String(arguments[0]);
- if (argsLen === 0) {
- return '';
- }
- if (argsLen > 1) {
- // Don't slice `arguments`, it prevents V8 optimizations
- for (var a = 1; a < argsLen; a++) {
- str += ' ' + args[a];
- }
- }
- if (!this.enabled || this.level <= 0 || !str) {
- return this._empty ? '' : str;
- } // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe,
- // see https://github.com/chalk/chalk/issues/58
- // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop.
- var originalDim = ansiStyles.dim.open;
- if (isSimpleWindowsTerm && this.hasGrey) {
- ansiStyles.dim.open = '';
- }
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = this._styles.slice().reverse()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var code = _step.value;
- // Replace any instances already present with a re-opening code
- // otherwise only the part of the string until said closing code
- // will be colored, and the rest will simply be 'plain'.
- str = code.open + str.replace(code.closeRe, code.open) + code.close; // Close the styling before a linebreak and reopen
- // after next line to fix a bleed issue on macOS
- // https://github.com/chalk/chalk/pull/92
- str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`);
- } // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- ansiStyles.dim.open = originalDim;
- return str;
- }
- function chalkTag(chalk, strings) {
- if (!Array.isArray(strings)) {
- // If chalk() was called by itself or with a string,
- // return the string itself as a string.
- return [].slice.call(arguments, 1).join(' ');
- }
- var args = [].slice.call(arguments, 2);
- var parts = [strings.raw[0]];
- for (var i = 1; i < strings.length; i++) {
- parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&'));
- parts.push(String(strings.raw[i]));
- }
- return templates(chalk, parts.join(''));
- }
- Object.defineProperties(Chalk.prototype, styles);
- module.exports = Chalk(); // eslint-disable-line new-cap
- module.exports.supportsColor = stdoutColor;
- module.exports.default = module.exports; // For TypeScript
- });
- var common = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.commonDeprecatedHandler = function (keyOrPair, redirectTo, _ref) {
- var descriptor = _ref.descriptor;
- var messages = [`${chalk.default.yellow(typeof keyOrPair === 'string' ? descriptor.key(keyOrPair) : descriptor.pair(keyOrPair))} is deprecated`];
- if (redirectTo) {
- messages.push(`we now treat it as ${chalk.default.blue(typeof redirectTo === 'string' ? descriptor.key(redirectTo) : descriptor.pair(redirectTo))}`);
- }
- return messages.join('; ') + '.';
- };
- });
- unwrapExports(common);
- var deprecated = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- tslib_1.__exportStar(common, exports);
- });
- unwrapExports(deprecated);
- var common$2 = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.commonInvalidHandler = function (key, value, utils) {
- return [`Invalid ${chalk.default.red(utils.descriptor.key(key))} value.`, `Expected ${chalk.default.blue(utils.schemas[key].expected(utils))},`, `but received ${chalk.default.red(utils.descriptor.value(value))}.`].join(' ');
- };
- });
- unwrapExports(common$2);
- var invalid = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- tslib_1.__exportStar(common$2, exports);
- });
- unwrapExports(invalid);
- /* eslint-disable no-nested-ternary */
- var arr = [];
- var charCodeCache = [];
- var leven$1 = function leven(a, b) {
- if (a === b) {
- return 0;
- }
- var swap = a; // Swapping the strings if `a` is longer than `b` so we know which one is the
- // shortest & which one is the longest
- if (a.length > b.length) {
- a = b;
- b = swap;
- }
- var aLen = a.length;
- var bLen = b.length;
- if (aLen === 0) {
- return bLen;
- }
- if (bLen === 0) {
- return aLen;
- } // Performing suffix trimming:
- // We can linearly drop suffix common to both strings since they
- // don't increase distance at all
- // Note: `~-` is the bitwise way to perform a `- 1` operation
- while (aLen > 0 && a.charCodeAt(~-aLen) === b.charCodeAt(~-bLen)) {
- aLen--;
- bLen--;
- }
- if (aLen === 0) {
- return bLen;
- } // Performing prefix trimming
- // We can linearly drop prefix common to both strings since they
- // don't increase distance at all
- var start = 0;
- while (start < aLen && a.charCodeAt(start) === b.charCodeAt(start)) {
- start++;
- }
- aLen -= start;
- bLen -= start;
- if (aLen === 0) {
- return bLen;
- }
- var bCharCode;
- var ret;
- var tmp;
- var tmp2;
- var i = 0;
- var j = 0;
- while (i < aLen) {
- charCodeCache[start + i] = a.charCodeAt(start + i);
- arr[i] = ++i;
- }
- while (j < bLen) {
- bCharCode = b.charCodeAt(start + j);
- tmp = j++;
- ret = j;
- for (i = 0; i < aLen; i++) {
- tmp2 = bCharCode === charCodeCache[start + i] ? tmp : tmp + 1;
- tmp = arr[i];
- ret = arr[i] = tmp > ret ? tmp2 > ret ? ret + 1 : tmp2 : tmp2 > tmp ? tmp + 1 : tmp2;
- }
- }
- return ret;
- };
- var leven_1 = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.levenUnknownHandler = function (key, value, _ref) {
- var descriptor = _ref.descriptor,
- logger = _ref.logger,
- schemas = _ref.schemas;
- var messages = [`Ignored unknown option ${chalk.default.yellow(descriptor.pair({
- key,
- value
- }))}.`];
- var suggestion = Object.keys(schemas).sort().find(function (knownKey) {
- return leven$1(key, knownKey) < 3;
- });
- if (suggestion) {
- messages.push(`Did you mean ${chalk.default.blue(descriptor.key(suggestion))}?`);
- }
- logger.warn(messages.join(' '));
- };
- });
- unwrapExports(leven_1);
- var unknown = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- tslib_1.__exportStar(leven_1, exports);
- });
- unwrapExports(unknown);
- var handlers = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- tslib_1.__exportStar(deprecated, exports);
- tslib_1.__exportStar(invalid, exports);
- tslib_1.__exportStar(unknown, exports);
- });
- unwrapExports(handlers);
- var schema = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- var HANDLER_KEYS = ['default', 'expected', 'validate', 'deprecated', 'forward', 'redirect', 'overlap', 'preprocess', 'postprocess'];
- function createSchema(SchemaConstructor, parameters) {
- var schema = new SchemaConstructor(parameters);
- var subSchema = Object.create(schema);
- for (var _i = 0; _i < HANDLER_KEYS.length; _i++) {
- var handlerKey = HANDLER_KEYS[_i];
- if (handlerKey in parameters) {
- subSchema[handlerKey] = normalizeHandler(parameters[handlerKey], schema, Schema.prototype[handlerKey].length);
- }
- }
- return subSchema;
- }
- exports.createSchema = createSchema;
- var Schema =
- /*#__PURE__*/
- function () {
- function Schema(parameters) {
- _classCallCheck(this, Schema);
- this.name = parameters.name;
- }
- _createClass(Schema, [{
- key: "default",
- value: function _default(_utils) {
- return undefined;
- } // istanbul ignore next: this is actually an abstract method but we need a placeholder to get `function.length`
- }, {
- key: "expected",
- value: function expected(_utils) {
- return 'nothing';
- } // istanbul ignore next: this is actually an abstract method but we need a placeholder to get `function.length`
- }, {
- key: "validate",
- value: function validate(_value, _utils) {
- return false;
- }
- }, {
- key: "deprecated",
- value: function deprecated(_value, _utils) {
- return false;
- }
- }, {
- key: "forward",
- value: function forward(_value, _utils) {
- return undefined;
- }
- }, {
- key: "redirect",
- value: function redirect(_value, _utils) {
- return undefined;
- }
- }, {
- key: "overlap",
- value: function overlap(currentValue, _newValue, _utils) {
- return currentValue;
- }
- }, {
- key: "preprocess",
- value: function preprocess(value, _utils) {
- return value;
- }
- }, {
- key: "postprocess",
- value: function postprocess(value, _utils) {
- return value;
- }
- }], [{
- key: "create",
- value: function create(parameters) {
- // @ts-ignore: https://github.com/Microsoft/TypeScript/issues/5863
- return createSchema(this, parameters);
- }
- }]);
- return Schema;
- }();
- exports.Schema = Schema;
- function normalizeHandler(handler, superSchema, handlerArgumentsLength) {
- return typeof handler === 'function' ? function () {
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
- return handler.apply(void 0, _toConsumableArray(args.slice(0, handlerArgumentsLength - 1)).concat([superSchema], _toConsumableArray(args.slice(handlerArgumentsLength - 1))));
- } : function () {
- return handler;
- };
- }
- });
- unwrapExports(schema);
- var alias = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- var AliasSchema =
- /*#__PURE__*/
- function (_schema_1$Schema) {
- _inherits(AliasSchema, _schema_1$Schema);
- function AliasSchema(parameters) {
- var _this;
- _classCallCheck(this, AliasSchema);
- _this = _possibleConstructorReturn(this, _getPrototypeOf(AliasSchema).call(this, parameters));
- _this._sourceName = parameters.sourceName;
- return _this;
- }
- _createClass(AliasSchema, [{
- key: "expected",
- value: function expected(utils) {
- return utils.schemas[this._sourceName].expected(utils);
- }
- }, {
- key: "validate",
- value: function validate(value, utils) {
- return utils.schemas[this._sourceName].validate(value, utils);
- }
- }, {
- key: "redirect",
- value: function redirect(_value, _utils) {
- return this._sourceName;
- }
- }]);
- return AliasSchema;
- }(schema.Schema);
- exports.AliasSchema = AliasSchema;
- });
- unwrapExports(alias);
- var any = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- var AnySchema =
- /*#__PURE__*/
- function (_schema_1$Schema) {
- _inherits(AnySchema, _schema_1$Schema);
- function AnySchema() {
- _classCallCheck(this, AnySchema);
- return _possibleConstructorReturn(this, _getPrototypeOf(AnySchema).apply(this, arguments));
- }
- _createClass(AnySchema, [{
- key: "expected",
- value: function expected() {
- return 'anything';
- }
- }, {
- key: "validate",
- value: function validate() {
- return true;
- }
- }]);
- return AnySchema;
- }(schema.Schema);
- exports.AnySchema = AnySchema;
- });
- unwrapExports(any);
- var array$2 = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- var ArraySchema =
- /*#__PURE__*/
- function (_schema_1$Schema) {
- _inherits(ArraySchema, _schema_1$Schema);
- function ArraySchema(_a) {
- var _this;
- _classCallCheck(this, ArraySchema);
- var valueSchema = _a.valueSchema,
- _a$name = _a.name,
- name = _a$name === void 0 ? valueSchema.name : _a$name,
- handlers = tslib_1.__rest(_a, ["valueSchema", "name"]);
- _this = _possibleConstructorReturn(this, _getPrototypeOf(ArraySchema).call(this, Object.assign({}, handlers, {
- name
- })));
- _this._valueSchema = valueSchema;
- return _this;
- }
- _createClass(ArraySchema, [{
- key: "expected",
- value: function expected(utils) {
- return `an array of ${this._valueSchema.expected(utils)}`;
- }
- }, {
- key: "validate",
- value: function validate(value, utils) {
- if (!Array.isArray(value)) {
- return false;
- }
- var invalidValues = [];
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = value[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var subValue = _step.value;
- var subValidateResult = utils.normalizeValidateResult(this._valueSchema.validate(subValue, utils), subValue);
- if (subValidateResult !== true) {
- invalidValues.push(subValidateResult.value);
- }
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- return invalidValues.length === 0 ? true : {
- value: invalidValues
- };
- }
- }, {
- key: "deprecated",
- value: function deprecated(value, utils) {
- var deprecatedResult = [];
- var _iteratorNormalCompletion2 = true;
- var _didIteratorError2 = false;
- var _iteratorError2 = undefined;
- try {
- for (var _iterator2 = value[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
- var subValue = _step2.value;
- var subDeprecatedResult = utils.normalizeDeprecatedResult(this._valueSchema.deprecated(subValue, utils), subValue);
- if (subDeprecatedResult !== false) {
- deprecatedResult.push.apply(deprecatedResult, _toConsumableArray(subDeprecatedResult.map(function (_ref) {
- var deprecatedValue = _ref.value;
- return {
- value: [deprecatedValue]
- };
- })));
- }
- }
- } catch (err) {
- _didIteratorError2 = true;
- _iteratorError2 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
- _iterator2.return();
- }
- } finally {
- if (_didIteratorError2) {
- throw _iteratorError2;
- }
- }
- }
- return deprecatedResult;
- }
- }, {
- key: "forward",
- value: function forward(value, utils) {
- var forwardResult = [];
- var _iteratorNormalCompletion3 = true;
- var _didIteratorError3 = false;
- var _iteratorError3 = undefined;
- try {
- for (var _iterator3 = value[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
- var subValue = _step3.value;
- var subForwardResult = utils.normalizeForwardResult(this._valueSchema.forward(subValue, utils), subValue);
- forwardResult.push.apply(forwardResult, _toConsumableArray(subForwardResult.map(wrapTransferResult)));
- }
- } catch (err) {
- _didIteratorError3 = true;
- _iteratorError3 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
- _iterator3.return();
- }
- } finally {
- if (_didIteratorError3) {
- throw _iteratorError3;
- }
- }
- }
- return forwardResult;
- }
- }, {
- key: "redirect",
- value: function redirect(value, utils) {
- var remain = [];
- var redirect = [];
- var _iteratorNormalCompletion4 = true;
- var _didIteratorError4 = false;
- var _iteratorError4 = undefined;
- try {
- for (var _iterator4 = value[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
- var subValue = _step4.value;
- var subRedirectResult = utils.normalizeRedirectResult(this._valueSchema.redirect(subValue, utils), subValue);
- if ('remain' in subRedirectResult) {
- remain.push(subRedirectResult.remain);
- }
- redirect.push.apply(redirect, _toConsumableArray(subRedirectResult.redirect.map(wrapTransferResult)));
- }
- } catch (err) {
- _didIteratorError4 = true;
- _iteratorError4 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion4 && _iterator4.return != null) {
- _iterator4.return();
- }
- } finally {
- if (_didIteratorError4) {
- throw _iteratorError4;
- }
- }
- }
- return remain.length === 0 ? {
- redirect
- } : {
- redirect,
- remain
- };
- }
- }, {
- key: "overlap",
- value: function overlap(currentValue, newValue) {
- return currentValue.concat(newValue);
- }
- }]);
- return ArraySchema;
- }(schema.Schema);
- exports.ArraySchema = ArraySchema;
- function wrapTransferResult(_ref2) {
- var from = _ref2.from,
- to = _ref2.to;
- return {
- from: [from],
- to
- };
- }
- });
- unwrapExports(array$2);
- var boolean_1 = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- var BooleanSchema =
- /*#__PURE__*/
- function (_schema_1$Schema) {
- _inherits(BooleanSchema, _schema_1$Schema);
- function BooleanSchema() {
- _classCallCheck(this, BooleanSchema);
- return _possibleConstructorReturn(this, _getPrototypeOf(BooleanSchema).apply(this, arguments));
- }
- _createClass(BooleanSchema, [{
- key: "expected",
- value: function expected() {
- return 'true or false';
- }
- }, {
- key: "validate",
- value: function validate(value) {
- return typeof value === 'boolean';
- }
- }]);
- return BooleanSchema;
- }(schema.Schema);
- exports.BooleanSchema = BooleanSchema;
- });
- unwrapExports(boolean_1);
- var utils = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- function recordFromArray(array, mainKey) {
- var record = Object.create(null);
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = array[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var value = _step.value;
- var key = value[mainKey]; // istanbul ignore next
- if (record[key]) {
- throw new Error(`Duplicate ${mainKey} ${JSON.stringify(key)}`);
- } // @ts-ignore
- record[key] = value;
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- return record;
- }
- exports.recordFromArray = recordFromArray;
- function mapFromArray(array, mainKey) {
- var map = new Map();
- var _iteratorNormalCompletion2 = true;
- var _didIteratorError2 = false;
- var _iteratorError2 = undefined;
- try {
- for (var _iterator2 = array[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
- var value = _step2.value;
- var key = value[mainKey]; // istanbul ignore next
- if (map.has(key)) {
- throw new Error(`Duplicate ${mainKey} ${JSON.stringify(key)}`);
- }
- map.set(key, value);
- }
- } catch (err) {
- _didIteratorError2 = true;
- _iteratorError2 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
- _iterator2.return();
- }
- } finally {
- if (_didIteratorError2) {
- throw _iteratorError2;
- }
- }
- }
- return map;
- }
- exports.mapFromArray = mapFromArray;
- function createAutoChecklist() {
- var map = Object.create(null);
- return function (id) {
- var idString = JSON.stringify(id);
- if (map[idString]) {
- return true;
- }
- map[idString] = true;
- return false;
- };
- }
- exports.createAutoChecklist = createAutoChecklist;
- function partition(array, predicate) {
- var trueArray = [];
- var falseArray = [];
- var _iteratorNormalCompletion3 = true;
- var _didIteratorError3 = false;
- var _iteratorError3 = undefined;
- try {
- for (var _iterator3 = array[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
- var value = _step3.value;
- if (predicate(value)) {
- trueArray.push(value);
- } else {
- falseArray.push(value);
- }
- }
- } catch (err) {
- _didIteratorError3 = true;
- _iteratorError3 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
- _iterator3.return();
- }
- } finally {
- if (_didIteratorError3) {
- throw _iteratorError3;
- }
- }
- }
- return [trueArray, falseArray];
- }
- exports.partition = partition;
- function isInt(value) {
- return value === Math.floor(value);
- }
- exports.isInt = isInt;
- function comparePrimitive(a, b) {
- if (a === b) {
- return 0;
- }
- var typeofA = typeof a;
- var typeofB = typeof b;
- var orders = ['undefined', 'object', 'boolean', 'number', 'string'];
- if (typeofA !== typeofB) {
- return orders.indexOf(typeofA) - orders.indexOf(typeofB);
- }
- if (typeofA !== 'string') {
- return Number(a) - Number(b);
- }
- return a.localeCompare(b);
- }
- exports.comparePrimitive = comparePrimitive;
- function normalizeDefaultResult(result) {
- return result === undefined ? {} : result;
- }
- exports.normalizeDefaultResult = normalizeDefaultResult;
- function normalizeValidateResult(result, value) {
- return result === true ? true : result === false ? {
- value
- } : result;
- }
- exports.normalizeValidateResult = normalizeValidateResult;
- function normalizeDeprecatedResult(result, value) {
- var doNotNormalizeTrue = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
- return result === false ? false : result === true ? doNotNormalizeTrue ? true : [{
- value
- }] : 'value' in result ? [result] : result.length === 0 ? false : result;
- }
- exports.normalizeDeprecatedResult = normalizeDeprecatedResult;
- function normalizeTransferResult(result, value) {
- return typeof result === 'string' || 'key' in result ? {
- from: value,
- to: result
- } : 'from' in result ? {
- from: result.from,
- to: result.to
- } : {
- from: value,
- to: result.to
- };
- }
- exports.normalizeTransferResult = normalizeTransferResult;
- function normalizeForwardResult(result, value) {
- return result === undefined ? [] : Array.isArray(result) ? result.map(function (transferResult) {
- return normalizeTransferResult(transferResult, value);
- }) : [normalizeTransferResult(result, value)];
- }
- exports.normalizeForwardResult = normalizeForwardResult;
- function normalizeRedirectResult(result, value) {
- var redirect = normalizeForwardResult(typeof result === 'object' && 'redirect' in result ? result.redirect : result, value);
- return redirect.length === 0 ? {
- remain: value,
- redirect
- } : typeof result === 'object' && 'remain' in result ? {
- remain: result.remain,
- redirect
- } : {
- redirect
- };
- }
- exports.normalizeRedirectResult = normalizeRedirectResult;
- });
- unwrapExports(utils);
- var choice = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- var ChoiceSchema =
- /*#__PURE__*/
- function (_schema_1$Schema) {
- _inherits(ChoiceSchema, _schema_1$Schema);
- function ChoiceSchema(parameters) {
- var _this;
- _classCallCheck(this, ChoiceSchema);
- _this = _possibleConstructorReturn(this, _getPrototypeOf(ChoiceSchema).call(this, parameters));
- _this._choices = utils.mapFromArray(parameters.choices.map(function (choice) {
- return choice && typeof choice === 'object' ? choice : {
- value: choice
- };
- }), 'value');
- return _this;
- }
- _createClass(ChoiceSchema, [{
- key: "expected",
- value: function expected(_ref) {
- var _this2 = this;
- var descriptor = _ref.descriptor;
- var choiceValues = Array.from(this._choices.keys()).map(function (value) {
- return _this2._choices.get(value);
- }).filter(function (choiceInfo) {
- return !choiceInfo.deprecated;
- }).map(function (choiceInfo) {
- return choiceInfo.value;
- }).sort(utils.comparePrimitive).map(descriptor.value);
- var head = choiceValues.slice(0, -2);
- var tail = choiceValues.slice(-2);
- return head.concat(tail.join(' or ')).join(', ');
- }
- }, {
- key: "validate",
- value: function validate(value) {
- return this._choices.has(value);
- }
- }, {
- key: "deprecated",
- value: function deprecated(value) {
- var choiceInfo = this._choices.get(value);
- return choiceInfo && choiceInfo.deprecated ? {
- value
- } : false;
- }
- }, {
- key: "forward",
- value: function forward(value) {
- var choiceInfo = this._choices.get(value);
- return choiceInfo ? choiceInfo.forward : undefined;
- }
- }, {
- key: "redirect",
- value: function redirect(value) {
- var choiceInfo = this._choices.get(value);
- return choiceInfo ? choiceInfo.redirect : undefined;
- }
- }]);
- return ChoiceSchema;
- }(schema.Schema);
- exports.ChoiceSchema = ChoiceSchema;
- });
- unwrapExports(choice);
- var number = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- var NumberSchema =
- /*#__PURE__*/
- function (_schema_1$Schema) {
- _inherits(NumberSchema, _schema_1$Schema);
- function NumberSchema() {
- _classCallCheck(this, NumberSchema);
- return _possibleConstructorReturn(this, _getPrototypeOf(NumberSchema).apply(this, arguments));
- }
- _createClass(NumberSchema, [{
- key: "expected",
- value: function expected() {
- return 'a number';
- }
- }, {
- key: "validate",
- value: function validate(value, _utils) {
- return typeof value === 'number';
- }
- }]);
- return NumberSchema;
- }(schema.Schema);
- exports.NumberSchema = NumberSchema;
- });
- unwrapExports(number);
- var integer = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- var IntegerSchema =
- /*#__PURE__*/
- function (_number_1$NumberSchem) {
- _inherits(IntegerSchema, _number_1$NumberSchem);
- function IntegerSchema() {
- _classCallCheck(this, IntegerSchema);
- return _possibleConstructorReturn(this, _getPrototypeOf(IntegerSchema).apply(this, arguments));
- }
- _createClass(IntegerSchema, [{
- key: "expected",
- value: function expected() {
- return 'an integer';
- }
- }, {
- key: "validate",
- value: function validate(value, utils$$2) {
- return utils$$2.normalizeValidateResult(_get(_getPrototypeOf(IntegerSchema.prototype), "validate", this).call(this, value, utils$$2), value) === true && utils.isInt(value);
- }
- }]);
- return IntegerSchema;
- }(number.NumberSchema);
- exports.IntegerSchema = IntegerSchema;
- });
- unwrapExports(integer);
- var string = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- var StringSchema =
- /*#__PURE__*/
- function (_schema_1$Schema) {
- _inherits(StringSchema, _schema_1$Schema);
- function StringSchema() {
- _classCallCheck(this, StringSchema);
- return _possibleConstructorReturn(this, _getPrototypeOf(StringSchema).apply(this, arguments));
- }
- _createClass(StringSchema, [{
- key: "expected",
- value: function expected() {
- return 'a string';
- }
- }, {
- key: "validate",
- value: function validate(value) {
- return typeof value === 'string';
- }
- }]);
- return StringSchema;
- }(schema.Schema);
- exports.StringSchema = StringSchema;
- });
- unwrapExports(string);
- var schemas = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- tslib_1.__exportStar(alias, exports);
- tslib_1.__exportStar(any, exports);
- tslib_1.__exportStar(array$2, exports);
- tslib_1.__exportStar(boolean_1, exports);
- tslib_1.__exportStar(choice, exports);
- tslib_1.__exportStar(integer, exports);
- tslib_1.__exportStar(number, exports);
- tslib_1.__exportStar(string, exports);
- });
- unwrapExports(schemas);
- var defaults = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.defaultDescriptor = api.apiDescriptor;
- exports.defaultUnknownHandler = leven_1.levenUnknownHandler;
- exports.defaultInvalidHandler = invalid.commonInvalidHandler;
- exports.defaultDeprecatedHandler = common.commonDeprecatedHandler;
- });
- unwrapExports(defaults);
- var normalize$1 = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.normalize = function (options, schemas, opts) {
- return new Normalizer(schemas, opts).normalize(options);
- };
- var Normalizer =
- /*#__PURE__*/
- function () {
- function Normalizer(schemas, opts) {
- _classCallCheck(this, Normalizer);
- // istanbul ignore next
- var _ref = opts || {},
- _ref$logger = _ref.logger,
- logger = _ref$logger === void 0 ? console : _ref$logger,
- _ref$descriptor = _ref.descriptor,
- descriptor = _ref$descriptor === void 0 ? defaults.defaultDescriptor : _ref$descriptor,
- _ref$unknown = _ref.unknown,
- unknown = _ref$unknown === void 0 ? defaults.defaultUnknownHandler : _ref$unknown,
- _ref$invalid = _ref.invalid,
- invalid = _ref$invalid === void 0 ? defaults.defaultInvalidHandler : _ref$invalid,
- _ref$deprecated = _ref.deprecated,
- deprecated = _ref$deprecated === void 0 ? defaults.defaultDeprecatedHandler : _ref$deprecated;
- this._utils = {
- descriptor,
- logger:
- /* istanbul ignore next */
- logger || {
- warn: function warn() {}
- },
- schemas: utils.recordFromArray(schemas, 'name'),
- normalizeDefaultResult: utils.normalizeDefaultResult,
- normalizeDeprecatedResult: utils.normalizeDeprecatedResult,
- normalizeForwardResult: utils.normalizeForwardResult,
- normalizeRedirectResult: utils.normalizeRedirectResult,
- normalizeValidateResult: utils.normalizeValidateResult
- };
- this._unknownHandler = unknown;
- this._invalidHandler = invalid;
- this._deprecatedHandler = deprecated;
- this.cleanHistory();
- }
- _createClass(Normalizer, [{
- key: "cleanHistory",
- value: function cleanHistory() {
- this._hasDeprecationWarned = utils.createAutoChecklist();
- }
- }, {
- key: "normalize",
- value: function normalize(options) {
- var _this = this;
- var normalized = {};
- var restOptionsArray = [options];
- var applyNormalization = function applyNormalization() {
- while (restOptionsArray.length !== 0) {
- var currentOptions = restOptionsArray.shift();
- var transferredOptionsArray = _this._applyNormalization(currentOptions, normalized);
- restOptionsArray.push.apply(restOptionsArray, _toConsumableArray(transferredOptionsArray));
- }
- };
- applyNormalization();
- var _arr = Object.keys(this._utils.schemas);
- for (var _i = 0; _i < _arr.length; _i++) {
- var key = _arr[_i];
- var schema = this._utils.schemas[key];
- if (!(key in normalized)) {
- var defaultResult = utils.normalizeDefaultResult(schema.default(this._utils));
- if ('value' in defaultResult) {
- restOptionsArray.push({
- [key]: defaultResult.value
- });
- }
- }
- }
- applyNormalization();
- var _arr2 = Object.keys(this._utils.schemas);
- for (var _i2 = 0; _i2 < _arr2.length; _i2++) {
- var _key = _arr2[_i2];
- var _schema = this._utils.schemas[_key];
- if (_key in normalized) {
- normalized[_key] = _schema.postprocess(normalized[_key], this._utils);
- }
- }
- return normalized;
- }
- }, {
- key: "_applyNormalization",
- value: function _applyNormalization(options, normalized) {
- var _this2 = this;
- var transferredOptionsArray = [];
- var _utils_1$partition = utils.partition(Object.keys(options), function (key) {
- return key in _this2._utils.schemas;
- }),
- _utils_1$partition2 = _slicedToArray(_utils_1$partition, 2),
- knownOptionNames = _utils_1$partition2[0],
- unknownOptionNames = _utils_1$partition2[1];
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- var _loop = function _loop() {
- var key = _step.value;
- var schema = _this2._utils.schemas[key];
- var value = schema.preprocess(options[key], _this2._utils);
- var validateResult = utils.normalizeValidateResult(schema.validate(value, _this2._utils), value);
- if (validateResult !== true) {
- var invalidValue = validateResult.value;
- var errorMessageOrError = _this2._invalidHandler(key, invalidValue, _this2._utils);
- throw typeof errorMessageOrError === 'string' ? new Error(errorMessageOrError) :
- /* istanbul ignore next*/
- errorMessageOrError;
- }
- var appendTransferredOptions = function appendTransferredOptions(_ref2) {
- var from = _ref2.from,
- to = _ref2.to;
- transferredOptionsArray.push(typeof to === 'string' ? {
- [to]: from
- } : {
- [to.key]: to.value
- });
- };
- var warnDeprecated = function warnDeprecated(_ref3) {
- var currentValue = _ref3.value,
- redirectTo = _ref3.redirectTo;
- var deprecatedResult = utils.normalizeDeprecatedResult(schema.deprecated(currentValue, _this2._utils), value,
- /* doNotNormalizeTrue */
- true);
- if (deprecatedResult === false) {
- return;
- }
- if (deprecatedResult === true) {
- if (!_this2._hasDeprecationWarned(key)) {
- _this2._utils.logger.warn(_this2._deprecatedHandler(key, redirectTo, _this2._utils));
- }
- } else {
- var _iteratorNormalCompletion3 = true;
- var _didIteratorError3 = false;
- var _iteratorError3 = undefined;
- try {
- for (var _iterator3 = deprecatedResult[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
- var deprecatedValue = _step3.value.value;
- var pair = {
- key,
- value: deprecatedValue
- };
- if (!_this2._hasDeprecationWarned(pair)) {
- var redirectToPair = typeof redirectTo === 'string' ? {
- key: redirectTo,
- value: deprecatedValue
- } : redirectTo;
- _this2._utils.logger.warn(_this2._deprecatedHandler(pair, redirectToPair, _this2._utils));
- }
- }
- } catch (err) {
- _didIteratorError3 = true;
- _iteratorError3 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
- _iterator3.return();
- }
- } finally {
- if (_didIteratorError3) {
- throw _iteratorError3;
- }
- }
- }
- }
- };
- var forwardResult = utils.normalizeForwardResult(schema.forward(value, _this2._utils), value);
- forwardResult.forEach(appendTransferredOptions);
- var redirectResult = utils.normalizeRedirectResult(schema.redirect(value, _this2._utils), value);
- redirectResult.redirect.forEach(appendTransferredOptions);
- if ('remain' in redirectResult) {
- var remainingValue = redirectResult.remain;
- normalized[key] = key in normalized ? schema.overlap(normalized[key], remainingValue, _this2._utils) : remainingValue;
- warnDeprecated({
- value: remainingValue
- });
- }
- var _iteratorNormalCompletion4 = true;
- var _didIteratorError4 = false;
- var _iteratorError4 = undefined;
- try {
- for (var _iterator4 = redirectResult.redirect[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
- var _step4$value = _step4.value,
- from = _step4$value.from,
- to = _step4$value.to;
- warnDeprecated({
- value: from,
- redirectTo: to
- });
- }
- } catch (err) {
- _didIteratorError4 = true;
- _iteratorError4 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion4 && _iterator4.return != null) {
- _iterator4.return();
- }
- } finally {
- if (_didIteratorError4) {
- throw _iteratorError4;
- }
- }
- }
- };
- for (var _iterator = knownOptionNames[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- _loop();
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- var _iteratorNormalCompletion2 = true;
- var _didIteratorError2 = false;
- var _iteratorError2 = undefined;
- try {
- for (var _iterator2 = unknownOptionNames[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
- var key = _step2.value;
- var value = options[key];
- var unknownResult = this._unknownHandler(key, value, this._utils);
- if (unknownResult) {
- var _arr3 = Object.keys(unknownResult);
- for (var _i3 = 0; _i3 < _arr3.length; _i3++) {
- var unknownKey = _arr3[_i3];
- var unknownOption = {
- [unknownKey]: unknownResult[unknownKey]
- };
- if (unknownKey in this._utils.schemas) {
- transferredOptionsArray.push(unknownOption);
- } else {
- Object.assign(normalized, unknownOption);
- }
- }
- }
- }
- } catch (err) {
- _didIteratorError2 = true;
- _iteratorError2 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
- _iterator2.return();
- }
- } finally {
- if (_didIteratorError2) {
- throw _iteratorError2;
- }
- }
- }
- return transferredOptionsArray;
- }
- }]);
- return Normalizer;
- }();
- exports.Normalizer = Normalizer;
- });
- unwrapExports(normalize$1);
- var lib$1 = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- tslib_1.__exportStar(descriptors, exports);
- tslib_1.__exportStar(handlers, exports);
- tslib_1.__exportStar(schemas, exports);
- tslib_1.__exportStar(normalize$1, exports);
- tslib_1.__exportStar(schema, exports);
- });
- unwrapExports(lib$1);
- var hasFlag$3 = function hasFlag(flag, argv) {
- argv = argv || process.argv;
- var terminatorPos = argv.indexOf('--');
- var prefix = /^-{1,2}/.test(flag) ? '' : '--';
- var pos = argv.indexOf(prefix + flag);
- return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos);
- };
- var supportsColor$1 = createCommonjsModule(function (module) {
- 'use strict';
- var env = process.env;
- var support = function support(level) {
- if (level === 0) {
- return false;
- }
- return {
- level,
- hasBasic: true,
- has256: level >= 2,
- has16m: level >= 3
- };
- };
- var supportLevel = function () {
- if (hasFlag$3('no-color') || hasFlag$3('no-colors') || hasFlag$3('color=false')) {
- return 0;
- }
- if (hasFlag$3('color=16m') || hasFlag$3('color=full') || hasFlag$3('color=truecolor')) {
- return 3;
- }
- if (hasFlag$3('color=256')) {
- return 2;
- }
- if (hasFlag$3('color') || hasFlag$3('colors') || hasFlag$3('color=true') || hasFlag$3('color=always')) {
- return 1;
- }
- if (process.stdout && !process.stdout.isTTY) {
- return 0;
- }
- if (process.platform === 'win32') {
- // Node.js 7.5.0 is the first version of Node.js to include a patch to
- // libuv that enables 256 color output on Windows. Anything earlier and it
- // won't work. However, here we target Node.js 8 at minimum as it is an LTS
- // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows
- // release that supports 256 colors.
- var osRelease = os.release().split('.');
- if (Number(process.versions.node.split('.')[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
- return 2;
- }
- return 1;
- }
- if ('CI' in env) {
- if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(function (sign) {
- return sign in env;
- }) || env.CI_NAME === 'codeship') {
- return 1;
- }
- return 0;
- }
- if ('TEAMCITY_VERSION' in env) {
- return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
- }
- if ('TERM_PROGRAM' in env) {
- var version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
- switch (env.TERM_PROGRAM) {
- case 'iTerm.app':
- return version >= 3 ? 3 : 2;
- case 'Hyper':
- return 3;
- case 'Apple_Terminal':
- return 2;
- // No default
- }
- }
- if (/-256(color)?$/i.test(env.TERM)) {
- return 2;
- }
- if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
- return 1;
- }
- if ('COLORTERM' in env) {
- return 1;
- }
- if (env.TERM === 'dumb') {
- return 0;
- }
- return 0;
- }();
- if ('FORCE_COLOR' in env) {
- supportLevel = parseInt(env.FORCE_COLOR, 10) === 0 ? 0 : supportLevel || 1;
- }
- module.exports = process && support(supportLevel);
- });
- var templates$2 = createCommonjsModule(function (module) {
- 'use strict';
- var TEMPLATE_REGEX = /(?:\\(u[a-f0-9]{4}|x[a-f0-9]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
- var STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
- var STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
- var ESCAPE_REGEX = /\\(u[0-9a-f]{4}|x[0-9a-f]{2}|.)|([^\\])/gi;
- var ESCAPES = {
- n: '\n',
- r: '\r',
- t: '\t',
- b: '\b',
- f: '\f',
- v: '\v',
- 0: '\0',
- '\\': '\\',
- e: '\u001b',
- a: '\u0007'
- };
- function unescape(c) {
- if (c[0] === 'u' && c.length === 5 || c[0] === 'x' && c.length === 3) {
- return String.fromCharCode(parseInt(c.slice(1), 16));
- }
- return ESCAPES[c] || c;
- }
- function parseArguments(name, args) {
- var results = [];
- var chunks = args.trim().split(/\s*,\s*/g);
- var matches;
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = chunks[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var chunk = _step.value;
- if (!isNaN(chunk)) {
- results.push(Number(chunk));
- } else if (matches = chunk.match(STRING_REGEX)) {
- results.push(matches[2].replace(ESCAPE_REGEX, function (m, escape, chr) {
- return escape ? unescape(escape) : chr;
- }));
- } else {
- throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
- }
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- return results;
- }
- function parseStyle(style) {
- STYLE_REGEX.lastIndex = 0;
- var results = [];
- var matches;
- while ((matches = STYLE_REGEX.exec(style)) !== null) {
- var name = matches[1];
- if (matches[2]) {
- var args = parseArguments(name, matches[2]);
- results.push([name].concat(args));
- } else {
- results.push([name]);
- }
- }
- return results;
- }
- function buildStyle(chalk, styles) {
- var enabled = {};
- var _iteratorNormalCompletion2 = true;
- var _didIteratorError2 = false;
- var _iteratorError2 = undefined;
- try {
- for (var _iterator2 = styles[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
- var layer = _step2.value;
- var _iteratorNormalCompletion3 = true;
- var _didIteratorError3 = false;
- var _iteratorError3 = undefined;
- try {
- for (var _iterator3 = layer.styles[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
- var style = _step3.value;
- enabled[style[0]] = layer.inverse ? null : style.slice(1);
- }
- } catch (err) {
- _didIteratorError3 = true;
- _iteratorError3 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
- _iterator3.return();
- }
- } finally {
- if (_didIteratorError3) {
- throw _iteratorError3;
- }
- }
- }
- }
- } catch (err) {
- _didIteratorError2 = true;
- _iteratorError2 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
- _iterator2.return();
- }
- } finally {
- if (_didIteratorError2) {
- throw _iteratorError2;
- }
- }
- }
- var current = chalk;
- var _arr = Object.keys(enabled);
- for (var _i = 0; _i < _arr.length; _i++) {
- var styleName = _arr[_i];
- if (Array.isArray(enabled[styleName])) {
- if (!(styleName in current)) {
- throw new Error(`Unknown Chalk style: ${styleName}`);
- }
- if (enabled[styleName].length > 0) {
- current = current[styleName].apply(current, enabled[styleName]);
- } else {
- current = current[styleName];
- }
- }
- }
- return current;
- }
- module.exports = function (chalk, tmp) {
- var styles = [];
- var chunks = [];
- var chunk = []; // eslint-disable-next-line max-params
- tmp.replace(TEMPLATE_REGEX, function (m, escapeChar, inverse, style, close, chr) {
- if (escapeChar) {
- chunk.push(unescape(escapeChar));
- } else if (style) {
- var str = chunk.join('');
- chunk = [];
- chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str));
- styles.push({
- inverse,
- styles: parseStyle(style)
- });
- } else if (close) {
- if (styles.length === 0) {
- throw new Error('Found extraneous } in Chalk template literal');
- }
- chunks.push(buildStyle(chalk, styles)(chunk.join('')));
- chunk = [];
- styles.pop();
- } else {
- chunk.push(chr);
- }
- });
- chunks.push(chunk.join(''));
- if (styles.length > 0) {
- var errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
- throw new Error(errMsg);
- }
- return chunks.join('');
- };
- });
- var isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); // `supportsColor.level` → `ansiStyles.color[name]` mapping
- var levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; // `color-convert` models to exclude from the Chalk API due to conflicts and such
- var skipModels = new Set(['gray']);
- var styles = Object.create(null);
- function applyOptions(obj, options) {
- options = options || {}; // Detect level if not set manually
- var scLevel = supportsColor$1 ? supportsColor$1.level : 0;
- obj.level = options.level === undefined ? scLevel : options.level;
- obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0;
- }
- function Chalk(options) {
- // We check for this.template here since calling `chalk.constructor()`
- // by itself will have a `this` of a previously constructed chalk object
- if (!this || !(this instanceof Chalk) || this.template) {
- var _chalk = {};
- applyOptions(_chalk, options);
- _chalk.template = function () {
- var args = [].slice.call(arguments);
- return chalkTag.apply(null, [_chalk.template].concat(args));
- };
- Object.setPrototypeOf(_chalk, Chalk.prototype);
- Object.setPrototypeOf(_chalk.template, _chalk);
- _chalk.template.constructor = Chalk;
- return _chalk.template;
- }
- applyOptions(this, options);
- } // Use bright blue on Windows as the normal blue color is illegible
- if (isSimpleWindowsTerm) {
- ansiStyles.blue.open = '\u001B[94m';
- }
- var _arr = Object.keys(ansiStyles);
- var _loop = function _loop() {
- var key = _arr[_i];
- ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g');
- styles[key] = {
- get() {
- var codes = ansiStyles[key];
- return build.call(this, this._styles ? this._styles.concat(codes) : [codes], key);
- }
- };
- };
- for (var _i = 0; _i < _arr.length; _i++) {
- _loop();
- }
- ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g');
- var _arr2 = Object.keys(ansiStyles.color.ansi);
- var _loop2 = function _loop2() {
- var model = _arr2[_i2];
- if (skipModels.has(model)) {
- return "continue";
- }
- styles[model] = {
- get() {
- var level = this.level;
- return function () {
- var open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments);
- var codes = {
- open,
- close: ansiStyles.color.close,
- closeRe: ansiStyles.color.closeRe
- };
- return build.call(this, this._styles ? this._styles.concat(codes) : [codes], model);
- };
- }
- };
- };
- for (var _i2 = 0; _i2 < _arr2.length; _i2++) {
- var _ret = _loop2();
- if (_ret === "continue") continue;
- }
- ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g');
- var _arr3 = Object.keys(ansiStyles.bgColor.ansi);
- var _loop3 = function _loop3() {
- var model = _arr3[_i3];
- if (skipModels.has(model)) {
- return "continue";
- }
- var bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
- styles[bgModel] = {
- get() {
- var level = this.level;
- return function () {
- var open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments);
- var codes = {
- open,
- close: ansiStyles.bgColor.close,
- closeRe: ansiStyles.bgColor.closeRe
- };
- return build.call(this, this._styles ? this._styles.concat(codes) : [codes], model);
- };
- }
- };
- };
- for (var _i3 = 0; _i3 < _arr3.length; _i3++) {
- var _ret2 = _loop3();
- if (_ret2 === "continue") continue;
- }
- var proto = Object.defineProperties(function () {}, styles);
- function build(_styles, key) {
- var builder = function builder() {
- return applyStyle.apply(builder, arguments);
- };
- builder._styles = _styles;
- var self = this;
- Object.defineProperty(builder, 'level', {
- enumerable: true,
- get() {
- return self.level;
- },
- set(level) {
- self.level = level;
- }
- });
- Object.defineProperty(builder, 'enabled', {
- enumerable: true,
- get() {
- return self.enabled;
- },
- set(enabled) {
- self.enabled = enabled;
- }
- }); // See below for fix regarding invisible grey/dim combination on Windows
- builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; // `__proto__` is used because we must return a function, but there is
- // no way to create a function with a different prototype
- builder.__proto__ = proto; // eslint-disable-line no-proto
- return builder;
- }
- function applyStyle() {
- // Support varags, but simply cast to string in case there's only one arg
- var args = arguments;
- var argsLen = args.length;
- var str = String(arguments[0]);
- if (argsLen === 0) {
- return '';
- }
- if (argsLen > 1) {
- // Don't slice `arguments`, it prevents V8 optimizations
- for (var a = 1; a < argsLen; a++) {
- str += ' ' + args[a];
- }
- }
- if (!this.enabled || this.level <= 0 || !str) {
- return str;
- } // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe,
- // see https://github.com/chalk/chalk/issues/58
- // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop.
- var originalDim = ansiStyles.dim.open;
- if (isSimpleWindowsTerm && this.hasGrey) {
- ansiStyles.dim.open = '';
- }
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = this._styles.slice().reverse()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var code = _step.value;
- // Replace any instances already present with a re-opening code
- // otherwise only the part of the string until said closing code
- // will be colored, and the rest will simply be 'plain'.
- str = code.open + str.replace(code.closeRe, code.open) + code.close; // Close the styling before a linebreak and reopen
- // after next line to fix a bleed issue on macOS
- // https://github.com/chalk/chalk/pull/92
- str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`);
- } // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- ansiStyles.dim.open = originalDim;
- return str;
- }
- function chalkTag(chalk, strings) {
- if (!Array.isArray(strings)) {
- // If chalk() was called by itself or with a string,
- // return the string itself as a string.
- return [].slice.call(arguments, 1).join(' ');
- }
- var args = [].slice.call(arguments, 2);
- var parts = [strings.raw[0]];
- for (var i = 1; i < strings.length; i++) {
- parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&'));
- parts.push(String(strings.raw[i]));
- }
- return templates$2(chalk, parts.join(''));
- }
- Object.defineProperties(Chalk.prototype, styles);
- var chalk$2 = Chalk(); // eslint-disable-line new-cap
- var supportsColor_1$2 = supportsColor$1;
- chalk$2.supportsColor = supportsColor_1$2;
- var cliDescriptor = {
- key: function key(_key) {
- return _key.length === 1 ? `-${_key}` : `--${_key}`;
- },
- value: function value(_value) {
- return lib$1.apiDescriptor.value(_value);
- },
- pair: function pair(_ref) {
- var key = _ref.key,
- value = _ref.value;
- return value === false ? `--no-${key}` : value === true ? cliDescriptor.key(key) : value === "" ? `${cliDescriptor.key(key)} without an argument` : `${cliDescriptor.key(key)}=${value}`;
- }
- };
- var FlagSchema =
- /*#__PURE__*/
- function (_vnopts$ChoiceSchema) {
- _inherits(FlagSchema, _vnopts$ChoiceSchema);
- function FlagSchema(_ref2) {
- var _this;
- var name = _ref2.name,
- flags = _ref2.flags;
- _classCallCheck(this, FlagSchema);
- _this = _possibleConstructorReturn(this, _getPrototypeOf(FlagSchema).call(this, {
- name,
- choices: flags
- }));
- _this._flags = flags.slice().sort();
- return _this;
- }
- _createClass(FlagSchema, [{
- key: "preprocess",
- value: function preprocess(value, utils) {
- if (typeof value === "string" && value.length !== 0 && this._flags.indexOf(value) === -1) {
- var suggestion = this._flags.find(function (flag) {
- return leven$1(flag, value) < 3;
- });
- if (suggestion) {
- utils.logger.warn([`Unknown flag ${chalk$2.yellow(utils.descriptor.value(value))},`, `did you mean ${chalk$2.blue(utils.descriptor.value(suggestion))}?`].join(" "));
- return suggestion;
- }
- }
- return value;
- }
- }, {
- key: "expected",
- value: function expected() {
- return "a flag";
- }
- }]);
- return FlagSchema;
- }(lib$1.ChoiceSchema);
- var hasDeprecationWarned;
- function normalizeOptions$1(options, optionInfos) {
- var _ref3 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {},
- logger = _ref3.logger,
- _ref3$isCLI = _ref3.isCLI,
- isCLI = _ref3$isCLI === void 0 ? false : _ref3$isCLI,
- _ref3$passThrough = _ref3.passThrough,
- passThrough = _ref3$passThrough === void 0 ? false : _ref3$passThrough;
- var unknown = !passThrough ? lib$1.levenUnknownHandler : Array.isArray(passThrough) ? function (key, value) {
- return passThrough.indexOf(key) === -1 ? undefined : {
- [key]: value
- };
- } : function (key, value) {
- return {
- [key]: value
- };
- };
- var descriptor = isCLI ? cliDescriptor : lib$1.apiDescriptor;
- var schemas = optionInfosToSchemas(optionInfos, {
- isCLI
- });
- var normalizer = new lib$1.Normalizer(schemas, {
- logger,
- unknown,
- descriptor
- });
- var shouldSuppressDuplicateDeprecationWarnings = logger !== false;
- if (shouldSuppressDuplicateDeprecationWarnings && hasDeprecationWarned) {
- normalizer._hasDeprecationWarned = hasDeprecationWarned;
- }
- var normalized = normalizer.normalize(options);
- if (shouldSuppressDuplicateDeprecationWarnings) {
- hasDeprecationWarned = normalizer._hasDeprecationWarned;
- }
- return normalized;
- }
- function optionInfosToSchemas(optionInfos, _ref4) {
- var isCLI = _ref4.isCLI;
- var schemas = [];
- if (isCLI) {
- schemas.push(lib$1.AnySchema.create({
- name: "_"
- }));
- }
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = optionInfos[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var optionInfo = _step.value;
- schemas.push(optionInfoToSchema(optionInfo, {
- isCLI,
- optionInfos
- }));
- if (optionInfo.alias && isCLI) {
- schemas.push(lib$1.AliasSchema.create({
- name: optionInfo.alias,
- sourceName: optionInfo.name
- }));
- }
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- return schemas;
- }
- function optionInfoToSchema(optionInfo, _ref5) {
- var isCLI = _ref5.isCLI,
- optionInfos = _ref5.optionInfos;
- var SchemaConstructor;
- var parameters = {
- name: optionInfo.name
- };
- var handlers = {};
- switch (optionInfo.type) {
- case "int":
- SchemaConstructor = lib$1.IntegerSchema;
- if (isCLI) {
- parameters.preprocess = function (value) {
- return Number(value);
- };
- }
- break;
- case "choice":
- SchemaConstructor = lib$1.ChoiceSchema;
- parameters.choices = optionInfo.choices.map(function (choiceInfo) {
- return typeof choiceInfo === "object" && choiceInfo.redirect ? Object.assign({}, choiceInfo, {
- redirect: {
- to: {
- key: optionInfo.name,
- value: choiceInfo.redirect
- }
- }
- }) : choiceInfo;
- });
- break;
- case "boolean":
- SchemaConstructor = lib$1.BooleanSchema;
- break;
- case "flag":
- SchemaConstructor = FlagSchema;
- parameters.flags = optionInfos.map(function (optionInfo) {
- return [].concat(optionInfo.alias || [], optionInfo.description ? optionInfo.name : [], optionInfo.oppositeDescription ? `no-${optionInfo.name}` : []);
- }).reduce(function (a, b) {
- return a.concat(b);
- }, []);
- break;
- case "path":
- SchemaConstructor = lib$1.StringSchema;
- break;
- default:
- throw new Error(`Unexpected type ${optionInfo.type}`);
- }
- if (optionInfo.exception) {
- parameters.validate = function (value, schema, utils) {
- return optionInfo.exception(value) || schema.validate(value, utils);
- };
- } else {
- parameters.validate = function (value, schema, utils) {
- return value === undefined || schema.validate(value, utils);
- };
- }
- if (optionInfo.redirect) {
- handlers.redirect = function (value) {
- return !value ? undefined : {
- to: {
- key: optionInfo.redirect.option,
- value: optionInfo.redirect.value
- }
- };
- };
- }
- if (optionInfo.deprecated) {
- handlers.deprecated = true;
- } // allow CLI overriding, e.g., prettier package.json --tab-width 1 --tab-width 2
- if (isCLI && !optionInfo.array) {
- var originalPreprocess = parameters.preprocess || function (x) {
- return x;
- };
- parameters.preprocess = function (value, schema, utils) {
- return schema.preprocess(originalPreprocess(Array.isArray(value) ? value[value.length - 1] : value), utils);
- };
- }
- return optionInfo.array ? lib$1.ArraySchema.create(Object.assign(isCLI ? {
- preprocess: function preprocess(v) {
- return [].concat(v);
- }
- } : {}, handlers, {
- valueSchema: SchemaConstructor.create(parameters)
- })) : SchemaConstructor.create(Object.assign({}, parameters, handlers));
- }
- function normalizeApiOptions(options, optionInfos, opts) {
- return normalizeOptions$1(options, optionInfos, opts);
- }
- function normalizeCliOptions(options, optionInfos, opts) {
- return normalizeOptions$1(options, optionInfos, Object.assign({
- isCLI: true
- }, opts));
- }
- var optionsNormalizer = {
- normalizeApiOptions,
- normalizeCliOptions
- };
- var getLast = function getLast(arr) {
- return arr.length > 0 ? arr[arr.length - 1] : null;
- };
- function locStart$1(node, opts) {
- opts = opts || {}; // Handle nodes with decorators. They should start at the first decorator
- if (!opts.ignoreDecorators && node.declaration && node.declaration.decorators && node.declaration.decorators.length > 0) {
- return locStart$1(node.declaration.decorators[0]);
- }
- if (!opts.ignoreDecorators && node.decorators && node.decorators.length > 0) {
- return locStart$1(node.decorators[0]);
- }
- if (node.__location) {
- return node.__location.startOffset;
- }
- if (node.range) {
- return node.range[0];
- }
- if (typeof node.start === "number") {
- return node.start;
- }
- if (node.loc) {
- return node.loc.start;
- }
- return null;
- }
- function locEnd$1(node) {
- var endNode = node.nodes && getLast(node.nodes);
- if (endNode && node.source && !node.source.end) {
- node = endNode;
- }
- if (node.__location) {
- return node.__location.endOffset;
- }
- var loc = node.range ? node.range[1] : typeof node.end === "number" ? node.end : null;
- if (node.typeAnnotation) {
- return Math.max(loc, locEnd$1(node.typeAnnotation));
- }
- if (node.loc && !loc) {
- return node.loc.end;
- }
- return loc;
- }
- var loc = {
- locStart: locStart$1,
- locEnd: locEnd$1
- };
- var jsTokens = createCommonjsModule(function (module, exports) {
- // Copyright 2014, 2015, 2016, 2017 Simon Lydell
- // License: MIT. (See LICENSE.)
- Object.defineProperty(exports, "__esModule", {
- value: true
- }); // This regex comes from regex.coffee, and is inserted here by generate-index.js
- // (run `npm run build`).
- exports.default = /((['"])(?:(?!\2|\\).|\\(?:\r\n|[\s\S]))*(\2)?|`(?:[^`\\$]|\\[\s\S]|\$(?!\{)|\$\{(?:[^{}]|\{[^}]*\}?)*\}?)*(`)?)|(\/\/.*)|(\/\*(?:[^*]|\*(?!\/))*(\*\/)?)|(\/(?!\*)(?:\[(?:(?![\]\\]).|\\.)*\]|(?![\/\]\\]).|\\.)+\/(?:(?!\s*(?:\b|[\u0080-\uFFFF$\\'"~({]|[+\-!](?!=)|\.?\d))|[gmiyu]{1,5}\b(?![\u0080-\uFFFF$\\]|\s*(?:[+\-*%&|^<>!=?({]|\/(?![\/*])))))|(0[xX][\da-fA-F]+|0[oO][0-7]+|0[bB][01]+|(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?)|((?!\d)(?:(?!\s)[$\w\u0080-\uFFFF]|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+)|(--|\+\+|&&|\|\||=>|\.{3}|(?:[+\-\/%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2})=?|[?~.,:;[\](){}])|(\s+)|(^$|[\s\S])/g;
- exports.matchToToken = function (match) {
- var token = {
- type: "invalid",
- value: match[0]
- };
- if (match[1]) token.type = "string", token.closed = !!(match[3] || match[4]);else if (match[5]) token.type = "comment";else if (match[6]) token.type = "comment", token.closed = !!match[7];else if (match[8]) token.type = "regex";else if (match[9]) token.type = "number";else if (match[10]) token.type = "name";else if (match[11]) token.type = "punctuator";else if (match[12]) token.type = "whitespace";
- return token;
- };
- });
- unwrapExports(jsTokens);
- var ast = createCommonjsModule(function (module) {
- /*
- Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are met:
-
- * Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
- * Redistributions in binary form must reproduce the above copyright
- notice, this list of conditions and the following disclaimer in the
- documentation and/or other materials provided with the distribution.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS'
- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
- DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
- (function () {
- 'use strict';
- function isExpression(node) {
- if (node == null) {
- return false;
- }
- switch (node.type) {
- case 'ArrayExpression':
- case 'AssignmentExpression':
- case 'BinaryExpression':
- case 'CallExpression':
- case 'ConditionalExpression':
- case 'FunctionExpression':
- case 'Identifier':
- case 'Literal':
- case 'LogicalExpression':
- case 'MemberExpression':
- case 'NewExpression':
- case 'ObjectExpression':
- case 'SequenceExpression':
- case 'ThisExpression':
- case 'UnaryExpression':
- case 'UpdateExpression':
- return true;
- }
- return false;
- }
- function isIterationStatement(node) {
- if (node == null) {
- return false;
- }
- switch (node.type) {
- case 'DoWhileStatement':
- case 'ForInStatement':
- case 'ForStatement':
- case 'WhileStatement':
- return true;
- }
- return false;
- }
- function isStatement(node) {
- if (node == null) {
- return false;
- }
- switch (node.type) {
- case 'BlockStatement':
- case 'BreakStatement':
- case 'ContinueStatement':
- case 'DebuggerStatement':
- case 'DoWhileStatement':
- case 'EmptyStatement':
- case 'ExpressionStatement':
- case 'ForInStatement':
- case 'ForStatement':
- case 'IfStatement':
- case 'LabeledStatement':
- case 'ReturnStatement':
- case 'SwitchStatement':
- case 'ThrowStatement':
- case 'TryStatement':
- case 'VariableDeclaration':
- case 'WhileStatement':
- case 'WithStatement':
- return true;
- }
- return false;
- }
- function isSourceElement(node) {
- return isStatement(node) || node != null && node.type === 'FunctionDeclaration';
- }
- function trailingStatement(node) {
- switch (node.type) {
- case 'IfStatement':
- if (node.alternate != null) {
- return node.alternate;
- }
- return node.consequent;
- case 'LabeledStatement':
- case 'ForStatement':
- case 'ForInStatement':
- case 'WhileStatement':
- case 'WithStatement':
- return node.body;
- }
- return null;
- }
- function isProblematicIfStatement(node) {
- var current;
- if (node.type !== 'IfStatement') {
- return false;
- }
- if (node.alternate == null) {
- return false;
- }
- current = node.consequent;
- do {
- if (current.type === 'IfStatement') {
- if (current.alternate == null) {
- return true;
- }
- }
- current = trailingStatement(current);
- } while (current);
- return false;
- }
- module.exports = {
- isExpression: isExpression,
- isStatement: isStatement,
- isIterationStatement: isIterationStatement,
- isSourceElement: isSourceElement,
- isProblematicIfStatement: isProblematicIfStatement,
- trailingStatement: trailingStatement
- };
- })();
- /* vim: set sw=4 ts=4 et tw=80 : */
- });
- var code = createCommonjsModule(function (module) {
- /*
- Copyright (C) 2013-2014 Yusuke Suzuki <utatane.tea@gmail.com>
- Copyright (C) 2014 Ivan Nikulin <ifaaan@gmail.com>
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are met:
-
- * Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
- * Redistributions in binary form must reproduce the above copyright
- notice, this list of conditions and the following disclaimer in the
- documentation and/or other materials provided with the distribution.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
- DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
- (function () {
- 'use strict';
- var ES6Regex, ES5Regex, NON_ASCII_WHITESPACES, IDENTIFIER_START, IDENTIFIER_PART, ch; // See `tools/generate-identifier-regex.js`.
- ES5Regex = {
- // ECMAScript 5.1/Unicode v7.0.0 NonAsciiIdentifierStart:
- NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B2\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/,
- // ECMAScript 5.1/Unicode v7.0.0 NonAsciiIdentifierPart:
- NonAsciiIdentifierPart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B2\u08E4-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2D\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/
- };
- ES6Regex = {
- // ECMAScript 6/Unicode v7.0.0 NonAsciiIdentifierStart:
- NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B2\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDE00-\uDE11\uDE13-\uDE2B\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDE00-\uDE2F\uDE44\uDE80-\uDEAA]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF98]|\uD809[\uDC00-\uDC6E]|[\uD80C\uD840-\uD868\uD86A-\uD86C][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D]|\uD87E[\uDC00-\uDE1D]/,
- // ECMAScript 6/Unicode v7.0.0 NonAsciiIdentifierPart:
- NonAsciiIdentifierPart: /[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B2\u08E4-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2D\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDD0-\uDDDA\uDE00-\uDE11\uDE13-\uDE37\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF01-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF98]|\uD809[\uDC00-\uDC6E]|[\uD80C\uD840-\uD868\uD86A-\uD86C][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/
- };
- function isDecimalDigit(ch) {
- return 0x30 <= ch && ch <= 0x39; // 0..9
- }
- function isHexDigit(ch) {
- return 0x30 <= ch && ch <= 0x39 || // 0..9
- 0x61 <= ch && ch <= 0x66 || // a..f
- 0x41 <= ch && ch <= 0x46; // A..F
- }
- function isOctalDigit(ch) {
- return ch >= 0x30 && ch <= 0x37; // 0..7
- } // 7.2 White Space
- NON_ASCII_WHITESPACES = [0x1680, 0x180E, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF];
- function isWhiteSpace(ch) {
- return ch === 0x20 || ch === 0x09 || ch === 0x0B || ch === 0x0C || ch === 0xA0 || ch >= 0x1680 && NON_ASCII_WHITESPACES.indexOf(ch) >= 0;
- } // 7.3 Line Terminators
- function isLineTerminator(ch) {
- return ch === 0x0A || ch === 0x0D || ch === 0x2028 || ch === 0x2029;
- } // 7.6 Identifier Names and Identifiers
- function fromCodePoint(cp) {
- if (cp <= 0xFFFF) {
- return String.fromCharCode(cp);
- }
- var cu1 = String.fromCharCode(Math.floor((cp - 0x10000) / 0x400) + 0xD800);
- var cu2 = String.fromCharCode((cp - 0x10000) % 0x400 + 0xDC00);
- return cu1 + cu2;
- }
- IDENTIFIER_START = new Array(0x80);
- for (ch = 0; ch < 0x80; ++ch) {
- IDENTIFIER_START[ch] = ch >= 0x61 && ch <= 0x7A || // a..z
- ch >= 0x41 && ch <= 0x5A || // A..Z
- ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore)
- }
- IDENTIFIER_PART = new Array(0x80);
- for (ch = 0; ch < 0x80; ++ch) {
- IDENTIFIER_PART[ch] = ch >= 0x61 && ch <= 0x7A || // a..z
- ch >= 0x41 && ch <= 0x5A || // A..Z
- ch >= 0x30 && ch <= 0x39 || // 0..9
- ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore)
- }
- function isIdentifierStartES5(ch) {
- return ch < 0x80 ? IDENTIFIER_START[ch] : ES5Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch));
- }
- function isIdentifierPartES5(ch) {
- return ch < 0x80 ? IDENTIFIER_PART[ch] : ES5Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch));
- }
- function isIdentifierStartES6(ch) {
- return ch < 0x80 ? IDENTIFIER_START[ch] : ES6Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch));
- }
- function isIdentifierPartES6(ch) {
- return ch < 0x80 ? IDENTIFIER_PART[ch] : ES6Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch));
- }
- module.exports = {
- isDecimalDigit: isDecimalDigit,
- isHexDigit: isHexDigit,
- isOctalDigit: isOctalDigit,
- isWhiteSpace: isWhiteSpace,
- isLineTerminator: isLineTerminator,
- isIdentifierStartES5: isIdentifierStartES5,
- isIdentifierPartES5: isIdentifierPartES5,
- isIdentifierStartES6: isIdentifierStartES6,
- isIdentifierPartES6: isIdentifierPartES6
- };
- })();
- /* vim: set sw=4 ts=4 et tw=80 : */
- });
- var keyword = createCommonjsModule(function (module) {
- /*
- Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are met:
-
- * Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
- * Redistributions in binary form must reproduce the above copyright
- notice, this list of conditions and the following disclaimer in the
- documentation and/or other materials provided with the distribution.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
- DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
- (function () {
- 'use strict';
- var code$$1 = code;
- function isStrictModeReservedWordES6(id) {
- switch (id) {
- case 'implements':
- case 'interface':
- case 'package':
- case 'private':
- case 'protected':
- case 'public':
- case 'static':
- case 'let':
- return true;
- default:
- return false;
- }
- }
- function isKeywordES5(id, strict) {
- // yield should not be treated as keyword under non-strict mode.
- if (!strict && id === 'yield') {
- return false;
- }
- return isKeywordES6(id, strict);
- }
- function isKeywordES6(id, strict) {
- if (strict && isStrictModeReservedWordES6(id)) {
- return true;
- }
- switch (id.length) {
- case 2:
- return id === 'if' || id === 'in' || id === 'do';
- case 3:
- return id === 'var' || id === 'for' || id === 'new' || id === 'try';
- case 4:
- return id === 'this' || id === 'else' || id === 'case' || id === 'void' || id === 'with' || id === 'enum';
- case 5:
- return id === 'while' || id === 'break' || id === 'catch' || id === 'throw' || id === 'const' || id === 'yield' || id === 'class' || id === 'super';
- case 6:
- return id === 'return' || id === 'typeof' || id === 'delete' || id === 'switch' || id === 'export' || id === 'import';
- case 7:
- return id === 'default' || id === 'finally' || id === 'extends';
- case 8:
- return id === 'function' || id === 'continue' || id === 'debugger';
- case 10:
- return id === 'instanceof';
- default:
- return false;
- }
- }
- function isReservedWordES5(id, strict) {
- return id === 'null' || id === 'true' || id === 'false' || isKeywordES5(id, strict);
- }
- function isReservedWordES6(id, strict) {
- return id === 'null' || id === 'true' || id === 'false' || isKeywordES6(id, strict);
- }
- function isRestrictedWord(id) {
- return id === 'eval' || id === 'arguments';
- }
- function isIdentifierNameES5(id) {
- var i, iz, ch;
- if (id.length === 0) {
- return false;
- }
- ch = id.charCodeAt(0);
- if (!code$$1.isIdentifierStartES5(ch)) {
- return false;
- }
- for (i = 1, iz = id.length; i < iz; ++i) {
- ch = id.charCodeAt(i);
- if (!code$$1.isIdentifierPartES5(ch)) {
- return false;
- }
- }
- return true;
- }
- function decodeUtf16(lead, trail) {
- return (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
- }
- function isIdentifierNameES6(id) {
- var i, iz, ch, lowCh, check;
- if (id.length === 0) {
- return false;
- }
- check = code$$1.isIdentifierStartES6;
- for (i = 0, iz = id.length; i < iz; ++i) {
- ch = id.charCodeAt(i);
- if (0xD800 <= ch && ch <= 0xDBFF) {
- ++i;
- if (i >= iz) {
- return false;
- }
- lowCh = id.charCodeAt(i);
- if (!(0xDC00 <= lowCh && lowCh <= 0xDFFF)) {
- return false;
- }
- ch = decodeUtf16(ch, lowCh);
- }
- if (!check(ch)) {
- return false;
- }
- check = code$$1.isIdentifierPartES6;
- }
- return true;
- }
- function isIdentifierES5(id, strict) {
- return isIdentifierNameES5(id) && !isReservedWordES5(id, strict);
- }
- function isIdentifierES6(id, strict) {
- return isIdentifierNameES6(id) && !isReservedWordES6(id, strict);
- }
- module.exports = {
- isKeywordES5: isKeywordES5,
- isKeywordES6: isKeywordES6,
- isReservedWordES5: isReservedWordES5,
- isReservedWordES6: isReservedWordES6,
- isRestrictedWord: isRestrictedWord,
- isIdentifierNameES5: isIdentifierNameES5,
- isIdentifierNameES6: isIdentifierNameES6,
- isIdentifierES5: isIdentifierES5,
- isIdentifierES6: isIdentifierES6
- };
- })();
- /* vim: set sw=4 ts=4 et tw=80 : */
- });
- var utils$2 = createCommonjsModule(function (module, exports) {
- /*
- Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are met:
-
- * Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
- * Redistributions in binary form must reproduce the above copyright
- notice, this list of conditions and the following disclaimer in the
- documentation and/or other materials provided with the distribution.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
- DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
- (function () {
- 'use strict';
- exports.ast = ast;
- exports.code = code;
- exports.keyword = keyword;
- })();
- /* vim: set sw=4 ts=4 et tw=80 : */
- });
- var hasFlag$6 = createCommonjsModule(function (module) {
- 'use strict';
- module.exports = function (flag, argv) {
- argv = argv || process.argv;
- var prefix = flag.startsWith('-') ? '' : flag.length === 1 ? '-' : '--';
- var pos = argv.indexOf(prefix + flag);
- var terminatorPos = argv.indexOf('--');
- return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos);
- };
- });
- var env$1 = process.env;
- var forceColor$1;
- if (hasFlag$6('no-color') || hasFlag$6('no-colors') || hasFlag$6('color=false')) {
- forceColor$1 = false;
- } else if (hasFlag$6('color') || hasFlag$6('colors') || hasFlag$6('color=true') || hasFlag$6('color=always')) {
- forceColor$1 = true;
- }
- if ('FORCE_COLOR' in env$1) {
- forceColor$1 = env$1.FORCE_COLOR.length === 0 || parseInt(env$1.FORCE_COLOR, 10) !== 0;
- }
- function translateLevel$1(level) {
- if (level === 0) {
- return false;
- }
- return {
- level,
- hasBasic: true,
- has256: level >= 2,
- has16m: level >= 3
- };
- }
- function supportsColor$4(stream) {
- if (forceColor$1 === false) {
- return 0;
- }
- if (hasFlag$6('color=16m') || hasFlag$6('color=full') || hasFlag$6('color=truecolor')) {
- return 3;
- }
- if (hasFlag$6('color=256')) {
- return 2;
- }
- if (stream && !stream.isTTY && forceColor$1 !== true) {
- return 0;
- }
- var min = forceColor$1 ? 1 : 0;
- if (process.platform === 'win32') {
- // Node.js 7.5.0 is the first version of Node.js to include a patch to
- // libuv that enables 256 color output on Windows. Anything earlier and it
- // won't work. However, here we target Node.js 8 at minimum as it is an LTS
- // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows
- // release that supports 256 colors. Windows 10 build 14931 is the first release
- // that supports 16m/TrueColor.
- var osRelease = os.release().split('.');
- if (Number(process.versions.node.split('.')[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
- return Number(osRelease[2]) >= 14931 ? 3 : 2;
- }
- return 1;
- }
- if ('CI' in env$1) {
- if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(function (sign) {
- return sign in env$1;
- }) || env$1.CI_NAME === 'codeship') {
- return 1;
- }
- return min;
- }
- if ('TEAMCITY_VERSION' in env$1) {
- return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$1.TEAMCITY_VERSION) ? 1 : 0;
- }
- if (env$1.COLORTERM === 'truecolor') {
- return 3;
- }
- if ('TERM_PROGRAM' in env$1) {
- var version = parseInt((env$1.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
- switch (env$1.TERM_PROGRAM) {
- case 'iTerm.app':
- return version >= 3 ? 3 : 2;
- case 'Apple_Terminal':
- return 2;
- // No default
- }
- }
- if (/-256(color)?$/i.test(env$1.TERM)) {
- return 2;
- }
- if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$1.TERM)) {
- return 1;
- }
- if ('COLORTERM' in env$1) {
- return 1;
- }
- if (env$1.TERM === 'dumb') {
- return min;
- }
- return min;
- }
- function getSupportLevel$1(stream) {
- var level = supportsColor$4(stream);
- return translateLevel$1(level);
- }
- var supportsColor_1$3 = {
- supportsColor: getSupportLevel$1,
- stdout: getSupportLevel$1(process.stdout),
- stderr: getSupportLevel$1(process.stderr)
- };
- var templates$4 = createCommonjsModule(function (module) {
- 'use strict';
- var TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
- var STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
- var STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
- var ESCAPE_REGEX = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi;
- var ESCAPES = new Map([['n', '\n'], ['r', '\r'], ['t', '\t'], ['b', '\b'], ['f', '\f'], ['v', '\v'], ['0', '\0'], ['\\', '\\'], ['e', '\u001B'], ['a', '\u0007']]);
- function unescape(c) {
- if (c[0] === 'u' && c.length === 5 || c[0] === 'x' && c.length === 3) {
- return String.fromCharCode(parseInt(c.slice(1), 16));
- }
- return ESCAPES.get(c) || c;
- }
- function parseArguments(name, args) {
- var results = [];
- var chunks = args.trim().split(/\s*,\s*/g);
- var matches;
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = chunks[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var chunk = _step.value;
- if (!isNaN(chunk)) {
- results.push(Number(chunk));
- } else if (matches = chunk.match(STRING_REGEX)) {
- results.push(matches[2].replace(ESCAPE_REGEX, function (m, escape, chr) {
- return escape ? unescape(escape) : chr;
- }));
- } else {
- throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
- }
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- return results;
- }
- function parseStyle(style) {
- STYLE_REGEX.lastIndex = 0;
- var results = [];
- var matches;
- while ((matches = STYLE_REGEX.exec(style)) !== null) {
- var name = matches[1];
- if (matches[2]) {
- var args = parseArguments(name, matches[2]);
- results.push([name].concat(args));
- } else {
- results.push([name]);
- }
- }
- return results;
- }
- function buildStyle(chalk, styles) {
- var enabled = {};
- var _iteratorNormalCompletion2 = true;
- var _didIteratorError2 = false;
- var _iteratorError2 = undefined;
- try {
- for (var _iterator2 = styles[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
- var layer = _step2.value;
- var _iteratorNormalCompletion3 = true;
- var _didIteratorError3 = false;
- var _iteratorError3 = undefined;
- try {
- for (var _iterator3 = layer.styles[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
- var style = _step3.value;
- enabled[style[0]] = layer.inverse ? null : style.slice(1);
- }
- } catch (err) {
- _didIteratorError3 = true;
- _iteratorError3 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
- _iterator3.return();
- }
- } finally {
- if (_didIteratorError3) {
- throw _iteratorError3;
- }
- }
- }
- }
- } catch (err) {
- _didIteratorError2 = true;
- _iteratorError2 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
- _iterator2.return();
- }
- } finally {
- if (_didIteratorError2) {
- throw _iteratorError2;
- }
- }
- }
- var current = chalk;
- var _arr = Object.keys(enabled);
- for (var _i = 0; _i < _arr.length; _i++) {
- var styleName = _arr[_i];
- if (Array.isArray(enabled[styleName])) {
- if (!(styleName in current)) {
- throw new Error(`Unknown Chalk style: ${styleName}`);
- }
- if (enabled[styleName].length > 0) {
- current = current[styleName].apply(current, enabled[styleName]);
- } else {
- current = current[styleName];
- }
- }
- }
- return current;
- }
- module.exports = function (chalk, tmp) {
- var styles = [];
- var chunks = [];
- var chunk = []; // eslint-disable-next-line max-params
- tmp.replace(TEMPLATE_REGEX, function (m, escapeChar, inverse, style, close, chr) {
- if (escapeChar) {
- chunk.push(unescape(escapeChar));
- } else if (style) {
- var str = chunk.join('');
- chunk = [];
- chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str));
- styles.push({
- inverse,
- styles: parseStyle(style)
- });
- } else if (close) {
- if (styles.length === 0) {
- throw new Error('Found extraneous } in Chalk template literal');
- }
- chunks.push(buildStyle(chalk, styles)(chunk.join('')));
- chunk = [];
- styles.pop();
- } else {
- chunk.push(chr);
- }
- });
- chunks.push(chunk.join(''));
- if (styles.length > 0) {
- var errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
- throw new Error(errMsg);
- }
- return chunks.join('');
- };
- });
- var chalk$5 = createCommonjsModule(function (module) {
- 'use strict';
- var stdoutColor = supportsColor_1$3.stdout;
- var isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); // `supportsColor.level` → `ansiStyles.color[name]` mapping
- var levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; // `color-convert` models to exclude from the Chalk API due to conflicts and such
- var skipModels = new Set(['gray']);
- var styles = Object.create(null);
- function applyOptions(obj, options) {
- options = options || {}; // Detect level if not set manually
- var scLevel = stdoutColor ? stdoutColor.level : 0;
- obj.level = options.level === undefined ? scLevel : options.level;
- obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0;
- }
- function Chalk(options) {
- // We check for this.template here since calling `chalk.constructor()`
- // by itself will have a `this` of a previously constructed chalk object
- if (!this || !(this instanceof Chalk) || this.template) {
- var _chalk = {};
- applyOptions(_chalk, options);
- _chalk.template = function () {
- var args = [].slice.call(arguments);
- return chalkTag.apply(null, [_chalk.template].concat(args));
- };
- Object.setPrototypeOf(_chalk, Chalk.prototype);
- Object.setPrototypeOf(_chalk.template, _chalk);
- _chalk.template.constructor = Chalk;
- return _chalk.template;
- }
- applyOptions(this, options);
- } // Use bright blue on Windows as the normal blue color is illegible
- if (isSimpleWindowsTerm) {
- ansiStyles.blue.open = '\u001B[94m';
- }
- var _arr = Object.keys(ansiStyles);
- var _loop = function _loop() {
- var key = _arr[_i];
- ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g');
- styles[key] = {
- get() {
- var codes = ansiStyles[key];
- return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key);
- }
- };
- };
- for (var _i = 0; _i < _arr.length; _i++) {
- _loop();
- }
- styles.visible = {
- get() {
- return build.call(this, this._styles || [], true, 'visible');
- }
- };
- ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g');
- var _arr2 = Object.keys(ansiStyles.color.ansi);
- var _loop2 = function _loop2() {
- var model = _arr2[_i2];
- if (skipModels.has(model)) {
- return "continue";
- }
- styles[model] = {
- get() {
- var level = this.level;
- return function () {
- var open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments);
- var codes = {
- open,
- close: ansiStyles.color.close,
- closeRe: ansiStyles.color.closeRe
- };
- return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
- };
- }
- };
- };
- for (var _i2 = 0; _i2 < _arr2.length; _i2++) {
- var _ret = _loop2();
- if (_ret === "continue") continue;
- }
- ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g');
- var _arr3 = Object.keys(ansiStyles.bgColor.ansi);
- var _loop3 = function _loop3() {
- var model = _arr3[_i3];
- if (skipModels.has(model)) {
- return "continue";
- }
- var bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
- styles[bgModel] = {
- get() {
- var level = this.level;
- return function () {
- var open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments);
- var codes = {
- open,
- close: ansiStyles.bgColor.close,
- closeRe: ansiStyles.bgColor.closeRe
- };
- return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
- };
- }
- };
- };
- for (var _i3 = 0; _i3 < _arr3.length; _i3++) {
- var _ret2 = _loop3();
- if (_ret2 === "continue") continue;
- }
- var proto = Object.defineProperties(function () {}, styles);
- function build(_styles, _empty, key) {
- var builder = function builder() {
- return applyStyle.apply(builder, arguments);
- };
- builder._styles = _styles;
- builder._empty = _empty;
- var self = this;
- Object.defineProperty(builder, 'level', {
- enumerable: true,
- get() {
- return self.level;
- },
- set(level) {
- self.level = level;
- }
- });
- Object.defineProperty(builder, 'enabled', {
- enumerable: true,
- get() {
- return self.enabled;
- },
- set(enabled) {
- self.enabled = enabled;
- }
- }); // See below for fix regarding invisible grey/dim combination on Windows
- builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; // `__proto__` is used because we must return a function, but there is
- // no way to create a function with a different prototype
- builder.__proto__ = proto; // eslint-disable-line no-proto
- return builder;
- }
- function applyStyle() {
- // Support varags, but simply cast to string in case there's only one arg
- var args = arguments;
- var argsLen = args.length;
- var str = String(arguments[0]);
- if (argsLen === 0) {
- return '';
- }
- if (argsLen > 1) {
- // Don't slice `arguments`, it prevents V8 optimizations
- for (var a = 1; a < argsLen; a++) {
- str += ' ' + args[a];
- }
- }
- if (!this.enabled || this.level <= 0 || !str) {
- return this._empty ? '' : str;
- } // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe,
- // see https://github.com/chalk/chalk/issues/58
- // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop.
- var originalDim = ansiStyles.dim.open;
- if (isSimpleWindowsTerm && this.hasGrey) {
- ansiStyles.dim.open = '';
- }
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = this._styles.slice().reverse()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var code = _step.value;
- // Replace any instances already present with a re-opening code
- // otherwise only the part of the string until said closing code
- // will be colored, and the rest will simply be 'plain'.
- str = code.open + str.replace(code.closeRe, code.open) + code.close; // Close the styling before a linebreak and reopen
- // after next line to fix a bleed issue on macOS
- // https://github.com/chalk/chalk/pull/92
- str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`);
- } // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- ansiStyles.dim.open = originalDim;
- return str;
- }
- function chalkTag(chalk, strings) {
- if (!Array.isArray(strings)) {
- // If chalk() was called by itself or with a string,
- // return the string itself as a string.
- return [].slice.call(arguments, 1).join(' ');
- }
- var args = [].slice.call(arguments, 2);
- var parts = [strings.raw[0]];
- for (var i = 1; i < strings.length; i++) {
- parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&'));
- parts.push(String(strings.raw[i]));
- }
- return templates$4(chalk, parts.join(''));
- }
- Object.defineProperties(Chalk.prototype, styles);
- module.exports = Chalk(); // eslint-disable-line new-cap
- module.exports.supportsColor = stdoutColor;
- module.exports.default = module.exports; // For TypeScript
- });
- var lib$3 = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.shouldHighlight = shouldHighlight;
- exports.getChalk = getChalk;
- exports.default = highlight;
- function _jsTokens() {
- var data = _interopRequireWildcard(jsTokens);
- _jsTokens = function _jsTokens() {
- return data;
- };
- return data;
- }
- function _esutils() {
- var data = _interopRequireDefault(utils$2);
- _esutils = function _esutils() {
- return data;
- };
- return data;
- }
- function _chalk() {
- var data = _interopRequireDefault(chalk$5);
- _chalk = function _chalk() {
- return data;
- };
- return data;
- }
- function _interopRequireDefault(obj) {
- return obj && obj.__esModule ? obj : {
- default: obj
- };
- }
- function _interopRequireWildcard(obj) {
- if (obj && obj.__esModule) {
- return obj;
- } else {
- var newObj = {};
- if (obj != null) {
- for (var key in obj) {
- if (Object.prototype.hasOwnProperty.call(obj, key)) {
- var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {};
- if (desc.get || desc.set) {
- Object.defineProperty(newObj, key, desc);
- } else {
- newObj[key] = obj[key];
- }
- }
- }
- }
- newObj.default = obj;
- return newObj;
- }
- }
- function getDefs(chalk) {
- return {
- keyword: chalk.cyan,
- capitalized: chalk.yellow,
- jsx_tag: chalk.yellow,
- punctuator: chalk.yellow,
- number: chalk.magenta,
- string: chalk.green,
- regex: chalk.magenta,
- comment: chalk.grey,
- invalid: chalk.white.bgRed.bold
- };
- }
- var NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
- var JSX_TAG = /^[a-z][\w-]*$/i;
- var BRACKET = /^[()[\]{}]$/;
- function getTokenType(match) {
- var _match$slice = match.slice(-2),
- offset = _match$slice[0],
- text = _match$slice[1];
- var token = (0, _jsTokens().matchToToken)(match);
- if (token.type === "name") {
- if (_esutils().default.keyword.isReservedWordES6(token.value)) {
- return "keyword";
- }
- if (JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.substr(offset - 2, 2) == "</")) {
- return "jsx_tag";
- }
- if (token.value[0] !== token.value[0].toLowerCase()) {
- return "capitalized";
- }
- }
- if (token.type === "punctuator" && BRACKET.test(token.value)) {
- return "bracket";
- }
- if (token.type === "invalid" && (token.value === "@" || token.value === "#")) {
- return "punctuator";
- }
- return token.type;
- }
- function highlightTokens(defs, text) {
- return text.replace(_jsTokens().default, function () {
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
- var type = getTokenType(args);
- var colorize = defs[type];
- if (colorize) {
- return args[0].split(NEWLINE).map(function (str) {
- return colorize(str);
- }).join("\n");
- } else {
- return args[0];
- }
- });
- }
- function shouldHighlight(options) {
- return _chalk().default.supportsColor || options.forceColor;
- }
- function getChalk(options) {
- var chalk = _chalk().default;
- if (options.forceColor) {
- chalk = new (_chalk().default.constructor)({
- enabled: true,
- level: 1
- });
- }
- return chalk;
- }
- function highlight(code, options) {
- if (options === void 0) {
- options = {};
- }
- if (shouldHighlight(options)) {
- var chalk = getChalk(options);
- var defs = getDefs(chalk);
- return highlightTokens(defs, code);
- } else {
- return code;
- }
- }
- });
- unwrapExports(lib$3);
- var lib$2 = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.codeFrameColumns = codeFrameColumns;
- exports.default = _default;
- function _highlight() {
- var data = _interopRequireWildcard(lib$3);
- _highlight = function _highlight() {
- return data;
- };
- return data;
- }
- function _interopRequireWildcard(obj) {
- if (obj && obj.__esModule) {
- return obj;
- } else {
- var newObj = {};
- if (obj != null) {
- for (var key in obj) {
- if (Object.prototype.hasOwnProperty.call(obj, key)) {
- var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {};
- if (desc.get || desc.set) {
- Object.defineProperty(newObj, key, desc);
- } else {
- newObj[key] = obj[key];
- }
- }
- }
- }
- newObj.default = obj;
- return newObj;
- }
- }
- var deprecationWarningShown = false;
- function getDefs(chalk) {
- return {
- gutter: chalk.grey,
- marker: chalk.red.bold,
- message: chalk.red.bold
- };
- }
- var NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
- function getMarkerLines(loc, source, opts) {
- var startLoc = Object.assign({}, {
- column: 0,
- line: -1
- }, loc.start);
- var endLoc = Object.assign({}, startLoc, loc.end);
- var _ref = opts || {},
- _ref$linesAbove = _ref.linesAbove,
- linesAbove = _ref$linesAbove === void 0 ? 2 : _ref$linesAbove,
- _ref$linesBelow = _ref.linesBelow,
- linesBelow = _ref$linesBelow === void 0 ? 3 : _ref$linesBelow;
- var startLine = startLoc.line;
- var startColumn = startLoc.column;
- var endLine = endLoc.line;
- var endColumn = endLoc.column;
- var start = Math.max(startLine - (linesAbove + 1), 0);
- var end = Math.min(source.length, endLine + linesBelow);
- if (startLine === -1) {
- start = 0;
- }
- if (endLine === -1) {
- end = source.length;
- }
- var lineDiff = endLine - startLine;
- var markerLines = {};
- if (lineDiff) {
- for (var i = 0; i <= lineDiff; i++) {
- var lineNumber = i + startLine;
- if (!startColumn) {
- markerLines[lineNumber] = true;
- } else if (i === 0) {
- var sourceLength = source[lineNumber - 1].length;
- markerLines[lineNumber] = [startColumn, sourceLength - startColumn];
- } else if (i === lineDiff) {
- markerLines[lineNumber] = [0, endColumn];
- } else {
- var _sourceLength = source[lineNumber - i].length;
- markerLines[lineNumber] = [0, _sourceLength];
- }
- }
- } else {
- if (startColumn === endColumn) {
- if (startColumn) {
- markerLines[startLine] = [startColumn, 0];
- } else {
- markerLines[startLine] = true;
- }
- } else {
- markerLines[startLine] = [startColumn, endColumn - startColumn];
- }
- }
- return {
- start: start,
- end: end,
- markerLines: markerLines
- };
- }
- function codeFrameColumns(rawLines, loc, opts) {
- if (opts === void 0) {
- opts = {};
- }
- var highlighted = (opts.highlightCode || opts.forceColor) && (0, _highlight().shouldHighlight)(opts);
- var chalk = (0, _highlight().getChalk)(opts);
- var defs = getDefs(chalk);
- var maybeHighlight = function maybeHighlight(chalkFn, string) {
- return highlighted ? chalkFn(string) : string;
- };
- if (highlighted) rawLines = (0, _highlight().default)(rawLines, opts);
- var lines = rawLines.split(NEWLINE);
- var _getMarkerLines = getMarkerLines(loc, lines, opts),
- start = _getMarkerLines.start,
- end = _getMarkerLines.end,
- markerLines = _getMarkerLines.markerLines;
- var hasColumns = loc.start && typeof loc.start.column === "number";
- var numberMaxWidth = String(end).length;
- var frame = lines.slice(start, end).map(function (line, index) {
- var number = start + 1 + index;
- var paddedNumber = (" " + number).slice(-numberMaxWidth);
- var gutter = " " + paddedNumber + " | ";
- var hasMarker = markerLines[number];
- var lastMarkerLine = !markerLines[number + 1];
- if (hasMarker) {
- var markerLine = "";
- if (Array.isArray(hasMarker)) {
- var markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " ");
- var numberOfMarkers = hasMarker[1] || 1;
- markerLine = ["\n ", maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")), markerSpacing, maybeHighlight(defs.marker, "^").repeat(numberOfMarkers)].join("");
- if (lastMarkerLine && opts.message) {
- markerLine += " " + maybeHighlight(defs.message, opts.message);
- }
- }
- return [maybeHighlight(defs.marker, ">"), maybeHighlight(defs.gutter, gutter), line, markerLine].join("");
- } else {
- return " " + maybeHighlight(defs.gutter, gutter) + line;
- }
- }).join("\n");
- if (opts.message && !hasColumns) {
- frame = "" + " ".repeat(numberMaxWidth + 1) + opts.message + "\n" + frame;
- }
- if (highlighted) {
- return chalk.reset(frame);
- } else {
- return frame;
- }
- }
- function _default(rawLines, lineNumber, colNumber, opts) {
- if (opts === void 0) {
- opts = {};
- }
- if (!deprecationWarningShown) {
- deprecationWarningShown = true;
- var message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`.";
- if (process.emitWarning) {
- process.emitWarning(message, "DeprecationWarning");
- } else {
- var deprecationError = new Error(message);
- deprecationError.name = "DeprecationWarning";
- console.warn(new Error(message));
- }
- }
- colNumber = Math.max(colNumber, 0);
- var location = {
- start: {
- column: colNumber,
- line: lineNumber
- }
- };
- return codeFrameColumns(rawLines, location, opts);
- }
- });
- unwrapExports(lib$2);
- var ConfigError$1 = errors.ConfigError;
- var locStart = loc.locStart;
- var locEnd = loc.locEnd; // Use defineProperties()/getOwnPropertyDescriptor() to prevent
- // triggering the parsers getters.
- var ownNames = Object.getOwnPropertyNames;
- var ownDescriptor = Object.getOwnPropertyDescriptor;
- function getParsers(options) {
- var parsers = {};
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = options.plugins[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var plugin = _step.value;
- if (!plugin.parsers) {
- continue;
- }
- var _iteratorNormalCompletion2 = true;
- var _didIteratorError2 = false;
- var _iteratorError2 = undefined;
- try {
- for (var _iterator2 = ownNames(plugin.parsers)[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
- var name = _step2.value;
- Object.defineProperty(parsers, name, ownDescriptor(plugin.parsers, name));
- }
- } catch (err) {
- _didIteratorError2 = true;
- _iteratorError2 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
- _iterator2.return();
- }
- } finally {
- if (_didIteratorError2) {
- throw _iteratorError2;
- }
- }
- }
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- return parsers;
- }
- function resolveParser$1(opts, parsers) {
- parsers = parsers || getParsers(opts);
- if (typeof opts.parser === "function") {
- // Custom parser API always works with JavaScript.
- return {
- parse: opts.parser,
- astFormat: "estree",
- locStart,
- locEnd
- };
- }
- if (typeof opts.parser === "string") {
- if (parsers.hasOwnProperty(opts.parser)) {
- return parsers[opts.parser];
- }
- /* istanbul ignore next */
- {
- try {
- return {
- parse: require(path.resolve(process.cwd(), opts.parser)),
- astFormat: "estree",
- locStart,
- locEnd
- };
- } catch (err) {
- /* istanbul ignore next */
- throw new ConfigError$1(`Couldn't resolve parser "${opts.parser}"`);
- }
- }
- }
- }
- function parse$2(text, opts) {
- var parsers = getParsers(opts); // Create a new object {parserName: parseFn}. Uses defineProperty() to only call
- // the parsers getters when actually calling the parser `parse` function.
- var parsersForCustomParserApi = Object.keys(parsers).reduce(function (object, parserName) {
- return Object.defineProperty(object, parserName, {
- enumerable: true,
- get() {
- return parsers[parserName].parse;
- }
- });
- }, {});
- var parser = resolveParser$1(opts, parsers);
- try {
- if (parser.preprocess) {
- text = parser.preprocess(text, opts);
- }
- return {
- text,
- ast: parser.parse(text, parsersForCustomParserApi, opts)
- };
- } catch (error) {
- var loc$$1 = error.loc;
- if (loc$$1) {
- var codeFrame = lib$2;
- error.codeFrame = codeFrame.codeFrameColumns(text, loc$$1, {
- highlightCode: true
- });
- error.message += "\n" + error.codeFrame;
- throw error;
- }
- /* istanbul ignore next */
- throw error.stack;
- }
- }
- var parser = {
- parse: parse$2,
- resolveParser: resolveParser$1
- };
- var UndefinedParserError = errors.UndefinedParserError;
- var getSupportInfo$1 = support.getSupportInfo;
- var resolveParser = parser.resolveParser;
- var hiddenDefaults = {
- astFormat: "estree",
- printer: {},
- originalText: undefined,
- locStart: null,
- locEnd: null
- }; // Copy options and fill in default values.
- function normalize(options, opts) {
- opts = opts || {};
- var rawOptions = Object.assign({}, options);
- var supportOptions = getSupportInfo$1(null, {
- plugins: options.plugins,
- showUnreleased: true,
- showDeprecated: true
- }).options;
- var defaults = supportOptions.reduce(function (reduced, optionInfo) {
- return optionInfo.default !== undefined ? Object.assign(reduced, {
- [optionInfo.name]: optionInfo.default
- }) : reduced;
- }, Object.assign({}, hiddenDefaults));
- if (!rawOptions.parser) {
- if (!rawOptions.filepath) {
- var logger = opts.logger || console;
- logger.warn("No parser and no filepath given, using 'babel' the parser now " + "but this will throw an error in the future. " + "Please specify a parser or a filepath so one can be inferred.");
- rawOptions.parser = "babel";
- } else {
- rawOptions.parser = inferParser(rawOptions.filepath, rawOptions.plugins);
- if (!rawOptions.parser) {
- throw new UndefinedParserError(`No parser could be inferred for file: ${rawOptions.filepath}`);
- }
- }
- }
- var parser$$1 = resolveParser(optionsNormalizer.normalizeApiOptions(rawOptions, [supportOptions.find(function (x) {
- return x.name === "parser";
- })], {
- passThrough: true,
- logger: false
- }));
- rawOptions.astFormat = parser$$1.astFormat;
- rawOptions.locEnd = parser$$1.locEnd;
- rawOptions.locStart = parser$$1.locStart;
- var plugin = getPlugin(rawOptions);
- rawOptions.printer = plugin.printers[rawOptions.astFormat];
- var pluginDefaults = supportOptions.filter(function (optionInfo) {
- return optionInfo.pluginDefaults && optionInfo.pluginDefaults[plugin.name];
- }).reduce(function (reduced, optionInfo) {
- return Object.assign(reduced, {
- [optionInfo.name]: optionInfo.pluginDefaults[plugin.name]
- });
- }, {});
- var mixedDefaults = Object.assign({}, defaults, pluginDefaults);
- Object.keys(mixedDefaults).forEach(function (k) {
- if (rawOptions[k] == null) {
- rawOptions[k] = mixedDefaults[k];
- }
- });
- if (rawOptions.parser === "json") {
- rawOptions.trailingComma = "none";
- }
- return optionsNormalizer.normalizeApiOptions(rawOptions, supportOptions, Object.assign({
- passThrough: Object.keys(hiddenDefaults)
- }, opts));
- }
- function getPlugin(options) {
- var astFormat = options.astFormat;
- if (!astFormat) {
- throw new Error("getPlugin() requires astFormat to be set");
- }
- var printerPlugin = options.plugins.find(function (plugin) {
- return plugin.printers && plugin.printers[astFormat];
- });
- if (!printerPlugin) {
- throw new Error(`Couldn't find plugin for AST format "${astFormat}"`);
- }
- return printerPlugin;
- }
- function getInterpreter(filepath) {
- if (typeof filepath !== "string") {
- return "";
- }
- var fd;
- try {
- fd = fs.openSync(filepath, "r");
- } catch (err) {
- return "";
- }
- try {
- var liner = new readlines(fd);
- var firstLine = liner.next().toString("utf8"); // #!/bin/env node, #!/usr/bin/env node
- var m1 = firstLine.match(/^#!\/(?:usr\/)?bin\/env\s+(\S+)/);
- if (m1) {
- return m1[1];
- } // #!/bin/node, #!/usr/bin/node, #!/usr/local/bin/node
- var m2 = firstLine.match(/^#!\/(?:usr\/(?:local\/)?)?bin\/(\S+)/);
- if (m2) {
- return m2[1];
- }
- return "";
- } catch (err) {
- // There are some weird cases where paths are missing, causing Jest
- // failures. It's unclear what these correspond to in the real world.
- return "";
- } finally {
- try {
- // There are some weird cases where paths are missing, causing Jest
- // failures. It's unclear what these correspond to in the real world.
- fs.closeSync(fd);
- } catch (err) {// nop
- }
- }
- }
- function inferParser(filepath, plugins) {
- var filepathParts = normalizePath(filepath).split("/");
- var filename = filepathParts[filepathParts.length - 1].toLowerCase(); // If the file has no extension, we can try to infer the language from the
- // interpreter in the shebang line, if any; but since this requires FS access,
- // do it last.
- var language = getSupportInfo$1(null, {
- plugins
- }).languages.find(function (language) {
- return language.since !== null && (language.extensions && language.extensions.some(function (extension) {
- return filename.endsWith(extension);
- }) || language.filenames && language.filenames.find(function (name) {
- return name.toLowerCase() === filename;
- }) || filename.indexOf(".") === -1 && language.interpreters && language.interpreters.indexOf(getInterpreter(filepath)) !== -1);
- });
- return language && language.parsers[0];
- }
- var options = {
- normalize,
- hiddenDefaults,
- inferParser
- };
- function massageAST(ast, options, parent) {
- if (Array.isArray(ast)) {
- return ast.map(function (e) {
- return massageAST(e, options, parent);
- }).filter(function (e) {
- return e;
- });
- }
- if (!ast || typeof ast !== "object") {
- return ast;
- }
- var newObj = {};
- var _arr = Object.keys(ast);
- for (var _i = 0; _i < _arr.length; _i++) {
- var key = _arr[_i];
- if (typeof ast[key] !== "function") {
- newObj[key] = massageAST(ast[key], options, ast);
- }
- }
- if (options.printer.massageAstNode) {
- var result = options.printer.massageAstNode(ast, newObj, parent);
- if (result === null) {
- return undefined;
- }
- if (result) {
- return result;
- }
- }
- return newObj;
- }
- var massageAst = massageAST;
- function concat$1(parts) {
- return {
- type: "concat",
- parts
- };
- }
- function indent$1(contents) {
- return {
- type: "indent",
- contents
- };
- }
- function align(n, contents) {
- return {
- type: "align",
- contents,
- n
- };
- }
- function group(contents, opts) {
- opts = opts || {};
- return {
- type: "group",
- id: opts.id,
- contents: contents,
- break: !!opts.shouldBreak,
- expandedStates: opts.expandedStates
- };
- }
- function dedentToRoot(contents) {
- return align(-Infinity, contents);
- }
- function markAsRoot(contents) {
- return align({
- type: "root"
- }, contents);
- }
- function dedent$1(contents) {
- return align(-1, contents);
- }
- function conditionalGroup(states, opts) {
- return group(states[0], Object.assign(opts || {}, {
- expandedStates: states
- }));
- }
- function fill(parts) {
- return {
- type: "fill",
- parts
- };
- }
- function ifBreak(breakContents, flatContents, opts) {
- opts = opts || {};
- return {
- type: "if-break",
- breakContents,
- flatContents,
- groupId: opts.groupId
- };
- }
- function lineSuffix$1(contents) {
- return {
- type: "line-suffix",
- contents
- };
- }
- var lineSuffixBoundary = {
- type: "line-suffix-boundary"
- };
- var breakParent$1 = {
- type: "break-parent"
- };
- var trim = {
- type: "trim"
- };
- var line$2 = {
- type: "line"
- };
- var softline = {
- type: "line",
- soft: true
- };
- var hardline$1 = concat$1([{
- type: "line",
- hard: true
- }, breakParent$1]);
- var literalline = concat$1([{
- type: "line",
- hard: true,
- literal: true
- }, breakParent$1]);
- var cursor$1 = {
- type: "cursor",
- placeholder: Symbol("cursor")
- };
- function join$1(sep, arr) {
- var res = [];
- for (var i = 0; i < arr.length; i++) {
- if (i !== 0) {
- res.push(sep);
- }
- res.push(arr[i]);
- }
- return concat$1(res);
- }
- function addAlignmentToDoc(doc, size, tabWidth) {
- var aligned = doc;
- if (size > 0) {
- // Use indent to add tabs for all the levels of tabs we need
- for (var i = 0; i < Math.floor(size / tabWidth); ++i) {
- aligned = indent$1(aligned);
- } // Use align for all the spaces that are needed
- aligned = align(size % tabWidth, aligned); // size is absolute from 0 and not relative to the current
- // indentation, so we use -Infinity to reset the indentation to 0
- aligned = align(-Infinity, aligned);
- }
- return aligned;
- }
- var docBuilders = {
- concat: concat$1,
- join: join$1,
- line: line$2,
- softline,
- hardline: hardline$1,
- literalline,
- group,
- conditionalGroup,
- fill,
- lineSuffix: lineSuffix$1,
- lineSuffixBoundary,
- cursor: cursor$1,
- breakParent: breakParent$1,
- ifBreak,
- trim,
- indent: indent$1,
- align,
- addAlignmentToDoc,
- markAsRoot,
- dedentToRoot,
- dedent: dedent$1
- };
- var ansiRegex = createCommonjsModule(function (module) {
- 'use strict';
- module.exports = function (options) {
- options = Object.assign({
- onlyFirst: false
- }, options);
- var pattern = ['[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[a-zA-Z\\d]*)*)?\\u0007)', '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))'].join('|');
- return new RegExp(pattern, options.onlyFirst ? undefined : 'g');
- };
- });
- var stripAnsi = function stripAnsi(input) {
- return typeof input === 'string' ? input.replace(ansiRegex(), '') : input;
- };
- var isFullwidthCodePoint = createCommonjsModule(function (module) {
- 'use strict';
- /* eslint-disable yoda */
- module.exports = function (x) {
- if (Number.isNaN(x)) {
- return false;
- } // code points are derived from:
- // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt
- if (x >= 0x1100 && (x <= 0x115f || // Hangul Jamo
- x === 0x2329 || // LEFT-POINTING ANGLE BRACKET
- x === 0x232a || // RIGHT-POINTING ANGLE BRACKET
- // CJK Radicals Supplement .. Enclosed CJK Letters and Months
- 0x2e80 <= x && x <= 0x3247 && x !== 0x303f || // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A
- 0x3250 <= x && x <= 0x4dbf || // CJK Unified Ideographs .. Yi Radicals
- 0x4e00 <= x && x <= 0xa4c6 || // Hangul Jamo Extended-A
- 0xa960 <= x && x <= 0xa97c || // Hangul Syllables
- 0xac00 <= x && x <= 0xd7a3 || // CJK Compatibility Ideographs
- 0xf900 <= x && x <= 0xfaff || // Vertical Forms
- 0xfe10 <= x && x <= 0xfe19 || // CJK Compatibility Forms .. Small Form Variants
- 0xfe30 <= x && x <= 0xfe6b || // Halfwidth and Fullwidth Forms
- 0xff01 <= x && x <= 0xff60 || 0xffe0 <= x && x <= 0xffe6 || // Kana Supplement
- 0x1b000 <= x && x <= 0x1b001 || // Enclosed Ideographic Supplement
- 0x1f200 <= x && x <= 0x1f251 || // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane
- 0x20000 <= x && x <= 0x3fffd)) {
- return true;
- }
- return false;
- };
- });
- var emojiRegex = function emojiRegex() {
- // https://mths.be/emoji
- return /\uD83C\uDFF4(?:\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74)\uDB40\uDC7F|\u200D\u2620\uFE0F)|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC68(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDB0-\uDDB3])|(?:\uD83C[\uDFFB-\uDFFF])\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDB0-\uDDB3]))|\uD83D\uDC69\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDB0-\uDDB3])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2695\u2696\u2708]|\uD83D\uDC68(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83D\uDC69\u200D[\u2695\u2696\u2708])\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC68(?:\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDB0-\uDDB3])|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83C\uDDF6\uD83C\uDDE6|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDD1-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDEEB\uDEEC\uDEF4-\uDEF9]|\uD83E[\uDD10-\uDD3A\uDD3C-\uDD3E\uDD40-\uDD45\uDD47-\uDD70\uDD73-\uDD76\uDD7A\uDD7C-\uDDA2\uDDB0-\uDDB9\uDDC0-\uDDC2\uDDD0-\uDDFF])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEF9]|\uD83E[\uDD10-\uDD3A\uDD3C-\uDD3E\uDD40-\uDD45\uDD47-\uDD70\uDD73-\uDD76\uDD7A\uDD7C-\uDDA2\uDDB0-\uDDB9\uDDC0-\uDDC2\uDDD0-\uDDFF])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC69\uDC6E\uDC70-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD18-\uDD1C\uDD1E\uDD1F\uDD26\uDD30-\uDD39\uDD3D\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDD1-\uDDDD])/g;
- };
- var stringWidth = createCommonjsModule(function (module) {
- 'use strict';
- var emojiRegex$$1 = emojiRegex();
- module.exports = function (input) {
- input = input.replace(emojiRegex$$1, ' ');
- if (typeof input !== 'string' || input.length === 0) {
- return 0;
- }
- input = stripAnsi(input);
- var width = 0;
- for (var i = 0; i < input.length; i++) {
- var code = input.codePointAt(i); // Ignore control characters
- if (code <= 0x1F || code >= 0x7F && code <= 0x9F) {
- continue;
- } // Ignore combining characters
- if (code >= 0x300 && code <= 0x36F) {
- continue;
- } // Surrogates
- if (code > 0xFFFF) {
- i++;
- }
- width += isFullwidthCodePoint(code) ? 2 : 1;
- }
- return width;
- };
- });
- var notAsciiRegex = /[^\x20-\x7F]/;
- function isExportDeclaration(node) {
- if (node) {
- switch (node.type) {
- case "ExportDefaultDeclaration":
- case "ExportDefaultSpecifier":
- case "DeclareExportDeclaration":
- case "ExportNamedDeclaration":
- case "ExportAllDeclaration":
- return true;
- }
- }
- return false;
- }
- function getParentExportDeclaration(path$$1) {
- var parentNode = path$$1.getParentNode();
- if (path$$1.getName() === "declaration" && isExportDeclaration(parentNode)) {
- return parentNode;
- }
- return null;
- }
- function getPenultimate(arr) {
- if (arr.length > 1) {
- return arr[arr.length - 2];
- }
- return null;
- }
- function getLast$3(arr) {
- if (arr.length > 0) {
- return arr[arr.length - 1];
- }
- return null;
- }
- function skip(chars) {
- return function (text, index, opts) {
- var backwards = opts && opts.backwards; // Allow `skip` functions to be threaded together without having
- // to check for failures (did someone say monads?).
- if (index === false) {
- return false;
- }
- var length = text.length;
- var cursor = index;
- while (cursor >= 0 && cursor < length) {
- var c = text.charAt(cursor);
- if (chars instanceof RegExp) {
- if (!chars.test(c)) {
- return cursor;
- }
- } else if (chars.indexOf(c) === -1) {
- return cursor;
- }
- backwards ? cursor-- : cursor++;
- }
- if (cursor === -1 || cursor === length) {
- // If we reached the beginning or end of the file, return the
- // out-of-bounds cursor. It's up to the caller to handle this
- // correctly. We don't want to indicate `false` though if it
- // actually skipped valid characters.
- return cursor;
- }
- return false;
- };
- }
- var skipWhitespace = skip(/\s/);
- var skipSpaces = skip(" \t");
- var skipToLineEnd = skip(",; \t");
- var skipEverythingButNewLine = skip(/[^\r\n]/);
- function skipInlineComment(text, index) {
- if (index === false) {
- return false;
- }
- if (text.charAt(index) === "/" && text.charAt(index + 1) === "*") {
- for (var i = index + 2; i < text.length; ++i) {
- if (text.charAt(i) === "*" && text.charAt(i + 1) === "/") {
- return i + 2;
- }
- }
- }
- return index;
- }
- function skipTrailingComment(text, index) {
- if (index === false) {
- return false;
- }
- if (text.charAt(index) === "/" && text.charAt(index + 1) === "/") {
- return skipEverythingButNewLine(text, index);
- }
- return index;
- } // This one doesn't use the above helper function because it wants to
- // test \r\n in order and `skip` doesn't support ordering and we only
- // want to skip one newline. It's simple to implement.
- function skipNewline$1(text, index, opts) {
- var backwards = opts && opts.backwards;
- if (index === false) {
- return false;
- }
- var atIndex = text.charAt(index);
- if (backwards) {
- if (text.charAt(index - 1) === "\r" && atIndex === "\n") {
- return index - 2;
- }
- if (atIndex === "\n" || atIndex === "\r" || atIndex === "\u2028" || atIndex === "\u2029") {
- return index - 1;
- }
- } else {
- if (atIndex === "\r" && text.charAt(index + 1) === "\n") {
- return index + 2;
- }
- if (atIndex === "\n" || atIndex === "\r" || atIndex === "\u2028" || atIndex === "\u2029") {
- return index + 1;
- }
- }
- return index;
- }
- function hasNewline$1(text, index, opts) {
- opts = opts || {};
- var idx = skipSpaces(text, opts.backwards ? index - 1 : index, opts);
- var idx2 = skipNewline$1(text, idx, opts);
- return idx !== idx2;
- }
- function hasNewlineInRange(text, start, end) {
- for (var i = start; i < end; ++i) {
- if (text.charAt(i) === "\n") {
- return true;
- }
- }
- return false;
- } // Note: this function doesn't ignore leading comments unlike isNextLineEmpty
- function isPreviousLineEmpty$1(text, node, locStart) {
- var idx = locStart(node) - 1;
- idx = skipSpaces(text, idx, {
- backwards: true
- });
- idx = skipNewline$1(text, idx, {
- backwards: true
- });
- idx = skipSpaces(text, idx, {
- backwards: true
- });
- var idx2 = skipNewline$1(text, idx, {
- backwards: true
- });
- return idx !== idx2;
- }
- function isNextLineEmptyAfterIndex(text, index) {
- var oldIdx = null;
- var idx = index;
- while (idx !== oldIdx) {
- // We need to skip all the potential trailing inline comments
- oldIdx = idx;
- idx = skipToLineEnd(text, idx);
- idx = skipInlineComment(text, idx);
- idx = skipSpaces(text, idx);
- }
- idx = skipTrailingComment(text, idx);
- idx = skipNewline$1(text, idx);
- return hasNewline$1(text, idx);
- }
- function isNextLineEmpty(text, node, locEnd) {
- return isNextLineEmptyAfterIndex(text, locEnd(node));
- }
- function getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, idx) {
- var oldIdx = null;
- while (idx !== oldIdx) {
- oldIdx = idx;
- idx = skipSpaces(text, idx);
- idx = skipInlineComment(text, idx);
- idx = skipTrailingComment(text, idx);
- idx = skipNewline$1(text, idx);
- }
- return idx;
- }
- function getNextNonSpaceNonCommentCharacterIndex(text, node, locEnd) {
- return getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, locEnd(node));
- }
- function getNextNonSpaceNonCommentCharacter(text, node, locEnd) {
- return text.charAt(getNextNonSpaceNonCommentCharacterIndex(text, node, locEnd));
- }
- function hasSpaces(text, index, opts) {
- opts = opts || {};
- var idx = skipSpaces(text, opts.backwards ? index - 1 : index, opts);
- return idx !== index;
- }
- function setLocStart(node, index) {
- if (node.range) {
- node.range[0] = index;
- } else {
- node.start = index;
- }
- }
- function setLocEnd(node, index) {
- if (node.range) {
- node.range[1] = index;
- } else {
- node.end = index;
- }
- }
- var PRECEDENCE = {};
- [["|>"], ["||", "??"], ["&&"], ["|"], ["^"], ["&"], ["==", "===", "!=", "!=="], ["<", ">", "<=", ">=", "in", "instanceof"], [">>", "<<", ">>>"], ["+", "-"], ["*", "/", "%"], ["**"]].forEach(function (tier, i) {
- tier.forEach(function (op) {
- PRECEDENCE[op] = i;
- });
- });
- function getPrecedence(op) {
- return PRECEDENCE[op];
- }
- var equalityOperators = {
- "==": true,
- "!=": true,
- "===": true,
- "!==": true
- };
- var multiplicativeOperators = {
- "*": true,
- "/": true,
- "%": true
- };
- var bitshiftOperators = {
- ">>": true,
- ">>>": true,
- "<<": true
- };
- function shouldFlatten(parentOp, nodeOp) {
- if (getPrecedence(nodeOp) !== getPrecedence(parentOp)) {
- return false;
- } // ** is right-associative
- // x ** y ** z --> x ** (y ** z)
- if (parentOp === "**") {
- return false;
- } // x == y == z --> (x == y) == z
- if (equalityOperators[parentOp] && equalityOperators[nodeOp]) {
- return false;
- } // x * y % z --> (x * y) % z
- if (nodeOp === "%" && multiplicativeOperators[parentOp] || parentOp === "%" && multiplicativeOperators[nodeOp]) {
- return false;
- } // x * y / z --> (x * y) / z
- // x / y * z --> (x / y) * z
- if (nodeOp !== parentOp && multiplicativeOperators[nodeOp] && multiplicativeOperators[parentOp]) {
- return false;
- } // x << y << z --> (x << y) << z
- if (bitshiftOperators[parentOp] && bitshiftOperators[nodeOp]) {
- return false;
- }
- return true;
- }
- function isBitwiseOperator(operator) {
- return !!bitshiftOperators[operator] || operator === "|" || operator === "^" || operator === "&";
- } // Tests if an expression starts with `{`, or (if forbidFunctionClassAndDoExpr
- // holds) `function`, `class`, or `do {}`. Will be overzealous if there's
- // already necessary grouping parentheses.
- function startsWithNoLookaheadToken(node, forbidFunctionClassAndDoExpr) {
- node = getLeftMost(node);
- switch (node.type) {
- case "FunctionExpression":
- case "ClassExpression":
- case "DoExpression":
- return forbidFunctionClassAndDoExpr;
- case "ObjectExpression":
- return true;
- case "MemberExpression":
- return startsWithNoLookaheadToken(node.object, forbidFunctionClassAndDoExpr);
- case "TaggedTemplateExpression":
- if (node.tag.type === "FunctionExpression") {
- // IIFEs are always already parenthesized
- return false;
- }
- return startsWithNoLookaheadToken(node.tag, forbidFunctionClassAndDoExpr);
- case "CallExpression":
- if (node.callee.type === "FunctionExpression") {
- // IIFEs are always already parenthesized
- return false;
- }
- return startsWithNoLookaheadToken(node.callee, forbidFunctionClassAndDoExpr);
- case "ConditionalExpression":
- return startsWithNoLookaheadToken(node.test, forbidFunctionClassAndDoExpr);
- case "UpdateExpression":
- return !node.prefix && startsWithNoLookaheadToken(node.argument, forbidFunctionClassAndDoExpr);
- case "BindExpression":
- return node.object && startsWithNoLookaheadToken(node.object, forbidFunctionClassAndDoExpr);
- case "SequenceExpression":
- return startsWithNoLookaheadToken(node.expressions[0], forbidFunctionClassAndDoExpr);
- case "TSAsExpression":
- return startsWithNoLookaheadToken(node.expression, forbidFunctionClassAndDoExpr);
- default:
- return false;
- }
- }
- function getLeftMost(node) {
- if (node.left) {
- return getLeftMost(node.left);
- }
- return node;
- }
- function getAlignmentSize(value, tabWidth, startIndex) {
- startIndex = startIndex || 0;
- var size = 0;
- for (var i = startIndex; i < value.length; ++i) {
- if (value[i] === "\t") {
- // Tabs behave in a way that they are aligned to the nearest
- // multiple of tabWidth:
- // 0 -> 4, 1 -> 4, 2 -> 4, 3 -> 4
- // 4 -> 8, 5 -> 8, 6 -> 8, 7 -> 8 ...
- size = size + tabWidth - size % tabWidth;
- } else {
- size++;
- }
- }
- return size;
- }
- function getIndentSize(value, tabWidth) {
- var lastNewlineIndex = value.lastIndexOf("\n");
- if (lastNewlineIndex === -1) {
- return 0;
- }
- return getAlignmentSize( // All the leading whitespaces
- value.slice(lastNewlineIndex + 1).match(/^[ \t]*/)[0], tabWidth);
- }
- function getPreferredQuote(raw, preferredQuote) {
- // `rawContent` is the string exactly like it appeared in the input source
- // code, without its enclosing quotes.
- var rawContent = raw.slice(1, -1);
- var double = {
- quote: '"',
- regex: /"/g
- };
- var single = {
- quote: "'",
- regex: /'/g
- };
- var preferred = preferredQuote === "'" ? single : double;
- var alternate = preferred === single ? double : single;
- var result = preferred.quote; // If `rawContent` contains at least one of the quote preferred for enclosing
- // the string, we might want to enclose with the alternate quote instead, to
- // minimize the number of escaped quotes.
- if (rawContent.includes(preferred.quote) || rawContent.includes(alternate.quote)) {
- var numPreferredQuotes = (rawContent.match(preferred.regex) || []).length;
- var numAlternateQuotes = (rawContent.match(alternate.regex) || []).length;
- result = numPreferredQuotes > numAlternateQuotes ? alternate.quote : preferred.quote;
- }
- return result;
- }
- function printString(raw, options, isDirectiveLiteral) {
- // `rawContent` is the string exactly like it appeared in the input source
- // code, without its enclosing quotes.
- var rawContent = raw.slice(1, -1); // Check for the alternate quote, to determine if we're allowed to swap
- // the quotes on a DirectiveLiteral.
- var canChangeDirectiveQuotes = !rawContent.includes('"') && !rawContent.includes("'");
- var enclosingQuote = options.parser === "json" ? '"' : options.__isInHtmlAttribute ? "'" : getPreferredQuote(raw, options.singleQuote ? "'" : '"'); // Directives are exact code unit sequences, which means that you can't
- // change the escape sequences they use.
- // See https://github.com/prettier/prettier/issues/1555
- // and https://tc39.github.io/ecma262/#directive-prologue
- if (isDirectiveLiteral) {
- if (canChangeDirectiveQuotes) {
- return enclosingQuote + rawContent + enclosingQuote;
- }
- return raw;
- } // It might sound unnecessary to use `makeString` even if the string already
- // is enclosed with `enclosingQuote`, but it isn't. The string could contain
- // unnecessary escapes (such as in `"\'"`). Always using `makeString` makes
- // sure that we consistently output the minimum amount of escaped quotes.
- return makeString(rawContent, enclosingQuote, !(options.parser === "css" || options.parser === "less" || options.parser === "scss" || options.parentParser === "html" || options.parentParser === "vue" || options.parentParser === "angular"));
- }
- function makeString(rawContent, enclosingQuote, unescapeUnnecessaryEscapes) {
- var otherQuote = enclosingQuote === '"' ? "'" : '"'; // Matches _any_ escape and unescaped quotes (both single and double).
- var regex = /\\([\s\S])|(['"])/g; // Escape and unescape single and double quotes as needed to be able to
- // enclose `rawContent` with `enclosingQuote`.
- var newContent = rawContent.replace(regex, function (match, escaped, quote) {
- // If we matched an escape, and the escaped character is a quote of the
- // other type than we intend to enclose the string with, there's no need for
- // it to be escaped, so return it _without_ the backslash.
- if (escaped === otherQuote) {
- return escaped;
- } // If we matched an unescaped quote and it is of the _same_ type as we
- // intend to enclose the string with, it must be escaped, so return it with
- // a backslash.
- if (quote === enclosingQuote) {
- return "\\" + quote;
- }
- if (quote) {
- return quote;
- } // Unescape any unnecessarily escaped character.
- // Adapted from https://github.com/eslint/eslint/blob/de0b4ad7bd820ade41b1f606008bea68683dc11a/lib/rules/no-useless-escape.js#L27
- return unescapeUnnecessaryEscapes && /^[^\\nrvtbfux\r\n\u2028\u2029"'0-7]$/.test(escaped) ? escaped : "\\" + escaped;
- });
- return enclosingQuote + newContent + enclosingQuote;
- }
- function printNumber(rawNumber) {
- return rawNumber.toLowerCase() // Remove unnecessary plus and zeroes from scientific notation.
- .replace(/^([+-]?[\d.]+e)(?:\+|(-))?0*(\d)/, "$1$2$3") // Remove unnecessary scientific notation (1e0).
- .replace(/^([+-]?[\d.]+)e[+-]?0+$/, "$1") // Make sure numbers always start with a digit.
- .replace(/^([+-])?\./, "$10.") // Remove extraneous trailing decimal zeroes.
- .replace(/(\.\d+?)0+(?=e|$)/, "$1") // Remove trailing dot.
- .replace(/\.(?=e|$)/, "");
- }
- function getMaxContinuousCount(str, target) {
- var results = str.match(new RegExp(`(${escapeStringRegexp(target)})+`, "g"));
- if (results === null) {
- return 0;
- }
- return results.reduce(function (maxCount, result) {
- return Math.max(maxCount, result.length / target.length);
- }, 0);
- }
- function getStringWidth$1(text) {
- if (!text) {
- return 0;
- } // shortcut to avoid needless string `RegExp`s, replacements, and allocations within `string-width`
- if (!notAsciiRegex.test(text)) {
- return text.length;
- }
- return stringWidth(text);
- }
- function hasIgnoreComment(path$$1) {
- var node = path$$1.getValue();
- return hasNodeIgnoreComment(node);
- }
- function hasNodeIgnoreComment(node) {
- return node && node.comments && node.comments.length > 0 && node.comments.some(function (comment) {
- return comment.value.trim() === "prettier-ignore";
- });
- }
- function matchAncestorTypes(path$$1, types, index) {
- index = index || 0;
- types = types.slice();
- while (types.length) {
- var parent = path$$1.getParentNode(index);
- var type = types.shift();
- if (!parent || parent.type !== type) {
- return false;
- }
- index++;
- }
- return true;
- }
- function addCommentHelper(node, comment) {
- var comments = node.comments || (node.comments = []);
- comments.push(comment);
- comment.printed = false; // For some reason, TypeScript parses `// x` inside of JSXText as a comment
- // We already "print" it via the raw text, we don't need to re-print it as a
- // comment
- if (node.type === "JSXText") {
- comment.printed = true;
- }
- }
- function addLeadingComment$1(node, comment) {
- comment.leading = true;
- comment.trailing = false;
- addCommentHelper(node, comment);
- }
- function addDanglingComment$1(node, comment) {
- comment.leading = false;
- comment.trailing = false;
- addCommentHelper(node, comment);
- }
- function addTrailingComment$1(node, comment) {
- comment.leading = false;
- comment.trailing = true;
- addCommentHelper(node, comment);
- }
- function isWithinParentArrayProperty(path$$1, propertyName) {
- var node = path$$1.getValue();
- var parent = path$$1.getParentNode();
- if (parent == null) {
- return false;
- }
- if (!Array.isArray(parent[propertyName])) {
- return false;
- }
- var key = path$$1.getName();
- return parent[propertyName][key] === node;
- }
- function replaceEndOfLineWith(text, replacement) {
- var parts = [];
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = text.split("\n")[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var part = _step.value;
- if (parts.length !== 0) {
- parts.push(replacement);
- }
- parts.push(part);
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- return parts;
- }
- var util$1 = {
- replaceEndOfLineWith,
- getStringWidth: getStringWidth$1,
- getMaxContinuousCount,
- getPrecedence,
- shouldFlatten,
- isBitwiseOperator,
- isExportDeclaration,
- getParentExportDeclaration,
- getPenultimate,
- getLast: getLast$3,
- getNextNonSpaceNonCommentCharacterIndexWithStartIndex,
- getNextNonSpaceNonCommentCharacterIndex,
- getNextNonSpaceNonCommentCharacter,
- skip,
- skipWhitespace,
- skipSpaces,
- skipToLineEnd,
- skipEverythingButNewLine,
- skipInlineComment,
- skipTrailingComment,
- skipNewline: skipNewline$1,
- isNextLineEmptyAfterIndex,
- isNextLineEmpty,
- isPreviousLineEmpty: isPreviousLineEmpty$1,
- hasNewline: hasNewline$1,
- hasNewlineInRange,
- hasSpaces,
- setLocStart,
- setLocEnd,
- startsWithNoLookaheadToken,
- getAlignmentSize,
- getIndentSize,
- getPreferredQuote,
- printString,
- printNumber,
- hasIgnoreComment,
- hasNodeIgnoreComment,
- makeString,
- matchAncestorTypes,
- addLeadingComment: addLeadingComment$1,
- addDanglingComment: addDanglingComment$1,
- addTrailingComment: addTrailingComment$1,
- isWithinParentArrayProperty
- };
- function guessEndOfLine$1(text) {
- var index = text.indexOf("\r");
- if (index >= 0) {
- return text.charAt(index + 1) === "\n" ? "crlf" : "cr";
- }
- return "lf";
- }
- function convertEndOfLineToChars$2(value) {
- switch (value) {
- case "cr":
- return "\r";
- case "crlf":
- return "\r\n";
- default:
- return "\n";
- }
- }
- var endOfLine = {
- guessEndOfLine: guessEndOfLine$1,
- convertEndOfLineToChars: convertEndOfLineToChars$2
- };
- var getStringWidth = util$1.getStringWidth;
- var convertEndOfLineToChars$1 = endOfLine.convertEndOfLineToChars;
- var concat$2 = docBuilders.concat;
- var fill$1 = docBuilders.fill;
- var cursor$2 = docBuilders.cursor;
- /** @type {{[groupId: PropertyKey]: MODE}} */
- var groupModeMap;
- var MODE_BREAK = 1;
- var MODE_FLAT = 2;
- function rootIndent() {
- return {
- value: "",
- length: 0,
- queue: []
- };
- }
- function makeIndent(ind, options) {
- return generateInd(ind, {
- type: "indent"
- }, options);
- }
- function makeAlign(ind, n, options) {
- return n === -Infinity ? ind.root || rootIndent() : n < 0 ? generateInd(ind, {
- type: "dedent"
- }, options) : !n ? ind : n.type === "root" ? Object.assign({}, ind, {
- root: ind
- }) : typeof n === "string" ? generateInd(ind, {
- type: "stringAlign",
- n
- }, options) : generateInd(ind, {
- type: "numberAlign",
- n
- }, options);
- }
- function generateInd(ind, newPart, options) {
- var queue = newPart.type === "dedent" ? ind.queue.slice(0, -1) : ind.queue.concat(newPart);
- var value = "";
- var length = 0;
- var lastTabs = 0;
- var lastSpaces = 0;
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = queue[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var part = _step.value;
- switch (part.type) {
- case "indent":
- flush();
- if (options.useTabs) {
- addTabs(1);
- } else {
- addSpaces(options.tabWidth);
- }
- break;
- case "stringAlign":
- flush();
- value += part.n;
- length += part.n.length;
- break;
- case "numberAlign":
- lastTabs += 1;
- lastSpaces += part.n;
- break;
- /* istanbul ignore next */
- default:
- throw new Error(`Unexpected type '${part.type}'`);
- }
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- flushSpaces();
- return Object.assign({}, ind, {
- value,
- length,
- queue
- });
- function addTabs(count) {
- value += "\t".repeat(count);
- length += options.tabWidth * count;
- }
- function addSpaces(count) {
- value += " ".repeat(count);
- length += count;
- }
- function flush() {
- if (options.useTabs) {
- flushTabs();
- } else {
- flushSpaces();
- }
- }
- function flushTabs() {
- if (lastTabs > 0) {
- addTabs(lastTabs);
- }
- resetLast();
- }
- function flushSpaces() {
- if (lastSpaces > 0) {
- addSpaces(lastSpaces);
- }
- resetLast();
- }
- function resetLast() {
- lastTabs = 0;
- lastSpaces = 0;
- }
- }
- function trim$1(out) {
- if (out.length === 0) {
- return 0;
- }
- var trimCount = 0; // Trim whitespace at the end of line
- while (out.length > 0 && typeof out[out.length - 1] === "string" && out[out.length - 1].match(/^[ \t]*$/)) {
- trimCount += out.pop().length;
- }
- if (out.length && typeof out[out.length - 1] === "string") {
- var trimmed = out[out.length - 1].replace(/[ \t]*$/, "");
- trimCount += out[out.length - 1].length - trimmed.length;
- out[out.length - 1] = trimmed;
- }
- return trimCount;
- }
- function fits(next, restCommands, width, options, mustBeFlat) {
- var restIdx = restCommands.length;
- var cmds = [next]; // `out` is only used for width counting because `trim` requires to look
- // backwards for space characters.
- var out = [];
- while (width >= 0) {
- if (cmds.length === 0) {
- if (restIdx === 0) {
- return true;
- }
- cmds.push(restCommands[restIdx - 1]);
- restIdx--;
- continue;
- }
- var x = cmds.pop();
- var ind = x[0];
- var mode = x[1];
- var doc = x[2];
- if (typeof doc === "string") {
- out.push(doc);
- width -= getStringWidth(doc);
- } else {
- switch (doc.type) {
- case "concat":
- for (var i = doc.parts.length - 1; i >= 0; i--) {
- cmds.push([ind, mode, doc.parts[i]]);
- }
- break;
- case "indent":
- cmds.push([makeIndent(ind, options), mode, doc.contents]);
- break;
- case "align":
- cmds.push([makeAlign(ind, doc.n, options), mode, doc.contents]);
- break;
- case "trim":
- width += trim$1(out);
- break;
- case "group":
- if (mustBeFlat && doc.break) {
- return false;
- }
- cmds.push([ind, doc.break ? MODE_BREAK : mode, doc.contents]);
- if (doc.id) {
- groupModeMap[doc.id] = cmds[cmds.length - 1][1];
- }
- break;
- case "fill":
- for (var _i = doc.parts.length - 1; _i >= 0; _i--) {
- cmds.push([ind, mode, doc.parts[_i]]);
- }
- break;
- case "if-break":
- {
- var groupMode = doc.groupId ? groupModeMap[doc.groupId] : mode;
- if (groupMode === MODE_BREAK) {
- if (doc.breakContents) {
- cmds.push([ind, mode, doc.breakContents]);
- }
- }
- if (groupMode === MODE_FLAT) {
- if (doc.flatContents) {
- cmds.push([ind, mode, doc.flatContents]);
- }
- }
- break;
- }
- case "line":
- switch (mode) {
- // fallthrough
- case MODE_FLAT:
- if (!doc.hard) {
- if (!doc.soft) {
- out.push(" ");
- width -= 1;
- }
- break;
- }
- return true;
- case MODE_BREAK:
- return true;
- }
- break;
- }
- }
- }
- return false;
- }
- function printDocToString$1(doc, options) {
- groupModeMap = {};
- var width = options.printWidth;
- var newLine = convertEndOfLineToChars$1(options.endOfLine);
- var pos = 0; // cmds is basically a stack. We've turned a recursive call into a
- // while loop which is much faster. The while loop below adds new
- // cmds to the array instead of recursively calling `print`.
- var cmds = [[rootIndent(), MODE_BREAK, doc]];
- var out = [];
- var shouldRemeasure = false;
- var lineSuffix = [];
- while (cmds.length !== 0) {
- var x = cmds.pop();
- var ind = x[0];
- var mode = x[1];
- var _doc = x[2];
- if (typeof _doc === "string") {
- out.push(_doc);
- pos += getStringWidth(_doc);
- } else {
- switch (_doc.type) {
- case "cursor":
- out.push(cursor$2.placeholder);
- break;
- case "concat":
- for (var i = _doc.parts.length - 1; i >= 0; i--) {
- cmds.push([ind, mode, _doc.parts[i]]);
- }
- break;
- case "indent":
- cmds.push([makeIndent(ind, options), mode, _doc.contents]);
- break;
- case "align":
- cmds.push([makeAlign(ind, _doc.n, options), mode, _doc.contents]);
- break;
- case "trim":
- pos -= trim$1(out);
- break;
- case "group":
- switch (mode) {
- case MODE_FLAT:
- if (!shouldRemeasure) {
- cmds.push([ind, _doc.break ? MODE_BREAK : MODE_FLAT, _doc.contents]);
- break;
- }
- // fallthrough
- case MODE_BREAK:
- {
- shouldRemeasure = false;
- var next = [ind, MODE_FLAT, _doc.contents];
- var rem = width - pos;
- if (!_doc.break && fits(next, cmds, rem, options)) {
- cmds.push(next);
- } else {
- // Expanded states are a rare case where a document
- // can manually provide multiple representations of
- // itself. It provides an array of documents
- // going from the least expanded (most flattened)
- // representation first to the most expanded. If a
- // group has these, we need to manually go through
- // these states and find the first one that fits.
- if (_doc.expandedStates) {
- var mostExpanded = _doc.expandedStates[_doc.expandedStates.length - 1];
- if (_doc.break) {
- cmds.push([ind, MODE_BREAK, mostExpanded]);
- break;
- } else {
- for (var _i2 = 1; _i2 < _doc.expandedStates.length + 1; _i2++) {
- if (_i2 >= _doc.expandedStates.length) {
- cmds.push([ind, MODE_BREAK, mostExpanded]);
- break;
- } else {
- var state = _doc.expandedStates[_i2];
- var cmd = [ind, MODE_FLAT, state];
- if (fits(cmd, cmds, rem, options)) {
- cmds.push(cmd);
- break;
- }
- }
- }
- }
- } else {
- cmds.push([ind, MODE_BREAK, _doc.contents]);
- }
- }
- break;
- }
- }
- if (_doc.id) {
- groupModeMap[_doc.id] = cmds[cmds.length - 1][1];
- }
- break;
- // Fills each line with as much code as possible before moving to a new
- // line with the same indentation.
- //
- // Expects doc.parts to be an array of alternating content and
- // whitespace. The whitespace contains the linebreaks.
- //
- // For example:
- // ["I", line, "love", line, "monkeys"]
- // or
- // [{ type: group, ... }, softline, { type: group, ... }]
- //
- // It uses this parts structure to handle three main layout cases:
- // * The first two content items fit on the same line without
- // breaking
- // -> output the first content item and the whitespace "flat".
- // * Only the first content item fits on the line without breaking
- // -> output the first content item "flat" and the whitespace with
- // "break".
- // * Neither content item fits on the line without breaking
- // -> output the first content item and the whitespace with "break".
- case "fill":
- {
- var _rem = width - pos;
- var parts = _doc.parts;
- if (parts.length === 0) {
- break;
- }
- var content = parts[0];
- var contentFlatCmd = [ind, MODE_FLAT, content];
- var contentBreakCmd = [ind, MODE_BREAK, content];
- var contentFits = fits(contentFlatCmd, [], _rem, options, true);
- if (parts.length === 1) {
- if (contentFits) {
- cmds.push(contentFlatCmd);
- } else {
- cmds.push(contentBreakCmd);
- }
- break;
- }
- var whitespace = parts[1];
- var whitespaceFlatCmd = [ind, MODE_FLAT, whitespace];
- var whitespaceBreakCmd = [ind, MODE_BREAK, whitespace];
- if (parts.length === 2) {
- if (contentFits) {
- cmds.push(whitespaceFlatCmd);
- cmds.push(contentFlatCmd);
- } else {
- cmds.push(whitespaceBreakCmd);
- cmds.push(contentBreakCmd);
- }
- break;
- } // At this point we've handled the first pair (context, separator)
- // and will create a new fill doc for the rest of the content.
- // Ideally we wouldn't mutate the array here but coping all the
- // elements to a new array would make this algorithm quadratic,
- // which is unusable for large arrays (e.g. large texts in JSX).
- parts.splice(0, 2);
- var remainingCmd = [ind, mode, fill$1(parts)];
- var secondContent = parts[0];
- var firstAndSecondContentFlatCmd = [ind, MODE_FLAT, concat$2([content, whitespace, secondContent])];
- var firstAndSecondContentFits = fits(firstAndSecondContentFlatCmd, [], _rem, options, true);
- if (firstAndSecondContentFits) {
- cmds.push(remainingCmd);
- cmds.push(whitespaceFlatCmd);
- cmds.push(contentFlatCmd);
- } else if (contentFits) {
- cmds.push(remainingCmd);
- cmds.push(whitespaceBreakCmd);
- cmds.push(contentFlatCmd);
- } else {
- cmds.push(remainingCmd);
- cmds.push(whitespaceBreakCmd);
- cmds.push(contentBreakCmd);
- }
- break;
- }
- case "if-break":
- {
- var groupMode = _doc.groupId ? groupModeMap[_doc.groupId] : mode;
- if (groupMode === MODE_BREAK) {
- if (_doc.breakContents) {
- cmds.push([ind, mode, _doc.breakContents]);
- }
- }
- if (groupMode === MODE_FLAT) {
- if (_doc.flatContents) {
- cmds.push([ind, mode, _doc.flatContents]);
- }
- }
- break;
- }
- case "line-suffix":
- lineSuffix.push([ind, mode, _doc.contents]);
- break;
- case "line-suffix-boundary":
- if (lineSuffix.length > 0) {
- cmds.push([ind, mode, {
- type: "line",
- hard: true
- }]);
- }
- break;
- case "line":
- switch (mode) {
- case MODE_FLAT:
- if (!_doc.hard) {
- if (!_doc.soft) {
- out.push(" ");
- pos += 1;
- }
- break;
- } else {
- // This line was forced into the output even if we
- // were in flattened mode, so we need to tell the next
- // group that no matter what, it needs to remeasure
- // because the previous measurement didn't accurately
- // capture the entire expression (this is necessary
- // for nested groups)
- shouldRemeasure = true;
- }
- // fallthrough
- case MODE_BREAK:
- if (lineSuffix.length) {
- cmds.push([ind, mode, _doc]);
- [].push.apply(cmds, lineSuffix.reverse());
- lineSuffix = [];
- break;
- }
- if (_doc.literal) {
- if (ind.root) {
- out.push(newLine, ind.root.value);
- pos = ind.root.length;
- } else {
- out.push(newLine);
- pos = 0;
- }
- } else {
- pos -= trim$1(out);
- out.push(newLine + ind.value);
- pos = ind.length;
- }
- break;
- }
- break;
- default:
- }
- }
- }
- var cursorPlaceholderIndex = out.indexOf(cursor$2.placeholder);
- if (cursorPlaceholderIndex !== -1) {
- var otherCursorPlaceholderIndex = out.indexOf(cursor$2.placeholder, cursorPlaceholderIndex + 1);
- var beforeCursor = out.slice(0, cursorPlaceholderIndex).join("");
- var aroundCursor = out.slice(cursorPlaceholderIndex + 1, otherCursorPlaceholderIndex).join("");
- var afterCursor = out.slice(otherCursorPlaceholderIndex + 1).join("");
- return {
- formatted: beforeCursor + aroundCursor + afterCursor,
- cursorNodeStart: beforeCursor.length,
- cursorNodeText: aroundCursor
- };
- }
- return {
- formatted: out.join("")
- };
- }
- var docPrinter = {
- printDocToString: printDocToString$1
- };
- var traverseDocOnExitStackMarker = {};
- function traverseDoc(doc, onEnter, onExit, shouldTraverseConditionalGroups) {
- var docsStack = [doc];
- while (docsStack.length !== 0) {
- var _doc = docsStack.pop();
- if (_doc === traverseDocOnExitStackMarker) {
- onExit(docsStack.pop());
- continue;
- }
- var shouldRecurse = true;
- if (onEnter) {
- if (onEnter(_doc) === false) {
- shouldRecurse = false;
- }
- }
- if (onExit) {
- docsStack.push(_doc);
- docsStack.push(traverseDocOnExitStackMarker);
- }
- if (shouldRecurse) {
- // When there are multiple parts to process,
- // the parts need to be pushed onto the stack in reverse order,
- // so that they are processed in the original order
- // when the stack is popped.
- if (_doc.type === "concat" || _doc.type === "fill") {
- for (var ic = _doc.parts.length, i = ic - 1; i >= 0; --i) {
- docsStack.push(_doc.parts[i]);
- }
- } else if (_doc.type === "if-break") {
- if (_doc.flatContents) {
- docsStack.push(_doc.flatContents);
- }
- if (_doc.breakContents) {
- docsStack.push(_doc.breakContents);
- }
- } else if (_doc.type === "group" && _doc.expandedStates) {
- if (shouldTraverseConditionalGroups) {
- for (var _ic = _doc.expandedStates.length, _i = _ic - 1; _i >= 0; --_i) {
- docsStack.push(_doc.expandedStates[_i]);
- }
- } else {
- docsStack.push(_doc.contents);
- }
- } else if (_doc.contents) {
- docsStack.push(_doc.contents);
- }
- }
- }
- }
- function mapDoc$1(doc, cb) {
- if (doc.type === "concat" || doc.type === "fill") {
- var parts = doc.parts.map(function (part) {
- return mapDoc$1(part, cb);
- });
- return cb(Object.assign({}, doc, {
- parts
- }));
- } else if (doc.type === "if-break") {
- var breakContents = doc.breakContents && mapDoc$1(doc.breakContents, cb);
- var flatContents = doc.flatContents && mapDoc$1(doc.flatContents, cb);
- return cb(Object.assign({}, doc, {
- breakContents,
- flatContents
- }));
- } else if (doc.contents) {
- var contents = mapDoc$1(doc.contents, cb);
- return cb(Object.assign({}, doc, {
- contents
- }));
- }
- return cb(doc);
- }
- function findInDoc(doc, fn, defaultValue) {
- var result = defaultValue;
- var hasStopped = false;
- function findInDocOnEnterFn(doc) {
- var maybeResult = fn(doc);
- if (maybeResult !== undefined) {
- hasStopped = true;
- result = maybeResult;
- }
- if (hasStopped) {
- return false;
- }
- }
- traverseDoc(doc, findInDocOnEnterFn);
- return result;
- }
- function isEmpty(n) {
- return typeof n === "string" && n.length === 0;
- }
- function isLineNextFn(doc) {
- if (typeof doc === "string") {
- return false;
- }
- if (doc.type === "line") {
- return true;
- }
- }
- function isLineNext(doc) {
- return findInDoc(doc, isLineNextFn, false);
- }
- function willBreakFn(doc) {
- if (doc.type === "group" && doc.break) {
- return true;
- }
- if (doc.type === "line" && doc.hard) {
- return true;
- }
- if (doc.type === "break-parent") {
- return true;
- }
- }
- function willBreak(doc) {
- return findInDoc(doc, willBreakFn, false);
- }
- function breakParentGroup(groupStack) {
- if (groupStack.length > 0) {
- var parentGroup = groupStack[groupStack.length - 1]; // Breaks are not propagated through conditional groups because
- // the user is expected to manually handle what breaks.
- if (!parentGroup.expandedStates) {
- parentGroup.break = true;
- }
- }
- return null;
- }
- function propagateBreaks(doc) {
- var alreadyVisitedSet = new Set();
- var groupStack = [];
- function propagateBreaksOnEnterFn(doc) {
- if (doc.type === "break-parent") {
- breakParentGroup(groupStack);
- }
- if (doc.type === "group") {
- groupStack.push(doc);
- if (alreadyVisitedSet.has(doc)) {
- return false;
- }
- alreadyVisitedSet.add(doc);
- }
- }
- function propagateBreaksOnExitFn(doc) {
- if (doc.type === "group") {
- var group = groupStack.pop();
- if (group.break) {
- breakParentGroup(groupStack);
- }
- }
- }
- traverseDoc(doc, propagateBreaksOnEnterFn, propagateBreaksOnExitFn,
- /* shouldTraverseConditionalGroups */
- true);
- }
- function removeLinesFn(doc) {
- // Force this doc into flat mode by statically converting all
- // lines into spaces (or soft lines into nothing). Hard lines
- // should still output because there's too great of a chance
- // of breaking existing assumptions otherwise.
- if (doc.type === "line" && !doc.hard) {
- return doc.soft ? "" : " ";
- } else if (doc.type === "if-break") {
- return doc.flatContents || "";
- }
- return doc;
- }
- function removeLines(doc) {
- return mapDoc$1(doc, removeLinesFn);
- }
- function stripTrailingHardline(doc) {
- // HACK remove ending hardline, original PR: #1984
- if (doc.type === "concat" && doc.parts.length !== 0) {
- var lastPart = doc.parts[doc.parts.length - 1];
- if (lastPart.type === "concat") {
- if (lastPart.parts.length === 2 && lastPart.parts[0].hard && lastPart.parts[1].type === "break-parent") {
- return {
- type: "concat",
- parts: doc.parts.slice(0, -1)
- };
- }
- return {
- type: "concat",
- parts: doc.parts.slice(0, -1).concat(stripTrailingHardline(lastPart))
- };
- }
- }
- return doc;
- }
- var docUtils = {
- isEmpty,
- willBreak,
- isLineNext,
- traverseDoc,
- mapDoc: mapDoc$1,
- propagateBreaks,
- removeLines,
- stripTrailingHardline
- };
- function flattenDoc(doc) {
- if (doc.type === "concat") {
- var res = [];
- for (var i = 0; i < doc.parts.length; ++i) {
- var doc2 = doc.parts[i];
- if (typeof doc2 !== "string" && doc2.type === "concat") {
- [].push.apply(res, flattenDoc(doc2).parts);
- } else {
- var flattened = flattenDoc(doc2);
- if (flattened !== "") {
- res.push(flattened);
- }
- }
- }
- return Object.assign({}, doc, {
- parts: res
- });
- } else if (doc.type === "if-break") {
- return Object.assign({}, doc, {
- breakContents: doc.breakContents != null ? flattenDoc(doc.breakContents) : null,
- flatContents: doc.flatContents != null ? flattenDoc(doc.flatContents) : null
- });
- } else if (doc.type === "group") {
- return Object.assign({}, doc, {
- contents: flattenDoc(doc.contents),
- expandedStates: doc.expandedStates ? doc.expandedStates.map(flattenDoc) : doc.expandedStates
- });
- } else if (doc.contents) {
- return Object.assign({}, doc, {
- contents: flattenDoc(doc.contents)
- });
- }
- return doc;
- }
- function printDoc(doc) {
- if (typeof doc === "string") {
- return JSON.stringify(doc);
- }
- if (doc.type === "line") {
- if (doc.literal) {
- return "literalline";
- }
- if (doc.hard) {
- return "hardline";
- }
- if (doc.soft) {
- return "softline";
- }
- return "line";
- }
- if (doc.type === "break-parent") {
- return "breakParent";
- }
- if (doc.type === "trim") {
- return "trim";
- }
- if (doc.type === "concat") {
- return "[" + doc.parts.map(printDoc).join(", ") + "]";
- }
- if (doc.type === "indent") {
- return "indent(" + printDoc(doc.contents) + ")";
- }
- if (doc.type === "align") {
- return doc.n === -Infinity ? "dedentToRoot(" + printDoc(doc.contents) + ")" : doc.n < 0 ? "dedent(" + printDoc(doc.contents) + ")" : doc.n.type === "root" ? "markAsRoot(" + printDoc(doc.contents) + ")" : "align(" + JSON.stringify(doc.n) + ", " + printDoc(doc.contents) + ")";
- }
- if (doc.type === "if-break") {
- return "ifBreak(" + printDoc(doc.breakContents) + (doc.flatContents ? ", " + printDoc(doc.flatContents) : "") + ")";
- }
- if (doc.type === "group") {
- if (doc.expandedStates) {
- return "conditionalGroup(" + "[" + doc.expandedStates.map(printDoc).join(",") + "])";
- }
- return (doc.break ? "wrappedGroup" : "group") + "(" + printDoc(doc.contents) + ")";
- }
- if (doc.type === "fill") {
- return "fill" + "(" + doc.parts.map(printDoc).join(", ") + ")";
- }
- if (doc.type === "line-suffix") {
- return "lineSuffix(" + printDoc(doc.contents) + ")";
- }
- if (doc.type === "line-suffix-boundary") {
- return "lineSuffixBoundary";
- }
- throw new Error("Unknown doc type " + doc.type);
- }
- var docDebug = {
- printDocToDebug: function printDocToDebug(doc) {
- return printDoc(flattenDoc(doc));
- }
- };
- var doc = {
- builders: docBuilders,
- printer: docPrinter,
- utils: docUtils,
- debug: docDebug
- };
- var mapDoc$2 = doc.utils.mapDoc;
- function isNextLineEmpty$1(text, node, options) {
- return util$1.isNextLineEmpty(text, node, options.locEnd);
- }
- function isPreviousLineEmpty$2(text, node, options) {
- return util$1.isPreviousLineEmpty(text, node, options.locStart);
- }
- function getNextNonSpaceNonCommentCharacterIndex$1(text, node, options) {
- return util$1.getNextNonSpaceNonCommentCharacterIndex(text, node, options.locEnd);
- }
- var utilShared = {
- getMaxContinuousCount: util$1.getMaxContinuousCount,
- getStringWidth: util$1.getStringWidth,
- getAlignmentSize: util$1.getAlignmentSize,
- getIndentSize: util$1.getIndentSize,
- skip: util$1.skip,
- skipWhitespace: util$1.skipWhitespace,
- skipSpaces: util$1.skipSpaces,
- skipNewline: util$1.skipNewline,
- skipToLineEnd: util$1.skipToLineEnd,
- skipEverythingButNewLine: util$1.skipEverythingButNewLine,
- skipInlineComment: util$1.skipInlineComment,
- skipTrailingComment: util$1.skipTrailingComment,
- hasNewline: util$1.hasNewline,
- hasNewlineInRange: util$1.hasNewlineInRange,
- hasSpaces: util$1.hasSpaces,
- isNextLineEmpty: isNextLineEmpty$1,
- isNextLineEmptyAfterIndex: util$1.isNextLineEmptyAfterIndex,
- isPreviousLineEmpty: isPreviousLineEmpty$2,
- getNextNonSpaceNonCommentCharacterIndex: getNextNonSpaceNonCommentCharacterIndex$1,
- mapDoc: mapDoc$2,
- // TODO: remove in 2.0, we already exposed it in docUtils
- makeString: util$1.makeString,
- addLeadingComment: util$1.addLeadingComment,
- addDanglingComment: util$1.addDanglingComment,
- addTrailingComment: util$1.addTrailingComment
- };
- var _require$$0$builders = doc.builders;
- var concat = _require$$0$builders.concat;
- var hardline = _require$$0$builders.hardline;
- var breakParent = _require$$0$builders.breakParent;
- var indent = _require$$0$builders.indent;
- var lineSuffix = _require$$0$builders.lineSuffix;
- var join = _require$$0$builders.join;
- var cursor = _require$$0$builders.cursor;
- var hasNewline = util$1.hasNewline;
- var skipNewline = util$1.skipNewline;
- var isPreviousLineEmpty = util$1.isPreviousLineEmpty;
- var addLeadingComment = utilShared.addLeadingComment;
- var addDanglingComment = utilShared.addDanglingComment;
- var addTrailingComment = utilShared.addTrailingComment;
- var childNodesCacheKey = Symbol("child-nodes");
- function getSortedChildNodes(node, options, resultArray) {
- if (!node) {
- return;
- }
- var printer = options.printer,
- locStart = options.locStart,
- locEnd = options.locEnd;
- if (resultArray) {
- if (node && printer.canAttachComment && printer.canAttachComment(node)) {
- // This reverse insertion sort almost always takes constant
- // time because we almost always (maybe always?) append the
- // nodes in order anyway.
- var i;
- for (i = resultArray.length - 1; i >= 0; --i) {
- if (locStart(resultArray[i]) <= locStart(node) && locEnd(resultArray[i]) <= locEnd(node)) {
- break;
- }
- }
- resultArray.splice(i + 1, 0, node);
- return;
- }
- } else if (node[childNodesCacheKey]) {
- return node[childNodesCacheKey];
- }
- var childNodes;
- if (printer.getCommentChildNodes) {
- childNodes = printer.getCommentChildNodes(node);
- } else if (node && typeof node === "object") {
- childNodes = Object.keys(node).filter(function (n) {
- return n !== "enclosingNode" && n !== "precedingNode" && n !== "followingNode";
- }).map(function (n) {
- return node[n];
- });
- }
- if (!childNodes) {
- return;
- }
- if (!resultArray) {
- Object.defineProperty(node, childNodesCacheKey, {
- value: resultArray = [],
- enumerable: false
- });
- }
- childNodes.forEach(function (childNode) {
- getSortedChildNodes(childNode, options, resultArray);
- });
- return resultArray;
- } // As efficiently as possible, decorate the comment object with
- // .precedingNode, .enclosingNode, and/or .followingNode properties, at
- // least one of which is guaranteed to be defined.
- function decorateComment(node, comment, options) {
- var locStart = options.locStart,
- locEnd = options.locEnd;
- var childNodes = getSortedChildNodes(node, options);
- var precedingNode;
- var followingNode; // Time to dust off the old binary search robes and wizard hat.
- var left = 0;
- var right = childNodes.length;
- while (left < right) {
- var middle = left + right >> 1;
- var child = childNodes[middle];
- if (locStart(child) - locStart(comment) <= 0 && locEnd(comment) - locEnd(child) <= 0) {
- // The comment is completely contained by this child node.
- comment.enclosingNode = child;
- decorateComment(child, comment, options);
- return; // Abandon the binary search at this level.
- }
- if (locEnd(child) - locStart(comment) <= 0) {
- // This child node falls completely before the comment.
- // Because we will never consider this node or any nodes
- // before it again, this node must be the closest preceding
- // node we have encountered so far.
- precedingNode = child;
- left = middle + 1;
- continue;
- }
- if (locEnd(comment) - locStart(child) <= 0) {
- // This child node falls completely after the comment.
- // Because we will never consider this node or any nodes after
- // it again, this node must be the closest following node we
- // have encountered so far.
- followingNode = child;
- right = middle;
- continue;
- }
- /* istanbul ignore next */
- throw new Error("Comment location overlaps with node location");
- } // We don't want comments inside of different expressions inside of the same
- // template literal to move to another expression.
- if (comment.enclosingNode && comment.enclosingNode.type === "TemplateLiteral") {
- var quasis = comment.enclosingNode.quasis;
- var commentIndex = findExpressionIndexForComment(quasis, comment, options);
- if (precedingNode && findExpressionIndexForComment(quasis, precedingNode, options) !== commentIndex) {
- precedingNode = null;
- }
- if (followingNode && findExpressionIndexForComment(quasis, followingNode, options) !== commentIndex) {
- followingNode = null;
- }
- }
- if (precedingNode) {
- comment.precedingNode = precedingNode;
- }
- if (followingNode) {
- comment.followingNode = followingNode;
- }
- }
- function attach(comments, ast, text, options) {
- if (!Array.isArray(comments)) {
- return;
- }
- var tiesToBreak = [];
- var locStart = options.locStart,
- locEnd = options.locEnd;
- comments.forEach(function (comment, i) {
- if (options.parser === "json" || options.parser === "json5" || options.parser === "__js_expression" || options.parser === "__vue_expression") {
- if (locStart(comment) - locStart(ast) <= 0) {
- addLeadingComment(ast, comment);
- return;
- }
- if (locEnd(comment) - locEnd(ast) >= 0) {
- addTrailingComment(ast, comment);
- return;
- }
- }
- decorateComment(ast, comment, options);
- var precedingNode = comment.precedingNode,
- enclosingNode = comment.enclosingNode,
- followingNode = comment.followingNode;
- var pluginHandleOwnLineComment = options.printer.handleComments && options.printer.handleComments.ownLine ? options.printer.handleComments.ownLine : function () {
- return false;
- };
- var pluginHandleEndOfLineComment = options.printer.handleComments && options.printer.handleComments.endOfLine ? options.printer.handleComments.endOfLine : function () {
- return false;
- };
- var pluginHandleRemainingComment = options.printer.handleComments && options.printer.handleComments.remaining ? options.printer.handleComments.remaining : function () {
- return false;
- };
- var isLastComment = comments.length - 1 === i;
- if (hasNewline(text, locStart(comment), {
- backwards: true
- })) {
- // If a comment exists on its own line, prefer a leading comment.
- // We also need to check if it's the first line of the file.
- if (pluginHandleOwnLineComment(comment, text, options, ast, isLastComment)) {// We're good
- } else if (followingNode) {
- // Always a leading comment.
- addLeadingComment(followingNode, comment);
- } else if (precedingNode) {
- addTrailingComment(precedingNode, comment);
- } else if (enclosingNode) {
- addDanglingComment(enclosingNode, comment);
- } else {
- // There are no nodes, let's attach it to the root of the ast
- /* istanbul ignore next */
- addDanglingComment(ast, comment);
- }
- } else if (hasNewline(text, locEnd(comment))) {
- if (pluginHandleEndOfLineComment(comment, text, options, ast, isLastComment)) {// We're good
- } else if (precedingNode) {
- // There is content before this comment on the same line, but
- // none after it, so prefer a trailing comment of the previous node.
- addTrailingComment(precedingNode, comment);
- } else if (followingNode) {
- addLeadingComment(followingNode, comment);
- } else if (enclosingNode) {
- addDanglingComment(enclosingNode, comment);
- } else {
- // There are no nodes, let's attach it to the root of the ast
- /* istanbul ignore next */
- addDanglingComment(ast, comment);
- }
- } else {
- if (pluginHandleRemainingComment(comment, text, options, ast, isLastComment)) {// We're good
- } else if (precedingNode && followingNode) {
- // Otherwise, text exists both before and after the comment on
- // the same line. If there is both a preceding and following
- // node, use a tie-breaking algorithm to determine if it should
- // be attached to the next or previous node. In the last case,
- // simply attach the right node;
- var tieCount = tiesToBreak.length;
- if (tieCount > 0) {
- var lastTie = tiesToBreak[tieCount - 1];
- if (lastTie.followingNode !== comment.followingNode) {
- breakTies(tiesToBreak, text, options);
- }
- }
- tiesToBreak.push(comment);
- } else if (precedingNode) {
- addTrailingComment(precedingNode, comment);
- } else if (followingNode) {
- addLeadingComment(followingNode, comment);
- } else if (enclosingNode) {
- addDanglingComment(enclosingNode, comment);
- } else {
- // There are no nodes, let's attach it to the root of the ast
- /* istanbul ignore next */
- addDanglingComment(ast, comment);
- }
- }
- });
- breakTies(tiesToBreak, text, options);
- comments.forEach(function (comment) {
- // These node references were useful for breaking ties, but we
- // don't need them anymore, and they create cycles in the AST that
- // may lead to infinite recursion if we don't delete them here.
- delete comment.precedingNode;
- delete comment.enclosingNode;
- delete comment.followingNode;
- });
- }
- function breakTies(tiesToBreak, text, options) {
- var tieCount = tiesToBreak.length;
- if (tieCount === 0) {
- return;
- }
- var _tiesToBreak$ = tiesToBreak[0],
- precedingNode = _tiesToBreak$.precedingNode,
- followingNode = _tiesToBreak$.followingNode;
- var gapEndPos = options.locStart(followingNode); // Iterate backwards through tiesToBreak, examining the gaps
- // between the tied comments. In order to qualify as leading, a
- // comment must be separated from followingNode by an unbroken series of
- // gaps (or other comments). Gaps should only contain whitespace or open
- // parentheses.
- var indexOfFirstLeadingComment;
- for (indexOfFirstLeadingComment = tieCount; indexOfFirstLeadingComment > 0; --indexOfFirstLeadingComment) {
- var comment = tiesToBreak[indexOfFirstLeadingComment - 1];
- assert.strictEqual(comment.precedingNode, precedingNode);
- assert.strictEqual(comment.followingNode, followingNode);
- var gap = text.slice(options.locEnd(comment), gapEndPos).trim();
- if (gap === "" || /^\(+$/.test(gap)) {
- gapEndPos = options.locStart(comment);
- } else {
- // The gap string contained something other than whitespace or open
- // parentheses.
- break;
- }
- }
- tiesToBreak.forEach(function (comment, i) {
- if (i < indexOfFirstLeadingComment) {
- addTrailingComment(precedingNode, comment);
- } else {
- addLeadingComment(followingNode, comment);
- }
- });
- tiesToBreak.length = 0;
- }
- function printComment(commentPath, options) {
- var comment = commentPath.getValue();
- comment.printed = true;
- return options.printer.printComment(commentPath, options);
- }
- function findExpressionIndexForComment(quasis, comment, options) {
- var startPos = options.locStart(comment) - 1;
- for (var i = 1; i < quasis.length; ++i) {
- if (startPos < getQuasiRange(quasis[i]).start) {
- return i - 1;
- }
- } // We haven't found it, it probably means that some of the locations are off.
- // Let's just return the first one.
- /* istanbul ignore next */
- return 0;
- }
- function getQuasiRange(expr) {
- if (expr.start !== undefined) {
- // Babel
- return {
- start: expr.start,
- end: expr.end
- };
- } // Flow
- return {
- start: expr.range[0],
- end: expr.range[1]
- };
- }
- function printLeadingComment(commentPath, print, options) {
- var comment = commentPath.getValue();
- var contents = printComment(commentPath, options);
- if (!contents) {
- return "";
- }
- var isBlock = options.printer.isBlockComment && options.printer.isBlockComment(comment); // Leading block comments should see if they need to stay on the
- // same line or not.
- if (isBlock) {
- return concat([contents, hasNewline(options.originalText, options.locEnd(comment)) ? hardline : " "]);
- }
- return concat([contents, hardline]);
- }
- function printTrailingComment(commentPath, print, options) {
- var comment = commentPath.getValue();
- var contents = printComment(commentPath, options);
- if (!contents) {
- return "";
- }
- var isBlock = options.printer.isBlockComment && options.printer.isBlockComment(comment); // We don't want the line to break
- // when the parentParentNode is a ClassDeclaration/-Expression
- // And the parentNode is in the superClass property
- var parentNode = commentPath.getNode(1);
- var parentParentNode = commentPath.getNode(2);
- var isParentSuperClass = parentParentNode && (parentParentNode.type === "ClassDeclaration" || parentParentNode.type === "ClassExpression") && parentParentNode.superClass === parentNode;
- if (hasNewline(options.originalText, options.locStart(comment), {
- backwards: true
- })) {
- // This allows comments at the end of nested structures:
- // {
- // x: 1,
- // y: 2
- // // A comment
- // }
- // Those kinds of comments are almost always leading comments, but
- // here it doesn't go "outside" the block and turns it into a
- // trailing comment for `2`. We can simulate the above by checking
- // if this a comment on its own line; normal trailing comments are
- // always at the end of another expression.
- var isLineBeforeEmpty = isPreviousLineEmpty(options.originalText, comment, options.locStart);
- return lineSuffix(concat([hardline, isLineBeforeEmpty ? hardline : "", contents]));
- } else if (isBlock || isParentSuperClass) {
- // Trailing block comments never need a newline
- return concat([" ", contents]);
- }
- return concat([lineSuffix(" " + contents), !isBlock ? breakParent : ""]);
- }
- function printDanglingComments(path$$1, options, sameIndent, filter) {
- var parts = [];
- var node = path$$1.getValue();
- if (!node || !node.comments) {
- return "";
- }
- path$$1.each(function (commentPath) {
- var comment = commentPath.getValue();
- if (comment && !comment.leading && !comment.trailing && (!filter || filter(comment))) {
- parts.push(printComment(commentPath, options));
- }
- }, "comments");
- if (parts.length === 0) {
- return "";
- }
- if (sameIndent) {
- return join(hardline, parts);
- }
- return indent(concat([hardline, join(hardline, parts)]));
- }
- function prependCursorPlaceholder(path$$1, options, printed) {
- if (path$$1.getNode() === options.cursorNode && path$$1.getValue()) {
- return concat([cursor, printed, cursor]);
- }
- return printed;
- }
- function printComments(path$$1, print, options, needsSemi) {
- var value = path$$1.getValue();
- var printed = print(path$$1);
- var comments = value && value.comments;
- if (!comments || comments.length === 0) {
- return prependCursorPlaceholder(path$$1, options, printed);
- }
- var leadingParts = [];
- var trailingParts = [needsSemi ? ";" : "", printed];
- path$$1.each(function (commentPath) {
- var comment = commentPath.getValue();
- var leading = comment.leading,
- trailing = comment.trailing;
- if (leading) {
- var contents = printLeadingComment(commentPath, print, options);
- if (!contents) {
- return;
- }
- leadingParts.push(contents);
- var text = options.originalText;
- if (hasNewline(text, skipNewline(text, options.locEnd(comment)))) {
- leadingParts.push(hardline);
- }
- } else if (trailing) {
- trailingParts.push(printTrailingComment(commentPath, print, options));
- }
- }, "comments");
- return prependCursorPlaceholder(path$$1, options, concat(leadingParts.concat(trailingParts)));
- }
- var comments = {
- attach,
- printComments,
- printDanglingComments,
- getSortedChildNodes
- };
- function FastPath(value) {
- assert.ok(this instanceof FastPath);
- this.stack = [value];
- } // The name of the current property is always the penultimate element of
- // this.stack, and always a String.
- FastPath.prototype.getName = function getName() {
- var s = this.stack;
- var len = s.length;
- if (len > 1) {
- return s[len - 2];
- } // Since the name is always a string, null is a safe sentinel value to
- // return if we do not know the name of the (root) value.
- /* istanbul ignore next */
- return null;
- }; // The value of the current property is always the final element of
- // this.stack.
- FastPath.prototype.getValue = function getValue() {
- var s = this.stack;
- return s[s.length - 1];
- };
- function getNodeHelper(path$$1, count) {
- var stackIndex = getNodeStackIndexHelper(path$$1.stack, count);
- return stackIndex === -1 ? null : path$$1.stack[stackIndex];
- }
- function getNodeStackIndexHelper(stack, count) {
- for (var i = stack.length - 1; i >= 0; i -= 2) {
- var value = stack[i];
- if (value && !Array.isArray(value) && --count < 0) {
- return i;
- }
- }
- return -1;
- }
- FastPath.prototype.getNode = function getNode(count) {
- return getNodeHelper(this, ~~count);
- };
- FastPath.prototype.getParentNode = function getParentNode(count) {
- return getNodeHelper(this, ~~count + 1);
- }; // Temporarily push properties named by string arguments given after the
- // callback function onto this.stack, then call the callback with a
- // reference to this (modified) FastPath object. Note that the stack will
- // be restored to its original state after the callback is finished, so it
- // is probably a mistake to retain a reference to the path.
- FastPath.prototype.call = function call(callback
- /*, name1, name2, ... */
- ) {
- var s = this.stack;
- var origLen = s.length;
- var value = s[origLen - 1];
- var argc = arguments.length;
- for (var i = 1; i < argc; ++i) {
- var name = arguments[i];
- value = value[name];
- s.push(name, value);
- }
- var result = callback(this);
- s.length = origLen;
- return result;
- };
- FastPath.prototype.callParent = function callParent(callback, count) {
- var stackIndex = getNodeStackIndexHelper(this.stack, ~~count + 1);
- var parentValues = this.stack.splice(stackIndex + 1);
- var result = callback(this);
- Array.prototype.push.apply(this.stack, parentValues);
- return result;
- }; // Similar to FastPath.prototype.call, except that the value obtained by
- // accessing this.getValue()[name1][name2]... should be array-like. The
- // callback will be called with a reference to this path object for each
- // element of the array.
- FastPath.prototype.each = function each(callback
- /*, name1, name2, ... */
- ) {
- var s = this.stack;
- var origLen = s.length;
- var value = s[origLen - 1];
- var argc = arguments.length;
- for (var i = 1; i < argc; ++i) {
- var name = arguments[i];
- value = value[name];
- s.push(name, value);
- }
- for (var _i = 0; _i < value.length; ++_i) {
- if (_i in value) {
- s.push(_i, value[_i]); // If the callback needs to know the value of i, call
- // path.getName(), assuming path is the parameter name.
- callback(this);
- s.length -= 2;
- }
- }
- s.length = origLen;
- }; // Similar to FastPath.prototype.each, except that the results of the
- // callback function invocations are stored in an array and returned at
- // the end of the iteration.
- FastPath.prototype.map = function map(callback
- /*, name1, name2, ... */
- ) {
- var s = this.stack;
- var origLen = s.length;
- var value = s[origLen - 1];
- var argc = arguments.length;
- for (var i = 1; i < argc; ++i) {
- var name = arguments[i];
- value = value[name];
- s.push(name, value);
- }
- var result = new Array(value.length);
- for (var _i2 = 0; _i2 < value.length; ++_i2) {
- if (_i2 in value) {
- s.push(_i2, value[_i2]);
- result[_i2] = callback(this, _i2);
- s.length -= 2;
- }
- }
- s.length = origLen;
- return result;
- };
- var fastPath = FastPath;
- var normalize$3 = options.normalize;
- function printSubtree(path$$1, print, options$$1, printAstToDoc) {
- if (options$$1.printer.embed) {
- return options$$1.printer.embed(path$$1, print, function (text, partialNextOptions) {
- return textToDoc(text, partialNextOptions, options$$1, printAstToDoc);
- }, options$$1);
- }
- }
- function textToDoc(text, partialNextOptions, parentOptions, printAstToDoc) {
- var nextOptions = normalize$3(Object.assign({}, parentOptions, partialNextOptions, {
- parentParser: parentOptions.parser,
- originalText: text
- }), {
- passThrough: true
- });
- var result = parser.parse(text, nextOptions);
- var ast = result.ast;
- text = result.text;
- var astComments = ast.comments;
- delete ast.comments;
- comments.attach(astComments, ast, text, nextOptions);
- return printAstToDoc(ast, nextOptions);
- }
- var multiparser = {
- printSubtree
- };
- var doc$2 = doc;
- var docBuilders$2 = doc$2.builders;
- var concat$3 = docBuilders$2.concat;
- var hardline$2 = docBuilders$2.hardline;
- var addAlignmentToDoc$1 = docBuilders$2.addAlignmentToDoc;
- var docUtils$2 = doc$2.utils;
- /**
- * Takes an abstract syntax tree (AST) and recursively converts it to a
- * document (series of printing primitives).
- *
- * This is done by descending down the AST recursively. The recursion
- * involves two functions that call each other:
- *
- * 1. printGenerically(), which is defined as an inner function here.
- * It basically takes care of node caching.
- * 2. callPluginPrintFunction(), which checks for some options, and
- * ultimately calls the print() function provided by the plugin.
- *
- * The plugin function will call printGenerically() again for child nodes
- * of the current node, which will do its housekeeping, then call the
- * plugin function again, and so on.
- *
- * All the while, these functions pass a "path" variable around, which
- * is a stack-like data structure (FastPath) that maintains the current
- * state of the recursion. It is called "path", because it represents
- * the path to the current node through the Abstract Syntax Tree.
- */
- function printAstToDoc(ast, options) {
- var alignmentSize = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
- var printer = options.printer;
- if (printer.preprocess) {
- ast = printer.preprocess(ast, options);
- }
- var cache = new Map();
- function printGenerically(path$$1, args) {
- var node = path$$1.getValue();
- var shouldCache = node && typeof node === "object" && args === undefined;
- if (shouldCache && cache.has(node)) {
- return cache.get(node);
- } // We let JSXElement print its comments itself because it adds () around
- // UnionTypeAnnotation has to align the child without the comments
- var res;
- if (printer.willPrintOwnComments && printer.willPrintOwnComments(path$$1)) {
- res = callPluginPrintFunction(path$$1, options, printGenerically, args);
- } else {
- // printComments will call the plugin print function and check for
- // comments to print
- res = comments.printComments(path$$1, function (p) {
- return callPluginPrintFunction(p, options, printGenerically, args);
- }, options, args && args.needsSemi);
- }
- if (shouldCache) {
- cache.set(node, res);
- }
- return res;
- }
- var doc$$2 = printGenerically(new fastPath(ast));
- if (alignmentSize > 0) {
- // Add a hardline to make the indents take effect
- // It should be removed in index.js format()
- doc$$2 = addAlignmentToDoc$1(concat$3([hardline$2, doc$$2]), alignmentSize, options.tabWidth);
- }
- docUtils$2.propagateBreaks(doc$$2);
- return doc$$2;
- }
- function callPluginPrintFunction(path$$1, options, printPath, args) {
- assert.ok(path$$1 instanceof fastPath);
- var node = path$$1.getValue();
- var printer = options.printer; // Escape hatch
- if (printer.hasPrettierIgnore && printer.hasPrettierIgnore(path$$1)) {
- return options.originalText.slice(options.locStart(node), options.locEnd(node));
- }
- if (node) {
- try {
- // Potentially switch to a different parser
- var sub = multiparser.printSubtree(path$$1, printPath, options, printAstToDoc);
- if (sub) {
- return sub;
- }
- } catch (error) {
- /* istanbul ignore if */
- if (process.env.PRETTIER_DEBUG) {
- throw error;
- } // Continue with current parser
- }
- }
- return printer.print(path$$1, options, printPath, args);
- }
- var astToDoc = printAstToDoc;
- function findSiblingAncestors(startNodeAndParents, endNodeAndParents, opts) {
- var resultStartNode = startNodeAndParents.node;
- var resultEndNode = endNodeAndParents.node;
- if (resultStartNode === resultEndNode) {
- return {
- startNode: resultStartNode,
- endNode: resultEndNode
- };
- }
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = endNodeAndParents.parentNodes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var endParent = _step.value;
- if (endParent.type !== "Program" && endParent.type !== "File" && opts.locStart(endParent) >= opts.locStart(startNodeAndParents.node)) {
- resultEndNode = endParent;
- } else {
- break;
- }
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- var _iteratorNormalCompletion2 = true;
- var _didIteratorError2 = false;
- var _iteratorError2 = undefined;
- try {
- for (var _iterator2 = startNodeAndParents.parentNodes[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
- var startParent = _step2.value;
- if (startParent.type !== "Program" && startParent.type !== "File" && opts.locEnd(startParent) <= opts.locEnd(endNodeAndParents.node)) {
- resultStartNode = startParent;
- } else {
- break;
- }
- }
- } catch (err) {
- _didIteratorError2 = true;
- _iteratorError2 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
- _iterator2.return();
- }
- } finally {
- if (_didIteratorError2) {
- throw _iteratorError2;
- }
- }
- }
- return {
- startNode: resultStartNode,
- endNode: resultEndNode
- };
- }
- function findNodeAtOffset(node, offset, options, predicate, parentNodes) {
- predicate = predicate || function () {
- return true;
- };
- parentNodes = parentNodes || [];
- var start = options.locStart(node, options.locStart);
- var end = options.locEnd(node, options.locEnd);
- if (start <= offset && offset <= end) {
- var _iteratorNormalCompletion3 = true;
- var _didIteratorError3 = false;
- var _iteratorError3 = undefined;
- try {
- for (var _iterator3 = comments.getSortedChildNodes(node, options)[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
- var childNode = _step3.value;
- var childResult = findNodeAtOffset(childNode, offset, options, predicate, [node].concat(parentNodes));
- if (childResult) {
- return childResult;
- }
- }
- } catch (err) {
- _didIteratorError3 = true;
- _iteratorError3 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
- _iterator3.return();
- }
- } finally {
- if (_didIteratorError3) {
- throw _iteratorError3;
- }
- }
- }
- if (predicate(node)) {
- return {
- node: node,
- parentNodes: parentNodes
- };
- }
- }
- } // See https://www.ecma-international.org/ecma-262/5.1/#sec-A.5
- function isSourceElement(opts, node) {
- if (node == null) {
- return false;
- } // JS and JS like to avoid repetitions
- var jsSourceElements = ["FunctionDeclaration", "BlockStatement", "BreakStatement", "ContinueStatement", "DebuggerStatement", "DoWhileStatement", "EmptyStatement", "ExpressionStatement", "ForInStatement", "ForStatement", "IfStatement", "LabeledStatement", "ReturnStatement", "SwitchStatement", "ThrowStatement", "TryStatement", "VariableDeclaration", "WhileStatement", "WithStatement", "ClassDeclaration", // ES 2015
- "ImportDeclaration", // Module
- "ExportDefaultDeclaration", // Module
- "ExportNamedDeclaration", // Module
- "ExportAllDeclaration", // Module
- "TypeAlias", // Flow
- "InterfaceDeclaration", // Flow, TypeScript
- "TypeAliasDeclaration", // TypeScript
- "ExportAssignment", // TypeScript
- "ExportDeclaration" // TypeScript
- ];
- var jsonSourceElements = ["ObjectExpression", "ArrayExpression", "StringLiteral", "NumericLiteral", "BooleanLiteral", "NullLiteral"];
- var graphqlSourceElements = ["OperationDefinition", "FragmentDefinition", "VariableDefinition", "TypeExtensionDefinition", "ObjectTypeDefinition", "FieldDefinition", "DirectiveDefinition", "EnumTypeDefinition", "EnumValueDefinition", "InputValueDefinition", "InputObjectTypeDefinition", "SchemaDefinition", "OperationTypeDefinition", "InterfaceTypeDefinition", "UnionTypeDefinition", "ScalarTypeDefinition"];
- switch (opts.parser) {
- case "flow":
- case "babel":
- case "typescript":
- return jsSourceElements.indexOf(node.type) > -1;
- case "json":
- return jsonSourceElements.indexOf(node.type) > -1;
- case "graphql":
- return graphqlSourceElements.indexOf(node.kind) > -1;
- case "vue":
- return node.tag !== "root";
- }
- return false;
- }
- function calculateRange(text, opts, ast) {
- // Contract the range so that it has non-whitespace characters at its endpoints.
- // This ensures we can format a range that doesn't end on a node.
- var rangeStringOrig = text.slice(opts.rangeStart, opts.rangeEnd);
- var startNonWhitespace = Math.max(opts.rangeStart + rangeStringOrig.search(/\S/), opts.rangeStart);
- var endNonWhitespace;
- for (endNonWhitespace = opts.rangeEnd; endNonWhitespace > opts.rangeStart; --endNonWhitespace) {
- if (text[endNonWhitespace - 1].match(/\S/)) {
- break;
- }
- }
- var startNodeAndParents = findNodeAtOffset(ast, startNonWhitespace, opts, function (node) {
- return isSourceElement(opts, node);
- });
- var endNodeAndParents = findNodeAtOffset(ast, endNonWhitespace, opts, function (node) {
- return isSourceElement(opts, node);
- });
- if (!startNodeAndParents || !endNodeAndParents) {
- return {
- rangeStart: 0,
- rangeEnd: 0
- };
- }
- var siblingAncestors = findSiblingAncestors(startNodeAndParents, endNodeAndParents, opts);
- var startNode = siblingAncestors.startNode,
- endNode = siblingAncestors.endNode;
- var rangeStart = Math.min(opts.locStart(startNode, opts.locStart), opts.locStart(endNode, opts.locStart));
- var rangeEnd = Math.max(opts.locEnd(startNode, opts.locEnd), opts.locEnd(endNode, opts.locEnd));
- return {
- rangeStart: rangeStart,
- rangeEnd: rangeEnd
- };
- }
- var rangeUtil = {
- calculateRange,
- findNodeAtOffset
- };
- var normalizeOptions = options.normalize;
- var guessEndOfLine = endOfLine.guessEndOfLine;
- var convertEndOfLineToChars = endOfLine.convertEndOfLineToChars;
- var mapDoc = doc.utils.mapDoc;
- var printDocToString = doc.printer.printDocToString;
- var printDocToDebug = doc.debug.printDocToDebug;
- var UTF8BOM = 0xfeff;
- var CURSOR = Symbol("cursor");
- var PLACEHOLDERS = {
- cursorOffset: "<<<PRETTIER_CURSOR>>>",
- rangeStart: "<<<PRETTIER_RANGE_START>>>",
- rangeEnd: "<<<PRETTIER_RANGE_END>>>"
- };
- function ensureAllCommentsPrinted(astComments) {
- if (!astComments) {
- return;
- }
- for (var i = 0; i < astComments.length; ++i) {
- if (astComments[i].value.trim() === "prettier-ignore") {
- // If there's a prettier-ignore, we're not printing that sub-tree so we
- // don't know if the comments was printed or not.
- return;
- }
- }
- astComments.forEach(function (comment) {
- if (!comment.printed) {
- throw new Error('Comment "' + comment.value.trim() + '" was not printed. Please report this error!');
- }
- delete comment.printed;
- });
- }
- function attachComments(text, ast, opts) {
- var astComments = ast.comments;
- if (astComments) {
- delete ast.comments;
- comments.attach(astComments, ast, text, opts);
- }
- ast.tokens = [];
- opts.originalText = opts.parser === "yaml" ? text : text.trimRight();
- return astComments;
- }
- function coreFormat(text, opts, addAlignmentSize) {
- if (!text || !text.trim().length) {
- return {
- formatted: "",
- cursorOffset: 0
- };
- }
- addAlignmentSize = addAlignmentSize || 0;
- var parsed = parser.parse(text, opts);
- var ast = parsed.ast;
- text = parsed.text;
- if (opts.cursorOffset >= 0) {
- var nodeResult = rangeUtil.findNodeAtOffset(ast, opts.cursorOffset, opts);
- if (nodeResult && nodeResult.node) {
- opts.cursorNode = nodeResult.node;
- }
- }
- var astComments = attachComments(text, ast, opts);
- var doc$$1 = astToDoc(ast, opts, addAlignmentSize);
- var eol = convertEndOfLineToChars(opts.endOfLine);
- var result = printDocToString(opts.endOfLine === "lf" ? doc$$1 : mapDoc(doc$$1, function (currentDoc) {
- return typeof currentDoc === "string" && currentDoc.indexOf("\n") !== -1 ? currentDoc.replace(/\n/g, eol) : currentDoc;
- }), opts);
- ensureAllCommentsPrinted(astComments); // Remove extra leading indentation as well as the added indentation after last newline
- if (addAlignmentSize > 0) {
- var trimmed = result.formatted.trim();
- if (result.cursorNodeStart !== undefined) {
- result.cursorNodeStart -= result.formatted.indexOf(trimmed);
- }
- result.formatted = trimmed + convertEndOfLineToChars(opts.endOfLine);
- }
- if (opts.cursorOffset >= 0) {
- var oldCursorNodeStart;
- var oldCursorNodeText;
- var cursorOffsetRelativeToOldCursorNode;
- var newCursorNodeStart;
- var newCursorNodeText;
- if (opts.cursorNode && result.cursorNodeText) {
- oldCursorNodeStart = opts.locStart(opts.cursorNode);
- oldCursorNodeText = text.slice(oldCursorNodeStart, opts.locEnd(opts.cursorNode));
- cursorOffsetRelativeToOldCursorNode = opts.cursorOffset - oldCursorNodeStart;
- newCursorNodeStart = result.cursorNodeStart;
- newCursorNodeText = result.cursorNodeText;
- } else {
- oldCursorNodeStart = 0;
- oldCursorNodeText = text;
- cursorOffsetRelativeToOldCursorNode = opts.cursorOffset;
- newCursorNodeStart = 0;
- newCursorNodeText = result.formatted;
- }
- if (oldCursorNodeText === newCursorNodeText) {
- return {
- formatted: result.formatted,
- cursorOffset: newCursorNodeStart + cursorOffsetRelativeToOldCursorNode
- };
- } // diff old and new cursor node texts, with a special cursor
- // symbol inserted to find out where it moves to
- var oldCursorNodeCharArray = oldCursorNodeText.split("");
- oldCursorNodeCharArray.splice(cursorOffsetRelativeToOldCursorNode, 0, CURSOR);
- var newCursorNodeCharArray = newCursorNodeText.split("");
- var cursorNodeDiff = lib.diffArrays(oldCursorNodeCharArray, newCursorNodeCharArray);
- var cursorOffset = newCursorNodeStart;
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = cursorNodeDiff[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var entry = _step.value;
- if (entry.removed) {
- if (entry.value.indexOf(CURSOR) > -1) {
- break;
- }
- } else {
- cursorOffset += entry.count;
- }
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- return {
- formatted: result.formatted,
- cursorOffset
- };
- }
- return {
- formatted: result.formatted
- };
- }
- function formatRange(text, opts) {
- var parsed = parser.parse(text, opts);
- var ast = parsed.ast;
- text = parsed.text;
- var range = rangeUtil.calculateRange(text, opts, ast);
- var rangeStart = range.rangeStart;
- var rangeEnd = range.rangeEnd;
- var rangeString = text.slice(rangeStart, rangeEnd); // Try to extend the range backwards to the beginning of the line.
- // This is so we can detect indentation correctly and restore it.
- // Use `Math.min` since `lastIndexOf` returns 0 when `rangeStart` is 0
- var rangeStart2 = Math.min(rangeStart, text.lastIndexOf("\n", rangeStart) + 1);
- var indentString = text.slice(rangeStart2, rangeStart);
- var alignmentSize = util$1.getAlignmentSize(indentString, opts.tabWidth);
- var rangeResult = coreFormat(rangeString, Object.assign({}, opts, {
- rangeStart: 0,
- rangeEnd: Infinity,
- printWidth: opts.printWidth - alignmentSize,
- // track the cursor offset only if it's within our range
- cursorOffset: opts.cursorOffset >= rangeStart && opts.cursorOffset < rangeEnd ? opts.cursorOffset - rangeStart : -1
- }), alignmentSize); // Since the range contracts to avoid trailing whitespace,
- // we need to remove the newline that was inserted by the `format` call.
- var rangeTrimmed = rangeResult.formatted.trimRight();
- var rangeLeft = text.slice(0, rangeStart);
- var rangeRight = text.slice(rangeEnd);
- var cursorOffset = opts.cursorOffset;
- if (opts.cursorOffset >= rangeEnd) {
- // handle the case where the cursor was past the end of the range
- cursorOffset = opts.cursorOffset - rangeEnd + (rangeStart + rangeTrimmed.length);
- } else if (rangeResult.cursorOffset !== undefined) {
- // handle the case where the cursor was in the range
- cursorOffset = rangeResult.cursorOffset + rangeStart;
- } // keep the cursor as it was if it was before the start of the range
- var formatted;
- if (opts.endOfLine === "lf") {
- formatted = rangeLeft + rangeTrimmed + rangeRight;
- } else {
- var eol = convertEndOfLineToChars(opts.endOfLine);
- if (cursorOffset >= 0) {
- var parts = [rangeLeft, rangeTrimmed, rangeRight];
- var partIndex = 0;
- var partOffset = cursorOffset;
- while (partIndex < parts.length) {
- var part = parts[partIndex];
- if (partOffset < part.length) {
- parts[partIndex] = parts[partIndex].slice(0, partOffset) + PLACEHOLDERS.cursorOffset + parts[partIndex].slice(partOffset);
- break;
- }
- partIndex++;
- partOffset -= part.length;
- }
- var newRangeLeft = parts[0],
- newRangeTrimmed = parts[1],
- newRangeRight = parts[2];
- formatted = (newRangeLeft.replace(/\n/g, eol) + newRangeTrimmed + newRangeRight.replace(/\n/g, eol)).replace(PLACEHOLDERS.cursorOffset, function (_, index) {
- cursorOffset = index;
- return "";
- });
- } else {
- formatted = rangeLeft.replace(/\n/g, eol) + rangeTrimmed + rangeRight.replace(/\n/g, eol);
- }
- }
- return {
- formatted,
- cursorOffset
- };
- }
- function format(text, opts) {
- var selectedParser = parser.resolveParser(opts);
- var hasPragma = !selectedParser.hasPragma || selectedParser.hasPragma(text);
- if (opts.requirePragma && !hasPragma) {
- return {
- formatted: text
- };
- }
- if (opts.endOfLine === "auto") {
- opts.endOfLine = guessEndOfLine(text);
- }
- var hasCursor = opts.cursorOffset >= 0;
- var hasRangeStart = opts.rangeStart > 0;
- var hasRangeEnd = opts.rangeEnd < text.length; // get rid of CR/CRLF parsing
- if (text.indexOf("\r") !== -1) {
- var offsetKeys = [hasCursor && "cursorOffset", hasRangeStart && "rangeStart", hasRangeEnd && "rangeEnd"].filter(Boolean).sort(function (aKey, bKey) {
- return opts[aKey] - opts[bKey];
- });
- for (var i = offsetKeys.length - 1; i >= 0; i--) {
- var key = offsetKeys[i];
- text = text.slice(0, opts[key]) + PLACEHOLDERS[key] + text.slice(opts[key]);
- }
- text = text.replace(/\r\n?/g, "\n");
- var _loop = function _loop(_i) {
- var key = offsetKeys[_i];
- text = text.replace(PLACEHOLDERS[key], function (_, index) {
- opts[key] = index;
- return "";
- });
- };
- for (var _i = 0; _i < offsetKeys.length; _i++) {
- _loop(_i);
- }
- }
- var hasUnicodeBOM = text.charCodeAt(0) === UTF8BOM;
- if (hasUnicodeBOM) {
- text = text.substring(1);
- if (hasCursor) {
- opts.cursorOffset++;
- }
- if (hasRangeStart) {
- opts.rangeStart++;
- }
- if (hasRangeEnd) {
- opts.rangeEnd++;
- }
- }
- if (!hasCursor) {
- opts.cursorOffset = -1;
- }
- if (opts.rangeStart < 0) {
- opts.rangeStart = 0;
- }
- if (opts.rangeEnd > text.length) {
- opts.rangeEnd = text.length;
- }
- var result = hasRangeStart || hasRangeEnd ? formatRange(text, opts) : coreFormat(opts.insertPragma && opts.printer.insertPragma && !hasPragma ? opts.printer.insertPragma(text) : text, opts);
- if (hasUnicodeBOM) {
- result.formatted = String.fromCharCode(UTF8BOM) + result.formatted;
- if (hasCursor) {
- result.cursorOffset++;
- }
- }
- return result;
- }
- var core = {
- formatWithCursor(text, opts) {
- opts = normalizeOptions(opts);
- return format(text, opts);
- },
- parse(text, opts, massage) {
- opts = normalizeOptions(opts);
- if (text.indexOf("\r") !== -1) {
- text = text.replace(/\r\n?/g, "\n");
- }
- var parsed = parser.parse(text, opts);
- if (massage) {
- parsed.ast = massageAst(parsed.ast, opts);
- }
- return parsed;
- },
- formatAST(ast, opts) {
- opts = normalizeOptions(opts);
- var doc$$1 = astToDoc(ast, opts);
- return printDocToString(doc$$1, opts);
- },
- // Doesn't handle shebang for now
- formatDoc(doc$$1, opts) {
- var debug = printDocToDebug(doc$$1);
- opts = normalizeOptions(Object.assign({}, opts, {
- parser: "babel"
- }));
- return format(debug, opts).formatted;
- },
- printToDoc(text, opts) {
- opts = normalizeOptions(opts);
- var parsed = parser.parse(text, opts);
- var ast = parsed.ast;
- text = parsed.text;
- attachComments(text, ast, opts);
- return astToDoc(ast, opts);
- },
- printDocToString(doc$$1, opts) {
- return printDocToString(doc$$1, normalizeOptions(opts));
- }
- };
- var _createClass$1 = function () {
- function defineProperties(target, props) {
- for (var i = 0; i < props.length; i++) {
- var descriptor = props[i];
- descriptor.enumerable = descriptor.enumerable || false;
- descriptor.configurable = true;
- if ("value" in descriptor) descriptor.writable = true;
- Object.defineProperty(target, descriptor.key, descriptor);
- }
- }
- return function (Constructor, protoProps, staticProps) {
- if (protoProps) defineProperties(Constructor.prototype, protoProps);
- if (staticProps) defineProperties(Constructor, staticProps);
- return Constructor;
- };
- }();
- function _classCallCheck$1(instance, Constructor) {
- if (!(instance instanceof Constructor)) {
- throw new TypeError("Cannot call a class as a function");
- }
- }
- var ignore = function ignore() {
- return new IgnoreBase();
- }; // A simple implementation of make-array
- function make_array(subject) {
- return Array.isArray(subject) ? subject : [subject];
- }
- var REGEX_BLANK_LINE = /^\s+$/;
- var REGEX_LEADING_EXCAPED_EXCLAMATION = /^\\\!/;
- var REGEX_LEADING_EXCAPED_HASH = /^\\#/;
- var SLASH = '/';
- var KEY_IGNORE = typeof Symbol !== 'undefined' ? Symbol.for('node-ignore')
- /* istanbul ignore next */
- : 'node-ignore';
- var IgnoreBase = function () {
- function IgnoreBase() {
- _classCallCheck$1(this, IgnoreBase);
- this._rules = [];
- this[KEY_IGNORE] = true;
- this._initCache();
- }
- _createClass$1(IgnoreBase, [{
- key: '_initCache',
- value: function _initCache() {
- this._cache = {};
- } // @param {Array.<string>|string|Ignore} pattern
- }, {
- key: 'add',
- value: function add(pattern) {
- this._added = false;
- if (typeof pattern === 'string') {
- pattern = pattern.split(/\r?\n/g);
- }
- make_array(pattern).forEach(this._addPattern, this); // Some rules have just added to the ignore,
- // making the behavior changed.
- if (this._added) {
- this._initCache();
- }
- return this;
- } // legacy
- }, {
- key: 'addPattern',
- value: function addPattern(pattern) {
- return this.add(pattern);
- }
- }, {
- key: '_addPattern',
- value: function _addPattern(pattern) {
- // #32
- if (pattern && pattern[KEY_IGNORE]) {
- this._rules = this._rules.concat(pattern._rules);
- this._added = true;
- return;
- }
- if (this._checkPattern(pattern)) {
- var rule = this._createRule(pattern);
- this._added = true;
- this._rules.push(rule);
- }
- }
- }, {
- key: '_checkPattern',
- value: function _checkPattern(pattern) {
- // > A blank line matches no files, so it can serve as a separator for readability.
- return pattern && typeof pattern === 'string' && !REGEX_BLANK_LINE.test(pattern) // > A line starting with # serves as a comment.
- && pattern.indexOf('#') !== 0;
- }
- }, {
- key: 'filter',
- value: function filter(paths) {
- var _this = this;
- return make_array(paths).filter(function (path$$1) {
- return _this._filter(path$$1);
- });
- }
- }, {
- key: 'createFilter',
- value: function createFilter() {
- var _this2 = this;
- return function (path$$1) {
- return _this2._filter(path$$1);
- };
- }
- }, {
- key: 'ignores',
- value: function ignores(path$$1) {
- return !this._filter(path$$1);
- }
- }, {
- key: '_createRule',
- value: function _createRule(pattern) {
- var origin = pattern;
- var negative = false; // > An optional prefix "!" which negates the pattern;
- if (pattern.indexOf('!') === 0) {
- negative = true;
- pattern = pattern.substr(1);
- }
- pattern = pattern // > Put a backslash ("\") in front of the first "!" for patterns that begin with a literal "!", for example, `"\!important!.txt"`.
- .replace(REGEX_LEADING_EXCAPED_EXCLAMATION, '!') // > Put a backslash ("\") in front of the first hash for patterns that begin with a hash.
- .replace(REGEX_LEADING_EXCAPED_HASH, '#');
- var regex = make_regex(pattern, negative);
- return {
- origin: origin,
- pattern: pattern,
- negative: negative,
- regex: regex
- };
- } // @returns `Boolean` true if the `path` is NOT ignored
- }, {
- key: '_filter',
- value: function _filter(path$$1, slices) {
- if (!path$$1) {
- return false;
- }
- if (path$$1 in this._cache) {
- return this._cache[path$$1];
- }
- if (!slices) {
- // path/to/a.js
- // ['path', 'to', 'a.js']
- slices = path$$1.split(SLASH);
- }
- slices.pop();
- return this._cache[path$$1] = slices.length // > It is not possible to re-include a file if a parent directory of that file is excluded.
- // If the path contains a parent directory, check the parent first
- ? this._filter(slices.join(SLASH) + SLASH, slices) && this._test(path$$1) // Or only test the path
- : this._test(path$$1);
- } // @returns {Boolean} true if a file is NOT ignored
- }, {
- key: '_test',
- value: function _test(path$$1) {
- // Explicitly define variable type by setting matched to `0`
- var matched = 0;
- this._rules.forEach(function (rule) {
- // if matched = true, then we only test negative rules
- // if matched = false, then we test non-negative rules
- if (!(matched ^ rule.negative)) {
- matched = rule.negative ^ rule.regex.test(path$$1);
- }
- });
- return !matched;
- }
- }]);
- return IgnoreBase;
- }(); // > If the pattern ends with a slash,
- // > it is removed for the purpose of the following description,
- // > but it would only find a match with a directory.
- // > In other words, foo/ will match a directory foo and paths underneath it,
- // > but will not match a regular file or a symbolic link foo
- // > (this is consistent with the way how pathspec works in general in Git).
- // '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`'
- // -> ignore-rules will not deal with it, because it costs extra `fs.stat` call
- // you could use option `mark: true` with `glob`
- // '`foo/`' should not continue with the '`..`'
- var DEFAULT_REPLACER_PREFIX = [// > Trailing spaces are ignored unless they are quoted with backslash ("\")
- [// (a\ ) -> (a )
- // (a ) -> (a)
- // (a \ ) -> (a )
- /\\?\s+$/, function (match) {
- return match.indexOf('\\') === 0 ? ' ' : '';
- }], // replace (\ ) with ' '
- [/\\\s/g, function () {
- return ' ';
- }], // Escape metacharacters
- // which is written down by users but means special for regular expressions.
- // > There are 12 characters with special meanings:
- // > - the backslash \,
- // > - the caret ^,
- // > - the dollar sign $,
- // > - the period or dot .,
- // > - the vertical bar or pipe symbol |,
- // > - the question mark ?,
- // > - the asterisk or star *,
- // > - the plus sign +,
- // > - the opening parenthesis (,
- // > - the closing parenthesis ),
- // > - and the opening square bracket [,
- // > - the opening curly brace {,
- // > These special characters are often called "metacharacters".
- [/[\\\^$.|?*+()\[{]/g, function (match) {
- return '\\' + match;
- }], // leading slash
- [// > A leading slash matches the beginning of the pathname.
- // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c".
- // A leading slash matches the beginning of the pathname
- /^\//, function () {
- return '^';
- }], // replace special metacharacter slash after the leading slash
- [/\//g, function () {
- return '\\/';
- }], [// > A leading "**" followed by a slash means match in all directories.
- // > For example, "**/foo" matches file or directory "foo" anywhere,
- // > the same as pattern "foo".
- // > "**/foo/bar" matches file or directory "bar" anywhere that is directly under directory "foo".
- // Notice that the '*'s have been replaced as '\\*'
- /^\^*\\\*\\\*\\\//, // '**/foo' <-> 'foo'
- function () {
- return '^(?:.*\\/)?';
- }]];
- var DEFAULT_REPLACER_SUFFIX = [// starting
- [// there will be no leading '/' (which has been replaced by section "leading slash")
- // If starts with '**', adding a '^' to the regular expression also works
- /^(?=[^\^])/, function () {
- return !/\/(?!$)/.test(this) // > If the pattern does not contain a slash /, Git treats it as a shell glob pattern
- // Actually, if there is only a trailing slash, git also treats it as a shell glob pattern
- ? '(?:^|\\/)' // > Otherwise, Git treats the pattern as a shell glob suitable for consumption by fnmatch(3)
- : '^';
- }], // two globstars
- [// Use lookahead assertions so that we could match more than one `'/**'`
- /\\\/\\\*\\\*(?=\\\/|$)/g, // Zero, one or several directories
- // should not use '*', or it will be replaced by the next replacer
- // Check if it is not the last `'/**'`
- function (match, index, str) {
- return index + 6 < str.length // case: /**/
- // > A slash followed by two consecutive asterisks then a slash matches zero or more directories.
- // > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on.
- // '/**/'
- ? '(?:\\/[^\\/]+)*' // case: /**
- // > A trailing `"/**"` matches everything inside.
- // #21: everything inside but it should not include the current folder
- : '\\/.+';
- }], // intermediate wildcards
- [// Never replace escaped '*'
- // ignore rule '\*' will match the path '*'
- // 'abc.*/' -> go
- // 'abc.*' -> skip this rule
- /(^|[^\\]+)\\\*(?=.+)/g, // '*.js' matches '.js'
- // '*.js' doesn't match 'abc'
- function (match, p1) {
- return p1 + '[^\\/]*';
- }], // trailing wildcard
- [/(\^|\\\/)?\\\*$/, function (match, p1) {
- return (p1 // '\^':
- // '/*' does not match ''
- // '/*' does not match everything
- // '\\\/':
- // 'abc/*' does not match 'abc/'
- ? p1 + '[^/]+' // 'a*' matches 'a'
- // 'a*' matches 'aa'
- : '[^/]*') + '(?=$|\\/$)';
- }], [// unescape
- /\\\\\\/g, function () {
- return '\\';
- }]];
- var POSITIVE_REPLACERS = [].concat(DEFAULT_REPLACER_PREFIX, [// 'f'
- // matches
- // - /f(end)
- // - /f/
- // - (start)f(end)
- // - (start)f/
- // doesn't match
- // - oof
- // - foo
- // pseudo:
- // -> (^|/)f(/|$)
- // ending
- [// 'js' will not match 'js.'
- // 'ab' will not match 'abc'
- /(?:[^*\/])$/, // 'js*' will not match 'a.js'
- // 'js/' will not match 'a.js'
- // 'js' will match 'a.js' and 'a.js/'
- function (match) {
- return match + '(?=$|\\/)';
- }]], DEFAULT_REPLACER_SUFFIX);
- var NEGATIVE_REPLACERS = [].concat(DEFAULT_REPLACER_PREFIX, [// #24
- // The MISSING rule of [gitignore docs](https://git-scm.com/docs/gitignore)
- // A negative pattern without a trailing wildcard should not
- // re-include the things inside that directory.
- // eg:
- // ['node_modules/*', '!node_modules']
- // should ignore `node_modules/a.js`
- [/(?:[^*\/])$/, function (match) {
- return match + '(?=$|\\/$)';
- }]], DEFAULT_REPLACER_SUFFIX); // A simple cache, because an ignore rule only has only one certain meaning
- var cache = {}; // @param {pattern}
- function make_regex(pattern, negative) {
- var r = cache[pattern];
- if (r) {
- return r;
- }
- var replacers = negative ? NEGATIVE_REPLACERS : POSITIVE_REPLACERS;
- var source = replacers.reduce(function (prev, current) {
- return prev.replace(current[0], current[1].bind(pattern));
- }, pattern);
- return cache[pattern] = new RegExp(source, 'i');
- } // Windows
- // --------------------------------------------------------------
- /* istanbul ignore if */
- if ( // Detect `process` so that it can run in browsers.
- typeof process !== 'undefined' && (process.env && process.env.IGNORE_TEST_WIN32 || process.platform === 'win32')) {
- var filter = IgnoreBase.prototype._filter;
- var make_posix = function make_posix(str) {
- return /^\\\\\?\\/.test(str) || /[^\x00-\x80]+/.test(str) ? str : str.replace(/\\/g, '/');
- };
- IgnoreBase.prototype._filter = function (path$$1, slices) {
- path$$1 = make_posix(path$$1);
- return filter.call(this, path$$1, slices);
- };
- }
- /**
- * @param {string} filename
- * @returns {Promise<null | string>}
- */
- function getFileContentOrNull(filename) {
- return new Promise(function (resolve, reject) {
- fs.readFile(filename, "utf8", function (error, data) {
- if (error && error.code !== "ENOENT") {
- reject(createError(filename, error));
- } else {
- resolve(error ? null : data);
- }
- });
- });
- }
- /**
- * @param {string} filename
- * @returns {null | string}
- */
- getFileContentOrNull.sync = function (filename) {
- try {
- return fs.readFileSync(filename, "utf8");
- } catch (error) {
- if (error && error.code === "ENOENT") {
- return null;
- }
- throw createError(filename, error);
- }
- };
- function createError(filename, error) {
- return new Error(`Unable to read ${filename}: ${error.message}`);
- }
- var getFileContentOrNull_1 = getFileContentOrNull;
- /**
- * @param {undefined | string} ignorePath
- * @param {undefined | boolean} withNodeModules
- */
- function createIgnorer(ignorePath, withNodeModules) {
- return (!ignorePath ? Promise.resolve(null) : getFileContentOrNull_1(path.resolve(ignorePath))).then(function (ignoreContent) {
- return _createIgnorer(ignoreContent, withNodeModules);
- });
- }
- /**
- * @param {undefined | string} ignorePath
- * @param {undefined | boolean} withNodeModules
- */
- createIgnorer.sync = function (ignorePath, withNodeModules) {
- var ignoreContent = !ignorePath ? null : getFileContentOrNull_1.sync(path.resolve(ignorePath));
- return _createIgnorer(ignoreContent, withNodeModules);
- };
- /**
- * @param {null | string} ignoreContent
- * @param {undefined | boolean} withNodeModules
- */
- function _createIgnorer(ignoreContent, withNodeModules) {
- var ignorer = ignore().add(ignoreContent || "");
- if (!withNodeModules) {
- ignorer.add("node_modules");
- }
- return ignorer;
- }
- var createIgnorer_1 = createIgnorer;
- /**
- * @typedef {{ ignorePath?: string, withNodeModules?: boolean, plugins: object }} FileInfoOptions
- * @typedef {{ ignored: boolean, inferredParser: string | null }} FileInfoResult
- */
- /**
- * @param {string} filePath
- * @param {FileInfoOptions} opts
- * @returns {Promise<FileInfoResult>}
- *
- * Please note that prettier.getFileInfo() expects opts.plugins to be an array of paths,
- * not an object. A transformation from this array to an object is automatically done
- * internally by the method wrapper. See withPlugins() in index.js.
- */
- function getFileInfo(filePath, opts) {
- return createIgnorer_1(opts.ignorePath, opts.withNodeModules).then(function (ignorer) {
- return _getFileInfo(ignorer, normalizeFilePath(filePath, opts.ignorePath), opts.plugins);
- });
- }
- /**
- * @param {string} filePath
- * @param {FileInfoOptions} opts
- * @returns {FileInfoResult}
- */
- getFileInfo.sync = function (filePath, opts) {
- var ignorer = createIgnorer_1.sync(opts.ignorePath, opts.withNodeModules);
- return _getFileInfo(ignorer, normalizeFilePath(filePath, opts.ignorePath), opts.plugins);
- };
- function _getFileInfo(ignorer, filePath, plugins) {
- var ignored = ignorer.ignores(filePath);
- var inferredParser = options.inferParser(filePath, plugins) || null;
- return {
- ignored,
- inferredParser
- };
- }
- function normalizeFilePath(filePath, ignorePath) {
- return ignorePath ? path.relative(path.dirname(ignorePath), filePath) : filePath;
- }
- var getFileInfo_1 = getFileInfo;
- var lodash_uniqby = createCommonjsModule(function (module, exports) {
- /**
- * lodash (Custom Build) <https://lodash.com/>
- * Build: `lodash modularize exports="npm" -o ./`
- * Copyright jQuery Foundation and other contributors <https://jquery.org/>
- * Released under MIT license <https://lodash.com/license>
- * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
- * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
- */
- /** Used as the size to enable large array optimizations. */
- var LARGE_ARRAY_SIZE = 200;
- /** Used as the `TypeError` message for "Functions" methods. */
- var FUNC_ERROR_TEXT = 'Expected a function';
- /** Used to stand-in for `undefined` hash values. */
- var HASH_UNDEFINED = '__lodash_hash_undefined__';
- /** Used to compose bitmasks for comparison styles. */
- var UNORDERED_COMPARE_FLAG = 1,
- PARTIAL_COMPARE_FLAG = 2;
- /** Used as references for various `Number` constants. */
- var INFINITY = 1 / 0,
- MAX_SAFE_INTEGER = 9007199254740991;
- /** `Object#toString` result references. */
- var argsTag = '[object Arguments]',
- arrayTag = '[object Array]',
- boolTag = '[object Boolean]',
- dateTag = '[object Date]',
- errorTag = '[object Error]',
- funcTag = '[object Function]',
- genTag = '[object GeneratorFunction]',
- mapTag = '[object Map]',
- numberTag = '[object Number]',
- objectTag = '[object Object]',
- promiseTag = '[object Promise]',
- regexpTag = '[object RegExp]',
- setTag = '[object Set]',
- stringTag = '[object String]',
- symbolTag = '[object Symbol]',
- weakMapTag = '[object WeakMap]';
- var arrayBufferTag = '[object ArrayBuffer]',
- dataViewTag = '[object DataView]',
- float32Tag = '[object Float32Array]',
- float64Tag = '[object Float64Array]',
- int8Tag = '[object Int8Array]',
- int16Tag = '[object Int16Array]',
- int32Tag = '[object Int32Array]',
- uint8Tag = '[object Uint8Array]',
- uint8ClampedTag = '[object Uint8ClampedArray]',
- uint16Tag = '[object Uint16Array]',
- uint32Tag = '[object Uint32Array]';
- /** Used to match property names within property paths. */
- var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
- reIsPlainProp = /^\w*$/,
- reLeadingDot = /^\./,
- rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
- /**
- * Used to match `RegExp`
- * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
- */
- var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
- /** Used to match backslashes in property paths. */
- var reEscapeChar = /\\(\\)?/g;
- /** Used to detect host constructors (Safari). */
- var reIsHostCtor = /^\[object .+?Constructor\]$/;
- /** Used to detect unsigned integer values. */
- var reIsUint = /^(?:0|[1-9]\d*)$/;
- /** Used to identify `toStringTag` values of typed arrays. */
- var typedArrayTags = {};
- typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true;
- typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;
- /** Detect free variable `global` from Node.js. */
- var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
- /** Detect free variable `self`. */
- var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
- /** Used as a reference to the global object. */
- var root = freeGlobal || freeSelf || Function('return this')();
- /** Detect free variable `exports`. */
- var freeExports = 'object' == 'object' && exports && !exports.nodeType && exports;
- /** Detect free variable `module`. */
- var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
- /** Detect the popular CommonJS extension `module.exports`. */
- var moduleExports = freeModule && freeModule.exports === freeExports;
- /** Detect free variable `process` from Node.js. */
- var freeProcess = moduleExports && freeGlobal.process;
- /** Used to access faster Node.js helpers. */
- var nodeUtil = function () {
- try {
- return freeProcess && freeProcess.binding('util');
- } catch (e) {}
- }();
- /* Node.js helper references. */
- var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
- /**
- * A specialized version of `_.includes` for arrays without support for
- * specifying an index to search from.
- *
- * @private
- * @param {Array} [array] The array to inspect.
- * @param {*} target The value to search for.
- * @returns {boolean} Returns `true` if `target` is found, else `false`.
- */
- function arrayIncludes(array, value) {
- var length = array ? array.length : 0;
- return !!length && baseIndexOf(array, value, 0) > -1;
- }
- /**
- * This function is like `arrayIncludes` except that it accepts a comparator.
- *
- * @private
- * @param {Array} [array] The array to inspect.
- * @param {*} target The value to search for.
- * @param {Function} comparator The comparator invoked per element.
- * @returns {boolean} Returns `true` if `target` is found, else `false`.
- */
- function arrayIncludesWith(array, value, comparator) {
- var index = -1,
- length = array ? array.length : 0;
- while (++index < length) {
- if (comparator(value, array[index])) {
- return true;
- }
- }
- return false;
- }
- /**
- * A specialized version of `_.some` for arrays without support for iteratee
- * shorthands.
- *
- * @private
- * @param {Array} [array] The array to iterate over.
- * @param {Function} predicate The function invoked per iteration.
- * @returns {boolean} Returns `true` if any element passes the predicate check,
- * else `false`.
- */
- function arraySome(array, predicate) {
- var index = -1,
- length = array ? array.length : 0;
- while (++index < length) {
- if (predicate(array[index], index, array)) {
- return true;
- }
- }
- return false;
- }
- /**
- * The base implementation of `_.findIndex` and `_.findLastIndex` without
- * support for iteratee shorthands.
- *
- * @private
- * @param {Array} array The array to inspect.
- * @param {Function} predicate The function invoked per iteration.
- * @param {number} fromIndex The index to search from.
- * @param {boolean} [fromRight] Specify iterating from right to left.
- * @returns {number} Returns the index of the matched value, else `-1`.
- */
- function baseFindIndex(array, predicate, fromIndex, fromRight) {
- var length = array.length,
- index = fromIndex + (fromRight ? 1 : -1);
- while (fromRight ? index-- : ++index < length) {
- if (predicate(array[index], index, array)) {
- return index;
- }
- }
- return -1;
- }
- /**
- * The base implementation of `_.indexOf` without `fromIndex` bounds checks.
- *
- * @private
- * @param {Array} array The array to inspect.
- * @param {*} value The value to search for.
- * @param {number} fromIndex The index to search from.
- * @returns {number} Returns the index of the matched value, else `-1`.
- */
- function baseIndexOf(array, value, fromIndex) {
- if (value !== value) {
- return baseFindIndex(array, baseIsNaN, fromIndex);
- }
- var index = fromIndex - 1,
- length = array.length;
- while (++index < length) {
- if (array[index] === value) {
- return index;
- }
- }
- return -1;
- }
- /**
- * The base implementation of `_.isNaN` without support for number objects.
- *
- * @private
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
- */
- function baseIsNaN(value) {
- return value !== value;
- }
- /**
- * The base implementation of `_.property` without support for deep paths.
- *
- * @private
- * @param {string} key The key of the property to get.
- * @returns {Function} Returns the new accessor function.
- */
- function baseProperty(key) {
- return function (object) {
- return object == null ? undefined : object[key];
- };
- }
- /**
- * The base implementation of `_.times` without support for iteratee shorthands
- * or max array length checks.
- *
- * @private
- * @param {number} n The number of times to invoke `iteratee`.
- * @param {Function} iteratee The function invoked per iteration.
- * @returns {Array} Returns the array of results.
- */
- function baseTimes(n, iteratee) {
- var index = -1,
- result = Array(n);
- while (++index < n) {
- result[index] = iteratee(index);
- }
- return result;
- }
- /**
- * The base implementation of `_.unary` without support for storing metadata.
- *
- * @private
- * @param {Function} func The function to cap arguments for.
- * @returns {Function} Returns the new capped function.
- */
- function baseUnary(func) {
- return function (value) {
- return func(value);
- };
- }
- /**
- * Checks if a cache value for `key` exists.
- *
- * @private
- * @param {Object} cache The cache to query.
- * @param {string} key The key of the entry to check.
- * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
- */
- function cacheHas(cache, key) {
- return cache.has(key);
- }
- /**
- * Gets the value at `key` of `object`.
- *
- * @private
- * @param {Object} [object] The object to query.
- * @param {string} key The key of the property to get.
- * @returns {*} Returns the property value.
- */
- function getValue(object, key) {
- return object == null ? undefined : object[key];
- }
- /**
- * Checks if `value` is a host object in IE < 9.
- *
- * @private
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a host object, else `false`.
- */
- function isHostObject(value) {
- // Many host objects are `Object` objects that can coerce to strings
- // despite having improperly defined `toString` methods.
- var result = false;
- if (value != null && typeof value.toString != 'function') {
- try {
- result = !!(value + '');
- } catch (e) {}
- }
- return result;
- }
- /**
- * Converts `map` to its key-value pairs.
- *
- * @private
- * @param {Object} map The map to convert.
- * @returns {Array} Returns the key-value pairs.
- */
- function mapToArray(map) {
- var index = -1,
- result = Array(map.size);
- map.forEach(function (value, key) {
- result[++index] = [key, value];
- });
- return result;
- }
- /**
- * Creates a unary function that invokes `func` with its argument transformed.
- *
- * @private
- * @param {Function} func The function to wrap.
- * @param {Function} transform The argument transform.
- * @returns {Function} Returns the new function.
- */
- function overArg(func, transform) {
- return function (arg) {
- return func(transform(arg));
- };
- }
- /**
- * Converts `set` to an array of its values.
- *
- * @private
- * @param {Object} set The set to convert.
- * @returns {Array} Returns the values.
- */
- function setToArray(set) {
- var index = -1,
- result = Array(set.size);
- set.forEach(function (value) {
- result[++index] = value;
- });
- return result;
- }
- /** Used for built-in method references. */
- var arrayProto = Array.prototype,
- funcProto = Function.prototype,
- objectProto = Object.prototype;
- /** Used to detect overreaching core-js shims. */
- var coreJsData = root['__core-js_shared__'];
- /** Used to detect methods masquerading as native. */
- var maskSrcKey = function () {
- var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
- return uid ? 'Symbol(src)_1.' + uid : '';
- }();
- /** Used to resolve the decompiled source of functions. */
- var funcToString = funcProto.toString;
- /** Used to check objects for own properties. */
- var hasOwnProperty = objectProto.hasOwnProperty;
- /**
- * Used to resolve the
- * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
- * of values.
- */
- var objectToString = objectProto.toString;
- /** Used to detect if a method is native. */
- var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&').replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$');
- /** Built-in value references. */
- var Symbol = root.Symbol,
- Uint8Array = root.Uint8Array,
- propertyIsEnumerable = objectProto.propertyIsEnumerable,
- splice = arrayProto.splice;
- /* Built-in method references for those with the same name as other `lodash` methods. */
- var nativeKeys = overArg(Object.keys, Object);
- /* Built-in method references that are verified to be native. */
- var DataView = getNative(root, 'DataView'),
- Map = getNative(root, 'Map'),
- Promise = getNative(root, 'Promise'),
- Set = getNative(root, 'Set'),
- WeakMap = getNative(root, 'WeakMap'),
- nativeCreate = getNative(Object, 'create');
- /** Used to detect maps, sets, and weakmaps. */
- var dataViewCtorString = toSource(DataView),
- mapCtorString = toSource(Map),
- promiseCtorString = toSource(Promise),
- setCtorString = toSource(Set),
- weakMapCtorString = toSource(WeakMap);
- /** Used to convert symbols to primitives and strings. */
- var symbolProto = Symbol ? Symbol.prototype : undefined,
- symbolValueOf = symbolProto ? symbolProto.valueOf : undefined,
- symbolToString = symbolProto ? symbolProto.toString : undefined;
- /**
- * Creates a hash object.
- *
- * @private
- * @constructor
- * @param {Array} [entries] The key-value pairs to cache.
- */
- function Hash(entries) {
- var index = -1,
- length = entries ? entries.length : 0;
- this.clear();
- while (++index < length) {
- var entry = entries[index];
- this.set(entry[0], entry[1]);
- }
- }
- /**
- * Removes all key-value entries from the hash.
- *
- * @private
- * @name clear
- * @memberOf Hash
- */
- function hashClear() {
- this.__data__ = nativeCreate ? nativeCreate(null) : {};
- }
- /**
- * Removes `key` and its value from the hash.
- *
- * @private
- * @name delete
- * @memberOf Hash
- * @param {Object} hash The hash to modify.
- * @param {string} key The key of the value to remove.
- * @returns {boolean} Returns `true` if the entry was removed, else `false`.
- */
- function hashDelete(key) {
- return this.has(key) && delete this.__data__[key];
- }
- /**
- * Gets the hash value for `key`.
- *
- * @private
- * @name get
- * @memberOf Hash
- * @param {string} key The key of the value to get.
- * @returns {*} Returns the entry value.
- */
- function hashGet(key) {
- var data = this.__data__;
- if (nativeCreate) {
- var result = data[key];
- return result === HASH_UNDEFINED ? undefined : result;
- }
- return hasOwnProperty.call(data, key) ? data[key] : undefined;
- }
- /**
- * Checks if a hash value for `key` exists.
- *
- * @private
- * @name has
- * @memberOf Hash
- * @param {string} key The key of the entry to check.
- * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
- */
- function hashHas(key) {
- var data = this.__data__;
- return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key);
- }
- /**
- * Sets the hash `key` to `value`.
- *
- * @private
- * @name set
- * @memberOf Hash
- * @param {string} key The key of the value to set.
- * @param {*} value The value to set.
- * @returns {Object} Returns the hash instance.
- */
- function hashSet(key, value) {
- var data = this.__data__;
- data[key] = nativeCreate && value === undefined ? HASH_UNDEFINED : value;
- return this;
- } // Add methods to `Hash`.
- Hash.prototype.clear = hashClear;
- Hash.prototype['delete'] = hashDelete;
- Hash.prototype.get = hashGet;
- Hash.prototype.has = hashHas;
- Hash.prototype.set = hashSet;
- /**
- * Creates an list cache object.
- *
- * @private
- * @constructor
- * @param {Array} [entries] The key-value pairs to cache.
- */
- function ListCache(entries) {
- var index = -1,
- length = entries ? entries.length : 0;
- this.clear();
- while (++index < length) {
- var entry = entries[index];
- this.set(entry[0], entry[1]);
- }
- }
- /**
- * Removes all key-value entries from the list cache.
- *
- * @private
- * @name clear
- * @memberOf ListCache
- */
- function listCacheClear() {
- this.__data__ = [];
- }
- /**
- * Removes `key` and its value from the list cache.
- *
- * @private
- * @name delete
- * @memberOf ListCache
- * @param {string} key The key of the value to remove.
- * @returns {boolean} Returns `true` if the entry was removed, else `false`.
- */
- function listCacheDelete(key) {
- var data = this.__data__,
- index = assocIndexOf(data, key);
- if (index < 0) {
- return false;
- }
- var lastIndex = data.length - 1;
- if (index == lastIndex) {
- data.pop();
- } else {
- splice.call(data, index, 1);
- }
- return true;
- }
- /**
- * Gets the list cache value for `key`.
- *
- * @private
- * @name get
- * @memberOf ListCache
- * @param {string} key The key of the value to get.
- * @returns {*} Returns the entry value.
- */
- function listCacheGet(key) {
- var data = this.__data__,
- index = assocIndexOf(data, key);
- return index < 0 ? undefined : data[index][1];
- }
- /**
- * Checks if a list cache value for `key` exists.
- *
- * @private
- * @name has
- * @memberOf ListCache
- * @param {string} key The key of the entry to check.
- * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
- */
- function listCacheHas(key) {
- return assocIndexOf(this.__data__, key) > -1;
- }
- /**
- * Sets the list cache `key` to `value`.
- *
- * @private
- * @name set
- * @memberOf ListCache
- * @param {string} key The key of the value to set.
- * @param {*} value The value to set.
- * @returns {Object} Returns the list cache instance.
- */
- function listCacheSet(key, value) {
- var data = this.__data__,
- index = assocIndexOf(data, key);
- if (index < 0) {
- data.push([key, value]);
- } else {
- data[index][1] = value;
- }
- return this;
- } // Add methods to `ListCache`.
- ListCache.prototype.clear = listCacheClear;
- ListCache.prototype['delete'] = listCacheDelete;
- ListCache.prototype.get = listCacheGet;
- ListCache.prototype.has = listCacheHas;
- ListCache.prototype.set = listCacheSet;
- /**
- * Creates a map cache object to store key-value pairs.
- *
- * @private
- * @constructor
- * @param {Array} [entries] The key-value pairs to cache.
- */
- function MapCache(entries) {
- var index = -1,
- length = entries ? entries.length : 0;
- this.clear();
- while (++index < length) {
- var entry = entries[index];
- this.set(entry[0], entry[1]);
- }
- }
- /**
- * Removes all key-value entries from the map.
- *
- * @private
- * @name clear
- * @memberOf MapCache
- */
- function mapCacheClear() {
- this.__data__ = {
- 'hash': new Hash(),
- 'map': new (Map || ListCache)(),
- 'string': new Hash()
- };
- }
- /**
- * Removes `key` and its value from the map.
- *
- * @private
- * @name delete
- * @memberOf MapCache
- * @param {string} key The key of the value to remove.
- * @returns {boolean} Returns `true` if the entry was removed, else `false`.
- */
- function mapCacheDelete(key) {
- return getMapData(this, key)['delete'](key);
- }
- /**
- * Gets the map value for `key`.
- *
- * @private
- * @name get
- * @memberOf MapCache
- * @param {string} key The key of the value to get.
- * @returns {*} Returns the entry value.
- */
- function mapCacheGet(key) {
- return getMapData(this, key).get(key);
- }
- /**
- * Checks if a map value for `key` exists.
- *
- * @private
- * @name has
- * @memberOf MapCache
- * @param {string} key The key of the entry to check.
- * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
- */
- function mapCacheHas(key) {
- return getMapData(this, key).has(key);
- }
- /**
- * Sets the map `key` to `value`.
- *
- * @private
- * @name set
- * @memberOf MapCache
- * @param {string} key The key of the value to set.
- * @param {*} value The value to set.
- * @returns {Object} Returns the map cache instance.
- */
- function mapCacheSet(key, value) {
- getMapData(this, key).set(key, value);
- return this;
- } // Add methods to `MapCache`.
- MapCache.prototype.clear = mapCacheClear;
- MapCache.prototype['delete'] = mapCacheDelete;
- MapCache.prototype.get = mapCacheGet;
- MapCache.prototype.has = mapCacheHas;
- MapCache.prototype.set = mapCacheSet;
- /**
- *
- * Creates an array cache object to store unique values.
- *
- * @private
- * @constructor
- * @param {Array} [values] The values to cache.
- */
- function SetCache(values) {
- var index = -1,
- length = values ? values.length : 0;
- this.__data__ = new MapCache();
- while (++index < length) {
- this.add(values[index]);
- }
- }
- /**
- * Adds `value` to the array cache.
- *
- * @private
- * @name add
- * @memberOf SetCache
- * @alias push
- * @param {*} value The value to cache.
- * @returns {Object} Returns the cache instance.
- */
- function setCacheAdd(value) {
- this.__data__.set(value, HASH_UNDEFINED);
- return this;
- }
- /**
- * Checks if `value` is in the array cache.
- *
- * @private
- * @name has
- * @memberOf SetCache
- * @param {*} value The value to search for.
- * @returns {number} Returns `true` if `value` is found, else `false`.
- */
- function setCacheHas(value) {
- return this.__data__.has(value);
- } // Add methods to `SetCache`.
- SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
- SetCache.prototype.has = setCacheHas;
- /**
- * Creates a stack cache object to store key-value pairs.
- *
- * @private
- * @constructor
- * @param {Array} [entries] The key-value pairs to cache.
- */
- function Stack(entries) {
- this.__data__ = new ListCache(entries);
- }
- /**
- * Removes all key-value entries from the stack.
- *
- * @private
- * @name clear
- * @memberOf Stack
- */
- function stackClear() {
- this.__data__ = new ListCache();
- }
- /**
- * Removes `key` and its value from the stack.
- *
- * @private
- * @name delete
- * @memberOf Stack
- * @param {string} key The key of the value to remove.
- * @returns {boolean} Returns `true` if the entry was removed, else `false`.
- */
- function stackDelete(key) {
- return this.__data__['delete'](key);
- }
- /**
- * Gets the stack value for `key`.
- *
- * @private
- * @name get
- * @memberOf Stack
- * @param {string} key The key of the value to get.
- * @returns {*} Returns the entry value.
- */
- function stackGet(key) {
- return this.__data__.get(key);
- }
- /**
- * Checks if a stack value for `key` exists.
- *
- * @private
- * @name has
- * @memberOf Stack
- * @param {string} key The key of the entry to check.
- * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
- */
- function stackHas(key) {
- return this.__data__.has(key);
- }
- /**
- * Sets the stack `key` to `value`.
- *
- * @private
- * @name set
- * @memberOf Stack
- * @param {string} key The key of the value to set.
- * @param {*} value The value to set.
- * @returns {Object} Returns the stack cache instance.
- */
- function stackSet(key, value) {
- var cache = this.__data__;
- if (cache instanceof ListCache) {
- var pairs = cache.__data__;
- if (!Map || pairs.length < LARGE_ARRAY_SIZE - 1) {
- pairs.push([key, value]);
- return this;
- }
- cache = this.__data__ = new MapCache(pairs);
- }
- cache.set(key, value);
- return this;
- } // Add methods to `Stack`.
- Stack.prototype.clear = stackClear;
- Stack.prototype['delete'] = stackDelete;
- Stack.prototype.get = stackGet;
- Stack.prototype.has = stackHas;
- Stack.prototype.set = stackSet;
- /**
- * Creates an array of the enumerable property names of the array-like `value`.
- *
- * @private
- * @param {*} value The value to query.
- * @param {boolean} inherited Specify returning inherited property names.
- * @returns {Array} Returns the array of property names.
- */
- function arrayLikeKeys(value, inherited) {
- // Safari 8.1 makes `arguments.callee` enumerable in strict mode.
- // Safari 9 makes `arguments.length` enumerable in strict mode.
- var result = isArray(value) || isArguments(value) ? baseTimes(value.length, String) : [];
- var length = result.length,
- skipIndexes = !!length;
- for (var key in value) {
- if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && (key == 'length' || isIndex(key, length)))) {
- result.push(key);
- }
- }
- return result;
- }
- /**
- * Gets the index at which the `key` is found in `array` of key-value pairs.
- *
- * @private
- * @param {Array} array The array to inspect.
- * @param {*} key The key to search for.
- * @returns {number} Returns the index of the matched value, else `-1`.
- */
- function assocIndexOf(array, key) {
- var length = array.length;
- while (length--) {
- if (eq(array[length][0], key)) {
- return length;
- }
- }
- return -1;
- }
- /**
- * The base implementation of `_.get` without support for default values.
- *
- * @private
- * @param {Object} object The object to query.
- * @param {Array|string} path The path of the property to get.
- * @returns {*} Returns the resolved value.
- */
- function baseGet(object, path$$1) {
- path$$1 = isKey(path$$1, object) ? [path$$1] : castPath(path$$1);
- var index = 0,
- length = path$$1.length;
- while (object != null && index < length) {
- object = object[toKey(path$$1[index++])];
- }
- return index && index == length ? object : undefined;
- }
- /**
- * The base implementation of `getTag`.
- *
- * @private
- * @param {*} value The value to query.
- * @returns {string} Returns the `toStringTag`.
- */
- function baseGetTag(value) {
- return objectToString.call(value);
- }
- /**
- * The base implementation of `_.hasIn` without support for deep paths.
- *
- * @private
- * @param {Object} [object] The object to query.
- * @param {Array|string} key The key to check.
- * @returns {boolean} Returns `true` if `key` exists, else `false`.
- */
- function baseHasIn(object, key) {
- return object != null && key in Object(object);
- }
- /**
- * The base implementation of `_.isEqual` which supports partial comparisons
- * and tracks traversed objects.
- *
- * @private
- * @param {*} value The value to compare.
- * @param {*} other The other value to compare.
- * @param {Function} [customizer] The function to customize comparisons.
- * @param {boolean} [bitmask] The bitmask of comparison flags.
- * The bitmask may be composed of the following flags:
- * 1 - Unordered comparison
- * 2 - Partial comparison
- * @param {Object} [stack] Tracks traversed `value` and `other` objects.
- * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
- */
- function baseIsEqual(value, other, customizer, bitmask, stack) {
- if (value === other) {
- return true;
- }
- if (value == null || other == null || !isObject(value) && !isObjectLike(other)) {
- return value !== value && other !== other;
- }
- return baseIsEqualDeep(value, other, baseIsEqual, customizer, bitmask, stack);
- }
- /**
- * A specialized version of `baseIsEqual` for arrays and objects which performs
- * deep comparisons and tracks traversed objects enabling objects with circular
- * references to be compared.
- *
- * @private
- * @param {Object} object The object to compare.
- * @param {Object} other The other object to compare.
- * @param {Function} equalFunc The function to determine equivalents of values.
- * @param {Function} [customizer] The function to customize comparisons.
- * @param {number} [bitmask] The bitmask of comparison flags. See `baseIsEqual`
- * for more details.
- * @param {Object} [stack] Tracks traversed `object` and `other` objects.
- * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
- */
- function baseIsEqualDeep(object, other, equalFunc, customizer, bitmask, stack) {
- var objIsArr = isArray(object),
- othIsArr = isArray(other),
- objTag = arrayTag,
- othTag = arrayTag;
- if (!objIsArr) {
- objTag = getTag(object);
- objTag = objTag == argsTag ? objectTag : objTag;
- }
- if (!othIsArr) {
- othTag = getTag(other);
- othTag = othTag == argsTag ? objectTag : othTag;
- }
- var objIsObj = objTag == objectTag && !isHostObject(object),
- othIsObj = othTag == objectTag && !isHostObject(other),
- isSameTag = objTag == othTag;
- if (isSameTag && !objIsObj) {
- stack || (stack = new Stack());
- return objIsArr || isTypedArray(object) ? equalArrays(object, other, equalFunc, customizer, bitmask, stack) : equalByTag(object, other, objTag, equalFunc, customizer, bitmask, stack);
- }
- if (!(bitmask & PARTIAL_COMPARE_FLAG)) {
- var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
- othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
- if (objIsWrapped || othIsWrapped) {
- var objUnwrapped = objIsWrapped ? object.value() : object,
- othUnwrapped = othIsWrapped ? other.value() : other;
- stack || (stack = new Stack());
- return equalFunc(objUnwrapped, othUnwrapped, customizer, bitmask, stack);
- }
- }
- if (!isSameTag) {
- return false;
- }
- stack || (stack = new Stack());
- return equalObjects(object, other, equalFunc, customizer, bitmask, stack);
- }
- /**
- * The base implementation of `_.isMatch` without support for iteratee shorthands.
- *
- * @private
- * @param {Object} object The object to inspect.
- * @param {Object} source The object of property values to match.
- * @param {Array} matchData The property names, values, and compare flags to match.
- * @param {Function} [customizer] The function to customize comparisons.
- * @returns {boolean} Returns `true` if `object` is a match, else `false`.
- */
- function baseIsMatch(object, source, matchData, customizer) {
- var index = matchData.length,
- length = index,
- noCustomizer = !customizer;
- if (object == null) {
- return !length;
- }
- object = Object(object);
- while (index--) {
- var data = matchData[index];
- if (noCustomizer && data[2] ? data[1] !== object[data[0]] : !(data[0] in object)) {
- return false;
- }
- }
- while (++index < length) {
- data = matchData[index];
- var key = data[0],
- objValue = object[key],
- srcValue = data[1];
- if (noCustomizer && data[2]) {
- if (objValue === undefined && !(key in object)) {
- return false;
- }
- } else {
- var stack = new Stack();
- if (customizer) {
- var result = customizer(objValue, srcValue, key, object, source, stack);
- }
- if (!(result === undefined ? baseIsEqual(srcValue, objValue, customizer, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG, stack) : result)) {
- return false;
- }
- }
- }
- return true;
- }
- /**
- * The base implementation of `_.isNative` without bad shim checks.
- *
- * @private
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a native function,
- * else `false`.
- */
- function baseIsNative(value) {
- if (!isObject(value) || isMasked(value)) {
- return false;
- }
- var pattern = isFunction(value) || isHostObject(value) ? reIsNative : reIsHostCtor;
- return pattern.test(toSource(value));
- }
- /**
- * The base implementation of `_.isTypedArray` without Node.js optimizations.
- *
- * @private
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
- */
- function baseIsTypedArray(value) {
- return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objectToString.call(value)];
- }
- /**
- * The base implementation of `_.iteratee`.
- *
- * @private
- * @param {*} [value=_.identity] The value to convert to an iteratee.
- * @returns {Function} Returns the iteratee.
- */
- function baseIteratee(value) {
- // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
- // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
- if (typeof value == 'function') {
- return value;
- }
- if (value == null) {
- return identity;
- }
- if (typeof value == 'object') {
- return isArray(value) ? baseMatchesProperty(value[0], value[1]) : baseMatches(value);
- }
- return property(value);
- }
- /**
- * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
- *
- * @private
- * @param {Object} object The object to query.
- * @returns {Array} Returns the array of property names.
- */
- function baseKeys(object) {
- if (!isPrototype(object)) {
- return nativeKeys(object);
- }
- var result = [];
- for (var key in Object(object)) {
- if (hasOwnProperty.call(object, key) && key != 'constructor') {
- result.push(key);
- }
- }
- return result;
- }
- /**
- * The base implementation of `_.matches` which doesn't clone `source`.
- *
- * @private
- * @param {Object} source The object of property values to match.
- * @returns {Function} Returns the new spec function.
- */
- function baseMatches(source) {
- var matchData = getMatchData(source);
- if (matchData.length == 1 && matchData[0][2]) {
- return matchesStrictComparable(matchData[0][0], matchData[0][1]);
- }
- return function (object) {
- return object === source || baseIsMatch(object, source, matchData);
- };
- }
- /**
- * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
- *
- * @private
- * @param {string} path The path of the property to get.
- * @param {*} srcValue The value to match.
- * @returns {Function} Returns the new spec function.
- */
- function baseMatchesProperty(path$$1, srcValue) {
- if (isKey(path$$1) && isStrictComparable(srcValue)) {
- return matchesStrictComparable(toKey(path$$1), srcValue);
- }
- return function (object) {
- var objValue = get(object, path$$1);
- return objValue === undefined && objValue === srcValue ? hasIn(object, path$$1) : baseIsEqual(srcValue, objValue, undefined, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG);
- };
- }
- /**
- * A specialized version of `baseProperty` which supports deep paths.
- *
- * @private
- * @param {Array|string} path The path of the property to get.
- * @returns {Function} Returns the new accessor function.
- */
- function basePropertyDeep(path$$1) {
- return function (object) {
- return baseGet(object, path$$1);
- };
- }
- /**
- * The base implementation of `_.toString` which doesn't convert nullish
- * values to empty strings.
- *
- * @private
- * @param {*} value The value to process.
- * @returns {string} Returns the string.
- */
- function baseToString(value) {
- // Exit early for strings to avoid a performance hit in some environments.
- if (typeof value == 'string') {
- return value;
- }
- if (isSymbol(value)) {
- return symbolToString ? symbolToString.call(value) : '';
- }
- var result = value + '';
- return result == '0' && 1 / value == -INFINITY ? '-0' : result;
- }
- /**
- * The base implementation of `_.uniqBy` without support for iteratee shorthands.
- *
- * @private
- * @param {Array} array The array to inspect.
- * @param {Function} [iteratee] The iteratee invoked per element.
- * @param {Function} [comparator] The comparator invoked per element.
- * @returns {Array} Returns the new duplicate free array.
- */
- function baseUniq(array, iteratee, comparator) {
- var index = -1,
- includes = arrayIncludes,
- length = array.length,
- isCommon = true,
- result = [],
- seen = result;
- if (comparator) {
- isCommon = false;
- includes = arrayIncludesWith;
- } else if (length >= LARGE_ARRAY_SIZE) {
- var set = iteratee ? null : createSet(array);
- if (set) {
- return setToArray(set);
- }
- isCommon = false;
- includes = cacheHas;
- seen = new SetCache();
- } else {
- seen = iteratee ? [] : result;
- }
- outer: while (++index < length) {
- var value = array[index],
- computed = iteratee ? iteratee(value) : value;
- value = comparator || value !== 0 ? value : 0;
- if (isCommon && computed === computed) {
- var seenIndex = seen.length;
- while (seenIndex--) {
- if (seen[seenIndex] === computed) {
- continue outer;
- }
- }
- if (iteratee) {
- seen.push(computed);
- }
- result.push(value);
- } else if (!includes(seen, computed, comparator)) {
- if (seen !== result) {
- seen.push(computed);
- }
- result.push(value);
- }
- }
- return result;
- }
- /**
- * Casts `value` to a path array if it's not one.
- *
- * @private
- * @param {*} value The value to inspect.
- * @returns {Array} Returns the cast property path array.
- */
- function castPath(value) {
- return isArray(value) ? value : stringToPath(value);
- }
- /**
- * Creates a set object of `values`.
- *
- * @private
- * @param {Array} values The values to add to the set.
- * @returns {Object} Returns the new set.
- */
- var createSet = !(Set && 1 / setToArray(new Set([, -0]))[1] == INFINITY) ? noop : function (values) {
- return new Set(values);
- };
- /**
- * A specialized version of `baseIsEqualDeep` for arrays with support for
- * partial deep comparisons.
- *
- * @private
- * @param {Array} array The array to compare.
- * @param {Array} other The other array to compare.
- * @param {Function} equalFunc The function to determine equivalents of values.
- * @param {Function} customizer The function to customize comparisons.
- * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual`
- * for more details.
- * @param {Object} stack Tracks traversed `array` and `other` objects.
- * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
- */
- function equalArrays(array, other, equalFunc, customizer, bitmask, stack) {
- var isPartial = bitmask & PARTIAL_COMPARE_FLAG,
- arrLength = array.length,
- othLength = other.length;
- if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
- return false;
- } // Assume cyclic values are equal.
- var stacked = stack.get(array);
- if (stacked && stack.get(other)) {
- return stacked == other;
- }
- var index = -1,
- result = true,
- seen = bitmask & UNORDERED_COMPARE_FLAG ? new SetCache() : undefined;
- stack.set(array, other);
- stack.set(other, array); // Ignore non-index properties.
- while (++index < arrLength) {
- var arrValue = array[index],
- othValue = other[index];
- if (customizer) {
- var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack);
- }
- if (compared !== undefined) {
- if (compared) {
- continue;
- }
- result = false;
- break;
- } // Recursively compare arrays (susceptible to call stack limits).
- if (seen) {
- if (!arraySome(other, function (othValue, othIndex) {
- if (!seen.has(othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, customizer, bitmask, stack))) {
- return seen.add(othIndex);
- }
- })) {
- result = false;
- break;
- }
- } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, customizer, bitmask, stack))) {
- result = false;
- break;
- }
- }
- stack['delete'](array);
- stack['delete'](other);
- return result;
- }
- /**
- * A specialized version of `baseIsEqualDeep` for comparing objects of
- * the same `toStringTag`.
- *
- * **Note:** This function only supports comparing values with tags of
- * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
- *
- * @private
- * @param {Object} object The object to compare.
- * @param {Object} other The other object to compare.
- * @param {string} tag The `toStringTag` of the objects to compare.
- * @param {Function} equalFunc The function to determine equivalents of values.
- * @param {Function} customizer The function to customize comparisons.
- * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual`
- * for more details.
- * @param {Object} stack Tracks traversed `object` and `other` objects.
- * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
- */
- function equalByTag(object, other, tag, equalFunc, customizer, bitmask, stack) {
- switch (tag) {
- case dataViewTag:
- if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) {
- return false;
- }
- object = object.buffer;
- other = other.buffer;
- case arrayBufferTag:
- if (object.byteLength != other.byteLength || !equalFunc(new Uint8Array(object), new Uint8Array(other))) {
- return false;
- }
- return true;
- case boolTag:
- case dateTag:
- case numberTag:
- // Coerce booleans to `1` or `0` and dates to milliseconds.
- // Invalid dates are coerced to `NaN`.
- return eq(+object, +other);
- case errorTag:
- return object.name == other.name && object.message == other.message;
- case regexpTag:
- case stringTag:
- // Coerce regexes to strings and treat strings, primitives and objects,
- // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
- // for more details.
- return object == other + '';
- case mapTag:
- var convert = mapToArray;
- case setTag:
- var isPartial = bitmask & PARTIAL_COMPARE_FLAG;
- convert || (convert = setToArray);
- if (object.size != other.size && !isPartial) {
- return false;
- } // Assume cyclic values are equal.
- var stacked = stack.get(object);
- if (stacked) {
- return stacked == other;
- }
- bitmask |= UNORDERED_COMPARE_FLAG; // Recursively compare objects (susceptible to call stack limits).
- stack.set(object, other);
- var result = equalArrays(convert(object), convert(other), equalFunc, customizer, bitmask, stack);
- stack['delete'](object);
- return result;
- case symbolTag:
- if (symbolValueOf) {
- return symbolValueOf.call(object) == symbolValueOf.call(other);
- }
- }
- return false;
- }
- /**
- * A specialized version of `baseIsEqualDeep` for objects with support for
- * partial deep comparisons.
- *
- * @private
- * @param {Object} object The object to compare.
- * @param {Object} other The other object to compare.
- * @param {Function} equalFunc The function to determine equivalents of values.
- * @param {Function} customizer The function to customize comparisons.
- * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual`
- * for more details.
- * @param {Object} stack Tracks traversed `object` and `other` objects.
- * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
- */
- function equalObjects(object, other, equalFunc, customizer, bitmask, stack) {
- var isPartial = bitmask & PARTIAL_COMPARE_FLAG,
- objProps = keys(object),
- objLength = objProps.length,
- othProps = keys(other),
- othLength = othProps.length;
- if (objLength != othLength && !isPartial) {
- return false;
- }
- var index = objLength;
- while (index--) {
- var key = objProps[index];
- if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {
- return false;
- }
- } // Assume cyclic values are equal.
- var stacked = stack.get(object);
- if (stacked && stack.get(other)) {
- return stacked == other;
- }
- var result = true;
- stack.set(object, other);
- stack.set(other, object);
- var skipCtor = isPartial;
- while (++index < objLength) {
- key = objProps[index];
- var objValue = object[key],
- othValue = other[key];
- if (customizer) {
- var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack);
- } // Recursively compare objects (susceptible to call stack limits).
- if (!(compared === undefined ? objValue === othValue || equalFunc(objValue, othValue, customizer, bitmask, stack) : compared)) {
- result = false;
- break;
- }
- skipCtor || (skipCtor = key == 'constructor');
- }
- if (result && !skipCtor) {
- var objCtor = object.constructor,
- othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal.
- if (objCtor != othCtor && 'constructor' in object && 'constructor' in other && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) {
- result = false;
- }
- }
- stack['delete'](object);
- stack['delete'](other);
- return result;
- }
- /**
- * Gets the data for `map`.
- *
- * @private
- * @param {Object} map The map to query.
- * @param {string} key The reference key.
- * @returns {*} Returns the map data.
- */
- function getMapData(map, key) {
- var data = map.__data__;
- return isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map;
- }
- /**
- * Gets the property names, values, and compare flags of `object`.
- *
- * @private
- * @param {Object} object The object to query.
- * @returns {Array} Returns the match data of `object`.
- */
- function getMatchData(object) {
- var result = keys(object),
- length = result.length;
- while (length--) {
- var key = result[length],
- value = object[key];
- result[length] = [key, value, isStrictComparable(value)];
- }
- return result;
- }
- /**
- * Gets the native function at `key` of `object`.
- *
- * @private
- * @param {Object} object The object to query.
- * @param {string} key The key of the method to get.
- * @returns {*} Returns the function if it's native, else `undefined`.
- */
- function getNative(object, key) {
- var value = getValue(object, key);
- return baseIsNative(value) ? value : undefined;
- }
- /**
- * Gets the `toStringTag` of `value`.
- *
- * @private
- * @param {*} value The value to query.
- * @returns {string} Returns the `toStringTag`.
- */
- var getTag = baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11,
- // for data views in Edge < 14, and promises in Node.js.
- if (DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag || Map && getTag(new Map()) != mapTag || Promise && getTag(Promise.resolve()) != promiseTag || Set && getTag(new Set()) != setTag || WeakMap && getTag(new WeakMap()) != weakMapTag) {
- getTag = function getTag(value) {
- var result = objectToString.call(value),
- Ctor = result == objectTag ? value.constructor : undefined,
- ctorString = Ctor ? toSource(Ctor) : undefined;
- if (ctorString) {
- switch (ctorString) {
- case dataViewCtorString:
- return dataViewTag;
- case mapCtorString:
- return mapTag;
- case promiseCtorString:
- return promiseTag;
- case setCtorString:
- return setTag;
- case weakMapCtorString:
- return weakMapTag;
- }
- }
- return result;
- };
- }
- /**
- * Checks if `path` exists on `object`.
- *
- * @private
- * @param {Object} object The object to query.
- * @param {Array|string} path The path to check.
- * @param {Function} hasFunc The function to check properties.
- * @returns {boolean} Returns `true` if `path` exists, else `false`.
- */
- function hasPath(object, path$$1, hasFunc) {
- path$$1 = isKey(path$$1, object) ? [path$$1] : castPath(path$$1);
- var result,
- index = -1,
- length = path$$1.length;
- while (++index < length) {
- var key = toKey(path$$1[index]);
- if (!(result = object != null && hasFunc(object, key))) {
- break;
- }
- object = object[key];
- }
- if (result) {
- return result;
- }
- var length = object ? object.length : 0;
- return !!length && isLength(length) && isIndex(key, length) && (isArray(object) || isArguments(object));
- }
- /**
- * Checks if `value` is a valid array-like index.
- *
- * @private
- * @param {*} value The value to check.
- * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
- * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
- */
- function isIndex(value, length) {
- length = length == null ? MAX_SAFE_INTEGER : length;
- return !!length && (typeof value == 'number' || reIsUint.test(value)) && value > -1 && value % 1 == 0 && value < length;
- }
- /**
- * Checks if `value` is a property name and not a property path.
- *
- * @private
- * @param {*} value The value to check.
- * @param {Object} [object] The object to query keys on.
- * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
- */
- function isKey(value, object) {
- if (isArray(value)) {
- return false;
- }
- var type = typeof value;
- if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol(value)) {
- return true;
- }
- return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object != null && value in Object(object);
- }
- /**
- * Checks if `value` is suitable for use as unique object key.
- *
- * @private
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
- */
- function isKeyable(value) {
- var type = typeof value;
- return type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean' ? value !== '__proto__' : value === null;
- }
- /**
- * Checks if `func` has its source masked.
- *
- * @private
- * @param {Function} func The function to check.
- * @returns {boolean} Returns `true` if `func` is masked, else `false`.
- */
- function isMasked(func) {
- return !!maskSrcKey && maskSrcKey in func;
- }
- /**
- * Checks if `value` is likely a prototype object.
- *
- * @private
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
- */
- function isPrototype(value) {
- var Ctor = value && value.constructor,
- proto = typeof Ctor == 'function' && Ctor.prototype || objectProto;
- return value === proto;
- }
- /**
- * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
- *
- * @private
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` if suitable for strict
- * equality comparisons, else `false`.
- */
- function isStrictComparable(value) {
- return value === value && !isObject(value);
- }
- /**
- * A specialized version of `matchesProperty` for source values suitable
- * for strict equality comparisons, i.e. `===`.
- *
- * @private
- * @param {string} key The key of the property to get.
- * @param {*} srcValue The value to match.
- * @returns {Function} Returns the new spec function.
- */
- function matchesStrictComparable(key, srcValue) {
- return function (object) {
- if (object == null) {
- return false;
- }
- return object[key] === srcValue && (srcValue !== undefined || key in Object(object));
- };
- }
- /**
- * Converts `string` to a property path array.
- *
- * @private
- * @param {string} string The string to convert.
- * @returns {Array} Returns the property path array.
- */
- var stringToPath = memoize(function (string) {
- string = toString(string);
- var result = [];
- if (reLeadingDot.test(string)) {
- result.push('');
- }
- string.replace(rePropName, function (match, number, quote, string) {
- result.push(quote ? string.replace(reEscapeChar, '$1') : number || match);
- });
- return result;
- });
- /**
- * Converts `value` to a string key if it's not a string or symbol.
- *
- * @private
- * @param {*} value The value to inspect.
- * @returns {string|symbol} Returns the key.
- */
- function toKey(value) {
- if (typeof value == 'string' || isSymbol(value)) {
- return value;
- }
- var result = value + '';
- return result == '0' && 1 / value == -INFINITY ? '-0' : result;
- }
- /**
- * Converts `func` to its source code.
- *
- * @private
- * @param {Function} func The function to process.
- * @returns {string} Returns the source code.
- */
- function toSource(func) {
- if (func != null) {
- try {
- return funcToString.call(func);
- } catch (e) {}
- try {
- return func + '';
- } catch (e) {}
- }
- return '';
- }
- /**
- * This method is like `_.uniq` except that it accepts `iteratee` which is
- * invoked for each element in `array` to generate the criterion by which
- * uniqueness is computed. The iteratee is invoked with one argument: (value).
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Array
- * @param {Array} array The array to inspect.
- * @param {Function} [iteratee=_.identity]
- * The iteratee invoked per element.
- * @returns {Array} Returns the new duplicate free array.
- * @example
- *
- * _.uniqBy([2.1, 1.2, 2.3], Math.floor);
- * // => [2.1, 1.2]
- *
- * // The `_.property` iteratee shorthand.
- * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
- * // => [{ 'x': 1 }, { 'x': 2 }]
- */
- function uniqBy(array, iteratee) {
- return array && array.length ? baseUniq(array, baseIteratee(iteratee, 2)) : [];
- }
- /**
- * Creates a function that memoizes the result of `func`. If `resolver` is
- * provided, it determines the cache key for storing the result based on the
- * arguments provided to the memoized function. By default, the first argument
- * provided to the memoized function is used as the map cache key. The `func`
- * is invoked with the `this` binding of the memoized function.
- *
- * **Note:** The cache is exposed as the `cache` property on the memoized
- * function. Its creation may be customized by replacing the `_.memoize.Cache`
- * constructor with one whose instances implement the
- * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
- * method interface of `delete`, `get`, `has`, and `set`.
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @category Function
- * @param {Function} func The function to have its output memoized.
- * @param {Function} [resolver] The function to resolve the cache key.
- * @returns {Function} Returns the new memoized function.
- * @example
- *
- * var object = { 'a': 1, 'b': 2 };
- * var other = { 'c': 3, 'd': 4 };
- *
- * var values = _.memoize(_.values);
- * values(object);
- * // => [1, 2]
- *
- * values(other);
- * // => [3, 4]
- *
- * object.a = 2;
- * values(object);
- * // => [1, 2]
- *
- * // Modify the result cache.
- * values.cache.set(object, ['a', 'b']);
- * values(object);
- * // => ['a', 'b']
- *
- * // Replace `_.memoize.Cache`.
- * _.memoize.Cache = WeakMap;
- */
- function memoize(func, resolver) {
- if (typeof func != 'function' || resolver && typeof resolver != 'function') {
- throw new TypeError(FUNC_ERROR_TEXT);
- }
- var memoized = function memoized() {
- var args = arguments,
- key = resolver ? resolver.apply(this, args) : args[0],
- cache = memoized.cache;
- if (cache.has(key)) {
- return cache.get(key);
- }
- var result = func.apply(this, args);
- memoized.cache = cache.set(key, result);
- return result;
- };
- memoized.cache = new (memoize.Cache || MapCache)();
- return memoized;
- } // Assign cache to `_.memoize`.
- memoize.Cache = MapCache;
- /**
- * Performs a
- * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
- * comparison between two values to determine if they are equivalent.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to compare.
- * @param {*} other The other value to compare.
- * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
- * @example
- *
- * var object = { 'a': 1 };
- * var other = { 'a': 1 };
- *
- * _.eq(object, object);
- * // => true
- *
- * _.eq(object, other);
- * // => false
- *
- * _.eq('a', 'a');
- * // => true
- *
- * _.eq('a', Object('a'));
- * // => false
- *
- * _.eq(NaN, NaN);
- * // => true
- */
- function eq(value, other) {
- return value === other || value !== value && other !== other;
- }
- /**
- * Checks if `value` is likely an `arguments` object.
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is an `arguments` object,
- * else `false`.
- * @example
- *
- * _.isArguments(function() { return arguments; }());
- * // => true
- *
- * _.isArguments([1, 2, 3]);
- * // => false
- */
- function isArguments(value) {
- // Safari 8.1 makes `arguments.callee` enumerable in strict mode.
- return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag);
- }
- /**
- * Checks if `value` is classified as an `Array` object.
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is an array, else `false`.
- * @example
- *
- * _.isArray([1, 2, 3]);
- * // => true
- *
- * _.isArray(document.body.children);
- * // => false
- *
- * _.isArray('abc');
- * // => false
- *
- * _.isArray(_.noop);
- * // => false
- */
- var isArray = Array.isArray;
- /**
- * Checks if `value` is array-like. A value is considered array-like if it's
- * not a function and has a `value.length` that's an integer greater than or
- * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
- * @example
- *
- * _.isArrayLike([1, 2, 3]);
- * // => true
- *
- * _.isArrayLike(document.body.children);
- * // => true
- *
- * _.isArrayLike('abc');
- * // => true
- *
- * _.isArrayLike(_.noop);
- * // => false
- */
- function isArrayLike(value) {
- return value != null && isLength(value.length) && !isFunction(value);
- }
- /**
- * This method is like `_.isArrayLike` except that it also checks if `value`
- * is an object.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is an array-like object,
- * else `false`.
- * @example
- *
- * _.isArrayLikeObject([1, 2, 3]);
- * // => true
- *
- * _.isArrayLikeObject(document.body.children);
- * // => true
- *
- * _.isArrayLikeObject('abc');
- * // => false
- *
- * _.isArrayLikeObject(_.noop);
- * // => false
- */
- function isArrayLikeObject(value) {
- return isObjectLike(value) && isArrayLike(value);
- }
- /**
- * Checks if `value` is classified as a `Function` object.
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a function, else `false`.
- * @example
- *
- * _.isFunction(_);
- * // => true
- *
- * _.isFunction(/abc/);
- * // => false
- */
- function isFunction(value) {
- // The use of `Object#toString` avoids issues with the `typeof` operator
- // in Safari 8-9 which returns 'object' for typed array and other constructors.
- var tag = isObject(value) ? objectToString.call(value) : '';
- return tag == funcTag || tag == genTag;
- }
- /**
- * Checks if `value` is a valid array-like length.
- *
- * **Note:** This method is loosely based on
- * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
- * @example
- *
- * _.isLength(3);
- * // => true
- *
- * _.isLength(Number.MIN_VALUE);
- * // => false
- *
- * _.isLength(Infinity);
- * // => false
- *
- * _.isLength('3');
- * // => false
- */
- function isLength(value) {
- return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
- }
- /**
- * Checks if `value` is the
- * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
- * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
- *
- * @static
- * @memberOf _
- * @since 0.1.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is an object, else `false`.
- * @example
- *
- * _.isObject({});
- * // => true
- *
- * _.isObject([1, 2, 3]);
- * // => true
- *
- * _.isObject(_.noop);
- * // => true
- *
- * _.isObject(null);
- * // => false
- */
- function isObject(value) {
- var type = typeof value;
- return !!value && (type == 'object' || type == 'function');
- }
- /**
- * Checks if `value` is object-like. A value is object-like if it's not `null`
- * and has a `typeof` result of "object".
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
- * @example
- *
- * _.isObjectLike({});
- * // => true
- *
- * _.isObjectLike([1, 2, 3]);
- * // => true
- *
- * _.isObjectLike(_.noop);
- * // => false
- *
- * _.isObjectLike(null);
- * // => false
- */
- function isObjectLike(value) {
- return !!value && typeof value == 'object';
- }
- /**
- * Checks if `value` is classified as a `Symbol` primitive or object.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
- * @example
- *
- * _.isSymbol(Symbol.iterator);
- * // => true
- *
- * _.isSymbol('abc');
- * // => false
- */
- function isSymbol(value) {
- return typeof value == 'symbol' || isObjectLike(value) && objectToString.call(value) == symbolTag;
- }
- /**
- * Checks if `value` is classified as a typed array.
- *
- * @static
- * @memberOf _
- * @since 3.0.0
- * @category Lang
- * @param {*} value The value to check.
- * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
- * @example
- *
- * _.isTypedArray(new Uint8Array);
- * // => true
- *
- * _.isTypedArray([]);
- * // => false
- */
- var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
- /**
- * Converts `value` to a string. An empty string is returned for `null`
- * and `undefined` values. The sign of `-0` is preserved.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Lang
- * @param {*} value The value to process.
- * @returns {string} Returns the string.
- * @example
- *
- * _.toString(null);
- * // => ''
- *
- * _.toString(-0);
- * // => '-0'
- *
- * _.toString([1, 2, 3]);
- * // => '1,2,3'
- */
- function toString(value) {
- return value == null ? '' : baseToString(value);
- }
- /**
- * Gets the value at `path` of `object`. If the resolved value is
- * `undefined`, the `defaultValue` is returned in its place.
- *
- * @static
- * @memberOf _
- * @since 3.7.0
- * @category Object
- * @param {Object} object The object to query.
- * @param {Array|string} path The path of the property to get.
- * @param {*} [defaultValue] The value returned for `undefined` resolved values.
- * @returns {*} Returns the resolved value.
- * @example
- *
- * var object = { 'a': [{ 'b': { 'c': 3 } }] };
- *
- * _.get(object, 'a[0].b.c');
- * // => 3
- *
- * _.get(object, ['a', '0', 'b', 'c']);
- * // => 3
- *
- * _.get(object, 'a.b.c', 'default');
- * // => 'default'
- */
- function get(object, path$$1, defaultValue) {
- var result = object == null ? undefined : baseGet(object, path$$1);
- return result === undefined ? defaultValue : result;
- }
- /**
- * Checks if `path` is a direct or inherited property of `object`.
- *
- * @static
- * @memberOf _
- * @since 4.0.0
- * @category Object
- * @param {Object} object The object to query.
- * @param {Array|string} path The path to check.
- * @returns {boolean} Returns `true` if `path` exists, else `false`.
- * @example
- *
- * var object = _.create({ 'a': _.create({ 'b': 2 }) });
- *
- * _.hasIn(object, 'a');
- * // => true
- *
- * _.hasIn(object, 'a.b');
- * // => true
- *
- * _.hasIn(object, ['a', 'b']);
- * // => true
- *
- * _.hasIn(object, 'b');
- * // => false
- */
- function hasIn(object, path$$1) {
- return object != null && hasPath(object, path$$1, baseHasIn);
- }
- /**
- * Creates an array of the own enumerable property names of `object`.
- *
- * **Note:** Non-object values are coerced to objects. See the
- * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
- * for more details.
- *
- * @static
- * @since 0.1.0
- * @memberOf _
- * @category Object
- * @param {Object} object The object to query.
- * @returns {Array} Returns the array of property names.
- * @example
- *
- * function Foo() {
- * this.a = 1;
- * this.b = 2;
- * }
- *
- * Foo.prototype.c = 3;
- *
- * _.keys(new Foo);
- * // => ['a', 'b'] (iteration order is not guaranteed)
- *
- * _.keys('hi');
- * // => ['0', '1']
- */
- function keys(object) {
- return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
- }
- /**
- * This method returns the first argument it receives.
- *
- * @static
- * @since 0.1.0
- * @memberOf _
- * @category Util
- * @param {*} value Any value.
- * @returns {*} Returns `value`.
- * @example
- *
- * var object = { 'a': 1 };
- *
- * console.log(_.identity(object) === object);
- * // => true
- */
- function identity(value) {
- return value;
- }
- /**
- * This method returns `undefined`.
- *
- * @static
- * @memberOf _
- * @since 2.3.0
- * @category Util
- * @example
- *
- * _.times(2, _.noop);
- * // => [undefined, undefined]
- */
- function noop() {} // No operation performed.
- /**
- * Creates a function that returns the value at `path` of a given object.
- *
- * @static
- * @memberOf _
- * @since 2.4.0
- * @category Util
- * @param {Array|string} path The path of the property to get.
- * @returns {Function} Returns the new accessor function.
- * @example
- *
- * var objects = [
- * { 'a': { 'b': 2 } },
- * { 'a': { 'b': 1 } }
- * ];
- *
- * _.map(objects, _.property('a.b'));
- * // => [2, 1]
- *
- * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
- * // => [1, 2]
- */
- function property(path$$1) {
- return isKey(path$$1) ? baseProperty(toKey(path$$1)) : basePropertyDeep(path$$1);
- }
- module.exports = uniqBy;
- });
- var PENDING = 'pending';
- var SETTLED = 'settled';
- var FULFILLED = 'fulfilled';
- var REJECTED = 'rejected';
- var NOOP = function NOOP() {};
- var isNode = typeof commonjsGlobal !== 'undefined' && typeof commonjsGlobal.process !== 'undefined' && typeof commonjsGlobal.process.emit === 'function';
- var asyncSetTimer = typeof setImmediate === 'undefined' ? setTimeout : setImmediate;
- var asyncQueue = [];
- var asyncTimer;
- function asyncFlush() {
- // run promise callbacks
- for (var i = 0; i < asyncQueue.length; i++) {
- asyncQueue[i][0](asyncQueue[i][1]);
- } // reset async asyncQueue
- asyncQueue = [];
- asyncTimer = false;
- }
- function asyncCall(callback, arg) {
- asyncQueue.push([callback, arg]);
- if (!asyncTimer) {
- asyncTimer = true;
- asyncSetTimer(asyncFlush, 0);
- }
- }
- function invokeResolver(resolver, promise) {
- function resolvePromise(value) {
- resolve(promise, value);
- }
- function rejectPromise(reason) {
- reject(promise, reason);
- }
- try {
- resolver(resolvePromise, rejectPromise);
- } catch (e) {
- rejectPromise(e);
- }
- }
- function invokeCallback(subscriber) {
- var owner = subscriber.owner;
- var settled = owner._state;
- var value = owner._data;
- var callback = subscriber[settled];
- var promise = subscriber.then;
- if (typeof callback === 'function') {
- settled = FULFILLED;
- try {
- value = callback(value);
- } catch (e) {
- reject(promise, e);
- }
- }
- if (!handleThenable(promise, value)) {
- if (settled === FULFILLED) {
- resolve(promise, value);
- }
- if (settled === REJECTED) {
- reject(promise, value);
- }
- }
- }
- function handleThenable(promise, value) {
- var resolved;
- try {
- if (promise === value) {
- throw new TypeError('A promises callback cannot return that same promise.');
- }
- if (value && (typeof value === 'function' || typeof value === 'object')) {
- // then should be retrieved only once
- var then = value.then;
- if (typeof then === 'function') {
- then.call(value, function (val) {
- if (!resolved) {
- resolved = true;
- if (value === val) {
- fulfill(promise, val);
- } else {
- resolve(promise, val);
- }
- }
- }, function (reason) {
- if (!resolved) {
- resolved = true;
- reject(promise, reason);
- }
- });
- return true;
- }
- }
- } catch (e) {
- if (!resolved) {
- reject(promise, e);
- }
- return true;
- }
- return false;
- }
- function resolve(promise, value) {
- if (promise === value || !handleThenable(promise, value)) {
- fulfill(promise, value);
- }
- }
- function fulfill(promise, value) {
- if (promise._state === PENDING) {
- promise._state = SETTLED;
- promise._data = value;
- asyncCall(publishFulfillment, promise);
- }
- }
- function reject(promise, reason) {
- if (promise._state === PENDING) {
- promise._state = SETTLED;
- promise._data = reason;
- asyncCall(publishRejection, promise);
- }
- }
- function publish(promise) {
- promise._then = promise._then.forEach(invokeCallback);
- }
- function publishFulfillment(promise) {
- promise._state = FULFILLED;
- publish(promise);
- }
- function publishRejection(promise) {
- promise._state = REJECTED;
- publish(promise);
- if (!promise._handled && isNode) {
- commonjsGlobal.process.emit('unhandledRejection', promise._data, promise);
- }
- }
- function notifyRejectionHandled(promise) {
- commonjsGlobal.process.emit('rejectionHandled', promise);
- }
- /**
- * @class
- */
- function Promise$1(resolver) {
- if (typeof resolver !== 'function') {
- throw new TypeError('Promise resolver ' + resolver + ' is not a function');
- }
- if (this instanceof Promise$1 === false) {
- throw new TypeError('Failed to construct \'Promise\': Please use the \'new\' operator, this object constructor cannot be called as a function.');
- }
- this._then = [];
- invokeResolver(resolver, this);
- }
- Promise$1.prototype = {
- constructor: Promise$1,
- _state: PENDING,
- _then: null,
- _data: undefined,
- _handled: false,
- then: function then(onFulfillment, onRejection) {
- var subscriber = {
- owner: this,
- then: new this.constructor(NOOP),
- fulfilled: onFulfillment,
- rejected: onRejection
- };
- if ((onRejection || onFulfillment) && !this._handled) {
- this._handled = true;
- if (this._state === REJECTED && isNode) {
- asyncCall(notifyRejectionHandled, this);
- }
- }
- if (this._state === FULFILLED || this._state === REJECTED) {
- // already resolved, call callback async
- asyncCall(invokeCallback, subscriber);
- } else {
- // subscribe
- this._then.push(subscriber);
- }
- return subscriber.then;
- },
- catch: function _catch(onRejection) {
- return this.then(null, onRejection);
- }
- };
- Promise$1.all = function (promises) {
- if (!Array.isArray(promises)) {
- throw new TypeError('You must pass an array to Promise.all().');
- }
- return new Promise$1(function (resolve, reject) {
- var results = [];
- var remaining = 0;
- function resolver(index) {
- remaining++;
- return function (value) {
- results[index] = value;
- if (! --remaining) {
- resolve(results);
- }
- };
- }
- for (var i = 0, promise; i < promises.length; i++) {
- promise = promises[i];
- if (promise && typeof promise.then === 'function') {
- promise.then(resolver(i), reject);
- } else {
- results[i] = promise;
- }
- }
- if (!remaining) {
- resolve(results);
- }
- });
- };
- Promise$1.race = function (promises) {
- if (!Array.isArray(promises)) {
- throw new TypeError('You must pass an array to Promise.race().');
- }
- return new Promise$1(function (resolve, reject) {
- for (var i = 0, promise; i < promises.length; i++) {
- promise = promises[i];
- if (promise && typeof promise.then === 'function') {
- promise.then(resolve, reject);
- } else {
- resolve(promise);
- }
- }
- });
- };
- Promise$1.resolve = function (value) {
- if (value && typeof value === 'object' && value.constructor === Promise$1) {
- return value;
- }
- return new Promise$1(function (resolve) {
- resolve(value);
- });
- };
- Promise$1.reject = function (reason) {
- return new Promise$1(function (resolve, reject) {
- reject(reason);
- });
- };
- var pinkie = Promise$1;
- var pinkiePromise = typeof Promise === 'function' ? Promise : pinkie;
- var arrayUniq = createCommonjsModule(function (module) {
- 'use strict'; // there's 3 implementations written in increasing order of efficiency
- // 1 - no Set type is defined
- function uniqNoSet(arr) {
- var ret = [];
- for (var i = 0; i < arr.length; i++) {
- if (ret.indexOf(arr[i]) === -1) {
- ret.push(arr[i]);
- }
- }
- return ret;
- } // 2 - a simple Set type is defined
- function uniqSet(arr) {
- var seen = new Set();
- return arr.filter(function (el) {
- if (!seen.has(el)) {
- seen.add(el);
- return true;
- }
- return false;
- });
- } // 3 - a standard Set type is defined and it has a forEach method
- function uniqSetWithForEach(arr) {
- var ret = [];
- new Set(arr).forEach(function (el) {
- ret.push(el);
- });
- return ret;
- } // V8 currently has a broken implementation
- // https://github.com/joyent/node/issues/8449
- function doesForEachActuallyWork() {
- var ret = false;
- new Set([true]).forEach(function (el) {
- ret = el;
- });
- return ret === true;
- }
- if ('Set' in commonjsGlobal) {
- if (typeof Set.prototype.forEach === 'function' && doesForEachActuallyWork()) {
- module.exports = uniqSetWithForEach;
- } else {
- module.exports = uniqSet;
- }
- } else {
- module.exports = uniqNoSet;
- }
- });
- var arrayUnion = function arrayUnion() {
- return arrayUniq([].concat.apply([], arguments));
- };
- /*
- object-assign
- (c) Sindre Sorhus
- @license MIT
- */
- /* eslint-disable no-unused-vars */
- var getOwnPropertySymbols = Object.getOwnPropertySymbols;
- var hasOwnProperty = Object.prototype.hasOwnProperty;
- var propIsEnumerable = Object.prototype.propertyIsEnumerable;
- function toObject(val) {
- if (val === null || val === undefined) {
- throw new TypeError('Object.assign cannot be called with null or undefined');
- }
- return Object(val);
- }
- function shouldUseNative() {
- try {
- if (!Object.assign) {
- return false;
- } // Detect buggy property enumeration order in older V8 versions.
- // https://bugs.chromium.org/p/v8/issues/detail?id=4118
- var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
- test1[5] = 'de';
- if (Object.getOwnPropertyNames(test1)[0] === '5') {
- return false;
- } // https://bugs.chromium.org/p/v8/issues/detail?id=3056
- var test2 = {};
- for (var i = 0; i < 10; i++) {
- test2['_' + String.fromCharCode(i)] = i;
- }
- var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
- return test2[n];
- });
- if (order2.join('') !== '0123456789') {
- return false;
- } // https://bugs.chromium.org/p/v8/issues/detail?id=3056
- var test3 = {};
- 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
- test3[letter] = letter;
- });
- if (Object.keys(Object.assign({}, test3)).join('') !== 'abcdefghijklmnopqrst') {
- return false;
- }
- return true;
- } catch (err) {
- // We don't expect any of the above to throw, but better to be safe.
- return false;
- }
- }
- var objectAssign = shouldUseNative() ? Object.assign : function (target, source) {
- var from;
- var to = toObject(target);
- var symbols;
- for (var s = 1; s < arguments.length; s++) {
- from = Object(arguments[s]);
- for (var key in from) {
- if (hasOwnProperty.call(from, key)) {
- to[key] = from[key];
- }
- }
- if (getOwnPropertySymbols) {
- symbols = getOwnPropertySymbols(from);
- for (var i = 0; i < symbols.length; i++) {
- if (propIsEnumerable.call(from, symbols[i])) {
- to[symbols[i]] = from[symbols[i]];
- }
- }
- }
- }
- return to;
- };
- //
- // Permission is hereby granted, free of charge, to any person obtaining a
- // copy of this software and associated documentation files (the
- // "Software"), to deal in the Software without restriction, including
- // without limitation the rights to use, copy, modify, merge, publish,
- // distribute, sublicense, and/or sell copies of the Software, and to permit
- // persons to whom the Software is furnished to do so, subject to the
- // following conditions:
- //
- // The above copyright notice and this permission notice shall be included
- // in all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
- // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
- // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
- // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
- // USE OR OTHER DEALINGS IN THE SOFTWARE.
- var isWindows = process.platform === 'win32'; // JavaScript implementation of realpath, ported from node pre-v6
- var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG);
- function rethrow() {
- // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and
- // is fairly slow to generate.
- var callback;
- if (DEBUG) {
- var backtrace = new Error();
- callback = debugCallback;
- } else callback = missingCallback;
- return callback;
- function debugCallback(err) {
- if (err) {
- backtrace.message = err.message;
- err = backtrace;
- missingCallback(err);
- }
- }
- function missingCallback(err) {
- if (err) {
- if (process.throwDeprecation) throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs
- else if (!process.noDeprecation) {
- var msg = 'fs: missing callback ' + (err.stack || err.message);
- if (process.traceDeprecation) console.trace(msg);else console.error(msg);
- }
- }
- }
- }
- function maybeCallback(cb) {
- return typeof cb === 'function' ? cb : rethrow();
- }
- // result is [base_with_slash, base], e.g. ['somedir/', 'somedir']
- if (isWindows) {
- var nextPartRe = /(.*?)(?:[\/\\]+|$)/g;
- } else {
- var nextPartRe = /(.*?)(?:[\/]+|$)/g;
- } // Regex to find the device root, including trailing slash. E.g. 'c:\\'.
- if (isWindows) {
- var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/;
- } else {
- var splitRootRe = /^[\/]*/;
- }
- var realpathSync$1 = function realpathSync(p, cache) {
- // make p is absolute
- p = path.resolve(p);
- if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
- return cache[p];
- }
- var original = p,
- seenLinks = {},
- knownHard = {}; // current character position in p
- var pos; // the partial path so far, including a trailing slash if any
- var current; // the partial path without a trailing slash (except when pointing at a root)
- var base; // the partial path scanned in the previous round, with slash
- var previous;
- start();
- function start() {
- // Skip over roots
- var m = splitRootRe.exec(p);
- pos = m[0].length;
- current = m[0];
- base = m[0];
- previous = ''; // On windows, check that the root exists. On unix there is no need.
- if (isWindows && !knownHard[base]) {
- fs.lstatSync(base);
- knownHard[base] = true;
- }
- } // walk down the path, swapping out linked pathparts for their real
- // values
- // NB: p.length changes.
- while (pos < p.length) {
- // find the next part
- nextPartRe.lastIndex = pos;
- var result = nextPartRe.exec(p);
- previous = current;
- current += result[0];
- base = previous + result[1];
- pos = nextPartRe.lastIndex; // continue if not a symlink
- if (knownHard[base] || cache && cache[base] === base) {
- continue;
- }
- var resolvedLink;
- if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
- // some known symbolic link. no need to stat again.
- resolvedLink = cache[base];
- } else {
- var stat = fs.lstatSync(base);
- if (!stat.isSymbolicLink()) {
- knownHard[base] = true;
- if (cache) cache[base] = base;
- continue;
- } // read the link if it wasn't read before
- // dev/ino always return 0 on windows, so skip the check.
- var linkTarget = null;
- if (!isWindows) {
- var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
- if (seenLinks.hasOwnProperty(id)) {
- linkTarget = seenLinks[id];
- }
- }
- if (linkTarget === null) {
- fs.statSync(base);
- linkTarget = fs.readlinkSync(base);
- }
- resolvedLink = path.resolve(previous, linkTarget); // track this, if given a cache.
- if (cache) cache[base] = resolvedLink;
- if (!isWindows) seenLinks[id] = linkTarget;
- } // resolve the link, then start over
- p = path.resolve(resolvedLink, p.slice(pos));
- start();
- }
- if (cache) cache[original] = p;
- return p;
- };
- var realpath$1 = function realpath(p, cache, cb) {
- if (typeof cb !== 'function') {
- cb = maybeCallback(cache);
- cache = null;
- } // make p is absolute
- p = path.resolve(p);
- if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
- return process.nextTick(cb.bind(null, null, cache[p]));
- }
- var original = p,
- seenLinks = {},
- knownHard = {}; // current character position in p
- var pos; // the partial path so far, including a trailing slash if any
- var current; // the partial path without a trailing slash (except when pointing at a root)
- var base; // the partial path scanned in the previous round, with slash
- var previous;
- start();
- function start() {
- // Skip over roots
- var m = splitRootRe.exec(p);
- pos = m[0].length;
- current = m[0];
- base = m[0];
- previous = ''; // On windows, check that the root exists. On unix there is no need.
- if (isWindows && !knownHard[base]) {
- fs.lstat(base, function (err) {
- if (err) return cb(err);
- knownHard[base] = true;
- LOOP();
- });
- } else {
- process.nextTick(LOOP);
- }
- } // walk down the path, swapping out linked pathparts for their real
- // values
- function LOOP() {
- // stop if scanned past end of path
- if (pos >= p.length) {
- if (cache) cache[original] = p;
- return cb(null, p);
- } // find the next part
- nextPartRe.lastIndex = pos;
- var result = nextPartRe.exec(p);
- previous = current;
- current += result[0];
- base = previous + result[1];
- pos = nextPartRe.lastIndex; // continue if not a symlink
- if (knownHard[base] || cache && cache[base] === base) {
- return process.nextTick(LOOP);
- }
- if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
- // known symbolic link. no need to stat again.
- return gotResolvedLink(cache[base]);
- }
- return fs.lstat(base, gotStat);
- }
- function gotStat(err, stat) {
- if (err) return cb(err); // if not a symlink, skip to the next path part
- if (!stat.isSymbolicLink()) {
- knownHard[base] = true;
- if (cache) cache[base] = base;
- return process.nextTick(LOOP);
- } // stat & read the link if not read before
- // call gotTarget as soon as the link target is known
- // dev/ino always return 0 on windows, so skip the check.
- if (!isWindows) {
- var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
- if (seenLinks.hasOwnProperty(id)) {
- return gotTarget(null, seenLinks[id], base);
- }
- }
- fs.stat(base, function (err) {
- if (err) return cb(err);
- fs.readlink(base, function (err, target) {
- if (!isWindows) seenLinks[id] = target;
- gotTarget(err, target);
- });
- });
- }
- function gotTarget(err, target, base) {
- if (err) return cb(err);
- var resolvedLink = path.resolve(previous, target);
- if (cache) cache[base] = resolvedLink;
- gotResolvedLink(resolvedLink);
- }
- function gotResolvedLink(resolvedLink) {
- // resolve the link, then start over
- p = path.resolve(resolvedLink, p.slice(pos));
- start();
- }
- };
- var old = {
- realpathSync: realpathSync$1,
- realpath: realpath$1
- };
- var fs_realpath = realpath;
- realpath.realpath = realpath;
- realpath.sync = realpathSync;
- realpath.realpathSync = realpathSync;
- realpath.monkeypatch = monkeypatch;
- realpath.unmonkeypatch = unmonkeypatch;
- var origRealpath = fs.realpath;
- var origRealpathSync = fs.realpathSync;
- var version$2 = process.version;
- var ok = /^v[0-5]\./.test(version$2);
- function newError(er) {
- return er && er.syscall === 'realpath' && (er.code === 'ELOOP' || er.code === 'ENOMEM' || er.code === 'ENAMETOOLONG');
- }
- function realpath(p, cache, cb) {
- if (ok) {
- return origRealpath(p, cache, cb);
- }
- if (typeof cache === 'function') {
- cb = cache;
- cache = null;
- }
- origRealpath(p, cache, function (er, result) {
- if (newError(er)) {
- old.realpath(p, cache, cb);
- } else {
- cb(er, result);
- }
- });
- }
- function realpathSync(p, cache) {
- if (ok) {
- return origRealpathSync(p, cache);
- }
- try {
- return origRealpathSync(p, cache);
- } catch (er) {
- if (newError(er)) {
- return old.realpathSync(p, cache);
- } else {
- throw er;
- }
- }
- }
- function monkeypatch() {
- fs.realpath = realpath;
- fs.realpathSync = realpathSync;
- }
- function unmonkeypatch() {
- fs.realpath = origRealpath;
- fs.realpathSync = origRealpathSync;
- }
- var concatMap = function concatMap(xs, fn) {
- var res = [];
- for (var i = 0; i < xs.length; i++) {
- var x = fn(xs[i], i);
- if (isArray(x)) res.push.apply(res, x);else res.push(x);
- }
- return res;
- };
- var isArray = Array.isArray || function (xs) {
- return Object.prototype.toString.call(xs) === '[object Array]';
- };
- var balancedMatch = balanced;
- function balanced(a, b, str) {
- if (a instanceof RegExp) a = maybeMatch(a, str);
- if (b instanceof RegExp) b = maybeMatch(b, str);
- var r = range(a, b, str);
- return r && {
- start: r[0],
- end: r[1],
- pre: str.slice(0, r[0]),
- body: str.slice(r[0] + a.length, r[1]),
- post: str.slice(r[1] + b.length)
- };
- }
- function maybeMatch(reg, str) {
- var m = str.match(reg);
- return m ? m[0] : null;
- }
- balanced.range = range;
- function range(a, b, str) {
- var begs, beg, left, right, result;
- var ai = str.indexOf(a);
- var bi = str.indexOf(b, ai + 1);
- var i = ai;
- if (ai >= 0 && bi > 0) {
- begs = [];
- left = str.length;
- while (i >= 0 && !result) {
- if (i == ai) {
- begs.push(i);
- ai = str.indexOf(a, i + 1);
- } else if (begs.length == 1) {
- result = [begs.pop(), bi];
- } else {
- beg = begs.pop();
- if (beg < left) {
- left = beg;
- right = bi;
- }
- bi = str.indexOf(b, i + 1);
- }
- i = ai < bi && ai >= 0 ? ai : bi;
- }
- if (begs.length) {
- result = [left, right];
- }
- }
- return result;
- }
- var braceExpansion = expandTop;
- var escSlash = '\0SLASH' + Math.random() + '\0';
- var escOpen = '\0OPEN' + Math.random() + '\0';
- var escClose = '\0CLOSE' + Math.random() + '\0';
- var escComma = '\0COMMA' + Math.random() + '\0';
- var escPeriod = '\0PERIOD' + Math.random() + '\0';
- function numeric(str) {
- return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0);
- }
- function escapeBraces(str) {
- return str.split('\\\\').join(escSlash).split('\\{').join(escOpen).split('\\}').join(escClose).split('\\,').join(escComma).split('\\.').join(escPeriod);
- }
- function unescapeBraces(str) {
- return str.split(escSlash).join('\\').split(escOpen).join('{').split(escClose).join('}').split(escComma).join(',').split(escPeriod).join('.');
- } // Basically just str.split(","), but handling cases
- // where we have nested braced sections, which should be
- // treated as individual members, like {a,{b,c},d}
- function parseCommaParts(str) {
- if (!str) return [''];
- var parts = [];
- var m = balancedMatch('{', '}', str);
- if (!m) return str.split(',');
- var pre = m.pre;
- var body = m.body;
- var post = m.post;
- var p = pre.split(',');
- p[p.length - 1] += '{' + body + '}';
- var postParts = parseCommaParts(post);
- if (post.length) {
- p[p.length - 1] += postParts.shift();
- p.push.apply(p, postParts);
- }
- parts.push.apply(parts, p);
- return parts;
- }
- function expandTop(str) {
- if (!str) return []; // I don't know why Bash 4.3 does this, but it does.
- // Anything starting with {} will have the first two bytes preserved
- // but *only* at the top level, so {},a}b will not expand to anything,
- // but a{},b}c will be expanded to [a}c,abc].
- // One could argue that this is a bug in Bash, but since the goal of
- // this module is to match Bash's rules, we escape a leading {}
- if (str.substr(0, 2) === '{}') {
- str = '\\{\\}' + str.substr(2);
- }
- return expand(escapeBraces(str), true).map(unescapeBraces);
- }
- function embrace(str) {
- return '{' + str + '}';
- }
- function isPadded(el) {
- return /^-?0\d/.test(el);
- }
- function lte(i, y) {
- return i <= y;
- }
- function gte(i, y) {
- return i >= y;
- }
- function expand(str, isTop) {
- var expansions = [];
- var m = balancedMatch('{', '}', str);
- if (!m || /\$$/.test(m.pre)) return [str];
- var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
- var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
- var isSequence = isNumericSequence || isAlphaSequence;
- var isOptions = m.body.indexOf(',') >= 0;
- if (!isSequence && !isOptions) {
- // {a},b}
- if (m.post.match(/,.*\}/)) {
- str = m.pre + '{' + m.body + escClose + m.post;
- return expand(str);
- }
- return [str];
- }
- var n;
- if (isSequence) {
- n = m.body.split(/\.\./);
- } else {
- n = parseCommaParts(m.body);
- if (n.length === 1) {
- // x{{a,b}}y ==> x{a}y x{b}y
- n = expand(n[0], false).map(embrace);
- if (n.length === 1) {
- var post = m.post.length ? expand(m.post, false) : [''];
- return post.map(function (p) {
- return m.pre + n[0] + p;
- });
- }
- }
- } // at this point, n is the parts, and we know it's not a comma set
- // with a single entry.
- // no need to expand pre, since it is guaranteed to be free of brace-sets
- var pre = m.pre;
- var post = m.post.length ? expand(m.post, false) : [''];
- var N;
- if (isSequence) {
- var x = numeric(n[0]);
- var y = numeric(n[1]);
- var width = Math.max(n[0].length, n[1].length);
- var incr = n.length == 3 ? Math.abs(numeric(n[2])) : 1;
- var test = lte;
- var reverse = y < x;
- if (reverse) {
- incr *= -1;
- test = gte;
- }
- var pad = n.some(isPadded);
- N = [];
- for (var i = x; test(i, y); i += incr) {
- var c;
- if (isAlphaSequence) {
- c = String.fromCharCode(i);
- if (c === '\\') c = '';
- } else {
- c = String(i);
- if (pad) {
- var need = width - c.length;
- if (need > 0) {
- var z = new Array(need + 1).join('0');
- if (i < 0) c = '-' + z + c.slice(1);else c = z + c;
- }
- }
- }
- N.push(c);
- }
- } else {
- N = concatMap(n, function (el) {
- return expand(el, false);
- });
- }
- for (var j = 0; j < N.length; j++) {
- for (var k = 0; k < post.length; k++) {
- var expansion = pre + N[j] + post[k];
- if (!isTop || isSequence || expansion) expansions.push(expansion);
- }
- }
- return expansions;
- }
- var minimatch_1 = minimatch;
- minimatch.Minimatch = Minimatch$1;
- var path$2 = {
- sep: '/'
- };
- try {
- path$2 = path;
- } catch (er) {}
- var GLOBSTAR = minimatch.GLOBSTAR = Minimatch$1.GLOBSTAR = {};
- var plTypes = {
- '!': {
- open: '(?:(?!(?:',
- close: '))[^/]*?)'
- },
- '?': {
- open: '(?:',
- close: ')?'
- },
- '+': {
- open: '(?:',
- close: ')+'
- },
- '*': {
- open: '(?:',
- close: ')*'
- },
- '@': {
- open: '(?:',
- close: ')'
- } // any single thing other than /
- // don't need to escape / when using new RegExp()
- };
- var qmark = '[^/]'; // * => any number of characters
- var star = qmark + '*?'; // ** when dots are allowed. Anything goes, except .. and .
- // not (^ or / followed by one or two dots followed by $ or /),
- // followed by anything, any number of times.
- var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?'; // not a ^ or / followed by a dot,
- // followed by anything, any number of times.
- var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?'; // characters that need to be escaped in RegExp.
- var reSpecials = charSet('().*{}+?[]^$\\!'); // "abc" -> { a:true, b:true, c:true }
- function charSet(s) {
- return s.split('').reduce(function (set, c) {
- set[c] = true;
- return set;
- }, {});
- } // normalizes slashes.
- var slashSplit = /\/+/;
- minimatch.filter = filter$1;
- function filter$1(pattern, options) {
- options = options || {};
- return function (p, i, list) {
- return minimatch(p, pattern, options);
- };
- }
- function ext(a, b) {
- a = a || {};
- b = b || {};
- var t = {};
- Object.keys(b).forEach(function (k) {
- t[k] = b[k];
- });
- Object.keys(a).forEach(function (k) {
- t[k] = a[k];
- });
- return t;
- }
- minimatch.defaults = function (def) {
- if (!def || !Object.keys(def).length) return minimatch;
- var orig = minimatch;
- var m = function minimatch(p, pattern, options) {
- return orig.minimatch(p, pattern, ext(def, options));
- };
- m.Minimatch = function Minimatch(pattern, options) {
- return new orig.Minimatch(pattern, ext(def, options));
- };
- return m;
- };
- Minimatch$1.defaults = function (def) {
- if (!def || !Object.keys(def).length) return Minimatch$1;
- return minimatch.defaults(def).Minimatch;
- };
- function minimatch(p, pattern, options) {
- if (typeof pattern !== 'string') {
- throw new TypeError('glob pattern string required');
- }
- if (!options) options = {}; // shortcut: comments match nothing.
- if (!options.nocomment && pattern.charAt(0) === '#') {
- return false;
- } // "" only matches ""
- if (pattern.trim() === '') return p === '';
- return new Minimatch$1(pattern, options).match(p);
- }
- function Minimatch$1(pattern, options) {
- if (!(this instanceof Minimatch$1)) {
- return new Minimatch$1(pattern, options);
- }
- if (typeof pattern !== 'string') {
- throw new TypeError('glob pattern string required');
- }
- if (!options) options = {};
- pattern = pattern.trim(); // windows support: need to use /, not \
- if (path$2.sep !== '/') {
- pattern = pattern.split(path$2.sep).join('/');
- }
- this.options = options;
- this.set = [];
- this.pattern = pattern;
- this.regexp = null;
- this.negate = false;
- this.comment = false;
- this.empty = false; // make the set of regexps etc.
- this.make();
- }
- Minimatch$1.prototype.debug = function () {};
- Minimatch$1.prototype.make = make;
- function make() {
- // don't do it more than once.
- if (this._made) return;
- var pattern = this.pattern;
- var options = this.options; // empty patterns and comments match nothing.
- if (!options.nocomment && pattern.charAt(0) === '#') {
- this.comment = true;
- return;
- }
- if (!pattern) {
- this.empty = true;
- return;
- } // step 1: figure out negation, etc.
- this.parseNegate(); // step 2: expand braces
- var set = this.globSet = this.braceExpand();
- if (options.debug) this.debug = console.error;
- this.debug(this.pattern, set); // step 3: now we have a set, so turn each one into a series of path-portion
- // matching patterns.
- // These will be regexps, except in the case of "**", which is
- // set to the GLOBSTAR object for globstar behavior,
- // and will not contain any / characters
- set = this.globParts = set.map(function (s) {
- return s.split(slashSplit);
- });
- this.debug(this.pattern, set); // glob --> regexps
- set = set.map(function (s, si, set) {
- return s.map(this.parse, this);
- }, this);
- this.debug(this.pattern, set); // filter out everything that didn't compile properly.
- set = set.filter(function (s) {
- return s.indexOf(false) === -1;
- });
- this.debug(this.pattern, set);
- this.set = set;
- }
- Minimatch$1.prototype.parseNegate = parseNegate;
- function parseNegate() {
- var pattern = this.pattern;
- var negate = false;
- var options = this.options;
- var negateOffset = 0;
- if (options.nonegate) return;
- for (var i = 0, l = pattern.length; i < l && pattern.charAt(i) === '!'; i++) {
- negate = !negate;
- negateOffset++;
- }
- if (negateOffset) this.pattern = pattern.substr(negateOffset);
- this.negate = negate;
- } // Brace expansion:
- // a{b,c}d -> abd acd
- // a{b,}c -> abc ac
- // a{0..3}d -> a0d a1d a2d a3d
- // a{b,c{d,e}f}g -> abg acdfg acefg
- // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
- //
- // Invalid sets are not expanded.
- // a{2..}b -> a{2..}b
- // a{b}c -> a{b}c
- minimatch.braceExpand = function (pattern, options) {
- return braceExpand(pattern, options);
- };
- Minimatch$1.prototype.braceExpand = braceExpand;
- function braceExpand(pattern, options) {
- if (!options) {
- if (this instanceof Minimatch$1) {
- options = this.options;
- } else {
- options = {};
- }
- }
- pattern = typeof pattern === 'undefined' ? this.pattern : pattern;
- if (typeof pattern === 'undefined') {
- throw new TypeError('undefined pattern');
- }
- if (options.nobrace || !pattern.match(/\{.*\}/)) {
- // shortcut. no need to expand.
- return [pattern];
- }
- return braceExpansion(pattern);
- } // parse a component of the expanded set.
- // At this point, no pattern may contain "/" in it
- // so we're going to return a 2d array, where each entry is the full
- // pattern, split on '/', and then turned into a regular expression.
- // A regexp is made at the end which joins each array with an
- // escaped /, and another full one which joins each regexp with |.
- //
- // Following the lead of Bash 4.1, note that "**" only has special meaning
- // when it is the *only* thing in a path portion. Otherwise, any series
- // of * is equivalent to a single *. Globstar behavior is enabled by
- // default, and can be disabled by setting options.noglobstar.
- Minimatch$1.prototype.parse = parse$3;
- var SUBPARSE = {};
- function parse$3(pattern, isSub) {
- if (pattern.length > 1024 * 64) {
- throw new TypeError('pattern is too long');
- }
- var options = this.options; // shortcuts
- if (!options.noglobstar && pattern === '**') return GLOBSTAR;
- if (pattern === '') return '';
- var re = '';
- var hasMagic = !!options.nocase;
- var escaping = false; // ? => one single character
- var patternListStack = [];
- var negativeLists = [];
- var stateChar;
- var inClass = false;
- var reClassStart = -1;
- var classStart = -1; // . and .. never match anything that doesn't start with .,
- // even when options.dot is set.
- var patternStart = pattern.charAt(0) === '.' ? '' // anything
- // not (start or / followed by . or .. followed by / or end)
- : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' : '(?!\\.)';
- var self = this;
- function clearStateChar() {
- if (stateChar) {
- // we had some state-tracking character
- // that wasn't consumed by this pass.
- switch (stateChar) {
- case '*':
- re += star;
- hasMagic = true;
- break;
- case '?':
- re += qmark;
- hasMagic = true;
- break;
- default:
- re += '\\' + stateChar;
- break;
- }
- self.debug('clearStateChar %j %j', stateChar, re);
- stateChar = false;
- }
- }
- for (var i = 0, len = pattern.length, c; i < len && (c = pattern.charAt(i)); i++) {
- this.debug('%s\t%s %s %j', pattern, i, re, c); // skip over any that are escaped.
- if (escaping && reSpecials[c]) {
- re += '\\' + c;
- escaping = false;
- continue;
- }
- switch (c) {
- case '/':
- // completely not allowed, even escaped.
- // Should already be path-split by now.
- return false;
- case '\\':
- clearStateChar();
- escaping = true;
- continue;
- // the various stateChar values
- // for the "extglob" stuff.
- case '?':
- case '*':
- case '+':
- case '@':
- case '!':
- this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c); // all of those are literals inside a class, except that
- // the glob [!a] means [^a] in regexp
- if (inClass) {
- this.debug(' in class');
- if (c === '!' && i === classStart + 1) c = '^';
- re += c;
- continue;
- } // if we already have a stateChar, then it means
- // that there was something like ** or +? in there.
- // Handle the stateChar, then proceed with this one.
- self.debug('call clearStateChar %j', stateChar);
- clearStateChar();
- stateChar = c; // if extglob is disabled, then +(asdf|foo) isn't a thing.
- // just clear the statechar *now*, rather than even diving into
- // the patternList stuff.
- if (options.noext) clearStateChar();
- continue;
- case '(':
- if (inClass) {
- re += '(';
- continue;
- }
- if (!stateChar) {
- re += '\\(';
- continue;
- }
- patternListStack.push({
- type: stateChar,
- start: i - 1,
- reStart: re.length,
- open: plTypes[stateChar].open,
- close: plTypes[stateChar].close
- }); // negation is (?:(?!js)[^/]*)
- re += stateChar === '!' ? '(?:(?!(?:' : '(?:';
- this.debug('plType %j %j', stateChar, re);
- stateChar = false;
- continue;
- case ')':
- if (inClass || !patternListStack.length) {
- re += '\\)';
- continue;
- }
- clearStateChar();
- hasMagic = true;
- var pl = patternListStack.pop(); // negation is (?:(?!js)[^/]*)
- // The others are (?:<pattern>)<type>
- re += pl.close;
- if (pl.type === '!') {
- negativeLists.push(pl);
- }
- pl.reEnd = re.length;
- continue;
- case '|':
- if (inClass || !patternListStack.length || escaping) {
- re += '\\|';
- escaping = false;
- continue;
- }
- clearStateChar();
- re += '|';
- continue;
- // these are mostly the same in regexp and glob
- case '[':
- // swallow any state-tracking char before the [
- clearStateChar();
- if (inClass) {
- re += '\\' + c;
- continue;
- }
- inClass = true;
- classStart = i;
- reClassStart = re.length;
- re += c;
- continue;
- case ']':
- // a right bracket shall lose its special
- // meaning and represent itself in
- // a bracket expression if it occurs
- // first in the list. -- POSIX.2 2.8.3.2
- if (i === classStart + 1 || !inClass) {
- re += '\\' + c;
- escaping = false;
- continue;
- } // handle the case where we left a class open.
- // "[z-a]" is valid, equivalent to "\[z-a\]"
- if (inClass) {
- // split where the last [ was, make sure we don't have
- // an invalid re. if so, re-walk the contents of the
- // would-be class to re-translate any characters that
- // were passed through as-is
- // TODO: It would probably be faster to determine this
- // without a try/catch and a new RegExp, but it's tricky
- // to do safely. For now, this is safe and works.
- var cs = pattern.substring(classStart + 1, i);
- try {
- RegExp('[' + cs + ']');
- } catch (er) {
- // not a valid class!
- var sp = this.parse(cs, SUBPARSE);
- re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]';
- hasMagic = hasMagic || sp[1];
- inClass = false;
- continue;
- }
- } // finish up the class.
- hasMagic = true;
- inClass = false;
- re += c;
- continue;
- default:
- // swallow any state char that wasn't consumed
- clearStateChar();
- if (escaping) {
- // no need
- escaping = false;
- } else if (reSpecials[c] && !(c === '^' && inClass)) {
- re += '\\';
- }
- re += c;
- } // switch
- } // for
- // handle the case where we left a class open.
- // "[abc" is valid, equivalent to "\[abc"
- if (inClass) {
- // split where the last [ was, and escape it
- // this is a huge pita. We now have to re-walk
- // the contents of the would-be class to re-translate
- // any characters that were passed through as-is
- cs = pattern.substr(classStart + 1);
- sp = this.parse(cs, SUBPARSE);
- re = re.substr(0, reClassStart) + '\\[' + sp[0];
- hasMagic = hasMagic || sp[1];
- } // handle the case where we had a +( thing at the *end*
- // of the pattern.
- // each pattern list stack adds 3 chars, and we need to go through
- // and escape any | chars that were passed through as-is for the regexp.
- // Go through and escape them, taking care not to double-escape any
- // | chars that were already escaped.
- for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
- var tail = re.slice(pl.reStart + pl.open.length);
- this.debug('setting tail', re, pl); // maybe some even number of \, then maybe 1 \, followed by a |
- tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) {
- if (!$2) {
- // the | isn't already escaped, so escape it.
- $2 = '\\';
- } // need to escape all those slashes *again*, without escaping the
- // one that we need for escaping the | character. As it works out,
- // escaping an even number of slashes can be done by simply repeating
- // it exactly after itself. That's why this trick works.
- //
- // I am sorry that you have to see this.
- return $1 + $1 + $2 + '|';
- });
- this.debug('tail=%j\n %s', tail, tail, pl, re);
- var t = pl.type === '*' ? star : pl.type === '?' ? qmark : '\\' + pl.type;
- hasMagic = true;
- re = re.slice(0, pl.reStart) + t + '\\(' + tail;
- } // handle trailing things that only matter at the very end.
- clearStateChar();
- if (escaping) {
- // trailing \\
- re += '\\\\';
- } // only need to apply the nodot start if the re starts with
- // something that could conceivably capture a dot
- var addPatternStart = false;
- switch (re.charAt(0)) {
- case '.':
- case '[':
- case '(':
- addPatternStart = true;
- } // Hack to work around lack of negative lookbehind in JS
- // A pattern like: *.!(x).!(y|z) needs to ensure that a name
- // like 'a.xyz.yz' doesn't match. So, the first negative
- // lookahead, has to look ALL the way ahead, to the end of
- // the pattern.
- for (var n = negativeLists.length - 1; n > -1; n--) {
- var nl = negativeLists[n];
- var nlBefore = re.slice(0, nl.reStart);
- var nlFirst = re.slice(nl.reStart, nl.reEnd - 8);
- var nlLast = re.slice(nl.reEnd - 8, nl.reEnd);
- var nlAfter = re.slice(nl.reEnd);
- nlLast += nlAfter; // Handle nested stuff like *(*.js|!(*.json)), where open parens
- // mean that we should *not* include the ) in the bit that is considered
- // "after" the negated section.
- var openParensBefore = nlBefore.split('(').length - 1;
- var cleanAfter = nlAfter;
- for (i = 0; i < openParensBefore; i++) {
- cleanAfter = cleanAfter.replace(/\)[+*?]?/, '');
- }
- nlAfter = cleanAfter;
- var dollar = '';
- if (nlAfter === '' && isSub !== SUBPARSE) {
- dollar = '$';
- }
- var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast;
- re = newRe;
- } // if the re is not "" at this point, then we need to make sure
- // it doesn't match against an empty path part.
- // Otherwise a/* will match a/, which it should not.
- if (re !== '' && hasMagic) {
- re = '(?=.)' + re;
- }
- if (addPatternStart) {
- re = patternStart + re;
- } // parsing just a piece of a larger pattern.
- if (isSub === SUBPARSE) {
- return [re, hasMagic];
- } // skip the regexp for non-magical patterns
- // unescape anything in it, though, so that it'll be
- // an exact match against a file etc.
- if (!hasMagic) {
- return globUnescape(pattern);
- }
- var flags = options.nocase ? 'i' : '';
- try {
- var regExp = new RegExp('^' + re + '$', flags);
- } catch (er) {
- // If it was an invalid regular expression, then it can't match
- // anything. This trick looks for a character after the end of
- // the string, which is of course impossible, except in multi-line
- // mode, but it's not a /m regex.
- return new RegExp('$.');
- }
- regExp._glob = pattern;
- regExp._src = re;
- return regExp;
- }
- minimatch.makeRe = function (pattern, options) {
- return new Minimatch$1(pattern, options || {}).makeRe();
- };
- Minimatch$1.prototype.makeRe = makeRe;
- function makeRe() {
- if (this.regexp || this.regexp === false) return this.regexp; // at this point, this.set is a 2d array of partial
- // pattern strings, or "**".
- //
- // It's better to use .match(). This function shouldn't
- // be used, really, but it's pretty convenient sometimes,
- // when you just want to work with a regex.
- var set = this.set;
- if (!set.length) {
- this.regexp = false;
- return this.regexp;
- }
- var options = this.options;
- var twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot;
- var flags = options.nocase ? 'i' : '';
- var re = set.map(function (pattern) {
- return pattern.map(function (p) {
- return p === GLOBSTAR ? twoStar : typeof p === 'string' ? regExpEscape(p) : p._src;
- }).join('\\\/');
- }).join('|'); // must match entire pattern
- // ending in a * or ** will make it less strict.
- re = '^(?:' + re + ')$'; // can match anything, as long as it's not this.
- if (this.negate) re = '^(?!' + re + ').*$';
- try {
- this.regexp = new RegExp(re, flags);
- } catch (ex) {
- this.regexp = false;
- }
- return this.regexp;
- }
- minimatch.match = function (list, pattern, options) {
- options = options || {};
- var mm = new Minimatch$1(pattern, options);
- list = list.filter(function (f) {
- return mm.match(f);
- });
- if (mm.options.nonull && !list.length) {
- list.push(pattern);
- }
- return list;
- };
- Minimatch$1.prototype.match = match;
- function match(f, partial) {
- this.debug('match', f, this.pattern); // short-circuit in the case of busted things.
- // comments, etc.
- if (this.comment) return false;
- if (this.empty) return f === '';
- if (f === '/' && partial) return true;
- var options = this.options; // windows: need to use /, not \
- if (path$2.sep !== '/') {
- f = f.split(path$2.sep).join('/');
- } // treat the test path as a set of pathparts.
- f = f.split(slashSplit);
- this.debug(this.pattern, 'split', f); // just ONE of the pattern sets in this.set needs to match
- // in order for it to be valid. If negating, then just one
- // match means that we have failed.
- // Either way, return on the first hit.
- var set = this.set;
- this.debug(this.pattern, 'set', set); // Find the basename of the path by looking for the last non-empty segment
- var filename;
- var i;
- for (i = f.length - 1; i >= 0; i--) {
- filename = f[i];
- if (filename) break;
- }
- for (i = 0; i < set.length; i++) {
- var pattern = set[i];
- var file = f;
- if (options.matchBase && pattern.length === 1) {
- file = [filename];
- }
- var hit = this.matchOne(file, pattern, partial);
- if (hit) {
- if (options.flipNegate) return true;
- return !this.negate;
- }
- } // didn't get any hits. this is success if it's a negative
- // pattern, failure otherwise.
- if (options.flipNegate) return false;
- return this.negate;
- } // set partial to true to test if, for example,
- // "/a/b" matches the start of "/*/b/*/d"
- // Partial means, if you run out of file before you run
- // out of pattern, then that's fine, as long as all
- // the parts match.
- Minimatch$1.prototype.matchOne = function (file, pattern, partial) {
- var options = this.options;
- this.debug('matchOne', {
- 'this': this,
- file: file,
- pattern: pattern
- });
- this.debug('matchOne', file.length, pattern.length);
- for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
- this.debug('matchOne loop');
- var p = pattern[pi];
- var f = file[fi];
- this.debug(pattern, p, f); // should be impossible.
- // some invalid regexp stuff in the set.
- if (p === false) return false;
- if (p === GLOBSTAR) {
- this.debug('GLOBSTAR', [pattern, p, f]); // "**"
- // a/**/b/**/c would match the following:
- // a/b/x/y/z/c
- // a/x/y/z/b/c
- // a/b/x/b/x/c
- // a/b/c
- // To do this, take the rest of the pattern after
- // the **, and see if it would match the file remainder.
- // If so, return success.
- // If not, the ** "swallows" a segment, and try again.
- // This is recursively awful.
- //
- // a/**/b/**/c matching a/b/x/y/z/c
- // - a matches a
- // - doublestar
- // - matchOne(b/x/y/z/c, b/**/c)
- // - b matches b
- // - doublestar
- // - matchOne(x/y/z/c, c) -> no
- // - matchOne(y/z/c, c) -> no
- // - matchOne(z/c, c) -> no
- // - matchOne(c, c) yes, hit
- var fr = fi;
- var pr = pi + 1;
- if (pr === pl) {
- this.debug('** at the end'); // a ** at the end will just swallow the rest.
- // We have found a match.
- // however, it will not swallow /.x, unless
- // options.dot is set.
- // . and .. are *never* matched by **, for explosively
- // exponential reasons.
- for (; fi < fl; fi++) {
- if (file[fi] === '.' || file[fi] === '..' || !options.dot && file[fi].charAt(0) === '.') return false;
- }
- return true;
- } // ok, let's see if we can swallow whatever we can.
- while (fr < fl) {
- var swallowee = file[fr];
- this.debug('\nglobstar while', file, fr, pattern, pr, swallowee); // XXX remove this slice. Just pass the start index.
- if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
- this.debug('globstar found match!', fr, fl, swallowee); // found a match.
- return true;
- } else {
- // can't swallow "." or ".." ever.
- // can only swallow ".foo" when explicitly asked.
- if (swallowee === '.' || swallowee === '..' || !options.dot && swallowee.charAt(0) === '.') {
- this.debug('dot detected!', file, fr, pattern, pr);
- break;
- } // ** swallows a segment, and continue.
- this.debug('globstar swallow a segment, and continue');
- fr++;
- }
- } // no match was found.
- // However, in partial mode, we can't say this is necessarily over.
- // If there's more *pattern* left, then
- if (partial) {
- // ran out of file
- this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
- if (fr === fl) return true;
- }
- return false;
- } // something other than **
- // non-magic patterns just have to match exactly
- // patterns with magic have been turned into regexps.
- var hit;
- if (typeof p === 'string') {
- if (options.nocase) {
- hit = f.toLowerCase() === p.toLowerCase();
- } else {
- hit = f === p;
- }
- this.debug('string match', p, f, hit);
- } else {
- hit = f.match(p);
- this.debug('pattern match', p, f, hit);
- }
- if (!hit) return false;
- } // Note: ending in / means that we'll get a final ""
- // at the end of the pattern. This can only match a
- // corresponding "" at the end of the file.
- // If the file ends in /, then it can only match a
- // a pattern that ends in /, unless the pattern just
- // doesn't have any more for it. But, a/b/ should *not*
- // match "a/b/*", even though "" matches against the
- // [^/]*? pattern, except in partial mode, where it might
- // simply not be reached yet.
- // However, a/b/ should still satisfy a/*
- // now either we fell off the end of the pattern, or we're done.
- if (fi === fl && pi === pl) {
- // ran out of pattern and filename at the same time.
- // an exact hit!
- return true;
- } else if (fi === fl) {
- // ran out of file, but still had pattern left.
- // this is ok if we're doing the match as part of
- // a glob fs traversal.
- return partial;
- } else if (pi === pl) {
- // ran out of pattern, still have file left.
- // this is only acceptable if we're on the very last
- // empty segment of a file with a trailing slash.
- // a/* should match a/b/
- var emptyFileEnd = fi === fl - 1 && file[fi] === '';
- return emptyFileEnd;
- } // should be unreachable.
- throw new Error('wtf?');
- }; // replace stuff like \* with *
- function globUnescape(s) {
- return s.replace(/\\(.)/g, '$1');
- }
- function regExpEscape(s) {
- return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
- }
- var inherits_browser = createCommonjsModule(function (module) {
- if (typeof Object.create === 'function') {
- // implementation from standard node.js 'util' module
- module.exports = function inherits(ctor, superCtor) {
- ctor.super_ = superCtor;
- ctor.prototype = Object.create(superCtor.prototype, {
- constructor: {
- value: ctor,
- enumerable: false,
- writable: true,
- configurable: true
- }
- });
- };
- } else {
- // old school shim for old browsers
- module.exports = function inherits(ctor, superCtor) {
- ctor.super_ = superCtor;
- var TempCtor = function TempCtor() {};
- TempCtor.prototype = superCtor.prototype;
- ctor.prototype = new TempCtor();
- ctor.prototype.constructor = ctor;
- };
- }
- });
- var inherits = createCommonjsModule(function (module) {
- try {
- var util$$1 = util;
- if (typeof util$$1.inherits !== 'function') throw '';
- module.exports = util$$1.inherits;
- } catch (e) {
- module.exports = inherits_browser;
- }
- });
- function posix(path$$1) {
- return path$$1.charAt(0) === '/';
- }
- function win32(path$$1) {
- // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56
- var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/;
- var result = splitDeviceRe.exec(path$$1);
- var device = result[1] || '';
- var isUnc = Boolean(device && device.charAt(1) !== ':'); // UNC paths are always absolute
- return Boolean(result[2] || isUnc);
- }
- var pathIsAbsolute = process.platform === 'win32' ? win32 : posix;
- var posix_1 = posix;
- var win32_1 = win32;
- pathIsAbsolute.posix = posix_1;
- pathIsAbsolute.win32 = win32_1;
- var alphasort_1 = alphasort$2;
- var alphasorti_1 = alphasorti$2;
- var setopts_1 = setopts$2;
- var ownProp_1 = ownProp$2;
- var makeAbs_1 = makeAbs;
- var finish_1 = finish;
- var mark_1 = mark;
- var isIgnored_1 = isIgnored$2;
- var childrenIgnored_1 = childrenIgnored$2;
- function ownProp$2(obj, field) {
- return Object.prototype.hasOwnProperty.call(obj, field);
- }
- var Minimatch$3 = minimatch_1.Minimatch;
- function alphasorti$2(a, b) {
- return a.toLowerCase().localeCompare(b.toLowerCase());
- }
- function alphasort$2(a, b) {
- return a.localeCompare(b);
- }
- function setupIgnores(self, options) {
- self.ignore = options.ignore || [];
- if (!Array.isArray(self.ignore)) self.ignore = [self.ignore];
- if (self.ignore.length) {
- self.ignore = self.ignore.map(ignoreMap);
- }
- } // ignore patterns are always in dot:true mode.
- function ignoreMap(pattern) {
- var gmatcher = null;
- if (pattern.slice(-3) === '/**') {
- var gpattern = pattern.replace(/(\/\*\*)+$/, '');
- gmatcher = new Minimatch$3(gpattern, {
- dot: true
- });
- }
- return {
- matcher: new Minimatch$3(pattern, {
- dot: true
- }),
- gmatcher: gmatcher
- };
- }
- function setopts$2(self, pattern, options) {
- if (!options) options = {}; // base-matching: just use globstar for that.
- if (options.matchBase && -1 === pattern.indexOf("/")) {
- if (options.noglobstar) {
- throw new Error("base matching requires globstar");
- }
- pattern = "**/" + pattern;
- }
- self.silent = !!options.silent;
- self.pattern = pattern;
- self.strict = options.strict !== false;
- self.realpath = !!options.realpath;
- self.realpathCache = options.realpathCache || Object.create(null);
- self.follow = !!options.follow;
- self.dot = !!options.dot;
- self.mark = !!options.mark;
- self.nodir = !!options.nodir;
- if (self.nodir) self.mark = true;
- self.sync = !!options.sync;
- self.nounique = !!options.nounique;
- self.nonull = !!options.nonull;
- self.nosort = !!options.nosort;
- self.nocase = !!options.nocase;
- self.stat = !!options.stat;
- self.noprocess = !!options.noprocess;
- self.absolute = !!options.absolute;
- self.maxLength = options.maxLength || Infinity;
- self.cache = options.cache || Object.create(null);
- self.statCache = options.statCache || Object.create(null);
- self.symlinks = options.symlinks || Object.create(null);
- setupIgnores(self, options);
- self.changedCwd = false;
- var cwd = process.cwd();
- if (!ownProp$2(options, "cwd")) self.cwd = cwd;else {
- self.cwd = path.resolve(options.cwd);
- self.changedCwd = self.cwd !== cwd;
- }
- self.root = options.root || path.resolve(self.cwd, "/");
- self.root = path.resolve(self.root);
- if (process.platform === "win32") self.root = self.root.replace(/\\/g, "/"); // TODO: is an absolute `cwd` supposed to be resolved against `root`?
- // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test')
- self.cwdAbs = pathIsAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd);
- if (process.platform === "win32") self.cwdAbs = self.cwdAbs.replace(/\\/g, "/");
- self.nomount = !!options.nomount; // disable comments and negation in Minimatch.
- // Note that they are not supported in Glob itself anyway.
- options.nonegate = true;
- options.nocomment = true;
- self.minimatch = new Minimatch$3(pattern, options);
- self.options = self.minimatch.options;
- }
- function finish(self) {
- var nou = self.nounique;
- var all = nou ? [] : Object.create(null);
- for (var i = 0, l = self.matches.length; i < l; i++) {
- var matches = self.matches[i];
- if (!matches || Object.keys(matches).length === 0) {
- if (self.nonull) {
- // do like the shell, and spit out the literal glob
- var literal = self.minimatch.globSet[i];
- if (nou) all.push(literal);else all[literal] = true;
- }
- } else {
- // had matches
- var m = Object.keys(matches);
- if (nou) all.push.apply(all, m);else m.forEach(function (m) {
- all[m] = true;
- });
- }
- }
- if (!nou) all = Object.keys(all);
- if (!self.nosort) all = all.sort(self.nocase ? alphasorti$2 : alphasort$2); // at *some* point we statted all of these
- if (self.mark) {
- for (var i = 0; i < all.length; i++) {
- all[i] = self._mark(all[i]);
- }
- if (self.nodir) {
- all = all.filter(function (e) {
- var notDir = !/\/$/.test(e);
- var c = self.cache[e] || self.cache[makeAbs(self, e)];
- if (notDir && c) notDir = c !== 'DIR' && !Array.isArray(c);
- return notDir;
- });
- }
- }
- if (self.ignore.length) all = all.filter(function (m) {
- return !isIgnored$2(self, m);
- });
- self.found = all;
- }
- function mark(self, p) {
- var abs = makeAbs(self, p);
- var c = self.cache[abs];
- var m = p;
- if (c) {
- var isDir = c === 'DIR' || Array.isArray(c);
- var slash = p.slice(-1) === '/';
- if (isDir && !slash) m += '/';else if (!isDir && slash) m = m.slice(0, -1);
- if (m !== p) {
- var mabs = makeAbs(self, m);
- self.statCache[mabs] = self.statCache[abs];
- self.cache[mabs] = self.cache[abs];
- }
- }
- return m;
- } // lotta situps...
- function makeAbs(self, f) {
- var abs = f;
- if (f.charAt(0) === '/') {
- abs = path.join(self.root, f);
- } else if (pathIsAbsolute(f) || f === '') {
- abs = f;
- } else if (self.changedCwd) {
- abs = path.resolve(self.cwd, f);
- } else {
- abs = path.resolve(f);
- }
- if (process.platform === 'win32') abs = abs.replace(/\\/g, '/');
- return abs;
- } // Return true, if pattern ends with globstar '**', for the accompanying parent directory.
- // Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents
- function isIgnored$2(self, path$$2) {
- if (!self.ignore.length) return false;
- return self.ignore.some(function (item) {
- return item.matcher.match(path$$2) || !!(item.gmatcher && item.gmatcher.match(path$$2));
- });
- }
- function childrenIgnored$2(self, path$$2) {
- if (!self.ignore.length) return false;
- return self.ignore.some(function (item) {
- return !!(item.gmatcher && item.gmatcher.match(path$$2));
- });
- }
- var common$4 = {
- alphasort: alphasort_1,
- alphasorti: alphasorti_1,
- setopts: setopts_1,
- ownProp: ownProp_1,
- makeAbs: makeAbs_1,
- finish: finish_1,
- mark: mark_1,
- isIgnored: isIgnored_1,
- childrenIgnored: childrenIgnored_1
- };
- var sync$1 = globSync;
- globSync.GlobSync = GlobSync$1;
- var setopts$1 = common$4.setopts;
- var ownProp$1 = common$4.ownProp;
- var childrenIgnored$1 = common$4.childrenIgnored;
- var isIgnored$1 = common$4.isIgnored;
- function globSync(pattern, options) {
- if (typeof options === 'function' || arguments.length === 3) throw new TypeError('callback provided to sync glob\n' + 'See: https://github.com/isaacs/node-glob/issues/167');
- return new GlobSync$1(pattern, options).found;
- }
- function GlobSync$1(pattern, options) {
- if (!pattern) throw new Error('must provide pattern');
- if (typeof options === 'function' || arguments.length === 3) throw new TypeError('callback provided to sync glob\n' + 'See: https://github.com/isaacs/node-glob/issues/167');
- if (!(this instanceof GlobSync$1)) return new GlobSync$1(pattern, options);
- setopts$1(this, pattern, options);
- if (this.noprocess) return this;
- var n = this.minimatch.set.length;
- this.matches = new Array(n);
- for (var i = 0; i < n; i++) {
- this._process(this.minimatch.set[i], i, false);
- }
- this._finish();
- }
- GlobSync$1.prototype._finish = function () {
- assert(this instanceof GlobSync$1);
- if (this.realpath) {
- var self = this;
- this.matches.forEach(function (matchset, index) {
- var set = self.matches[index] = Object.create(null);
- for (var p in matchset) {
- try {
- p = self._makeAbs(p);
- var real = fs_realpath.realpathSync(p, self.realpathCache);
- set[real] = true;
- } catch (er) {
- if (er.syscall === 'stat') set[self._makeAbs(p)] = true;else throw er;
- }
- }
- });
- }
- common$4.finish(this);
- };
- GlobSync$1.prototype._process = function (pattern, index, inGlobStar) {
- assert(this instanceof GlobSync$1); // Get the first [n] parts of pattern that are all strings.
- var n = 0;
- while (typeof pattern[n] === 'string') {
- n++;
- } // now n is the index of the first one that is *not* a string.
- // See if there's anything else
- var prefix;
- switch (n) {
- // if not, then this is rather simple
- case pattern.length:
- this._processSimple(pattern.join('/'), index);
- return;
- case 0:
- // pattern *starts* with some non-trivial item.
- // going to readdir(cwd), but not include the prefix in matches.
- prefix = null;
- break;
- default:
- // pattern has some string bits in the front.
- // whatever it starts with, whether that's 'absolute' like /foo/bar,
- // or 'relative' like '../baz'
- prefix = pattern.slice(0, n).join('/');
- break;
- }
- var remain = pattern.slice(n); // get the list of entries.
- var read;
- if (prefix === null) read = '.';else if (pathIsAbsolute(prefix) || pathIsAbsolute(pattern.join('/'))) {
- if (!prefix || !pathIsAbsolute(prefix)) prefix = '/' + prefix;
- read = prefix;
- } else read = prefix;
- var abs = this._makeAbs(read); //if ignored, skip processing
- if (childrenIgnored$1(this, read)) return;
- var isGlobStar = remain[0] === minimatch_1.GLOBSTAR;
- if (isGlobStar) this._processGlobStar(prefix, read, abs, remain, index, inGlobStar);else this._processReaddir(prefix, read, abs, remain, index, inGlobStar);
- };
- GlobSync$1.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) {
- var entries = this._readdir(abs, inGlobStar); // if the abs isn't a dir, then nothing can match!
- if (!entries) return; // It will only match dot entries if it starts with a dot, or if
- // dot is set. Stuff like @(.foo|.bar) isn't allowed.
- var pn = remain[0];
- var negate = !!this.minimatch.negate;
- var rawGlob = pn._glob;
- var dotOk = this.dot || rawGlob.charAt(0) === '.';
- var matchedEntries = [];
- for (var i = 0; i < entries.length; i++) {
- var e = entries[i];
- if (e.charAt(0) !== '.' || dotOk) {
- var m;
- if (negate && !prefix) {
- m = !e.match(pn);
- } else {
- m = e.match(pn);
- }
- if (m) matchedEntries.push(e);
- }
- }
- var len = matchedEntries.length; // If there are no matched entries, then nothing matches.
- if (len === 0) return; // if this is the last remaining pattern bit, then no need for
- // an additional stat *unless* the user has specified mark or
- // stat explicitly. We know they exist, since readdir returned
- // them.
- if (remain.length === 1 && !this.mark && !this.stat) {
- if (!this.matches[index]) this.matches[index] = Object.create(null);
- for (var i = 0; i < len; i++) {
- var e = matchedEntries[i];
- if (prefix) {
- if (prefix.slice(-1) !== '/') e = prefix + '/' + e;else e = prefix + e;
- }
- if (e.charAt(0) === '/' && !this.nomount) {
- e = path.join(this.root, e);
- }
- this._emitMatch(index, e);
- } // This was the last one, and no stats were needed
- return;
- } // now test all matched entries as stand-ins for that part
- // of the pattern.
- remain.shift();
- for (var i = 0; i < len; i++) {
- var e = matchedEntries[i];
- var newPattern;
- if (prefix) newPattern = [prefix, e];else newPattern = [e];
- this._process(newPattern.concat(remain), index, inGlobStar);
- }
- };
- GlobSync$1.prototype._emitMatch = function (index, e) {
- if (isIgnored$1(this, e)) return;
- var abs = this._makeAbs(e);
- if (this.mark) e = this._mark(e);
- if (this.absolute) {
- e = abs;
- }
- if (this.matches[index][e]) return;
- if (this.nodir) {
- var c = this.cache[abs];
- if (c === 'DIR' || Array.isArray(c)) return;
- }
- this.matches[index][e] = true;
- if (this.stat) this._stat(e);
- };
- GlobSync$1.prototype._readdirInGlobStar = function (abs) {
- // follow all symlinked directories forever
- // just proceed as if this is a non-globstar situation
- if (this.follow) return this._readdir(abs, false);
- var entries;
- var lstat;
- var stat;
- try {
- lstat = fs.lstatSync(abs);
- } catch (er) {
- if (er.code === 'ENOENT') {
- // lstat failed, doesn't exist
- return null;
- }
- }
- var isSym = lstat && lstat.isSymbolicLink();
- this.symlinks[abs] = isSym; // If it's not a symlink or a dir, then it's definitely a regular file.
- // don't bother doing a readdir in that case.
- if (!isSym && lstat && !lstat.isDirectory()) this.cache[abs] = 'FILE';else entries = this._readdir(abs, false);
- return entries;
- };
- GlobSync$1.prototype._readdir = function (abs, inGlobStar) {
- var entries;
- if (inGlobStar && !ownProp$1(this.symlinks, abs)) return this._readdirInGlobStar(abs);
- if (ownProp$1(this.cache, abs)) {
- var c = this.cache[abs];
- if (!c || c === 'FILE') return null;
- if (Array.isArray(c)) return c;
- }
- try {
- return this._readdirEntries(abs, fs.readdirSync(abs));
- } catch (er) {
- this._readdirError(abs, er);
- return null;
- }
- };
- GlobSync$1.prototype._readdirEntries = function (abs, entries) {
- // if we haven't asked to stat everything, then just
- // assume that everything in there exists, so we can avoid
- // having to stat it a second time.
- if (!this.mark && !this.stat) {
- for (var i = 0; i < entries.length; i++) {
- var e = entries[i];
- if (abs === '/') e = abs + e;else e = abs + '/' + e;
- this.cache[e] = true;
- }
- }
- this.cache[abs] = entries; // mark and cache dir-ness
- return entries;
- };
- GlobSync$1.prototype._readdirError = function (f, er) {
- // handle errors, and cache the information
- switch (er.code) {
- case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
- case 'ENOTDIR':
- // totally normal. means it *does* exist.
- var abs = this._makeAbs(f);
- this.cache[abs] = 'FILE';
- if (abs === this.cwdAbs) {
- var error = new Error(er.code + ' invalid cwd ' + this.cwd);
- error.path = this.cwd;
- error.code = er.code;
- throw error;
- }
- break;
- case 'ENOENT': // not terribly unusual
- case 'ELOOP':
- case 'ENAMETOOLONG':
- case 'UNKNOWN':
- this.cache[this._makeAbs(f)] = false;
- break;
- default:
- // some unusual error. Treat as failure.
- this.cache[this._makeAbs(f)] = false;
- if (this.strict) throw er;
- if (!this.silent) console.error('glob error', er);
- break;
- }
- };
- GlobSync$1.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) {
- var entries = this._readdir(abs, inGlobStar); // no entries means not a dir, so it can never have matches
- // foo.txt/** doesn't match foo.txt
- if (!entries) return; // test without the globstar, and with every child both below
- // and replacing the globstar.
- var remainWithoutGlobStar = remain.slice(1);
- var gspref = prefix ? [prefix] : [];
- var noGlobStar = gspref.concat(remainWithoutGlobStar); // the noGlobStar pattern exits the inGlobStar state
- this._process(noGlobStar, index, false);
- var len = entries.length;
- var isSym = this.symlinks[abs]; // If it's a symlink, and we're in a globstar, then stop
- if (isSym && inGlobStar) return;
- for (var i = 0; i < len; i++) {
- var e = entries[i];
- if (e.charAt(0) === '.' && !this.dot) continue; // these two cases enter the inGlobStar state
- var instead = gspref.concat(entries[i], remainWithoutGlobStar);
- this._process(instead, index, true);
- var below = gspref.concat(entries[i], remain);
- this._process(below, index, true);
- }
- };
- GlobSync$1.prototype._processSimple = function (prefix, index) {
- // XXX review this. Shouldn't it be doing the mounting etc
- // before doing stat? kinda weird?
- var exists = this._stat(prefix);
- if (!this.matches[index]) this.matches[index] = Object.create(null); // If it doesn't exist, then just mark the lack of results
- if (!exists) return;
- if (prefix && pathIsAbsolute(prefix) && !this.nomount) {
- var trail = /[\/\\]$/.test(prefix);
- if (prefix.charAt(0) === '/') {
- prefix = path.join(this.root, prefix);
- } else {
- prefix = path.resolve(this.root, prefix);
- if (trail) prefix += '/';
- }
- }
- if (process.platform === 'win32') prefix = prefix.replace(/\\/g, '/'); // Mark this as a match
- this._emitMatch(index, prefix);
- }; // Returns either 'DIR', 'FILE', or false
- GlobSync$1.prototype._stat = function (f) {
- var abs = this._makeAbs(f);
- var needDir = f.slice(-1) === '/';
- if (f.length > this.maxLength) return false;
- if (!this.stat && ownProp$1(this.cache, abs)) {
- var c = this.cache[abs];
- if (Array.isArray(c)) c = 'DIR'; // It exists, but maybe not how we need it
- if (!needDir || c === 'DIR') return c;
- if (needDir && c === 'FILE') return false; // otherwise we have to stat, because maybe c=true
- // if we know it exists, but not what it is.
- }
- var exists;
- var stat = this.statCache[abs];
- if (!stat) {
- var lstat;
- try {
- lstat = fs.lstatSync(abs);
- } catch (er) {
- if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
- this.statCache[abs] = false;
- return false;
- }
- }
- if (lstat && lstat.isSymbolicLink()) {
- try {
- stat = fs.statSync(abs);
- } catch (er) {
- stat = lstat;
- }
- } else {
- stat = lstat;
- }
- }
- this.statCache[abs] = stat;
- var c = true;
- if (stat) c = stat.isDirectory() ? 'DIR' : 'FILE';
- this.cache[abs] = this.cache[abs] || c;
- if (needDir && c === 'FILE') return false;
- return c;
- };
- GlobSync$1.prototype._mark = function (p) {
- return common$4.mark(this, p);
- };
- GlobSync$1.prototype._makeAbs = function (f) {
- return common$4.makeAbs(this, f);
- };
- // Returns a wrapper function that returns a wrapped callback
- // The wrapper function should do some stuff, and return a
- // presumably different callback function.
- // This makes sure that own properties are retained, so that
- // decorations and such are not lost along the way.
- var wrappy_1 = wrappy;
- function wrappy(fn, cb) {
- if (fn && cb) return wrappy(fn)(cb);
- if (typeof fn !== 'function') throw new TypeError('need wrapper function');
- Object.keys(fn).forEach(function (k) {
- wrapper[k] = fn[k];
- });
- return wrapper;
- function wrapper() {
- var args = new Array(arguments.length);
- for (var i = 0; i < args.length; i++) {
- args[i] = arguments[i];
- }
- var ret = fn.apply(this, args);
- var cb = args[args.length - 1];
- if (typeof ret === 'function' && ret !== cb) {
- Object.keys(cb).forEach(function (k) {
- ret[k] = cb[k];
- });
- }
- return ret;
- }
- }
- var once_1 = wrappy_1(once);
- var strict = wrappy_1(onceStrict);
- once.proto = once(function () {
- Object.defineProperty(Function.prototype, 'once', {
- value: function value() {
- return once(this);
- },
- configurable: true
- });
- Object.defineProperty(Function.prototype, 'onceStrict', {
- value: function value() {
- return onceStrict(this);
- },
- configurable: true
- });
- });
- function once(fn) {
- var f = function f() {
- if (f.called) return f.value;
- f.called = true;
- return f.value = fn.apply(this, arguments);
- };
- f.called = false;
- return f;
- }
- function onceStrict(fn) {
- var f = function f() {
- if (f.called) throw new Error(f.onceError);
- f.called = true;
- return f.value = fn.apply(this, arguments);
- };
- var name = fn.name || 'Function wrapped with `once`';
- f.onceError = name + " shouldn't be called more than once";
- f.called = false;
- return f;
- }
- once_1.strict = strict;
- var reqs = Object.create(null);
- var inflight_1 = wrappy_1(inflight);
- function inflight(key, cb) {
- if (reqs[key]) {
- reqs[key].push(cb);
- return null;
- } else {
- reqs[key] = [cb];
- return makeres(key);
- }
- }
- function makeres(key) {
- return once_1(function RES() {
- var cbs = reqs[key];
- var len = cbs.length;
- var args = slice(arguments); // XXX It's somewhat ambiguous whether a new callback added in this
- // pass should be queued for later execution if something in the
- // list of callbacks throws, or if it should just be discarded.
- // However, it's such an edge case that it hardly matters, and either
- // choice is likely as surprising as the other.
- // As it happens, we do go ahead and schedule it for later execution.
- try {
- for (var i = 0; i < len; i++) {
- cbs[i].apply(null, args);
- }
- } finally {
- if (cbs.length > len) {
- // added more in the interim.
- // de-zalgo, just in case, but don't call again.
- cbs.splice(0, len);
- process.nextTick(function () {
- RES.apply(null, args);
- });
- } else {
- delete reqs[key];
- }
- }
- });
- }
- function slice(args) {
- var length = args.length;
- var array = [];
- for (var i = 0; i < length; i++) {
- array[i] = args[i];
- }
- return array;
- }
- //
- // 1. Get the minimatch set
- // 2. For each pattern in the set, PROCESS(pattern, false)
- // 3. Store matches per-set, then uniq them
- //
- // PROCESS(pattern, inGlobStar)
- // Get the first [n] items from pattern that are all strings
- // Join these together. This is PREFIX.
- // If there is no more remaining, then stat(PREFIX) and
- // add to matches if it succeeds. END.
- //
- // If inGlobStar and PREFIX is symlink and points to dir
- // set ENTRIES = []
- // else readdir(PREFIX) as ENTRIES
- // If fail, END
- //
- // with ENTRIES
- // If pattern[n] is GLOBSTAR
- // // handle the case where the globstar match is empty
- // // by pruning it out, and testing the resulting pattern
- // PROCESS(pattern[0..n] + pattern[n+1 .. $], false)
- // // handle other cases.
- // for ENTRY in ENTRIES (not dotfiles)
- // // attach globstar + tail onto the entry
- // // Mark that this entry is a globstar match
- // PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true)
- //
- // else // not globstar
- // for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot)
- // Test ENTRY against pattern[n]
- // If fails, continue
- // If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $])
- //
- // Caveat:
- // Cache all stats and readdirs results to minimize syscall. Since all
- // we ever care about is existence and directory-ness, we can just keep
- // `true` for files, and [children,...] for directories, or `false` for
- // things that don't exist.
- var glob_1 = glob;
- var EE = events.EventEmitter;
- var setopts = common$4.setopts;
- var ownProp = common$4.ownProp;
- var childrenIgnored = common$4.childrenIgnored;
- var isIgnored = common$4.isIgnored;
- function glob(pattern, options, cb) {
- if (typeof options === 'function') cb = options, options = {};
- if (!options) options = {};
- if (options.sync) {
- if (cb) throw new TypeError('callback provided to sync glob');
- return sync$1(pattern, options);
- }
- return new Glob(pattern, options, cb);
- }
- glob.sync = sync$1;
- var GlobSync = glob.GlobSync = sync$1.GlobSync; // old api surface
- glob.glob = glob;
- function extend(origin, add) {
- if (add === null || typeof add !== 'object') {
- return origin;
- }
- var keys = Object.keys(add);
- var i = keys.length;
- while (i--) {
- origin[keys[i]] = add[keys[i]];
- }
- return origin;
- }
- glob.hasMagic = function (pattern, options_) {
- var options = extend({}, options_);
- options.noprocess = true;
- var g = new Glob(pattern, options);
- var set = g.minimatch.set;
- if (!pattern) return false;
- if (set.length > 1) return true;
- for (var j = 0; j < set[0].length; j++) {
- if (typeof set[0][j] !== 'string') return true;
- }
- return false;
- };
- glob.Glob = Glob;
- inherits(Glob, EE);
- function Glob(pattern, options, cb) {
- if (typeof options === 'function') {
- cb = options;
- options = null;
- }
- if (options && options.sync) {
- if (cb) throw new TypeError('callback provided to sync glob');
- return new GlobSync(pattern, options);
- }
- if (!(this instanceof Glob)) return new Glob(pattern, options, cb);
- setopts(this, pattern, options);
- this._didRealPath = false; // process each pattern in the minimatch set
- var n = this.minimatch.set.length; // The matches are stored as {<filename>: true,...} so that
- // duplicates are automagically pruned.
- // Later, we do an Object.keys() on these.
- // Keep them as a list so we can fill in when nonull is set.
- this.matches = new Array(n);
- if (typeof cb === 'function') {
- cb = once_1(cb);
- this.on('error', cb);
- this.on('end', function (matches) {
- cb(null, matches);
- });
- }
- var self = this;
- this._processing = 0;
- this._emitQueue = [];
- this._processQueue = [];
- this.paused = false;
- if (this.noprocess) return this;
- if (n === 0) return done();
- var sync = true;
- for (var i = 0; i < n; i++) {
- this._process(this.minimatch.set[i], i, false, done);
- }
- sync = false;
- function done() {
- --self._processing;
- if (self._processing <= 0) {
- if (sync) {
- process.nextTick(function () {
- self._finish();
- });
- } else {
- self._finish();
- }
- }
- }
- }
- Glob.prototype._finish = function () {
- assert(this instanceof Glob);
- if (this.aborted) return;
- if (this.realpath && !this._didRealpath) return this._realpath();
- common$4.finish(this);
- this.emit('end', this.found);
- };
- Glob.prototype._realpath = function () {
- if (this._didRealpath) return;
- this._didRealpath = true;
- var n = this.matches.length;
- if (n === 0) return this._finish();
- var self = this;
- for (var i = 0; i < this.matches.length; i++) {
- this._realpathSet(i, next);
- }
- function next() {
- if (--n === 0) self._finish();
- }
- };
- Glob.prototype._realpathSet = function (index, cb) {
- var matchset = this.matches[index];
- if (!matchset) return cb();
- var found = Object.keys(matchset);
- var self = this;
- var n = found.length;
- if (n === 0) return cb();
- var set = this.matches[index] = Object.create(null);
- found.forEach(function (p, i) {
- // If there's a problem with the stat, then it means that
- // one or more of the links in the realpath couldn't be
- // resolved. just return the abs value in that case.
- p = self._makeAbs(p);
- fs_realpath.realpath(p, self.realpathCache, function (er, real) {
- if (!er) set[real] = true;else if (er.syscall === 'stat') set[p] = true;else self.emit('error', er); // srsly wtf right here
- if (--n === 0) {
- self.matches[index] = set;
- cb();
- }
- });
- });
- };
- Glob.prototype._mark = function (p) {
- return common$4.mark(this, p);
- };
- Glob.prototype._makeAbs = function (f) {
- return common$4.makeAbs(this, f);
- };
- Glob.prototype.abort = function () {
- this.aborted = true;
- this.emit('abort');
- };
- Glob.prototype.pause = function () {
- if (!this.paused) {
- this.paused = true;
- this.emit('pause');
- }
- };
- Glob.prototype.resume = function () {
- if (this.paused) {
- this.emit('resume');
- this.paused = false;
- if (this._emitQueue.length) {
- var eq = this._emitQueue.slice(0);
- this._emitQueue.length = 0;
- for (var i = 0; i < eq.length; i++) {
- var e = eq[i];
- this._emitMatch(e[0], e[1]);
- }
- }
- if (this._processQueue.length) {
- var pq = this._processQueue.slice(0);
- this._processQueue.length = 0;
- for (var i = 0; i < pq.length; i++) {
- var p = pq[i];
- this._processing--;
- this._process(p[0], p[1], p[2], p[3]);
- }
- }
- }
- };
- Glob.prototype._process = function (pattern, index, inGlobStar, cb) {
- assert(this instanceof Glob);
- assert(typeof cb === 'function');
- if (this.aborted) return;
- this._processing++;
- if (this.paused) {
- this._processQueue.push([pattern, index, inGlobStar, cb]);
- return;
- } //console.error('PROCESS %d', this._processing, pattern)
- // Get the first [n] parts of pattern that are all strings.
- var n = 0;
- while (typeof pattern[n] === 'string') {
- n++;
- } // now n is the index of the first one that is *not* a string.
- // see if there's anything else
- var prefix;
- switch (n) {
- // if not, then this is rather simple
- case pattern.length:
- this._processSimple(pattern.join('/'), index, cb);
- return;
- case 0:
- // pattern *starts* with some non-trivial item.
- // going to readdir(cwd), but not include the prefix in matches.
- prefix = null;
- break;
- default:
- // pattern has some string bits in the front.
- // whatever it starts with, whether that's 'absolute' like /foo/bar,
- // or 'relative' like '../baz'
- prefix = pattern.slice(0, n).join('/');
- break;
- }
- var remain = pattern.slice(n); // get the list of entries.
- var read;
- if (prefix === null) read = '.';else if (pathIsAbsolute(prefix) || pathIsAbsolute(pattern.join('/'))) {
- if (!prefix || !pathIsAbsolute(prefix)) prefix = '/' + prefix;
- read = prefix;
- } else read = prefix;
- var abs = this._makeAbs(read); //if ignored, skip _processing
- if (childrenIgnored(this, read)) return cb();
- var isGlobStar = remain[0] === minimatch_1.GLOBSTAR;
- if (isGlobStar) this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb);else this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb);
- };
- Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) {
- var self = this;
- this._readdir(abs, inGlobStar, function (er, entries) {
- return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb);
- });
- };
- Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
- // if the abs isn't a dir, then nothing can match!
- if (!entries) return cb(); // It will only match dot entries if it starts with a dot, or if
- // dot is set. Stuff like @(.foo|.bar) isn't allowed.
- var pn = remain[0];
- var negate = !!this.minimatch.negate;
- var rawGlob = pn._glob;
- var dotOk = this.dot || rawGlob.charAt(0) === '.';
- var matchedEntries = [];
- for (var i = 0; i < entries.length; i++) {
- var e = entries[i];
- if (e.charAt(0) !== '.' || dotOk) {
- var m;
- if (negate && !prefix) {
- m = !e.match(pn);
- } else {
- m = e.match(pn);
- }
- if (m) matchedEntries.push(e);
- }
- } //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries)
- var len = matchedEntries.length; // If there are no matched entries, then nothing matches.
- if (len === 0) return cb(); // if this is the last remaining pattern bit, then no need for
- // an additional stat *unless* the user has specified mark or
- // stat explicitly. We know they exist, since readdir returned
- // them.
- if (remain.length === 1 && !this.mark && !this.stat) {
- if (!this.matches[index]) this.matches[index] = Object.create(null);
- for (var i = 0; i < len; i++) {
- var e = matchedEntries[i];
- if (prefix) {
- if (prefix !== '/') e = prefix + '/' + e;else e = prefix + e;
- }
- if (e.charAt(0) === '/' && !this.nomount) {
- e = path.join(this.root, e);
- }
- this._emitMatch(index, e);
- } // This was the last one, and no stats were needed
- return cb();
- } // now test all matched entries as stand-ins for that part
- // of the pattern.
- remain.shift();
- for (var i = 0; i < len; i++) {
- var e = matchedEntries[i];
- var newPattern;
- if (prefix) {
- if (prefix !== '/') e = prefix + '/' + e;else e = prefix + e;
- }
- this._process([e].concat(remain), index, inGlobStar, cb);
- }
- cb();
- };
- Glob.prototype._emitMatch = function (index, e) {
- if (this.aborted) return;
- if (isIgnored(this, e)) return;
- if (this.paused) {
- this._emitQueue.push([index, e]);
- return;
- }
- var abs = pathIsAbsolute(e) ? e : this._makeAbs(e);
- if (this.mark) e = this._mark(e);
- if (this.absolute) e = abs;
- if (this.matches[index][e]) return;
- if (this.nodir) {
- var c = this.cache[abs];
- if (c === 'DIR' || Array.isArray(c)) return;
- }
- this.matches[index][e] = true;
- var st = this.statCache[abs];
- if (st) this.emit('stat', e, st);
- this.emit('match', e);
- };
- Glob.prototype._readdirInGlobStar = function (abs, cb) {
- if (this.aborted) return; // follow all symlinked directories forever
- // just proceed as if this is a non-globstar situation
- if (this.follow) return this._readdir(abs, false, cb);
- var lstatkey = 'lstat\0' + abs;
- var self = this;
- var lstatcb = inflight_1(lstatkey, lstatcb_);
- if (lstatcb) fs.lstat(abs, lstatcb);
- function lstatcb_(er, lstat) {
- if (er && er.code === 'ENOENT') return cb();
- var isSym = lstat && lstat.isSymbolicLink();
- self.symlinks[abs] = isSym; // If it's not a symlink or a dir, then it's definitely a regular file.
- // don't bother doing a readdir in that case.
- if (!isSym && lstat && !lstat.isDirectory()) {
- self.cache[abs] = 'FILE';
- cb();
- } else self._readdir(abs, false, cb);
- }
- };
- Glob.prototype._readdir = function (abs, inGlobStar, cb) {
- if (this.aborted) return;
- cb = inflight_1('readdir\0' + abs + '\0' + inGlobStar, cb);
- if (!cb) return; //console.error('RD %j %j', +inGlobStar, abs)
- if (inGlobStar && !ownProp(this.symlinks, abs)) return this._readdirInGlobStar(abs, cb);
- if (ownProp(this.cache, abs)) {
- var c = this.cache[abs];
- if (!c || c === 'FILE') return cb();
- if (Array.isArray(c)) return cb(null, c);
- }
- var self = this;
- fs.readdir(abs, readdirCb(this, abs, cb));
- };
- function readdirCb(self, abs, cb) {
- return function (er, entries) {
- if (er) self._readdirError(abs, er, cb);else self._readdirEntries(abs, entries, cb);
- };
- }
- Glob.prototype._readdirEntries = function (abs, entries, cb) {
- if (this.aborted) return; // if we haven't asked to stat everything, then just
- // assume that everything in there exists, so we can avoid
- // having to stat it a second time.
- if (!this.mark && !this.stat) {
- for (var i = 0; i < entries.length; i++) {
- var e = entries[i];
- if (abs === '/') e = abs + e;else e = abs + '/' + e;
- this.cache[e] = true;
- }
- }
- this.cache[abs] = entries;
- return cb(null, entries);
- };
- Glob.prototype._readdirError = function (f, er, cb) {
- if (this.aborted) return; // handle errors, and cache the information
- switch (er.code) {
- case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
- case 'ENOTDIR':
- // totally normal. means it *does* exist.
- var abs = this._makeAbs(f);
- this.cache[abs] = 'FILE';
- if (abs === this.cwdAbs) {
- var error = new Error(er.code + ' invalid cwd ' + this.cwd);
- error.path = this.cwd;
- error.code = er.code;
- this.emit('error', error);
- this.abort();
- }
- break;
- case 'ENOENT': // not terribly unusual
- case 'ELOOP':
- case 'ENAMETOOLONG':
- case 'UNKNOWN':
- this.cache[this._makeAbs(f)] = false;
- break;
- default:
- // some unusual error. Treat as failure.
- this.cache[this._makeAbs(f)] = false;
- if (this.strict) {
- this.emit('error', er); // If the error is handled, then we abort
- // if not, we threw out of here
- this.abort();
- }
- if (!this.silent) console.error('glob error', er);
- break;
- }
- return cb();
- };
- Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) {
- var self = this;
- this._readdir(abs, inGlobStar, function (er, entries) {
- self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb);
- });
- };
- Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
- //console.error('pgs2', prefix, remain[0], entries)
- // no entries means not a dir, so it can never have matches
- // foo.txt/** doesn't match foo.txt
- if (!entries) return cb(); // test without the globstar, and with every child both below
- // and replacing the globstar.
- var remainWithoutGlobStar = remain.slice(1);
- var gspref = prefix ? [prefix] : [];
- var noGlobStar = gspref.concat(remainWithoutGlobStar); // the noGlobStar pattern exits the inGlobStar state
- this._process(noGlobStar, index, false, cb);
- var isSym = this.symlinks[abs];
- var len = entries.length; // If it's a symlink, and we're in a globstar, then stop
- if (isSym && inGlobStar) return cb();
- for (var i = 0; i < len; i++) {
- var e = entries[i];
- if (e.charAt(0) === '.' && !this.dot) continue; // these two cases enter the inGlobStar state
- var instead = gspref.concat(entries[i], remainWithoutGlobStar);
- this._process(instead, index, true, cb);
- var below = gspref.concat(entries[i], remain);
- this._process(below, index, true, cb);
- }
- cb();
- };
- Glob.prototype._processSimple = function (prefix, index, cb) {
- // XXX review this. Shouldn't it be doing the mounting etc
- // before doing stat? kinda weird?
- var self = this;
- this._stat(prefix, function (er, exists) {
- self._processSimple2(prefix, index, er, exists, cb);
- });
- };
- Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) {
- //console.error('ps2', prefix, exists)
- if (!this.matches[index]) this.matches[index] = Object.create(null); // If it doesn't exist, then just mark the lack of results
- if (!exists) return cb();
- if (prefix && pathIsAbsolute(prefix) && !this.nomount) {
- var trail = /[\/\\]$/.test(prefix);
- if (prefix.charAt(0) === '/') {
- prefix = path.join(this.root, prefix);
- } else {
- prefix = path.resolve(this.root, prefix);
- if (trail) prefix += '/';
- }
- }
- if (process.platform === 'win32') prefix = prefix.replace(/\\/g, '/'); // Mark this as a match
- this._emitMatch(index, prefix);
- cb();
- }; // Returns either 'DIR', 'FILE', or false
- Glob.prototype._stat = function (f, cb) {
- var abs = this._makeAbs(f);
- var needDir = f.slice(-1) === '/';
- if (f.length > this.maxLength) return cb();
- if (!this.stat && ownProp(this.cache, abs)) {
- var c = this.cache[abs];
- if (Array.isArray(c)) c = 'DIR'; // It exists, but maybe not how we need it
- if (!needDir || c === 'DIR') return cb(null, c);
- if (needDir && c === 'FILE') return cb(); // otherwise we have to stat, because maybe c=true
- // if we know it exists, but not what it is.
- }
- var exists;
- var stat = this.statCache[abs];
- if (stat !== undefined) {
- if (stat === false) return cb(null, stat);else {
- var type = stat.isDirectory() ? 'DIR' : 'FILE';
- if (needDir && type === 'FILE') return cb();else return cb(null, type, stat);
- }
- }
- var self = this;
- var statcb = inflight_1('stat\0' + abs, lstatcb_);
- if (statcb) fs.lstat(abs, statcb);
- function lstatcb_(er, lstat) {
- if (lstat && lstat.isSymbolicLink()) {
- // If it's a symlink, then treat it as the target, unless
- // the target does not exist, then treat it as a file.
- return fs.stat(abs, function (er, stat) {
- if (er) self._stat2(f, abs, null, lstat, cb);else self._stat2(f, abs, er, stat, cb);
- });
- } else {
- self._stat2(f, abs, er, lstat, cb);
- }
- }
- };
- Glob.prototype._stat2 = function (f, abs, er, stat, cb) {
- if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
- this.statCache[abs] = false;
- return cb();
- }
- var needDir = f.slice(-1) === '/';
- this.statCache[abs] = stat;
- if (abs.slice(-1) === '/' && stat && !stat.isDirectory()) return cb(null, false, stat);
- var c = true;
- if (stat) c = stat.isDirectory() ? 'DIR' : 'FILE';
- this.cache[abs] = this.cache[abs] || c;
- if (needDir && c === 'FILE') return cb();
- return cb(null, c, stat);
- };
- var pify_1 = createCommonjsModule(function (module) {
- 'use strict';
- var processFn = function processFn(fn, P, opts) {
- return function () {
- var that = this;
- var args = new Array(arguments.length);
- for (var i = 0; i < arguments.length; i++) {
- args[i] = arguments[i];
- }
- return new P(function (resolve, reject) {
- args.push(function (err, result) {
- if (err) {
- reject(err);
- } else if (opts.multiArgs) {
- var results = new Array(arguments.length - 1);
- for (var i = 1; i < arguments.length; i++) {
- results[i - 1] = arguments[i];
- }
- resolve(results);
- } else {
- resolve(result);
- }
- });
- fn.apply(that, args);
- });
- };
- };
- var pify = module.exports = function (obj, P, opts) {
- if (typeof P !== 'function') {
- opts = P;
- P = Promise;
- }
- opts = opts || {};
- opts.exclude = opts.exclude || [/.+Sync$/];
- var filter = function filter(key) {
- var match = function match(pattern) {
- return typeof pattern === 'string' ? key === pattern : pattern.test(key);
- };
- return opts.include ? opts.include.some(match) : !opts.exclude.some(match);
- };
- var ret = typeof obj === 'function' ? function () {
- if (opts.excludeMain) {
- return obj.apply(this, arguments);
- }
- return processFn(obj, P, opts).apply(this, arguments);
- } : {};
- return Object.keys(obj).reduce(function (ret, key) {
- var x = obj[key];
- ret[key] = typeof x === 'function' && filter(key) ? processFn(x, P, opts) : x;
- return ret;
- }, ret);
- };
- pify.all = pify;
- });
- var globP = pify_1(glob_1, pinkiePromise).bind(glob_1);
- function isNegative(pattern) {
- return pattern[0] === '!';
- }
- function isString(value) {
- return typeof value === 'string';
- }
- function assertPatternsInput(patterns) {
- if (!patterns.every(isString)) {
- throw new TypeError('patterns must be a string or an array of strings');
- }
- }
- function generateGlobTasks(patterns, opts) {
- patterns = [].concat(patterns);
- assertPatternsInput(patterns);
- var globTasks = [];
- opts = objectAssign({
- cache: Object.create(null),
- statCache: Object.create(null),
- realpathCache: Object.create(null),
- symlinks: Object.create(null),
- ignore: []
- }, opts);
- patterns.forEach(function (pattern, i) {
- if (isNegative(pattern)) {
- return;
- }
- var ignore = patterns.slice(i).filter(isNegative).map(function (pattern) {
- return pattern.slice(1);
- });
- globTasks.push({
- pattern: pattern,
- opts: objectAssign({}, opts, {
- ignore: opts.ignore.concat(ignore)
- })
- });
- });
- return globTasks;
- }
- var globby = function globby(patterns, opts) {
- var globTasks;
- try {
- globTasks = generateGlobTasks(patterns, opts);
- } catch (err) {
- return pinkiePromise.reject(err);
- }
- return pinkiePromise.all(globTasks.map(function (task) {
- return globP(task.pattern, task.opts);
- })).then(function (paths) {
- return arrayUnion.apply(null, paths);
- });
- };
- var sync = function sync(patterns, opts) {
- var globTasks = generateGlobTasks(patterns, opts);
- return globTasks.reduce(function (matches, task) {
- return arrayUnion(matches, glob_1.sync(task.pattern, task.opts));
- }, []);
- };
- var generateGlobTasks_1 = generateGlobTasks;
- var hasMagic = function hasMagic(patterns, opts) {
- return [].concat(patterns).some(function (pattern) {
- return glob_1.hasMagic(pattern, opts);
- });
- };
- globby.sync = sync;
- globby.generateGlobTasks = generateGlobTasks_1;
- globby.hasMagic = hasMagic;
- var assert$2 = true;
- var buffer_ieee754 = "< 0.9.7";
- var buffer = true;
- var child_process = true;
- var cluster = true;
- var console$1 = true;
- var constants = true;
- var crypto = true;
- var _debugger = "< 8";
- var dgram = true;
- var dns = true;
- var domain = true;
- var events$1 = true;
- var freelist = "< 6";
- var fs$2 = true;
- var http = true;
- var http2 = ">= 8.8";
- var https = true;
- var _http_server = ">= 0.11";
- var _linklist = "< 8";
- var module$1 = true;
- var net = true;
- var os$1 = true;
- var path$3 = true;
- var perf_hooks = ">= 8.5";
- var process$1 = ">= 1";
- var punycode = true;
- var querystring = true;
- var readline$1 = true;
- var repl = true;
- var stream = true;
- var string_decoder = true;
- var sys = true;
- var timers = true;
- var tls = true;
- var tty = true;
- var url = true;
- var util$4 = true;
- var v8 = ">= 1";
- var vm = true;
- var zlib = true;
- var core$3 = {
- assert: assert$2,
- buffer_ieee754: buffer_ieee754,
- buffer: buffer,
- child_process: child_process,
- cluster: cluster,
- console: console$1,
- constants: constants,
- crypto: crypto,
- _debugger: _debugger,
- dgram: dgram,
- dns: dns,
- domain: domain,
- events: events$1,
- freelist: freelist,
- fs: fs$2,
- http: http,
- http2: http2,
- https: https,
- _http_server: _http_server,
- _linklist: _linklist,
- module: module$1,
- net: net,
- os: os$1,
- path: path$3,
- perf_hooks: perf_hooks,
- process: process$1,
- punycode: punycode,
- querystring: querystring,
- readline: readline$1,
- repl: repl,
- stream: stream,
- string_decoder: string_decoder,
- sys: sys,
- timers: timers,
- tls: tls,
- tty: tty,
- url: url,
- util: util$4,
- v8: v8,
- vm: vm,
- zlib: zlib
- };
- var core$4 = Object.freeze({
- assert: assert$2,
- buffer_ieee754: buffer_ieee754,
- buffer: buffer,
- child_process: child_process,
- cluster: cluster,
- console: console$1,
- constants: constants,
- crypto: crypto,
- _debugger: _debugger,
- dgram: dgram,
- dns: dns,
- domain: domain,
- events: events$1,
- freelist: freelist,
- fs: fs$2,
- http: http,
- http2: http2,
- https: https,
- _http_server: _http_server,
- _linklist: _linklist,
- module: module$1,
- net: net,
- os: os$1,
- path: path$3,
- perf_hooks: perf_hooks,
- process: process$1,
- punycode: punycode,
- querystring: querystring,
- readline: readline$1,
- repl: repl,
- stream: stream,
- string_decoder: string_decoder,
- sys: sys,
- timers: timers,
- tls: tls,
- tty: tty,
- url: url,
- util: util$4,
- v8: v8,
- vm: vm,
- zlib: zlib,
- default: core$3
- });
- var data = ( core$4 && core$3 ) || core$4;
- var current = process.versions && process.versions.node && process.versions.node.split('.') || [];
- function versionIncluded(specifier) {
- if (specifier === true) {
- return true;
- }
- var parts = specifier.split(' ');
- var op = parts[0];
- var versionParts = parts[1].split('.');
- for (var i = 0; i < 3; ++i) {
- var cur = Number(current[i] || 0);
- var ver = Number(versionParts[i] || 0);
- if (cur === ver) {
- continue; // eslint-disable-line no-restricted-syntax, no-continue
- }
- if (op === '<') {
- return cur < ver;
- } else if (op === '>=') {
- return cur >= ver;
- } else {
- return false;
- }
- }
- return false;
- }
- var core$2 = {};
- for (var mod in data) {
- // eslint-disable-line no-restricted-syntax
- if (Object.prototype.hasOwnProperty.call(data, mod)) {
- core$2[mod] = versionIncluded(data[mod]);
- }
- }
- var core_1 = core$2;
- var caller = function caller() {
- // see https://code.google.com/p/v8/wiki/JavaScriptStackTraceApi
- var origPrepareStackTrace = Error.prepareStackTrace;
- Error.prepareStackTrace = function (_, stack) {
- return stack;
- };
- var stack = new Error().stack;
- Error.prepareStackTrace = origPrepareStackTrace;
- return stack[2].getFileName();
- };
- var pathParse = createCommonjsModule(function (module) {
- 'use strict';
- var isWindows = process.platform === 'win32'; // Regex to split a windows path into three parts: [*, device, slash,
- // tail] windows-only
- var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; // Regex to split the tail part of the above into [*, dir, basename, ext]
- var splitTailRe = /^([\s\S]*?)((?:\.{1,2}|[^\\\/]+?|)(\.[^.\/\\]*|))(?:[\\\/]*)$/;
- var win32 = {}; // Function to split a filename into [root, dir, basename, ext]
- function win32SplitPath(filename) {
- // Separate device+slash from tail
- var result = splitDeviceRe.exec(filename),
- device = (result[1] || '') + (result[2] || ''),
- tail = result[3] || ''; // Split the tail into dir, basename and extension
- var result2 = splitTailRe.exec(tail),
- dir = result2[1],
- basename = result2[2],
- ext = result2[3];
- return [device, dir, basename, ext];
- }
- win32.parse = function (pathString) {
- if (typeof pathString !== 'string') {
- throw new TypeError("Parameter 'pathString' must be a string, not " + typeof pathString);
- }
- var allParts = win32SplitPath(pathString);
- if (!allParts || allParts.length !== 4) {
- throw new TypeError("Invalid path '" + pathString + "'");
- }
- return {
- root: allParts[0],
- dir: allParts[0] + allParts[1].slice(0, -1),
- base: allParts[2],
- ext: allParts[3],
- name: allParts[2].slice(0, allParts[2].length - allParts[3].length)
- };
- }; // Split a filename into [root, dir, basename, ext], unix version
- // 'root' is just a slash, or nothing.
- var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
- var posix = {};
- function posixSplitPath(filename) {
- return splitPathRe.exec(filename).slice(1);
- }
- posix.parse = function (pathString) {
- if (typeof pathString !== 'string') {
- throw new TypeError("Parameter 'pathString' must be a string, not " + typeof pathString);
- }
- var allParts = posixSplitPath(pathString);
- if (!allParts || allParts.length !== 4) {
- throw new TypeError("Invalid path '" + pathString + "'");
- }
- allParts[1] = allParts[1] || '';
- allParts[2] = allParts[2] || '';
- allParts[3] = allParts[3] || '';
- return {
- root: allParts[0],
- dir: allParts[0] + allParts[1].slice(0, -1),
- base: allParts[2],
- ext: allParts[3],
- name: allParts[2].slice(0, allParts[2].length - allParts[3].length)
- };
- };
- if (isWindows) module.exports = win32.parse;else
- /* posix */
- module.exports = posix.parse;
- module.exports.posix = posix.parse;
- module.exports.win32 = win32.parse;
- });
- var parse$4 = path.parse || pathParse;
- var nodeModulesPaths = function nodeModulesPaths(start, opts) {
- var modules = opts && opts.moduleDirectory ? [].concat(opts.moduleDirectory) : ['node_modules']; // ensure that `start` is an absolute path at this point,
- // resolving against the process' current working directory
- var absoluteStart = path.resolve(start);
- if (opts && opts.preserveSymlinks === false) {
- try {
- absoluteStart = fs.realpathSync(absoluteStart);
- } catch (err) {
- if (err.code !== 'ENOENT') {
- throw err;
- }
- }
- }
- var prefix = '/';
- if (/^([A-Za-z]:)/.test(absoluteStart)) {
- prefix = '';
- } else if (/^\\\\/.test(absoluteStart)) {
- prefix = '\\\\';
- }
- var paths = [absoluteStart];
- var parsed = parse$4(absoluteStart);
- while (parsed.dir !== paths[paths.length - 1]) {
- paths.push(parsed.dir);
- parsed = parse$4(parsed.dir);
- }
- var dirs = paths.reduce(function (dirs, aPath) {
- return dirs.concat(modules.map(function (moduleDir) {
- return path.join(prefix, aPath, moduleDir);
- }));
- }, []);
- return opts && opts.paths ? dirs.concat(opts.paths) : dirs;
- };
- var async = function resolve(x, options, callback) {
- var cb = callback;
- var opts = options || {};
- if (typeof opts === 'function') {
- cb = opts;
- opts = {};
- }
- if (typeof x !== 'string') {
- var err = new TypeError('Path must be a string.');
- return process.nextTick(function () {
- cb(err);
- });
- }
- var isFile = opts.isFile || function (file, cb) {
- fs.stat(file, function (err, stat) {
- if (!err) {
- return cb(null, stat.isFile() || stat.isFIFO());
- }
- if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false);
- return cb(err);
- });
- };
- var readFile = opts.readFile || fs.readFile;
- var extensions = opts.extensions || ['.js'];
- var y = opts.basedir || path.dirname(caller());
- opts.paths = opts.paths || [];
- if (/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/.test(x)) {
- var res = path.resolve(y, x);
- if (x === '..' || x.slice(-1) === '/') res += '/';
- if (/\/$/.test(x) && res === y) {
- loadAsDirectory(res, opts.package, onfile);
- } else loadAsFile(res, opts.package, onfile);
- } else loadNodeModules(x, y, function (err, n, pkg) {
- if (err) cb(err);else if (n) cb(null, n, pkg);else if (core_1[x]) return cb(null, x);else {
- var moduleError = new Error("Cannot find module '" + x + "' from '" + y + "'");
- moduleError.code = 'MODULE_NOT_FOUND';
- cb(moduleError);
- }
- });
- function onfile(err, m, pkg) {
- if (err) cb(err);else if (m) cb(null, m, pkg);else loadAsDirectory(res, function (err, d, pkg) {
- if (err) cb(err);else if (d) cb(null, d, pkg);else {
- var moduleError = new Error("Cannot find module '" + x + "' from '" + y + "'");
- moduleError.code = 'MODULE_NOT_FOUND';
- cb(moduleError);
- }
- });
- }
- function loadAsFile(x, thePackage, callback) {
- var loadAsFilePackage = thePackage;
- var cb = callback;
- if (typeof loadAsFilePackage === 'function') {
- cb = loadAsFilePackage;
- loadAsFilePackage = undefined;
- }
- var exts = [''].concat(extensions);
- load(exts, x, loadAsFilePackage);
- function load(exts, x, loadPackage) {
- if (exts.length === 0) return cb(null, undefined, loadPackage);
- var file = x + exts[0];
- var pkg = loadPackage;
- if (pkg) onpkg(null, pkg);else loadpkg(path.dirname(file), onpkg);
- function onpkg(err, pkg_, dir) {
- pkg = pkg_;
- if (err) return cb(err);
- if (dir && pkg && opts.pathFilter) {
- var rfile = path.relative(dir, file);
- var rel = rfile.slice(0, rfile.length - exts[0].length);
- var r = opts.pathFilter(pkg, x, rel);
- if (r) return load([''].concat(extensions.slice()), path.resolve(dir, r), pkg);
- }
- isFile(file, onex);
- }
- function onex(err, ex) {
- if (err) return cb(err);
- if (ex) return cb(null, file, pkg);
- load(exts.slice(1), x, pkg);
- }
- }
- }
- function loadpkg(dir, cb) {
- if (dir === '' || dir === '/') return cb(null);
- if (process.platform === 'win32' && /^\w:[/\\]*$/.test(dir)) {
- return cb(null);
- }
- if (/[/\\]node_modules[/\\]*$/.test(dir)) return cb(null);
- var pkgfile = path.join(dir, 'package.json');
- isFile(pkgfile, function (err, ex) {
- // on err, ex is false
- if (!ex) return loadpkg(path.dirname(dir), cb);
- readFile(pkgfile, function (err, body) {
- if (err) cb(err);
- try {
- var pkg = JSON.parse(body);
- } catch (jsonErr) {}
- if (pkg && opts.packageFilter) {
- pkg = opts.packageFilter(pkg, pkgfile);
- }
- cb(null, pkg, dir);
- });
- });
- }
- function loadAsDirectory(x, loadAsDirectoryPackage, callback) {
- var cb = callback;
- var fpkg = loadAsDirectoryPackage;
- if (typeof fpkg === 'function') {
- cb = fpkg;
- fpkg = opts.package;
- }
- var pkgfile = path.join(x, 'package.json');
- isFile(pkgfile, function (err, ex) {
- if (err) return cb(err);
- if (!ex) return loadAsFile(path.join(x, 'index'), fpkg, cb);
- readFile(pkgfile, function (err, body) {
- if (err) return cb(err);
- try {
- var pkg = JSON.parse(body);
- } catch (jsonErr) {}
- if (opts.packageFilter) {
- pkg = opts.packageFilter(pkg, pkgfile);
- }
- if (pkg.main) {
- if (pkg.main === '.' || pkg.main === './') {
- pkg.main = 'index';
- }
- loadAsFile(path.resolve(x, pkg.main), pkg, function (err, m, pkg) {
- if (err) return cb(err);
- if (m) return cb(null, m, pkg);
- if (!pkg) return loadAsFile(path.join(x, 'index'), pkg, cb);
- var dir = path.resolve(x, pkg.main);
- loadAsDirectory(dir, pkg, function (err, n, pkg) {
- if (err) return cb(err);
- if (n) return cb(null, n, pkg);
- loadAsFile(path.join(x, 'index'), pkg, cb);
- });
- });
- return;
- }
- loadAsFile(path.join(x, '/index'), pkg, cb);
- });
- });
- }
- function processDirs(cb, dirs) {
- if (dirs.length === 0) return cb(null, undefined);
- var dir = dirs[0];
- var file = path.join(dir, x);
- loadAsFile(file, undefined, onfile);
- function onfile(err, m, pkg) {
- if (err) return cb(err);
- if (m) return cb(null, m, pkg);
- loadAsDirectory(path.join(dir, x), undefined, ondir);
- }
- function ondir(err, n, pkg) {
- if (err) return cb(err);
- if (n) return cb(null, n, pkg);
- processDirs(cb, dirs.slice(1));
- }
- }
- function loadNodeModules(x, start, cb) {
- processDirs(cb, nodeModulesPaths(start, opts));
- }
- };
- var sync$3 = function sync(x, options) {
- if (typeof x !== 'string') {
- throw new TypeError('Path must be a string.');
- }
- var opts = options || {};
- var isFile = opts.isFile || function (file) {
- try {
- var stat = fs.statSync(file);
- } catch (e) {
- if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false;
- throw e;
- }
- return stat.isFile() || stat.isFIFO();
- };
- var readFileSync = opts.readFileSync || fs.readFileSync;
- var extensions = opts.extensions || ['.js'];
- var y = opts.basedir || path.dirname(caller());
- opts.paths = opts.paths || [];
- if (/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/.test(x)) {
- var res = path.resolve(y, x);
- if (x === '..' || x.slice(-1) === '/') res += '/';
- var m = loadAsFileSync(res) || loadAsDirectorySync(res);
- if (m) return m;
- } else {
- var n = loadNodeModulesSync(x, y);
- if (n) return n;
- }
- if (core_1[x]) return x;
- var err = new Error("Cannot find module '" + x + "' from '" + y + "'");
- err.code = 'MODULE_NOT_FOUND';
- throw err;
- function loadAsFileSync(x) {
- if (isFile(x)) {
- return x;
- }
- for (var i = 0; i < extensions.length; i++) {
- var file = x + extensions[i];
- if (isFile(file)) {
- return file;
- }
- }
- }
- function loadAsDirectorySync(x) {
- var pkgfile = path.join(x, '/package.json');
- if (isFile(pkgfile)) {
- try {
- var body = readFileSync(pkgfile, 'UTF8');
- var pkg = JSON.parse(body);
- if (opts.packageFilter) {
- pkg = opts.packageFilter(pkg, x);
- }
- if (pkg.main) {
- if (pkg.main === '.' || pkg.main === './') {
- pkg.main = 'index';
- }
- var m = loadAsFileSync(path.resolve(x, pkg.main));
- if (m) return m;
- var n = loadAsDirectorySync(path.resolve(x, pkg.main));
- if (n) return n;
- }
- } catch (e) {}
- }
- return loadAsFileSync(path.join(x, '/index'));
- }
- function loadNodeModulesSync(x, start) {
- var dirs = nodeModulesPaths(start, opts);
- for (var i = 0; i < dirs.length; i++) {
- var dir = dirs[i];
- var m = loadAsFileSync(path.join(dir, '/', x));
- if (m) return m;
- var n = loadAsDirectorySync(path.join(dir, '/', x));
- if (n) return n;
- }
- }
- };
- var resolve$1 = createCommonjsModule(function (module, exports) {
- async.core = core_1;
- async.isCore = function isCore(x) {
- return core_1[x];
- };
- async.sync = sync$3;
- exports = async;
- module.exports = async;
- });
- var addLeadingComment$2 = utilShared.addLeadingComment;
- var addTrailingComment$2 = utilShared.addTrailingComment;
- var addDanglingComment$2 = utilShared.addDanglingComment;
- function handleOwnLineComment(comment, text, options, ast, isLastComment) {
- var precedingNode = comment.precedingNode,
- enclosingNode = comment.enclosingNode,
- followingNode = comment.followingNode;
- if (handleLastFunctionArgComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleMemberExpressionComments(enclosingNode, followingNode, comment) || handleIfStatementComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleWhileComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleTryStatementComments(enclosingNode, precedingNode, followingNode, comment) || handleClassComments(enclosingNode, precedingNode, followingNode, comment) || handleImportSpecifierComments(enclosingNode, comment) || handleForComments(enclosingNode, precedingNode, comment) || handleUnionTypeComments(precedingNode, enclosingNode, followingNode, comment) || handleOnlyComments(enclosingNode, ast, comment, isLastComment) || handleImportDeclarationComments(text, enclosingNode, precedingNode, comment, options) || handleAssignmentPatternComments(enclosingNode, comment) || handleMethodNameComments(text, enclosingNode, precedingNode, comment, options)) {
- return true;
- }
- return false;
- }
- function handleEndOfLineComment(comment, text, options, ast, isLastComment) {
- var precedingNode = comment.precedingNode,
- enclosingNode = comment.enclosingNode,
- followingNode = comment.followingNode;
- if (handleLastFunctionArgComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleConditionalExpressionComments(enclosingNode, precedingNode, followingNode, comment, text, options) || handleImportSpecifierComments(enclosingNode, comment) || handleIfStatementComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleWhileComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleTryStatementComments(enclosingNode, precedingNode, followingNode, comment) || handleClassComments(enclosingNode, precedingNode, followingNode, comment) || handleLabeledStatementComments(enclosingNode, comment) || handleCallExpressionComments(precedingNode, enclosingNode, comment) || handlePropertyComments(enclosingNode, comment) || handleOnlyComments(enclosingNode, ast, comment, isLastComment) || handleTypeAliasComments(enclosingNode, followingNode, comment) || handleVariableDeclaratorComments(enclosingNode, followingNode, comment)) {
- return true;
- }
- return false;
- }
- function handleRemainingComment(comment, text, options, ast, isLastComment) {
- var precedingNode = comment.precedingNode,
- enclosingNode = comment.enclosingNode,
- followingNode = comment.followingNode;
- if (handleIfStatementComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleWhileComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleObjectPropertyAssignment(enclosingNode, precedingNode, comment) || handleCommentInEmptyParens(text, enclosingNode, comment, options) || handleMethodNameComments(text, enclosingNode, precedingNode, comment, options) || handleOnlyComments(enclosingNode, ast, comment, isLastComment) || handleCommentAfterArrowParams(text, enclosingNode, comment, options) || handleFunctionNameComments(text, enclosingNode, precedingNode, comment, options) || handleTSMappedTypeComments(text, enclosingNode, precedingNode, followingNode, comment) || handleBreakAndContinueStatementComments(enclosingNode, comment)) {
- return true;
- }
- return false;
- }
- function addBlockStatementFirstComment(node, comment) {
- var body = node.body.filter(function (n) {
- return n.type !== "EmptyStatement";
- });
- if (body.length === 0) {
- addDanglingComment$2(node, comment);
- } else {
- addLeadingComment$2(body[0], comment);
- }
- }
- function addBlockOrNotComment(node, comment) {
- if (node.type === "BlockStatement") {
- addBlockStatementFirstComment(node, comment);
- } else {
- addLeadingComment$2(node, comment);
- }
- } // There are often comments before the else clause of if statements like
- //
- // if (1) { ... }
- // // comment
- // else { ... }
- //
- // They are being attached as leading comments of the BlockExpression which
- // is not well printed. What we want is to instead move the comment inside
- // of the block and make it leadingComment of the first element of the block
- // or dangling comment of the block if there is nothing inside
- //
- // if (1) { ... }
- // else {
- // // comment
- // ...
- // }
- function handleIfStatementComments(text, precedingNode, enclosingNode, followingNode, comment, options) {
- if (!enclosingNode || enclosingNode.type !== "IfStatement" || !followingNode) {
- return false;
- } // We unfortunately have no way using the AST or location of nodes to know
- // if the comment is positioned before the condition parenthesis:
- // if (a /* comment */) {}
- // The only workaround I found is to look at the next character to see if
- // it is a ).
- var nextCharacter = util$1.getNextNonSpaceNonCommentCharacter(text, comment, options.locEnd);
- if (nextCharacter === ")") {
- addTrailingComment$2(precedingNode, comment);
- return true;
- } // Comments before `else`:
- // - treat as trailing comments of the consequent, if it's a BlockStatement
- // - treat as a dangling comment otherwise
- if (precedingNode === enclosingNode.consequent && followingNode === enclosingNode.alternate) {
- if (precedingNode.type === "BlockStatement") {
- addTrailingComment$2(precedingNode, comment);
- } else {
- addDanglingComment$2(enclosingNode, comment);
- }
- return true;
- }
- if (followingNode.type === "BlockStatement") {
- addBlockStatementFirstComment(followingNode, comment);
- return true;
- }
- if (followingNode.type === "IfStatement") {
- addBlockOrNotComment(followingNode.consequent, comment);
- return true;
- } // For comments positioned after the condition parenthesis in an if statement
- // before the consequent without brackets on, such as
- // if (a) /* comment */ true,
- // we look at the next character to see if the following node
- // is the consequent for the if statement
- if (enclosingNode.consequent === followingNode) {
- addLeadingComment$2(followingNode, comment);
- return true;
- }
- return false;
- }
- function handleWhileComments(text, precedingNode, enclosingNode, followingNode, comment, options) {
- if (!enclosingNode || enclosingNode.type !== "WhileStatement" || !followingNode) {
- return false;
- } // We unfortunately have no way using the AST or location of nodes to know
- // if the comment is positioned before the condition parenthesis:
- // while (a /* comment */) {}
- // The only workaround I found is to look at the next character to see if
- // it is a ).
- var nextCharacter = util$1.getNextNonSpaceNonCommentCharacter(text, comment, options.locEnd);
- if (nextCharacter === ")") {
- addTrailingComment$2(precedingNode, comment);
- return true;
- }
- if (followingNode.type === "BlockStatement") {
- addBlockStatementFirstComment(followingNode, comment);
- return true;
- }
- return false;
- } // Same as IfStatement but for TryStatement
- function handleTryStatementComments(enclosingNode, precedingNode, followingNode, comment) {
- if (!enclosingNode || enclosingNode.type !== "TryStatement" && enclosingNode.type !== "CatchClause" || !followingNode) {
- return false;
- }
- if (enclosingNode.type === "CatchClause" && precedingNode) {
- addTrailingComment$2(precedingNode, comment);
- return true;
- }
- if (followingNode.type === "BlockStatement") {
- addBlockStatementFirstComment(followingNode, comment);
- return true;
- }
- if (followingNode.type === "TryStatement") {
- addBlockOrNotComment(followingNode.finalizer, comment);
- return true;
- }
- if (followingNode.type === "CatchClause") {
- addBlockOrNotComment(followingNode.body, comment);
- return true;
- }
- return false;
- }
- function handleMemberExpressionComments(enclosingNode, followingNode, comment) {
- if (enclosingNode && enclosingNode.type === "MemberExpression" && followingNode && followingNode.type === "Identifier") {
- addLeadingComment$2(enclosingNode, comment);
- return true;
- }
- return false;
- }
- function handleConditionalExpressionComments(enclosingNode, precedingNode, followingNode, comment, text, options) {
- var isSameLineAsPrecedingNode = precedingNode && !util$1.hasNewlineInRange(text, options.locEnd(precedingNode), options.locStart(comment));
- if ((!precedingNode || !isSameLineAsPrecedingNode) && enclosingNode && enclosingNode.type === "ConditionalExpression" && followingNode) {
- addLeadingComment$2(followingNode, comment);
- return true;
- }
- return false;
- }
- function handleObjectPropertyAssignment(enclosingNode, precedingNode, comment) {
- if (enclosingNode && (enclosingNode.type === "ObjectProperty" || enclosingNode.type === "Property") && enclosingNode.shorthand && enclosingNode.key === precedingNode && enclosingNode.value.type === "AssignmentPattern") {
- addTrailingComment$2(enclosingNode.value.left, comment);
- return true;
- }
- return false;
- }
- function handleClassComments(enclosingNode, precedingNode, followingNode, comment) {
- if (enclosingNode && (enclosingNode.type === "ClassDeclaration" || enclosingNode.type === "ClassExpression") && enclosingNode.decorators && enclosingNode.decorators.length > 0 && !(followingNode && followingNode.type === "Decorator")) {
- if (!enclosingNode.decorators || enclosingNode.decorators.length === 0) {
- addLeadingComment$2(enclosingNode, comment);
- } else {
- addTrailingComment$2(enclosingNode.decorators[enclosingNode.decorators.length - 1], comment);
- }
- return true;
- }
- return false;
- }
- function handleMethodNameComments(text, enclosingNode, precedingNode, comment, options) {
- // This is only needed for estree parsers (flow, typescript) to attach
- // after a method name:
- // obj = { fn /*comment*/() {} };
- if (enclosingNode && precedingNode && (enclosingNode.type === "Property" || enclosingNode.type === "MethodDefinition") && precedingNode.type === "Identifier" && enclosingNode.key === precedingNode && // special Property case: { key: /*comment*/(value) };
- // comment should be attached to value instead of key
- util$1.getNextNonSpaceNonCommentCharacter(text, precedingNode, options.locEnd) !== ":") {
- addTrailingComment$2(precedingNode, comment);
- return true;
- } // Print comments between decorators and class methods as a trailing comment
- // on the decorator node instead of the method node
- if (precedingNode && enclosingNode && precedingNode.type === "Decorator" && (enclosingNode.type === "ClassMethod" || enclosingNode.type === "ClassProperty" || enclosingNode.type === "TSAbstractClassProperty" || enclosingNode.type === "TSAbstractMethodDefinition" || enclosingNode.type === "MethodDefinition")) {
- addTrailingComment$2(precedingNode, comment);
- return true;
- }
- return false;
- }
- function handleFunctionNameComments(text, enclosingNode, precedingNode, comment, options) {
- if (util$1.getNextNonSpaceNonCommentCharacter(text, comment, options.locEnd) !== "(") {
- return false;
- }
- if (precedingNode && enclosingNode && (enclosingNode.type === "FunctionDeclaration" || enclosingNode.type === "FunctionExpression" || enclosingNode.type === "ClassMethod" || enclosingNode.type === "MethodDefinition" || enclosingNode.type === "ObjectMethod")) {
- addTrailingComment$2(precedingNode, comment);
- return true;
- }
- return false;
- }
- function handleCommentAfterArrowParams(text, enclosingNode, comment, options) {
- if (!(enclosingNode && enclosingNode.type === "ArrowFunctionExpression")) {
- return false;
- }
- var index = utilShared.getNextNonSpaceNonCommentCharacterIndex(text, comment, options);
- if (text.substr(index, 2) === "=>") {
- addDanglingComment$2(enclosingNode, comment);
- return true;
- }
- return false;
- }
- function handleCommentInEmptyParens(text, enclosingNode, comment, options) {
- if (util$1.getNextNonSpaceNonCommentCharacter(text, comment, options.locEnd) !== ")") {
- return false;
- } // Only add dangling comments to fix the case when no params are present,
- // i.e. a function without any argument.
- if (enclosingNode && ((enclosingNode.type === "FunctionDeclaration" || enclosingNode.type === "FunctionExpression" || enclosingNode.type === "ArrowFunctionExpression" && (enclosingNode.body.type !== "CallExpression" || enclosingNode.body.arguments.length === 0) || enclosingNode.type === "ClassMethod" || enclosingNode.type === "ObjectMethod") && enclosingNode.params.length === 0 || (enclosingNode.type === "CallExpression" || enclosingNode.type === "NewExpression") && enclosingNode.arguments.length === 0)) {
- addDanglingComment$2(enclosingNode, comment);
- return true;
- }
- if (enclosingNode && enclosingNode.type === "MethodDefinition" && enclosingNode.value.params.length === 0) {
- addDanglingComment$2(enclosingNode.value, comment);
- return true;
- }
- return false;
- }
- function handleLastFunctionArgComments(text, precedingNode, enclosingNode, followingNode, comment, options) {
- // Type definitions functions
- if (precedingNode && precedingNode.type === "FunctionTypeParam" && enclosingNode && enclosingNode.type === "FunctionTypeAnnotation" && followingNode && followingNode.type !== "FunctionTypeParam") {
- addTrailingComment$2(precedingNode, comment);
- return true;
- } // Real functions
- if (precedingNode && (precedingNode.type === "Identifier" || precedingNode.type === "AssignmentPattern") && enclosingNode && (enclosingNode.type === "ArrowFunctionExpression" || enclosingNode.type === "FunctionExpression" || enclosingNode.type === "FunctionDeclaration" || enclosingNode.type === "ObjectMethod" || enclosingNode.type === "ClassMethod") && util$1.getNextNonSpaceNonCommentCharacter(text, comment, options.locEnd) === ")") {
- addTrailingComment$2(precedingNode, comment);
- return true;
- }
- if (enclosingNode && enclosingNode.type === "FunctionDeclaration" && followingNode && followingNode.type === "BlockStatement") {
- var functionParamRightParenIndex = function () {
- if (enclosingNode.params.length !== 0) {
- return util$1.getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, options.locEnd(util$1.getLast(enclosingNode.params)));
- }
- var functionParamLeftParenIndex = util$1.getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, options.locEnd(enclosingNode.id));
- return util$1.getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, functionParamLeftParenIndex + 1);
- }();
- if (options.locStart(comment) > functionParamRightParenIndex) {
- addBlockStatementFirstComment(followingNode, comment);
- return true;
- }
- }
- return false;
- }
- function handleImportSpecifierComments(enclosingNode, comment) {
- if (enclosingNode && enclosingNode.type === "ImportSpecifier") {
- addLeadingComment$2(enclosingNode, comment);
- return true;
- }
- return false;
- }
- function handleLabeledStatementComments(enclosingNode, comment) {
- if (enclosingNode && enclosingNode.type === "LabeledStatement") {
- addLeadingComment$2(enclosingNode, comment);
- return true;
- }
- return false;
- }
- function handleBreakAndContinueStatementComments(enclosingNode, comment) {
- if (enclosingNode && (enclosingNode.type === "ContinueStatement" || enclosingNode.type === "BreakStatement") && !enclosingNode.label) {
- addTrailingComment$2(enclosingNode, comment);
- return true;
- }
- return false;
- }
- function handleCallExpressionComments(precedingNode, enclosingNode, comment) {
- if (enclosingNode && enclosingNode.type === "CallExpression" && precedingNode && enclosingNode.callee === precedingNode && enclosingNode.arguments.length > 0) {
- addLeadingComment$2(enclosingNode.arguments[0], comment);
- return true;
- }
- return false;
- }
- function handleUnionTypeComments(precedingNode, enclosingNode, followingNode, comment) {
- if (enclosingNode && (enclosingNode.type === "UnionTypeAnnotation" || enclosingNode.type === "TSUnionType")) {
- addTrailingComment$2(precedingNode, comment);
- return true;
- }
- return false;
- }
- function handlePropertyComments(enclosingNode, comment) {
- if (enclosingNode && (enclosingNode.type === "Property" || enclosingNode.type === "ObjectProperty")) {
- addLeadingComment$2(enclosingNode, comment);
- return true;
- }
- return false;
- }
- function handleOnlyComments(enclosingNode, ast, comment, isLastComment) {
- // With Flow the enclosingNode is undefined so use the AST instead.
- if (ast && ast.body && ast.body.length === 0) {
- if (isLastComment) {
- addDanglingComment$2(ast, comment);
- } else {
- addLeadingComment$2(ast, comment);
- }
- return true;
- } else if (enclosingNode && enclosingNode.type === "Program" && enclosingNode.body.length === 0 && enclosingNode.directives && enclosingNode.directives.length === 0) {
- if (isLastComment) {
- addDanglingComment$2(enclosingNode, comment);
- } else {
- addLeadingComment$2(enclosingNode, comment);
- }
- return true;
- }
- return false;
- }
- function handleForComments(enclosingNode, precedingNode, comment) {
- if (enclosingNode && (enclosingNode.type === "ForInStatement" || enclosingNode.type === "ForOfStatement")) {
- addLeadingComment$2(enclosingNode, comment);
- return true;
- }
- return false;
- }
- function handleImportDeclarationComments(text, enclosingNode, precedingNode, comment, options) {
- if (precedingNode && precedingNode.type === "ImportSpecifier" && enclosingNode && enclosingNode.type === "ImportDeclaration" && util$1.hasNewline(text, options.locEnd(comment))) {
- addTrailingComment$2(precedingNode, comment);
- return true;
- }
- return false;
- }
- function handleAssignmentPatternComments(enclosingNode, comment) {
- if (enclosingNode && enclosingNode.type === "AssignmentPattern") {
- addLeadingComment$2(enclosingNode, comment);
- return true;
- }
- return false;
- }
- function handleTypeAliasComments(enclosingNode, followingNode, comment) {
- if (enclosingNode && enclosingNode.type === "TypeAlias") {
- addLeadingComment$2(enclosingNode, comment);
- return true;
- }
- return false;
- }
- function handleVariableDeclaratorComments(enclosingNode, followingNode, comment) {
- if (enclosingNode && (enclosingNode.type === "VariableDeclarator" || enclosingNode.type === "AssignmentExpression") && followingNode && (followingNode.type === "ObjectExpression" || followingNode.type === "ArrayExpression" || followingNode.type === "TemplateLiteral" || followingNode.type === "TaggedTemplateExpression")) {
- addLeadingComment$2(followingNode, comment);
- return true;
- }
- return false;
- }
- function handleTSMappedTypeComments(text, enclosingNode, precedingNode, followingNode, comment) {
- if (!enclosingNode || enclosingNode.type !== "TSMappedType") {
- return false;
- }
- if (followingNode && followingNode.type === "TSTypeParameter" && followingNode.name) {
- addLeadingComment$2(followingNode.name, comment);
- return true;
- }
- if (precedingNode && precedingNode.type === "TSTypeParameter" && precedingNode.constraint) {
- addTrailingComment$2(precedingNode.constraint, comment);
- return true;
- }
- return false;
- }
- function isBlockComment$1(comment) {
- return comment.type === "Block" || comment.type === "CommentBlock";
- }
- function hasLeadingComment$2(node) {
- var fn = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function () {
- return true;
- };
- if (node.leadingComments) {
- return node.leadingComments.some(fn);
- }
- if (node.comments) {
- return node.comments.some(function (comment) {
- return comment.leading && fn(comment);
- });
- }
- return false;
- }
- var comments$3 = {
- handleOwnLineComment,
- handleEndOfLineComment,
- handleRemainingComment,
- hasLeadingComment: hasLeadingComment$2,
- isBlockComment: isBlockComment$1
- };
- var isBlockComment = comments$3.isBlockComment;
- var hasLeadingComment$1 = comments$3.hasLeadingComment;
- var _require$$1$builders = doc.builders;
- var indent$3 = _require$$1$builders.indent;
- var join$3 = _require$$1$builders.join;
- var hardline$4 = _require$$1$builders.hardline;
- var softline$2 = _require$$1$builders.softline;
- var literalline$2 = _require$$1$builders.literalline;
- var concat$5 = _require$$1$builders.concat;
- var group$2 = _require$$1$builders.group;
- var dedentToRoot$1 = _require$$1$builders.dedentToRoot;
- var _require$$1$utils = doc.utils;
- var mapDoc$3 = _require$$1$utils.mapDoc;
- var stripTrailingHardline$1 = _require$$1$utils.stripTrailingHardline;
- function embed(path$$1, print, textToDoc
- /*, options */
- ) {
- var node = path$$1.getValue();
- var parent = path$$1.getParentNode();
- var parentParent = path$$1.getParentNode(1);
- switch (node.type) {
- case "TemplateLiteral":
- {
- var isCss = [isStyledJsx, isStyledComponents, isCssProp, isAngularComponentStyles].some(function (isIt) {
- return isIt(path$$1);
- });
- if (isCss) {
- // Get full template literal with expressions replaced by placeholders
- var rawQuasis = node.quasis.map(function (q) {
- return q.value.raw;
- });
- var placeholderID = 0;
- var text = rawQuasis.reduce(function (prevVal, currVal, idx) {
- return idx == 0 ? currVal : prevVal + "@prettier-placeholder-" + placeholderID++ + "-id" + currVal;
- }, "");
- var doc$$2 = textToDoc(text, {
- parser: "css"
- });
- return transformCssDoc(doc$$2, path$$1, print);
- }
- /*
- * react-relay and graphql-tag
- * graphql`...`
- * graphql.experimental`...`
- * gql`...`
- *
- * This intentionally excludes Relay Classic tags, as Prettier does not
- * support Relay Classic formatting.
- */
- if (isGraphQL(path$$1)) {
- var expressionDocs = node.expressions ? path$$1.map(print, "expressions") : [];
- var numQuasis = node.quasis.length;
- if (numQuasis === 1 && node.quasis[0].value.raw.trim() === "") {
- return "``";
- }
- var parts = [];
- for (var i = 0; i < numQuasis; i++) {
- var templateElement = node.quasis[i];
- var isFirst = i === 0;
- var isLast = i === numQuasis - 1;
- var _text = templateElement.value.cooked; // Bail out if any of the quasis have an invalid escape sequence
- // (which would make the `cooked` value be `null` or `undefined`)
- if (typeof _text !== "string") {
- return null;
- }
- var lines = _text.split("\n");
- var numLines = lines.length;
- var expressionDoc = expressionDocs[i];
- var startsWithBlankLine = numLines > 2 && lines[0].trim() === "" && lines[1].trim() === "";
- var endsWithBlankLine = numLines > 2 && lines[numLines - 1].trim() === "" && lines[numLines - 2].trim() === "";
- var commentsAndWhitespaceOnly = lines.every(function (line) {
- return /^\s*(?:#[^\r\n]*)?$/.test(line);
- }); // Bail out if an interpolation occurs within a comment.
- if (!isLast && /#[^\r\n]*$/.test(lines[numLines - 1])) {
- return null;
- }
- var _doc = null;
- if (commentsAndWhitespaceOnly) {
- _doc = printGraphqlComments(lines);
- } else {
- _doc = stripTrailingHardline$1(textToDoc(_text, {
- parser: "graphql"
- }));
- }
- if (_doc) {
- _doc = escapeTemplateCharacters(_doc, false);
- if (!isFirst && startsWithBlankLine) {
- parts.push("");
- }
- parts.push(_doc);
- if (!isLast && endsWithBlankLine) {
- parts.push("");
- }
- } else if (!isFirst && !isLast && startsWithBlankLine) {
- parts.push("");
- }
- if (expressionDoc) {
- parts.push(concat$5(["${", expressionDoc, "}"]));
- }
- }
- return concat$5(["`", indent$3(concat$5([hardline$4, join$3(hardline$4, parts)])), hardline$4, "`"]);
- }
- if (isHtml(path$$1)) {
- return printHtmlTemplateLiteral(path$$1, print, textToDoc, "html");
- }
- if (isAngularComponentTemplate(path$$1)) {
- return printHtmlTemplateLiteral(path$$1, print, textToDoc, "angular");
- }
- break;
- }
- case "TemplateElement":
- {
- /**
- * md`...`
- * markdown`...`
- */
- if (parentParent && parentParent.type === "TaggedTemplateExpression" && parent.quasis.length === 1 && parentParent.tag.type === "Identifier" && (parentParent.tag.name === "md" || parentParent.tag.name === "markdown")) {
- var _text2 = parent.quasis[0].value.raw.replace(/((?:\\\\)*)\\`/g, function (_, backslashes) {
- return "\\".repeat(backslashes.length / 2) + "`";
- });
- var indentation = getIndentation(_text2);
- var hasIndent = indentation !== "";
- return concat$5([hasIndent ? indent$3(concat$5([softline$2, printMarkdown(_text2.replace(new RegExp(`^${indentation}`, "gm"), ""))])) : concat$5([literalline$2, dedentToRoot$1(printMarkdown(_text2))]), softline$2]);
- }
- break;
- }
- }
- function printMarkdown(text) {
- var doc$$2 = textToDoc(text, {
- parser: "markdown",
- __inJsTemplate: true
- });
- return stripTrailingHardline$1(escapeTemplateCharacters(doc$$2, true));
- }
- }
- function getIndentation(str) {
- var firstMatchedIndent = str.match(/^([^\S\n]*)\S/m);
- return firstMatchedIndent === null ? "" : firstMatchedIndent[1];
- }
- function escapeTemplateCharacters(doc$$2, raw) {
- return mapDoc$3(doc$$2, function (currentDoc) {
- if (!currentDoc.parts) {
- return currentDoc;
- }
- var parts = [];
- currentDoc.parts.forEach(function (part) {
- if (typeof part === "string") {
- parts.push(raw ? part.replace(/(\\*)`/g, "$1$1\\`") : part.replace(/([\\`]|\$\{)/g, "\\$1"));
- } else {
- parts.push(part);
- }
- });
- return Object.assign({}, currentDoc, {
- parts
- });
- });
- }
- function transformCssDoc(quasisDoc, path$$1, print) {
- var parentNode = path$$1.getValue();
- var isEmpty = parentNode.quasis.length === 1 && !parentNode.quasis[0].value.raw.trim();
- if (isEmpty) {
- return "``";
- }
- var expressionDocs = parentNode.expressions ? path$$1.map(print, "expressions") : [];
- var newDoc = replacePlaceholders(quasisDoc, expressionDocs);
- /* istanbul ignore if */
- if (!newDoc) {
- throw new Error("Couldn't insert all the expressions");
- }
- return concat$5(["`", indent$3(concat$5([hardline$4, stripTrailingHardline$1(newDoc)])), softline$2, "`"]);
- } // Search all the placeholders in the quasisDoc tree
- // and replace them with the expression docs one by one
- // returns a new doc with all the placeholders replaced,
- // or null if it couldn't replace any expression
- function replacePlaceholders(quasisDoc, expressionDocs) {
- if (!expressionDocs || !expressionDocs.length) {
- return quasisDoc;
- }
- var expressions = expressionDocs.slice();
- var replaceCounter = 0;
- var newDoc = mapDoc$3(quasisDoc, function (doc$$2) {
- if (!doc$$2 || !doc$$2.parts || !doc$$2.parts.length) {
- return doc$$2;
- }
- var parts = doc$$2.parts;
- var atIndex = parts.indexOf("@");
- var placeholderIndex = atIndex + 1;
- if (atIndex > -1 && typeof parts[placeholderIndex] === "string" && parts[placeholderIndex].startsWith("prettier-placeholder")) {
- // If placeholder is split, join it
- var at = parts[atIndex];
- var placeholder = parts[placeholderIndex];
- var rest = parts.slice(placeholderIndex + 1);
- parts = parts.slice(0, atIndex).concat([at + placeholder]).concat(rest);
- }
- var atPlaceholderIndex = parts.findIndex(function (part) {
- return typeof part === "string" && part.startsWith("@prettier-placeholder");
- });
- if (atPlaceholderIndex > -1) {
- var _placeholder = parts[atPlaceholderIndex];
- var _rest = parts.slice(atPlaceholderIndex + 1);
- var placeholderMatch = _placeholder.match(/@prettier-placeholder-(.+)-id([\s\S]*)/);
- var placeholderID = placeholderMatch[1]; // When the expression has a suffix appended, like:
- // animation: linear ${time}s ease-out;
- var suffix = placeholderMatch[2];
- var expression = expressions[placeholderID];
- replaceCounter++;
- parts = parts.slice(0, atPlaceholderIndex).concat(["${", expression, "}" + suffix]).concat(_rest);
- }
- return Object.assign({}, doc$$2, {
- parts: parts
- });
- });
- return expressions.length === replaceCounter ? newDoc : null;
- }
- function printGraphqlComments(lines) {
- var parts = [];
- var seenComment = false;
- lines.map(function (textLine) {
- return textLine.trim();
- }).forEach(function (textLine, i, array) {
- // Lines are either whitespace only, or a comment (with poential whitespace
- // around it). Drop whitespace-only lines.
- if (textLine === "") {
- return;
- }
- if (array[i - 1] === "" && seenComment) {
- // If a non-first comment is preceded by a blank (whitespace only) line,
- // add in a blank line.
- parts.push(concat$5([hardline$4, textLine]));
- } else {
- parts.push(textLine);
- }
- seenComment = true;
- }); // If `lines` was whitespace only, return `null`.
- return parts.length === 0 ? null : join$3(hardline$4, parts);
- }
- /**
- * Template literal in this context:
- * <style jsx>{`div{color:red}`}</style>
- */
- function isStyledJsx(path$$1) {
- var node = path$$1.getValue();
- var parent = path$$1.getParentNode();
- var parentParent = path$$1.getParentNode(1);
- return parentParent && node.quasis && parent.type === "JSXExpressionContainer" && parentParent.type === "JSXElement" && parentParent.openingElement.name.name === "style" && parentParent.openingElement.attributes.some(function (attribute) {
- return attribute.name.name === "jsx";
- });
- }
- /**
- * Angular Components can have:
- * - Inline HTML template
- * - Inline CSS styles
- *
- * ...which are both within template literals somewhere
- * inside of the Component decorator factory.
- *
- * E.g.
- * @Component({
- * template: `<div>...</div>`,
- * styles: [`h1 { color: blue; }`]
- * })
- */
- function isAngularComponentStyles(path$$1) {
- return isPathMatch(path$$1, [function (node) {
- return node.type === "TemplateLiteral";
- }, function (node, name) {
- return node.type === "ArrayExpression" && name === "elements";
- }, function (node, name) {
- return node.type === "Property" && node.key.type === "Identifier" && node.key.name === "styles" && name === "value";
- }].concat(getAngularComponentObjectExpressionPredicates()));
- }
- function isAngularComponentTemplate(path$$1) {
- return isPathMatch(path$$1, [function (node) {
- return node.type === "TemplateLiteral";
- }, function (node, name) {
- return node.type === "Property" && node.key.type === "Identifier" && node.key.name === "template" && name === "value";
- }].concat(getAngularComponentObjectExpressionPredicates()));
- }
- function getAngularComponentObjectExpressionPredicates() {
- return [function (node, name) {
- return node.type === "ObjectExpression" && name === "properties";
- }, function (node, name) {
- return node.type === "CallExpression" && node.callee.type === "Identifier" && node.callee.name === "Component" && name === "arguments";
- }, function (node, name) {
- return node.type === "Decorator" && name === "expression";
- }];
- }
- /**
- * styled-components template literals
- */
- function isStyledComponents(path$$1) {
- var parent = path$$1.getParentNode();
- if (!parent || parent.type !== "TaggedTemplateExpression") {
- return false;
- }
- var tag = parent.tag;
- switch (tag.type) {
- case "MemberExpression":
- return (// styled.foo``
- isStyledIdentifier(tag.object) || // Component.extend``
- isStyledExtend(tag)
- );
- case "CallExpression":
- return (// styled(Component)``
- isStyledIdentifier(tag.callee) || tag.callee.type === "MemberExpression" && (tag.callee.object.type === "MemberExpression" && ( // styled.foo.attr({})``
- isStyledIdentifier(tag.callee.object.object) || // Component.extend.attr({)``
- isStyledExtend(tag.callee.object)) || // styled(Component).attr({})``
- tag.callee.object.type === "CallExpression" && isStyledIdentifier(tag.callee.object.callee))
- );
- case "Identifier":
- // css``
- return tag.name === "css";
- default:
- return false;
- }
- }
- /**
- * JSX element with CSS prop
- */
- function isCssProp(path$$1) {
- var parent = path$$1.getParentNode();
- var parentParent = path$$1.getParentNode(1);
- return parentParent && parent.type === "JSXExpressionContainer" && parentParent.type === "JSXAttribute" && parentParent.name.type === "JSXIdentifier" && parentParent.name.name === "css";
- }
- function isStyledIdentifier(node) {
- return node.type === "Identifier" && node.name === "styled";
- }
- function isStyledExtend(node) {
- return /^[A-Z]/.test(node.object.name) && node.property.name === "extend";
- }
- /*
- * react-relay and graphql-tag
- * graphql`...`
- * graphql.experimental`...`
- * gql`...`
- * GraphQL comment block
- *
- * This intentionally excludes Relay Classic tags, as Prettier does not
- * support Relay Classic formatting.
- */
- function isGraphQL(path$$1) {
- var node = path$$1.getValue();
- var parent = path$$1.getParentNode();
- return hasLanguageComment(node, "GraphQL") || parent && (parent.type === "TaggedTemplateExpression" && (parent.tag.type === "MemberExpression" && parent.tag.object.name === "graphql" && parent.tag.property.name === "experimental" || parent.tag.type === "Identifier" && (parent.tag.name === "gql" || parent.tag.name === "graphql")) || parent.type === "CallExpression" && parent.callee.type === "Identifier" && parent.callee.name === "graphql");
- }
- function hasLanguageComment(node, languageName) {
- // This checks for a leading comment that is exactly `/* GraphQL */`
- // In order to be in line with other implementations of this comment tag
- // we will not trim the comment value and we will expect exactly one space on
- // either side of the GraphQL string
- // Also see ./clean.js
- return hasLeadingComment$1(node, function (comment) {
- return isBlockComment(comment) && comment.value === ` ${languageName} `;
- });
- }
- function isPathMatch(path$$1, predicateStack) {
- var stack = path$$1.stack.slice();
- var name = null;
- var node = stack.pop();
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = predicateStack[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var predicate = _step.value;
- if (node === undefined) {
- return false;
- } // skip index/array
- if (typeof name === "number") {
- name = stack.pop();
- node = stack.pop();
- }
- if (!predicate(node, name)) {
- return false;
- }
- name = stack.pop();
- node = stack.pop();
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- return true;
- }
- /**
- * - html`...`
- * - HTML comment block
- */
- function isHtml(path$$1) {
- var node = path$$1.getValue();
- return hasLanguageComment(node, "HTML") || isPathMatch(path$$1, [function (node) {
- return node.type === "TemplateLiteral";
- }, function (node, name) {
- return node.type === "TaggedTemplateExpression" && node.tag.type === "Identifier" && node.tag.name === "html" && name === "quasi";
- }]);
- }
- function printHtmlTemplateLiteral(path$$1, print, textToDoc, parser) {
- var node = path$$1.getValue();
- var placeholderPattern = "PRETTIER_HTML_PLACEHOLDER_(\\d+)_IN_JS";
- var placeholders = node.expressions.map(function (_, i) {
- return `PRETTIER_HTML_PLACEHOLDER_${i}_IN_JS`;
- });
- var text = node.quasis.map(function (quasi, index, quasis) {
- return index === quasis.length - 1 ? quasi.value.raw : quasi.value.raw + placeholders[index];
- }).join("");
- var expressionDocs = path$$1.map(print, "expressions");
- if (expressionDocs.length === 0 && text.trim().length === 0) {
- return "``";
- }
- var contentDoc = mapDoc$3(stripTrailingHardline$1(textToDoc(text, {
- parser
- })), function (doc$$2) {
- var placeholderRegex = new RegExp(placeholderPattern, "g");
- var hasPlaceholder = typeof doc$$2 === "string" && placeholderRegex.test(doc$$2);
- if (!hasPlaceholder) {
- return doc$$2;
- }
- var parts = [];
- var components = doc$$2.split(placeholderRegex);
- for (var i = 0; i < components.length; i++) {
- var component = components[i];
- if (i % 2 === 0) {
- if (component) {
- parts.push(component);
- }
- continue;
- }
- var placeholderIndex = +component;
- parts.push(concat$5(["${", group$2(expressionDocs[placeholderIndex]), "}"]));
- }
- return concat$5(parts);
- });
- return group$2(concat$5(["`", indent$3(concat$5([hardline$4, group$2(contentDoc)])), softline$2, "`"]));
- }
- var embed_1 = embed;
- function clean(ast, newObj, parent) {
- ["range", "raw", "comments", "leadingComments", "trailingComments", "extra", "start", "end", "flags"].forEach(function (name) {
- delete newObj[name];
- });
- if (ast.type === "BigIntLiteral") {
- newObj.value = newObj.value.toLowerCase();
- } // We remove extra `;` and add them when needed
- if (ast.type === "EmptyStatement") {
- return null;
- } // We move text around, including whitespaces and add {" "}
- if (ast.type === "JSXText") {
- return null;
- }
- if (ast.type === "JSXExpressionContainer" && ast.expression.type === "Literal" && ast.expression.value === " ") {
- return null;
- } // (TypeScript) Ignore `static` in `constructor(static p) {}`
- // and `export` in `constructor(export p) {}`
- if (ast.type === "TSParameterProperty" && ast.accessibility === null && !ast.readonly) {
- return {
- type: "Identifier",
- name: ast.parameter.name,
- typeAnnotation: newObj.parameter.typeAnnotation,
- decorators: newObj.decorators
- };
- } // (TypeScript) ignore empty `specifiers` array
- if (ast.type === "TSNamespaceExportDeclaration" && ast.specifiers && ast.specifiers.length === 0) {
- delete newObj.specifiers;
- } // (TypeScript) bypass TSParenthesizedType
- if (ast.type === "TSParenthesizedType") {
- return newObj.typeAnnotation;
- } // We convert <div></div> to <div />
- if (ast.type === "JSXOpeningElement") {
- delete newObj.selfClosing;
- }
- if (ast.type === "JSXElement") {
- delete newObj.closingElement;
- } // We change {'key': value} into {key: value}
- if ((ast.type === "Property" || ast.type === "ObjectProperty" || ast.type === "MethodDefinition" || ast.type === "ClassProperty" || ast.type === "TSPropertySignature" || ast.type === "ObjectTypeProperty") && typeof ast.key === "object" && ast.key && (ast.key.type === "Literal" || ast.key.type === "StringLiteral" || ast.key.type === "Identifier")) {
- delete newObj.key;
- }
- if (ast.type === "OptionalMemberExpression" && ast.optional === false) {
- newObj.type = "MemberExpression";
- delete newObj.optional;
- } // Remove raw and cooked values from TemplateElement when it's CSS
- // styled-jsx
- if (ast.type === "JSXElement" && ast.openingElement.name.name === "style" && ast.openingElement.attributes.some(function (attr) {
- return attr.name.name === "jsx";
- })) {
- var templateLiterals = newObj.children.filter(function (child) {
- return child.type === "JSXExpressionContainer" && child.expression.type === "TemplateLiteral";
- }).map(function (container) {
- return container.expression;
- });
- var quasis = templateLiterals.reduce(function (quasis, templateLiteral) {
- return quasis.concat(templateLiteral.quasis);
- }, []);
- quasis.forEach(function (q) {
- return delete q.value;
- });
- } // CSS template literals in css prop
- if (ast.type === "JSXAttribute" && ast.name.name === "css" && ast.value.type === "JSXExpressionContainer" && ast.value.expression.type === "TemplateLiteral") {
- newObj.value.expression.quasis.forEach(function (q) {
- return delete q.value;
- });
- } // Angular Components: Inline HTML template and Inline CSS styles
- var expression = ast.expression || ast.callee;
- if (ast.type === "Decorator" && expression.type === "CallExpression" && expression.callee.name === "Component" && expression.arguments.length === 1) {
- var astProps = ast.expression.arguments[0].properties;
- newObj.expression.arguments[0].properties.forEach(function (prop, index) {
- var templateLiteral = null;
- switch (astProps[index].key.name) {
- case "styles":
- if (prop.value.type === "ArrayExpression") {
- templateLiteral = prop.value.elements[0];
- }
- break;
- case "template":
- if (prop.value.type === "TemplateLiteral") {
- templateLiteral = prop.value;
- }
- break;
- }
- if (templateLiteral) {
- templateLiteral.quasis.forEach(function (q) {
- return delete q.value;
- });
- }
- });
- } // styled-components, graphql, markdown
- if (ast.type === "TaggedTemplateExpression" && (ast.tag.type === "MemberExpression" || ast.tag.type === "Identifier" && (ast.tag.name === "gql" || ast.tag.name === "graphql" || ast.tag.name === "css" || ast.tag.name === "md" || ast.tag.name === "markdown" || ast.tag.name === "html") || ast.tag.type === "CallExpression")) {
- newObj.quasi.quasis.forEach(function (quasi) {
- return delete quasi.value;
- });
- }
- if (ast.type === "TemplateLiteral") {
- // This checks for a leading comment that is exactly `/* GraphQL */`
- // In order to be in line with other implementations of this comment tag
- // we will not trim the comment value and we will expect exactly one space on
- // either side of the GraphQL string
- // Also see ./embed.js
- var hasLanguageComment = ast.leadingComments && ast.leadingComments.some(function (comment) {
- return comment.type === "CommentBlock" && ["GraphQL", "HTML"].some(function (languageName) {
- return comment.value === ` ${languageName} `;
- });
- });
- if (hasLanguageComment || parent.type === "CallExpression" && parent.callee.name === "graphql") {
- newObj.quasis.forEach(function (quasi) {
- return delete quasi.value;
- });
- }
- }
- }
- var clean_1 = clean;
- var detectNewline = createCommonjsModule(function (module) {
- 'use strict';
- module.exports = function (str) {
- if (typeof str !== 'string') {
- throw new TypeError('Expected a string');
- }
- var newlines = str.match(/(?:\r?\n)/g) || [];
- if (newlines.length === 0) {
- return null;
- }
- var crlf = newlines.filter(function (el) {
- return el === '\r\n';
- }).length;
- var lf = newlines.length - crlf;
- return crlf > lf ? '\r\n' : '\n';
- };
- module.exports.graceful = function (str) {
- return module.exports(str) || '\n';
- };
- });
- var build$1 = createCommonjsModule(function (module, exports) {
- 'use strict';
- Object.defineProperty(exports, '__esModule', {
- value: true
- });
- exports.extract = extract;
- exports.strip = strip;
- exports.parse = parse;
- exports.parseWithComments = parseWithComments;
- exports.print = print;
- var _detectNewline;
- function _load_detectNewline() {
- return _detectNewline = _interopRequireDefault(detectNewline);
- }
- var _os;
- function _load_os() {
- return _os = os;
- }
- function _interopRequireDefault(obj) {
- return obj && obj.__esModule ? obj : {
- default: obj
- };
- }
- /**
- * Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- *
- */
- var commentEndRe = /\*\/$/;
- var commentStartRe = /^\/\*\*/;
- var docblockRe = /^\s*(\/\*\*?(.|\r?\n)*?\*\/)/;
- var lineCommentRe = /(^|\s+)\/\/([^\r\n]*)/g;
- var ltrimNewlineRe = /^(\r?\n)+/;
- var multilineRe = /(?:^|\r?\n) *(@[^\r\n]*?) *\r?\n *(?![^@\r\n]*\/\/[^]*)([^@\r\n\s][^@\r\n]+?) *\r?\n/g;
- var propertyRe = /(?:^|\r?\n) *@(\S+) *([^\r\n]*)/g;
- var stringStartRe = /(\r?\n|^) *\* ?/g;
- function extract(contents) {
- var match = contents.match(docblockRe);
- return match ? match[0].trimLeft() : '';
- }
- function strip(contents) {
- var match = contents.match(docblockRe);
- return match && match[0] ? contents.substring(match[0].length) : contents;
- }
- function parse(docblock) {
- return parseWithComments(docblock).pragmas;
- }
- function parseWithComments(docblock) {
- var line = (0, (_detectNewline || _load_detectNewline()).default)(docblock) || (_os || _load_os()).EOL;
- docblock = docblock.replace(commentStartRe, '').replace(commentEndRe, '').replace(stringStartRe, '$1'); // Normalize multi-line directives
- var prev = '';
- while (prev !== docblock) {
- prev = docblock;
- docblock = docblock.replace(multilineRe, `${line}$1 $2${line}`);
- }
- docblock = docblock.replace(ltrimNewlineRe, '').trimRight();
- var result = Object.create(null);
- var comments = docblock.replace(propertyRe, '').replace(ltrimNewlineRe, '').trimRight();
- var match;
- while (match = propertyRe.exec(docblock)) {
- // strip linecomments from pragmas
- var nextPragma = match[2].replace(lineCommentRe, '');
- if (typeof result[match[1]] === 'string' || Array.isArray(result[match[1]])) {
- result[match[1]] = [].concat(result[match[1]], nextPragma);
- } else {
- result[match[1]] = nextPragma;
- }
- }
- return {
- comments,
- pragmas: result
- };
- }
- function print(_ref) {
- var _ref$comments = _ref.comments;
- var comments = _ref$comments === undefined ? '' : _ref$comments;
- var _ref$pragmas = _ref.pragmas;
- var pragmas = _ref$pragmas === undefined ? {} : _ref$pragmas;
- var line = (0, (_detectNewline || _load_detectNewline()).default)(comments) || (_os || _load_os()).EOL;
- var head = '/**';
- var start = ' *';
- var tail = ' */';
- var keys = Object.keys(pragmas);
- var printedObject = keys.map(function (key) {
- return printKeyValues(key, pragmas[key]);
- }).reduce(function (arr, next) {
- return arr.concat(next);
- }, []).map(function (keyValue) {
- return start + ' ' + keyValue + line;
- }).join('');
- if (!comments) {
- if (keys.length === 0) {
- return '';
- }
- if (keys.length === 1 && !Array.isArray(pragmas[keys[0]])) {
- var value = pragmas[keys[0]];
- return `${head} ${printKeyValues(keys[0], value)[0]}${tail}`;
- }
- }
- var printedComments = comments.split(line).map(function (textLine) {
- return `${start} ${textLine}`;
- }).join(line) + line;
- return head + line + (comments ? printedComments : '') + (comments && keys.length ? start + line : '') + printedObject + tail;
- }
- function printKeyValues(key, valueOrArray) {
- return [].concat(valueOrArray).map(function (value) {
- return `@${key} ${value}`.trim();
- });
- }
- });
- unwrapExports(build$1);
- function hasPragma(text) {
- var pragmas = Object.keys(build$1.parse(build$1.extract(text)));
- return pragmas.indexOf("prettier") !== -1 || pragmas.indexOf("format") !== -1;
- }
- function insertPragma$1(text) {
- var parsedDocblock = build$1.parseWithComments(build$1.extract(text));
- var pragmas = Object.assign({
- format: ""
- }, parsedDocblock.pragmas);
- var newDocblock = build$1.print({
- pragmas,
- comments: parsedDocblock.comments.replace(/^(\s+?\r?\n)+/, "") // remove leading newlines
- }).replace(/(\r\n|\r)/g, "\n"); // normalise newlines (mitigate use of os.EOL by jest-docblock)
- var strippedText = build$1.strip(text);
- var separatingNewlines = strippedText.startsWith("\n") ? "\n" : "\n\n";
- return newDocblock + separatingNewlines + strippedText;
- }
- var pragma = {
- hasPragma,
- insertPragma: insertPragma$1
- };
- // Flow annotation comments cannot be split across lines. For example:
- //
- // (this /*
- // : any */).foo = 5;
- //
- // is not picked up by Flow (see https://github.com/facebook/flow/issues/7050), so
- // removing the newline would create a type annotation that the user did not intend
- // to create.
- var NON_LINE_TERMINATING_WHITE_SPACE = "(?:(?=.)\\s)";
- var FLOW_SHORTHAND_ANNOTATION = new RegExp(`^${NON_LINE_TERMINATING_WHITE_SPACE}*:`);
- var FLOW_ANNOTATION = new RegExp(`^${NON_LINE_TERMINATING_WHITE_SPACE}*::`);
- function hasFlowShorthandAnnotationComment$2(node) {
- // https://flow.org/en/docs/types/comments/
- // Syntax example: const r = new (window.Request /*: Class<Request> */)("");
- return node.extra && node.extra.parenthesized && node.trailingComments && node.trailingComments[0].value.match(FLOW_SHORTHAND_ANNOTATION);
- }
- function hasFlowAnnotationComment$1(comments) {
- return comments && comments[0].value.match(FLOW_ANNOTATION);
- }
- function hasNode$1(node, fn) {
- if (!node || typeof node !== "object") {
- return false;
- }
- if (Array.isArray(node)) {
- return node.some(function (value) {
- return hasNode$1(value, fn);
- });
- }
- var result = fn(node);
- return typeof result === "boolean" ? result : Object.keys(node).some(function (key) {
- return hasNode$1(node[key], fn);
- });
- }
- var utils$4 = {
- hasNode: hasNode$1,
- hasFlowShorthandAnnotationComment: hasFlowShorthandAnnotationComment$2,
- hasFlowAnnotationComment: hasFlowAnnotationComment$1
- };
- var hasFlowShorthandAnnotationComment$1 = utils$4.hasFlowShorthandAnnotationComment;
- function hasClosureCompilerTypeCastComment(text, path$$1, locStart, locEnd) {
- // https://github.com/google/closure-compiler/wiki/Annotating-Types#type-casts
- // Syntax example: var x = /** @type {string} */ (fruit);
- var n = path$$1.getValue();
- return util$1.getNextNonSpaceNonCommentCharacter(text, n, locEnd) === ")" && (hasTypeCastComment(n) || hasAncestorTypeCastComment(0)); // for sub-item: /** @type {array} */ (numberOrString).map(x => x);
- function hasAncestorTypeCastComment(index) {
- var ancestor = path$$1.getParentNode(index);
- return ancestor && util$1.getNextNonSpaceNonCommentCharacter(text, ancestor, locEnd) !== ")" && /^[\s(]*$/.test(text.slice(locStart(ancestor), locStart(n))) ? hasTypeCastComment(ancestor) || hasAncestorTypeCastComment(index + 1) : false;
- }
- function hasTypeCastComment(node) {
- return node.comments && node.comments.some(function (comment) {
- return comment.leading && comments$3.isBlockComment(comment) && isTypeCastComment(comment.value) && util$1.getNextNonSpaceNonCommentCharacter(text, comment, locEnd) === "(";
- });
- }
- function isTypeCastComment(comment) {
- var trimmed = comment.trim();
- if (!/^\*\s*@type\s*\{[^]+\}$/.test(trimmed)) {
- return false;
- }
- var isCompletelyClosed = false;
- var unpairedBracketCount = 0;
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = trimmed[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var char = _step.value;
- if (char === "{") {
- if (isCompletelyClosed) {
- return false;
- }
- unpairedBracketCount++;
- } else if (char === "}") {
- if (unpairedBracketCount === 0) {
- return false;
- }
- unpairedBracketCount--;
- if (unpairedBracketCount === 0) {
- isCompletelyClosed = true;
- }
- }
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- return unpairedBracketCount === 0;
- }
- }
- function needsParens(path$$1, options) {
- var parent = path$$1.getParentNode();
- if (!parent) {
- return false;
- }
- var name = path$$1.getName();
- var node = path$$1.getNode(); // If the value of this path is some child of a Node and not a Node
- // itself, then it doesn't need parentheses. Only Node objects (in
- // fact, only Expression nodes) need parentheses.
- if (path$$1.getValue() !== node) {
- return false;
- } // to avoid unexpected `}}` in HTML interpolations
- if (options.__isInHtmlInterpolation && !options.bracketSpacing && endsWithRightBracket(node) && isFollowedByRightBracket(path$$1)) {
- return true;
- } // Only statements don't need parentheses.
- if (isStatement(node)) {
- return false;
- } // Closure compiler requires that type casted expressions to be surrounded by
- // parentheses.
- if (hasClosureCompilerTypeCastComment(options.originalText, path$$1, options.locStart, options.locEnd)) {
- return true;
- }
- if ( // Preserve parens if we have a Flow annotation comment, unless we're using the Flow
- // parser. The Flow parser turns Flow comments into type annotation nodes in its
- // AST, which we handle separately.
- options.parser !== "flow" && hasFlowShorthandAnnotationComment$1(path$$1.getValue())) {
- return true;
- } // Identifiers never need parentheses.
- if (node.type === "Identifier") {
- return false;
- }
- if (parent.type === "ParenthesizedExpression") {
- return false;
- } // Add parens around the extends clause of a class. It is needed for almost
- // all expressions.
- if ((parent.type === "ClassDeclaration" || parent.type === "ClassExpression") && parent.superClass === node && (node.type === "ArrowFunctionExpression" || node.type === "AssignmentExpression" || node.type === "AwaitExpression" || node.type === "BinaryExpression" || node.type === "ConditionalExpression" || node.type === "LogicalExpression" || node.type === "NewExpression" || node.type === "ObjectExpression" || node.type === "ParenthesizedExpression" || node.type === "SequenceExpression" || node.type === "TaggedTemplateExpression" || node.type === "UnaryExpression" || node.type === "UpdateExpression" || node.type === "YieldExpression")) {
- return true;
- }
- if (parent.type === "Decorator" && parent.expression === node) {
- var hasCallExpression = false;
- var hasMemberExpression = false;
- var current = node;
- while (current) {
- switch (current.type) {
- case "MemberExpression":
- hasMemberExpression = true;
- current = current.object;
- break;
- case "CallExpression":
- if (
- /** @(x().y) */
- hasMemberExpression ||
- /** @(x().y()) */
- hasCallExpression) {
- return true;
- }
- hasCallExpression = true;
- current = current.callee;
- break;
- case "Identifier":
- return false;
- default:
- return true;
- }
- }
- return true;
- }
- if (parent.type === "ArrowFunctionExpression" && parent.body === node && node.type !== "SequenceExpression" && // these have parens added anyway
- util$1.startsWithNoLookaheadToken(node,
- /* forbidFunctionClassAndDoExpr */
- false) || parent.type === "ExpressionStatement" && util$1.startsWithNoLookaheadToken(node,
- /* forbidFunctionClassAndDoExpr */
- true)) {
- return true;
- }
- switch (node.type) {
- case "CallExpression":
- {
- var firstParentNotMemberExpression = parent;
- var i = 0;
- while (firstParentNotMemberExpression && firstParentNotMemberExpression.type === "MemberExpression") {
- firstParentNotMemberExpression = path$$1.getParentNode(++i);
- }
- if (firstParentNotMemberExpression.type === "NewExpression" && firstParentNotMemberExpression.callee === path$$1.getParentNode(i - 1)) {
- return true;
- }
- if (parent.type === "BindExpression" && parent.callee === node) {
- return true;
- }
- return false;
- }
- case "SpreadElement":
- case "SpreadProperty":
- return parent.type === "MemberExpression" && name === "object" && parent.object === node;
- case "UpdateExpression":
- if (parent.type === "UnaryExpression") {
- return node.prefix && (node.operator === "++" && parent.operator === "+" || node.operator === "--" && parent.operator === "-");
- }
- // else fallthrough
- case "UnaryExpression":
- switch (parent.type) {
- case "UnaryExpression":
- return node.operator === parent.operator && (node.operator === "+" || node.operator === "-");
- case "BindExpression":
- return true;
- case "MemberExpression":
- return name === "object" && parent.object === node;
- case "TaggedTemplateExpression":
- return true;
- case "NewExpression":
- case "CallExpression":
- return name === "callee" && parent.callee === node;
- case "BinaryExpression":
- return parent.operator === "**" && name === "left";
- case "TSNonNullExpression":
- return true;
- default:
- return false;
- }
- case "BinaryExpression":
- {
- if (parent.type === "UpdateExpression") {
- return true;
- }
- var isLeftOfAForStatement = function isLeftOfAForStatement(node) {
- var i = 0;
- while (node) {
- var _parent = path$$1.getParentNode(i++);
- if (!_parent) {
- return false;
- }
- if (_parent.type === "ForStatement" && _parent.init === node) {
- return true;
- }
- node = _parent;
- }
- return false;
- };
- if (node.operator === "in" && isLeftOfAForStatement(node)) {
- return true;
- }
- }
- // fallthrough
- case "TSTypeAssertion":
- case "TSAsExpression":
- case "LogicalExpression":
- switch (parent.type) {
- case "ConditionalExpression":
- return node.type === "TSAsExpression";
- case "CallExpression":
- case "NewExpression":
- return name === "callee" && parent.callee === node;
- case "ClassExpression":
- case "ClassDeclaration":
- case "TSAbstractClassDeclaration":
- return name === "superClass" && parent.superClass === node;
- case "TSTypeAssertion":
- case "TaggedTemplateExpression":
- case "UnaryExpression":
- case "SpreadElement":
- case "SpreadProperty":
- case "BindExpression":
- case "AwaitExpression":
- case "TSAsExpression":
- case "TSNonNullExpression":
- case "UpdateExpression":
- return true;
- case "MemberExpression":
- case "OptionalMemberExpression":
- return name === "object" && parent.object === node;
- case "AssignmentExpression":
- return parent.left === node && (node.type === "TSTypeAssertion" || node.type === "TSAsExpression");
- case "BinaryExpression":
- case "LogicalExpression":
- {
- if (!node.operator && node.type !== "TSTypeAssertion") {
- return true;
- }
- var po = parent.operator;
- var pp = util$1.getPrecedence(po);
- var no = node.operator;
- var np = util$1.getPrecedence(no);
- if (pp > np) {
- return true;
- }
- if ((po === "||" || po === "??") && no === "&&") {
- return true;
- }
- if (pp === np && name === "right") {
- assert.strictEqual(parent.right, node);
- return true;
- }
- if (pp === np && !util$1.shouldFlatten(po, no)) {
- return true;
- }
- if (pp < np && no === "%") {
- return po === "+" || po === "-";
- } // Add parenthesis when working with bitwise operators
- // It's not stricly needed but helps with code understanding
- if (util$1.isBitwiseOperator(po)) {
- return true;
- }
- return false;
- }
- default:
- return false;
- }
- case "TSParenthesizedType":
- {
- var grandParent = path$$1.getParentNode(1);
- /**
- * const foo = (): (() => void) => (): void => null;
- * ^ ^
- */
- if (getUnparenthesizedNode(node).type === "TSFunctionType" && parent.type === "TSTypeAnnotation" && grandParent.type === "ArrowFunctionExpression" && grandParent.returnType === parent) {
- return true;
- }
- if ((parent.type === "TSTypeParameter" || parent.type === "TypeParameter" || parent.type === "TSTypeAliasDeclaration" || parent.type === "TSTypeAnnotation" || parent.type === "TSParenthesizedType" || parent.type === "TSTypeParameterInstantiation") && grandParent.type !== "TSTypeOperator" && grandParent.type !== "TSOptionalType") {
- return false;
- } // Delegate to inner TSParenthesizedType
- if (node.typeAnnotation.type === "TSParenthesizedType") {
- return false;
- }
- return true;
- }
- case "SequenceExpression":
- switch (parent.type) {
- case "ReturnStatement":
- return false;
- case "ForStatement":
- // Although parentheses wouldn't hurt around sequence
- // expressions in the head of for loops, traditional style
- // dictates that e.g. i++, j++ should not be wrapped with
- // parentheses.
- return false;
- case "ExpressionStatement":
- return name !== "expression";
- case "ArrowFunctionExpression":
- // We do need parentheses, but SequenceExpressions are handled
- // specially when printing bodies of arrow functions.
- return name !== "body";
- default:
- // Otherwise err on the side of overparenthesization, adding
- // explicit exceptions above if this proves overzealous.
- return true;
- }
- case "YieldExpression":
- if (parent.type === "UnaryExpression" || parent.type === "AwaitExpression" || parent.type === "TSAsExpression" || parent.type === "TSNonNullExpression") {
- return true;
- }
- // else fallthrough
- case "AwaitExpression":
- switch (parent.type) {
- case "TaggedTemplateExpression":
- case "UnaryExpression":
- case "BinaryExpression":
- case "LogicalExpression":
- case "SpreadElement":
- case "SpreadProperty":
- case "TSAsExpression":
- case "TSNonNullExpression":
- case "BindExpression":
- return true;
- case "MemberExpression":
- return parent.object === node;
- case "NewExpression":
- case "CallExpression":
- return parent.callee === node;
- case "ConditionalExpression":
- return parent.test === node;
- default:
- return false;
- }
- case "ArrayTypeAnnotation":
- return parent.type === "NullableTypeAnnotation";
- case "IntersectionTypeAnnotation":
- case "UnionTypeAnnotation":
- return parent.type === "ArrayTypeAnnotation" || parent.type === "NullableTypeAnnotation" || parent.type === "IntersectionTypeAnnotation" || parent.type === "UnionTypeAnnotation";
- case "NullableTypeAnnotation":
- return parent.type === "ArrayTypeAnnotation";
- case "FunctionTypeAnnotation":
- {
- var ancestor = parent.type === "NullableTypeAnnotation" ? path$$1.getParentNode(1) : parent;
- return ancestor.type === "UnionTypeAnnotation" || ancestor.type === "IntersectionTypeAnnotation" || ancestor.type === "ArrayTypeAnnotation" || // We should check ancestor's parent to know whether the parentheses
- // are really needed, but since ??T doesn't make sense this check
- // will almost never be true.
- ancestor.type === "NullableTypeAnnotation";
- }
- case "StringLiteral":
- case "NumericLiteral":
- case "Literal":
- if (typeof node.value === "string" && parent.type === "ExpressionStatement" && ( // TypeScript workaround for https://github.com/JamesHenry/typescript-estree/issues/2
- // See corresponding workaround in printer.js case: "Literal"
- options.parser !== "typescript" && !parent.directive || options.parser === "typescript" && options.originalText.substr(options.locStart(node) - 1, 1) === "(")) {
- // To avoid becoming a directive
- var _grandParent = path$$1.getParentNode(1);
- return _grandParent.type === "Program" || _grandParent.type === "BlockStatement";
- }
- return parent.type === "MemberExpression" && typeof node.value === "number" && name === "object" && parent.object === node;
- case "AssignmentExpression":
- {
- var _grandParent2 = path$$1.getParentNode(1);
- if (parent.type === "ArrowFunctionExpression" && parent.body === node) {
- return true;
- } else if (parent.type === "ClassProperty" && parent.key === node && parent.computed) {
- return false;
- } else if (parent.type === "TSPropertySignature" && parent.name === node) {
- return false;
- } else if (parent.type === "ForStatement" && (parent.init === node || parent.update === node)) {
- return false;
- } else if (parent.type === "ExpressionStatement") {
- return node.left.type === "ObjectPattern";
- } else if (parent.type === "TSPropertySignature" && parent.key === node) {
- return false;
- } else if (parent.type === "AssignmentExpression") {
- return false;
- } else if (parent.type === "SequenceExpression" && _grandParent2 && _grandParent2.type === "ForStatement" && (_grandParent2.init === parent || _grandParent2.update === parent)) {
- return false;
- } else if (parent.type === "Property" && parent.value === node) {
- return false;
- } else if (parent.type === "NGChainedExpression") {
- return false;
- }
- return true;
- }
- case "ConditionalExpression":
- switch (parent.type) {
- case "TaggedTemplateExpression":
- case "UnaryExpression":
- case "SpreadElement":
- case "SpreadProperty":
- case "BinaryExpression":
- case "LogicalExpression":
- case "NGPipeExpression":
- case "ExportDefaultDeclaration":
- case "AwaitExpression":
- case "JSXSpreadAttribute":
- case "TSTypeAssertion":
- case "TypeCastExpression":
- case "TSAsExpression":
- case "TSNonNullExpression":
- case "OptionalMemberExpression":
- return true;
- case "NewExpression":
- case "CallExpression":
- return name === "callee" && parent.callee === node;
- case "ConditionalExpression":
- return name === "test" && parent.test === node;
- case "MemberExpression":
- return name === "object" && parent.object === node;
- default:
- return false;
- }
- case "FunctionExpression":
- switch (parent.type) {
- case "CallExpression":
- return name === "callee";
- // Not strictly necessary, but it's clearer to the reader if IIFEs are wrapped in parentheses.
- case "TaggedTemplateExpression":
- return true;
- // This is basically a kind of IIFE.
- case "ExportDefaultDeclaration":
- return true;
- default:
- return false;
- }
- case "ArrowFunctionExpression":
- switch (parent.type) {
- case "CallExpression":
- return name === "callee";
- case "NewExpression":
- return name === "callee";
- case "MemberExpression":
- return name === "object";
- case "TSAsExpression":
- case "BindExpression":
- case "TaggedTemplateExpression":
- case "UnaryExpression":
- case "LogicalExpression":
- case "BinaryExpression":
- case "AwaitExpression":
- case "TSTypeAssertion":
- return true;
- case "ConditionalExpression":
- return name === "test";
- default:
- return false;
- }
- case "ClassExpression":
- return parent.type === "ExportDefaultDeclaration";
- case "OptionalMemberExpression":
- return parent.type === "MemberExpression";
- case "MemberExpression":
- if (parent.type === "BindExpression" && name === "callee" && parent.callee === node) {
- var object = node.object;
- while (object) {
- if (object.type === "CallExpression") {
- return true;
- }
- if (object.type !== "MemberExpression" && object.type !== "BindExpression") {
- break;
- }
- object = object.object;
- }
- }
- return false;
- case "BindExpression":
- if (parent.type === "BindExpression" && name === "callee" && parent.callee === node || parent.type === "MemberExpression") {
- return true;
- }
- return false;
- case "NGPipeExpression":
- if (parent.type === "NGRoot" || parent.type === "ObjectProperty" || parent.type === "ArrayExpression" || (parent.type === "CallExpression" || parent.type === "OptionalCallExpression") && parent.arguments[name] === node || parent.type === "NGPipeExpression" && name === "right" || parent.type === "MemberExpression" && name === "property" || parent.type === "AssignmentExpression") {
- return false;
- }
- return true;
- }
- return false;
- }
- function isStatement(node) {
- return node.type === "BlockStatement" || node.type === "BreakStatement" || node.type === "ClassBody" || node.type === "ClassDeclaration" || node.type === "ClassMethod" || node.type === "ClassProperty" || node.type === "ClassPrivateProperty" || node.type === "ContinueStatement" || node.type === "DebuggerStatement" || node.type === "DeclareClass" || node.type === "DeclareExportAllDeclaration" || node.type === "DeclareExportDeclaration" || node.type === "DeclareFunction" || node.type === "DeclareInterface" || node.type === "DeclareModule" || node.type === "DeclareModuleExports" || node.type === "DeclareVariable" || node.type === "DoWhileStatement" || node.type === "ExportAllDeclaration" || node.type === "ExportDefaultDeclaration" || node.type === "ExportNamedDeclaration" || node.type === "ExpressionStatement" || node.type === "ForAwaitStatement" || node.type === "ForInStatement" || node.type === "ForOfStatement" || node.type === "ForStatement" || node.type === "FunctionDeclaration" || node.type === "IfStatement" || node.type === "ImportDeclaration" || node.type === "InterfaceDeclaration" || node.type === "LabeledStatement" || node.type === "MethodDefinition" || node.type === "ReturnStatement" || node.type === "SwitchStatement" || node.type === "ThrowStatement" || node.type === "TryStatement" || node.type === "TSAbstractClassDeclaration" || node.type === "TSDeclareFunction" || node.type === "TSEnumDeclaration" || node.type === "TSImportEqualsDeclaration" || node.type === "TSInterfaceDeclaration" || node.type === "TSModuleDeclaration" || node.type === "TSNamespaceExportDeclaration" || node.type === "TypeAlias" || node.type === "VariableDeclaration" || node.type === "WhileStatement" || node.type === "WithStatement";
- }
- function getUnparenthesizedNode(node) {
- return node.type === "TSParenthesizedType" ? getUnparenthesizedNode(node.typeAnnotation) : node;
- }
- function endsWithRightBracket(node) {
- switch (node.type) {
- case "ObjectExpression":
- return true;
- default:
- return false;
- }
- }
- function isFollowedByRightBracket(path$$1) {
- var node = path$$1.getValue();
- var parent = path$$1.getParentNode();
- var name = path$$1.getName();
- switch (parent.type) {
- case "NGPipeExpression":
- if (typeof name === "number" && parent.arguments[name] === node && parent.arguments.length - 1 === name) {
- return path$$1.callParent(isFollowedByRightBracket);
- }
- break;
- case "ObjectProperty":
- if (name === "value") {
- var parentParent = path$$1.getParentNode(1);
- return parentParent.properties[parentParent.properties.length - 1] === parent;
- }
- break;
- case "BinaryExpression":
- case "LogicalExpression":
- if (name === "right") {
- return path$$1.callParent(isFollowedByRightBracket);
- }
- break;
- case "ConditionalExpression":
- if (name === "alternate") {
- return path$$1.callParent(isFollowedByRightBracket);
- }
- break;
- case "UnaryExpression":
- if (parent.prefix) {
- return path$$1.callParent(isFollowedByRightBracket);
- }
- break;
- }
- return false;
- }
- var needsParens_1 = needsParens;
- var _require$$0$builders$1 = doc.builders;
- var concat$6 = _require$$0$builders$1.concat;
- var join$4 = _require$$0$builders$1.join;
- var line$4 = _require$$0$builders$1.line;
- function printHtmlBinding$1(path$$1, options, print) {
- var node = path$$1.getValue();
- if (options.__onHtmlBindingRoot && path$$1.getName() === null) {
- options.__onHtmlBindingRoot(node);
- }
- if (node.type !== "File") {
- return;
- }
- if (options.__isVueForBindingLeft) {
- return path$$1.call(function (functionDeclarationPath) {
- var _functionDeclarationP = functionDeclarationPath.getValue(),
- params = _functionDeclarationP.params;
- return concat$6([params.length > 1 ? "(" : "", join$4(concat$6([",", line$4]), functionDeclarationPath.map(print, "params")), params.length > 1 ? ")" : ""]);
- }, "program", "body", 0);
- }
- if (options.__isVueSlotScope) {
- return path$$1.call(function (functionDeclarationPath) {
- return join$4(concat$6([",", line$4]), functionDeclarationPath.map(print, "params"));
- }, "program", "body", 0);
- }
- } // based on https://github.com/prettier/prettier/blob/master/src/language-html/syntax-vue.js isVueEventBindingExpression()
- function isVueEventBindingExpression$1(node) {
- switch (node.type) {
- case "MemberExpression":
- switch (node.property.type) {
- case "Identifier":
- case "NumericLiteral":
- case "StringLiteral":
- return isVueEventBindingExpression$1(node.object);
- }
- return false;
- case "Identifier":
- return true;
- default:
- return false;
- }
- }
- var htmlBinding = {
- isVueEventBindingExpression: isVueEventBindingExpression$1,
- printHtmlBinding: printHtmlBinding$1
- };
- function preprocess(ast, options) {
- switch (options.parser) {
- case "json":
- case "json5":
- case "json-stringify":
- case "__js_expression":
- case "__vue_expression":
- return Object.assign({}, ast, {
- type: options.parser.startsWith("__") ? "JsExpressionRoot" : "JsonRoot",
- node: ast,
- comments: []
- });
- default:
- return ast;
- }
- }
- var preprocess_1 = preprocess;
- var getParentExportDeclaration$1 = util$1.getParentExportDeclaration;
- var isExportDeclaration$1 = util$1.isExportDeclaration;
- var shouldFlatten$1 = util$1.shouldFlatten;
- var getNextNonSpaceNonCommentCharacter$1 = util$1.getNextNonSpaceNonCommentCharacter;
- var hasNewline$2 = util$1.hasNewline;
- var hasNewlineInRange$1 = util$1.hasNewlineInRange;
- var getLast$4 = util$1.getLast;
- var getStringWidth$2 = util$1.getStringWidth;
- var printString$1 = util$1.printString;
- var printNumber$1 = util$1.printNumber;
- var hasIgnoreComment$1 = util$1.hasIgnoreComment;
- var skipWhitespace$1 = util$1.skipWhitespace;
- var hasNodeIgnoreComment$1 = util$1.hasNodeIgnoreComment;
- var getPenultimate$1 = util$1.getPenultimate;
- var startsWithNoLookaheadToken$1 = util$1.startsWithNoLookaheadToken;
- var getIndentSize$1 = util$1.getIndentSize;
- var matchAncestorTypes$1 = util$1.matchAncestorTypes;
- var getPreferredQuote$1 = util$1.getPreferredQuote;
- var isNextLineEmpty$2 = utilShared.isNextLineEmpty;
- var isNextLineEmptyAfterIndex$1 = utilShared.isNextLineEmptyAfterIndex;
- var getNextNonSpaceNonCommentCharacterIndex$2 = utilShared.getNextNonSpaceNonCommentCharacterIndex;
- var isIdentifierName = utils$2.keyword.isIdentifierNameES5;
- var insertPragma = pragma.insertPragma;
- var printHtmlBinding = htmlBinding.printHtmlBinding;
- var isVueEventBindingExpression = htmlBinding.isVueEventBindingExpression;
- var hasNode = utils$4.hasNode;
- var hasFlowAnnotationComment = utils$4.hasFlowAnnotationComment;
- var hasFlowShorthandAnnotationComment = utils$4.hasFlowShorthandAnnotationComment;
- var _require$$6$builders = doc.builders;
- var concat$4 = _require$$6$builders.concat;
- var join$2 = _require$$6$builders.join;
- var line$3 = _require$$6$builders.line;
- var hardline$3 = _require$$6$builders.hardline;
- var softline$1 = _require$$6$builders.softline;
- var literalline$1 = _require$$6$builders.literalline;
- var group$1 = _require$$6$builders.group;
- var indent$2 = _require$$6$builders.indent;
- var align$1 = _require$$6$builders.align;
- var conditionalGroup$1 = _require$$6$builders.conditionalGroup;
- var fill$2 = _require$$6$builders.fill;
- var ifBreak$1 = _require$$6$builders.ifBreak;
- var breakParent$2 = _require$$6$builders.breakParent;
- var lineSuffixBoundary$1 = _require$$6$builders.lineSuffixBoundary;
- var addAlignmentToDoc$2 = _require$$6$builders.addAlignmentToDoc;
- var dedent$2 = _require$$6$builders.dedent;
- var _require$$6$utils = doc.utils;
- var willBreak$1 = _require$$6$utils.willBreak;
- var isLineNext$1 = _require$$6$utils.isLineNext;
- var isEmpty$1 = _require$$6$utils.isEmpty;
- var removeLines$1 = _require$$6$utils.removeLines;
- var printDocToString$2 = doc.printer.printDocToString;
- var uid = 0;
- function shouldPrintComma(options, level) {
- level = level || "es5";
- switch (options.trailingComma) {
- case "all":
- if (level === "all") {
- return true;
- }
- // fallthrough
- case "es5":
- if (level === "es5") {
- return true;
- }
- // fallthrough
- case "none":
- default:
- return false;
- }
- }
- function genericPrint(path$$1, options, printPath, args) {
- var node = path$$1.getValue();
- var needsParens = false;
- var linesWithoutParens = printPathNoParens(path$$1, options, printPath, args);
- if (!node || isEmpty$1(linesWithoutParens)) {
- return linesWithoutParens;
- }
- var parentExportDecl = getParentExportDeclaration$1(path$$1);
- var decorators = [];
- if (node.type === "ClassMethod" || node.type === "ClassPrivateMethod" || node.type === "ClassProperty" || node.type === "TSAbstractClassProperty" || node.type === "ClassPrivateProperty" || node.type === "MethodDefinition" || node.type === "TSAbstractMethodDefinition") {// their decorators are handled themselves
- } else if (node.decorators && node.decorators.length > 0 && // If the parent node is an export declaration and the decorator
- // was written before the export, the export will be responsible
- // for printing the decorators.
- !(parentExportDecl && options.locStart(parentExportDecl, {
- ignoreDecorators: true
- }) > options.locStart(node.decorators[0]))) {
- var shouldBreak = node.type === "ClassExpression" || node.type === "ClassDeclaration" || hasNewlineBetweenOrAfterDecorators(node, options);
- var separator = shouldBreak ? hardline$3 : line$3;
- path$$1.each(function (decoratorPath) {
- var decorator = decoratorPath.getValue();
- if (decorator.expression) {
- decorator = decorator.expression;
- } else {
- decorator = decorator.callee;
- }
- decorators.push(printPath(decoratorPath), separator);
- }, "decorators");
- if (parentExportDecl) {
- decorators.unshift(hardline$3);
- }
- } else if (isExportDeclaration$1(node) && node.declaration && node.declaration.decorators && node.declaration.decorators.length > 0 && // Only print decorators here if they were written before the export,
- // otherwise they are printed by the node.declaration
- options.locStart(node, {
- ignoreDecorators: true
- }) > options.locStart(node.declaration.decorators[0])) {
- // Export declarations are responsible for printing any decorators
- // that logically apply to node.declaration.
- path$$1.each(function (decoratorPath) {
- var decorator = decoratorPath.getValue();
- var prefix = decorator.type === "Decorator" ? "" : "@";
- decorators.push(prefix, printPath(decoratorPath), hardline$3);
- }, "declaration", "decorators");
- } else {
- // Nodes with decorators can't have parentheses, so we can avoid
- // computing pathNeedsParens() except in this case.
- needsParens = needsParens_1(path$$1, options);
- }
- var parts = [];
- if (needsParens) {
- parts.unshift("(");
- }
- parts.push(linesWithoutParens);
- if (needsParens) {
- var _node = path$$1.getValue();
- if (hasFlowShorthandAnnotationComment(_node)) {
- parts.push(" /*");
- parts.push(_node.trailingComments[0].value.trimLeft());
- parts.push("*/");
- _node.trailingComments[0].printed = true;
- }
- parts.push(")");
- }
- if (decorators.length > 0) {
- return group$1(concat$4(decorators.concat(parts)));
- }
- return concat$4(parts);
- }
- function hasNewlineBetweenOrAfterDecorators(node, options) {
- return hasNewlineInRange$1(options.originalText, options.locStart(node.decorators[0]), options.locEnd(getLast$4(node.decorators))) || hasNewline$2(options.originalText, options.locEnd(getLast$4(node.decorators)));
- }
- function printDecorators(path$$1, options, print) {
- var node = path$$1.getValue();
- return group$1(concat$4([join$2(line$3, path$$1.map(print, "decorators")), hasNewlineBetweenOrAfterDecorators(node, options) ? hardline$3 : line$3]));
- }
- function hasPrettierIgnore(path$$1) {
- return hasIgnoreComment$1(path$$1) || hasJsxIgnoreComment(path$$1);
- }
- function hasJsxIgnoreComment(path$$1) {
- var node = path$$1.getValue();
- var parent = path$$1.getParentNode();
- if (!parent || !node || !isJSXNode(node) || !isJSXNode(parent)) {
- return false;
- } // Lookup the previous sibling, ignoring any empty JSXText elements
- var index = parent.children.indexOf(node);
- var prevSibling = null;
- for (var i = index; i > 0; i--) {
- var candidate = parent.children[i - 1];
- if (candidate.type === "JSXText" && !isMeaningfulJSXText(candidate)) {
- continue;
- }
- prevSibling = candidate;
- break;
- }
- return prevSibling && prevSibling.type === "JSXExpressionContainer" && prevSibling.expression.type === "JSXEmptyExpression" && prevSibling.expression.comments && prevSibling.expression.comments.find(function (comment) {
- return comment.value.trim() === "prettier-ignore";
- });
- }
- /**
- * The following is the shared logic for
- * ternary operators, namely ConditionalExpression
- * and TSConditionalType
- * @typedef {Object} OperatorOptions
- * @property {() => Array<string | Doc>} beforeParts - Parts to print before the `?`.
- * @property {(breakClosingParen: boolean) => Array<string | Doc>} afterParts - Parts to print after the conditional expression.
- * @property {boolean} shouldCheckJsx - Whether to check for and print in JSX mode.
- * @property {string} conditionalNodeType - The type of the conditional expression node, ie "ConditionalExpression" or "TSConditionalType".
- * @property {string} consequentNodePropertyName - The property at which the consequent node can be found on the main node, eg "consequent".
- * @property {string} alternateNodePropertyName - The property at which the alternate node can be found on the main node, eg "alternate".
- * @property {string} testNodePropertyName - The property at which the test node can be found on the main node, eg "test".
- * @property {boolean} breakNested - Whether to break all nested ternaries when one breaks.
- * @param {FastPath} path - The path to the ConditionalExpression/TSConditionalType node.
- * @param {Options} options - Prettier options
- * @param {Function} print - Print function to call recursively
- * @param {OperatorOptions} operatorOptions
- * @returns Doc
- */
- function printTernaryOperator(path$$1, options, print, operatorOptions) {
- var node = path$$1.getValue();
- var testNode = node[operatorOptions.testNodePropertyName];
- var consequentNode = node[operatorOptions.consequentNodePropertyName];
- var alternateNode = node[operatorOptions.alternateNodePropertyName];
- var parts = []; // We print a ConditionalExpression in either "JSX mode" or "normal mode".
- // See tests/jsx/conditional-expression.js for more info.
- var jsxMode = false;
- var parent = path$$1.getParentNode();
- var forceNoIndent = parent.type === operatorOptions.conditionalNodeType; // Find the outermost non-ConditionalExpression parent, and the outermost
- // ConditionalExpression parent. We'll use these to determine if we should
- // print in JSX mode.
- var currentParent;
- var previousParent;
- var i = 0;
- do {
- previousParent = currentParent || node;
- currentParent = path$$1.getParentNode(i);
- i++;
- } while (currentParent && currentParent.type === operatorOptions.conditionalNodeType);
- var firstNonConditionalParent = currentParent || parent;
- var lastConditionalParent = previousParent;
- if (operatorOptions.shouldCheckJsx && (isJSXNode(testNode) || isJSXNode(consequentNode) || isJSXNode(alternateNode) || conditionalExpressionChainContainsJSX(lastConditionalParent))) {
- jsxMode = true;
- forceNoIndent = true; // Even though they don't need parens, we wrap (almost) everything in
- // parens when using ?: within JSX, because the parens are analogous to
- // curly braces in an if statement.
- var wrap = function wrap(doc$$2) {
- return concat$4([ifBreak$1("(", ""), indent$2(concat$4([softline$1, doc$$2])), softline$1, ifBreak$1(")", "")]);
- }; // The only things we don't wrap are:
- // * Nested conditional expressions in alternates
- // * null
- var isNull = function isNull(node) {
- return node.type === "NullLiteral" || node.type === "Literal" && node.value === null;
- };
- parts.push(" ? ", isNull(consequentNode) ? path$$1.call(print, operatorOptions.consequentNodePropertyName) : wrap(path$$1.call(print, operatorOptions.consequentNodePropertyName)), " : ", alternateNode.type === operatorOptions.conditionalNodeType || isNull(alternateNode) ? path$$1.call(print, operatorOptions.alternateNodePropertyName) : wrap(path$$1.call(print, operatorOptions.alternateNodePropertyName)));
- } else {
- // normal mode
- var part = concat$4([line$3, "? ", consequentNode.type === operatorOptions.conditionalNodeType ? ifBreak$1("", "(") : "", align$1(2, path$$1.call(print, operatorOptions.consequentNodePropertyName)), consequentNode.type === operatorOptions.conditionalNodeType ? ifBreak$1("", ")") : "", line$3, ": ", alternateNode.type === operatorOptions.conditionalNodeType ? path$$1.call(print, operatorOptions.alternateNodePropertyName) : align$1(2, path$$1.call(print, operatorOptions.alternateNodePropertyName))]);
- parts.push(parent.type !== operatorOptions.conditionalNodeType || parent[operatorOptions.alternateNodePropertyName] === node ? part : options.useTabs ? dedent$2(indent$2(part)) : align$1(Math.max(0, options.tabWidth - 2), part));
- } // We want a whole chain of ConditionalExpressions to all
- // break if any of them break. That means we should only group around the
- // outer-most ConditionalExpression.
- var maybeGroup = function maybeGroup(doc$$2) {
- return operatorOptions.breakNested ? parent === firstNonConditionalParent ? group$1(doc$$2) : doc$$2 : group$1(doc$$2);
- }; // Break the closing paren to keep the chain right after it:
- // (a
- // ? b
- // : c
- // ).call()
- var breakClosingParen = !jsxMode && (parent.type === "MemberExpression" || parent.type === "OptionalMemberExpression") && !parent.computed;
- return maybeGroup(concat$4([].concat(function (testDoc) {
- return (
- /**
- * a
- * ? b
- * : multiline
- * test
- * node
- * ^^ align(2)
- * ? d
- * : e
- */
- parent.type === operatorOptions.conditionalNodeType && parent[operatorOptions.alternateNodePropertyName] === node ? align$1(2, testDoc) : testDoc
- );
- }(concat$4(operatorOptions.beforeParts())), forceNoIndent ? concat$4(parts) : indent$2(concat$4(parts)), operatorOptions.afterParts(breakClosingParen))));
- }
- function getTypeScriptMappedTypeModifier(tokenNode, keyword) {
- if (tokenNode === "+") {
- return "+" + keyword;
- } else if (tokenNode === "-") {
- return "-" + keyword;
- }
- return keyword;
- }
- function printPathNoParens(path$$1, options, print, args) {
- var n = path$$1.getValue();
- var semi = options.semi ? ";" : "";
- if (!n) {
- return "";
- }
- if (typeof n === "string") {
- return n;
- }
- var htmlBinding$$1 = printHtmlBinding(path$$1, options, print);
- if (htmlBinding$$1) {
- return htmlBinding$$1;
- }
- var parts = [];
- switch (n.type) {
- case "JsExpressionRoot":
- return path$$1.call(print, "node");
- case "JsonRoot":
- return concat$4([path$$1.call(print, "node"), hardline$3]);
- case "File":
- // Print @babel/parser's InterpreterDirective here so that
- // leading comments on the `Program` node get printed after the hashbang.
- if (n.program && n.program.interpreter) {
- parts.push(path$$1.call(function (programPath) {
- return programPath.call(print, "interpreter");
- }, "program"));
- }
- parts.push(path$$1.call(print, "program"));
- return concat$4(parts);
- case "Program":
- // Babel 6
- if (n.directives) {
- path$$1.each(function (childPath) {
- parts.push(print(childPath), semi, hardline$3);
- if (isNextLineEmpty$2(options.originalText, childPath.getValue(), options)) {
- parts.push(hardline$3);
- }
- }, "directives");
- }
- parts.push(path$$1.call(function (bodyPath) {
- return printStatementSequence(bodyPath, options, print);
- }, "body"));
- parts.push(comments.printDanglingComments(path$$1, options,
- /* sameIndent */
- true)); // Only force a trailing newline if there were any contents.
- if (n.body.length || n.comments) {
- parts.push(hardline$3);
- }
- return concat$4(parts);
- // Babel extension.
- case "EmptyStatement":
- return "";
- case "ExpressionStatement":
- // Detect Flow-parsed directives
- if (n.directive) {
- return concat$4([nodeStr(n.expression, options, true), semi]);
- }
- if (options.parser === "__vue_event_binding") {
- var parent = path$$1.getParentNode();
- if (parent.type === "Program" && parent.body.length === 1 && parent.body[0] === n) {
- return concat$4([path$$1.call(print, "expression"), isVueEventBindingExpression(n.expression) ? ";" : ""]);
- }
- } // Do not append semicolon after the only JSX element in a program
- return concat$4([path$$1.call(print, "expression"), isTheOnlyJSXElementInMarkdown(options, path$$1) ? "" : semi]);
- // Babel extension.
- case "ParenthesizedExpression":
- return concat$4(["(", path$$1.call(print, "expression"), ")"]);
- case "AssignmentExpression":
- return printAssignment(n.left, path$$1.call(print, "left"), concat$4([" ", n.operator]), n.right, path$$1.call(print, "right"), options);
- case "BinaryExpression":
- case "LogicalExpression":
- case "NGPipeExpression":
- {
- var _parent = path$$1.getParentNode();
- var parentParent = path$$1.getParentNode(1);
- var isInsideParenthesis = n !== _parent.body && (_parent.type === "IfStatement" || _parent.type === "WhileStatement" || _parent.type === "DoWhileStatement");
- var _parts = printBinaryishExpressions(path$$1, print, options,
- /* isNested */
- false, isInsideParenthesis); // if (
- // this.hasPlugin("dynamicImports") && this.lookahead().type === tt.parenLeft
- // ) {
- //
- // looks super weird, we want to break the children if the parent breaks
- //
- // if (
- // this.hasPlugin("dynamicImports") &&
- // this.lookahead().type === tt.parenLeft
- // ) {
- if (isInsideParenthesis) {
- return concat$4(_parts);
- } // Break between the parens in unaries or in a member expression, i.e.
- //
- // (
- // a &&
- // b &&
- // c
- // ).call()
- if (_parent.type === "UnaryExpression" || (_parent.type === "MemberExpression" || _parent.type === "OptionalMemberExpression") && !_parent.computed) {
- return group$1(concat$4([indent$2(concat$4([softline$1, concat$4(_parts)])), softline$1]));
- } // Avoid indenting sub-expressions in some cases where the first sub-expression is already
- // indented accordingly. We should indent sub-expressions where the first case isn't indented.
- var shouldNotIndent = _parent.type === "ReturnStatement" || _parent.type === "JSXExpressionContainer" && parentParent.type === "JSXAttribute" || n.type !== "NGPipeExpression" && (_parent.type === "NGRoot" && options.parser === "__ng_binding" || _parent.type === "NGMicrosyntaxExpression" && parentParent.type === "NGMicrosyntax" && parentParent.body.length === 1) || n === _parent.body && _parent.type === "ArrowFunctionExpression" || n !== _parent.body && _parent.type === "ForStatement" || _parent.type === "ConditionalExpression" && parentParent.type !== "ReturnStatement" && parentParent.type !== "CallExpression";
- var shouldIndentIfInlining = _parent.type === "AssignmentExpression" || _parent.type === "VariableDeclarator" || _parent.type === "ClassProperty" || _parent.type === "TSAbstractClassProperty" || _parent.type === "ClassPrivateProperty" || _parent.type === "ObjectProperty" || _parent.type === "Property";
- var samePrecedenceSubExpression = isBinaryish(n.left) && shouldFlatten$1(n.operator, n.left.operator);
- if (shouldNotIndent || shouldInlineLogicalExpression(n) && !samePrecedenceSubExpression || !shouldInlineLogicalExpression(n) && shouldIndentIfInlining) {
- return group$1(concat$4(_parts));
- }
- if (_parts.length === 0) {
- return "";
- } // If the right part is a JSX node, we include it in a separate group to
- // prevent it breaking the whole chain, so we can print the expression like:
- //
- // foo && bar && (
- // <Foo>
- // <Bar />
- // </Foo>
- // )
- var hasJSX = isJSXNode(n.right);
- var rest = concat$4(hasJSX ? _parts.slice(1, -1) : _parts.slice(1));
- var groupId = Symbol("logicalChain-" + ++uid);
- var chain = group$1(concat$4([// Don't include the initial expression in the indentation
- // level. The first item is guaranteed to be the first
- // left-most expression.
- _parts.length > 0 ? _parts[0] : "", indent$2(rest)]), {
- id: groupId
- });
- if (!hasJSX) {
- return chain;
- }
- var jsxPart = getLast$4(_parts);
- return group$1(concat$4([chain, ifBreak$1(indent$2(jsxPart), jsxPart, {
- groupId
- })]));
- }
- case "AssignmentPattern":
- return concat$4([path$$1.call(print, "left"), " = ", path$$1.call(print, "right")]);
- case "TSTypeAssertion":
- {
- var shouldBreakAfterCast = !(n.expression.type === "ArrayExpression" || n.expression.type === "ObjectExpression");
- var castGroup = group$1(concat$4(["<", indent$2(concat$4([softline$1, path$$1.call(print, "typeAnnotation")])), softline$1, ">"]));
- var exprContents = concat$4([ifBreak$1("("), indent$2(concat$4([softline$1, path$$1.call(print, "expression")])), softline$1, ifBreak$1(")")]);
- if (shouldBreakAfterCast) {
- return conditionalGroup$1([concat$4([castGroup, path$$1.call(print, "expression")]), concat$4([castGroup, group$1(exprContents, {
- shouldBreak: true
- })]), concat$4([castGroup, path$$1.call(print, "expression")])]);
- }
- return group$1(concat$4([castGroup, path$$1.call(print, "expression")]));
- }
- case "OptionalMemberExpression":
- case "MemberExpression":
- {
- var _parent2 = path$$1.getParentNode();
- var firstNonMemberParent;
- var i = 0;
- do {
- firstNonMemberParent = path$$1.getParentNode(i);
- i++;
- } while (firstNonMemberParent && (firstNonMemberParent.type === "MemberExpression" || firstNonMemberParent.type === "OptionalMemberExpression" || firstNonMemberParent.type === "TSNonNullExpression"));
- var shouldInline = firstNonMemberParent && (firstNonMemberParent.type === "NewExpression" || firstNonMemberParent.type === "BindExpression" || firstNonMemberParent.type === "VariableDeclarator" && firstNonMemberParent.id.type !== "Identifier" || firstNonMemberParent.type === "AssignmentExpression" && firstNonMemberParent.left.type !== "Identifier") || n.computed || n.object.type === "Identifier" && n.property.type === "Identifier" && _parent2.type !== "MemberExpression" && _parent2.type !== "OptionalMemberExpression";
- return concat$4([path$$1.call(print, "object"), shouldInline ? printMemberLookup(path$$1, options, print) : group$1(indent$2(concat$4([softline$1, printMemberLookup(path$$1, options, print)])))]);
- }
- case "MetaProperty":
- return concat$4([path$$1.call(print, "meta"), ".", path$$1.call(print, "property")]);
- case "BindExpression":
- if (n.object) {
- parts.push(path$$1.call(print, "object"));
- }
- parts.push(group$1(indent$2(concat$4([softline$1, printBindExpressionCallee(path$$1, options, print)]))));
- return concat$4(parts);
- case "Identifier":
- {
- return concat$4([n.name, printOptionalToken(path$$1), printTypeAnnotation(path$$1, options, print)]);
- }
- case "SpreadElement":
- case "SpreadElementPattern":
- case "RestProperty":
- case "SpreadProperty":
- case "SpreadPropertyPattern":
- case "RestElement":
- case "ObjectTypeSpreadProperty":
- return concat$4(["...", path$$1.call(print, "argument"), printTypeAnnotation(path$$1, options, print)]);
- case "FunctionDeclaration":
- case "FunctionExpression":
- parts.push(printFunctionDeclaration(path$$1, print, options));
- if (!n.body) {
- parts.push(semi);
- }
- return concat$4(parts);
- case "ArrowFunctionExpression":
- {
- if (n.async) {
- parts.push("async ");
- }
- if (shouldPrintParamsWithoutParens(path$$1, options)) {
- parts.push(path$$1.call(print, "params", 0));
- } else {
- parts.push(group$1(concat$4([printFunctionParams(path$$1, print, options,
- /* expandLast */
- args && (args.expandLastArg || args.expandFirstArg),
- /* printTypeParams */
- true), printReturnType(path$$1, print, options)])));
- }
- var dangling = comments.printDanglingComments(path$$1, options,
- /* sameIndent */
- true, function (comment) {
- var nextCharacter = getNextNonSpaceNonCommentCharacterIndex$2(options.originalText, comment, options);
- return options.originalText.substr(nextCharacter, 2) === "=>";
- });
- if (dangling) {
- parts.push(" ", dangling);
- }
- parts.push(" =>");
- var body = path$$1.call(function (bodyPath) {
- return print(bodyPath, args);
- }, "body"); // We want to always keep these types of nodes on the same line
- // as the arrow.
- if (!hasLeadingOwnLineComment(options.originalText, n.body, options) && (n.body.type === "ArrayExpression" || n.body.type === "ObjectExpression" || n.body.type === "BlockStatement" || isJSXNode(n.body) || isTemplateOnItsOwnLine(n.body, options.originalText, options) || n.body.type === "ArrowFunctionExpression" || n.body.type === "DoExpression")) {
- return group$1(concat$4([concat$4(parts), " ", body]));
- } // We handle sequence expressions as the body of arrows specially,
- // so that the required parentheses end up on their own lines.
- if (n.body.type === "SequenceExpression") {
- return group$1(concat$4([concat$4(parts), group$1(concat$4([" (", indent$2(concat$4([softline$1, body])), softline$1, ")"]))]));
- } // if the arrow function is expanded as last argument, we are adding a
- // level of indentation and need to add a softline to align the closing )
- // with the opening (, or if it's inside a JSXExpression (e.g. an attribute)
- // we should align the expression's closing } with the line with the opening {.
- var shouldAddSoftLine = (args && args.expandLastArg || path$$1.getParentNode().type === "JSXExpressionContainer") && !(n.comments && n.comments.length);
- var printTrailingComma = args && args.expandLastArg && shouldPrintComma(options, "all"); // In order to avoid confusion between
- // a => a ? a : a
- // a <= a ? a : a
- var shouldAddParens = n.body.type === "ConditionalExpression" && !startsWithNoLookaheadToken$1(n.body,
- /* forbidFunctionAndClass */
- false);
- return group$1(concat$4([concat$4(parts), group$1(concat$4([indent$2(concat$4([line$3, shouldAddParens ? ifBreak$1("", "(") : "", body, shouldAddParens ? ifBreak$1("", ")") : ""])), shouldAddSoftLine ? concat$4([ifBreak$1(printTrailingComma ? "," : ""), softline$1]) : ""]))]));
- }
- case "MethodDefinition":
- case "TSAbstractMethodDefinition":
- if (n.decorators && n.decorators.length !== 0) {
- parts.push(printDecorators(path$$1, options, print));
- }
- if (n.accessibility) {
- parts.push(n.accessibility + " ");
- }
- if (n.static) {
- parts.push("static ");
- }
- if (n.type === "TSAbstractMethodDefinition") {
- parts.push("abstract ");
- }
- parts.push(printMethod(path$$1, options, print));
- return concat$4(parts);
- case "YieldExpression":
- parts.push("yield");
- if (n.delegate) {
- parts.push("*");
- }
- if (n.argument) {
- parts.push(" ", path$$1.call(print, "argument"));
- }
- return concat$4(parts);
- case "AwaitExpression":
- return concat$4(["await ", path$$1.call(print, "argument")]);
- case "ImportSpecifier":
- if (n.importKind) {
- parts.push(path$$1.call(print, "importKind"), " ");
- }
- parts.push(path$$1.call(print, "imported"));
- if (n.local && n.local.name !== n.imported.name) {
- parts.push(" as ", path$$1.call(print, "local"));
- }
- return concat$4(parts);
- case "ExportSpecifier":
- parts.push(path$$1.call(print, "local"));
- if (n.exported && n.exported.name !== n.local.name) {
- parts.push(" as ", path$$1.call(print, "exported"));
- }
- return concat$4(parts);
- case "ImportNamespaceSpecifier":
- parts.push("* as ");
- parts.push(path$$1.call(print, "local"));
- return concat$4(parts);
- case "ImportDefaultSpecifier":
- return path$$1.call(print, "local");
- case "TSExportAssignment":
- return concat$4(["export = ", path$$1.call(print, "expression"), semi]);
- case "ExportDefaultDeclaration":
- case "ExportNamedDeclaration":
- return printExportDeclaration(path$$1, options, print);
- case "ExportAllDeclaration":
- parts.push("export ");
- if (n.exportKind === "type") {
- parts.push("type ");
- }
- parts.push("* from ", path$$1.call(print, "source"), semi);
- return concat$4(parts);
- case "ExportNamespaceSpecifier":
- case "ExportDefaultSpecifier":
- return path$$1.call(print, "exported");
- case "ImportDeclaration":
- {
- parts.push("import ");
- if (n.importKind && n.importKind !== "value") {
- parts.push(n.importKind + " ");
- }
- var standalones = [];
- var grouped = [];
- if (n.specifiers && n.specifiers.length > 0) {
- path$$1.each(function (specifierPath) {
- var value = specifierPath.getValue();
- if (value.type === "ImportDefaultSpecifier" || value.type === "ImportNamespaceSpecifier") {
- standalones.push(print(specifierPath));
- } else {
- grouped.push(print(specifierPath));
- }
- }, "specifiers");
- if (standalones.length > 0) {
- parts.push(join$2(", ", standalones));
- }
- if (standalones.length > 0 && grouped.length > 0) {
- parts.push(", ");
- }
- if (grouped.length === 1 && standalones.length === 0 && n.specifiers && !n.specifiers.some(function (node) {
- return node.comments;
- })) {
- parts.push(concat$4(["{", options.bracketSpacing ? " " : "", concat$4(grouped), options.bracketSpacing ? " " : "", "}"]));
- } else if (grouped.length >= 1) {
- parts.push(group$1(concat$4(["{", indent$2(concat$4([options.bracketSpacing ? line$3 : softline$1, join$2(concat$4([",", line$3]), grouped)])), ifBreak$1(shouldPrintComma(options) ? "," : ""), options.bracketSpacing ? line$3 : softline$1, "}"])));
- }
- parts.push(" from ");
- } else if (n.importKind && n.importKind === "type" || // import {} from 'x'
- /{\s*}/.test(options.originalText.slice(options.locStart(n), options.locStart(n.source)))) {
- parts.push("{} from ");
- }
- parts.push(path$$1.call(print, "source"), semi);
- return concat$4(parts);
- }
- case "Import":
- return "import";
- case "TSModuleBlock":
- case "BlockStatement":
- {
- var naked = path$$1.call(function (bodyPath) {
- return printStatementSequence(bodyPath, options, print);
- }, "body");
- var hasContent = n.body.find(function (node) {
- return node.type !== "EmptyStatement";
- });
- var hasDirectives = n.directives && n.directives.length > 0;
- var _parent3 = path$$1.getParentNode();
- var _parentParent = path$$1.getParentNode(1);
- if (!hasContent && !hasDirectives && !hasDanglingComments(n) && (_parent3.type === "ArrowFunctionExpression" || _parent3.type === "FunctionExpression" || _parent3.type === "FunctionDeclaration" || _parent3.type === "ObjectMethod" || _parent3.type === "ClassMethod" || _parent3.type === "ClassPrivateMethod" || _parent3.type === "ForStatement" || _parent3.type === "WhileStatement" || _parent3.type === "DoWhileStatement" || _parent3.type === "DoExpression" || _parent3.type === "CatchClause" && !_parentParent.finalizer || _parent3.type === "TSModuleDeclaration")) {
- return "{}";
- }
- parts.push("{"); // Babel 6
- if (hasDirectives) {
- path$$1.each(function (childPath) {
- parts.push(indent$2(concat$4([hardline$3, print(childPath), semi])));
- if (isNextLineEmpty$2(options.originalText, childPath.getValue(), options)) {
- parts.push(hardline$3);
- }
- }, "directives");
- }
- if (hasContent) {
- parts.push(indent$2(concat$4([hardline$3, naked])));
- }
- parts.push(comments.printDanglingComments(path$$1, options));
- parts.push(hardline$3, "}");
- return concat$4(parts);
- }
- case "ReturnStatement":
- parts.push("return");
- if (n.argument) {
- if (returnArgumentHasLeadingComment(options, n.argument)) {
- parts.push(concat$4([" (", indent$2(concat$4([hardline$3, path$$1.call(print, "argument")])), hardline$3, ")"]));
- } else if (n.argument.type === "LogicalExpression" || n.argument.type === "BinaryExpression" || n.argument.type === "SequenceExpression") {
- parts.push(group$1(concat$4([ifBreak$1(" (", " "), indent$2(concat$4([softline$1, path$$1.call(print, "argument")])), softline$1, ifBreak$1(")")])));
- } else {
- parts.push(" ", path$$1.call(print, "argument"));
- }
- }
- if (hasDanglingComments(n)) {
- parts.push(" ", comments.printDanglingComments(path$$1, options,
- /* sameIndent */
- true));
- }
- parts.push(semi);
- return concat$4(parts);
- case "NewExpression":
- case "OptionalCallExpression":
- case "CallExpression":
- {
- var isNew = n.type === "NewExpression";
- var optional = printOptionalToken(path$$1);
- if ( // We want to keep CommonJS- and AMD-style require calls, and AMD-style
- // define calls, as a unit.
- // e.g. `define(["some/lib", (lib) => {`
- !isNew && n.callee.type === "Identifier" && (n.callee.name === "require" || n.callee.name === "define") || n.callee.type === "Import" || // Template literals as single arguments
- n.arguments.length === 1 && isTemplateOnItsOwnLine(n.arguments[0], options.originalText, options) || // Keep test declarations on a single line
- // e.g. `it('long name', () => {`
- !isNew && isTestCall(n, path$$1.getParentNode())) {
- return concat$4([isNew ? "new " : "", path$$1.call(print, "callee"), optional, printFunctionTypeParameters(path$$1, options, print), concat$4(["(", join$2(", ", path$$1.map(print, "arguments")), ")"])]);
- } // Inline Flow annotation comments following Identifiers in Call nodes need to
- // stay with the Identifier. For example:
- //
- // foo /*:: <SomeGeneric> */(bar);
- //
- // Here, we ensure that such comments stay between the Identifier and the Callee.
- var isIdentifierWithFlowAnnotation = n.callee.type === "Identifier" && hasFlowAnnotationComment(n.callee.trailingComments);
- if (isIdentifierWithFlowAnnotation) {
- n.callee.trailingComments[0].printed = true;
- } // We detect calls on member lookups and possibly print them in a
- // special chain format. See `printMemberChain` for more info.
- if (!isNew && isMemberish(n.callee)) {
- return printMemberChain(path$$1, options, print);
- }
- return concat$4([isNew ? "new " : "", path$$1.call(print, "callee"), optional, isIdentifierWithFlowAnnotation ? `/*:: ${n.callee.trailingComments[0].value.substring(2).trim()} */` : "", printFunctionTypeParameters(path$$1, options, print), printArgumentsList(path$$1, options, print)]);
- }
- case "TSInterfaceDeclaration":
- if (isNodeStartingWithDeclare(n, options)) {
- parts.push("declare ");
- }
- parts.push(n.abstract ? "abstract " : "", printTypeScriptModifiers(path$$1, options, print), "interface ", path$$1.call(print, "id"), n.typeParameters ? path$$1.call(print, "typeParameters") : "", " ");
- if (n.extends && n.extends.length) {
- parts.push(group$1(indent$2(concat$4([softline$1, "extends ", (n.extends.length === 1 ? identity$1 : indent$2)(join$2(concat$4([",", line$3]), path$$1.map(print, "extends"))), " "]))));
- }
- parts.push(path$$1.call(print, "body"));
- return concat$4(parts);
- case "ObjectTypeInternalSlot":
- return concat$4([n.static ? "static " : "", "[[", path$$1.call(print, "id"), "]]", printOptionalToken(path$$1), n.method ? "" : ": ", path$$1.call(print, "value")]);
- case "ObjectExpression":
- case "ObjectPattern":
- case "ObjectTypeAnnotation":
- case "TSInterfaceBody":
- case "TSTypeLiteral":
- {
- var propertiesField;
- if (n.type === "TSTypeLiteral") {
- propertiesField = "members";
- } else if (n.type === "TSInterfaceBody") {
- propertiesField = "body";
- } else {
- propertiesField = "properties";
- }
- var isTypeAnnotation = n.type === "ObjectTypeAnnotation";
- var fields = [];
- if (isTypeAnnotation) {
- fields.push("indexers", "callProperties", "internalSlots");
- }
- fields.push(propertiesField);
- var firstProperty = fields.map(function (field) {
- return n[field][0];
- }).sort(function (a, b) {
- return options.locStart(a) - options.locStart(b);
- })[0];
- var _parent4 = path$$1.getParentNode(0);
- var isFlowInterfaceLikeBody = isTypeAnnotation && _parent4 && (_parent4.type === "InterfaceDeclaration" || _parent4.type === "DeclareInterface" || _parent4.type === "DeclareClass") && path$$1.getName() === "body";
- var shouldBreak = n.type === "TSInterfaceBody" || isFlowInterfaceLikeBody || n.type === "ObjectPattern" && _parent4.type !== "FunctionDeclaration" && _parent4.type !== "FunctionExpression" && _parent4.type !== "ArrowFunctionExpression" && _parent4.type !== "AssignmentPattern" && _parent4.type !== "CatchClause" && n.properties.some(function (property) {
- return property.value && (property.value.type === "ObjectPattern" || property.value.type === "ArrayPattern");
- }) || n.type !== "ObjectPattern" && firstProperty && hasNewlineInRange$1(options.originalText, options.locStart(n), options.locStart(firstProperty));
- var separator = isFlowInterfaceLikeBody ? ";" : n.type === "TSInterfaceBody" || n.type === "TSTypeLiteral" ? ifBreak$1(semi, ";") : ",";
- var leftBrace = n.exact ? "{|" : "{";
- var rightBrace = n.exact ? "|}" : "}"; // Unfortunately, things are grouped together in the ast can be
- // interleaved in the source code. So we need to reorder them before
- // printing them.
- var propsAndLoc = [];
- fields.forEach(function (field) {
- path$$1.each(function (childPath) {
- var node = childPath.getValue();
- propsAndLoc.push({
- node: node,
- printed: print(childPath),
- loc: options.locStart(node)
- });
- }, field);
- });
- var separatorParts = [];
- var props = propsAndLoc.sort(function (a, b) {
- return a.loc - b.loc;
- }).map(function (prop) {
- var result = concat$4(separatorParts.concat(group$1(prop.printed)));
- separatorParts = [separator, line$3];
- if ((prop.node.type === "TSPropertySignature" || prop.node.type === "TSMethodSignature" || prop.node.type === "TSConstructSignatureDeclaration") && hasNodeIgnoreComment$1(prop.node)) {
- separatorParts.shift();
- }
- if (isNextLineEmpty$2(options.originalText, prop.node, options)) {
- separatorParts.push(hardline$3);
- }
- return result;
- });
- if (n.inexact) {
- props.push(concat$4(separatorParts.concat(group$1("..."))));
- }
- var lastElem = getLast$4(n[propertiesField]);
- var canHaveTrailingSeparator = !(lastElem && (lastElem.type === "RestProperty" || lastElem.type === "RestElement" || hasNodeIgnoreComment$1(lastElem) || n.inexact));
- var content;
- if (props.length === 0 && !n.typeAnnotation) {
- if (!hasDanglingComments(n)) {
- return concat$4([leftBrace, rightBrace]);
- }
- content = group$1(concat$4([leftBrace, comments.printDanglingComments(path$$1, options), softline$1, rightBrace, printOptionalToken(path$$1)]));
- } else {
- content = concat$4([leftBrace, indent$2(concat$4([options.bracketSpacing ? line$3 : softline$1, concat$4(props)])), ifBreak$1(canHaveTrailingSeparator && (separator !== "," || shouldPrintComma(options)) ? separator : ""), concat$4([options.bracketSpacing ? line$3 : softline$1, rightBrace]), printOptionalToken(path$$1), printTypeAnnotation(path$$1, options, print)]);
- } // If we inline the object as first argument of the parent, we don't want
- // to create another group so that the object breaks before the return
- // type
- var parentParentParent = path$$1.getParentNode(2);
- if (n.type === "ObjectPattern" && _parent4 && shouldHugArguments(_parent4) && _parent4.params[0] === n || shouldHugType(n) && parentParentParent && shouldHugArguments(parentParentParent) && parentParentParent.params[0].typeAnnotation && parentParentParent.params[0].typeAnnotation.typeAnnotation === n) {
- return content;
- }
- return group$1(content, {
- shouldBreak
- });
- }
- // Babel 6
- case "ObjectProperty": // Non-standard AST node type.
- case "Property":
- if (n.method || n.kind === "get" || n.kind === "set") {
- return printMethod(path$$1, options, print);
- }
- if (n.shorthand) {
- parts.push(path$$1.call(print, "value"));
- } else {
- var printedLeft;
- if (n.computed) {
- printedLeft = concat$4(["[", path$$1.call(print, "key"), "]"]);
- } else {
- printedLeft = printPropertyKey(path$$1, options, print);
- }
- parts.push(printAssignment(n.key, printedLeft, ":", n.value, path$$1.call(print, "value"), options));
- }
- return concat$4(parts);
- // Babel 6
- case "ClassMethod":
- case "ClassPrivateMethod":
- if (n.decorators && n.decorators.length !== 0) {
- parts.push(printDecorators(path$$1, options, print));
- }
- if (n.static) {
- parts.push("static ");
- }
- parts = parts.concat(printObjectMethod(path$$1, options, print));
- return concat$4(parts);
- // Babel 6
- case "ObjectMethod":
- return printObjectMethod(path$$1, options, print);
- case "Decorator":
- return concat$4(["@", path$$1.call(print, "expression"), path$$1.call(print, "callee")]);
- case "ArrayExpression":
- case "ArrayPattern":
- if (n.elements.length === 0) {
- if (!hasDanglingComments(n)) {
- parts.push("[]");
- } else {
- parts.push(group$1(concat$4(["[", comments.printDanglingComments(path$$1, options), softline$1, "]"])));
- }
- } else {
- var _lastElem = getLast$4(n.elements);
- var canHaveTrailingComma = !(_lastElem && _lastElem.type === "RestElement"); // JavaScript allows you to have empty elements in an array which
- // changes its length based on the number of commas. The algorithm
- // is that if the last argument is null, we need to force insert
- // a comma to ensure JavaScript recognizes it.
- // [,].length === 1
- // [1,].length === 1
- // [1,,].length === 2
- //
- // Note that getLast returns null if the array is empty, but
- // we already check for an empty array just above so we are safe
- var needsForcedTrailingComma = canHaveTrailingComma && _lastElem === null;
- parts.push(group$1(concat$4(["[", indent$2(concat$4([softline$1, printArrayItems(path$$1, options, "elements", print)])), needsForcedTrailingComma ? "," : "", ifBreak$1(canHaveTrailingComma && !needsForcedTrailingComma && shouldPrintComma(options) ? "," : ""), comments.printDanglingComments(path$$1, options,
- /* sameIndent */
- true), softline$1, "]"])));
- }
- parts.push(printOptionalToken(path$$1), printTypeAnnotation(path$$1, options, print));
- return concat$4(parts);
- case "SequenceExpression":
- {
- var _parent5 = path$$1.getParentNode(0);
- if (_parent5.type === "ExpressionStatement" || _parent5.type === "ForStatement") {
- // For ExpressionStatements and for-loop heads, which are among
- // the few places a SequenceExpression appears unparenthesized, we want
- // to indent expressions after the first.
- var _parts2 = [];
- path$$1.each(function (p) {
- if (p.getName() === 0) {
- _parts2.push(print(p));
- } else {
- _parts2.push(",", indent$2(concat$4([line$3, print(p)])));
- }
- }, "expressions");
- return group$1(concat$4(_parts2));
- }
- return group$1(concat$4([join$2(concat$4([",", line$3]), path$$1.map(print, "expressions"))]));
- }
- case "ThisExpression":
- return "this";
- case "Super":
- return "super";
- case "NullLiteral":
- // Babel 6 Literal split
- return "null";
- case "RegExpLiteral":
- // Babel 6 Literal split
- return printRegex(n);
- case "NumericLiteral":
- // Babel 6 Literal split
- return printNumber$1(n.extra.raw);
- case "BigIntLiteral":
- return concat$4([printNumber$1(n.extra ? n.extra.rawValue : // TypeScript
- n.value), "n"]);
- case "BooleanLiteral": // Babel 6 Literal split
- case "StringLiteral": // Babel 6 Literal split
- case "Literal":
- {
- if (n.regex) {
- return printRegex(n.regex);
- }
- if (typeof n.value === "number") {
- return printNumber$1(n.raw);
- }
- if (typeof n.value !== "string") {
- return "" + n.value;
- } // TypeScript workaround for https://github.com/JamesHenry/typescript-estree/issues/2
- // See corresponding workaround in needs-parens.js
- var grandParent = path$$1.getParentNode(1);
- var isTypeScriptDirective = options.parser === "typescript" && typeof n.value === "string" && grandParent && (grandParent.type === "Program" || grandParent.type === "BlockStatement");
- return nodeStr(n, options, isTypeScriptDirective);
- }
- case "Directive":
- return path$$1.call(print, "value");
- // Babel 6
- case "DirectiveLiteral":
- return nodeStr(n, options);
- case "UnaryExpression":
- parts.push(n.operator);
- if (/[a-z]$/.test(n.operator)) {
- parts.push(" ");
- }
- parts.push(path$$1.call(print, "argument"));
- return concat$4(parts);
- case "UpdateExpression":
- parts.push(path$$1.call(print, "argument"), n.operator);
- if (n.prefix) {
- parts.reverse();
- }
- return concat$4(parts);
- case "ConditionalExpression":
- return printTernaryOperator(path$$1, options, print, {
- beforeParts: function beforeParts() {
- return [path$$1.call(print, "test")];
- },
- afterParts: function afterParts(breakClosingParen) {
- return [breakClosingParen ? softline$1 : ""];
- },
- shouldCheckJsx: true,
- conditionalNodeType: "ConditionalExpression",
- consequentNodePropertyName: "consequent",
- alternateNodePropertyName: "alternate",
- testNodePropertyName: "test",
- breakNested: true
- });
- case "VariableDeclaration":
- {
- var printed = path$$1.map(function (childPath) {
- return print(childPath);
- }, "declarations"); // We generally want to terminate all variable declarations with a
- // semicolon, except when they in the () part of for loops.
- var parentNode = path$$1.getParentNode();
- var isParentForLoop = parentNode.type === "ForStatement" || parentNode.type === "ForInStatement" || parentNode.type === "ForOfStatement" || parentNode.type === "ForAwaitStatement";
- var hasValue = n.declarations.some(function (decl) {
- return decl.init;
- });
- var firstVariable;
- if (printed.length === 1 && !n.declarations[0].comments) {
- firstVariable = printed[0];
- } else if (printed.length > 0) {
- // Indent first var to comply with eslint one-var rule
- firstVariable = indent$2(printed[0]);
- }
- parts = [isNodeStartingWithDeclare(n, options) ? "declare " : "", n.kind, firstVariable ? concat$4([" ", firstVariable]) : "", indent$2(concat$4(printed.slice(1).map(function (p) {
- return concat$4([",", hasValue && !isParentForLoop ? hardline$3 : line$3, p]);
- })))];
- if (!(isParentForLoop && parentNode.body !== n)) {
- parts.push(semi);
- }
- return group$1(concat$4(parts));
- }
- case "TSTypeAliasDeclaration":
- {
- if (n.declare) {
- parts.push("declare ");
- }
- var _printed = printAssignmentRight(n.id, n.typeAnnotation, n.typeAnnotation && path$$1.call(print, "typeAnnotation"), options);
- parts.push("type ", path$$1.call(print, "id"), path$$1.call(print, "typeParameters"), " =", _printed, semi);
- return group$1(concat$4(parts));
- }
- case "VariableDeclarator":
- return printAssignment(n.id, path$$1.call(print, "id"), " =", n.init, n.init && path$$1.call(print, "init"), options);
- case "WithStatement":
- return group$1(concat$4(["with (", path$$1.call(print, "object"), ")", adjustClause(n.body, path$$1.call(print, "body"))]));
- case "IfStatement":
- {
- var con = adjustClause(n.consequent, path$$1.call(print, "consequent"));
- var opening = group$1(concat$4(["if (", group$1(concat$4([indent$2(concat$4([softline$1, path$$1.call(print, "test")])), softline$1])), ")", con]));
- parts.push(opening);
- if (n.alternate) {
- var commentOnOwnLine = hasTrailingComment(n.consequent) && n.consequent.comments.some(function (comment) {
- return comment.trailing && !comments$3.isBlockComment(comment);
- }) || needsHardlineAfterDanglingComment(n);
- var elseOnSameLine = n.consequent.type === "BlockStatement" && !commentOnOwnLine;
- parts.push(elseOnSameLine ? " " : hardline$3);
- if (hasDanglingComments(n)) {
- parts.push(comments.printDanglingComments(path$$1, options, true), commentOnOwnLine ? hardline$3 : " ");
- }
- parts.push("else", group$1(adjustClause(n.alternate, path$$1.call(print, "alternate"), n.alternate.type === "IfStatement")));
- }
- return concat$4(parts);
- }
- case "ForStatement":
- {
- var _body = adjustClause(n.body, path$$1.call(print, "body")); // We want to keep dangling comments above the loop to stay consistent.
- // Any comment positioned between the for statement and the parentheses
- // is going to be printed before the statement.
- var _dangling = comments.printDanglingComments(path$$1, options,
- /* sameLine */
- true);
- var printedComments = _dangling ? concat$4([_dangling, softline$1]) : "";
- if (!n.init && !n.test && !n.update) {
- return concat$4([printedComments, group$1(concat$4(["for (;;)", _body]))]);
- }
- return concat$4([printedComments, group$1(concat$4(["for (", group$1(concat$4([indent$2(concat$4([softline$1, path$$1.call(print, "init"), ";", line$3, path$$1.call(print, "test"), ";", line$3, path$$1.call(print, "update")])), softline$1])), ")", _body]))]);
- }
- case "WhileStatement":
- return group$1(concat$4(["while (", group$1(concat$4([indent$2(concat$4([softline$1, path$$1.call(print, "test")])), softline$1])), ")", adjustClause(n.body, path$$1.call(print, "body"))]));
- case "ForInStatement":
- // Note: esprima can't actually parse "for each (".
- return group$1(concat$4([n.each ? "for each (" : "for (", path$$1.call(print, "left"), " in ", path$$1.call(print, "right"), ")", adjustClause(n.body, path$$1.call(print, "body"))]));
- case "ForOfStatement":
- case "ForAwaitStatement":
- {
- // Babel 7 removed ForAwaitStatement in favor of ForOfStatement
- // with `"await": true`:
- // https://github.com/estree/estree/pull/138
- var isAwait = n.type === "ForAwaitStatement" || n.await;
- return group$1(concat$4(["for", isAwait ? " await" : "", " (", path$$1.call(print, "left"), " of ", path$$1.call(print, "right"), ")", adjustClause(n.body, path$$1.call(print, "body"))]));
- }
- case "DoWhileStatement":
- {
- var clause = adjustClause(n.body, path$$1.call(print, "body"));
- var doBody = group$1(concat$4(["do", clause]));
- parts = [doBody];
- if (n.body.type === "BlockStatement") {
- parts.push(" ");
- } else {
- parts.push(hardline$3);
- }
- parts.push("while (");
- parts.push(group$1(concat$4([indent$2(concat$4([softline$1, path$$1.call(print, "test")])), softline$1])), ")", semi);
- return concat$4(parts);
- }
- case "DoExpression":
- return concat$4(["do ", path$$1.call(print, "body")]);
- case "BreakStatement":
- parts.push("break");
- if (n.label) {
- parts.push(" ", path$$1.call(print, "label"));
- }
- parts.push(semi);
- return concat$4(parts);
- case "ContinueStatement":
- parts.push("continue");
- if (n.label) {
- parts.push(" ", path$$1.call(print, "label"));
- }
- parts.push(semi);
- return concat$4(parts);
- case "LabeledStatement":
- if (n.body.type === "EmptyStatement") {
- return concat$4([path$$1.call(print, "label"), ":;"]);
- }
- return concat$4([path$$1.call(print, "label"), ": ", path$$1.call(print, "body")]);
- case "TryStatement":
- return concat$4(["try ", path$$1.call(print, "block"), n.handler ? concat$4([" ", path$$1.call(print, "handler")]) : "", n.finalizer ? concat$4([" finally ", path$$1.call(print, "finalizer")]) : ""]);
- case "CatchClause":
- if (n.param) {
- var hasComments = n.param.comments && n.param.comments.some(function (comment) {
- return !comments$3.isBlockComment(comment) || comment.leading && hasNewline$2(options.originalText, options.locEnd(comment)) || comment.trailing && hasNewline$2(options.originalText, options.locStart(comment), {
- backwards: true
- });
- });
- var param = path$$1.call(print, "param");
- return concat$4(["catch ", hasComments ? concat$4(["(", indent$2(concat$4([softline$1, param])), softline$1, ") "]) : concat$4(["(", param, ") "]), path$$1.call(print, "body")]);
- }
- return concat$4(["catch ", path$$1.call(print, "body")]);
- case "ThrowStatement":
- return concat$4(["throw ", path$$1.call(print, "argument"), semi]);
- // Note: ignoring n.lexical because it has no printing consequences.
- case "SwitchStatement":
- return concat$4([group$1(concat$4(["switch (", indent$2(concat$4([softline$1, path$$1.call(print, "discriminant")])), softline$1, ")"])), " {", n.cases.length > 0 ? indent$2(concat$4([hardline$3, join$2(hardline$3, path$$1.map(function (casePath) {
- var caseNode = casePath.getValue();
- return concat$4([casePath.call(print), n.cases.indexOf(caseNode) !== n.cases.length - 1 && isNextLineEmpty$2(options.originalText, caseNode, options) ? hardline$3 : ""]);
- }, "cases"))])) : "", hardline$3, "}"]);
- case "SwitchCase":
- {
- if (n.test) {
- parts.push("case ", path$$1.call(print, "test"), ":");
- } else {
- parts.push("default:");
- }
- var consequent = n.consequent.filter(function (node) {
- return node.type !== "EmptyStatement";
- });
- if (consequent.length > 0) {
- var cons = path$$1.call(function (consequentPath) {
- return printStatementSequence(consequentPath, options, print);
- }, "consequent");
- parts.push(consequent.length === 1 && consequent[0].type === "BlockStatement" ? concat$4([" ", cons]) : indent$2(concat$4([hardline$3, cons])));
- }
- return concat$4(parts);
- }
- // JSX extensions below.
- case "DebuggerStatement":
- return concat$4(["debugger", semi]);
- case "JSXAttribute":
- parts.push(path$$1.call(print, "name"));
- if (n.value) {
- var res;
- if (isStringLiteral(n.value)) {
- var raw = rawText(n.value); // Unescape all quotes so we get an accurate preferred quote
- var final = raw.replace(/'/g, "'").replace(/"/g, '"');
- var quote = getPreferredQuote$1(final, options.jsxSingleQuote ? "'" : '"');
- var _escape = quote === "'" ? "'" : """;
- final = final.slice(1, -1).replace(new RegExp(quote, "g"), _escape);
- res = concat$4([quote, final, quote]);
- } else {
- res = path$$1.call(print, "value");
- }
- parts.push("=", res);
- }
- return concat$4(parts);
- case "JSXIdentifier":
- return "" + n.name;
- case "JSXNamespacedName":
- return join$2(":", [path$$1.call(print, "namespace"), path$$1.call(print, "name")]);
- case "JSXMemberExpression":
- return join$2(".", [path$$1.call(print, "object"), path$$1.call(print, "property")]);
- case "TSQualifiedName":
- return join$2(".", [path$$1.call(print, "left"), path$$1.call(print, "right")]);
- case "JSXSpreadAttribute":
- case "JSXSpreadChild":
- {
- return concat$4(["{", path$$1.call(function (p) {
- var printed = concat$4(["...", print(p)]);
- var n = p.getValue();
- if (!n.comments || !n.comments.length) {
- return printed;
- }
- return concat$4([indent$2(concat$4([softline$1, comments.printComments(p, function () {
- return printed;
- }, options)])), softline$1]);
- }, n.type === "JSXSpreadAttribute" ? "argument" : "expression"), "}"]);
- }
- case "JSXExpressionContainer":
- {
- var _parent6 = path$$1.getParentNode(0);
- var preventInline = _parent6.type === "JSXAttribute" && n.expression.comments && n.expression.comments.length > 0;
- var _shouldInline = !preventInline && (n.expression.type === "ArrayExpression" || n.expression.type === "ObjectExpression" || n.expression.type === "ArrowFunctionExpression" || n.expression.type === "CallExpression" || n.expression.type === "OptionalCallExpression" || n.expression.type === "FunctionExpression" || n.expression.type === "JSXEmptyExpression" || n.expression.type === "TemplateLiteral" || n.expression.type === "TaggedTemplateExpression" || n.expression.type === "DoExpression" || isJSXNode(_parent6) && (n.expression.type === "ConditionalExpression" || isBinaryish(n.expression)));
- if (_shouldInline) {
- return group$1(concat$4(["{", path$$1.call(print, "expression"), lineSuffixBoundary$1, "}"]));
- }
- return group$1(concat$4(["{", indent$2(concat$4([softline$1, path$$1.call(print, "expression")])), softline$1, lineSuffixBoundary$1, "}"]));
- }
- case "JSXFragment":
- case "JSXElement":
- {
- var elem = comments.printComments(path$$1, function () {
- return printJSXElement(path$$1, options, print);
- }, options);
- return maybeWrapJSXElementInParens(path$$1, elem);
- }
- case "JSXOpeningElement":
- {
- var _n = path$$1.getValue();
- var nameHasComments = _n.name && _n.name.comments && _n.name.comments.length > 0; // Don't break self-closing elements with no attributes and no comments
- if (_n.selfClosing && !_n.attributes.length && !nameHasComments) {
- return concat$4(["<", path$$1.call(print, "name"), path$$1.call(print, "typeParameters"), " />"]);
- } // don't break up opening elements with a single long text attribute
- if (_n.attributes && _n.attributes.length === 1 && _n.attributes[0].value && isStringLiteral(_n.attributes[0].value) && !_n.attributes[0].value.value.includes("\n") && // We should break for the following cases:
- // <div
- // // comment
- // attr="value"
- // >
- // <div
- // attr="value"
- // // comment
- // >
- !nameHasComments && (!_n.attributes[0].comments || !_n.attributes[0].comments.length)) {
- return group$1(concat$4(["<", path$$1.call(print, "name"), path$$1.call(print, "typeParameters"), " ", concat$4(path$$1.map(print, "attributes")), _n.selfClosing ? " />" : ">"]));
- }
- var lastAttrHasTrailingComments = _n.attributes.length && hasTrailingComment(getLast$4(_n.attributes));
- var bracketSameLine = // Simple tags (no attributes and no comment in tag name) should be
- // kept unbroken regardless of `jsxBracketSameLine`
- !_n.attributes.length && !nameHasComments || options.jsxBracketSameLine && ( // We should print the bracket in a new line for the following cases:
- // <div
- // // comment
- // >
- // <div
- // attr // comment
- // >
- !nameHasComments || _n.attributes.length) && !lastAttrHasTrailingComments; // We should print the opening element expanded if any prop value is a
- // string literal with newlines
- var _shouldBreak = _n.attributes && _n.attributes.some(function (attr) {
- return attr.value && isStringLiteral(attr.value) && attr.value.value.includes("\n");
- });
- return group$1(concat$4(["<", path$$1.call(print, "name"), path$$1.call(print, "typeParameters"), concat$4([indent$2(concat$4(path$$1.map(function (attr) {
- return concat$4([line$3, print(attr)]);
- }, "attributes"))), _n.selfClosing ? line$3 : bracketSameLine ? ">" : softline$1]), _n.selfClosing ? "/>" : bracketSameLine ? "" : ">"]), {
- shouldBreak: _shouldBreak
- });
- }
- case "JSXClosingElement":
- return concat$4(["</", path$$1.call(print, "name"), ">"]);
- case "JSXOpeningFragment":
- case "JSXClosingFragment":
- {
- var hasComment = n.comments && n.comments.length;
- var hasOwnLineComment = hasComment && !n.comments.every(comments$3.isBlockComment);
- var isOpeningFragment = n.type === "JSXOpeningFragment";
- return concat$4([isOpeningFragment ? "<" : "</", indent$2(concat$4([hasOwnLineComment ? hardline$3 : hasComment && !isOpeningFragment ? " " : "", comments.printDanglingComments(path$$1, options, true)])), hasOwnLineComment ? hardline$3 : "", ">"]);
- }
- case "JSXText":
- /* istanbul ignore next */
- throw new Error("JSXTest should be handled by JSXElement");
- case "JSXEmptyExpression":
- {
- var requiresHardline = n.comments && !n.comments.every(comments$3.isBlockComment);
- return concat$4([comments.printDanglingComments(path$$1, options,
- /* sameIndent */
- !requiresHardline), requiresHardline ? hardline$3 : ""]);
- }
- case "ClassBody":
- if (!n.comments && n.body.length === 0) {
- return "{}";
- }
- return concat$4(["{", n.body.length > 0 ? indent$2(concat$4([hardline$3, path$$1.call(function (bodyPath) {
- return printStatementSequence(bodyPath, options, print);
- }, "body")])) : comments.printDanglingComments(path$$1, options), hardline$3, "}"]);
- case "ClassProperty":
- case "TSAbstractClassProperty":
- case "ClassPrivateProperty":
- {
- if (n.decorators && n.decorators.length !== 0) {
- parts.push(printDecorators(path$$1, options, print));
- }
- if (n.accessibility) {
- parts.push(n.accessibility + " ");
- }
- if (n.static) {
- parts.push("static ");
- }
- if (n.type === "TSAbstractClassProperty") {
- parts.push("abstract ");
- }
- if (n.readonly) {
- parts.push("readonly ");
- }
- var variance = getFlowVariance(n);
- if (variance) {
- parts.push(variance);
- }
- if (n.computed) {
- parts.push("[", path$$1.call(print, "key"), "]");
- } else {
- parts.push(printPropertyKey(path$$1, options, print));
- }
- parts.push(printOptionalToken(path$$1));
- parts.push(printTypeAnnotation(path$$1, options, print));
- if (n.value) {
- parts.push(" =", printAssignmentRight(n.key, n.value, path$$1.call(print, "value"), options));
- }
- parts.push(semi);
- return group$1(concat$4(parts));
- }
- case "ClassDeclaration":
- case "ClassExpression":
- case "TSAbstractClassDeclaration":
- if (isNodeStartingWithDeclare(n, options)) {
- parts.push("declare ");
- }
- parts.push(concat$4(printClass(path$$1, options, print)));
- return concat$4(parts);
- case "TSInterfaceHeritage":
- parts.push(path$$1.call(print, "expression"));
- if (n.typeParameters) {
- parts.push(path$$1.call(print, "typeParameters"));
- }
- return concat$4(parts);
- case "TemplateElement":
- return join$2(literalline$1, n.value.raw.split(/\r?\n/g));
- case "TemplateLiteral":
- {
- var expressions = path$$1.map(print, "expressions");
- var _parentNode = path$$1.getParentNode();
- /**
- * describe.each`table`(name, fn)
- * describe.only.each`table`(name, fn)
- * describe.skip.each`table`(name, fn)
- * test.each`table`(name, fn)
- * test.only.each`table`(name, fn)
- * test.skip.each`table`(name, fn)
- *
- * Ref: https://github.com/facebook/jest/pull/6102
- */
- var jestEachTriggerRegex = /^[xf]?(describe|it|test)$/;
- if (_parentNode.type === "TaggedTemplateExpression" && _parentNode.quasi === n && _parentNode.tag.type === "MemberExpression" && _parentNode.tag.property.type === "Identifier" && _parentNode.tag.property.name === "each" && (_parentNode.tag.object.type === "Identifier" && jestEachTriggerRegex.test(_parentNode.tag.object.name) || _parentNode.tag.object.type === "MemberExpression" && _parentNode.tag.object.property.type === "Identifier" && (_parentNode.tag.object.property.name === "only" || _parentNode.tag.object.property.name === "skip") && _parentNode.tag.object.object.type === "Identifier" && jestEachTriggerRegex.test(_parentNode.tag.object.object.name))) {
- /**
- * a | b | expected
- * ${1} | ${1} | ${2}
- * ${1} | ${2} | ${3}
- * ${2} | ${1} | ${3}
- */
- var headerNames = n.quasis[0].value.raw.trim().split(/\s*\|\s*/);
- if (headerNames.length > 1 || headerNames.some(function (headerName) {
- return headerName.length !== 0;
- })) {
- var stringifiedExpressions = expressions.map(function (doc$$2) {
- return "${" + printDocToString$2(doc$$2, Object.assign({}, options, {
- printWidth: Infinity,
- endOfLine: "lf"
- })).formatted + "}";
- });
- var tableBody = [{
- hasLineBreak: false,
- cells: []
- }];
- for (var _i = 1; _i < n.quasis.length; _i++) {
- var row = tableBody[tableBody.length - 1];
- var correspondingExpression = stringifiedExpressions[_i - 1];
- row.cells.push(correspondingExpression);
- if (correspondingExpression.indexOf("\n") !== -1) {
- row.hasLineBreak = true;
- }
- if (n.quasis[_i].value.raw.indexOf("\n") !== -1) {
- tableBody.push({
- hasLineBreak: false,
- cells: []
- });
- }
- }
- var maxColumnCount = tableBody.reduce(function (maxColumnCount, row) {
- return Math.max(maxColumnCount, row.cells.length);
- }, headerNames.length);
- var maxColumnWidths = Array.from(new Array(maxColumnCount), function () {
- return 0;
- });
- var table = [{
- cells: headerNames
- }].concat(tableBody.filter(function (row) {
- return row.cells.length !== 0;
- }));
- table.filter(function (row) {
- return !row.hasLineBreak;
- }).forEach(function (row) {
- row.cells.forEach(function (cell, index) {
- maxColumnWidths[index] = Math.max(maxColumnWidths[index], getStringWidth$2(cell));
- });
- });
- parts.push("`", indent$2(concat$4([hardline$3, join$2(hardline$3, table.map(function (row) {
- return join$2(" | ", row.cells.map(function (cell, index) {
- return row.hasLineBreak ? cell : cell + " ".repeat(maxColumnWidths[index] - getStringWidth$2(cell));
- }));
- }))])), hardline$3, "`");
- return concat$4(parts);
- }
- }
- parts.push("`");
- path$$1.each(function (childPath) {
- var i = childPath.getName();
- parts.push(print(childPath));
- if (i < expressions.length) {
- // For a template literal of the following form:
- // `someQuery {
- // ${call({
- // a,
- // b,
- // })}
- // }`
- // the expression is on its own line (there is a \n in the previous
- // quasi literal), therefore we want to indent the JavaScript
- // expression inside at the beginning of ${ instead of the beginning
- // of the `.
- var tabWidth = options.tabWidth;
- var quasi = childPath.getValue();
- var indentSize = getIndentSize$1(quasi.value.raw, tabWidth);
- var _printed2 = expressions[i];
- if (n.expressions[i].comments && n.expressions[i].comments.length || n.expressions[i].type === "MemberExpression" || n.expressions[i].type === "OptionalMemberExpression" || n.expressions[i].type === "ConditionalExpression") {
- _printed2 = concat$4([indent$2(concat$4([softline$1, _printed2])), softline$1]);
- }
- var aligned = indentSize === 0 && quasi.value.raw.endsWith("\n") ? align$1(-Infinity, _printed2) : addAlignmentToDoc$2(_printed2, indentSize, tabWidth);
- parts.push(group$1(concat$4(["${", aligned, lineSuffixBoundary$1, "}"])));
- }
- }, "quasis");
- parts.push("`");
- return concat$4(parts);
- }
- // These types are unprintable because they serve as abstract
- // supertypes for other (printable) types.
- case "TaggedTemplateExpression":
- return concat$4([path$$1.call(print, "tag"), path$$1.call(print, "typeParameters"), path$$1.call(print, "quasi")]);
- case "Node":
- case "Printable":
- case "SourceLocation":
- case "Position":
- case "Statement":
- case "Function":
- case "Pattern":
- case "Expression":
- case "Declaration":
- case "Specifier":
- case "NamedSpecifier":
- case "Comment":
- case "MemberTypeAnnotation": // Flow
- case "Type":
- /* istanbul ignore next */
- throw new Error("unprintable type: " + JSON.stringify(n.type));
- // Type Annotations for Facebook Flow, typically stripped out or
- // transformed away before printing.
- case "TypeAnnotation":
- case "TSTypeAnnotation":
- if (n.typeAnnotation) {
- return path$$1.call(print, "typeAnnotation");
- }
- /* istanbul ignore next */
- return "";
- case "TSTupleType":
- case "TupleTypeAnnotation":
- {
- var typesField = n.type === "TSTupleType" ? "elementTypes" : "types";
- return group$1(concat$4(["[", indent$2(concat$4([softline$1, printArrayItems(path$$1, options, typesField, print)])), // TypeScript doesn't support trailing commas in tuple types
- n.type === "TSTupleType" ? "" : ifBreak$1(shouldPrintComma(options) ? "," : ""), comments.printDanglingComments(path$$1, options,
- /* sameIndent */
- true), softline$1, "]"]));
- }
- case "ExistsTypeAnnotation":
- return "*";
- case "EmptyTypeAnnotation":
- return "empty";
- case "AnyTypeAnnotation":
- return "any";
- case "MixedTypeAnnotation":
- return "mixed";
- case "ArrayTypeAnnotation":
- return concat$4([path$$1.call(print, "elementType"), "[]"]);
- case "BooleanTypeAnnotation":
- return "boolean";
- case "BooleanLiteralTypeAnnotation":
- return "" + n.value;
- case "DeclareClass":
- return printFlowDeclaration(path$$1, printClass(path$$1, options, print));
- case "TSDeclareFunction":
- // For TypeScript the TSDeclareFunction node shares the AST
- // structure with FunctionDeclaration
- return concat$4([n.declare ? "declare " : "", printFunctionDeclaration(path$$1, print, options), semi]);
- case "DeclareFunction":
- return printFlowDeclaration(path$$1, ["function ", path$$1.call(print, "id"), n.predicate ? " " : "", path$$1.call(print, "predicate"), semi]);
- case "DeclareModule":
- return printFlowDeclaration(path$$1, ["module ", path$$1.call(print, "id"), " ", path$$1.call(print, "body")]);
- case "DeclareModuleExports":
- return printFlowDeclaration(path$$1, ["module.exports", ": ", path$$1.call(print, "typeAnnotation"), semi]);
- case "DeclareVariable":
- return printFlowDeclaration(path$$1, ["var ", path$$1.call(print, "id"), semi]);
- case "DeclareExportAllDeclaration":
- return concat$4(["declare export * from ", path$$1.call(print, "source")]);
- case "DeclareExportDeclaration":
- return concat$4(["declare ", printExportDeclaration(path$$1, options, print)]);
- case "DeclareOpaqueType":
- case "OpaqueType":
- {
- parts.push("opaque type ", path$$1.call(print, "id"), path$$1.call(print, "typeParameters"));
- if (n.supertype) {
- parts.push(": ", path$$1.call(print, "supertype"));
- }
- if (n.impltype) {
- parts.push(" = ", path$$1.call(print, "impltype"));
- }
- parts.push(semi);
- if (n.type === "DeclareOpaqueType") {
- return printFlowDeclaration(path$$1, parts);
- }
- return concat$4(parts);
- }
- case "FunctionTypeAnnotation":
- case "TSFunctionType":
- {
- // FunctionTypeAnnotation is ambiguous:
- // declare function foo(a: B): void; OR
- // var A: (a: B) => void;
- var _parent7 = path$$1.getParentNode(0);
- var _parentParent2 = path$$1.getParentNode(1);
- var _parentParentParent = path$$1.getParentNode(2);
- var isArrowFunctionTypeAnnotation = n.type === "TSFunctionType" || !((_parent7.type === "ObjectTypeProperty" || _parent7.type === "ObjectTypeInternalSlot") && !getFlowVariance(_parent7) && !_parent7.optional && options.locStart(_parent7) === options.locStart(n) || _parent7.type === "ObjectTypeCallProperty" || _parentParentParent && _parentParentParent.type === "DeclareFunction");
- var needsColon = isArrowFunctionTypeAnnotation && (_parent7.type === "TypeAnnotation" || _parent7.type === "TSTypeAnnotation"); // Sadly we can't put it inside of FastPath::needsColon because we are
- // printing ":" as part of the expression and it would put parenthesis
- // around :(
- var needsParens = needsColon && isArrowFunctionTypeAnnotation && (_parent7.type === "TypeAnnotation" || _parent7.type === "TSTypeAnnotation") && _parentParent2.type === "ArrowFunctionExpression";
- if (isObjectTypePropertyAFunction(_parent7, options)) {
- isArrowFunctionTypeAnnotation = true;
- needsColon = true;
- }
- if (needsParens) {
- parts.push("(");
- }
- parts.push(printFunctionParams(path$$1, print, options,
- /* expandArg */
- false,
- /* printTypeParams */
- true)); // The returnType is not wrapped in a TypeAnnotation, so the colon
- // needs to be added separately.
- if (n.returnType || n.predicate || n.typeAnnotation) {
- parts.push(isArrowFunctionTypeAnnotation ? " => " : ": ", path$$1.call(print, "returnType"), path$$1.call(print, "predicate"), path$$1.call(print, "typeAnnotation"));
- }
- if (needsParens) {
- parts.push(")");
- }
- return group$1(concat$4(parts));
- }
- case "TSRestType":
- return concat$4(["...", path$$1.call(print, "typeAnnotation")]);
- case "TSOptionalType":
- return concat$4([path$$1.call(print, "typeAnnotation"), "?"]);
- case "FunctionTypeParam":
- return concat$4([path$$1.call(print, "name"), printOptionalToken(path$$1), n.name ? ": " : "", path$$1.call(print, "typeAnnotation")]);
- case "GenericTypeAnnotation":
- return concat$4([path$$1.call(print, "id"), path$$1.call(print, "typeParameters")]);
- case "DeclareInterface":
- case "InterfaceDeclaration":
- case "InterfaceTypeAnnotation":
- {
- if (n.type === "DeclareInterface" || isNodeStartingWithDeclare(n, options)) {
- parts.push("declare ");
- }
- parts.push("interface");
- if (n.type === "DeclareInterface" || n.type === "InterfaceDeclaration") {
- parts.push(" ", path$$1.call(print, "id"), path$$1.call(print, "typeParameters"));
- }
- if (n["extends"].length > 0) {
- parts.push(group$1(indent$2(concat$4([line$3, "extends ", (n.extends.length === 1 ? identity$1 : indent$2)(join$2(concat$4([",", line$3]), path$$1.map(print, "extends")))]))));
- }
- parts.push(" ", path$$1.call(print, "body"));
- return group$1(concat$4(parts));
- }
- case "ClassImplements":
- case "InterfaceExtends":
- return concat$4([path$$1.call(print, "id"), path$$1.call(print, "typeParameters")]);
- case "TSClassImplements":
- return concat$4([path$$1.call(print, "expression"), path$$1.call(print, "typeParameters")]);
- case "TSIntersectionType":
- case "IntersectionTypeAnnotation":
- {
- var types = path$$1.map(print, "types");
- var result = [];
- var wasIndented = false;
- for (var _i2 = 0; _i2 < types.length; ++_i2) {
- if (_i2 === 0) {
- result.push(types[_i2]);
- } else if (isObjectType(n.types[_i2 - 1]) && isObjectType(n.types[_i2])) {
- // If both are objects, don't indent
- result.push(concat$4([" & ", wasIndented ? indent$2(types[_i2]) : types[_i2]]));
- } else if (!isObjectType(n.types[_i2 - 1]) && !isObjectType(n.types[_i2])) {
- // If no object is involved, go to the next line if it breaks
- result.push(indent$2(concat$4([" &", line$3, types[_i2]])));
- } else {
- // If you go from object to non-object or vis-versa, then inline it
- if (_i2 > 1) {
- wasIndented = true;
- }
- result.push(" & ", _i2 > 1 ? indent$2(types[_i2]) : types[_i2]);
- }
- }
- return group$1(concat$4(result));
- }
- case "TSUnionType":
- case "UnionTypeAnnotation":
- {
- // single-line variation
- // A | B | C
- // multi-line variation
- // | A
- // | B
- // | C
- var _parent8 = path$$1.getParentNode(); // If there's a leading comment, the parent is doing the indentation
- var shouldIndent = _parent8.type !== "TypeParameterInstantiation" && _parent8.type !== "TSTypeParameterInstantiation" && _parent8.type !== "GenericTypeAnnotation" && _parent8.type !== "TSTypeReference" && _parent8.type !== "TSTypeAssertion" && !(_parent8.type === "FunctionTypeParam" && !_parent8.name) && !((_parent8.type === "TypeAlias" || _parent8.type === "VariableDeclarator" || _parent8.type === "TSTypeAliasDeclaration") && hasLeadingOwnLineComment(options.originalText, n, options)); // {
- // a: string
- // } | null | void
- // should be inlined and not be printed in the multi-line variant
- var shouldHug = shouldHugType(n); // We want to align the children but without its comment, so it looks like
- // | child1
- // // comment
- // | child2
- var _printed3 = path$$1.map(function (typePath) {
- var printedType = typePath.call(print);
- if (!shouldHug) {
- printedType = align$1(2, printedType);
- }
- return comments.printComments(typePath, function () {
- return printedType;
- }, options);
- }, "types");
- if (shouldHug) {
- return join$2(" | ", _printed3);
- }
- var shouldAddStartLine = shouldIndent && !hasLeadingOwnLineComment(options.originalText, n, options);
- var code = concat$4([ifBreak$1(concat$4([shouldAddStartLine ? line$3 : "", "| "])), join$2(concat$4([line$3, "| "]), _printed3)]);
- var hasParens;
- if (n.type === "TSUnionType") {
- var greatGrandParent = path$$1.getParentNode(2);
- var greatGreatGrandParent = path$$1.getParentNode(3);
- hasParens = greatGrandParent && greatGrandParent.type === "TSParenthesizedType" && greatGreatGrandParent && (greatGreatGrandParent.type === "TSUnionType" || greatGreatGrandParent.type === "TSIntersectionType");
- } else {
- hasParens = needsParens_1(path$$1, options);
- }
- if (hasParens) {
- return group$1(concat$4([indent$2(code), softline$1]));
- }
- return group$1(shouldIndent ? indent$2(code) : code);
- }
- case "NullableTypeAnnotation":
- return concat$4(["?", path$$1.call(print, "typeAnnotation")]);
- case "TSNullKeyword":
- case "NullLiteralTypeAnnotation":
- return "null";
- case "ThisTypeAnnotation":
- return "this";
- case "NumberTypeAnnotation":
- return "number";
- case "ObjectTypeCallProperty":
- if (n.static) {
- parts.push("static ");
- }
- parts.push(path$$1.call(print, "value"));
- return concat$4(parts);
- case "ObjectTypeIndexer":
- {
- var _variance = getFlowVariance(n);
- return concat$4([_variance || "", "[", path$$1.call(print, "id"), n.id ? ": " : "", path$$1.call(print, "key"), "]: ", path$$1.call(print, "value")]);
- }
- case "ObjectTypeProperty":
- {
- var _variance2 = getFlowVariance(n);
- var modifier = "";
- if (n.proto) {
- modifier = "proto ";
- } else if (n.static) {
- modifier = "static ";
- }
- return concat$4([modifier, isGetterOrSetter(n) ? n.kind + " " : "", _variance2 || "", printPropertyKey(path$$1, options, print), printOptionalToken(path$$1), isFunctionNotation(n, options) ? "" : ": ", path$$1.call(print, "value")]);
- }
- case "QualifiedTypeIdentifier":
- return concat$4([path$$1.call(print, "qualification"), ".", path$$1.call(print, "id")]);
- case "StringLiteralTypeAnnotation":
- return nodeStr(n, options);
- case "NumberLiteralTypeAnnotation":
- assert.strictEqual(typeof n.value, "number");
- if (n.extra != null) {
- return printNumber$1(n.extra.raw);
- }
- return printNumber$1(n.raw);
- case "StringTypeAnnotation":
- return "string";
- case "DeclareTypeAlias":
- case "TypeAlias":
- {
- if (n.type === "DeclareTypeAlias" || isNodeStartingWithDeclare(n, options)) {
- parts.push("declare ");
- }
- var _printed4 = printAssignmentRight(n.id, n.right, path$$1.call(print, "right"), options);
- parts.push("type ", path$$1.call(print, "id"), path$$1.call(print, "typeParameters"), " =", _printed4, semi);
- return group$1(concat$4(parts));
- }
- case "TypeCastExpression":
- {
- var value = path$$1.getValue(); // Flow supports a comment syntax for specifying type annotations: https://flow.org/en/docs/types/comments/.
- // Unfortunately, its parser doesn't differentiate between comment annotations and regular
- // annotations when producing an AST. So to preserve parentheses around type casts that use
- // the comment syntax, we need to hackily read the source itself to see if the code contains
- // a type annotation comment.
- //
- // Note that we're able to use the normal whitespace regex here because the Flow parser has
- // already deemed this AST node to be a type cast. Only the Babel parser needs the
- // non-line-break whitespace regex, which is why hasFlowShorthandAnnotationComment() is
- // implemented differently.
- var commentSyntax = value && value.typeAnnotation && value.typeAnnotation.range && options.originalText.substring(value.typeAnnotation.range[0]).match(/^\/\*\s*:/);
- return concat$4(["(", path$$1.call(print, "expression"), commentSyntax ? " /*" : "", ": ", path$$1.call(print, "typeAnnotation"), commentSyntax ? " */" : "", ")"]);
- }
- case "TypeParameterDeclaration":
- case "TypeParameterInstantiation":
- {
- var _value = path$$1.getValue();
- var commentStart = _value.range ? options.originalText.substring(0, _value.range[0]).lastIndexOf("/*") : -1; // As noted in the TypeCastExpression comments above, we're able to use a normal whitespace regex here
- // because we know for sure that this is a type definition.
- var _commentSyntax = commentStart >= 0 && options.originalText.substring(commentStart).match(/^\/\*\s*::/);
- if (_commentSyntax) {
- return concat$4(["/*:: ", printTypeParameters(path$$1, options, print, "params"), " */"]);
- }
- return printTypeParameters(path$$1, options, print, "params");
- }
- case "TSTypeParameterDeclaration":
- case "TSTypeParameterInstantiation":
- return printTypeParameters(path$$1, options, print, "params");
- case "TSTypeParameter":
- case "TypeParameter":
- {
- var _parent9 = path$$1.getParentNode();
- if (_parent9.type === "TSMappedType") {
- parts.push("[", path$$1.call(print, "name"));
- if (n.constraint) {
- parts.push(" in ", path$$1.call(print, "constraint"));
- }
- parts.push("]");
- return concat$4(parts);
- }
- var _variance3 = getFlowVariance(n);
- if (_variance3) {
- parts.push(_variance3);
- }
- parts.push(path$$1.call(print, "name"));
- if (n.bound) {
- parts.push(": ");
- parts.push(path$$1.call(print, "bound"));
- }
- if (n.constraint) {
- parts.push(" extends ", path$$1.call(print, "constraint"));
- }
- if (n["default"]) {
- parts.push(" = ", path$$1.call(print, "default"));
- }
- return concat$4(parts);
- }
- case "TypeofTypeAnnotation":
- return concat$4(["typeof ", path$$1.call(print, "argument")]);
- case "VoidTypeAnnotation":
- return "void";
- case "InferredPredicate":
- return "%checks";
- // Unhandled types below. If encountered, nodes of these types should
- // be either left alone or desugared into AST types that are fully
- // supported by the pretty-printer.
- case "DeclaredPredicate":
- return concat$4(["%checks(", path$$1.call(print, "value"), ")"]);
- case "TSAbstractKeyword":
- return "abstract";
- case "TSAnyKeyword":
- return "any";
- case "TSAsyncKeyword":
- return "async";
- case "TSBooleanKeyword":
- return "boolean";
- case "TSBigIntKeyword":
- return "bigint";
- case "TSConstKeyword":
- return "const";
- case "TSDeclareKeyword":
- return "declare";
- case "TSExportKeyword":
- return "export";
- case "TSNeverKeyword":
- return "never";
- case "TSNumberKeyword":
- return "number";
- case "TSObjectKeyword":
- return "object";
- case "TSProtectedKeyword":
- return "protected";
- case "TSPrivateKeyword":
- return "private";
- case "TSPublicKeyword":
- return "public";
- case "TSReadonlyKeyword":
- return "readonly";
- case "TSSymbolKeyword":
- return "symbol";
- case "TSStaticKeyword":
- return "static";
- case "TSStringKeyword":
- return "string";
- case "TSUndefinedKeyword":
- return "undefined";
- case "TSUnknownKeyword":
- return "unknown";
- case "TSVoidKeyword":
- return "void";
- case "TSAsExpression":
- return concat$4([path$$1.call(print, "expression"), " as ", path$$1.call(print, "typeAnnotation")]);
- case "TSArrayType":
- return concat$4([path$$1.call(print, "elementType"), "[]"]);
- case "TSPropertySignature":
- {
- if (n.export) {
- parts.push("export ");
- }
- if (n.accessibility) {
- parts.push(n.accessibility + " ");
- }
- if (n.static) {
- parts.push("static ");
- }
- if (n.readonly) {
- parts.push("readonly ");
- }
- if (n.computed) {
- parts.push("[");
- }
- parts.push(printPropertyKey(path$$1, options, print));
- if (n.computed) {
- parts.push("]");
- }
- parts.push(printOptionalToken(path$$1));
- if (n.typeAnnotation) {
- parts.push(": ");
- parts.push(path$$1.call(print, "typeAnnotation"));
- } // This isn't valid semantically, but it's in the AST so we can print it.
- if (n.initializer) {
- parts.push(" = ", path$$1.call(print, "initializer"));
- }
- return concat$4(parts);
- }
- case "TSParameterProperty":
- if (n.accessibility) {
- parts.push(n.accessibility + " ");
- }
- if (n.export) {
- parts.push("export ");
- }
- if (n.static) {
- parts.push("static ");
- }
- if (n.readonly) {
- parts.push("readonly ");
- }
- parts.push(path$$1.call(print, "parameter"));
- return concat$4(parts);
- case "TSTypeReference":
- return concat$4([path$$1.call(print, "typeName"), printTypeParameters(path$$1, options, print, "typeParameters")]);
- case "TSTypeQuery":
- return concat$4(["typeof ", path$$1.call(print, "exprName")]);
- case "TSParenthesizedType":
- {
- return path$$1.call(print, "typeAnnotation");
- }
- case "TSIndexSignature":
- {
- var _parent10 = path$$1.getParentNode();
- return concat$4([n.export ? "export " : "", n.accessibility ? concat$4([n.accessibility, " "]) : "", n.static ? "static " : "", n.readonly ? "readonly " : "", "[", n.parameters ? concat$4(path$$1.map(print, "parameters")) : "", "]: ", path$$1.call(print, "typeAnnotation"), _parent10.type === "ClassBody" ? semi : ""]);
- }
- case "TSTypePredicate":
- return concat$4([path$$1.call(print, "parameterName"), " is ", path$$1.call(print, "typeAnnotation")]);
- case "TSNonNullExpression":
- return concat$4([path$$1.call(print, "expression"), "!"]);
- case "TSThisType":
- return "this";
- case "TSImportType":
- return concat$4([!n.isTypeOf ? "" : "typeof ", "import(", path$$1.call(print, "parameter"), ")", !n.qualifier ? "" : concat$4([".", path$$1.call(print, "qualifier")]), printTypeParameters(path$$1, options, print, "typeParameters")]);
- case "TSLiteralType":
- return path$$1.call(print, "literal");
- case "TSIndexedAccessType":
- return concat$4([path$$1.call(print, "objectType"), "[", path$$1.call(print, "indexType"), "]"]);
- case "TSConstructSignatureDeclaration":
- case "TSCallSignatureDeclaration":
- case "TSConstructorType":
- {
- if (n.type !== "TSCallSignatureDeclaration") {
- parts.push("new ");
- }
- parts.push(group$1(printFunctionParams(path$$1, print, options,
- /* expandArg */
- false,
- /* printTypeParams */
- true)));
- if (n.returnType) {
- var isType = n.type === "TSConstructorType";
- parts.push(isType ? " => " : ": ", path$$1.call(print, "returnType"));
- }
- return concat$4(parts);
- }
- case "TSTypeOperator":
- return concat$4([n.operator, " ", path$$1.call(print, "typeAnnotation")]);
- case "TSMappedType":
- return group$1(concat$4(["{", indent$2(concat$4([options.bracketSpacing ? line$3 : softline$1, n.readonly ? concat$4([getTypeScriptMappedTypeModifier(n.readonly, "readonly"), " "]) : "", printTypeScriptModifiers(path$$1, options, print), path$$1.call(print, "typeParameter"), n.optional ? getTypeScriptMappedTypeModifier(n.optional, "?") : "", ": ", path$$1.call(print, "typeAnnotation")])), comments.printDanglingComments(path$$1, options,
- /* sameIndent */
- true), options.bracketSpacing ? line$3 : softline$1, "}"]));
- case "TSMethodSignature":
- parts.push(n.accessibility ? concat$4([n.accessibility, " "]) : "", n.export ? "export " : "", n.static ? "static " : "", n.readonly ? "readonly " : "", n.computed ? "[" : "", path$$1.call(print, "key"), n.computed ? "]" : "", printOptionalToken(path$$1), printFunctionParams(path$$1, print, options,
- /* expandArg */
- false,
- /* printTypeParams */
- true));
- if (n.returnType) {
- parts.push(": ", path$$1.call(print, "returnType"));
- }
- return group$1(concat$4(parts));
- case "TSNamespaceExportDeclaration":
- parts.push("export as namespace ", path$$1.call(print, "id"));
- if (options.semi) {
- parts.push(";");
- }
- return group$1(concat$4(parts));
- case "TSEnumDeclaration":
- if (isNodeStartingWithDeclare(n, options)) {
- parts.push("declare ");
- }
- if (n.modifiers) {
- parts.push(printTypeScriptModifiers(path$$1, options, print));
- }
- if (n.const) {
- parts.push("const ");
- }
- parts.push("enum ", path$$1.call(print, "id"), " ");
- if (n.members.length === 0) {
- parts.push(group$1(concat$4(["{", comments.printDanglingComments(path$$1, options), softline$1, "}"])));
- } else {
- parts.push(group$1(concat$4(["{", indent$2(concat$4([hardline$3, printArrayItems(path$$1, options, "members", print), shouldPrintComma(options, "es5") ? "," : ""])), comments.printDanglingComments(path$$1, options,
- /* sameIndent */
- true), hardline$3, "}"])));
- }
- return concat$4(parts);
- case "TSEnumMember":
- parts.push(path$$1.call(print, "id"));
- if (n.initializer) {
- parts.push(" = ", path$$1.call(print, "initializer"));
- }
- return concat$4(parts);
- case "TSImportEqualsDeclaration":
- if (n.isExport) {
- parts.push("export ");
- }
- parts.push("import ", path$$1.call(print, "id"), " = ", path$$1.call(print, "moduleReference"));
- if (options.semi) {
- parts.push(";");
- }
- return group$1(concat$4(parts));
- case "TSExternalModuleReference":
- return concat$4(["require(", path$$1.call(print, "expression"), ")"]);
- case "TSModuleDeclaration":
- {
- var _parent11 = path$$1.getParentNode();
- var isExternalModule = isLiteral(n.id);
- var parentIsDeclaration = _parent11.type === "TSModuleDeclaration";
- var bodyIsDeclaration = n.body && n.body.type === "TSModuleDeclaration";
- if (parentIsDeclaration) {
- parts.push(".");
- } else {
- if (n.declare === true) {
- parts.push("declare ");
- }
- parts.push(printTypeScriptModifiers(path$$1, options, print));
- var textBetweenNodeAndItsId = options.originalText.slice(options.locStart(n), options.locStart(n.id)); // Global declaration looks like this:
- // (declare)? global { ... }
- var isGlobalDeclaration = n.id.type === "Identifier" && n.id.name === "global" && !/namespace|module/.test(textBetweenNodeAndItsId);
- if (!isGlobalDeclaration) {
- parts.push(isExternalModule || /(^|\s)module(\s|$)/.test(textBetweenNodeAndItsId) ? "module " : "namespace ");
- }
- }
- parts.push(path$$1.call(print, "id"));
- if (bodyIsDeclaration) {
- parts.push(path$$1.call(print, "body"));
- } else if (n.body) {
- parts.push(" ", group$1(path$$1.call(print, "body")));
- } else {
- parts.push(semi);
- }
- return concat$4(parts);
- }
- case "PrivateName":
- return concat$4(["#", path$$1.call(print, "id")]);
- case "TSConditionalType":
- return printTernaryOperator(path$$1, options, print, {
- beforeParts: function beforeParts() {
- return [path$$1.call(print, "checkType"), " ", "extends", " ", path$$1.call(print, "extendsType")];
- },
- afterParts: function afterParts() {
- return [];
- },
- shouldCheckJsx: false,
- conditionalNodeType: "TSConditionalType",
- consequentNodePropertyName: "trueType",
- alternateNodePropertyName: "falseType",
- testNodePropertyName: "checkType",
- breakNested: true
- });
- case "TSInferType":
- return concat$4(["infer", " ", path$$1.call(print, "typeParameter")]);
- case "InterpreterDirective":
- parts.push("#!", n.value, hardline$3);
- if (isNextLineEmpty$2(options.originalText, n, options)) {
- parts.push(hardline$3);
- }
- return concat$4(parts);
- case "NGRoot":
- return concat$4([].concat(path$$1.call(print, "node"), !n.node.comments || n.node.comments.length === 0 ? [] : concat$4([" //", n.node.comments[0].value.trimRight()])));
- case "NGChainedExpression":
- return group$1(join$2(concat$4([";", line$3]), path$$1.map(function (childPath) {
- return hasNgSideEffect(childPath) ? print(childPath) : concat$4(["(", print(childPath), ")"]);
- }, "expressions")));
- case "NGEmptyExpression":
- return "";
- case "NGQuotedExpression":
- return concat$4([n.prefix, ":", n.value]);
- case "NGMicrosyntax":
- return concat$4(path$$1.map(function (childPath, index) {
- return concat$4([index === 0 ? "" : isNgForOf(childPath.getValue(), index, n) ? " " : concat$4([";", line$3]), print(childPath)]);
- }, "body"));
- case "NGMicrosyntaxKey":
- return /^[a-z_$][a-z0-9_$]*(-[a-z_$][a-z0-9_$])*$/i.test(n.name) ? n.name : JSON.stringify(n.name);
- case "NGMicrosyntaxExpression":
- return concat$4([path$$1.call(print, "expression"), n.alias === null ? "" : concat$4([" as ", path$$1.call(print, "alias")])]);
- case "NGMicrosyntaxKeyedExpression":
- {
- var index = path$$1.getName();
- var _parentNode2 = path$$1.getParentNode();
- var shouldNotPrintColon = isNgForOf(n, index, _parentNode2) || (index === 1 && (n.key.name === "then" || n.key.name === "else") || index === 2 && n.key.name === "else" && _parentNode2.body[index - 1].type === "NGMicrosyntaxKeyedExpression" && _parentNode2.body[index - 1].key.name === "then") && _parentNode2.body[0].type === "NGMicrosyntaxExpression";
- return concat$4([path$$1.call(print, "key"), shouldNotPrintColon ? " " : ": ", path$$1.call(print, "expression")]);
- }
- case "NGMicrosyntaxLet":
- return concat$4(["let ", path$$1.call(print, "key"), n.value === null ? "" : concat$4([" = ", path$$1.call(print, "value")])]);
- case "NGMicrosyntaxAs":
- return concat$4([path$$1.call(print, "key"), " as ", path$$1.call(print, "alias")]);
- default:
- /* istanbul ignore next */
- throw new Error("unknown type: " + JSON.stringify(n.type));
- }
- }
- function isNgForOf(node, index, parentNode) {
- return node.type === "NGMicrosyntaxKeyedExpression" && node.key.name === "of" && index === 1 && parentNode.body[0].type === "NGMicrosyntaxLet" && parentNode.body[0].value === null;
- }
- /** identify if an angular expression seems to have side effects */
- function hasNgSideEffect(path$$1) {
- return hasNode(path$$1.getValue(), function (node) {
- switch (node.type) {
- case undefined:
- return false;
- case "CallExpression":
- case "OptionalCallExpression":
- case "AssignmentExpression":
- return true;
- }
- });
- }
- function printStatementSequence(path$$1, options, print) {
- var printed = [];
- var bodyNode = path$$1.getNode();
- var isClass = bodyNode.type === "ClassBody";
- path$$1.map(function (stmtPath, i) {
- var stmt = stmtPath.getValue(); // Just in case the AST has been modified to contain falsy
- // "statements," it's safer simply to skip them.
- /* istanbul ignore if */
- if (!stmt) {
- return;
- } // Skip printing EmptyStatement nodes to avoid leaving stray
- // semicolons lying around.
- if (stmt.type === "EmptyStatement") {
- return;
- }
- var stmtPrinted = print(stmtPath);
- var text = options.originalText;
- var parts = []; // in no-semi mode, prepend statement with semicolon if it might break ASI
- // don't prepend the only JSX element in a program with semicolon
- if (!options.semi && !isClass && !isTheOnlyJSXElementInMarkdown(options, stmtPath) && stmtNeedsASIProtection(stmtPath, options)) {
- if (stmt.comments && stmt.comments.some(function (comment) {
- return comment.leading;
- })) {
- parts.push(print(stmtPath, {
- needsSemi: true
- }));
- } else {
- parts.push(";", stmtPrinted);
- }
- } else {
- parts.push(stmtPrinted);
- }
- if (!options.semi && isClass) {
- if (classPropMayCauseASIProblems(stmtPath)) {
- parts.push(";");
- } else if (stmt.type === "ClassProperty") {
- var nextChild = bodyNode.body[i + 1];
- if (classChildNeedsASIProtection(nextChild)) {
- parts.push(";");
- }
- }
- }
- if (isNextLineEmpty$2(text, stmt, options) && !isLastStatement(stmtPath)) {
- parts.push(hardline$3);
- }
- printed.push(concat$4(parts));
- });
- return join$2(hardline$3, printed);
- }
- function printPropertyKey(path$$1, options, print) {
- var node = path$$1.getNode();
- var key = node.key;
- if (key.type === "Identifier" && !node.computed && options.parser === "json") {
- // a -> "a"
- return path$$1.call(function (keyPath) {
- return comments.printComments(keyPath, function () {
- return JSON.stringify(key.name);
- }, options);
- }, "key");
- }
- if (isStringLiteral(key) && isIdentifierName(key.value) && !node.computed && options.parser !== "json" && !(options.parser === "typescript" && node.type === "ClassProperty")) {
- // 'a' -> a
- return path$$1.call(function (keyPath) {
- return comments.printComments(keyPath, function () {
- return key.value;
- }, options);
- }, "key");
- }
- return path$$1.call(print, "key");
- }
- function printMethod(path$$1, options, print) {
- var node = path$$1.getNode();
- var semi = options.semi ? ";" : "";
- var kind = node.kind;
- var parts = [];
- if (node.type === "ObjectMethod" || node.type === "ClassMethod" || node.type === "ClassPrivateMethod") {
- node.value = node;
- }
- if (node.value.async) {
- parts.push("async ");
- }
- if (!kind || kind === "init" || kind === "method" || kind === "constructor") {
- if (node.value.generator) {
- parts.push("*");
- }
- } else {
- assert.ok(kind === "get" || kind === "set");
- parts.push(kind, " ");
- }
- var key = printPropertyKey(path$$1, options, print);
- if (node.computed) {
- key = concat$4(["[", key, "]"]);
- }
- parts.push(key, concat$4(path$$1.call(function (valuePath) {
- return [printFunctionTypeParameters(valuePath, options, print), group$1(concat$4([printFunctionParams(valuePath, print, options), printReturnType(valuePath, print, options)]))];
- }, "value")));
- if (!node.value.body || node.value.body.length === 0) {
- parts.push(semi);
- } else {
- parts.push(" ", path$$1.call(print, "value", "body"));
- }
- return concat$4(parts);
- }
- function couldGroupArg(arg) {
- return arg.type === "ObjectExpression" && (arg.properties.length > 0 || arg.comments) || arg.type === "ArrayExpression" && (arg.elements.length > 0 || arg.comments) || arg.type === "TSTypeAssertion" || arg.type === "TSAsExpression" || arg.type === "FunctionExpression" || arg.type === "ArrowFunctionExpression" && !arg.returnType && (arg.body.type === "BlockStatement" || arg.body.type === "ArrowFunctionExpression" || arg.body.type === "ObjectExpression" || arg.body.type === "ArrayExpression" || arg.body.type === "CallExpression" || arg.body.type === "OptionalCallExpression" || arg.body.type === "ConditionalExpression" || isJSXNode(arg.body));
- }
- function shouldGroupLastArg(args) {
- var lastArg = getLast$4(args);
- var penultimateArg = getPenultimate$1(args);
- return !hasLeadingComment(lastArg) && !hasTrailingComment(lastArg) && couldGroupArg(lastArg) && ( // If the last two arguments are of the same type,
- // disable last element expansion.
- !penultimateArg || penultimateArg.type !== lastArg.type);
- }
- function shouldGroupFirstArg(args) {
- if (args.length !== 2) {
- return false;
- }
- var firstArg = args[0];
- var secondArg = args[1];
- return (!firstArg.comments || !firstArg.comments.length) && (firstArg.type === "FunctionExpression" || firstArg.type === "ArrowFunctionExpression" && firstArg.body.type === "BlockStatement") && secondArg.type !== "FunctionExpression" && secondArg.type !== "ArrowFunctionExpression" && secondArg.type !== "ConditionalExpression" && !couldGroupArg(secondArg);
- }
- function isSimpleFlowType(node) {
- var flowTypeAnnotations = ["AnyTypeAnnotation", "NullLiteralTypeAnnotation", "GenericTypeAnnotation", "ThisTypeAnnotation", "NumberTypeAnnotation", "VoidTypeAnnotation", "EmptyTypeAnnotation", "MixedTypeAnnotation", "BooleanTypeAnnotation", "BooleanLiteralTypeAnnotation", "StringTypeAnnotation"];
- return node && flowTypeAnnotations.indexOf(node.type) !== -1 && !(node.type === "GenericTypeAnnotation" && node.typeParameters);
- }
- var functionCompositionFunctionNames = new Set(["pipe", // RxJS, Ramda
- "pipeP", // Ramda
- "pipeK", // Ramda
- "compose", // Ramda, Redux
- "composeFlipped", // Not from any library, but common in Haskell, so supported
- "composeP", // Ramda
- "composeK", // Ramda
- "flow", // Lodash
- "flowRight", // Lodash
- "connect", // Redux
- "createSelector" // Reselect
- ]);
- var ordinaryMethodNames = new Set(["connect" // GObject, MongoDB
- ]);
- function isFunctionCompositionFunction(node) {
- switch (node.type) {
- case "OptionalMemberExpression":
- case "MemberExpression":
- {
- return isFunctionCompositionFunction(node.property) && !ordinaryMethodNames.has(node.property.name);
- }
- case "Identifier":
- {
- return functionCompositionFunctionNames.has(node.name);
- }
- case "StringLiteral":
- case "Literal":
- {
- return functionCompositionFunctionNames.has(node.value);
- }
- }
- }
- function printArgumentsList(path$$1, options, print) {
- var node = path$$1.getValue();
- var args = node.arguments;
- if (args.length === 0) {
- return concat$4(["(", comments.printDanglingComments(path$$1, options,
- /* sameIndent */
- true), ")"]);
- } // useEffect(() => { ... }, [foo, bar, baz])
- if (args.length === 2 && args[0].type === "ArrowFunctionExpression" && args[0].params.length === 0 && args[0].body.type === "BlockStatement" && args[1].type === "ArrayExpression" && !args.find(function (arg) {
- return arg.leadingComments || arg.trailingComments;
- })) {
- return concat$4(["(", path$$1.call(print, "arguments", 0), ", ", path$$1.call(print, "arguments", 1), ")"]);
- }
- var anyArgEmptyLine = false;
- var hasEmptyLineFollowingFirstArg = false;
- var lastArgIndex = args.length - 1;
- var printedArguments = path$$1.map(function (argPath, index) {
- var arg = argPath.getNode();
- var parts = [print(argPath)];
- if (index === lastArgIndex) {// do nothing
- } else if (isNextLineEmpty$2(options.originalText, arg, options)) {
- if (index === 0) {
- hasEmptyLineFollowingFirstArg = true;
- }
- anyArgEmptyLine = true;
- parts.push(",", hardline$3, hardline$3);
- } else {
- parts.push(",", line$3);
- }
- return concat$4(parts);
- }, "arguments");
- var maybeTrailingComma = shouldPrintComma(options, "all") ? "," : "";
- function allArgsBrokenOut() {
- return group$1(concat$4(["(", indent$2(concat$4([line$3, concat$4(printedArguments)])), maybeTrailingComma, line$3, ")"]), {
- shouldBreak: true
- });
- } // We want to get
- // pipe(
- // x => x + 1,
- // x => x - 1
- // )
- // here, but not
- // process.stdout.pipe(socket)
- if (isFunctionCompositionFunction(node.callee) && args.length > 1) {
- return allArgsBrokenOut();
- }
- var shouldGroupFirst = shouldGroupFirstArg(args);
- var shouldGroupLast = shouldGroupLastArg(args);
- if (shouldGroupFirst || shouldGroupLast) {
- var shouldBreak = (shouldGroupFirst ? printedArguments.slice(1).some(willBreak$1) : printedArguments.slice(0, -1).some(willBreak$1)) || anyArgEmptyLine; // We want to print the last argument with a special flag
- var printedExpanded;
- var i = 0;
- path$$1.each(function (argPath) {
- if (shouldGroupFirst && i === 0) {
- printedExpanded = [concat$4([argPath.call(function (p) {
- return print(p, {
- expandFirstArg: true
- });
- }), printedArguments.length > 1 ? "," : "", hasEmptyLineFollowingFirstArg ? hardline$3 : line$3, hasEmptyLineFollowingFirstArg ? hardline$3 : ""])].concat(printedArguments.slice(1));
- }
- if (shouldGroupLast && i === args.length - 1) {
- printedExpanded = printedArguments.slice(0, -1).concat(argPath.call(function (p) {
- return print(p, {
- expandLastArg: true
- });
- }));
- }
- i++;
- }, "arguments");
- var somePrintedArgumentsWillBreak = printedArguments.some(willBreak$1);
- return concat$4([somePrintedArgumentsWillBreak ? breakParent$2 : "", conditionalGroup$1([concat$4([ifBreak$1(indent$2(concat$4(["(", softline$1, concat$4(printedExpanded)])), concat$4(["(", concat$4(printedExpanded)])), somePrintedArgumentsWillBreak ? concat$4([ifBreak$1(maybeTrailingComma), softline$1]) : "", ")"]), shouldGroupFirst ? concat$4(["(", group$1(printedExpanded[0], {
- shouldBreak: true
- }), concat$4(printedExpanded.slice(1)), ")"]) : concat$4(["(", concat$4(printedArguments.slice(0, -1)), group$1(getLast$4(printedExpanded), {
- shouldBreak: true
- }), ")"]), allArgsBrokenOut()], {
- shouldBreak
- })]);
- }
- return group$1(concat$4(["(", indent$2(concat$4([softline$1, concat$4(printedArguments)])), ifBreak$1(shouldPrintComma(options, "all") ? "," : ""), softline$1, ")"]), {
- shouldBreak: printedArguments.some(willBreak$1) || anyArgEmptyLine
- });
- }
- function printTypeAnnotation(path$$1, options, print) {
- var node = path$$1.getValue();
- if (!node.typeAnnotation) {
- return "";
- }
- var parentNode = path$$1.getParentNode();
- var isDefinite = node.definite || parentNode && parentNode.type === "VariableDeclarator" && parentNode.definite;
- var isFunctionDeclarationIdentifier = parentNode.type === "DeclareFunction" && parentNode.id === node;
- if (isFlowAnnotationComment(options.originalText, node.typeAnnotation, options)) {
- return concat$4([" /*: ", path$$1.call(print, "typeAnnotation"), " */"]);
- }
- return concat$4([isFunctionDeclarationIdentifier ? "" : isDefinite ? "!: " : ": ", path$$1.call(print, "typeAnnotation")]);
- }
- function printFunctionTypeParameters(path$$1, options, print) {
- var fun = path$$1.getValue();
- if (fun.typeArguments) {
- return path$$1.call(print, "typeArguments");
- }
- if (fun.typeParameters) {
- return path$$1.call(print, "typeParameters");
- }
- return "";
- }
- function printFunctionParams(path$$1, print, options, expandArg, printTypeParams) {
- var fun = path$$1.getValue();
- var paramsField = fun.parameters ? "parameters" : "params";
- var typeParams = printTypeParams ? printFunctionTypeParameters(path$$1, options, print) : "";
- var printed = [];
- if (fun[paramsField]) {
- printed = path$$1.map(print, paramsField);
- }
- if (fun.rest) {
- printed.push(concat$4(["...", path$$1.call(print, "rest")]));
- }
- if (printed.length === 0) {
- return concat$4([typeParams, "(", comments.printDanglingComments(path$$1, options,
- /* sameIndent */
- true, function (comment) {
- return getNextNonSpaceNonCommentCharacter$1(options.originalText, comment, options.locEnd) === ")";
- }), ")"]);
- }
- var lastParam = getLast$4(fun[paramsField]); // If the parent is a call with the first/last argument expansion and this is the
- // params of the first/last argument, we dont want the arguments to break and instead
- // want the whole expression to be on a new line.
- //
- // Good: Bad:
- // verylongcall( verylongcall((
- // (a, b) => { a,
- // } b,
- // }) ) => {
- // })
- if (expandArg && !(fun[paramsField] && fun[paramsField].some(function (n) {
- return n.comments;
- }))) {
- return group$1(concat$4([removeLines$1(typeParams), "(", join$2(", ", printed.map(removeLines$1)), ")"]));
- } // Single object destructuring should hug
- //
- // function({
- // a,
- // b,
- // c
- // }) {}
- if (shouldHugArguments(fun)) {
- return concat$4([typeParams, "(", join$2(", ", printed), ")"]);
- }
- var parent = path$$1.getParentNode(); // don't break in specs, eg; `it("should maintain parens around done even when long", (done) => {})`
- if (isTestCall(parent)) {
- return concat$4([typeParams, "(", join$2(", ", printed), ")"]);
- }
- var isFlowShorthandWithOneArg = (isObjectTypePropertyAFunction(parent, options) || isTypeAnnotationAFunction(parent, options) || parent.type === "TypeAlias" || parent.type === "UnionTypeAnnotation" || parent.type === "TSUnionType" || parent.type === "IntersectionTypeAnnotation" || parent.type === "FunctionTypeAnnotation" && parent.returnType === fun) && fun[paramsField].length === 1 && fun[paramsField][0].name === null && fun[paramsField][0].typeAnnotation && fun.typeParameters === null && isSimpleFlowType(fun[paramsField][0].typeAnnotation) && !fun.rest;
- if (isFlowShorthandWithOneArg) {
- if (options.arrowParens === "always") {
- return concat$4(["(", concat$4(printed), ")"]);
- }
- return concat$4(printed);
- }
- var canHaveTrailingComma = !(lastParam && lastParam.type === "RestElement") && !fun.rest;
- return concat$4([typeParams, "(", indent$2(concat$4([softline$1, join$2(concat$4([",", line$3]), printed)])), ifBreak$1(canHaveTrailingComma && shouldPrintComma(options, "all") ? "," : ""), softline$1, ")"]);
- }
- function shouldPrintParamsWithoutParens(path$$1, options) {
- if (options.arrowParens === "always") {
- return false;
- }
- if (options.arrowParens === "avoid") {
- var node = path$$1.getValue();
- return canPrintParamsWithoutParens(node);
- } // Fallback default; should be unreachable
- return false;
- }
- function canPrintParamsWithoutParens(node) {
- return node.params.length === 1 && !node.rest && !node.typeParameters && !hasDanglingComments(node) && node.params[0].type === "Identifier" && !node.params[0].typeAnnotation && !node.params[0].comments && !node.params[0].optional && !node.predicate && !node.returnType;
- }
- function printFunctionDeclaration(path$$1, print, options) {
- var n = path$$1.getValue();
- var parts = [];
- if (n.async) {
- parts.push("async ");
- }
- parts.push("function");
- if (n.generator) {
- parts.push("*");
- }
- if (n.id) {
- parts.push(" ", path$$1.call(print, "id"));
- }
- parts.push(printFunctionTypeParameters(path$$1, options, print), group$1(concat$4([printFunctionParams(path$$1, print, options), printReturnType(path$$1, print, options)])), n.body ? " " : "", path$$1.call(print, "body"));
- return concat$4(parts);
- }
- function printObjectMethod(path$$1, options, print) {
- var objMethod = path$$1.getValue();
- var parts = [];
- if (objMethod.async) {
- parts.push("async ");
- }
- if (objMethod.generator) {
- parts.push("*");
- }
- if (objMethod.method || objMethod.kind === "get" || objMethod.kind === "set") {
- return printMethod(path$$1, options, print);
- }
- var key = printPropertyKey(path$$1, options, print);
- if (objMethod.computed) {
- parts.push("[", key, "]");
- } else {
- parts.push(key);
- }
- parts.push(printFunctionTypeParameters(path$$1, options, print), group$1(concat$4([printFunctionParams(path$$1, print, options), printReturnType(path$$1, print, options)])), " ", path$$1.call(print, "body"));
- return concat$4(parts);
- }
- function printReturnType(path$$1, print, options) {
- var n = path$$1.getValue();
- var returnType = path$$1.call(print, "returnType");
- if (n.returnType && isFlowAnnotationComment(options.originalText, n.returnType, options)) {
- return concat$4([" /*: ", returnType, " */"]);
- }
- var parts = [returnType]; // prepend colon to TypeScript type annotation
- if (n.returnType && n.returnType.typeAnnotation) {
- parts.unshift(": ");
- }
- if (n.predicate) {
- // The return type will already add the colon, but otherwise we
- // need to do it ourselves
- parts.push(n.returnType ? " " : ": ", path$$1.call(print, "predicate"));
- }
- return concat$4(parts);
- }
- function printExportDeclaration(path$$1, options, print) {
- var decl = path$$1.getValue();
- var semi = options.semi ? ";" : "";
- var parts = ["export "];
- var isDefault = decl["default"] || decl.type === "ExportDefaultDeclaration";
- if (isDefault) {
- parts.push("default ");
- }
- parts.push(comments.printDanglingComments(path$$1, options,
- /* sameIndent */
- true));
- if (needsHardlineAfterDanglingComment(decl)) {
- parts.push(hardline$3);
- }
- if (decl.declaration) {
- parts.push(path$$1.call(print, "declaration"));
- if (isDefault && decl.declaration.type !== "ClassDeclaration" && decl.declaration.type !== "FunctionDeclaration" && decl.declaration.type !== "TSAbstractClassDeclaration" && decl.declaration.type !== "TSInterfaceDeclaration" && decl.declaration.type !== "DeclareClass" && decl.declaration.type !== "DeclareFunction" && decl.declaration.type !== "TSDeclareFunction") {
- parts.push(semi);
- }
- } else {
- if (decl.specifiers && decl.specifiers.length > 0) {
- var specifiers = [];
- var defaultSpecifiers = [];
- var namespaceSpecifiers = [];
- path$$1.each(function (specifierPath) {
- var specifierType = path$$1.getValue().type;
- if (specifierType === "ExportSpecifier") {
- specifiers.push(print(specifierPath));
- } else if (specifierType === "ExportDefaultSpecifier") {
- defaultSpecifiers.push(print(specifierPath));
- } else if (specifierType === "ExportNamespaceSpecifier") {
- namespaceSpecifiers.push(concat$4(["* as ", print(specifierPath)]));
- }
- }, "specifiers");
- var isNamespaceFollowed = namespaceSpecifiers.length !== 0 && specifiers.length !== 0;
- var isDefaultFollowed = defaultSpecifiers.length !== 0 && (namespaceSpecifiers.length !== 0 || specifiers.length !== 0);
- parts.push(decl.exportKind === "type" ? "type " : "", concat$4(defaultSpecifiers), concat$4([isDefaultFollowed ? ", " : ""]), concat$4(namespaceSpecifiers), concat$4([isNamespaceFollowed ? ", " : ""]), specifiers.length !== 0 ? group$1(concat$4(["{", indent$2(concat$4([options.bracketSpacing ? line$3 : softline$1, join$2(concat$4([",", line$3]), specifiers)])), ifBreak$1(shouldPrintComma(options) ? "," : ""), options.bracketSpacing ? line$3 : softline$1, "}"])) : "");
- } else {
- parts.push("{}");
- }
- if (decl.source) {
- parts.push(" from ", path$$1.call(print, "source"));
- }
- parts.push(semi);
- }
- return concat$4(parts);
- }
- function printFlowDeclaration(path$$1, parts) {
- var parentExportDecl = getParentExportDeclaration$1(path$$1);
- if (parentExportDecl) {
- assert.strictEqual(parentExportDecl.type, "DeclareExportDeclaration");
- } else {
- // If the parent node has type DeclareExportDeclaration, then it
- // will be responsible for printing the "declare" token. Otherwise
- // it needs to be printed with this non-exported declaration node.
- parts.unshift("declare ");
- }
- return concat$4(parts);
- }
- function getFlowVariance(path$$1) {
- if (!path$$1.variance) {
- return null;
- } // Babel 7.0 currently uses variance node type, and flow should
- // follow suit soon:
- // https://github.com/babel/babel/issues/4722
- var variance = path$$1.variance.kind || path$$1.variance;
- switch (variance) {
- case "plus":
- return "+";
- case "minus":
- return "-";
- default:
- /* istanbul ignore next */
- return variance;
- }
- }
- function printTypeScriptModifiers(path$$1, options, print) {
- var n = path$$1.getValue();
- if (!n.modifiers || !n.modifiers.length) {
- return "";
- }
- return concat$4([join$2(" ", path$$1.map(print, "modifiers")), " "]);
- }
- function printTypeParameters(path$$1, options, print, paramsKey) {
- var n = path$$1.getValue();
- if (!n[paramsKey]) {
- return "";
- } // for TypeParameterDeclaration typeParameters is a single node
- if (!Array.isArray(n[paramsKey])) {
- return path$$1.call(print, paramsKey);
- }
- var grandparent = path$$1.getNode(2);
- var isParameterInTestCall = grandparent != null && isTestCall(grandparent);
- var shouldInline = isParameterInTestCall || n[paramsKey].length === 0 || n[paramsKey].length === 1 && (shouldHugType(n[paramsKey][0]) || n[paramsKey][0].type === "GenericTypeAnnotation" && shouldHugType(n[paramsKey][0].id) || n[paramsKey][0].type === "TSTypeReference" && shouldHugType(n[paramsKey][0].typeName) || n[paramsKey][0].type === "NullableTypeAnnotation");
- if (shouldInline) {
- return concat$4(["<", join$2(", ", path$$1.map(print, paramsKey)), ">"]);
- }
- return group$1(concat$4(["<", indent$2(concat$4([softline$1, join$2(concat$4([",", line$3]), path$$1.map(print, paramsKey))])), ifBreak$1(options.parser !== "typescript" && shouldPrintComma(options, "all") ? "," : ""), softline$1, ">"]));
- }
- function printClass(path$$1, options, print) {
- var n = path$$1.getValue();
- var parts = [];
- if (n.type === "TSAbstractClassDeclaration") {
- parts.push("abstract ");
- }
- parts.push("class");
- if (n.id) {
- parts.push(" ", path$$1.call(print, "id"));
- }
- parts.push(path$$1.call(print, "typeParameters"));
- var partsGroup = [];
- if (n.superClass) {
- var printed = concat$4(["extends ", path$$1.call(print, "superClass"), path$$1.call(print, "superTypeParameters")]); // Keep old behaviour of extends in same line
- // If there is only on extends and there are not comments
- if ((!n.implements || n.implements.length === 0) && (!n.superClass.comments || n.superClass.comments.length === 0)) {
- parts.push(concat$4([" ", path$$1.call(function (superClass) {
- return comments.printComments(superClass, function () {
- return printed;
- }, options);
- }, "superClass")]));
- } else {
- partsGroup.push(group$1(concat$4([line$3, path$$1.call(function (superClass) {
- return comments.printComments(superClass, function () {
- return printed;
- }, options);
- }, "superClass")])));
- }
- } else if (n.extends && n.extends.length > 0) {
- parts.push(" extends ", join$2(", ", path$$1.map(print, "extends")));
- }
- if (n["mixins"] && n["mixins"].length > 0) {
- partsGroup.push(line$3, "mixins ", group$1(indent$2(join$2(concat$4([",", line$3]), path$$1.map(print, "mixins")))));
- }
- if (n["implements"] && n["implements"].length > 0) {
- partsGroup.push(line$3, "implements", group$1(indent$2(concat$4([line$3, join$2(concat$4([",", line$3]), path$$1.map(print, "implements"))]))));
- }
- if (partsGroup.length > 0) {
- parts.push(group$1(indent$2(concat$4(partsGroup))));
- }
- if (n.body && n.body.comments && hasLeadingOwnLineComment(options.originalText, n.body, options)) {
- parts.push(hardline$3);
- } else {
- parts.push(" ");
- }
- parts.push(path$$1.call(print, "body"));
- return parts;
- }
- function printOptionalToken(path$$1) {
- var node = path$$1.getValue();
- if (!node.optional) {
- return "";
- }
- if (node.type === "OptionalCallExpression" || node.type === "OptionalMemberExpression" && node.computed) {
- return "?.";
- }
- return "?";
- }
- function printMemberLookup(path$$1, options, print) {
- var property = path$$1.call(print, "property");
- var n = path$$1.getValue();
- var optional = printOptionalToken(path$$1);
- if (!n.computed) {
- return concat$4([optional, ".", property]);
- }
- if (!n.property || isNumericLiteral(n.property)) {
- return concat$4([optional, "[", property, "]"]);
- }
- return group$1(concat$4([optional, "[", indent$2(concat$4([softline$1, property])), softline$1, "]"]));
- }
- function printBindExpressionCallee(path$$1, options, print) {
- return concat$4(["::", path$$1.call(print, "callee")]);
- } // We detect calls on member expressions specially to format a
- // common pattern better. The pattern we are looking for is this:
- //
- // arr
- // .map(x => x + 1)
- // .filter(x => x > 10)
- // .some(x => x % 2)
- //
- // The way it is structured in the AST is via a nested sequence of
- // MemberExpression and CallExpression. We need to traverse the AST
- // and make groups out of it to print it in the desired way.
- function printMemberChain(path$$1, options, print) {
- // The first phase is to linearize the AST by traversing it down.
- //
- // a().b()
- // has the following AST structure:
- // CallExpression(MemberExpression(CallExpression(Identifier)))
- // and we transform it into
- // [Identifier, CallExpression, MemberExpression, CallExpression]
- var printedNodes = []; // Here we try to retain one typed empty line after each call expression or
- // the first group whether it is in parentheses or not
- function shouldInsertEmptyLineAfter(node) {
- var originalText = options.originalText;
- var nextCharIndex = getNextNonSpaceNonCommentCharacterIndex$2(originalText, node, options);
- var nextChar = originalText.charAt(nextCharIndex); // if it is cut off by a parenthesis, we only account for one typed empty
- // line after that parenthesis
- if (nextChar == ")") {
- return isNextLineEmptyAfterIndex$1(originalText, nextCharIndex + 1, options);
- }
- return isNextLineEmpty$2(originalText, node, options);
- }
- function rec(path$$1) {
- var node = path$$1.getValue();
- if ((node.type === "CallExpression" || node.type === "OptionalCallExpression") && (isMemberish(node.callee) || node.callee.type === "CallExpression" || node.callee.type === "OptionalCallExpression")) {
- printedNodes.unshift({
- node: node,
- printed: concat$4([comments.printComments(path$$1, function () {
- return concat$4([printOptionalToken(path$$1), printFunctionTypeParameters(path$$1, options, print), printArgumentsList(path$$1, options, print)]);
- }, options), shouldInsertEmptyLineAfter(node) ? hardline$3 : ""])
- });
- path$$1.call(function (callee) {
- return rec(callee);
- }, "callee");
- } else if (isMemberish(node)) {
- printedNodes.unshift({
- node: node,
- needsParens: needsParens_1(path$$1, options),
- printed: comments.printComments(path$$1, function () {
- return node.type === "OptionalMemberExpression" || node.type === "MemberExpression" ? printMemberLookup(path$$1, options, print) : printBindExpressionCallee(path$$1, options, print);
- }, options)
- });
- path$$1.call(function (object) {
- return rec(object);
- }, "object");
- } else if (node.type === "TSNonNullExpression") {
- printedNodes.unshift({
- node: node,
- printed: comments.printComments(path$$1, function () {
- return "!";
- }, options)
- });
- path$$1.call(function (expression) {
- return rec(expression);
- }, "expression");
- } else {
- printedNodes.unshift({
- node: node,
- printed: path$$1.call(print)
- });
- }
- } // Note: the comments of the root node have already been printed, so we
- // need to extract this first call without printing them as they would
- // if handled inside of the recursive call.
- var node = path$$1.getValue();
- printedNodes.unshift({
- node,
- printed: concat$4([printOptionalToken(path$$1), printFunctionTypeParameters(path$$1, options, print), printArgumentsList(path$$1, options, print)])
- });
- path$$1.call(function (callee) {
- return rec(callee);
- }, "callee"); // Once we have a linear list of printed nodes, we want to create groups out
- // of it.
- //
- // a().b.c().d().e
- // will be grouped as
- // [
- // [Identifier, CallExpression],
- // [MemberExpression, MemberExpression, CallExpression],
- // [MemberExpression, CallExpression],
- // [MemberExpression],
- // ]
- // so that we can print it as
- // a()
- // .b.c()
- // .d()
- // .e
- // The first group is the first node followed by
- // - as many CallExpression as possible
- // < fn()()() >.something()
- // - as many array acessors as possible
- // < fn()[0][1][2] >.something()
- // - then, as many MemberExpression as possible but the last one
- // < this.items >.something()
- var groups = [];
- var currentGroup = [printedNodes[0]];
- var i = 1;
- for (; i < printedNodes.length; ++i) {
- if (printedNodes[i].node.type === "TSNonNullExpression" || printedNodes[i].node.type === "OptionalCallExpression" || printedNodes[i].node.type === "CallExpression" || (printedNodes[i].node.type === "MemberExpression" || printedNodes[i].node.type === "OptionalMemberExpression") && printedNodes[i].node.computed && isNumericLiteral(printedNodes[i].node.property)) {
- currentGroup.push(printedNodes[i]);
- } else {
- break;
- }
- }
- if (printedNodes[0].node.type !== "CallExpression" && printedNodes[0].node.type !== "OptionalCallExpression") {
- for (; i + 1 < printedNodes.length; ++i) {
- if (isMemberish(printedNodes[i].node) && isMemberish(printedNodes[i + 1].node)) {
- currentGroup.push(printedNodes[i]);
- } else {
- break;
- }
- }
- }
- groups.push(currentGroup);
- currentGroup = []; // Then, each following group is a sequence of MemberExpression followed by
- // a sequence of CallExpression. To compute it, we keep adding things to the
- // group until we has seen a CallExpression in the past and reach a
- // MemberExpression
- var hasSeenCallExpression = false;
- for (; i < printedNodes.length; ++i) {
- if (hasSeenCallExpression && isMemberish(printedNodes[i].node)) {
- // [0] should be appended at the end of the group instead of the
- // beginning of the next one
- if (printedNodes[i].node.computed && isNumericLiteral(printedNodes[i].node.property)) {
- currentGroup.push(printedNodes[i]);
- continue;
- }
- groups.push(currentGroup);
- currentGroup = [];
- hasSeenCallExpression = false;
- }
- if (printedNodes[i].node.type === "CallExpression" || printedNodes[i].node.type === "OptionalCallExpression") {
- hasSeenCallExpression = true;
- }
- currentGroup.push(printedNodes[i]);
- if (printedNodes[i].node.comments && printedNodes[i].node.comments.some(function (comment) {
- return comment.trailing;
- })) {
- groups.push(currentGroup);
- currentGroup = [];
- hasSeenCallExpression = false;
- }
- }
- if (currentGroup.length > 0) {
- groups.push(currentGroup);
- } // There are cases like Object.keys(), Observable.of(), _.values() where
- // they are the subject of all the chained calls and therefore should
- // be kept on the same line:
- //
- // Object.keys(items)
- // .filter(x => x)
- // .map(x => x)
- //
- // In order to detect those cases, we use an heuristic: if the first
- // node is an identifier with the name starting with a capital
- // letter or just a sequence of _$. The rationale is that they are
- // likely to be factories.
- function isFactory(name) {
- return /^[A-Z]|^[_$]+$/.test(name);
- } // In case the Identifier is shorter than tab width, we can keep the
- // first call in a single line, if it's an ExpressionStatement.
- //
- // d3.scaleLinear()
- // .domain([0, 100])
- // .range([0, width]);
- //
- function isShort(name) {
- return name.length <= options.tabWidth;
- }
- function shouldNotWrap(groups) {
- var parent = path$$1.getParentNode();
- var isExpression = parent && parent.type === "ExpressionStatement";
- var hasComputed = groups[1].length && groups[1][0].node.computed;
- if (groups[0].length === 1) {
- var firstNode = groups[0][0].node;
- return firstNode.type === "ThisExpression" || firstNode.type === "Identifier" && (isFactory(firstNode.name) || isExpression && isShort(firstNode.name) || hasComputed);
- }
- var lastNode = getLast$4(groups[0]).node;
- return (lastNode.type === "MemberExpression" || lastNode.type === "OptionalMemberExpression") && lastNode.property.type === "Identifier" && (isFactory(lastNode.property.name) || hasComputed);
- }
- var shouldMerge = groups.length >= 2 && !groups[1][0].node.comments && shouldNotWrap(groups);
- function printGroup(printedGroup) {
- var result = [];
- for (var _i3 = 0; _i3 < printedGroup.length; _i3++) {
- // Checks if the next node (i.e. the parent node) needs parens
- // and print accordingly
- if (printedGroup[_i3 + 1] && printedGroup[_i3 + 1].needsParens) {
- result.push("(", printedGroup[_i3].printed, printedGroup[_i3 + 1].printed, ")");
- _i3++;
- } else {
- result.push(printedGroup[_i3].printed);
- }
- }
- return concat$4(result);
- }
- function printIndentedGroup(groups) {
- if (groups.length === 0) {
- return "";
- }
- return indent$2(group$1(concat$4([hardline$3, join$2(hardline$3, groups.map(printGroup))])));
- }
- var printedGroups = groups.map(printGroup);
- var oneLine = concat$4(printedGroups);
- var cutoff = shouldMerge ? 3 : 2;
- var flatGroups = groups.slice(0, cutoff).reduce(function (res, group) {
- return res.concat(group);
- }, []);
- var hasComment = flatGroups.slice(1, -1).some(function (node) {
- return hasLeadingComment(node.node);
- }) || flatGroups.slice(0, -1).some(function (node) {
- return hasTrailingComment(node.node);
- }) || groups[cutoff] && hasLeadingComment(groups[cutoff][0].node); // If we only have a single `.`, we shouldn't do anything fancy and just
- // render everything concatenated together.
- if (groups.length <= cutoff && !hasComment) {
- return group$1(oneLine);
- } // Find out the last node in the first group and check if it has an
- // empty line after
- var lastNodeBeforeIndent = getLast$4(shouldMerge ? groups.slice(1, 2)[0] : groups[0]).node;
- var shouldHaveEmptyLineBeforeIndent = lastNodeBeforeIndent.type !== "CallExpression" && lastNodeBeforeIndent.type !== "OptionalCallExpression" && shouldInsertEmptyLineAfter(lastNodeBeforeIndent);
- var expanded = concat$4([printGroup(groups[0]), shouldMerge ? concat$4(groups.slice(1, 2).map(printGroup)) : "", shouldHaveEmptyLineBeforeIndent ? hardline$3 : "", printIndentedGroup(groups.slice(shouldMerge ? 2 : 1))]);
- var callExpressions = printedNodes.map(function (_ref) {
- var node = _ref.node;
- return node;
- }).filter(isCallOrOptionalCallExpression); // We don't want to print in one line if there's:
- // * A comment.
- // * 3 or more chained calls.
- // * Any group but the last one has a hard line.
- // If the last group is a function it's okay to inline if it fits.
- if (hasComment || callExpressions.length >= 3 || printedGroups.slice(0, -1).some(willBreak$1) ||
- /**
- * scopes.filter(scope => scope.value !== '').map((scope, i) => {
- * // multi line content
- * })
- */
- function (lastGroupDoc, lastGroupNode) {
- return isCallOrOptionalCallExpression(lastGroupNode) && willBreak$1(lastGroupDoc);
- }(getLast$4(printedGroups), getLast$4(getLast$4(groups)).node) && callExpressions.slice(0, -1).some(function (n) {
- return n.arguments.some(isFunctionOrArrowExpression);
- })) {
- return group$1(expanded);
- }
- return concat$4([// We only need to check `oneLine` because if `expanded` is chosen
- // that means that the parent group has already been broken
- // naturally
- willBreak$1(oneLine) || shouldHaveEmptyLineBeforeIndent ? breakParent$2 : "", conditionalGroup$1([oneLine, expanded])]);
- }
- function isCallOrOptionalCallExpression(node) {
- return node.type === "CallExpression" || node.type === "OptionalCallExpression";
- }
- function isJSXNode(node) {
- return node.type === "JSXElement" || node.type === "JSXFragment";
- }
- function isEmptyJSXElement(node) {
- if (node.children.length === 0) {
- return true;
- }
- if (node.children.length > 1) {
- return false;
- } // if there is one text child and does not contain any meaningful text
- // we can treat the element as empty.
- var child = node.children[0];
- return isLiteral(child) && !isMeaningfulJSXText(child);
- } // Only space, newline, carriage return, and tab are treated as whitespace
- // inside JSX.
- var jsxWhitespaceChars = " \n\r\t";
- var containsNonJsxWhitespaceRegex = new RegExp("[^" + jsxWhitespaceChars + "]");
- var matchJsxWhitespaceRegex = new RegExp("([" + jsxWhitespaceChars + "]+)"); // Meaningful if it contains non-whitespace characters,
- // or it contains whitespace without a new line.
- function isMeaningfulJSXText(node) {
- return isLiteral(node) && (containsNonJsxWhitespaceRegex.test(rawText(node)) || !/\n/.test(rawText(node)));
- }
- function conditionalExpressionChainContainsJSX(node) {
- return Boolean(getConditionalChainContents(node).find(isJSXNode));
- } // If we have nested conditional expressions, we want to print them in JSX mode
- // if there's at least one JSXElement somewhere in the tree.
- //
- // A conditional expression chain like this should be printed in normal mode,
- // because there aren't JSXElements anywhere in it:
- //
- // isA ? "A" : isB ? "B" : isC ? "C" : "Unknown";
- //
- // But a conditional expression chain like this should be printed in JSX mode,
- // because there is a JSXElement in the last ConditionalExpression:
- //
- // isA ? "A" : isB ? "B" : isC ? "C" : <span className="warning">Unknown</span>;
- //
- // This type of ConditionalExpression chain is structured like this in the AST:
- //
- // ConditionalExpression {
- // test: ...,
- // consequent: ...,
- // alternate: ConditionalExpression {
- // test: ...,
- // consequent: ...,
- // alternate: ConditionalExpression {
- // test: ...,
- // consequent: ...,
- // alternate: ...,
- // }
- // }
- // }
- //
- // We want to traverse over that shape and convert it into a flat structure so
- // that we can find if there's a JSXElement somewhere inside.
- function getConditionalChainContents(node) {
- // Given this code:
- //
- // // Using a ConditionalExpression as the consequent is uncommon, but should
- // // be handled.
- // A ? B : C ? D : E ? F ? G : H : I
- //
- // which has this AST:
- //
- // ConditionalExpression {
- // test: Identifier(A),
- // consequent: Identifier(B),
- // alternate: ConditionalExpression {
- // test: Identifier(C),
- // consequent: Identifier(D),
- // alternate: ConditionalExpression {
- // test: Identifier(E),
- // consequent: ConditionalExpression {
- // test: Identifier(F),
- // consequent: Identifier(G),
- // alternate: Identifier(H),
- // },
- // alternate: Identifier(I),
- // }
- // }
- // }
- //
- // we should return this Array:
- //
- // [
- // Identifier(A),
- // Identifier(B),
- // Identifier(C),
- // Identifier(D),
- // Identifier(E),
- // Identifier(F),
- // Identifier(G),
- // Identifier(H),
- // Identifier(I)
- // ];
- //
- // This loses the information about whether each node was the test,
- // consequent, or alternate, but we don't care about that here- we are only
- // flattening this structure to find if there's any JSXElements inside.
- var nonConditionalExpressions = [];
- function recurse(node) {
- if (node.type === "ConditionalExpression") {
- recurse(node.test);
- recurse(node.consequent);
- recurse(node.alternate);
- } else {
- nonConditionalExpressions.push(node);
- }
- }
- recurse(node);
- return nonConditionalExpressions;
- } // Detect an expression node representing `{" "}`
- function isJSXWhitespaceExpression(node) {
- return node.type === "JSXExpressionContainer" && isLiteral(node.expression) && node.expression.value === " " && !node.expression.comments;
- }
- function separatorNoWhitespace(isFacebookTranslationTag, child, childNode, nextNode) {
- if (isFacebookTranslationTag) {
- return "";
- }
- if (childNode.type === "JSXElement" && !childNode.closingElement || nextNode && nextNode.type === "JSXElement" && !nextNode.closingElement) {
- return child.length === 1 ? softline$1 : hardline$3;
- }
- return softline$1;
- }
- function separatorWithWhitespace(isFacebookTranslationTag, child, childNode, nextNode) {
- if (isFacebookTranslationTag) {
- return hardline$3;
- }
- if (child.length === 1) {
- return childNode.type === "JSXElement" && !childNode.closingElement || nextNode && nextNode.type === "JSXElement" && !nextNode.closingElement ? hardline$3 : softline$1;
- }
- return hardline$3;
- } // JSX Children are strange, mostly for two reasons:
- // 1. JSX reads newlines into string values, instead of skipping them like JS
- // 2. up to one whitespace between elements within a line is significant,
- // but not between lines.
- //
- // Leading, trailing, and lone whitespace all need to
- // turn themselves into the rather ugly `{' '}` when breaking.
- //
- // We print JSX using the `fill` doc primitive.
- // This requires that we give it an array of alternating
- // content and whitespace elements.
- // To ensure this we add dummy `""` content elements as needed.
- function printJSXChildren(path$$1, options, print, jsxWhitespace, isFacebookTranslationTag) {
- var n = path$$1.getValue();
- var children = []; // using `map` instead of `each` because it provides `i`
- path$$1.map(function (childPath, i) {
- var child = childPath.getValue();
- if (isLiteral(child)) {
- var text = rawText(child); // Contains a non-whitespace character
- if (isMeaningfulJSXText(child)) {
- var words = text.split(matchJsxWhitespaceRegex); // Starts with whitespace
- if (words[0] === "") {
- children.push("");
- words.shift();
- if (/\n/.test(words[0])) {
- var next = n.children[i + 1];
- children.push(separatorWithWhitespace(isFacebookTranslationTag, words[1], child, next));
- } else {
- children.push(jsxWhitespace);
- }
- words.shift();
- }
- var endWhitespace; // Ends with whitespace
- if (getLast$4(words) === "") {
- words.pop();
- endWhitespace = words.pop();
- } // This was whitespace only without a new line.
- if (words.length === 0) {
- return;
- }
- words.forEach(function (word, i) {
- if (i % 2 === 1) {
- children.push(line$3);
- } else {
- children.push(word);
- }
- });
- if (endWhitespace !== undefined) {
- if (/\n/.test(endWhitespace)) {
- var _next = n.children[i + 1];
- children.push(separatorWithWhitespace(isFacebookTranslationTag, getLast$4(children), child, _next));
- } else {
- children.push(jsxWhitespace);
- }
- } else {
- var _next2 = n.children[i + 1];
- children.push(separatorNoWhitespace(isFacebookTranslationTag, getLast$4(children), child, _next2));
- }
- } else if (/\n/.test(text)) {
- // Keep (up to one) blank line between tags/expressions/text.
- // Note: We don't keep blank lines between text elements.
- if (text.match(/\n/g).length > 1) {
- children.push("");
- children.push(hardline$3);
- }
- } else {
- children.push("");
- children.push(jsxWhitespace);
- }
- } else {
- var printedChild = print(childPath);
- children.push(printedChild);
- var _next3 = n.children[i + 1];
- var directlyFollowedByMeaningfulText = _next3 && isMeaningfulJSXText(_next3);
- if (directlyFollowedByMeaningfulText) {
- var firstWord = rawText(_next3).trim().split(matchJsxWhitespaceRegex)[0];
- children.push(separatorNoWhitespace(isFacebookTranslationTag, firstWord, child, _next3));
- } else {
- children.push(hardline$3);
- }
- }
- }, "children");
- return children;
- } // JSX expands children from the inside-out, instead of the outside-in.
- // This is both to break children before attributes,
- // and to ensure that when children break, their parents do as well.
- //
- // Any element that is written without any newlines and fits on a single line
- // is left that way.
- // Not only that, any user-written-line containing multiple JSX siblings
- // should also be kept on one line if possible,
- // so each user-written-line is wrapped in its own group.
- //
- // Elements that contain newlines or don't fit on a single line (recursively)
- // are fully-split, using hardline and shouldBreak: true.
- //
- // To support that case properly, all leading and trailing spaces
- // are stripped from the list of children, and replaced with a single hardline.
- function printJSXElement(path$$1, options, print) {
- var n = path$$1.getValue(); // Turn <div></div> into <div />
- if (n.type === "JSXElement" && isEmptyJSXElement(n)) {
- n.openingElement.selfClosing = true;
- return path$$1.call(print, "openingElement");
- }
- var openingLines = n.type === "JSXElement" ? path$$1.call(print, "openingElement") : path$$1.call(print, "openingFragment");
- var closingLines = n.type === "JSXElement" ? path$$1.call(print, "closingElement") : path$$1.call(print, "closingFragment");
- if (n.children.length === 1 && n.children[0].type === "JSXExpressionContainer" && (n.children[0].expression.type === "TemplateLiteral" || n.children[0].expression.type === "TaggedTemplateExpression")) {
- return concat$4([openingLines, concat$4(path$$1.map(print, "children")), closingLines]);
- } // Convert `{" "}` to text nodes containing a space.
- // This makes it easy to turn them into `jsxWhitespace` which
- // can then print as either a space or `{" "}` when breaking.
- n.children = n.children.map(function (child) {
- if (isJSXWhitespaceExpression(child)) {
- return {
- type: "JSXText",
- value: " ",
- raw: " "
- };
- }
- return child;
- });
- var containsTag = n.children.filter(isJSXNode).length > 0;
- var containsMultipleExpressions = n.children.filter(function (child) {
- return child.type === "JSXExpressionContainer";
- }).length > 1;
- var containsMultipleAttributes = n.type === "JSXElement" && n.openingElement.attributes.length > 1; // Record any breaks. Should never go from true to false, only false to true.
- var forcedBreak = willBreak$1(openingLines) || containsTag || containsMultipleAttributes || containsMultipleExpressions;
- var rawJsxWhitespace = options.singleQuote ? "{' '}" : '{" "}';
- var jsxWhitespace = ifBreak$1(concat$4([rawJsxWhitespace, softline$1]), " ");
- var isFacebookTranslationTag = n.openingElement && n.openingElement.name && n.openingElement.name.name === "fbt";
- var children = printJSXChildren(path$$1, options, print, jsxWhitespace, isFacebookTranslationTag);
- var containsText = n.children.filter(function (child) {
- return isMeaningfulJSXText(child);
- }).length > 0; // We can end up we multiple whitespace elements with empty string
- // content between them.
- // We need to remove empty whitespace and softlines before JSX whitespace
- // to get the correct output.
- for (var i = children.length - 2; i >= 0; i--) {
- var isPairOfEmptyStrings = children[i] === "" && children[i + 1] === "";
- var isPairOfHardlines = children[i] === hardline$3 && children[i + 1] === "" && children[i + 2] === hardline$3;
- var isLineFollowedByJSXWhitespace = (children[i] === softline$1 || children[i] === hardline$3) && children[i + 1] === "" && children[i + 2] === jsxWhitespace;
- var isJSXWhitespaceFollowedByLine = children[i] === jsxWhitespace && children[i + 1] === "" && (children[i + 2] === softline$1 || children[i + 2] === hardline$3);
- var isDoubleJSXWhitespace = children[i] === jsxWhitespace && children[i + 1] === "" && children[i + 2] === jsxWhitespace;
- var isPairOfHardOrSoftLines = children[i] === softline$1 && children[i + 1] === "" && children[i + 2] === hardline$3 || children[i] === hardline$3 && children[i + 1] === "" && children[i + 2] === softline$1;
- if (isPairOfHardlines && containsText || isPairOfEmptyStrings || isLineFollowedByJSXWhitespace || isDoubleJSXWhitespace || isPairOfHardOrSoftLines) {
- children.splice(i, 2);
- } else if (isJSXWhitespaceFollowedByLine) {
- children.splice(i + 1, 2);
- }
- } // Trim trailing lines (or empty strings)
- while (children.length && (isLineNext$1(getLast$4(children)) || isEmpty$1(getLast$4(children)))) {
- children.pop();
- } // Trim leading lines (or empty strings)
- while (children.length && (isLineNext$1(children[0]) || isEmpty$1(children[0])) && (isLineNext$1(children[1]) || isEmpty$1(children[1]))) {
- children.shift();
- children.shift();
- } // Tweak how we format children if outputting this element over multiple lines.
- // Also detect whether we will force this element to output over multiple lines.
- var multilineChildren = [];
- children.forEach(function (child, i) {
- // There are a number of situations where we need to ensure we display
- // whitespace as `{" "}` when outputting this element over multiple lines.
- if (child === jsxWhitespace) {
- if (i === 1 && children[i - 1] === "") {
- if (children.length === 2) {
- // Solitary whitespace
- multilineChildren.push(rawJsxWhitespace);
- return;
- } // Leading whitespace
- multilineChildren.push(concat$4([rawJsxWhitespace, hardline$3]));
- return;
- } else if (i === children.length - 1) {
- // Trailing whitespace
- multilineChildren.push(rawJsxWhitespace);
- return;
- } else if (children[i - 1] === "" && children[i - 2] === hardline$3) {
- // Whitespace after line break
- multilineChildren.push(rawJsxWhitespace);
- return;
- }
- }
- multilineChildren.push(child);
- if (willBreak$1(child)) {
- forcedBreak = true;
- }
- }); // If there is text we use `fill` to fit as much onto each line as possible.
- // When there is no text (just tags and expressions) we use `group`
- // to output each on a separate line.
- var content = containsText ? fill$2(multilineChildren) : group$1(concat$4(multilineChildren), {
- shouldBreak: true
- });
- var multiLineElem = group$1(concat$4([openingLines, indent$2(concat$4([hardline$3, content])), hardline$3, closingLines]));
- if (forcedBreak) {
- return multiLineElem;
- }
- return conditionalGroup$1([group$1(concat$4([openingLines, concat$4(children), closingLines])), multiLineElem]);
- }
- function maybeWrapJSXElementInParens(path$$1, elem) {
- var parent = path$$1.getParentNode();
- if (!parent) {
- return elem;
- }
- var NO_WRAP_PARENTS = {
- ArrayExpression: true,
- JSXAttribute: true,
- JSXElement: true,
- JSXExpressionContainer: true,
- JSXFragment: true,
- ExpressionStatement: true,
- CallExpression: true,
- OptionalCallExpression: true,
- ConditionalExpression: true,
- JsExpressionRoot: true
- };
- if (NO_WRAP_PARENTS[parent.type]) {
- return elem;
- }
- var shouldBreak = matchAncestorTypes$1(path$$1, ["ArrowFunctionExpression", "CallExpression", "JSXExpressionContainer"]);
- return group$1(concat$4([ifBreak$1("("), indent$2(concat$4([softline$1, elem])), softline$1, ifBreak$1(")")]), {
- shouldBreak
- });
- }
- function isBinaryish(node) {
- return node.type === "BinaryExpression" || node.type === "LogicalExpression" || node.type === "NGPipeExpression";
- }
- function isMemberish(node) {
- return node.type === "MemberExpression" || node.type === "OptionalMemberExpression" || node.type === "BindExpression" && node.object;
- }
- function shouldInlineLogicalExpression(node) {
- if (node.type !== "LogicalExpression") {
- return false;
- }
- if (node.right.type === "ObjectExpression" && node.right.properties.length !== 0) {
- return true;
- }
- if (node.right.type === "ArrayExpression" && node.right.elements.length !== 0) {
- return true;
- }
- if (isJSXNode(node.right)) {
- return true;
- }
- return false;
- } // For binary expressions to be consistent, we need to group
- // subsequent operators with the same precedence level under a single
- // group. Otherwise they will be nested such that some of them break
- // onto new lines but not all. Operators with the same precedence
- // level should either all break or not. Because we group them by
- // precedence level and the AST is structured based on precedence
- // level, things are naturally broken up correctly, i.e. `&&` is
- // broken before `+`.
- function printBinaryishExpressions(path$$1, print, options, isNested, isInsideParenthesis) {
- var parts = [];
- var node = path$$1.getValue(); // We treat BinaryExpression and LogicalExpression nodes the same.
- if (isBinaryish(node)) {
- // Put all operators with the same precedence level in the same
- // group. The reason we only need to do this with the `left`
- // expression is because given an expression like `1 + 2 - 3`, it
- // is always parsed like `((1 + 2) - 3)`, meaning the `left` side
- // is where the rest of the expression will exist. Binary
- // expressions on the right side mean they have a difference
- // precedence level and should be treated as a separate group, so
- // print them normally. (This doesn't hold for the `**` operator,
- // which is unique in that it is right-associative.)
- if (shouldFlatten$1(node.operator, node.left.operator)) {
- // Flatten them out by recursively calling this function.
- parts = parts.concat(path$$1.call(function (left) {
- return printBinaryishExpressions(left, print, options,
- /* isNested */
- true, isInsideParenthesis);
- }, "left"));
- } else {
- parts.push(path$$1.call(print, "left"));
- }
- var shouldInline = shouldInlineLogicalExpression(node);
- var lineBeforeOperator = (node.operator === "|>" || node.type === "NGPipeExpression" || node.operator === "|" && options.parser === "__vue_expression") && !hasLeadingOwnLineComment(options.originalText, node.right, options);
- var operator = node.type === "NGPipeExpression" ? "|" : node.operator;
- var rightSuffix = node.type === "NGPipeExpression" && node.arguments.length !== 0 ? group$1(indent$2(concat$4([softline$1, ": ", join$2(concat$4([softline$1, ":", ifBreak$1(" ")]), path$$1.map(print, "arguments").map(function (arg) {
- return align$1(2, group$1(arg));
- }))]))) : "";
- var right = shouldInline ? concat$4([operator, " ", path$$1.call(print, "right"), rightSuffix]) : concat$4([lineBeforeOperator ? softline$1 : "", operator, lineBeforeOperator ? " " : line$3, path$$1.call(print, "right"), rightSuffix]); // If there's only a single binary expression, we want to create a group
- // in order to avoid having a small right part like -1 be on its own line.
- var parent = path$$1.getParentNode();
- var shouldGroup = !(isInsideParenthesis && node.type === "LogicalExpression") && parent.type !== node.type && node.left.type !== node.type && node.right.type !== node.type;
- parts.push(" ", shouldGroup ? group$1(right) : right); // The root comments are already printed, but we need to manually print
- // the other ones since we don't call the normal print on BinaryExpression,
- // only for the left and right parts
- if (isNested && node.comments) {
- parts = comments.printComments(path$$1, function () {
- return concat$4(parts);
- }, options);
- }
- } else {
- // Our stopping case. Simply print the node normally.
- parts.push(path$$1.call(print));
- }
- return parts;
- }
- function printAssignmentRight(leftNode, rightNode, printedRight, options) {
- if (hasLeadingOwnLineComment(options.originalText, rightNode, options)) {
- return indent$2(concat$4([hardline$3, printedRight]));
- }
- var canBreak = isBinaryish(rightNode) && !shouldInlineLogicalExpression(rightNode) || rightNode.type === "ConditionalExpression" && isBinaryish(rightNode.test) && !shouldInlineLogicalExpression(rightNode.test) || rightNode.type === "StringLiteralTypeAnnotation" || rightNode.type === "ClassExpression" && rightNode.decorators && rightNode.decorators.length || (leftNode.type === "Identifier" || isStringLiteral(leftNode) || leftNode.type === "MemberExpression") && (isStringLiteral(rightNode) || isMemberExpressionChain(rightNode)) && // do not put values on a separate line from the key in json
- options.parser !== "json" && options.parser !== "json5";
- if (canBreak) {
- return group$1(indent$2(concat$4([line$3, printedRight])));
- }
- return concat$4([" ", printedRight]);
- }
- function printAssignment(leftNode, printedLeft, operator, rightNode, printedRight, options) {
- if (!rightNode) {
- return printedLeft;
- }
- var printed = printAssignmentRight(leftNode, rightNode, printedRight, options);
- return group$1(concat$4([printedLeft, operator, printed]));
- }
- function adjustClause(node, clause, forceSpace) {
- if (node.type === "EmptyStatement") {
- return ";";
- }
- if (node.type === "BlockStatement" || forceSpace) {
- return concat$4([" ", clause]);
- }
- return indent$2(concat$4([line$3, clause]));
- }
- function nodeStr(node, options, isFlowOrTypeScriptDirectiveLiteral) {
- var raw = rawText(node);
- var isDirectiveLiteral = isFlowOrTypeScriptDirectiveLiteral || node.type === "DirectiveLiteral";
- return printString$1(raw, options, isDirectiveLiteral);
- }
- function printRegex(node) {
- var flags = node.flags.split("").sort().join("");
- return `/${node.pattern}/${flags}`;
- }
- function isLastStatement(path$$1) {
- var parent = path$$1.getParentNode();
- if (!parent) {
- return true;
- }
- var node = path$$1.getValue();
- var body = (parent.body || parent.consequent).filter(function (stmt) {
- return stmt.type !== "EmptyStatement";
- });
- return body && body[body.length - 1] === node;
- }
- function hasLeadingComment(node) {
- return node.comments && node.comments.some(function (comment) {
- return comment.leading;
- });
- }
- function hasTrailingComment(node) {
- return node.comments && node.comments.some(function (comment) {
- return comment.trailing;
- });
- }
- function hasLeadingOwnLineComment(text, node, options) {
- if (isJSXNode(node)) {
- return hasNodeIgnoreComment$1(node);
- }
- var res = node.comments && node.comments.some(function (comment) {
- return comment.leading && hasNewline$2(text, options.locEnd(comment));
- });
- return res;
- }
- function hasNakedLeftSide(node) {
- return node.type === "AssignmentExpression" || node.type === "BinaryExpression" || node.type === "LogicalExpression" || node.type === "NGPipeExpression" || node.type === "ConditionalExpression" || node.type === "CallExpression" || node.type === "OptionalCallExpression" || node.type === "MemberExpression" || node.type === "OptionalMemberExpression" || node.type === "SequenceExpression" || node.type === "TaggedTemplateExpression" || node.type === "BindExpression" || node.type === "UpdateExpression" && !node.prefix || node.type === "TSNonNullExpression";
- }
- function isFlowAnnotationComment(text, typeAnnotation, options) {
- var start = options.locStart(typeAnnotation);
- var end = skipWhitespace$1(text, options.locEnd(typeAnnotation));
- return text.substr(start, 2) === "/*" && text.substr(end, 2) === "*/";
- }
- function getLeftSide(node) {
- if (node.expressions) {
- return node.expressions[0];
- }
- return node.left || node.test || node.callee || node.object || node.tag || node.argument || node.expression;
- }
- function getLeftSidePathName(path$$1, node) {
- if (node.expressions) {
- return ["expressions", 0];
- }
- if (node.left) {
- return ["left"];
- }
- if (node.test) {
- return ["test"];
- }
- if (node.object) {
- return ["object"];
- }
- if (node.callee) {
- return ["callee"];
- }
- if (node.tag) {
- return ["tag"];
- }
- if (node.argument) {
- return ["argument"];
- }
- if (node.expression) {
- return ["expression"];
- }
- throw new Error("Unexpected node has no left side", node);
- }
- function exprNeedsASIProtection(path$$1, options) {
- var node = path$$1.getValue();
- var maybeASIProblem = needsParens_1(path$$1, options) || node.type === "ParenthesizedExpression" || node.type === "TypeCastExpression" || node.type === "ArrowFunctionExpression" && !shouldPrintParamsWithoutParens(path$$1, options) || node.type === "ArrayExpression" || node.type === "ArrayPattern" || node.type === "UnaryExpression" && node.prefix && (node.operator === "+" || node.operator === "-") || node.type === "TemplateLiteral" || node.type === "TemplateElement" || isJSXNode(node) || node.type === "BindExpression" && !node.object || node.type === "RegExpLiteral" || node.type === "Literal" && node.pattern || node.type === "Literal" && node.regex;
- if (maybeASIProblem) {
- return true;
- }
- if (!hasNakedLeftSide(node)) {
- return false;
- }
- return path$$1.call.apply(path$$1, [function (childPath) {
- return exprNeedsASIProtection(childPath, options);
- }].concat(getLeftSidePathName(path$$1, node)));
- }
- function stmtNeedsASIProtection(path$$1, options) {
- var node = path$$1.getNode();
- if (node.type !== "ExpressionStatement") {
- return false;
- }
- return path$$1.call(function (childPath) {
- return exprNeedsASIProtection(childPath, options);
- }, "expression");
- }
- function classPropMayCauseASIProblems(path$$1) {
- var node = path$$1.getNode();
- if (node.type !== "ClassProperty") {
- return false;
- }
- var name = node.key && node.key.name; // this isn't actually possible yet with most parsers available today
- // so isn't properly tested yet.
- if ((name === "static" || name === "get" || name === "set") && !node.value && !node.typeAnnotation) {
- return true;
- }
- }
- function classChildNeedsASIProtection(node) {
- if (!node) {
- return;
- }
- if (node.static || node.accessibility // TypeScript
- ) {
- return false;
- }
- if (!node.computed) {
- var name = node.key && node.key.name;
- if (name === "in" || name === "instanceof") {
- return true;
- }
- }
- switch (node.type) {
- case "ClassProperty":
- case "TSAbstractClassProperty":
- return node.computed;
- case "MethodDefinition": // Flow
- case "TSAbstractMethodDefinition": // TypeScript
- case "ClassMethod":
- case "ClassPrivateMethod":
- {
- // Babel
- var isAsync = node.value ? node.value.async : node.async;
- var isGenerator = node.value ? node.value.generator : node.generator;
- if (isAsync || node.kind === "get" || node.kind === "set") {
- return false;
- }
- if (node.computed || isGenerator) {
- return true;
- }
- return false;
- }
- default:
- /* istanbul ignore next */
- return false;
- }
- } // This recurses the return argument, looking for the first token
- // (the leftmost leaf node) and, if it (or its parents) has any
- // leadingComments, returns true (so it can be wrapped in parens).
- function returnArgumentHasLeadingComment(options, argument) {
- if (hasLeadingOwnLineComment(options.originalText, argument, options)) {
- return true;
- }
- if (hasNakedLeftSide(argument)) {
- var leftMost = argument;
- var newLeftMost;
- while (newLeftMost = getLeftSide(leftMost)) {
- leftMost = newLeftMost;
- if (hasLeadingOwnLineComment(options.originalText, leftMost, options)) {
- return true;
- }
- }
- }
- return false;
- }
- function isMemberExpressionChain(node) {
- if (node.type !== "MemberExpression" && node.type !== "OptionalMemberExpression") {
- return false;
- }
- if (node.object.type === "Identifier") {
- return true;
- }
- return isMemberExpressionChain(node.object);
- } // Hack to differentiate between the following two which have the same ast
- // type T = { method: () => void };
- // type T = { method(): void };
- function isObjectTypePropertyAFunction(node, options) {
- return (node.type === "ObjectTypeProperty" || node.type === "ObjectTypeInternalSlot") && node.value.type === "FunctionTypeAnnotation" && !node.static && !isFunctionNotation(node, options);
- } // TODO: This is a bad hack and we need a better way to distinguish between
- // arrow functions and otherwise
- function isFunctionNotation(node, options) {
- return isGetterOrSetter(node) || sameLocStart(node, node.value, options);
- }
- function isGetterOrSetter(node) {
- return node.kind === "get" || node.kind === "set";
- }
- function sameLocStart(nodeA, nodeB, options) {
- return options.locStart(nodeA) === options.locStart(nodeB);
- } // Hack to differentiate between the following two which have the same ast
- // declare function f(a): void;
- // var f: (a) => void;
- function isTypeAnnotationAFunction(node, options) {
- return (node.type === "TypeAnnotation" || node.type === "TSTypeAnnotation") && node.typeAnnotation.type === "FunctionTypeAnnotation" && !node.static && !sameLocStart(node, node.typeAnnotation, options);
- }
- function isNodeStartingWithDeclare(node, options) {
- if (!(options.parser === "flow" || options.parser === "typescript")) {
- return false;
- }
- return options.originalText.slice(0, options.locStart(node)).match(/declare[ \t]*$/) || options.originalText.slice(node.range[0], node.range[1]).startsWith("declare ");
- }
- function shouldHugType(node) {
- if (isSimpleFlowType(node) || isObjectType(node)) {
- return true;
- }
- if (node.type === "UnionTypeAnnotation" || node.type === "TSUnionType") {
- var voidCount = node.types.filter(function (n) {
- return n.type === "VoidTypeAnnotation" || n.type === "TSVoidKeyword" || n.type === "NullLiteralTypeAnnotation" || n.type === "TSNullKeyword";
- }).length;
- var objectCount = node.types.filter(function (n) {
- return n.type === "ObjectTypeAnnotation" || n.type === "TSTypeLiteral" || // This is a bit aggressive but captures Array<{x}>
- n.type === "GenericTypeAnnotation" || n.type === "TSTypeReference";
- }).length;
- if (node.types.length - 1 === voidCount && objectCount > 0) {
- return true;
- }
- }
- return false;
- }
- function shouldHugArguments(fun) {
- return fun && fun.params && fun.params.length === 1 && !fun.params[0].comments && (fun.params[0].type === "ObjectPattern" || fun.params[0].type === "ArrayPattern" || fun.params[0].type === "Identifier" && fun.params[0].typeAnnotation && (fun.params[0].typeAnnotation.type === "TypeAnnotation" || fun.params[0].typeAnnotation.type === "TSTypeAnnotation") && isObjectType(fun.params[0].typeAnnotation.typeAnnotation) || fun.params[0].type === "FunctionTypeParam" && isObjectType(fun.params[0].typeAnnotation) || fun.params[0].type === "AssignmentPattern" && (fun.params[0].left.type === "ObjectPattern" || fun.params[0].left.type === "ArrayPattern") && (fun.params[0].right.type === "Identifier" || fun.params[0].right.type === "ObjectExpression" && fun.params[0].right.properties.length === 0 || fun.params[0].right.type === "ArrayExpression" && fun.params[0].right.elements.length === 0)) && !fun.rest;
- }
- function templateLiteralHasNewLines(template) {
- return template.quasis.some(function (quasi) {
- return quasi.value.raw.includes("\n");
- });
- }
- function isTemplateOnItsOwnLine(n, text, options) {
- return (n.type === "TemplateLiteral" && templateLiteralHasNewLines(n) || n.type === "TaggedTemplateExpression" && templateLiteralHasNewLines(n.quasi)) && !hasNewline$2(text, options.locStart(n), {
- backwards: true
- });
- }
- function printArrayItems(path$$1, options, printPath, print) {
- var printedElements = [];
- var separatorParts = [];
- path$$1.each(function (childPath) {
- printedElements.push(concat$4(separatorParts));
- printedElements.push(group$1(print(childPath)));
- separatorParts = [",", line$3];
- if (childPath.getValue() && isNextLineEmpty$2(options.originalText, childPath.getValue(), options)) {
- separatorParts.push(softline$1);
- }
- }, printPath);
- return concat$4(printedElements);
- }
- function hasDanglingComments(node) {
- return node.comments && node.comments.some(function (comment) {
- return !comment.leading && !comment.trailing;
- });
- }
- function needsHardlineAfterDanglingComment(node) {
- if (!node.comments) {
- return false;
- }
- var lastDanglingComment = getLast$4(node.comments.filter(function (comment) {
- return !comment.leading && !comment.trailing;
- }));
- return lastDanglingComment && !comments$3.isBlockComment(lastDanglingComment);
- }
- function isLiteral(node) {
- return node.type === "BooleanLiteral" || node.type === "DirectiveLiteral" || node.type === "Literal" || node.type === "NullLiteral" || node.type === "NumericLiteral" || node.type === "RegExpLiteral" || node.type === "StringLiteral" || node.type === "TemplateLiteral" || node.type === "TSTypeLiteral" || node.type === "JSXText";
- }
- function isNumericLiteral(node) {
- return node.type === "NumericLiteral" || node.type === "Literal" && typeof node.value === "number";
- }
- function isStringLiteral(node) {
- return node.type === "StringLiteral" || node.type === "Literal" && typeof node.value === "string";
- }
- function isObjectType(n) {
- return n.type === "ObjectTypeAnnotation" || n.type === "TSTypeLiteral";
- }
- var unitTestRe = /^(skip|[fx]?(it|describe|test))$/; // eg; `describe("some string", (done) => {})`
- function isTestCall(n, parent) {
- if (n.type !== "CallExpression") {
- return false;
- }
- if (n.arguments.length === 1) {
- if (isAngularTestWrapper(n) && parent && isTestCall(parent)) {
- return isFunctionOrArrowExpression(n.arguments[0]);
- }
- if (isUnitTestSetUp(n)) {
- return isAngularTestWrapper(n.arguments[0]);
- }
- } else if (n.arguments.length === 2 || n.arguments.length === 3) {
- if ((n.callee.type === "Identifier" && unitTestRe.test(n.callee.name) || isSkipOrOnlyBlock(n)) && (isTemplateLiteral(n.arguments[0]) || isStringLiteral(n.arguments[0]))) {
- // it("name", () => { ... }, 2500)
- if (n.arguments[2] && !isNumericLiteral(n.arguments[2])) {
- return false;
- }
- return (n.arguments.length === 2 ? isFunctionOrArrowExpression(n.arguments[1]) : isFunctionOrArrowExpressionWithBody(n.arguments[1]) && n.arguments[1].params.length <= 1) || isAngularTestWrapper(n.arguments[1]);
- }
- }
- return false;
- }
- function isSkipOrOnlyBlock(node) {
- return (node.callee.type === "MemberExpression" || node.callee.type === "OptionalMemberExpression") && node.callee.object.type === "Identifier" && node.callee.property.type === "Identifier" && unitTestRe.test(node.callee.object.name) && (node.callee.property.name === "only" || node.callee.property.name === "skip");
- }
- function isTemplateLiteral(node) {
- return node.type === "TemplateLiteral";
- } // `inject` is used in AngularJS 1.x, `async` in Angular 2+
- // example: https://docs.angularjs.org/guide/unit-testing#using-beforeall-
- function isAngularTestWrapper(node) {
- return (node.type === "CallExpression" || node.type === "OptionalCallExpression") && node.callee.type === "Identifier" && (node.callee.name === "async" || node.callee.name === "inject" || node.callee.name === "fakeAsync");
- }
- function isFunctionOrArrowExpression(node) {
- return node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression";
- }
- function isFunctionOrArrowExpressionWithBody(node) {
- return node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression" && node.body.type === "BlockStatement";
- }
- function isUnitTestSetUp(n) {
- var unitTestSetUpRe = /^(before|after)(Each|All)$/;
- return n.callee.type === "Identifier" && unitTestSetUpRe.test(n.callee.name) && n.arguments.length === 1;
- }
- function isTheOnlyJSXElementInMarkdown(options, path$$1) {
- if (options.parentParser !== "markdown" && options.parentParser !== "mdx") {
- return false;
- }
- var node = path$$1.getNode();
- if (!node.expression || !isJSXNode(node.expression)) {
- return false;
- }
- var parent = path$$1.getParentNode();
- return parent.type === "Program" && parent.body.length == 1;
- }
- function willPrintOwnComments(path$$1) {
- var node = path$$1.getValue();
- var parent = path$$1.getParentNode();
- return (node && (isJSXNode(node) || hasFlowShorthandAnnotationComment(node) || parent && parent.type === "CallExpression" && (hasFlowAnnotationComment(node.leadingComments) || hasFlowAnnotationComment(node.trailingComments))) || parent && (parent.type === "JSXSpreadAttribute" || parent.type === "JSXSpreadChild" || parent.type === "UnionTypeAnnotation" || parent.type === "TSUnionType" || (parent.type === "ClassDeclaration" || parent.type === "ClassExpression") && parent.superClass === node)) && !hasIgnoreComment$1(path$$1);
- }
- function canAttachComment(node) {
- return node.type && node.type !== "CommentBlock" && node.type !== "CommentLine" && node.type !== "Line" && node.type !== "Block" && node.type !== "EmptyStatement" && node.type !== "TemplateElement" && node.type !== "Import" && !(node.callee && node.callee.type === "Import");
- }
- function printComment$1(commentPath, options) {
- var comment = commentPath.getValue();
- switch (comment.type) {
- case "CommentBlock":
- case "Block":
- {
- if (isIndentableBlockComment(comment)) {
- var printed = printIndentableBlockComment(comment); // We need to prevent an edge case of a previous trailing comment
- // printed as a `lineSuffix` which causes the comments to be
- // interleaved. See https://github.com/prettier/prettier/issues/4412
- if (comment.trailing && !hasNewline$2(options.originalText, options.locStart(comment), {
- backwards: true
- })) {
- return concat$4([hardline$3, printed]);
- }
- return printed;
- }
- var isInsideFlowComment = options.originalText.substr(options.locEnd(comment) - 3, 3) === "*-/";
- return "/*" + comment.value + (isInsideFlowComment ? "*-/" : "*/");
- }
- case "CommentLine":
- case "Line":
- // Print shebangs with the proper comment characters
- if (options.originalText.slice(options.locStart(comment)).startsWith("#!")) {
- return "#!" + comment.value.trimRight();
- }
- return "//" + comment.value.trimRight();
- default:
- throw new Error("Not a comment: " + JSON.stringify(comment));
- }
- }
- function isIndentableBlockComment(comment) {
- // If the comment has multiple lines and every line starts with a star
- // we can fix the indentation of each line. The stars in the `/*` and
- // `*/` delimiters are not included in the comment value, so add them
- // back first.
- var lines = `*${comment.value}*`.split("\n");
- return lines.length > 1 && lines.every(function (line) {
- return line.trim()[0] === "*";
- });
- }
- function printIndentableBlockComment(comment) {
- var lines = comment.value.split("\n");
- return concat$4(["/*", join$2(hardline$3, lines.map(function (line, index) {
- return index === 0 ? line.trimRight() : " " + (index < lines.length - 1 ? line.trim() : line.trimLeft());
- })), "*/"]);
- }
- function rawText(node) {
- return node.extra ? node.extra.raw : node.raw;
- }
- function identity$1(x) {
- return x;
- }
- var printerEstree = {
- preprocess: preprocess_1,
- print: genericPrint,
- embed: embed_1,
- insertPragma,
- massageAstNode: clean_1,
- hasPrettierIgnore,
- willPrintOwnComments,
- canAttachComment,
- printComment: printComment$1,
- isBlockComment: comments$3.isBlockComment,
- handleComments: {
- ownLine: comments$3.handleOwnLineComment,
- endOfLine: comments$3.handleEndOfLineComment,
- remaining: comments$3.handleRemainingComment
- }
- };
- var _require$$0$builders$2 = doc.builders;
- var concat$7 = _require$$0$builders$2.concat;
- var hardline$5 = _require$$0$builders$2.hardline;
- var indent$4 = _require$$0$builders$2.indent;
- var join$5 = _require$$0$builders$2.join;
- function genericPrint$1(path$$1, options, print) {
- var node = path$$1.getValue();
- switch (node.type) {
- case "JsonRoot":
- return concat$7([path$$1.call(print, "node"), hardline$5]);
- case "ArrayExpression":
- return node.elements.length === 0 ? "[]" : concat$7(["[", indent$4(concat$7([hardline$5, join$5(concat$7([",", hardline$5]), path$$1.map(print, "elements"))])), hardline$5, "]"]);
- case "ObjectExpression":
- return node.properties.length === 0 ? "{}" : concat$7(["{", indent$4(concat$7([hardline$5, join$5(concat$7([",", hardline$5]), path$$1.map(print, "properties"))])), hardline$5, "}"]);
- case "ObjectProperty":
- return concat$7([path$$1.call(print, "key"), ": ", path$$1.call(print, "value")]);
- case "UnaryExpression":
- return concat$7([node.operator === "+" ? "" : node.operator, path$$1.call(print, "argument")]);
- case "NullLiteral":
- return "null";
- case "BooleanLiteral":
- return node.value ? "true" : "false";
- case "StringLiteral":
- case "NumericLiteral":
- return JSON.stringify(node.value);
- case "Identifier":
- return JSON.stringify(node.name);
- default:
- /* istanbul ignore next */
- throw new Error("unknown type: " + JSON.stringify(node.type));
- }
- }
- function clean$2(node, newNode
- /*, parent*/
- ) {
- delete newNode.start;
- delete newNode.end;
- delete newNode.extra;
- delete newNode.loc;
- delete newNode.comments;
- if (node.type === "Identifier") {
- return {
- type: "StringLiteral",
- value: node.name
- };
- }
- if (node.type === "UnaryExpression" && node.operator === "+") {
- return newNode.argument;
- }
- }
- var printerEstreeJson = {
- preprocess: preprocess_1,
- print: genericPrint$1,
- massageAstNode: clean$2
- };
- var CATEGORY_COMMON = "Common"; // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js
- var commonOptions = {
- bracketSpacing: {
- since: "0.0.0",
- category: CATEGORY_COMMON,
- type: "boolean",
- default: true,
- description: "Print spaces between brackets.",
- oppositeDescription: "Do not print spaces between brackets."
- },
- singleQuote: {
- since: "0.0.0",
- category: CATEGORY_COMMON,
- type: "boolean",
- default: false,
- description: "Use single quotes instead of double quotes."
- },
- proseWrap: {
- since: "1.8.2",
- category: CATEGORY_COMMON,
- type: "choice",
- default: [{
- since: "1.8.2",
- value: true
- }, {
- since: "1.9.0",
- value: "preserve"
- }],
- description: "How to wrap prose.",
- choices: [{
- since: "1.9.0",
- value: "always",
- description: "Wrap prose if it exceeds the print width."
- }, {
- since: "1.9.0",
- value: "never",
- description: "Do not wrap prose."
- }, {
- since: "1.9.0",
- value: "preserve",
- description: "Wrap prose as-is."
- }, {
- value: false,
- deprecated: "1.9.0",
- redirect: "never"
- }, {
- value: true,
- deprecated: "1.9.0",
- redirect: "always"
- }]
- }
- };
- var CATEGORY_JAVASCRIPT = "JavaScript"; // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js
- var options$3 = {
- arrowParens: {
- since: "1.9.0",
- category: CATEGORY_JAVASCRIPT,
- type: "choice",
- default: "avoid",
- description: "Include parentheses around a sole arrow function parameter.",
- choices: [{
- value: "avoid",
- description: "Omit parens when possible. Example: `x => x`"
- }, {
- value: "always",
- description: "Always include parens. Example: `(x) => x`"
- }]
- },
- bracketSpacing: commonOptions.bracketSpacing,
- jsxBracketSameLine: {
- since: "0.17.0",
- category: CATEGORY_JAVASCRIPT,
- type: "boolean",
- default: false,
- description: "Put > on the last line instead of at a new line."
- },
- semi: {
- since: "1.0.0",
- category: CATEGORY_JAVASCRIPT,
- type: "boolean",
- default: true,
- description: "Print semicolons.",
- oppositeDescription: "Do not print semicolons, except at the beginning of lines which may need them."
- },
- singleQuote: commonOptions.singleQuote,
- jsxSingleQuote: {
- since: "1.15.0",
- category: CATEGORY_JAVASCRIPT,
- type: "boolean",
- default: false,
- description: "Use single quotes in JSX."
- },
- trailingComma: {
- since: "0.0.0",
- category: CATEGORY_JAVASCRIPT,
- type: "choice",
- default: [{
- since: "0.0.0",
- value: false
- }, {
- since: "0.19.0",
- value: "none"
- }],
- description: "Print trailing commas wherever possible when multi-line.",
- choices: [{
- value: "none",
- description: "No trailing commas."
- }, {
- value: "es5",
- description: "Trailing commas where valid in ES5 (objects, arrays, etc.)"
- }, {
- value: "all",
- description: "Trailing commas wherever possible (including function arguments)."
- }, {
- value: true,
- deprecated: "0.19.0",
- redirect: "es5"
- }, {
- value: false,
- deprecated: "0.19.0",
- redirect: "none"
- }]
- }
- };
- var createLanguage = function createLanguage(linguistData, _ref) {
- var extend = _ref.extend,
- override = _ref.override;
- var language = {};
- for (var key in linguistData) {
- var newKey = key === "languageId" ? "linguistLanguageId" : key;
- language[newKey] = linguistData[key];
- }
- if (extend) {
- for (var _key in extend) {
- language[_key] = (language[_key] || []).concat(extend[_key]);
- }
- }
- for (var _key2 in override) {
- language[_key2] = override[_key2];
- }
- return language;
- };
- var name$1 = "JavaScript";
- var type = "programming";
- var tmScope = "source.js";
- var aceMode = "javascript";
- var codemirrorMode = "javascript";
- var codemirrorMimeType = "text/javascript";
- var color = "#f1e05a";
- var aliases = ["js", "node"];
- var extensions = [".js", "._js", ".bones", ".es", ".es6", ".frag", ".gs", ".jake", ".jsb", ".jscad", ".jsfl", ".jsm", ".jss", ".mjs", ".njs", ".pac", ".sjs", ".ssjs", ".xsjs", ".xsjslib"];
- var filenames = ["Jakefile"];
- var interpreters = ["node"];
- var languageId = 183;
- var javascript = {
- name: name$1,
- type: type,
- tmScope: tmScope,
- aceMode: aceMode,
- codemirrorMode: codemirrorMode,
- codemirrorMimeType: codemirrorMimeType,
- color: color,
- aliases: aliases,
- extensions: extensions,
- filenames: filenames,
- interpreters: interpreters,
- languageId: languageId
- };
- var javascript$1 = Object.freeze({
- name: name$1,
- type: type,
- tmScope: tmScope,
- aceMode: aceMode,
- codemirrorMode: codemirrorMode,
- codemirrorMimeType: codemirrorMimeType,
- color: color,
- aliases: aliases,
- extensions: extensions,
- filenames: filenames,
- interpreters: interpreters,
- languageId: languageId,
- default: javascript
- });
- var name$2 = "JSX";
- var type$1 = "programming";
- var group$3 = "JavaScript";
- var extensions$1 = [".jsx"];
- var tmScope$1 = "source.js.jsx";
- var aceMode$1 = "javascript";
- var codemirrorMode$1 = "jsx";
- var codemirrorMimeType$1 = "text/jsx";
- var languageId$1 = 178;
- var jsx = {
- name: name$2,
- type: type$1,
- group: group$3,
- extensions: extensions$1,
- tmScope: tmScope$1,
- aceMode: aceMode$1,
- codemirrorMode: codemirrorMode$1,
- codemirrorMimeType: codemirrorMimeType$1,
- languageId: languageId$1
- };
- var jsx$1 = Object.freeze({
- name: name$2,
- type: type$1,
- group: group$3,
- extensions: extensions$1,
- tmScope: tmScope$1,
- aceMode: aceMode$1,
- codemirrorMode: codemirrorMode$1,
- codemirrorMimeType: codemirrorMimeType$1,
- languageId: languageId$1,
- default: jsx
- });
- var name$3 = "TypeScript";
- var type$2 = "programming";
- var color$1 = "#2b7489";
- var aliases$1 = ["ts"];
- var extensions$2 = [".ts", ".tsx"];
- var tmScope$2 = "source.ts";
- var aceMode$2 = "typescript";
- var codemirrorMode$2 = "javascript";
- var codemirrorMimeType$2 = "application/typescript";
- var languageId$2 = 378;
- var typescript = {
- name: name$3,
- type: type$2,
- color: color$1,
- aliases: aliases$1,
- extensions: extensions$2,
- tmScope: tmScope$2,
- aceMode: aceMode$2,
- codemirrorMode: codemirrorMode$2,
- codemirrorMimeType: codemirrorMimeType$2,
- languageId: languageId$2
- };
- var typescript$1 = Object.freeze({
- name: name$3,
- type: type$2,
- color: color$1,
- aliases: aliases$1,
- extensions: extensions$2,
- tmScope: tmScope$2,
- aceMode: aceMode$2,
- codemirrorMode: codemirrorMode$2,
- codemirrorMimeType: codemirrorMimeType$2,
- languageId: languageId$2,
- default: typescript
- });
- var name$4 = "JSON";
- var type$3 = "data";
- var tmScope$3 = "source.json";
- var group$4 = "JavaScript";
- var aceMode$3 = "json";
- var codemirrorMode$3 = "javascript";
- var codemirrorMimeType$3 = "application/json";
- var searchable = false;
- var extensions$3 = [".json", ".avsc", ".geojson", ".gltf", ".JSON-tmLanguage", ".jsonl", ".tfstate", ".tfstate.backup", ".topojson", ".webapp", ".webmanifest"];
- var filenames$1 = [".arcconfig", ".htmlhintrc", ".tern-config", ".tern-project", "composer.lock", "mcmod.info"];
- var languageId$3 = 174;
- var json$2 = {
- name: name$4,
- type: type$3,
- tmScope: tmScope$3,
- group: group$4,
- aceMode: aceMode$3,
- codemirrorMode: codemirrorMode$3,
- codemirrorMimeType: codemirrorMimeType$3,
- searchable: searchable,
- extensions: extensions$3,
- filenames: filenames$1,
- languageId: languageId$3
- };
- var json$3 = Object.freeze({
- name: name$4,
- type: type$3,
- tmScope: tmScope$3,
- group: group$4,
- aceMode: aceMode$3,
- codemirrorMode: codemirrorMode$3,
- codemirrorMimeType: codemirrorMimeType$3,
- searchable: searchable,
- extensions: extensions$3,
- filenames: filenames$1,
- languageId: languageId$3,
- default: json$2
- });
- var name$5 = "JSON with Comments";
- var type$4 = "data";
- var group$5 = "JSON";
- var tmScope$4 = "source.js";
- var aceMode$4 = "javascript";
- var codemirrorMode$4 = "javascript";
- var codemirrorMimeType$4 = "text/javascript";
- var aliases$2 = ["jsonc"];
- var extensions$4 = [".sublime-build", ".sublime-commands", ".sublime-completions", ".sublime-keymap", ".sublime-macro", ".sublime-menu", ".sublime-mousemap", ".sublime-project", ".sublime-settings", ".sublime-theme", ".sublime-workspace", ".sublime_metrics", ".sublime_session"];
- var filenames$2 = [".babelrc", ".eslintrc.json", ".jscsrc", ".jshintrc", ".jslintrc", "tsconfig.json"];
- var languageId$4 = 423;
- var jsonWithComments = {
- name: name$5,
- type: type$4,
- group: group$5,
- tmScope: tmScope$4,
- aceMode: aceMode$4,
- codemirrorMode: codemirrorMode$4,
- codemirrorMimeType: codemirrorMimeType$4,
- aliases: aliases$2,
- extensions: extensions$4,
- filenames: filenames$2,
- languageId: languageId$4
- };
- var jsonWithComments$1 = Object.freeze({
- name: name$5,
- type: type$4,
- group: group$5,
- tmScope: tmScope$4,
- aceMode: aceMode$4,
- codemirrorMode: codemirrorMode$4,
- codemirrorMimeType: codemirrorMimeType$4,
- aliases: aliases$2,
- extensions: extensions$4,
- filenames: filenames$2,
- languageId: languageId$4,
- default: jsonWithComments
- });
- var name$6 = "JSON5";
- var type$5 = "data";
- var extensions$5 = [".json5"];
- var tmScope$5 = "source.js";
- var aceMode$5 = "javascript";
- var codemirrorMode$5 = "javascript";
- var codemirrorMimeType$5 = "application/json";
- var languageId$5 = 175;
- var json5 = {
- name: name$6,
- type: type$5,
- extensions: extensions$5,
- tmScope: tmScope$5,
- aceMode: aceMode$5,
- codemirrorMode: codemirrorMode$5,
- codemirrorMimeType: codemirrorMimeType$5,
- languageId: languageId$5
- };
- var json5$1 = Object.freeze({
- name: name$6,
- type: type$5,
- extensions: extensions$5,
- tmScope: tmScope$5,
- aceMode: aceMode$5,
- codemirrorMode: codemirrorMode$5,
- codemirrorMimeType: codemirrorMimeType$5,
- languageId: languageId$5,
- default: json5
- });
- var require$$0$21 = ( javascript$1 && javascript ) || javascript$1;
- var require$$1$8 = ( jsx$1 && jsx ) || jsx$1;
- var require$$2$10 = ( typescript$1 && typescript ) || typescript$1;
- var require$$3$3 = ( json$3 && json$2 ) || json$3;
- var require$$4$2 = ( jsonWithComments$1 && jsonWithComments ) || jsonWithComments$1;
- var require$$5$1 = ( json5$1 && json5 ) || json5$1;
- var languages = [createLanguage(require$$0$21, {
- override: {
- since: "0.0.0",
- parsers: ["babel", "flow"],
- vscodeLanguageIds: ["javascript"]
- },
- extend: {
- interpreters: ["nodejs"]
- }
- }), createLanguage(require$$0$21, {
- override: {
- name: "Flow",
- since: "0.0.0",
- parsers: ["babel", "flow"],
- vscodeLanguageIds: ["javascript"],
- aliases: [],
- filenames: [],
- extensions: [".js.flow"]
- }
- }), createLanguage(require$$1$8, {
- override: {
- since: "0.0.0",
- parsers: ["babel", "flow"],
- vscodeLanguageIds: ["javascriptreact"]
- }
- }), createLanguage(require$$2$10, {
- override: {
- since: "1.4.0",
- parsers: ["typescript"],
- vscodeLanguageIds: ["typescript", "typescriptreact"]
- }
- }), createLanguage(require$$3$3, {
- override: {
- name: "JSON.stringify",
- since: "1.13.0",
- parsers: ["json-stringify"],
- vscodeLanguageIds: ["json"],
- extensions: [],
- // .json file defaults to json instead of json-stringify
- filenames: ["package.json", "package-lock.json", "composer.json"]
- }
- }), createLanguage(require$$3$3, {
- override: {
- since: "1.5.0",
- parsers: ["json"],
- vscodeLanguageIds: ["json"]
- },
- extend: {
- filenames: [".prettierrc"]
- }
- }), createLanguage(require$$4$2, {
- override: {
- since: "1.5.0",
- parsers: ["json"],
- vscodeLanguageIds: ["jsonc"]
- },
- extend: {
- filenames: [".eslintrc"]
- }
- }), createLanguage(require$$5$1, {
- override: {
- since: "1.13.0",
- parsers: ["json5"],
- vscodeLanguageIds: ["json5"]
- }
- })];
- var printers = {
- estree: printerEstree,
- "estree-json": printerEstreeJson
- };
- var languageJs = {
- languages,
- options: options$3,
- printers
- };
- var index$12 = ["a", "abbr", "acronym", "address", "applet", "area", "article", "aside", "audio", "b", "base", "basefont", "bdi", "bdo", "bgsound", "big", "blink", "blockquote", "body", "br", "button", "canvas", "caption", "center", "cite", "code", "col", "colgroup", "command", "content", "data", "datalist", "dd", "del", "details", "dfn", "dialog", "dir", "div", "dl", "dt", "element", "em", "embed", "fieldset", "figcaption", "figure", "font", "footer", "form", "frame", "frameset", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hgroup", "hr", "html", "i", "iframe", "image", "img", "input", "ins", "isindex", "kbd", "keygen", "label", "legend", "li", "link", "listing", "main", "map", "mark", "marquee", "math", "menu", "menuitem", "meta", "meter", "multicol", "nav", "nextid", "nobr", "noembed", "noframes", "noscript", "object", "ol", "optgroup", "option", "output", "p", "param", "picture", "plaintext", "pre", "progress", "q", "rb", "rbc", "rp", "rt", "rtc", "ruby", "s", "samp", "script", "section", "select", "shadow", "slot", "small", "source", "spacer", "span", "strike", "strong", "style", "sub", "summary", "sup", "svg", "table", "tbody", "td", "template", "textarea", "tfoot", "th", "thead", "time", "title", "tr", "track", "tt", "u", "ul", "var", "video", "wbr", "xmp"];
- var htmlTagNames = Object.freeze({
- default: index$12
- });
- var htmlTagNames$1 = ( htmlTagNames && index$12 ) || htmlTagNames;
- function clean$3(ast, newObj, parent) {
- ["raw", // front-matter
- "raws", "sourceIndex", "source", "before", "after", "trailingComma"].forEach(function (name) {
- delete newObj[name];
- });
- if (ast.type === "yaml") {
- delete newObj.value;
- } // --insert-pragma
- if (ast.type === "css-comment" && parent.type === "css-root" && parent.nodes.length !== 0 && ( // first non-front-matter comment
- parent.nodes[0] === ast || (parent.nodes[0].type === "yaml" || parent.nodes[0].type === "toml") && parent.nodes[1] === ast)) {
- /**
- * something
- *
- * @format
- */
- delete newObj.text; // standalone pragma
- if (/^\*\s*@(format|prettier)\s*$/.test(ast.text)) {
- return null;
- }
- }
- if (ast.type === "media-query" || ast.type === "media-query-list" || ast.type === "media-feature-expression") {
- delete newObj.value;
- }
- if (ast.type === "css-rule") {
- delete newObj.params;
- }
- if (ast.type === "selector-combinator") {
- newObj.value = newObj.value.replace(/\s+/g, " ");
- }
- if (ast.type === "media-feature") {
- newObj.value = newObj.value.replace(/ /g, "");
- }
- if (ast.type === "value-word" && (ast.isColor && ast.isHex || ["initial", "inherit", "unset", "revert"].indexOf(newObj.value.replace().toLowerCase()) !== -1) || ast.type === "media-feature" || ast.type === "selector-root-invalid" || ast.type === "selector-pseudo") {
- newObj.value = newObj.value.toLowerCase();
- }
- if (ast.type === "css-decl") {
- newObj.prop = newObj.prop.toLowerCase();
- }
- if (ast.type === "css-atrule" || ast.type === "css-import") {
- newObj.name = newObj.name.toLowerCase();
- }
- if (ast.type === "value-number") {
- newObj.unit = newObj.unit.toLowerCase();
- }
- if ((ast.type === "media-feature" || ast.type === "media-keyword" || ast.type === "media-type" || ast.type === "media-unknown" || ast.type === "media-url" || ast.type === "media-value" || ast.type === "selector-attribute" || ast.type === "selector-string" || ast.type === "selector-class" || ast.type === "selector-combinator" || ast.type === "value-string") && newObj.value) {
- newObj.value = cleanCSSStrings(newObj.value);
- }
- if (ast.type === "selector-attribute") {
- newObj.attribute = newObj.attribute.trim();
- if (newObj.namespace) {
- if (typeof newObj.namespace === "string") {
- newObj.namespace = newObj.namespace.trim();
- if (newObj.namespace.length === 0) {
- newObj.namespace = true;
- }
- }
- }
- if (newObj.value) {
- newObj.value = newObj.value.trim().replace(/^['"]|['"]$/g, "");
- delete newObj.quoted;
- }
- }
- if ((ast.type === "media-value" || ast.type === "media-type" || ast.type === "value-number" || ast.type === "selector-root-invalid" || ast.type === "selector-class" || ast.type === "selector-combinator" || ast.type === "selector-tag") && newObj.value) {
- newObj.value = newObj.value.replace(/([\d.eE+-]+)([a-zA-Z]*)/g, function (match, numStr, unit) {
- var num = Number(numStr);
- return isNaN(num) ? match : num + unit.toLowerCase();
- });
- }
- if (ast.type === "selector-tag") {
- var lowercasedValue = ast.value.toLowerCase();
- if (htmlTagNames$1.indexOf(lowercasedValue) !== -1) {
- newObj.value = lowercasedValue;
- }
- if (["from", "to"].indexOf(lowercasedValue) !== -1) {
- newObj.value = lowercasedValue;
- }
- } // Workaround when `postcss-values-parser` parse `not`, `and` or `or` keywords as `value-func`
- if (ast.type === "css-atrule" && ast.name.toLowerCase() === "supports") {
- delete newObj.value;
- } // Workaround for SCSS nested properties
- if (ast.type === "selector-unknown") {
- delete newObj.value;
- }
- }
- function cleanCSSStrings(value) {
- return value.replace(/'/g, '"').replace(/\\([^a-fA-F\d])/g, "$1");
- }
- var clean_1$2 = clean$3;
- var _require$$0$builders$3 = doc.builders;
- var hardline$7 = _require$$0$builders$3.hardline;
- var literalline$3 = _require$$0$builders$3.literalline;
- var concat$9 = _require$$0$builders$3.concat;
- var markAsRoot$1 = _require$$0$builders$3.markAsRoot;
- var mapDoc$4 = doc.utils.mapDoc;
- function embed$2(path$$1, print, textToDoc
- /*, options */
- ) {
- var node = path$$1.getValue();
- if (node.type === "yaml") {
- return markAsRoot$1(concat$9(["---", hardline$7, node.value.trim() ? replaceNewlinesWithLiterallines(textToDoc(node.value, {
- parser: "yaml"
- })) : "", "---", hardline$7]));
- }
- return null;
- function replaceNewlinesWithLiterallines(doc$$2) {
- return mapDoc$4(doc$$2, function (currentDoc) {
- return typeof currentDoc === "string" && currentDoc.includes("\n") ? concat$9(currentDoc.split(/(\n)/g).map(function (v, i) {
- return i % 2 === 0 ? v : literalline$3;
- })) : currentDoc;
- });
- }
- }
- var embed_1$2 = embed$2;
- var DELIMITER_MAP = {
- "---": "yaml",
- "+++": "toml"
- };
- function parse$5(text) {
- var delimiterRegex = Object.keys(DELIMITER_MAP).map(escapeStringRegexp).join("|");
- var match = text.match( // trailing spaces after delimiters are allowed
- new RegExp(`^(${delimiterRegex})[^\\n\\S]*\\n(?:([\\s\\S]*?)\\n)?\\1[^\\n\\S]*(\\n|$)`));
- if (match === null) {
- return {
- frontMatter: null,
- content: text
- };
- }
- var raw = match[0].replace(/\n$/, "");
- var delimiter = match[1];
- var value = match[2];
- return {
- frontMatter: {
- type: DELIMITER_MAP[delimiter],
- value,
- raw
- },
- content: match[0].replace(/[^\n]/g, " ") + text.slice(match[0].length)
- };
- }
- var frontMatter = parse$5;
- function hasPragma$1(text) {
- return pragma.hasPragma(frontMatter(text).content);
- }
- function insertPragma$3(text) {
- var _parseFrontMatter = frontMatter(text),
- frontMatter$$1 = _parseFrontMatter.frontMatter,
- content = _parseFrontMatter.content;
- return (frontMatter$$1 ? frontMatter$$1.raw + "\n\n" : "") + pragma.insertPragma(content);
- }
- var pragma$2 = {
- hasPragma: hasPragma$1,
- insertPragma: insertPragma$3
- };
- var colorAdjusterFunctions = ["red", "green", "blue", "alpha", "a", "rgb", "hue", "h", "saturation", "s", "lightness", "l", "whiteness", "w", "blackness", "b", "tint", "shade", "blend", "blenda", "contrast", "hsl", "hsla", "hwb", "hwba"];
- function getAncestorCounter(path$$1, typeOrTypes) {
- var types = [].concat(typeOrTypes);
- var counter = -1;
- var ancestorNode;
- while (ancestorNode = path$$1.getParentNode(++counter)) {
- if (types.indexOf(ancestorNode.type) !== -1) {
- return counter;
- }
- }
- return -1;
- }
- function getAncestorNode$1(path$$1, typeOrTypes) {
- var counter = getAncestorCounter(path$$1, typeOrTypes);
- return counter === -1 ? null : path$$1.getParentNode(counter);
- }
- function getPropOfDeclNode$1(path$$1) {
- var declAncestorNode = getAncestorNode$1(path$$1, "css-decl");
- return declAncestorNode && declAncestorNode.prop && declAncestorNode.prop.toLowerCase();
- }
- function isSCSS$1(parser, text) {
- var hasExplicitParserChoice = parser === "less" || parser === "scss";
- var IS_POSSIBLY_SCSS = /(\w\s*: [^}:]+|#){|@import[^\n]+(url|,)/;
- return hasExplicitParserChoice ? parser === "scss" : IS_POSSIBLY_SCSS.test(text);
- }
- function isWideKeywords$1(value) {
- return ["initial", "inherit", "unset", "revert"].indexOf(value.toLowerCase()) !== -1;
- }
- function isKeyframeAtRuleKeywords$1(path$$1, value) {
- var atRuleAncestorNode = getAncestorNode$1(path$$1, "css-atrule");
- return atRuleAncestorNode && atRuleAncestorNode.name && atRuleAncestorNode.name.toLowerCase().endsWith("keyframes") && ["from", "to"].indexOf(value.toLowerCase()) !== -1;
- }
- function maybeToLowerCase$1(value) {
- return value.includes("$") || value.includes("@") || value.includes("#") || value.startsWith("%") || value.startsWith("--") || value.startsWith(":--") || value.includes("(") && value.includes(")") ? value : value.toLowerCase();
- }
- function insideValueFunctionNode$1(path$$1, functionName) {
- var funcAncestorNode = getAncestorNode$1(path$$1, "value-func");
- return funcAncestorNode && funcAncestorNode.value && funcAncestorNode.value.toLowerCase() === functionName;
- }
- function insideICSSRuleNode$1(path$$1) {
- var ruleAncestorNode = getAncestorNode$1(path$$1, "css-rule");
- return ruleAncestorNode && ruleAncestorNode.raws && ruleAncestorNode.raws.selector && (ruleAncestorNode.raws.selector.startsWith(":import") || ruleAncestorNode.raws.selector.startsWith(":export"));
- }
- function insideAtRuleNode$1(path$$1, atRuleNameOrAtRuleNames) {
- var atRuleNames = [].concat(atRuleNameOrAtRuleNames);
- var atRuleAncestorNode = getAncestorNode$1(path$$1, "css-atrule");
- return atRuleAncestorNode && atRuleNames.indexOf(atRuleAncestorNode.name.toLowerCase()) !== -1;
- }
- function insideURLFunctionInImportAtRuleNode$1(path$$1) {
- var node = path$$1.getValue();
- var atRuleAncestorNode = getAncestorNode$1(path$$1, "css-atrule");
- return atRuleAncestorNode && atRuleAncestorNode.name === "import" && node.groups[0].value === "url" && node.groups.length === 2;
- }
- function isURLFunctionNode$1(node) {
- return node.type === "value-func" && node.value.toLowerCase() === "url";
- }
- function isLastNode$1(path$$1, node) {
- var parentNode = path$$1.getParentNode();
- if (!parentNode) {
- return false;
- }
- var nodes = parentNode.nodes;
- return nodes && nodes.indexOf(node) === nodes.length - 1;
- }
- function isHTMLTag$1(value) {
- return htmlTagNames$1.indexOf(value.toLowerCase()) !== -1;
- }
- function isDetachedRulesetDeclarationNode$1(node) {
- // If a Less file ends up being parsed with the SCSS parser, Less
- // variable declarations will be parsed as atrules with names ending
- // with a colon, so keep the original case then.
- if (!node.selector) {
- return false;
- }
- return typeof node.selector === "string" && /^@.+:.*$/.test(node.selector) || node.selector.value && /^@.+:.*$/.test(node.selector.value);
- }
- function isForKeywordNode$1(node) {
- return node.type === "value-word" && ["from", "through", "end"].indexOf(node.value) !== -1;
- }
- function isIfElseKeywordNode$1(node) {
- return node.type === "value-word" && ["and", "or", "not"].indexOf(node.value) !== -1;
- }
- function isEachKeywordNode$1(node) {
- return node.type === "value-word" && node.value === "in";
- }
- function isMultiplicationNode$1(node) {
- return node.type === "value-operator" && node.value === "*";
- }
- function isDivisionNode$1(node) {
- return node.type === "value-operator" && node.value === "/";
- }
- function isAdditionNode$1(node) {
- return node.type === "value-operator" && node.value === "+";
- }
- function isSubtractionNode$1(node) {
- return node.type === "value-operator" && node.value === "-";
- }
- function isModuloNode(node) {
- return node.type === "value-operator" && node.value === "%";
- }
- function isMathOperatorNode$1(node) {
- return isMultiplicationNode$1(node) || isDivisionNode$1(node) || isAdditionNode$1(node) || isSubtractionNode$1(node) || isModuloNode(node);
- }
- function isEqualityOperatorNode$1(node) {
- return node.type === "value-word" && ["==", "!="].indexOf(node.value) !== -1;
- }
- function isRelationalOperatorNode$1(node) {
- return node.type === "value-word" && ["<", ">", "<=", ">="].indexOf(node.value) !== -1;
- }
- function isSCSSControlDirectiveNode$1(node) {
- return node.type === "css-atrule" && ["if", "else", "for", "each", "while"].indexOf(node.name) !== -1;
- }
- function isSCSSNestedPropertyNode(node) {
- if (!node.selector) {
- return false;
- }
- return node.selector.replace(/\/\*.*?\*\//, "").replace(/\/\/.*?\n/, "").trim().endsWith(":");
- }
- function isDetachedRulesetCallNode$1(node) {
- return node.raws && node.raws.params && /^\(\s*\)$/.test(node.raws.params);
- }
- function isTemplatePlaceholderNode$1(node) {
- return node.name.startsWith("prettier-placeholder");
- }
- function isTemplatePropNode$1(node) {
- return node.prop.startsWith("@prettier-placeholder");
- }
- function isPostcssSimpleVarNode$1(currentNode, nextNode) {
- return currentNode.value === "$$" && currentNode.type === "value-func" && nextNode && nextNode.type === "value-word" && !nextNode.raws.before;
- }
- function hasComposesNode$1(node) {
- return node.value && node.value.type === "value-root" && node.value.group && node.value.group.type === "value-value" && node.prop.toLowerCase() === "composes";
- }
- function hasParensAroundNode$1(node) {
- return node.value && node.value.group && node.value.group.group && node.value.group.group.type === "value-paren_group" && node.value.group.group.open !== null && node.value.group.group.close !== null;
- }
- function hasEmptyRawBefore$1(node) {
- return node.raws && node.raws.before === "";
- }
- function isKeyValuePairNode$1(node) {
- return node.type === "value-comma_group" && node.groups && node.groups[1] && node.groups[1].type === "value-colon";
- }
- function isKeyValuePairInParenGroupNode(node) {
- return node.type === "value-paren_group" && node.groups && node.groups[0] && isKeyValuePairNode$1(node.groups[0]);
- }
- function isSCSSMapItemNode$1(path$$1) {
- var node = path$$1.getValue(); // Ignore empty item (i.e. `$key: ()`)
- if (node.groups.length === 0) {
- return false;
- }
- var parentParentNode = path$$1.getParentNode(1); // Check open parens contain key/value pair (i.e. `(key: value)` and `(key: (value, other-value)`)
- if (!isKeyValuePairInParenGroupNode(node) && !(parentParentNode && isKeyValuePairInParenGroupNode(parentParentNode))) {
- return false;
- }
- var declNode = getAncestorNode$1(path$$1, "css-decl"); // SCSS map declaration (i.e. `$map: (key: value, other-key: other-value)`)
- if (declNode && declNode.prop && declNode.prop.startsWith("$")) {
- return true;
- } // List as value of key inside SCSS map (i.e. `$map: (key: (value other-value other-other-value))`)
- if (isKeyValuePairInParenGroupNode(parentParentNode)) {
- return true;
- } // SCSS Map is argument of function (i.e. `func((key: value, other-key: other-value))`)
- if (parentParentNode.type === "value-func") {
- return true;
- }
- return false;
- }
- function isInlineValueCommentNode$1(node) {
- return node.type === "value-comment" && node.inline;
- }
- function isHashNode$1(node) {
- return node.type === "value-word" && node.value === "#";
- }
- function isLeftCurlyBraceNode$1(node) {
- return node.type === "value-word" && node.value === "{";
- }
- function isRightCurlyBraceNode$1(node) {
- return node.type === "value-word" && node.value === "}";
- }
- function isWordNode$1(node) {
- return ["value-word", "value-atword"].indexOf(node.type) !== -1;
- }
- function isColonNode$1(node) {
- return node.type === "value-colon";
- }
- function isMediaAndSupportsKeywords$1(node) {
- return node.value && ["not", "and", "or"].indexOf(node.value.toLowerCase()) !== -1;
- }
- function isColorAdjusterFuncNode$1(node) {
- if (node.type !== "value-func") {
- return false;
- }
- return colorAdjusterFunctions.indexOf(node.value.toLowerCase()) !== -1;
- }
- var utils$6 = {
- getAncestorCounter,
- getAncestorNode: getAncestorNode$1,
- getPropOfDeclNode: getPropOfDeclNode$1,
- maybeToLowerCase: maybeToLowerCase$1,
- insideValueFunctionNode: insideValueFunctionNode$1,
- insideICSSRuleNode: insideICSSRuleNode$1,
- insideAtRuleNode: insideAtRuleNode$1,
- insideURLFunctionInImportAtRuleNode: insideURLFunctionInImportAtRuleNode$1,
- isKeyframeAtRuleKeywords: isKeyframeAtRuleKeywords$1,
- isHTMLTag: isHTMLTag$1,
- isWideKeywords: isWideKeywords$1,
- isSCSS: isSCSS$1,
- isLastNode: isLastNode$1,
- isSCSSControlDirectiveNode: isSCSSControlDirectiveNode$1,
- isDetachedRulesetDeclarationNode: isDetachedRulesetDeclarationNode$1,
- isRelationalOperatorNode: isRelationalOperatorNode$1,
- isEqualityOperatorNode: isEqualityOperatorNode$1,
- isMultiplicationNode: isMultiplicationNode$1,
- isDivisionNode: isDivisionNode$1,
- isAdditionNode: isAdditionNode$1,
- isSubtractionNode: isSubtractionNode$1,
- isModuloNode,
- isMathOperatorNode: isMathOperatorNode$1,
- isEachKeywordNode: isEachKeywordNode$1,
- isForKeywordNode: isForKeywordNode$1,
- isURLFunctionNode: isURLFunctionNode$1,
- isIfElseKeywordNode: isIfElseKeywordNode$1,
- hasComposesNode: hasComposesNode$1,
- hasParensAroundNode: hasParensAroundNode$1,
- hasEmptyRawBefore: hasEmptyRawBefore$1,
- isSCSSNestedPropertyNode,
- isDetachedRulesetCallNode: isDetachedRulesetCallNode$1,
- isTemplatePlaceholderNode: isTemplatePlaceholderNode$1,
- isTemplatePropNode: isTemplatePropNode$1,
- isPostcssSimpleVarNode: isPostcssSimpleVarNode$1,
- isKeyValuePairNode: isKeyValuePairNode$1,
- isKeyValuePairInParenGroupNode,
- isSCSSMapItemNode: isSCSSMapItemNode$1,
- isInlineValueCommentNode: isInlineValueCommentNode$1,
- isHashNode: isHashNode$1,
- isLeftCurlyBraceNode: isLeftCurlyBraceNode$1,
- isRightCurlyBraceNode: isRightCurlyBraceNode$1,
- isWordNode: isWordNode$1,
- isColonNode: isColonNode$1,
- isMediaAndSupportsKeywords: isMediaAndSupportsKeywords$1,
- isColorAdjusterFuncNode: isColorAdjusterFuncNode$1
- };
- var insertPragma$2 = pragma$2.insertPragma;
- var printNumber$2 = util$1.printNumber;
- var printString$2 = util$1.printString;
- var hasIgnoreComment$2 = util$1.hasIgnoreComment;
- var hasNewline$3 = util$1.hasNewline;
- var isNextLineEmpty$3 = utilShared.isNextLineEmpty;
- var _require$$3$builders = doc.builders;
- var concat$8 = _require$$3$builders.concat;
- var join$6 = _require$$3$builders.join;
- var line$5 = _require$$3$builders.line;
- var hardline$6 = _require$$3$builders.hardline;
- var softline$3 = _require$$3$builders.softline;
- var group$6 = _require$$3$builders.group;
- var fill$3 = _require$$3$builders.fill;
- var indent$5 = _require$$3$builders.indent;
- var dedent$3 = _require$$3$builders.dedent;
- var ifBreak$2 = _require$$3$builders.ifBreak;
- var removeLines$2 = doc.utils.removeLines;
- var getAncestorNode = utils$6.getAncestorNode;
- var getPropOfDeclNode = utils$6.getPropOfDeclNode;
- var maybeToLowerCase = utils$6.maybeToLowerCase;
- var insideValueFunctionNode = utils$6.insideValueFunctionNode;
- var insideICSSRuleNode = utils$6.insideICSSRuleNode;
- var insideAtRuleNode = utils$6.insideAtRuleNode;
- var insideURLFunctionInImportAtRuleNode = utils$6.insideURLFunctionInImportAtRuleNode;
- var isKeyframeAtRuleKeywords = utils$6.isKeyframeAtRuleKeywords;
- var isHTMLTag = utils$6.isHTMLTag;
- var isWideKeywords = utils$6.isWideKeywords;
- var isSCSS = utils$6.isSCSS;
- var isLastNode = utils$6.isLastNode;
- var isSCSSControlDirectiveNode = utils$6.isSCSSControlDirectiveNode;
- var isDetachedRulesetDeclarationNode = utils$6.isDetachedRulesetDeclarationNode;
- var isRelationalOperatorNode = utils$6.isRelationalOperatorNode;
- var isEqualityOperatorNode = utils$6.isEqualityOperatorNode;
- var isMultiplicationNode = utils$6.isMultiplicationNode;
- var isDivisionNode = utils$6.isDivisionNode;
- var isAdditionNode = utils$6.isAdditionNode;
- var isSubtractionNode = utils$6.isSubtractionNode;
- var isMathOperatorNode = utils$6.isMathOperatorNode;
- var isEachKeywordNode = utils$6.isEachKeywordNode;
- var isForKeywordNode = utils$6.isForKeywordNode;
- var isURLFunctionNode = utils$6.isURLFunctionNode;
- var isIfElseKeywordNode = utils$6.isIfElseKeywordNode;
- var hasComposesNode = utils$6.hasComposesNode;
- var hasParensAroundNode = utils$6.hasParensAroundNode;
- var hasEmptyRawBefore = utils$6.hasEmptyRawBefore;
- var isKeyValuePairNode = utils$6.isKeyValuePairNode;
- var isDetachedRulesetCallNode = utils$6.isDetachedRulesetCallNode;
- var isTemplatePlaceholderNode = utils$6.isTemplatePlaceholderNode;
- var isTemplatePropNode = utils$6.isTemplatePropNode;
- var isPostcssSimpleVarNode = utils$6.isPostcssSimpleVarNode;
- var isSCSSMapItemNode = utils$6.isSCSSMapItemNode;
- var isInlineValueCommentNode = utils$6.isInlineValueCommentNode;
- var isHashNode = utils$6.isHashNode;
- var isLeftCurlyBraceNode = utils$6.isLeftCurlyBraceNode;
- var isRightCurlyBraceNode = utils$6.isRightCurlyBraceNode;
- var isWordNode = utils$6.isWordNode;
- var isColonNode = utils$6.isColonNode;
- var isMediaAndSupportsKeywords = utils$6.isMediaAndSupportsKeywords;
- var isColorAdjusterFuncNode = utils$6.isColorAdjusterFuncNode;
- function shouldPrintComma$1(options) {
- switch (options.trailingComma) {
- case "all":
- case "es5":
- return true;
- case "none":
- default:
- return false;
- }
- }
- function genericPrint$2(path$$1, options, print) {
- var node = path$$1.getValue();
- /* istanbul ignore if */
- if (!node) {
- return "";
- }
- if (typeof node === "string") {
- return node;
- }
- switch (node.type) {
- case "yaml":
- case "toml":
- return concat$8([node.raw, hardline$6]);
- case "css-root":
- {
- var nodes = printNodeSequence(path$$1, options, print);
- if (nodes.parts.length) {
- return concat$8([nodes, hardline$6]);
- }
- return nodes;
- }
- case "css-comment":
- {
- if (node.raws.content) {
- return node.raws.content;
- }
- var text = options.originalText.slice(options.locStart(node), options.locEnd(node));
- var rawText = node.raws.text || node.text; // Workaround a bug where the location is off.
- // https://github.com/postcss/postcss-scss/issues/63
- if (text.indexOf(rawText) === -1) {
- if (node.raws.inline) {
- return concat$8(["// ", rawText]);
- }
- return concat$8(["/* ", rawText, " */"]);
- }
- return text;
- }
- case "css-rule":
- {
- return concat$8([path$$1.call(print, "selector"), node.important ? " !important" : "", node.nodes ? concat$8([" {", node.nodes.length > 0 ? indent$5(concat$8([hardline$6, printNodeSequence(path$$1, options, print)])) : "", hardline$6, "}", isDetachedRulesetDeclarationNode(node) ? ";" : ""]) : ";"]);
- }
- case "css-decl":
- {
- var parentNode = path$$1.getParentNode();
- return concat$8([node.raws.before.replace(/[\s;]/g, ""), insideICSSRuleNode(path$$1) ? node.prop : maybeToLowerCase(node.prop), node.raws.between.trim() === ":" ? ":" : node.raws.between.trim(), node.extend ? "" : " ", hasComposesNode(node) ? removeLines$2(path$$1.call(print, "value")) : path$$1.call(print, "value"), node.raws.important ? node.raws.important.replace(/\s*!\s*important/i, " !important") : node.important ? " !important" : "", node.raws.scssDefault ? node.raws.scssDefault.replace(/\s*!default/i, " !default") : node.scssDefault ? " !default" : "", node.raws.scssGlobal ? node.raws.scssGlobal.replace(/\s*!global/i, " !global") : node.scssGlobal ? " !global" : "", node.nodes ? concat$8([" {", indent$5(concat$8([softline$3, printNodeSequence(path$$1, options, print)])), softline$3, "}"]) : isTemplatePropNode(node) && !parentNode.raws.semicolon && options.originalText[options.locEnd(node) - 1] !== ";" ? "" : ";"]);
- }
- case "css-atrule":
- {
- var _parentNode = path$$1.getParentNode();
- return concat$8(["@", // If a Less file ends up being parsed with the SCSS parser, Less
- // variable declarations will be parsed as at-rules with names ending
- // with a colon, so keep the original case then.
- isDetachedRulesetCallNode(node) || node.name.endsWith(":") ? node.name : maybeToLowerCase(node.name), node.params ? concat$8([isDetachedRulesetCallNode(node) ? "" : isTemplatePlaceholderNode(node) && /^\s*\n/.test(node.raws.afterName) ? /^\s*\n\s*\n/.test(node.raws.afterName) ? concat$8([hardline$6, hardline$6]) : hardline$6 : " ", path$$1.call(print, "params")]) : "", node.selector ? indent$5(concat$8([" ", path$$1.call(print, "selector")])) : "", node.value ? group$6(concat$8([" ", path$$1.call(print, "value"), isSCSSControlDirectiveNode(node) ? hasParensAroundNode(node) ? " " : line$5 : ""])) : node.name === "else" ? " " : "", node.nodes ? concat$8([isSCSSControlDirectiveNode(node) ? "" : " ", "{", indent$5(concat$8([node.nodes.length > 0 ? softline$3 : "", printNodeSequence(path$$1, options, print)])), softline$3, "}"]) : isTemplatePlaceholderNode(node) && !_parentNode.raws.semicolon && options.originalText[options.locEnd(node) - 1] !== ";" ? "" : ";"]);
- }
- // postcss-media-query-parser
- case "media-query-list":
- {
- var parts = [];
- path$$1.each(function (childPath) {
- var node = childPath.getValue();
- if (node.type === "media-query" && node.value === "") {
- return;
- }
- parts.push(childPath.call(print));
- }, "nodes");
- return group$6(indent$5(join$6(line$5, parts)));
- }
- case "media-query":
- {
- return concat$8([join$6(" ", path$$1.map(print, "nodes")), isLastNode(path$$1, node) ? "" : ","]);
- }
- case "media-type":
- {
- return adjustNumbers(adjustStrings(node.value, options));
- }
- case "media-feature-expression":
- {
- if (!node.nodes) {
- return node.value;
- }
- return concat$8(["(", concat$8(path$$1.map(print, "nodes")), ")"]);
- }
- case "media-feature":
- {
- return maybeToLowerCase(adjustStrings(node.value.replace(/ +/g, " "), options));
- }
- case "media-colon":
- {
- return concat$8([node.value, " "]);
- }
- case "media-value":
- {
- return adjustNumbers(adjustStrings(node.value, options));
- }
- case "media-keyword":
- {
- return adjustStrings(node.value, options);
- }
- case "media-url":
- {
- return adjustStrings(node.value.replace(/^url\(\s+/gi, "url(").replace(/\s+\)$/gi, ")"), options);
- }
- case "media-unknown":
- {
- return node.value;
- }
- // postcss-selector-parser
- case "selector-root":
- {
- return group$6(concat$8([insideAtRuleNode(path$$1, "custom-selector") ? concat$8([getAncestorNode(path$$1, "css-atrule").customSelector, line$5]) : "", join$6(concat$8([",", insideAtRuleNode(path$$1, ["extend", "custom-selector", "nest"]) ? line$5 : hardline$6]), path$$1.map(print, "nodes"))]));
- }
- case "selector-selector":
- {
- return group$6(indent$5(concat$8(path$$1.map(print, "nodes"))));
- }
- case "selector-comment":
- {
- return node.value;
- }
- case "selector-string":
- {
- return adjustStrings(node.value, options);
- }
- case "selector-tag":
- {
- var _parentNode2 = path$$1.getParentNode();
- var index = _parentNode2 && _parentNode2.nodes.indexOf(node);
- var prevNode = index && _parentNode2.nodes[index - 1];
- return concat$8([node.namespace ? concat$8([node.namespace === true ? "" : node.namespace.trim(), "|"]) : "", prevNode.type === "selector-nesting" ? node.value : adjustNumbers(isHTMLTag(node.value) || isKeyframeAtRuleKeywords(path$$1, node.value) ? node.value.toLowerCase() : node.value)]);
- }
- case "selector-id":
- {
- return concat$8(["#", node.value]);
- }
- case "selector-class":
- {
- return concat$8([".", adjustNumbers(adjustStrings(node.value, options))]);
- }
- case "selector-attribute":
- {
- return concat$8(["[", node.namespace ? concat$8([node.namespace === true ? "" : node.namespace.trim(), "|"]) : "", node.attribute.trim(), node.operator ? node.operator : "", node.value ? quoteAttributeValue(adjustStrings(node.value.trim(), options), options) : "", node.insensitive ? " i" : "", "]"]);
- }
- case "selector-combinator":
- {
- if (node.value === "+" || node.value === ">" || node.value === "~" || node.value === ">>>") {
- var _parentNode3 = path$$1.getParentNode();
- var _leading = _parentNode3.type === "selector-selector" && _parentNode3.nodes[0] === node ? "" : line$5;
- return concat$8([_leading, node.value, isLastNode(path$$1, node) ? "" : " "]);
- }
- var leading = node.value.trim().startsWith("(") ? line$5 : "";
- var value = adjustNumbers(adjustStrings(node.value.trim(), options)) || line$5;
- return concat$8([leading, value]);
- }
- case "selector-universal":
- {
- return concat$8([node.namespace ? concat$8([node.namespace === true ? "" : node.namespace.trim(), "|"]) : "", node.value]);
- }
- case "selector-pseudo":
- {
- return concat$8([maybeToLowerCase(node.value), node.nodes && node.nodes.length > 0 ? concat$8(["(", join$6(", ", path$$1.map(print, "nodes")), ")"]) : ""]);
- }
- case "selector-nesting":
- {
- return node.value;
- }
- case "selector-unknown":
- {
- var ruleAncestorNode = getAncestorNode(path$$1, "css-rule"); // Nested SCSS property
- if (ruleAncestorNode && ruleAncestorNode.isSCSSNesterProperty) {
- return adjustNumbers(adjustStrings(maybeToLowerCase(node.value), options));
- }
- return node.value;
- }
- // postcss-values-parser
- case "value-value":
- case "value-root":
- {
- return path$$1.call(print, "group");
- }
- case "value-comment":
- {
- return concat$8([node.inline ? "//" : "/*", node.value, node.inline ? "" : "*/"]);
- }
- case "value-comma_group":
- {
- var _parentNode4 = path$$1.getParentNode();
- var parentParentNode = path$$1.getParentNode(1);
- var declAncestorProp = getPropOfDeclNode(path$$1);
- var isGridValue = declAncestorProp && _parentNode4.type === "value-value" && (declAncestorProp === "grid" || declAncestorProp.startsWith("grid-template"));
- var atRuleAncestorNode = getAncestorNode(path$$1, "css-atrule");
- var isControlDirective = atRuleAncestorNode && isSCSSControlDirectiveNode(atRuleAncestorNode);
- var printed = path$$1.map(print, "groups");
- var _parts = [];
- var insideURLFunction = insideValueFunctionNode(path$$1, "url");
- var insideSCSSInterpolationInString = false;
- var didBreak = false;
- for (var i = 0; i < node.groups.length; ++i) {
- _parts.push(printed[i]); // Ignore value inside `url()`
- if (insideURLFunction) {
- continue;
- }
- var iPrevNode = node.groups[i - 1];
- var iNode = node.groups[i];
- var iNextNode = node.groups[i + 1];
- var iNextNextNode = node.groups[i + 2]; // Ignore after latest node (i.e. before semicolon)
- if (!iNextNode) {
- continue;
- } // Ignore spaces before/after string interpolation (i.e. `"#{my-fn("_")}"`)
- var isStartSCSSinterpolationInString = iNode.type === "value-string" && iNode.value.startsWith("#{");
- var isEndingSCSSinterpolationInString = insideSCSSInterpolationInString && iNextNode.type === "value-string" && iNextNode.value.endsWith("}");
- if (isStartSCSSinterpolationInString || isEndingSCSSinterpolationInString) {
- insideSCSSInterpolationInString = !insideSCSSInterpolationInString;
- continue;
- }
- if (insideSCSSInterpolationInString) {
- continue;
- } // Ignore colon (i.e. `:`)
- if (isColonNode(iNode) || isColonNode(iNextNode)) {
- continue;
- } // Ignore `@` in Less (i.e. `@@var;`)
- if (iNode.type === "value-atword" && iNode.value === "") {
- continue;
- } // Ignore `~` in Less (i.e. `content: ~"^//* some horrible but needed css hack";`)
- if (iNode.value === "~") {
- continue;
- } // Ignore escape `\`
- if (iNode.value && iNode.value.indexOf("\\") !== -1 && iNextNode && iNextNode.type !== "value-comment") {
- continue;
- } // Ignore escaped `/`
- if (iPrevNode && iPrevNode.value && iPrevNode.value.indexOf("\\") === iPrevNode.value.length - 1 && iNode.type === "value-operator" && iNode.value === "/") {
- continue;
- } // Ignore `\` (i.e. `$variable: \@small;`)
- if (iNode.value === "\\") {
- continue;
- } // Ignore `$$` (i.e. `background-color: $$(style)Color;`)
- if (isPostcssSimpleVarNode(iNode, iNextNode)) {
- continue;
- } // Ignore spaces after `#` and after `{` and before `}` in SCSS interpolation (i.e. `#{variable}`)
- if (isHashNode(iNode) || isLeftCurlyBraceNode(iNode) || isRightCurlyBraceNode(iNextNode) || isLeftCurlyBraceNode(iNextNode) && hasEmptyRawBefore(iNextNode) || isRightCurlyBraceNode(iNode) && hasEmptyRawBefore(iNextNode)) {
- continue;
- } // Ignore css variables and interpolation in SCSS (i.e. `--#{$var}`)
- if (iNode.value === "--" && isHashNode(iNextNode)) {
- continue;
- } // Formatting math operations
- var isMathOperator = isMathOperatorNode(iNode);
- var isNextMathOperator = isMathOperatorNode(iNextNode); // Print spaces before and after math operators beside SCSS interpolation as is
- // (i.e. `#{$var}+5`, `#{$var} +5`, `#{$var}+ 5`, `#{$var} + 5`)
- // (i.e. `5+#{$var}`, `5 +#{$var}`, `5+ #{$var}`, `5 + #{$var}`)
- if ((isMathOperator && isHashNode(iNextNode) || isNextMathOperator && isRightCurlyBraceNode(iNode)) && hasEmptyRawBefore(iNextNode)) {
- continue;
- } // Print spaces before and after addition and subtraction math operators as is in `calc` function
- // due to the fact that it is not valid syntax
- // (i.e. `calc(1px+1px)`, `calc(1px+ 1px)`, `calc(1px +1px)`, `calc(1px + 1px)`)
- if (insideValueFunctionNode(path$$1, "calc") && (isAdditionNode(iNode) || isAdditionNode(iNextNode) || isSubtractionNode(iNode) || isSubtractionNode(iNextNode)) && hasEmptyRawBefore(iNextNode)) {
- continue;
- } // Print spaces after `+` and `-` in color adjuster functions as is (e.g. `color(red l(+ 20%))`)
- // Adjusters with signed numbers (e.g. `color(red l(+20%))`) output as-is.
- var isColorAdjusterNode = (isAdditionNode(iNode) || isSubtractionNode(iNode)) && i === 0 && (iNextNode.type === "value-number" || iNextNode.isHex) && parentParentNode && isColorAdjusterFuncNode(parentParentNode) && !hasEmptyRawBefore(iNextNode);
- var requireSpaceBeforeOperator = iNextNextNode && iNextNextNode.type === "value-func" || iNextNextNode && isWordNode(iNextNextNode) || iNode.type === "value-func" || isWordNode(iNode);
- var requireSpaceAfterOperator = iNextNode.type === "value-func" || isWordNode(iNextNode) || iPrevNode && iPrevNode.type === "value-func" || iPrevNode && isWordNode(iPrevNode); // Formatting `/`, `+`, `-` sign
- if (!(isMultiplicationNode(iNextNode) || isMultiplicationNode(iNode)) && !insideValueFunctionNode(path$$1, "calc") && !isColorAdjusterNode && (isDivisionNode(iNextNode) && !requireSpaceBeforeOperator || isDivisionNode(iNode) && !requireSpaceAfterOperator || isAdditionNode(iNextNode) && !requireSpaceBeforeOperator || isAdditionNode(iNode) && !requireSpaceAfterOperator || isSubtractionNode(iNextNode) || isSubtractionNode(iNode)) && (hasEmptyRawBefore(iNextNode) || isMathOperator && (!iPrevNode || iPrevNode && isMathOperatorNode(iPrevNode)))) {
- continue;
- } // Add `hardline` after inline comment (i.e. `// comment\n foo: bar;`)
- if (isInlineValueCommentNode(iNode)) {
- _parts.push(hardline$6);
- continue;
- } // Handle keywords in SCSS control directive
- if (isControlDirective && (isEqualityOperatorNode(iNextNode) || isRelationalOperatorNode(iNextNode) || isIfElseKeywordNode(iNextNode) || isEachKeywordNode(iNode) || isForKeywordNode(iNode))) {
- _parts.push(" ");
- continue;
- } // At-rule `namespace` should be in one line
- if (atRuleAncestorNode && atRuleAncestorNode.name.toLowerCase() === "namespace") {
- _parts.push(" ");
- continue;
- } // Formatting `grid` property
- if (isGridValue) {
- if (iNode.source && iNextNode.source && iNode.source.start.line !== iNextNode.source.start.line) {
- _parts.push(hardline$6);
- didBreak = true;
- } else {
- _parts.push(" ");
- }
- continue;
- } // Add `space` before next math operation
- // Note: `grip` property have `/` delimiter and it is not math operation, so
- // `grid` property handles above
- if (isNextMathOperator) {
- _parts.push(" ");
- continue;
- } // Be default all values go through `line`
- _parts.push(line$5);
- }
- if (didBreak) {
- _parts.unshift(hardline$6);
- }
- if (isControlDirective) {
- return group$6(indent$5(concat$8(_parts)));
- } // Indent is not needed for import url when url is very long
- // and node has two groups
- // when type is value-comma_group
- // example @import url("verylongurl") projection,tv
- if (insideURLFunctionInImportAtRuleNode(path$$1)) {
- return group$6(fill$3(_parts));
- }
- return group$6(indent$5(fill$3(_parts)));
- }
- case "value-paren_group":
- {
- var _parentNode5 = path$$1.getParentNode();
- if (_parentNode5 && isURLFunctionNode(_parentNode5) && (node.groups.length === 1 || node.groups.length > 0 && node.groups[0].type === "value-comma_group" && node.groups[0].groups.length > 0 && node.groups[0].groups[0].type === "value-word" && node.groups[0].groups[0].value.startsWith("data:"))) {
- return concat$8([node.open ? path$$1.call(print, "open") : "", join$6(",", path$$1.map(print, "groups")), node.close ? path$$1.call(print, "close") : ""]);
- }
- if (!node.open) {
- var _printed = path$$1.map(print, "groups");
- var res = [];
- for (var _i = 0; _i < _printed.length; _i++) {
- if (_i !== 0) {
- res.push(concat$8([",", line$5]));
- }
- res.push(_printed[_i]);
- }
- return group$6(indent$5(fill$3(res)));
- }
- var isSCSSMapItem = isSCSSMapItemNode(path$$1);
- return group$6(concat$8([node.open ? path$$1.call(print, "open") : "", indent$5(concat$8([softline$3, join$6(concat$8([",", line$5]), path$$1.map(function (childPath) {
- var node = childPath.getValue();
- var printed = print(childPath); // Key/Value pair in open paren already indented
- if (isKeyValuePairNode(node) && node.type === "value-comma_group" && node.groups && node.groups[2] && node.groups[2].type === "value-paren_group") {
- printed.contents.contents.parts[1] = group$6(printed.contents.contents.parts[1]);
- return group$6(dedent$3(printed));
- }
- return printed;
- }, "groups"))])), ifBreak$2(isSCSS(options.parser, options.originalText) && isSCSSMapItem && shouldPrintComma$1(options) ? "," : ""), softline$3, node.close ? path$$1.call(print, "close") : ""]), {
- shouldBreak: isSCSSMapItem
- });
- }
- case "value-func":
- {
- return concat$8([node.value, insideAtRuleNode(path$$1, "supports") && isMediaAndSupportsKeywords(node) ? " " : "", path$$1.call(print, "group")]);
- }
- case "value-paren":
- {
- return node.value;
- }
- case "value-number":
- {
- return concat$8([printCssNumber(node.value), maybeToLowerCase(node.unit)]);
- }
- case "value-operator":
- {
- return node.value;
- }
- case "value-word":
- {
- if (node.isColor && node.isHex || isWideKeywords(node.value)) {
- return node.value.toLowerCase();
- }
- return node.value;
- }
- case "value-colon":
- {
- return concat$8([node.value, // Don't add spaces on `:` in `url` function (i.e. `url(fbglyph: cross-outline, fig-white)`)
- insideValueFunctionNode(path$$1, "url") ? "" : line$5]);
- }
- case "value-comma":
- {
- return concat$8([node.value, " "]);
- }
- case "value-string":
- {
- return printString$2(node.raws.quote + node.value + node.raws.quote, options);
- }
- case "value-atword":
- {
- return concat$8(["@", node.value]);
- }
- case "value-unicode-range":
- {
- return node.value;
- }
- case "value-unknown":
- {
- return node.value;
- }
- default:
- /* istanbul ignore next */
- throw new Error(`Unknown postcss type ${JSON.stringify(node.type)}`);
- }
- }
- function printNodeSequence(path$$1, options, print) {
- var node = path$$1.getValue();
- var parts = [];
- var i = 0;
- path$$1.map(function (pathChild) {
- var prevNode = node.nodes[i - 1];
- if (prevNode && prevNode.type === "css-comment" && prevNode.text.trim() === "prettier-ignore") {
- var childNode = pathChild.getValue();
- parts.push(options.originalText.slice(options.locStart(childNode), options.locEnd(childNode)));
- } else {
- parts.push(pathChild.call(print));
- }
- if (i !== node.nodes.length - 1) {
- if (node.nodes[i + 1].type === "css-comment" && !hasNewline$3(options.originalText, options.locStart(node.nodes[i + 1]), {
- backwards: true
- }) && node.nodes[i].type !== "yaml" && node.nodes[i].type !== "toml" || node.nodes[i + 1].type === "css-atrule" && node.nodes[i + 1].name === "else" && node.nodes[i].type !== "css-comment") {
- parts.push(" ");
- } else {
- parts.push(hardline$6);
- if (isNextLineEmpty$3(options.originalText, pathChild.getValue(), options) && node.nodes[i].type !== "yaml" && node.nodes[i].type !== "toml") {
- parts.push(hardline$6);
- }
- }
- }
- i++;
- }, "nodes");
- return concat$8(parts);
- }
- var STRING_REGEX = /(['"])(?:(?!\1)[^\\]|\\[\s\S])*\1/g;
- var NUMBER_REGEX = /(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?/g;
- var STANDARD_UNIT_REGEX = /[a-zA-Z]+/g;
- var WORD_PART_REGEX = /[$@]?[a-zA-Z_\u0080-\uFFFF][\w\-\u0080-\uFFFF]*/g;
- var ADJUST_NUMBERS_REGEX = RegExp(STRING_REGEX.source + `|` + `(${WORD_PART_REGEX.source})?` + `(${NUMBER_REGEX.source})` + `(${STANDARD_UNIT_REGEX.source})?`, "g");
- function adjustStrings(value, options) {
- return value.replace(STRING_REGEX, function (match) {
- return printString$2(match, options);
- });
- }
- function quoteAttributeValue(value, options) {
- var quote = options.singleQuote ? "'" : '"';
- return value.includes('"') || value.includes("'") ? value : quote + value + quote;
- }
- function adjustNumbers(value) {
- return value.replace(ADJUST_NUMBERS_REGEX, function (match, quote, wordPart, number, unit) {
- return !wordPart && number ? (wordPart || "") + printCssNumber(number) + maybeToLowerCase(unit || "") : match;
- });
- }
- function printCssNumber(rawNumber) {
- return printNumber$2(rawNumber) // Remove trailing `.0`.
- .replace(/\.0(?=$|e)/, "");
- }
- var printerPostcss = {
- print: genericPrint$2,
- embed: embed_1$2,
- insertPragma: insertPragma$2,
- hasPrettierIgnore: hasIgnoreComment$2,
- massageAstNode: clean_1$2
- };
- var options$6 = {
- singleQuote: commonOptions.singleQuote
- };
- var name$7 = "CSS";
- var type$6 = "markup";
- var tmScope$6 = "source.css";
- var aceMode$6 = "css";
- var codemirrorMode$6 = "css";
- var codemirrorMimeType$6 = "text/css";
- var color$2 = "#563d7c";
- var extensions$6 = [".css"];
- var languageId$6 = 50;
- var css$2 = {
- name: name$7,
- type: type$6,
- tmScope: tmScope$6,
- aceMode: aceMode$6,
- codemirrorMode: codemirrorMode$6,
- codemirrorMimeType: codemirrorMimeType$6,
- color: color$2,
- extensions: extensions$6,
- languageId: languageId$6
- };
- var css$3 = Object.freeze({
- name: name$7,
- type: type$6,
- tmScope: tmScope$6,
- aceMode: aceMode$6,
- codemirrorMode: codemirrorMode$6,
- codemirrorMimeType: codemirrorMimeType$6,
- color: color$2,
- extensions: extensions$6,
- languageId: languageId$6,
- default: css$2
- });
- var name$8 = "PostCSS";
- var type$7 = "markup";
- var tmScope$7 = "source.postcss";
- var group$7 = "CSS";
- var extensions$7 = [".pcss"];
- var aceMode$7 = "text";
- var languageId$7 = 262764437;
- var postcss = {
- name: name$8,
- type: type$7,
- tmScope: tmScope$7,
- group: group$7,
- extensions: extensions$7,
- aceMode: aceMode$7,
- languageId: languageId$7
- };
- var postcss$1 = Object.freeze({
- name: name$8,
- type: type$7,
- tmScope: tmScope$7,
- group: group$7,
- extensions: extensions$7,
- aceMode: aceMode$7,
- languageId: languageId$7,
- default: postcss
- });
- var name$9 = "Less";
- var type$8 = "markup";
- var group$8 = "CSS";
- var extensions$8 = [".less"];
- var tmScope$8 = "source.css.less";
- var aceMode$8 = "less";
- var codemirrorMode$7 = "css";
- var codemirrorMimeType$7 = "text/css";
- var languageId$8 = 198;
- var less = {
- name: name$9,
- type: type$8,
- group: group$8,
- extensions: extensions$8,
- tmScope: tmScope$8,
- aceMode: aceMode$8,
- codemirrorMode: codemirrorMode$7,
- codemirrorMimeType: codemirrorMimeType$7,
- languageId: languageId$8
- };
- var less$1 = Object.freeze({
- name: name$9,
- type: type$8,
- group: group$8,
- extensions: extensions$8,
- tmScope: tmScope$8,
- aceMode: aceMode$8,
- codemirrorMode: codemirrorMode$7,
- codemirrorMimeType: codemirrorMimeType$7,
- languageId: languageId$8,
- default: less
- });
- var name$10 = "SCSS";
- var type$9 = "markup";
- var tmScope$9 = "source.scss";
- var group$9 = "CSS";
- var aceMode$9 = "scss";
- var codemirrorMode$8 = "css";
- var codemirrorMimeType$8 = "text/x-scss";
- var extensions$9 = [".scss"];
- var languageId$9 = 329;
- var scss = {
- name: name$10,
- type: type$9,
- tmScope: tmScope$9,
- group: group$9,
- aceMode: aceMode$9,
- codemirrorMode: codemirrorMode$8,
- codemirrorMimeType: codemirrorMimeType$8,
- extensions: extensions$9,
- languageId: languageId$9
- };
- var scss$1 = Object.freeze({
- name: name$10,
- type: type$9,
- tmScope: tmScope$9,
- group: group$9,
- aceMode: aceMode$9,
- codemirrorMode: codemirrorMode$8,
- codemirrorMimeType: codemirrorMimeType$8,
- extensions: extensions$9,
- languageId: languageId$9,
- default: scss
- });
- var require$$0$23 = ( css$3 && css$2 ) || css$3;
- var require$$1$9 = ( postcss$1 && postcss ) || postcss$1;
- var require$$2$11 = ( less$1 && less ) || less$1;
- var require$$3$4 = ( scss$1 && scss ) || scss$1;
- var languages$1 = [createLanguage(require$$0$23, {
- override: {
- since: "1.4.0",
- parsers: ["css"],
- vscodeLanguageIds: ["css"]
- }
- }), createLanguage(require$$1$9, {
- override: {
- since: "1.4.0",
- parsers: ["css"],
- vscodeLanguageIds: ["postcss"]
- },
- extend: {
- extensions: [".postcss"]
- }
- }), createLanguage(require$$2$11, {
- override: {
- since: "1.4.0",
- parsers: ["less"],
- vscodeLanguageIds: ["less"]
- }
- }), createLanguage(require$$3$4, {
- override: {
- since: "1.4.0",
- parsers: ["scss"],
- vscodeLanguageIds: ["scss"]
- }
- })];
- var printers$1 = {
- postcss: printerPostcss
- };
- var languageCss = {
- languages: languages$1,
- options: options$6,
- printers: printers$1
- };
- var _require$$0$builders$4 = doc.builders;
- var concat$10 = _require$$0$builders$4.concat;
- var join$7 = _require$$0$builders$4.join;
- var softline$4 = _require$$0$builders$4.softline;
- var hardline$8 = _require$$0$builders$4.hardline;
- var line$6 = _require$$0$builders$4.line;
- var group$10 = _require$$0$builders$4.group;
- var indent$6 = _require$$0$builders$4.indent;
- var ifBreak$3 = _require$$0$builders$4.ifBreak; // http://w3c.github.io/html/single-page.html#void-elements
- var voidTags = ["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr"]; // Formatter based on @glimmerjs/syntax's built-in test formatter:
- // https://github.com/glimmerjs/glimmer-vm/blob/master/packages/%40glimmer/syntax/lib/generation/print.ts
- function print(path$$1, options, print) {
- var n = path$$1.getValue();
- /* istanbul ignore if*/
- if (!n) {
- return "";
- }
- switch (n.type) {
- case "Program":
- {
- return group$10(join$7(softline$4, path$$1.map(print, "body").filter(function (text) {
- return text !== "";
- })));
- }
- case "ElementNode":
- {
- var tagFirstChar = n.tag[0];
- var isLocal = n.tag.indexOf(".") !== -1;
- var isGlimmerComponent = tagFirstChar.toUpperCase() === tagFirstChar || isLocal;
- var hasChildren = n.children.length > 0;
- var isVoid = isGlimmerComponent && !hasChildren || voidTags.indexOf(n.tag) !== -1;
- var closeTag = isVoid ? concat$10([" />", softline$4]) : ">";
- var _getParams = function _getParams(path$$1, print) {
- return indent$6(concat$10([n.attributes.length ? line$6 : "", join$7(line$6, path$$1.map(print, "attributes")), n.modifiers.length ? line$6 : "", join$7(line$6, path$$1.map(print, "modifiers")), n.comments.length ? line$6 : "", join$7(line$6, path$$1.map(print, "comments"))]));
- }; // The problem here is that I want to not break at all if the children
- // would not break but I need to force an indent, so I use a hardline.
- /**
- * What happens now:
- * <div>
- * Hello
- * </div>
- * ==>
- * <div>Hello</div>
- * This is due to me using hasChildren to decide to put the hardline in.
- * I would rather use a {DOES THE WHOLE THING NEED TO BREAK}
- */
- return concat$10([group$10(concat$10(["<", n.tag, _getParams(path$$1, print), n.blockParams.length ? ` as |${n.blockParams.join(" ")}|` : "", ifBreak$3(softline$4, ""), closeTag])), group$10(concat$10([indent$6(join$7(softline$4, [""].concat(path$$1.map(print, "children")))), ifBreak$3(hasChildren ? hardline$8 : "", ""), !isVoid ? concat$10(["</", n.tag, ">"]) : ""]))]);
- }
- case "BlockStatement":
- {
- var pp = path$$1.getParentNode(1);
- var isElseIf = pp && pp.inverse && pp.inverse.body[0] === n && pp.inverse.body[0].path.parts[0] === "if";
- var hasElseIf = n.inverse && n.inverse.body[0] && n.inverse.body[0].type === "BlockStatement" && n.inverse.body[0].path.parts[0] === "if";
- var indentElse = hasElseIf ? function (a) {
- return a;
- } : indent$6;
- if (n.inverse) {
- return concat$10([isElseIf ? concat$10(["{{else ", printPathParams(path$$1, print), "}}"]) : printOpenBlock(path$$1, print), indent$6(concat$10([hardline$8, path$$1.call(print, "program")])), n.inverse && !hasElseIf ? concat$10([hardline$8, "{{else}}"]) : "", n.inverse ? indentElse(concat$10([hardline$8, path$$1.call(print, "inverse")])) : "", isElseIf ? "" : concat$10([hardline$8, printCloseBlock(path$$1, print)])]);
- } else if (isElseIf) {
- return concat$10([concat$10(["{{else ", printPathParams(path$$1, print), "}}"]), indent$6(concat$10([hardline$8, path$$1.call(print, "program")]))]);
- }
- /**
- * I want this boolean to be: if params are going to cause a break,
- * not that it has params.
- */
- var hasParams = n.params.length > 0 || n.hash.pairs.length > 0;
- var _hasChildren = n.program.body.length > 0;
- return concat$10([printOpenBlock(path$$1, print), group$10(concat$10([indent$6(concat$10([softline$4, path$$1.call(print, "program")])), hasParams && _hasChildren ? hardline$8 : softline$4, printCloseBlock(path$$1, print)]))]);
- }
- case "ElementModifierStatement":
- case "MustacheStatement":
- {
- var _pp = path$$1.getParentNode(1);
- var isConcat = _pp && _pp.type === "ConcatStatement";
- return group$10(concat$10([n.escaped === false ? "{{{" : "{{", printPathParams(path$$1, print), isConcat ? "" : softline$4, n.escaped === false ? "}}}" : "}}"]));
- }
- case "SubExpression":
- {
- var params = getParams(path$$1, print);
- var printedParams = params.length > 0 ? indent$6(concat$10([line$6, group$10(join$7(line$6, params))])) : "";
- return group$10(concat$10(["(", printPath(path$$1, print), printedParams, softline$4, ")"]));
- }
- case "AttrNode":
- {
- var isText = n.value.type === "TextNode";
- if (isText && n.value.loc.start.column === n.value.loc.end.column) {
- return concat$10([n.name]);
- }
- var quote = isText ? '"' : "";
- return concat$10([n.name, "=", quote, path$$1.call(print, "value"), quote]);
- }
- case "ConcatStatement":
- {
- return concat$10(['"', group$10(indent$6(join$7(softline$4, path$$1.map(function (partPath) {
- return print(partPath);
- }, "parts").filter(function (a) {
- return a !== "";
- })))), '"']);
- }
- case "Hash":
- {
- return concat$10([join$7(line$6, path$$1.map(print, "pairs"))]);
- }
- case "HashPair":
- {
- return concat$10([n.key, "=", path$$1.call(print, "value")]);
- }
- case "TextNode":
- {
- var leadingSpace = "";
- var trailingSpace = ""; // preserve a space inside of an attribute node where whitespace present, when next to mustache statement.
- var inAttrNode = path$$1.stack.indexOf("attributes") >= 0;
- if (inAttrNode) {
- var parentNode = path$$1.getParentNode(0);
- var _isConcat = parentNode.type === "ConcatStatement";
- if (_isConcat) {
- var parts = parentNode.parts;
- var partIndex = parts.indexOf(n);
- if (partIndex > 0) {
- var partType = parts[partIndex - 1].type;
- var isMustache = partType === "MustacheStatement";
- if (isMustache) {
- leadingSpace = " ";
- }
- }
- if (partIndex < parts.length - 1) {
- var _partType = parts[partIndex + 1].type;
- var _isMustache = _partType === "MustacheStatement";
- if (_isMustache) {
- trailingSpace = " ";
- }
- }
- }
- }
- return n.chars.replace(/^\s+/, leadingSpace).replace(/\s+$/, trailingSpace);
- }
- case "MustacheCommentStatement":
- {
- var dashes = n.value.indexOf("}}") > -1 ? "--" : "";
- return concat$10(["{{!", dashes, n.value, dashes, "}}"]);
- }
- case "PathExpression":
- {
- return n.original;
- }
- case "BooleanLiteral":
- {
- return String(n.value);
- }
- case "CommentStatement":
- {
- return concat$10(["<!--", n.value, "-->"]);
- }
- case "StringLiteral":
- {
- return printStringLiteral(n.value, options);
- }
- case "NumberLiteral":
- {
- return String(n.value);
- }
- case "UndefinedLiteral":
- {
- return "undefined";
- }
- case "NullLiteral":
- {
- return "null";
- }
- /* istanbul ignore next */
- default:
- throw new Error("unknown glimmer type: " + JSON.stringify(n.type));
- }
- }
- /**
- * Prints a string literal with the correct surrounding quotes based on
- * `options.singleQuote` and the number of escaped quotes contained in
- * the string literal. This function is the glimmer equivalent of `printString`
- * in `common/util`, but has differences because of the way escaped characters
- * are treated in hbs string literals.
- * @param {string} stringLiteral - the string literal value
- * @param {object} options - the prettier options object
- */
- function printStringLiteral(stringLiteral, options) {
- var double = {
- quote: '"',
- regex: /"/g
- };
- var single = {
- quote: "'",
- regex: /'/g
- };
- var preferred = options.singleQuote ? single : double;
- var alternate = preferred === single ? double : single;
- var shouldUseAlternateQuote = false; // If `stringLiteral` contains at least one of the quote preferred for
- // enclosing the string, we might want to enclose with the alternate quote
- // instead, to minimize the number of escaped quotes.
- if (stringLiteral.includes(preferred.quote) || stringLiteral.includes(alternate.quote)) {
- var numPreferredQuotes = (stringLiteral.match(preferred.regex) || []).length;
- var numAlternateQuotes = (stringLiteral.match(alternate.regex) || []).length;
- shouldUseAlternateQuote = numPreferredQuotes > numAlternateQuotes;
- }
- var enclosingQuote = shouldUseAlternateQuote ? alternate : preferred;
- var escapedStringLiteral = stringLiteral.replace(enclosingQuote.regex, `\\${enclosingQuote.quote}`);
- return `${enclosingQuote.quote}${escapedStringLiteral}${enclosingQuote.quote}`;
- }
- function printPath(path$$1, print) {
- return path$$1.call(print, "path");
- }
- function getParams(path$$1, print) {
- var node = path$$1.getValue();
- var parts = [];
- if (node.params.length > 0) {
- parts = parts.concat(path$$1.map(print, "params"));
- }
- if (node.hash && node.hash.pairs.length > 0) {
- parts.push(path$$1.call(print, "hash"));
- }
- return parts;
- }
- function printPathParams(path$$1, print) {
- var parts = [];
- parts.push(printPath(path$$1, print));
- parts = parts.concat(getParams(path$$1, print));
- return indent$6(group$10(join$7(line$6, parts)));
- }
- function printBlockParams(path$$1) {
- var block = path$$1.getValue();
- if (!block.program || !block.program.blockParams.length) {
- return "";
- }
- return concat$10([" as |", block.program.blockParams.join(" "), "|"]);
- }
- function printOpenBlock(path$$1, print) {
- return group$10(concat$10(["{{#", printPathParams(path$$1, print), printBlockParams(path$$1), softline$4, "}}"]));
- }
- function printCloseBlock(path$$1, print) {
- return concat$10(["{{/", path$$1.call(print, "path"), "}}"]);
- }
- function clean$5(ast, newObj) {
- delete newObj.loc; // (Glimmer/HTML) ignore TextNode whitespace
- if (ast.type === "TextNode") {
- if (ast.chars.replace(/\s+/, "") === "") {
- return null;
- }
- newObj.chars = ast.chars.replace(/^\s+/, "").replace(/\s+$/, "");
- }
- }
- var printerGlimmer = {
- print,
- massageAstNode: clean$5
- };
- var name$11 = "Handlebars";
- var type$10 = "markup";
- var group$11 = "HTML";
- var aliases$3 = ["hbs", "htmlbars"];
- var extensions$10 = [".handlebars", ".hbs"];
- var tmScope$10 = "text.html.handlebars";
- var aceMode$10 = "handlebars";
- var languageId$10 = 155;
- var handlebars = {
- name: name$11,
- type: type$10,
- group: group$11,
- aliases: aliases$3,
- extensions: extensions$10,
- tmScope: tmScope$10,
- aceMode: aceMode$10,
- languageId: languageId$10
- };
- var handlebars$1 = Object.freeze({
- name: name$11,
- type: type$10,
- group: group$11,
- aliases: aliases$3,
- extensions: extensions$10,
- tmScope: tmScope$10,
- aceMode: aceMode$10,
- languageId: languageId$10,
- default: handlebars
- });
- var require$$0$24 = ( handlebars$1 && handlebars ) || handlebars$1;
- var languages$2 = [createLanguage(require$$0$24, {
- override: {
- since: null,
- // unreleased
- parsers: ["glimmer"],
- vscodeLanguageIds: ["handlebars"]
- }
- })];
- var printers$2 = {
- glimmer: printerGlimmer
- };
- var languageHandlebars = {
- languages: languages$2,
- printers: printers$2
- };
- function hasPragma$2(text) {
- return /^\s*#[^\n\S]*@(format|prettier)\s*(\n|$)/.test(text);
- }
- function insertPragma$5(text) {
- return "# @format\n\n" + text;
- }
- var pragma$4 = {
- hasPragma: hasPragma$2,
- insertPragma: insertPragma$5
- };
- var _require$$0$builders$5 = doc.builders;
- var concat$11 = _require$$0$builders$5.concat;
- var join$8 = _require$$0$builders$5.join;
- var hardline$9 = _require$$0$builders$5.hardline;
- var line$7 = _require$$0$builders$5.line;
- var softline$5 = _require$$0$builders$5.softline;
- var group$12 = _require$$0$builders$5.group;
- var indent$7 = _require$$0$builders$5.indent;
- var ifBreak$4 = _require$$0$builders$5.ifBreak;
- var hasIgnoreComment$3 = util$1.hasIgnoreComment;
- var isNextLineEmpty$4 = utilShared.isNextLineEmpty;
- var insertPragma$4 = pragma$4.insertPragma;
- function genericPrint$3(path$$1, options, print) {
- var n = path$$1.getValue();
- if (!n) {
- return "";
- }
- if (typeof n === "string") {
- return n;
- }
- switch (n.kind) {
- case "Document":
- {
- var parts = [];
- path$$1.map(function (pathChild, index) {
- parts.push(concat$11([pathChild.call(print)]));
- if (index !== n.definitions.length - 1) {
- parts.push(hardline$9);
- if (isNextLineEmpty$4(options.originalText, pathChild.getValue(), options)) {
- parts.push(hardline$9);
- }
- }
- }, "definitions");
- return concat$11([concat$11(parts), hardline$9]);
- }
- case "OperationDefinition":
- {
- var hasOperation = options.originalText[options.locStart(n)] !== "{";
- var hasName = !!n.name;
- return concat$11([hasOperation ? n.operation : "", hasOperation && hasName ? concat$11([" ", path$$1.call(print, "name")]) : "", n.variableDefinitions && n.variableDefinitions.length ? group$12(concat$11(["(", indent$7(concat$11([softline$5, join$8(concat$11([ifBreak$4("", ", "), softline$5]), path$$1.map(print, "variableDefinitions"))])), softline$5, ")"])) : "", printDirectives(path$$1, print, n), n.selectionSet ? !hasOperation && !hasName ? "" : " " : "", path$$1.call(print, "selectionSet")]);
- }
- case "FragmentDefinition":
- {
- return concat$11(["fragment ", path$$1.call(print, "name"), " on ", path$$1.call(print, "typeCondition"), printDirectives(path$$1, print, n), " ", path$$1.call(print, "selectionSet")]);
- }
- case "SelectionSet":
- {
- return concat$11(["{", indent$7(concat$11([hardline$9, join$8(hardline$9, path$$1.call(function (selectionsPath) {
- return printSequence(selectionsPath, options, print);
- }, "selections"))])), hardline$9, "}"]);
- }
- case "Field":
- {
- return group$12(concat$11([n.alias ? concat$11([path$$1.call(print, "alias"), ": "]) : "", path$$1.call(print, "name"), n.arguments.length > 0 ? group$12(concat$11(["(", indent$7(concat$11([softline$5, join$8(concat$11([ifBreak$4("", ", "), softline$5]), path$$1.call(function (argsPath) {
- return printSequence(argsPath, options, print);
- }, "arguments"))])), softline$5, ")"])) : "", printDirectives(path$$1, print, n), n.selectionSet ? " " : "", path$$1.call(print, "selectionSet")]));
- }
- case "Name":
- {
- return n.value;
- }
- case "StringValue":
- {
- if (n.block) {
- return concat$11(['"""', hardline$9, join$8(hardline$9, n.value.replace(/"""/g, "\\$&").split("\n")), hardline$9, '"""']);
- }
- return concat$11(['"', n.value.replace(/["\\]/g, "\\$&").replace(/\n/g, "\\n"), '"']);
- }
- case "IntValue":
- case "FloatValue":
- case "EnumValue":
- {
- return n.value;
- }
- case "BooleanValue":
- {
- return n.value ? "true" : "false";
- }
- case "NullValue":
- {
- return "null";
- }
- case "Variable":
- {
- return concat$11(["$", path$$1.call(print, "name")]);
- }
- case "ListValue":
- {
- return group$12(concat$11(["[", indent$7(concat$11([softline$5, join$8(concat$11([ifBreak$4("", ", "), softline$5]), path$$1.map(print, "values"))])), softline$5, "]"]));
- }
- case "ObjectValue":
- {
- return group$12(concat$11(["{", options.bracketSpacing && n.fields.length > 0 ? " " : "", indent$7(concat$11([softline$5, join$8(concat$11([ifBreak$4("", ", "), softline$5]), path$$1.map(print, "fields"))])), softline$5, ifBreak$4("", options.bracketSpacing && n.fields.length > 0 ? " " : ""), "}"]));
- }
- case "ObjectField":
- case "Argument":
- {
- return concat$11([path$$1.call(print, "name"), ": ", path$$1.call(print, "value")]);
- }
- case "Directive":
- {
- return concat$11(["@", path$$1.call(print, "name"), n.arguments.length > 0 ? group$12(concat$11(["(", indent$7(concat$11([softline$5, join$8(concat$11([ifBreak$4("", ", "), softline$5]), path$$1.call(function (argsPath) {
- return printSequence(argsPath, options, print);
- }, "arguments"))])), softline$5, ")"])) : ""]);
- }
- case "NamedType":
- {
- return path$$1.call(print, "name");
- }
- case "VariableDefinition":
- {
- return concat$11([path$$1.call(print, "variable"), ": ", path$$1.call(print, "type"), n.defaultValue ? concat$11([" = ", path$$1.call(print, "defaultValue")]) : ""]);
- }
- case "TypeExtensionDefinition":
- {
- return concat$11(["extend ", path$$1.call(print, "definition")]);
- }
- case "ObjectTypeExtension":
- case "ObjectTypeDefinition":
- {
- return concat$11([path$$1.call(print, "description"), n.description ? hardline$9 : "", n.kind === "ObjectTypeExtension" ? "extend " : "", "type ", path$$1.call(print, "name"), n.interfaces.length > 0 ? concat$11([" implements ", join$8(determineInterfaceSeparator(options.originalText.substr(options.locStart(n), options.locEnd(n))), path$$1.map(print, "interfaces"))]) : "", printDirectives(path$$1, print, n), n.fields.length > 0 ? concat$11([" {", indent$7(concat$11([hardline$9, join$8(hardline$9, path$$1.call(function (fieldsPath) {
- return printSequence(fieldsPath, options, print);
- }, "fields"))])), hardline$9, "}"]) : ""]);
- }
- case "FieldDefinition":
- {
- return concat$11([path$$1.call(print, "description"), n.description ? hardline$9 : "", path$$1.call(print, "name"), n.arguments.length > 0 ? group$12(concat$11(["(", indent$7(concat$11([softline$5, join$8(concat$11([ifBreak$4("", ", "), softline$5]), path$$1.call(function (argsPath) {
- return printSequence(argsPath, options, print);
- }, "arguments"))])), softline$5, ")"])) : "", ": ", path$$1.call(print, "type"), printDirectives(path$$1, print, n)]);
- }
- case "DirectiveDefinition":
- {
- return concat$11([path$$1.call(print, "description"), n.description ? hardline$9 : "", "directive ", "@", path$$1.call(print, "name"), n.arguments.length > 0 ? group$12(concat$11(["(", indent$7(concat$11([softline$5, join$8(concat$11([ifBreak$4("", ", "), softline$5]), path$$1.call(function (argsPath) {
- return printSequence(argsPath, options, print);
- }, "arguments"))])), softline$5, ")"])) : "", concat$11([" on ", join$8(" | ", path$$1.map(print, "locations"))])]);
- }
- case "EnumTypeExtension":
- case "EnumTypeDefinition":
- {
- return concat$11([path$$1.call(print, "description"), n.description ? hardline$9 : "", n.kind === "EnumTypeExtension" ? "extend " : "", "enum ", path$$1.call(print, "name"), printDirectives(path$$1, print, n), n.values.length > 0 ? concat$11([" {", indent$7(concat$11([hardline$9, join$8(hardline$9, path$$1.call(function (valuesPath) {
- return printSequence(valuesPath, options, print);
- }, "values"))])), hardline$9, "}"]) : ""]);
- }
- case "EnumValueDefinition":
- {
- return concat$11([path$$1.call(print, "description"), n.description ? hardline$9 : "", path$$1.call(print, "name"), printDirectives(path$$1, print, n)]);
- }
- case "InputValueDefinition":
- {
- return concat$11([path$$1.call(print, "description"), n.description ? n.description.block ? hardline$9 : line$7 : "", path$$1.call(print, "name"), ": ", path$$1.call(print, "type"), n.defaultValue ? concat$11([" = ", path$$1.call(print, "defaultValue")]) : "", printDirectives(path$$1, print, n)]);
- }
- case "InputObjectTypeExtension":
- case "InputObjectTypeDefinition":
- {
- return concat$11([path$$1.call(print, "description"), n.description ? hardline$9 : "", n.kind === "InputObjectTypeExtension" ? "extend " : "", "input ", path$$1.call(print, "name"), printDirectives(path$$1, print, n), n.fields.length > 0 ? concat$11([" {", indent$7(concat$11([hardline$9, join$8(hardline$9, path$$1.call(function (fieldsPath) {
- return printSequence(fieldsPath, options, print);
- }, "fields"))])), hardline$9, "}"]) : ""]);
- }
- case "SchemaDefinition":
- {
- return concat$11(["schema", printDirectives(path$$1, print, n), " {", n.operationTypes.length > 0 ? indent$7(concat$11([hardline$9, join$8(hardline$9, path$$1.call(function (opsPath) {
- return printSequence(opsPath, options, print);
- }, "operationTypes"))])) : "", hardline$9, "}"]);
- }
- case "OperationTypeDefinition":
- {
- return concat$11([path$$1.call(print, "operation"), ": ", path$$1.call(print, "type")]);
- }
- case "InterfaceTypeExtension":
- case "InterfaceTypeDefinition":
- {
- return concat$11([path$$1.call(print, "description"), n.description ? hardline$9 : "", n.kind === "InterfaceTypeExtension" ? "extend " : "", "interface ", path$$1.call(print, "name"), printDirectives(path$$1, print, n), n.fields.length > 0 ? concat$11([" {", indent$7(concat$11([hardline$9, join$8(hardline$9, path$$1.call(function (fieldsPath) {
- return printSequence(fieldsPath, options, print);
- }, "fields"))])), hardline$9, "}"]) : ""]);
- }
- case "FragmentSpread":
- {
- return concat$11(["...", path$$1.call(print, "name"), printDirectives(path$$1, print, n)]);
- }
- case "InlineFragment":
- {
- return concat$11(["...", n.typeCondition ? concat$11([" on ", path$$1.call(print, "typeCondition")]) : "", printDirectives(path$$1, print, n), " ", path$$1.call(print, "selectionSet")]);
- }
- case "UnionTypeExtension":
- case "UnionTypeDefinition":
- {
- return group$12(concat$11([path$$1.call(print, "description"), n.description ? hardline$9 : "", group$12(concat$11([n.kind === "UnionTypeExtension" ? "extend " : "", "union ", path$$1.call(print, "name"), printDirectives(path$$1, print, n), n.types.length > 0 ? concat$11([" =", ifBreak$4("", " "), indent$7(concat$11([ifBreak$4(concat$11([line$7, " "])), join$8(concat$11([line$7, "| "]), path$$1.map(print, "types"))]))]) : ""]))]));
- }
- case "ScalarTypeExtension":
- case "ScalarTypeDefinition":
- {
- return concat$11([path$$1.call(print, "description"), n.description ? hardline$9 : "", n.kind === "ScalarTypeExtension" ? "extend " : "", "scalar ", path$$1.call(print, "name"), printDirectives(path$$1, print, n)]);
- }
- case "NonNullType":
- {
- return concat$11([path$$1.call(print, "type"), "!"]);
- }
- case "ListType":
- {
- return concat$11(["[", path$$1.call(print, "type"), "]"]);
- }
- default:
- /* istanbul ignore next */
- throw new Error("unknown graphql type: " + JSON.stringify(n.kind));
- }
- }
- function printDirectives(path$$1, print, n) {
- if (n.directives.length === 0) {
- return "";
- }
- return concat$11([" ", group$12(indent$7(concat$11([softline$5, join$8(concat$11([ifBreak$4("", " "), softline$5]), path$$1.map(print, "directives"))])))]);
- }
- function printSequence(sequencePath, options, print) {
- var count = sequencePath.getValue().length;
- return sequencePath.map(function (path$$1, i) {
- var printed = print(path$$1);
- if (isNextLineEmpty$4(options.originalText, path$$1.getValue(), options) && i < count - 1) {
- return concat$11([printed, hardline$9]);
- }
- return printed;
- });
- }
- function canAttachComment$1(node) {
- return node.kind && node.kind !== "Comment";
- }
- function printComment$2(commentPath) {
- var comment = commentPath.getValue();
- if (comment.kind === "Comment") {
- return "#" + comment.value.trimRight();
- }
- throw new Error("Not a comment: " + JSON.stringify(comment));
- }
- function determineInterfaceSeparator(originalSource) {
- var start = originalSource.indexOf("implements");
- if (start === -1) {
- throw new Error("Must implement interfaces: " + originalSource);
- }
- var end = originalSource.indexOf("{");
- if (end === -1) {
- end = originalSource.length;
- }
- return originalSource.substr(start, end).includes("&") ? " & " : ", ";
- }
- function clean$6(node, newNode
- /*, parent*/
- ) {
- delete newNode.loc;
- delete newNode.comments;
- }
- var printerGraphql = {
- print: genericPrint$3,
- massageAstNode: clean$6,
- hasPrettierIgnore: hasIgnoreComment$3,
- insertPragma: insertPragma$4,
- printComment: printComment$2,
- canAttachComment: canAttachComment$1
- };
- var options$9 = {
- bracketSpacing: commonOptions.bracketSpacing
- };
- var name$12 = "GraphQL";
- var type$11 = "data";
- var extensions$11 = [".graphql", ".gql"];
- var tmScope$11 = "source.graphql";
- var aceMode$11 = "text";
- var languageId$11 = 139;
- var graphql = {
- name: name$12,
- type: type$11,
- extensions: extensions$11,
- tmScope: tmScope$11,
- aceMode: aceMode$11,
- languageId: languageId$11
- };
- var graphql$1 = Object.freeze({
- name: name$12,
- type: type$11,
- extensions: extensions$11,
- tmScope: tmScope$11,
- aceMode: aceMode$11,
- languageId: languageId$11,
- default: graphql
- });
- var require$$0$25 = ( graphql$1 && graphql ) || graphql$1;
- var languages$3 = [createLanguage(require$$0$25, {
- override: {
- since: "1.5.0",
- parsers: ["graphql"],
- vscodeLanguageIds: ["graphql"]
- }
- })];
- var printers$3 = {
- graphql: printerGraphql
- };
- var languageGraphql = {
- languages: languages$3,
- options: options$9,
- printers: printers$3
- };
- var json$6 = {"cjkPattern":"[\\u02ea-\\u02eb\\u1100-\\u11ff\\u2e80-\\u2e99\\u2e9b-\\u2ef3\\u2f00-\\u2fd5\\u3000-\\u303f\\u3041-\\u3096\\u3099-\\u309f\\u30a1-\\u30fa\\u30fc-\\u30ff\\u3105-\\u312e\\u3131-\\u318e\\u3190-\\u3191\\u3196-\\u31ba\\u31c0-\\u31e3\\u31f0-\\u321e\\u322a-\\u3247\\u3260-\\u327e\\u328a-\\u32b0\\u32c0-\\u32cb\\u32d0-\\u32fe\\u3300-\\u3370\\u337b-\\u337f\\u33e0-\\u33fe\\u3400-\\u4db5\\u4e00-\\u9fea\\ua960-\\ua97c\\uac00-\\ud7a3\\ud7b0-\\ud7c6\\ud7cb-\\ud7fb\\uf900-\\ufa6d\\ufa70-\\ufad9\\ufe10-\\ufe1f\\ufe30-\\ufe6f\\uff00-\\uffef]|[\\ud840-\\ud868\\ud86a-\\ud86c\\ud86f-\\ud872\\ud874-\\ud879][\\udc00-\\udfff]|\\ud82c[\\udc00-\\udd1e]|\\ud83c[\\ude00\\ude50-\\ude51]|\\ud869[\\udc00-\\uded6\\udf00-\\udfff]|\\ud86d[\\udc00-\\udf34\\udf40-\\udfff]|\\ud86e[\\udc00-\\udc1d\\udc20-\\udfff]|\\ud873[\\udc00-\\udea1\\udeb0-\\udfff]|\\ud87a[\\udc00-\\udfe0]|\\ud87e[\\udc00-\\ude1d]","kPattern":"[\\u1100-\\u11ff\\u3001-\\u3003\\u3008-\\u3011\\u3013-\\u301f\\u302e-\\u3030\\u3037\\u30fb\\u3131-\\u318e\\u3200-\\u321e\\u3260-\\u327e\\ua960-\\ua97c\\uac00-\\ud7a3\\ud7b0-\\ud7c6\\ud7cb-\\ud7fb\\ufe45-\\ufe46\\uff61-\\uff65\\uffa0-\\uffbe\\uffc2-\\uffc7\\uffca-\\uffcf\\uffd2-\\uffd7\\uffda-\\uffdc]","punctuationPattern":"[\\u0021-\\u002f\\u003a-\\u0040\\u005b-\\u0060\\u007b-\\u007e\\u00a1\\u00a7\\u00ab\\u00b6-\\u00b7\\u00bb\\u00bf\\u037e\\u0387\\u055a-\\u055f\\u0589-\\u058a\\u05be\\u05c0\\u05c3\\u05c6\\u05f3-\\u05f4\\u0609-\\u060a\\u060c-\\u060d\\u061b\\u061e-\\u061f\\u066a-\\u066d\\u06d4\\u0700-\\u070d\\u07f7-\\u07f9\\u0830-\\u083e\\u085e\\u0964-\\u0965\\u0970\\u09fd\\u0af0\\u0df4\\u0e4f\\u0e5a-\\u0e5b\\u0f04-\\u0f12\\u0f14\\u0f3a-\\u0f3d\\u0f85\\u0fd0-\\u0fd4\\u0fd9-\\u0fda\\u104a-\\u104f\\u10fb\\u1360-\\u1368\\u1400\\u166d-\\u166e\\u169b-\\u169c\\u16eb-\\u16ed\\u1735-\\u1736\\u17d4-\\u17d6\\u17d8-\\u17da\\u1800-\\u180a\\u1944-\\u1945\\u1a1e-\\u1a1f\\u1aa0-\\u1aa6\\u1aa8-\\u1aad\\u1b5a-\\u1b60\\u1bfc-\\u1bff\\u1c3b-\\u1c3f\\u1c7e-\\u1c7f\\u1cc0-\\u1cc7\\u1cd3\\u2010-\\u2027\\u2030-\\u2043\\u2045-\\u2051\\u2053-\\u205e\\u207d-\\u207e\\u208d-\\u208e\\u2308-\\u230b\\u2329-\\u232a\\u2768-\\u2775\\u27c5-\\u27c6\\u27e6-\\u27ef\\u2983-\\u2998\\u29d8-\\u29db\\u29fc-\\u29fd\\u2cf9-\\u2cfc\\u2cfe-\\u2cff\\u2d70\\u2e00-\\u2e2e\\u2e30-\\u2e49\\u3001-\\u3003\\u3008-\\u3011\\u3014-\\u301f\\u3030\\u303d\\u30a0\\u30fb\\ua4fe-\\ua4ff\\ua60d-\\ua60f\\ua673\\ua67e\\ua6f2-\\ua6f7\\ua874-\\ua877\\ua8ce-\\ua8cf\\ua8f8-\\ua8fa\\ua8fc\\ua92e-\\ua92f\\ua95f\\ua9c1-\\ua9cd\\ua9de-\\ua9df\\uaa5c-\\uaa5f\\uaade-\\uaadf\\uaaf0-\\uaaf1\\uabeb\\ufd3e-\\ufd3f\\ufe10-\\ufe19\\ufe30-\\ufe52\\ufe54-\\ufe61\\ufe63\\ufe68\\ufe6a-\\ufe6b\\uff01-\\uff03\\uff05-\\uff0a\\uff0c-\\uff0f\\uff1a-\\uff1b\\uff1f-\\uff20\\uff3b-\\uff3d\\uff3f\\uff5b\\uff5d\\uff5f-\\uff65]|\\ud800[\\udd00-\\udd02\\udf9f\\udfd0]|\\ud801[\\udd6f]|\\ud802[\\udc57\\udd1f\\udd3f\\ude50-\\ude58\\ude7f\\udef0-\\udef6\\udf39-\\udf3f\\udf99-\\udf9c]|\\ud804[\\udc47-\\udc4d\\udcbb-\\udcbc\\udcbe-\\udcc1\\udd40-\\udd43\\udd74-\\udd75\\uddc5-\\uddc9\\uddcd\\udddb\\udddd-\\udddf\\ude38-\\ude3d\\udea9]|\\ud805[\\udc4b-\\udc4f\\udc5b\\udc5d\\udcc6\\uddc1-\\uddd7\\ude41-\\ude43\\ude60-\\ude6c\\udf3c-\\udf3e]|\\ud806[\\ude3f-\\ude46\\ude9a-\\ude9c\\ude9e-\\udea2]|\\ud807[\\udc41-\\udc45\\udc70-\\udc71]|\\ud809[\\udc70-\\udc74]|\\ud81a[\\ude6e-\\ude6f\\udef5\\udf37-\\udf3b\\udf44]|\\ud82f[\\udc9f]|\\ud836[\\ude87-\\ude8b]|\\ud83a[\\udd5e-\\udd5f]"};
- var cjkPattern = json$6.cjkPattern;
- var kPattern = json$6.kPattern;
- var punctuationPattern$1 = json$6.punctuationPattern;
- var getLast$5 = util$1.getLast;
- var INLINE_NODE_TYPES$1 = ["liquidNode", "inlineCode", "emphasis", "strong", "delete", "link", "linkReference", "image", "imageReference", "footnote", "footnoteReference", "sentence", "whitespace", "word", "break", "inlineMath"];
- var INLINE_NODE_WRAPPER_TYPES$1 = INLINE_NODE_TYPES$1.concat(["tableCell", "paragraph", "heading"]);
- var kRegex = new RegExp(kPattern);
- var punctuationRegex = new RegExp(punctuationPattern$1);
- /**
- * split text into whitespaces and words
- * @param {string} text
- * @return {Array<{ type: "whitespace", value: " " | "\n" | "" } | { type: "word", value: string }>}
- */
- function splitText$1(text, options) {
- var KIND_NON_CJK = "non-cjk";
- var KIND_CJ_LETTER = "cj-letter";
- var KIND_K_LETTER = "k-letter";
- var KIND_CJK_PUNCTUATION = "cjk-punctuation";
- var nodes = [];
- (options.proseWrap === "preserve" ? text : text.replace(new RegExp(`(${cjkPattern})\n(${cjkPattern})`, "g"), "$1$2")).split(/([ \t\n]+)/).forEach(function (token, index, tokens) {
- // whitespace
- if (index % 2 === 1) {
- nodes.push({
- type: "whitespace",
- value: /\n/.test(token) ? "\n" : " "
- });
- return;
- } // word separated by whitespace
- if ((index === 0 || index === tokens.length - 1) && token === "") {
- return;
- }
- token.split(new RegExp(`(${cjkPattern})`)).forEach(function (innerToken, innerIndex, innerTokens) {
- if ((innerIndex === 0 || innerIndex === innerTokens.length - 1) && innerToken === "") {
- return;
- } // non-CJK word
- if (innerIndex % 2 === 0) {
- if (innerToken !== "") {
- appendNode({
- type: "word",
- value: innerToken,
- kind: KIND_NON_CJK,
- hasLeadingPunctuation: punctuationRegex.test(innerToken[0]),
- hasTrailingPunctuation: punctuationRegex.test(getLast$5(innerToken))
- });
- }
- return;
- } // CJK character
- appendNode(punctuationRegex.test(innerToken) ? {
- type: "word",
- value: innerToken,
- kind: KIND_CJK_PUNCTUATION,
- hasLeadingPunctuation: true,
- hasTrailingPunctuation: true
- } : {
- type: "word",
- value: innerToken,
- kind: kRegex.test(innerToken) ? KIND_K_LETTER : KIND_CJ_LETTER,
- hasLeadingPunctuation: false,
- hasTrailingPunctuation: false
- });
- });
- });
- return nodes;
- function appendNode(node) {
- var lastNode = getLast$5(nodes);
- if (lastNode && lastNode.type === "word") {
- if (lastNode.kind === KIND_NON_CJK && node.kind === KIND_CJ_LETTER && !lastNode.hasTrailingPunctuation || lastNode.kind === KIND_CJ_LETTER && node.kind === KIND_NON_CJK && !node.hasLeadingPunctuation) {
- nodes.push({
- type: "whitespace",
- value: " "
- });
- } else if (!isBetween(KIND_NON_CJK, KIND_CJK_PUNCTUATION) && // disallow leading/trailing full-width whitespace
- ![lastNode.value, node.value].some(function (value) {
- return /\u3000/.test(value);
- })) {
- nodes.push({
- type: "whitespace",
- value: ""
- });
- }
- }
- nodes.push(node);
- function isBetween(kind1, kind2) {
- return lastNode.kind === kind1 && node.kind === kind2 || lastNode.kind === kind2 && node.kind === kind1;
- }
- }
- }
- function getOrderedListItemInfo$1(orderListItem, originalText) {
- var _originalText$slice$m = originalText.slice(orderListItem.position.start.offset, orderListItem.position.end.offset).match(/^\s*(\d+)(\.|\))(\s*)/),
- _originalText$slice$m2 = _slicedToArray(_originalText$slice$m, 4),
- numberText = _originalText$slice$m2[1],
- marker = _originalText$slice$m2[2],
- leadingSpaces = _originalText$slice$m2[3];
- return {
- numberText,
- marker,
- leadingSpaces
- };
- } // workaround for https://github.com/remarkjs/remark/issues/351
- // leading and trailing newlines are stripped by remark
- function getFencedCodeBlockValue$2(node, originalText) {
- var text = originalText.slice(node.position.start.offset, node.position.end.offset);
- var leadingSpaceCount = text.match(/^\s*/)[0].length;
- var replaceRegex = new RegExp(`^\\s{0,${leadingSpaceCount}}`);
- var lineContents = text.split("\n");
- var markerStyle = text[leadingSpaceCount]; // ` or ~
- var marker = text.slice(leadingSpaceCount).match(new RegExp(`^[${markerStyle}]+`))[0]; // https://spec.commonmark.org/0.28/#example-104: Closing fences may be indented by 0-3 spaces
- // https://spec.commonmark.org/0.28/#example-93: The closing code fence must be at least as long as the opening fence
- var hasEndMarker = new RegExp(`^\\s{0,3}${marker}`).test(lineContents[lineContents.length - 1].slice(getIndent(lineContents.length - 1)));
- return lineContents.slice(1, hasEndMarker ? -1 : undefined).map(function (x, i) {
- return x.slice(getIndent(i + 1)).replace(replaceRegex, "");
- }).join("\n");
- function getIndent(lineIndex) {
- return node.position.indent[lineIndex - 1] - 1;
- }
- }
- function mapAst(ast, handler) {
- return function preorder(node, index, parentStack) {
- parentStack = parentStack || [];
- var newNode = Object.assign({}, handler(node, index, parentStack));
- if (newNode.children) {
- newNode.children = newNode.children.map(function (child, index) {
- return preorder(child, index, [newNode].concat(parentStack));
- });
- }
- return newNode;
- }(ast, null, null);
- }
- var utils$8 = {
- mapAst,
- splitText: splitText$1,
- punctuationPattern: punctuationPattern$1,
- getFencedCodeBlockValue: getFencedCodeBlockValue$2,
- getOrderedListItemInfo: getOrderedListItemInfo$1,
- INLINE_NODE_TYPES: INLINE_NODE_TYPES$1,
- INLINE_NODE_WRAPPER_TYPES: INLINE_NODE_WRAPPER_TYPES$1
- };
- var _require$$0$builders$7 = doc.builders;
- var hardline$11 = _require$$0$builders$7.hardline;
- var literalline$5 = _require$$0$builders$7.literalline;
- var concat$13 = _require$$0$builders$7.concat;
- var markAsRoot$3 = _require$$0$builders$7.markAsRoot;
- var mapDoc$6 = doc.utils.mapDoc;
- var getFencedCodeBlockValue$1 = utils$8.getFencedCodeBlockValue;
- function embed$4(path$$1, print, textToDoc, options) {
- var node = path$$1.getValue();
- if (node.type === "code" && node.lang !== null) {
- // only look for the first string so as to support [markdown-preview-enhanced](https://shd101wyy.github.io/markdown-preview-enhanced/#/code-chunk)
- var langMatch = node.lang.match(/^[A-Za-z0-9_-]+/);
- var lang = langMatch ? langMatch[0] : "";
- var parser = getParserName(lang);
- if (parser) {
- var styleUnit = options.__inJsTemplate ? "~" : "`";
- var style = styleUnit.repeat(Math.max(3, util$1.getMaxContinuousCount(node.value, styleUnit) + 1));
- var doc$$2 = textToDoc(getFencedCodeBlockValue$1(node, options.originalText), {
- parser
- });
- return markAsRoot$3(concat$13([style, node.lang, hardline$11, replaceNewlinesWithLiterallines(doc$$2), style]));
- }
- }
- if (node.type === "yaml") {
- return markAsRoot$3(concat$13(["---", hardline$11, node.value && node.value.trim() ? replaceNewlinesWithLiterallines(textToDoc(node.value, {
- parser: "yaml"
- })) : "", "---"]));
- } // MDX
- switch (node.type) {
- case "importExport":
- return textToDoc(node.value, {
- parser: "babel"
- });
- case "jsx":
- return textToDoc(node.value, {
- parser: "__js_expression"
- });
- }
- return null;
- function getParserName(lang) {
- var supportInfo = support.getSupportInfo(null, {
- plugins: options.plugins
- });
- var language = supportInfo.languages.find(function (language) {
- return language.name.toLowerCase() === lang || language.aliases && language.aliases.indexOf(lang) !== -1 || language.extensions && language.extensions.find(function (ext) {
- return ext.substring(1) === lang;
- });
- });
- if (language) {
- return language.parsers[0];
- }
- return null;
- }
- function replaceNewlinesWithLiterallines(doc$$2) {
- return mapDoc$6(doc$$2, function (currentDoc) {
- return typeof currentDoc === "string" && currentDoc.includes("\n") ? concat$13(currentDoc.split(/(\n)/g).map(function (v, i) {
- return i % 2 === 0 ? v : literalline$5;
- })) : currentDoc;
- });
- }
- }
- var embed_1$4 = embed$4;
- var pragma$6 = createCommonjsModule(function (module) {
- "use strict";
- var pragmas = ["format", "prettier"];
- function startWithPragma(text) {
- var pragma = `@(${pragmas.join("|")})`;
- var regex = new RegExp([`<!--\\s*${pragma}\\s*-->`, `<!--.*\r?\n[\\s\\S]*(^|\n)[^\\S\n]*${pragma}[^\\S\n]*($|\n)[\\s\\S]*\n.*-->`].join("|"), "m");
- var matched = text.match(regex);
- return matched && matched.index === 0;
- }
- module.exports = {
- startWithPragma,
- hasPragma: function hasPragma(text) {
- return startWithPragma(frontMatter(text).content.trimLeft());
- },
- insertPragma: function insertPragma(text) {
- var extracted = frontMatter(text);
- var pragma = `<!-- @${pragmas[0]} -->`;
- return extracted.frontMatter ? `${extracted.frontMatter.raw}\n\n${pragma}\n\n${extracted.content}` : `${pragma}\n\n${extracted.content}`;
- }
- };
- });
- var getOrderedListItemInfo$2 = utils$8.getOrderedListItemInfo;
- var mapAst$1 = utils$8.mapAst;
- var splitText$2 = utils$8.splitText; // 0x0 ~ 0x10ffff
- var isSingleCharRegex = /^([\u0000-\uffff]|[\ud800-\udbff][\udc00-\udfff])$/;
- function preprocess$2(ast, options) {
- ast = restoreUnescapedCharacter(ast, options);
- ast = mergeContinuousTexts(ast);
- ast = transformInlineCode(ast);
- ast = transformIndentedCodeblockAndMarkItsParentList(ast, options);
- ast = markAlignedList(ast, options);
- ast = splitTextIntoSentences(ast, options);
- ast = transformImportExport(ast);
- ast = mergeContinuousImportExport(ast);
- return ast;
- }
- function transformImportExport(ast) {
- return mapAst$1(ast, function (node) {
- if (node.type !== "import" && node.type !== "export") {
- return node;
- }
- return Object.assign({}, node, {
- type: "importExport"
- });
- });
- }
- function transformInlineCode(ast) {
- return mapAst$1(ast, function (node) {
- if (node.type !== "inlineCode") {
- return node;
- }
- return Object.assign({}, node, {
- value: node.value.replace(/\s+/g, " ")
- });
- });
- }
- function restoreUnescapedCharacter(ast, options) {
- return mapAst$1(ast, function (node) {
- return node.type !== "text" ? node : Object.assign({}, node, {
- value: node.value !== "*" && node.value !== "_" && node.value !== "$" && // handle these cases in printer
- isSingleCharRegex.test(node.value) && node.position.end.offset - node.position.start.offset !== node.value.length ? options.originalText.slice(node.position.start.offset, node.position.end.offset) : node.value
- });
- });
- }
- function mergeContinuousImportExport(ast) {
- return mergeChildren(ast, function (prevNode, node) {
- return prevNode.type === "importExport" && node.type === "importExport";
- }, function (prevNode, node) {
- return {
- type: "importExport",
- value: prevNode.value + "\n\n" + node.value,
- position: {
- start: prevNode.position.start,
- end: node.position.end
- }
- };
- });
- }
- function mergeChildren(ast, shouldMerge, mergeNode) {
- return mapAst$1(ast, function (node) {
- if (!node.children) {
- return node;
- }
- var children = node.children.reduce(function (current, child) {
- var lastChild = current[current.length - 1];
- if (lastChild && shouldMerge(lastChild, child)) {
- current.splice(-1, 1, mergeNode(lastChild, child));
- } else {
- current.push(child);
- }
- return current;
- }, []);
- return Object.assign({}, node, {
- children
- });
- });
- }
- function mergeContinuousTexts(ast) {
- return mergeChildren(ast, function (prevNode, node) {
- return prevNode.type === "text" && node.type === "text";
- }, function (prevNode, node) {
- return {
- type: "text",
- value: prevNode.value + node.value,
- position: {
- start: prevNode.position.start,
- end: node.position.end
- }
- };
- });
- }
- function splitTextIntoSentences(ast, options) {
- return mapAst$1(ast, function (node, index, _ref) {
- var _ref2 = _slicedToArray(_ref, 1),
- parentNode = _ref2[0];
- if (node.type !== "text") {
- return node;
- }
- var value = node.value;
- if (parentNode.type === "paragraph") {
- if (index === 0) {
- value = value.trimLeft();
- }
- if (index === parentNode.children.length - 1) {
- value = value.trimRight();
- }
- }
- return {
- type: "sentence",
- position: node.position,
- children: splitText$2(value, options)
- };
- });
- }
- function transformIndentedCodeblockAndMarkItsParentList(ast, options) {
- return mapAst$1(ast, function (node, index, parentStack) {
- if (node.type === "code") {
- // the first char may point to `\n`, e.g. `\n\t\tbar`, just ignore it
- var isIndented = /^\n?( {4,}|\t)/.test(options.originalText.slice(node.position.start.offset, node.position.end.offset));
- node.isIndented = isIndented;
- if (isIndented) {
- for (var i = 0; i < parentStack.length; i++) {
- var parent = parentStack[i]; // no need to check checked items
- if (parent.hasIndentedCodeblock) {
- break;
- }
- if (parent.type === "list") {
- parent.hasIndentedCodeblock = true;
- }
- }
- }
- }
- return node;
- });
- }
- function markAlignedList(ast, options) {
- return mapAst$1(ast, function (node, index, parentStack) {
- if (node.type === "list" && node.children.length !== 0) {
- // if one of its parents is not aligned, it's not possible to be aligned in sub-lists
- for (var i = 0; i < parentStack.length; i++) {
- var parent = parentStack[i];
- if (parent.type === "list" && !parent.isAligned) {
- node.isAligned = false;
- return node;
- }
- }
- node.isAligned = isAligned(node);
- }
- return node;
- });
- function getListItemStart(listItem) {
- return listItem.children.length === 0 ? -1 : listItem.children[0].position.start.column - 1;
- }
- function isAligned(list) {
- if (!list.ordered) {
- /**
- * - 123
- * - 123
- */
- return true;
- }
- var _list$children = _slicedToArray(list.children, 2),
- firstItem = _list$children[0],
- secondItem = _list$children[1];
- var firstInfo = getOrderedListItemInfo$2(firstItem, options.originalText);
- if (firstInfo.leadingSpaces.length > 1) {
- /**
- * 1. 123
- *
- * 1. 123
- * 1. 123
- */
- return true;
- }
- var firstStart = getListItemStart(firstItem);
- if (firstStart === -1) {
- /**
- * 1.
- *
- * 1.
- * 1.
- */
- return false;
- }
- if (list.children.length === 1) {
- /**
- * aligned:
- *
- * 11. 123
- *
- * not aligned:
- *
- * 1. 123
- */
- return firstStart % options.tabWidth === 0;
- }
- var secondStart = getListItemStart(secondItem);
- if (firstStart !== secondStart) {
- /**
- * 11. 123
- * 1. 123
- *
- * 1. 123
- * 11. 123
- */
- return false;
- }
- if (firstStart % options.tabWidth === 0) {
- /**
- * 11. 123
- * 12. 123
- */
- return true;
- }
- /**
- * aligned:
- *
- * 11. 123
- * 1. 123
- *
- * not aligned:
- *
- * 1. 123
- * 2. 123
- */
- var secondInfo = getOrderedListItemInfo$2(secondItem, options.originalText);
- return secondInfo.leadingSpaces.length > 1;
- }
- }
- var preprocess_1$2 = preprocess$2;
- var _require$$0$builders$6 = doc.builders;
- var concat$12 = _require$$0$builders$6.concat;
- var join$9 = _require$$0$builders$6.join;
- var line$8 = _require$$0$builders$6.line;
- var literalline$4 = _require$$0$builders$6.literalline;
- var markAsRoot$2 = _require$$0$builders$6.markAsRoot;
- var hardline$10 = _require$$0$builders$6.hardline;
- var softline$6 = _require$$0$builders$6.softline;
- var fill$4 = _require$$0$builders$6.fill;
- var align$2 = _require$$0$builders$6.align;
- var indent$8 = _require$$0$builders$6.indent;
- var group$13 = _require$$0$builders$6.group;
- var mapDoc$5 = doc.utils.mapDoc;
- var printDocToString$3 = doc.printer.printDocToString;
- var getFencedCodeBlockValue = utils$8.getFencedCodeBlockValue;
- var getOrderedListItemInfo = utils$8.getOrderedListItemInfo;
- var splitText = utils$8.splitText;
- var punctuationPattern = utils$8.punctuationPattern;
- var INLINE_NODE_TYPES = utils$8.INLINE_NODE_TYPES;
- var INLINE_NODE_WRAPPER_TYPES = utils$8.INLINE_NODE_WRAPPER_TYPES;
- var replaceEndOfLineWith$1 = util$1.replaceEndOfLineWith;
- var TRAILING_HARDLINE_NODES = ["importExport"];
- var SINGLE_LINE_NODE_TYPES = ["heading", "tableCell", "link"];
- var SIBLING_NODE_TYPES = ["listItem", "definition", "footnoteDefinition"];
- function genericPrint$4(path$$1, options, print) {
- var node = path$$1.getValue();
- if (shouldRemainTheSameContent(path$$1)) {
- return concat$12(splitText(options.originalText.slice(node.position.start.offset, node.position.end.offset), options).map(function (node) {
- return node.type === "word" ? node.value : node.value === "" ? "" : printLine(path$$1, node.value, options);
- }));
- }
- switch (node.type) {
- case "root":
- if (node.children.length === 0) {
- return "";
- }
- return concat$12([normalizeDoc(printRoot(path$$1, options, print)), TRAILING_HARDLINE_NODES.indexOf(getLastDescendantNode(node).type) === -1 ? hardline$10 : ""]);
- case "paragraph":
- return printChildren(path$$1, options, print, {
- postprocessor: fill$4
- });
- case "sentence":
- return printChildren(path$$1, options, print);
- case "word":
- return node.value.replace(/[*$]/g, "\\$&") // escape all `*` and `$` (math)
- .replace(new RegExp([`(^|${punctuationPattern})(_+)`, `(_+)(${punctuationPattern}|$)`].join("|"), "g"), function (_, text1, underscore1, underscore2, text2) {
- return (underscore1 ? `${text1}${underscore1}` : `${underscore2}${text2}`).replace(/_/g, "\\_");
- });
- // escape all `_` except concating with non-punctuation, e.g. `1_2_3` is not considered emphasis
- case "whitespace":
- {
- var parentNode = path$$1.getParentNode();
- var index = parentNode.children.indexOf(node);
- var nextNode = parentNode.children[index + 1];
- var proseWrap = // leading char that may cause different syntax
- nextNode && /^>|^([-+*]|#{1,6}|[0-9]+[.)])$/.test(nextNode.value) ? "never" : options.proseWrap;
- return printLine(path$$1, node.value, {
- proseWrap
- });
- }
- case "emphasis":
- {
- var _parentNode = path$$1.getParentNode();
- var _index = _parentNode.children.indexOf(node);
- var prevNode = _parentNode.children[_index - 1];
- var _nextNode = _parentNode.children[_index + 1];
- var hasPrevOrNextWord = // `1*2*3` is considered emphais but `1_2_3` is not
- prevNode && prevNode.type === "sentence" && prevNode.children.length > 0 && util$1.getLast(prevNode.children).type === "word" && !util$1.getLast(prevNode.children).hasTrailingPunctuation || _nextNode && _nextNode.type === "sentence" && _nextNode.children.length > 0 && _nextNode.children[0].type === "word" && !_nextNode.children[0].hasLeadingPunctuation;
- var style = hasPrevOrNextWord || getAncestorNode$2(path$$1, "emphasis") ? "*" : "_";
- return concat$12([style, printChildren(path$$1, options, print), style]);
- }
- case "strong":
- return concat$12(["**", printChildren(path$$1, options, print), "**"]);
- case "delete":
- return concat$12(["~~", printChildren(path$$1, options, print), "~~"]);
- case "inlineCode":
- {
- var backtickCount = util$1.getMaxContinuousCount(node.value, "`");
- var _style = backtickCount === 1 ? "``" : "`";
- var gap = backtickCount ? " " : "";
- return concat$12([_style, gap, node.value, gap, _style]);
- }
- case "link":
- switch (options.originalText[node.position.start.offset]) {
- case "<":
- {
- var mailto = "mailto:";
- var url = // <hello@example.com> is parsed as { url: "mailto:hello@example.com" }
- node.url.startsWith(mailto) && options.originalText.slice(node.position.start.offset + 1, node.position.start.offset + 1 + mailto.length) !== mailto ? node.url.slice(mailto.length) : node.url;
- return concat$12(["<", url, ">"]);
- }
- case "[":
- return concat$12(["[", printChildren(path$$1, options, print), "](", printUrl(node.url, ")"), printTitle(node.title, options), ")"]);
- default:
- return options.originalText.slice(node.position.start.offset, node.position.end.offset);
- }
- case "image":
- return concat$12(["![", node.alt || "", "](", printUrl(node.url, ")"), printTitle(node.title, options), ")"]);
- case "blockquote":
- return concat$12(["> ", align$2("> ", printChildren(path$$1, options, print))]);
- case "heading":
- return concat$12(["#".repeat(node.depth) + " ", printChildren(path$$1, options, print)]);
- case "code":
- {
- if (node.isIndented) {
- // indented code block
- var alignment = " ".repeat(4);
- return align$2(alignment, concat$12([alignment, concat$12(replaceEndOfLineWith$1(node.value, hardline$10))]));
- } // fenced code block
- var styleUnit = options.__inJsTemplate ? "~" : "`";
- var _style2 = styleUnit.repeat(Math.max(3, util$1.getMaxContinuousCount(node.value, styleUnit) + 1));
- return concat$12([_style2, node.lang || "", hardline$10, concat$12(replaceEndOfLineWith$1(getFencedCodeBlockValue(node, options.originalText), hardline$10)), hardline$10, _style2]);
- }
- case "yaml":
- case "toml":
- return options.originalText.slice(node.position.start.offset, node.position.end.offset);
- case "html":
- {
- var _parentNode2 = path$$1.getParentNode();
- var value = _parentNode2.type === "root" && util$1.getLast(_parentNode2.children) === node ? node.value.trimRight() : node.value;
- var isHtmlComment = /^<!--[\s\S]*-->$/.test(value);
- return concat$12(replaceEndOfLineWith$1(value, isHtmlComment ? hardline$10 : markAsRoot$2(literalline$4)));
- }
- case "list":
- {
- var nthSiblingIndex = getNthListSiblingIndex(node, path$$1.getParentNode());
- var isGitDiffFriendlyOrderedList = node.ordered && node.children.length > 1 && +getOrderedListItemInfo(node.children[1], options.originalText).numberText === 1;
- return printChildren(path$$1, options, print, {
- processor: function processor(childPath, index) {
- var prefix = getPrefix();
- return concat$12([prefix, align$2(" ".repeat(prefix.length), printListItem(childPath, options, print, prefix))]);
- function getPrefix() {
- var rawPrefix = node.ordered ? (index === 0 ? node.start : isGitDiffFriendlyOrderedList ? 1 : node.start + index) + (nthSiblingIndex % 2 === 0 ? ". " : ") ") : nthSiblingIndex % 2 === 0 ? "- " : "* ";
- return node.isAligned ||
- /* workaround for https://github.com/remarkjs/remark/issues/315 */
- node.hasIndentedCodeblock ? alignListPrefix(rawPrefix, options) : rawPrefix;
- }
- }
- });
- }
- case "thematicBreak":
- {
- var counter = getAncestorCounter$1(path$$1, "list");
- if (counter === -1) {
- return "---";
- }
- var _nthSiblingIndex = getNthListSiblingIndex(path$$1.getParentNode(counter), path$$1.getParentNode(counter + 1));
- return _nthSiblingIndex % 2 === 0 ? "***" : "---";
- }
- case "linkReference":
- return concat$12(["[", printChildren(path$$1, options, print), "]", node.referenceType === "full" ? concat$12(["[", node.identifier, "]"]) : node.referenceType === "collapsed" ? "[]" : ""]);
- case "imageReference":
- switch (node.referenceType) {
- case "full":
- return concat$12(["![", node.alt || "", "][", node.identifier, "]"]);
- default:
- return concat$12(["![", node.alt, "]", node.referenceType === "collapsed" ? "[]" : ""]);
- }
- case "definition":
- {
- var lineOrSpace = options.proseWrap === "always" ? line$8 : " ";
- return group$13(concat$12([concat$12(["[", node.identifier, "]:"]), indent$8(concat$12([lineOrSpace, printUrl(node.url), node.title === null ? "" : concat$12([lineOrSpace, printTitle(node.title, options, false)])]))]));
- }
- case "footnote":
- return concat$12(["[^", printChildren(path$$1, options, print), "]"]);
- case "footnoteReference":
- return concat$12(["[^", node.identifier, "]"]);
- case "footnoteDefinition":
- {
- var _nextNode2 = path$$1.getParentNode().children[path$$1.getName() + 1];
- var shouldInlineFootnote = node.children.length === 1 && node.children[0].type === "paragraph" && (options.proseWrap === "never" || options.proseWrap === "preserve" && node.children[0].position.start.line === node.children[0].position.end.line);
- return concat$12(["[^", node.identifier, "]: ", shouldInlineFootnote ? printChildren(path$$1, options, print) : group$13(concat$12([align$2(" ".repeat(options.tabWidth), printChildren(path$$1, options, print, {
- processor: function processor(childPath, index) {
- return index === 0 ? group$13(concat$12([softline$6, softline$6, childPath.call(print)])) : childPath.call(print);
- }
- })), _nextNode2 && _nextNode2.type === "footnoteDefinition" ? softline$6 : ""]))]);
- }
- case "table":
- return printTable(path$$1, options, print);
- case "tableCell":
- return printChildren(path$$1, options, print);
- case "break":
- return /\s/.test(options.originalText[node.position.start.offset]) ? concat$12([" ", markAsRoot$2(literalline$4)]) : concat$12(["\\", hardline$10]);
- case "liquidNode":
- return concat$12(replaceEndOfLineWith$1(node.value, hardline$10));
- // MDX
- case "importExport":
- case "jsx":
- return node.value;
- // fallback to the original text if multiparser failed
- case "math":
- return concat$12(["$$", hardline$10, node.value ? concat$12([concat$12(replaceEndOfLineWith$1(node.value, hardline$10)), hardline$10]) : "", "$$"]);
- case "inlineMath":
- {
- // remark-math trims content but we don't want to remove whitespaces
- // since it's very possible that it's recognized as math accidentally
- return options.originalText.slice(options.locStart(node), options.locEnd(node));
- }
- case "tableRow": // handled in "table"
- case "listItem": // handled in "list"
- default:
- throw new Error(`Unknown markdown type ${JSON.stringify(node.type)}`);
- }
- }
- function printListItem(path$$1, options, print, listPrefix) {
- var node = path$$1.getValue();
- var prefix = node.checked === null ? "" : node.checked ? "[x] " : "[ ] ";
- return concat$12([prefix, printChildren(path$$1, options, print, {
- processor: function processor(childPath, index) {
- if (index === 0 && childPath.getValue().type !== "list") {
- return align$2(" ".repeat(prefix.length), childPath.call(print));
- }
- var alignment = " ".repeat(clamp(options.tabWidth - listPrefix.length, 0, 3) // 4+ will cause indented code block
- );
- return concat$12([alignment, align$2(alignment, childPath.call(print))]);
- }
- })]);
- }
- function alignListPrefix(prefix, options) {
- var additionalSpaces = getAdditionalSpaces();
- return prefix + " ".repeat(additionalSpaces >= 4 ? 0 : additionalSpaces // 4+ will cause indented code block
- );
- function getAdditionalSpaces() {
- var restSpaces = prefix.length % options.tabWidth;
- return restSpaces === 0 ? 0 : options.tabWidth - restSpaces;
- }
- }
- function getNthListSiblingIndex(node, parentNode) {
- return getNthSiblingIndex(node, parentNode, function (siblingNode) {
- return siblingNode.ordered === node.ordered;
- });
- }
- function getNthSiblingIndex(node, parentNode, condition) {
- condition = condition || function () {
- return true;
- };
- var index = -1;
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = parentNode.children[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var childNode = _step.value;
- if (childNode.type === node.type && condition(childNode)) {
- index++;
- } else {
- index = -1;
- }
- if (childNode === node) {
- return index;
- }
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- }
- function getAncestorCounter$1(path$$1, typeOrTypes) {
- var types = [].concat(typeOrTypes);
- var counter = -1;
- var ancestorNode;
- while (ancestorNode = path$$1.getParentNode(++counter)) {
- if (types.indexOf(ancestorNode.type) !== -1) {
- return counter;
- }
- }
- return -1;
- }
- function getAncestorNode$2(path$$1, typeOrTypes) {
- var counter = getAncestorCounter$1(path$$1, typeOrTypes);
- return counter === -1 ? null : path$$1.getParentNode(counter);
- }
- function printLine(path$$1, value, options) {
- if (options.proseWrap === "preserve" && value === "\n") {
- return hardline$10;
- }
- var isBreakable = options.proseWrap === "always" && !getAncestorNode$2(path$$1, SINGLE_LINE_NODE_TYPES);
- return value !== "" ? isBreakable ? line$8 : " " : isBreakable ? softline$6 : "";
- }
- function printTable(path$$1, options, print) {
- var node = path$$1.getValue();
- var contents = []; // { [rowIndex: number]: { [columnIndex: number]: string } }
- path$$1.map(function (rowPath) {
- var rowContents = [];
- rowPath.map(function (cellPath) {
- rowContents.push(printDocToString$3(cellPath.call(print), options).formatted);
- }, "children");
- contents.push(rowContents);
- }, "children");
- var columnMaxWidths = contents.reduce(function (currentWidths, rowContents) {
- return currentWidths.map(function (width, columnIndex) {
- return Math.max(width, util$1.getStringWidth(rowContents[columnIndex]));
- });
- }, contents[0].map(function () {
- return 3;
- }) // minimum width = 3 (---, :--, :-:, --:)
- );
- return join$9(hardline$10, [printRow(contents[0]), printSeparator(), join$9(hardline$10, contents.slice(1).map(printRow))]);
- function printSeparator() {
- return concat$12(["| ", join$9(" | ", columnMaxWidths.map(function (width, index) {
- switch (node.align[index]) {
- case "left":
- return ":" + "-".repeat(width - 1);
- case "right":
- return "-".repeat(width - 1) + ":";
- case "center":
- return ":" + "-".repeat(width - 2) + ":";
- default:
- return "-".repeat(width);
- }
- })), " |"]);
- }
- function printRow(rowContents) {
- return concat$12(["| ", join$9(" | ", rowContents.map(function (rowContent, columnIndex) {
- switch (node.align[columnIndex]) {
- case "right":
- return alignRight(rowContent, columnMaxWidths[columnIndex]);
- case "center":
- return alignCenter(rowContent, columnMaxWidths[columnIndex]);
- default:
- return alignLeft(rowContent, columnMaxWidths[columnIndex]);
- }
- })), " |"]);
- }
- function alignLeft(text, width) {
- return concat$12([text, " ".repeat(width - util$1.getStringWidth(text))]);
- }
- function alignRight(text, width) {
- return concat$12([" ".repeat(width - util$1.getStringWidth(text)), text]);
- }
- function alignCenter(text, width) {
- var spaces = width - util$1.getStringWidth(text);
- var left = Math.floor(spaces / 2);
- var right = spaces - left;
- return concat$12([" ".repeat(left), text, " ".repeat(right)]);
- }
- }
- function printRoot(path$$1, options, print) {
- /** @typedef {{ index: number, offset: number }} IgnorePosition */
- /** @type {Array<{start: IgnorePosition, end: IgnorePosition}>} */
- var ignoreRanges = [];
- /** @type {IgnorePosition | null} */
- var ignoreStart = null;
- var children = path$$1.getValue().children;
- children.forEach(function (childNode, index) {
- switch (isPrettierIgnore(childNode)) {
- case "start":
- if (ignoreStart === null) {
- ignoreStart = {
- index,
- offset: childNode.position.end.offset
- };
- }
- break;
- case "end":
- if (ignoreStart !== null) {
- ignoreRanges.push({
- start: ignoreStart,
- end: {
- index,
- offset: childNode.position.start.offset
- }
- });
- ignoreStart = null;
- }
- break;
- default:
- // do nothing
- break;
- }
- });
- return printChildren(path$$1, options, print, {
- processor: function processor(childPath, index) {
- if (ignoreRanges.length !== 0) {
- var ignoreRange = ignoreRanges[0];
- if (index === ignoreRange.start.index) {
- return concat$12([children[ignoreRange.start.index].value, options.originalText.slice(ignoreRange.start.offset, ignoreRange.end.offset), children[ignoreRange.end.index].value]);
- }
- if (ignoreRange.start.index < index && index < ignoreRange.end.index) {
- return false;
- }
- if (index === ignoreRange.end.index) {
- ignoreRanges.shift();
- return false;
- }
- }
- return childPath.call(print);
- }
- });
- }
- function printChildren(path$$1, options, print, events$$1) {
- events$$1 = events$$1 || {};
- var postprocessor = events$$1.postprocessor || concat$12;
- var processor = events$$1.processor || function (childPath) {
- return childPath.call(print);
- };
- var node = path$$1.getValue();
- var parts = [];
- var lastChildNode;
- path$$1.map(function (childPath, index) {
- var childNode = childPath.getValue();
- var result = processor(childPath, index);
- if (result !== false) {
- var data = {
- parts,
- prevNode: lastChildNode,
- parentNode: node,
- options
- };
- if (!shouldNotPrePrintHardline(childNode, data)) {
- parts.push(hardline$10);
- if (lastChildNode && TRAILING_HARDLINE_NODES.indexOf(lastChildNode.type) !== -1) {
- if (shouldPrePrintTripleHardline(childNode, data)) {
- parts.push(hardline$10);
- }
- } else {
- if (shouldPrePrintDoubleHardline(childNode, data) || shouldPrePrintTripleHardline(childNode, data)) {
- parts.push(hardline$10);
- }
- if (shouldPrePrintTripleHardline(childNode, data)) {
- parts.push(hardline$10);
- }
- }
- }
- parts.push(result);
- lastChildNode = childNode;
- }
- }, "children");
- return postprocessor(parts);
- }
- function getLastDescendantNode(node) {
- var current = node;
- while (current.children && current.children.length !== 0) {
- current = current.children[current.children.length - 1];
- }
- return current;
- }
- /** @return {false | 'next' | 'start' | 'end'} */
- function isPrettierIgnore(node) {
- if (node.type !== "html") {
- return false;
- }
- var match = node.value.match(/^<!--\s*prettier-ignore(?:-(start|end))?\s*-->$/);
- return match === null ? false : match[1] ? match[1] : "next";
- }
- function shouldNotPrePrintHardline(node, data) {
- var isFirstNode = data.parts.length === 0;
- var isInlineNode = INLINE_NODE_TYPES.indexOf(node.type) !== -1;
- var isInlineHTML = node.type === "html" && INLINE_NODE_WRAPPER_TYPES.indexOf(data.parentNode.type) !== -1;
- return isFirstNode || isInlineNode || isInlineHTML;
- }
- function shouldPrePrintDoubleHardline(node, data) {
- var isSequence = (data.prevNode && data.prevNode.type) === node.type;
- var isSiblingNode = isSequence && SIBLING_NODE_TYPES.indexOf(node.type) !== -1;
- var isInTightListItem = data.parentNode.type === "listItem" && !data.parentNode.loose;
- var isPrevNodeLooseListItem = data.prevNode && data.prevNode.type === "listItem" && data.prevNode.loose;
- var isPrevNodePrettierIgnore = isPrettierIgnore(data.prevNode) === "next";
- var isBlockHtmlWithoutBlankLineBetweenPrevHtml = node.type === "html" && data.prevNode && data.prevNode.type === "html" && data.prevNode.position.end.line + 1 === node.position.start.line;
- return isPrevNodeLooseListItem || !(isSiblingNode || isInTightListItem || isPrevNodePrettierIgnore || isBlockHtmlWithoutBlankLineBetweenPrevHtml);
- }
- function shouldPrePrintTripleHardline(node, data) {
- var isPrevNodeList = data.prevNode && data.prevNode.type === "list";
- var isIndentedCode = node.type === "code" && node.isIndented;
- return isPrevNodeList && isIndentedCode;
- }
- function shouldRemainTheSameContent(path$$1) {
- var ancestorNode = getAncestorNode$2(path$$1, ["linkReference", "imageReference"]);
- return ancestorNode && (ancestorNode.type !== "linkReference" || ancestorNode.referenceType !== "full");
- }
- function normalizeDoc(doc$$2) {
- return mapDoc$5(doc$$2, function (currentDoc) {
- if (!currentDoc.parts) {
- return currentDoc;
- }
- if (currentDoc.type === "concat" && currentDoc.parts.length === 1) {
- return currentDoc.parts[0];
- }
- var parts = [];
- currentDoc.parts.forEach(function (part) {
- if (part.type === "concat") {
- parts.push.apply(parts, part.parts);
- } else if (part !== "") {
- parts.push(part);
- }
- });
- return Object.assign({}, currentDoc, {
- parts: normalizeParts(parts)
- });
- });
- }
- function printUrl(url, dangerousCharOrChars) {
- var dangerousChars = [" "].concat(dangerousCharOrChars || []);
- return new RegExp(dangerousChars.map(function (x) {
- return `\\${x}`;
- }).join("|")).test(url) ? `<${url}>` : url;
- }
- function printTitle(title, options, printSpace) {
- if (printSpace == null) {
- printSpace = true;
- }
- if (!title) {
- return "";
- }
- if (printSpace) {
- return " " + printTitle(title, options, false);
- }
- if (title.includes('"') && title.includes("'") && !title.includes(")")) {
- return `(${title})`; // avoid escaped quotes
- } // faster than using RegExps: https://jsperf.com/performance-of-match-vs-split
- var singleCount = title.split("'").length - 1;
- var doubleCount = title.split('"').length - 1;
- var quote = singleCount > doubleCount ? '"' : doubleCount > singleCount ? "'" : options.singleQuote ? "'" : '"';
- title = title.replace(new RegExp(`(${quote})`, "g"), "\\$1");
- return `${quote}${title}${quote}`;
- }
- function normalizeParts(parts) {
- return parts.reduce(function (current, part) {
- var lastPart = util$1.getLast(current);
- if (typeof lastPart === "string" && typeof part === "string") {
- current.splice(-1, 1, lastPart + part);
- } else {
- current.push(part);
- }
- return current;
- }, []);
- }
- function clamp(value, min, max) {
- return value < min ? min : value > max ? max : value;
- }
- function clean$7(ast, newObj, parent) {
- delete newObj.position;
- delete newObj.raw; // front-matter
- // for codeblock
- if (ast.type === "code" || ast.type === "yaml" || ast.type === "import" || ast.type === "export" || ast.type === "jsx") {
- delete newObj.value;
- }
- if (ast.type === "list") {
- delete newObj.isAligned;
- } // texts can be splitted or merged
- if (ast.type === "text") {
- return null;
- }
- if (ast.type === "inlineCode") {
- newObj.value = ast.value.replace(/[ \t\n]+/g, " ");
- } // for insert pragma
- if (parent && parent.type === "root" && parent.children.length > 0 && (parent.children[0] === ast || (parent.children[0].type === "yaml" || parent.children[0].type === "toml") && parent.children[1] === ast) && ast.type === "html" && pragma$6.startWithPragma(ast.value)) {
- return null;
- }
- }
- function hasPrettierIgnore$1(path$$1) {
- var index = +path$$1.getName();
- if (index === 0) {
- return false;
- }
- var prevNode = path$$1.getParentNode().children[index - 1];
- return isPrettierIgnore(prevNode) === "next";
- }
- var printerMarkdown = {
- preprocess: preprocess_1$2,
- print: genericPrint$4,
- embed: embed_1$4,
- massageAstNode: clean$7,
- hasPrettierIgnore: hasPrettierIgnore$1,
- insertPragma: pragma$6.insertPragma
- };
- var options$12 = {
- proseWrap: commonOptions.proseWrap,
- singleQuote: commonOptions.singleQuote
- };
- var name$13 = "Markdown";
- var type$12 = "prose";
- var aliases$4 = ["pandoc"];
- var aceMode$12 = "markdown";
- var codemirrorMode$9 = "gfm";
- var codemirrorMimeType$9 = "text/x-gfm";
- var wrap = true;
- var extensions$12 = [".md", ".markdown", ".mdown", ".mdwn", ".mkd", ".mkdn", ".mkdown", ".ronn", ".workbook"];
- var tmScope$12 = "source.gfm";
- var languageId$12 = 222;
- var markdown = {
- name: name$13,
- type: type$12,
- aliases: aliases$4,
- aceMode: aceMode$12,
- codemirrorMode: codemirrorMode$9,
- codemirrorMimeType: codemirrorMimeType$9,
- wrap: wrap,
- extensions: extensions$12,
- tmScope: tmScope$12,
- languageId: languageId$12
- };
- var markdown$1 = Object.freeze({
- name: name$13,
- type: type$12,
- aliases: aliases$4,
- aceMode: aceMode$12,
- codemirrorMode: codemirrorMode$9,
- codemirrorMimeType: codemirrorMimeType$9,
- wrap: wrap,
- extensions: extensions$12,
- tmScope: tmScope$12,
- languageId: languageId$12,
- default: markdown
- });
- var require$$0$28 = ( markdown$1 && markdown ) || markdown$1;
- var languages$4 = [createLanguage(require$$0$28, {
- override: {
- since: "1.8.0",
- parsers: ["remark"],
- vscodeLanguageIds: ["markdown"]
- },
- extend: {
- filenames: ["README"]
- }
- }), createLanguage({
- name: "MDX",
- extensions: [".mdx"]
- }, // TODO: use linguist data
- {
- override: {
- since: "1.15.0",
- parsers: ["mdx"],
- vscodeLanguageIds: ["mdx"]
- }
- })];
- var printers$4 = {
- mdast: printerMarkdown
- };
- var languageMarkdown = {
- languages: languages$4,
- options: options$12,
- printers: printers$4
- };
- var clean$8 = function clean(ast, newNode) {
- delete newNode.sourceSpan;
- delete newNode.startSourceSpan;
- delete newNode.endSourceSpan;
- delete newNode.nameSpan;
- delete newNode.valueSpan;
- if (ast.type === "text" || ast.type === "comment") {
- return null;
- } // may be formatted by multiparser
- if (ast.type === "yaml" || ast.type === "toml") {
- return null;
- }
- if (ast.type === "attribute") {
- delete newNode.value;
- }
- if (ast.type === "docType") {
- delete newNode.value;
- }
- };
- var a = ["accesskey", "charset", "coords", "download", "href", "hreflang", "name", "ping", "referrerpolicy", "rel", "rev", "shape", "tabindex", "target", "type"];
- var abbr = ["title"];
- var applet = ["align", "alt", "archive", "code", "codebase", "height", "hspace", "name", "object", "vspace", "width"];
- var area = ["accesskey", "alt", "coords", "download", "href", "hreflang", "nohref", "ping", "referrerpolicy", "rel", "shape", "tabindex", "target", "type"];
- var audio = ["autoplay", "controls", "crossorigin", "loop", "muted", "preload", "src"];
- var base$2 = ["href", "target"];
- var basefont = ["color", "face", "size"];
- var bdo = ["dir"];
- var blockquote = ["cite"];
- var body = ["alink", "background", "bgcolor", "link", "text", "vlink"];
- var br = ["clear"];
- var button = ["accesskey", "autofocus", "disabled", "form", "formaction", "formenctype", "formmethod", "formnovalidate", "formtarget", "name", "tabindex", "type", "value"];
- var canvas = ["height", "width"];
- var caption = ["align"];
- var col = ["align", "char", "charoff", "span", "valign", "width"];
- var colgroup = ["align", "char", "charoff", "span", "valign", "width"];
- var data$1 = ["value"];
- var del = ["cite", "datetime"];
- var details = ["open"];
- var dfn = ["title"];
- var dialog = ["open"];
- var dir = ["compact"];
- var div = ["align"];
- var dl = ["compact"];
- var embed$7 = ["height", "src", "type", "width"];
- var fieldset = ["disabled", "form", "name"];
- var font = ["color", "face", "size"];
- var form = ["accept", "accept-charset", "action", "autocomplete", "enctype", "method", "name", "novalidate", "target"];
- var frame = ["frameborder", "longdesc", "marginheight", "marginwidth", "name", "noresize", "scrolling", "src"];
- var frameset = ["cols", "rows"];
- var h1 = ["align"];
- var h2 = ["align"];
- var h3 = ["align"];
- var h4 = ["align"];
- var h5 = ["align"];
- var h6 = ["align"];
- var head = ["profile"];
- var hr = ["align", "noshade", "size", "width"];
- var html = ["manifest", "version"];
- var iframe = ["align", "allowfullscreen", "allowpaymentrequest", "allowusermedia", "frameborder", "height", "longdesc", "marginheight", "marginwidth", "name", "referrerpolicy", "sandbox", "scrolling", "src", "srcdoc", "width"];
- var img = ["align", "alt", "border", "crossorigin", "decoding", "height", "hspace", "ismap", "longdesc", "name", "referrerpolicy", "sizes", "src", "srcset", "usemap", "vspace", "width"];
- var input = ["accept", "accesskey", "align", "alt", "autocomplete", "autofocus", "checked", "dirname", "disabled", "form", "formaction", "formenctype", "formmethod", "formnovalidate", "formtarget", "height", "ismap", "list", "max", "maxlength", "min", "minlength", "multiple", "name", "pattern", "placeholder", "readonly", "required", "size", "src", "step", "tabindex", "title", "type", "usemap", "value", "width"];
- var ins = ["cite", "datetime"];
- var isindex = ["prompt"];
- var label = ["accesskey", "for", "form"];
- var legend = ["accesskey", "align"];
- var li = ["type", "value"];
- var link$1 = ["as", "charset", "color", "crossorigin", "href", "hreflang", "integrity", "media", "nonce", "referrerpolicy", "rel", "rev", "sizes", "target", "title", "type"];
- var map = ["name"];
- var menu = ["compact"];
- var meta = ["charset", "content", "http-equiv", "name", "scheme"];
- var meter = ["high", "low", "max", "min", "optimum", "value"];
- var object = ["align", "archive", "border", "classid", "codebase", "codetype", "data", "declare", "form", "height", "hspace", "name", "standby", "tabindex", "type", "typemustmatch", "usemap", "vspace", "width"];
- var ol = ["compact", "reversed", "start", "type"];
- var optgroup = ["disabled", "label"];
- var option = ["disabled", "label", "selected", "value"];
- var output = ["for", "form", "name"];
- var p = ["align"];
- var param = ["name", "type", "value", "valuetype"];
- var pre = ["width"];
- var progress = ["max", "value"];
- var q = ["cite"];
- var script = ["async", "charset", "crossorigin", "defer", "integrity", "language", "nomodule", "nonce", "referrerpolicy", "src", "type"];
- var select = ["autocomplete", "autofocus", "disabled", "form", "multiple", "name", "required", "size", "tabindex"];
- var slot = ["name"];
- var source = ["media", "sizes", "src", "srcset", "type"];
- var style = ["media", "nonce", "title", "type"];
- var table = ["align", "bgcolor", "border", "cellpadding", "cellspacing", "frame", "rules", "summary", "width"];
- var tbody = ["align", "char", "charoff", "valign"];
- var td = ["abbr", "align", "axis", "bgcolor", "char", "charoff", "colspan", "headers", "height", "nowrap", "rowspan", "scope", "valign", "width"];
- var textarea = ["accesskey", "autocomplete", "autofocus", "cols", "dirname", "disabled", "form", "maxlength", "minlength", "name", "placeholder", "readonly", "required", "rows", "tabindex", "wrap"];
- var tfoot = ["align", "char", "charoff", "valign"];
- var th = ["abbr", "align", "axis", "bgcolor", "char", "charoff", "colspan", "headers", "height", "nowrap", "rowspan", "scope", "valign", "width"];
- var thead = ["align", "char", "charoff", "valign"];
- var time = ["datetime"];
- var tr = ["align", "bgcolor", "char", "charoff", "valign"];
- var track = ["default", "kind", "label", "src", "srclang"];
- var ul = ["compact", "type"];
- var video = ["autoplay", "controls", "crossorigin", "height", "loop", "muted", "playsinline", "poster", "preload", "src", "width"];
- var index$13 = {
- a: a,
- abbr: abbr,
- applet: applet,
- area: area,
- audio: audio,
- base: base$2,
- basefont: basefont,
- bdo: bdo,
- blockquote: blockquote,
- body: body,
- br: br,
- button: button,
- canvas: canvas,
- caption: caption,
- col: col,
- colgroup: colgroup,
- data: data$1,
- del: del,
- details: details,
- dfn: dfn,
- dialog: dialog,
- dir: dir,
- div: div,
- dl: dl,
- embed: embed$7,
- fieldset: fieldset,
- font: font,
- form: form,
- frame: frame,
- frameset: frameset,
- h1: h1,
- h2: h2,
- h3: h3,
- h4: h4,
- h5: h5,
- h6: h6,
- head: head,
- hr: hr,
- html: html,
- iframe: iframe,
- img: img,
- input: input,
- ins: ins,
- isindex: isindex,
- label: label,
- legend: legend,
- li: li,
- link: link$1,
- map: map,
- menu: menu,
- meta: meta,
- meter: meter,
- object: object,
- ol: ol,
- optgroup: optgroup,
- option: option,
- output: output,
- p: p,
- param: param,
- pre: pre,
- progress: progress,
- q: q,
- script: script,
- select: select,
- slot: slot,
- source: source,
- style: style,
- table: table,
- tbody: tbody,
- td: td,
- textarea: textarea,
- tfoot: tfoot,
- th: th,
- thead: thead,
- time: time,
- tr: tr,
- track: track,
- ul: ul,
- video: video,
- "*": ["accesskey", "autocapitalize", "class", "contenteditable", "dir", "draggable", "hidden", "id", "inputmode", "is", "itemid", "itemprop", "itemref", "itemscope", "itemtype", "lang", "nonce", "slot", "spellcheck", "style", "tabindex", "title", "translate"]
- };
- var htmlElementAttributes = Object.freeze({
- a: a,
- abbr: abbr,
- applet: applet,
- area: area,
- audio: audio,
- base: base$2,
- basefont: basefont,
- bdo: bdo,
- blockquote: blockquote,
- body: body,
- br: br,
- button: button,
- canvas: canvas,
- caption: caption,
- col: col,
- colgroup: colgroup,
- data: data$1,
- del: del,
- details: details,
- dfn: dfn,
- dialog: dialog,
- dir: dir,
- div: div,
- dl: dl,
- embed: embed$7,
- fieldset: fieldset,
- font: font,
- form: form,
- frame: frame,
- frameset: frameset,
- h1: h1,
- h2: h2,
- h3: h3,
- h4: h4,
- h5: h5,
- h6: h6,
- head: head,
- hr: hr,
- html: html,
- iframe: iframe,
- img: img,
- input: input,
- ins: ins,
- isindex: isindex,
- label: label,
- legend: legend,
- li: li,
- link: link$1,
- map: map,
- menu: menu,
- meta: meta,
- meter: meter,
- object: object,
- ol: ol,
- optgroup: optgroup,
- option: option,
- output: output,
- p: p,
- param: param,
- pre: pre,
- progress: progress,
- q: q,
- script: script,
- select: select,
- slot: slot,
- source: source,
- style: style,
- table: table,
- tbody: tbody,
- td: td,
- textarea: textarea,
- tfoot: tfoot,
- th: th,
- thead: thead,
- time: time,
- tr: tr,
- track: track,
- ul: ul,
- video: video,
- default: index$13
- });
- var json$9 = {"CSS_DISPLAY_TAGS":{"area":"none","base":"none","basefont":"none","datalist":"none","head":"none","link":"none","meta":"none","noembed":"none","noframes":"none","param":"none","rp":"none","script":"none","source":"block","style":"none","template":"inline","track":"block","title":"none","html":"block","body":"block","address":"block","blockquote":"block","center":"block","div":"block","figure":"block","figcaption":"block","footer":"block","form":"block","header":"block","hr":"block","legend":"block","listing":"block","main":"block","p":"block","plaintext":"block","pre":"block","xmp":"block","slot":"contents","ruby":"ruby","rt":"ruby-text","article":"block","aside":"block","h1":"block","h2":"block","h3":"block","h4":"block","h5":"block","h6":"block","hgroup":"block","nav":"block","section":"block","dir":"block","dd":"block","dl":"block","dt":"block","ol":"block","ul":"block","li":"list-item","table":"table","caption":"table-caption","colgroup":"table-column-group","col":"table-column","thead":"table-header-group","tbody":"table-row-group","tfoot":"table-footer-group","tr":"table-row","td":"table-cell","th":"table-cell","fieldset":"block","button":"inline-block","video":"inline-block","audio":"inline-block"},"CSS_DISPLAY_DEFAULT":"inline","CSS_WHITE_SPACE_TAGS":{"listing":"pre","plaintext":"pre","pre":"pre","xmp":"pre","nobr":"nowrap","table":"initial","textarea":"pre-wrap"},"CSS_WHITE_SPACE_DEFAULT":"normal"};
- var htmlElementAttributes$1 = ( htmlElementAttributes && index$13 ) || htmlElementAttributes;
- var CSS_DISPLAY_TAGS = json$9.CSS_DISPLAY_TAGS;
- var CSS_DISPLAY_DEFAULT = json$9.CSS_DISPLAY_DEFAULT;
- var CSS_WHITE_SPACE_TAGS = json$9.CSS_WHITE_SPACE_TAGS;
- var CSS_WHITE_SPACE_DEFAULT = json$9.CSS_WHITE_SPACE_DEFAULT;
- var HTML_TAGS = arrayToMap(htmlTagNames$1);
- var HTML_ELEMENT_ATTRIBUTES = mapObject(htmlElementAttributes$1, arrayToMap);
- function arrayToMap(array) {
- var map = Object.create(null);
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = array[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var value = _step.value;
- map[value] = true;
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- return map;
- }
- function mapObject(object, fn) {
- var newObject = Object.create(null);
- var _arr = Object.keys(object);
- for (var _i = 0; _i < _arr.length; _i++) {
- var key = _arr[_i];
- newObject[key] = fn(object[key], key);
- }
- return newObject;
- }
- function shouldPreserveContent$1(node, options) {
- if (node.type === "element" && node.fullName === "template" && node.attrMap.lang && node.attrMap.lang !== "html") {
- return true;
- } // unterminated node in ie conditional comment
- // e.g. <!--[if lt IE 9]><html><![endif]-->
- if (node.type === "ieConditionalComment" && node.lastChild && !node.lastChild.isSelfClosing && !node.lastChild.endSourceSpan) {
- return true;
- } // incomplete html in ie conditional comment
- // e.g. <!--[if lt IE 9]></div><![endif]-->
- if (node.type === "ieConditionalComment" && !node.complete) {
- return true;
- } // top-level elements (excluding <template>, <style> and <script>) in Vue SFC are considered custom block
- // custom blocks can be written in other languages so we should preserve them to not break the code
- if (options.parser === "vue" && node.type === "element" && node.parent.type === "root" && ["template", "style", "script", // vue parser can be used for vue dom template as well, so we should still format top-level <html>
- "html"].indexOf(node.fullName) === -1) {
- return true;
- } // TODO: handle non-text children in <pre>
- if (isPreLikeNode(node) && node.children.some(function (child) {
- return child.type !== "text" && child.type !== "interpolation";
- })) {
- return true;
- }
- return false;
- }
- function hasPrettierIgnore$3(node) {
- if (node.type === "attribute" || isTextLikeNode$1(node)) {
- return false;
- }
- if (!node.parent) {
- return false;
- }
- if (typeof node.index !== "number" || node.index === 0) {
- return false;
- }
- var prevNode = node.parent.children[node.index - 1];
- return isPrettierIgnore$1(prevNode);
- }
- function isPrettierIgnore$1(node) {
- return node.type === "comment" && node.value.trim() === "prettier-ignore";
- }
- function getPrettierIgnoreAttributeCommentData$1(value) {
- var match = value.trim().match(/^prettier-ignore-attribute(?:\s+([^]+))?$/);
- if (!match) {
- return false;
- }
- if (!match[1]) {
- return true;
- }
- return match[1].split(/\s+/);
- }
- /** there's no opening/closing tag or it's considered not breakable */
- function isTextLikeNode$1(node) {
- return node.type === "text" || node.type === "comment";
- }
- function isScriptLikeTag$1(node) {
- return node.type === "element" && (node.fullName === "script" || node.fullName === "style" || node.fullName === "svg:style");
- }
- function isFrontMatterNode(node) {
- return node.type === "yaml" || node.type === "toml";
- }
- function canHaveInterpolation(node) {
- return node.children && !isScriptLikeTag$1(node);
- }
- function isWhitespaceSensitiveNode(node) {
- return isScriptLikeTag$1(node) || node.type === "interpolation" || isIndentationSensitiveNode(node);
- }
- function isIndentationSensitiveNode(node) {
- return getNodeCssStyleWhiteSpace(node).startsWith("pre");
- }
- function isLeadingSpaceSensitiveNode(node) {
- var isLeadingSpaceSensitive = _isLeadingSpaceSensitiveNode();
- if (isLeadingSpaceSensitive && !node.prev && node.parent && node.parent.tagDefinition && node.parent.tagDefinition.ignoreFirstLf) {
- return node.type === "interpolation";
- }
- return isLeadingSpaceSensitive;
- function _isLeadingSpaceSensitiveNode() {
- if (isFrontMatterNode(node)) {
- return false;
- }
- if ((node.type === "text" || node.type === "interpolation") && node.prev && (node.prev.type === "text" || node.prev.type === "interpolation")) {
- return true;
- }
- if (!node.parent || node.parent.cssDisplay === "none") {
- return false;
- }
- if (isPreLikeNode(node.parent)) {
- return true;
- }
- if (!node.prev && (node.parent.type === "root" || isScriptLikeTag$1(node.parent) || !isFirstChildLeadingSpaceSensitiveCssDisplay(node.parent.cssDisplay))) {
- return false;
- }
- if (node.prev && !isNextLeadingSpaceSensitiveCssDisplay(node.prev.cssDisplay)) {
- return false;
- }
- return true;
- }
- }
- function isTrailingSpaceSensitiveNode(node) {
- if (isFrontMatterNode(node)) {
- return false;
- }
- if ((node.type === "text" || node.type === "interpolation") && node.next && (node.next.type === "text" || node.next.type === "interpolation")) {
- return true;
- }
- if (!node.parent || node.parent.cssDisplay === "none") {
- return false;
- }
- if (isPreLikeNode(node.parent)) {
- return true;
- }
- if (!node.next && (node.parent.type === "root" || isScriptLikeTag$1(node.parent) || !isLastChildTrailingSpaceSensitiveCssDisplay(node.parent.cssDisplay))) {
- return false;
- }
- if (node.next && !isPrevTrailingSpaceSensitiveCssDisplay(node.next.cssDisplay)) {
- return false;
- }
- return true;
- }
- function isDanglingSpaceSensitiveNode(node) {
- return isDanglingSpaceSensitiveCssDisplay(node.cssDisplay) && !isScriptLikeTag$1(node);
- }
- function forceNextEmptyLine$1(node) {
- return isFrontMatterNode(node) || node.next && node.sourceSpan.end.line + 1 < node.next.sourceSpan.start.line;
- }
- /** firstChild leadingSpaces and lastChild trailingSpaces */
- function forceBreakContent$1(node) {
- return forceBreakChildren$1(node) || node.type === "element" && node.children.length !== 0 && (["body", "template", "script", "style"].indexOf(node.name) !== -1 || node.children.some(function (child) {
- return hasNonTextChild(child);
- })) || node.firstChild && node.firstChild === node.lastChild && hasLeadingLineBreak(node.firstChild) && (!node.lastChild.isTrailingSpaceSensitive || hasTrailingLineBreak(node.lastChild));
- }
- /** spaces between children */
- function forceBreakChildren$1(node) {
- return node.type === "element" && node.children.length !== 0 && (["html", "head", "ul", "ol", "select"].indexOf(node.name) !== -1 || node.cssDisplay.startsWith("table") && node.cssDisplay !== "table-cell");
- }
- function preferHardlineAsLeadingSpaces$1(node) {
- return preferHardlineAsSurroundingSpaces(node) || node.prev && preferHardlineAsTrailingSpaces(node.prev) || hasSurroundingLineBreak(node);
- }
- function preferHardlineAsTrailingSpaces(node) {
- return preferHardlineAsSurroundingSpaces(node) || node.type === "element" && node.fullName === "br" || hasSurroundingLineBreak(node);
- }
- function hasSurroundingLineBreak(node) {
- return hasLeadingLineBreak(node) && hasTrailingLineBreak(node);
- }
- function hasLeadingLineBreak(node) {
- return node.hasLeadingSpaces && (node.prev ? node.prev.sourceSpan.end.line < node.sourceSpan.start.line : node.parent.type === "root" || node.parent.startSourceSpan.end.line < node.sourceSpan.start.line);
- }
- function hasTrailingLineBreak(node) {
- return node.hasTrailingSpaces && (node.next ? node.next.sourceSpan.start.line > node.sourceSpan.end.line : node.parent.type === "root" || node.parent.endSourceSpan.start.line > node.sourceSpan.end.line);
- }
- function preferHardlineAsSurroundingSpaces(node) {
- switch (node.type) {
- case "ieConditionalComment":
- case "comment":
- case "directive":
- return true;
- case "element":
- return ["script", "select"].indexOf(node.name) !== -1;
- }
- return false;
- }
- function getLastDescendant$1(node) {
- return node.lastChild ? getLastDescendant$1(node.lastChild) : node;
- }
- function hasNonTextChild(node) {
- return node.children && node.children.some(function (child) {
- return child.type !== "text";
- });
- }
- function inferScriptParser$1(node) {
- if (node.name === "script" && !node.attrMap.src) {
- if (!node.attrMap.lang && !node.attrMap.type || node.attrMap.type === "module" || node.attrMap.type === "text/javascript" || node.attrMap.type === "text/babel" || node.attrMap.type === "application/javascript") {
- return "babel";
- }
- if (node.attrMap.type === "application/x-typescript" || node.attrMap.lang === "ts" || node.attrMap.lang === "tsx") {
- return "typescript";
- }
- if (node.attrMap.type === "text/markdown") {
- return "markdown";
- }
- if (node.attrMap.type === "application/ld+json") {
- return "json";
- }
- }
- if (node.name === "style") {
- if (!node.attrMap.lang || node.attrMap.lang === "postcss") {
- return "css";
- }
- if (node.attrMap.lang === "scss") {
- return "scss";
- }
- if (node.attrMap.lang === "less") {
- return "less";
- }
- }
- return null;
- }
- function isBlockLikeCssDisplay(cssDisplay) {
- return cssDisplay === "block" || cssDisplay === "list-item" || cssDisplay.startsWith("table");
- }
- function isFirstChildLeadingSpaceSensitiveCssDisplay(cssDisplay) {
- return !isBlockLikeCssDisplay(cssDisplay) && cssDisplay !== "inline-block";
- }
- function isLastChildTrailingSpaceSensitiveCssDisplay(cssDisplay) {
- return !isBlockLikeCssDisplay(cssDisplay) && cssDisplay !== "inline-block";
- }
- function isPrevTrailingSpaceSensitiveCssDisplay(cssDisplay) {
- return !isBlockLikeCssDisplay(cssDisplay);
- }
- function isNextLeadingSpaceSensitiveCssDisplay(cssDisplay) {
- return !isBlockLikeCssDisplay(cssDisplay);
- }
- function isDanglingSpaceSensitiveCssDisplay(cssDisplay) {
- return !isBlockLikeCssDisplay(cssDisplay) && cssDisplay !== "inline-block";
- }
- function isPreLikeNode(node) {
- return getNodeCssStyleWhiteSpace(node).startsWith("pre");
- }
- function countParents$1(path$$1) {
- var predicate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function () {
- return true;
- };
- var counter = 0;
- for (var i = path$$1.stack.length - 1; i >= 0; i--) {
- var value = path$$1.stack[i];
- if (value && typeof value === "object" && !Array.isArray(value) && predicate(value)) {
- counter++;
- }
- }
- return counter;
- }
- function hasParent(node, fn) {
- var current = node;
- while (current) {
- if (fn(current)) {
- return true;
- }
- current = current.parent;
- }
- return false;
- }
- function getNodeCssStyleDisplay(node, options) {
- if (node.prev && node.prev.type === "comment") {
- // <!-- display: block -->
- var match = node.prev.value.match(/^\s*display:\s*([a-z]+)\s*$/);
- if (match) {
- return match[1];
- }
- }
- var isInSvgForeignObject = false;
- if (node.type === "element" && node.namespace === "svg") {
- if (hasParent(node, function (parent) {
- return parent.fullName === "svg:foreignObject";
- })) {
- isInSvgForeignObject = true;
- } else {
- return node.name === "svg" ? "inline-block" : "block";
- }
- }
- switch (options.htmlWhitespaceSensitivity) {
- case "strict":
- return "inline";
- case "ignore":
- return "block";
- default:
- return node.type === "element" && (!node.namespace || isInSvgForeignObject) && CSS_DISPLAY_TAGS[node.name] || CSS_DISPLAY_DEFAULT;
- }
- }
- function getNodeCssStyleWhiteSpace(node) {
- return node.type === "element" && !node.namespace && CSS_WHITE_SPACE_TAGS[node.name] || CSS_WHITE_SPACE_DEFAULT;
- }
- function getMinIndentation(text) {
- var minIndentation = Infinity;
- var _iteratorNormalCompletion2 = true;
- var _didIteratorError2 = false;
- var _iteratorError2 = undefined;
- try {
- for (var _iterator2 = text.split("\n")[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
- var lineText = _step2.value;
- if (lineText.length === 0) {
- continue;
- }
- if (/\S/.test(lineText[0])) {
- return 0;
- }
- var indentation = lineText.match(/^\s*/)[0].length;
- if (lineText.length === indentation) {
- continue;
- }
- if (indentation < minIndentation) {
- minIndentation = indentation;
- }
- }
- } catch (err) {
- _didIteratorError2 = true;
- _iteratorError2 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
- _iterator2.return();
- }
- } finally {
- if (_didIteratorError2) {
- throw _iteratorError2;
- }
- }
- }
- return minIndentation === Infinity ? 0 : minIndentation;
- }
- function dedentString$1(text) {
- var minIndent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : getMinIndentation(text);
- return minIndent === 0 ? text : text.split("\n").map(function (lineText) {
- return lineText.slice(minIndent);
- }).join("\n");
- }
- function normalizeParts$2(parts) {
- var newParts = [];
- var restParts = parts.slice();
- while (restParts.length !== 0) {
- var part = restParts.shift();
- if (!part) {
- continue;
- }
- if (part.type === "concat") {
- Array.prototype.unshift.apply(restParts, part.parts);
- continue;
- }
- if (newParts.length !== 0 && typeof newParts[newParts.length - 1] === "string" && typeof part === "string") {
- newParts.push(newParts.pop() + part);
- continue;
- }
- newParts.push(part);
- }
- return newParts;
- }
- function identity$2(x) {
- return x;
- }
- function shouldNotPrintClosingTag$1(node, options) {
- return !node.isSelfClosing && !node.endSourceSpan && (hasPrettierIgnore$3(node) || shouldPreserveContent$1(node.parent, options));
- }
- function countChars$1(text, char) {
- var counter = 0;
- for (var i = 0; i < text.length; i++) {
- if (text[i] === char) {
- counter++;
- }
- }
- return counter;
- }
- function unescapeQuoteEntities$1(text) {
- return text.replace(/'/g, "'").replace(/"/g, '"');
- }
- var utils$10 = {
- HTML_ELEMENT_ATTRIBUTES,
- HTML_TAGS,
- canHaveInterpolation,
- countChars: countChars$1,
- countParents: countParents$1,
- dedentString: dedentString$1,
- forceBreakChildren: forceBreakChildren$1,
- forceBreakContent: forceBreakContent$1,
- forceNextEmptyLine: forceNextEmptyLine$1,
- getLastDescendant: getLastDescendant$1,
- getNodeCssStyleDisplay,
- getNodeCssStyleWhiteSpace,
- getPrettierIgnoreAttributeCommentData: getPrettierIgnoreAttributeCommentData$1,
- hasPrettierIgnore: hasPrettierIgnore$3,
- identity: identity$2,
- inferScriptParser: inferScriptParser$1,
- isDanglingSpaceSensitiveNode,
- isFrontMatterNode,
- isIndentationSensitiveNode,
- isLeadingSpaceSensitiveNode,
- isPreLikeNode,
- isScriptLikeTag: isScriptLikeTag$1,
- isTextLikeNode: isTextLikeNode$1,
- isTrailingSpaceSensitiveNode,
- isWhitespaceSensitiveNode,
- normalizeParts: normalizeParts$2,
- preferHardlineAsLeadingSpaces: preferHardlineAsLeadingSpaces$1,
- preferHardlineAsTrailingSpaces,
- shouldNotPrintClosingTag: shouldNotPrintClosingTag$1,
- shouldPreserveContent: shouldPreserveContent$1,
- unescapeQuoteEntities: unescapeQuoteEntities$1
- };
- var canHaveInterpolation$1 = utils$10.canHaveInterpolation;
- var getNodeCssStyleDisplay$1 = utils$10.getNodeCssStyleDisplay;
- var isDanglingSpaceSensitiveNode$1 = utils$10.isDanglingSpaceSensitiveNode;
- var isIndentationSensitiveNode$1 = utils$10.isIndentationSensitiveNode;
- var isLeadingSpaceSensitiveNode$1 = utils$10.isLeadingSpaceSensitiveNode;
- var isTrailingSpaceSensitiveNode$1 = utils$10.isTrailingSpaceSensitiveNode;
- var isWhitespaceSensitiveNode$1 = utils$10.isWhitespaceSensitiveNode;
- var PREPROCESS_PIPELINE = [removeIgnorableFirstLf, mergeIeConditonalStartEndCommentIntoElementOpeningTag, mergeCdataIntoText, extractInterpolation, extractWhitespaces, addCssDisplay, addIsSelfClosing, addHasHtmComponentClosingTag, addIsSpaceSensitive, mergeSimpleElementIntoText];
- function preprocess$4(ast, options) {
- for (var _i = 0; _i < PREPROCESS_PIPELINE.length; _i++) {
- var fn = PREPROCESS_PIPELINE[_i];
- ast = fn(ast, options);
- }
- return ast;
- }
- function removeIgnorableFirstLf(ast
- /*, options */
- ) {
- return ast.map(function (node) {
- if (node.type === "element" && node.tagDefinition.ignoreFirstLf && node.children.length !== 0 && node.children[0].type === "text" && node.children[0].value[0] === "\n") {
- var text = node.children[0];
- return node.clone({
- children: text.value.length === 1 ? node.children.slice(1) : [].concat(text.clone({
- value: text.value.slice(1)
- }), node.children.slice(1))
- });
- }
- return node;
- });
- }
- function mergeIeConditonalStartEndCommentIntoElementOpeningTag(ast
- /*, options */
- ) {
- /**
- * <!--[if ...]><!--><target><!--<![endif]-->
- */
- var isTarget = function isTarget(node) {
- return node.type === "element" && node.prev && node.prev.type === "ieConditionalStartComment" && node.prev.sourceSpan.end.offset === node.startSourceSpan.start.offset && node.firstChild && node.firstChild.type === "ieConditionalEndComment" && node.firstChild.sourceSpan.start.offset === node.startSourceSpan.end.offset;
- };
- return ast.map(function (node) {
- if (node.children) {
- var isTargetResults = node.children.map(isTarget);
- if (isTargetResults.some(Boolean)) {
- var newChildren = [];
- for (var i = 0; i < node.children.length; i++) {
- var child = node.children[i];
- if (isTargetResults[i + 1]) {
- // ieConditionalStartComment
- continue;
- }
- if (isTargetResults[i]) {
- var ieConditionalStartComment = child.prev;
- var ieConditionalEndComment = child.firstChild;
- var ParseSourceSpan = child.sourceSpan.constructor;
- var startSourceSpan = new ParseSourceSpan(ieConditionalStartComment.sourceSpan.start, ieConditionalEndComment.sourceSpan.end);
- var sourceSpan = new ParseSourceSpan(startSourceSpan.start, child.sourceSpan.end);
- newChildren.push(child.clone({
- condition: ieConditionalStartComment.condition,
- sourceSpan,
- startSourceSpan,
- children: child.children.slice(1)
- }));
- continue;
- }
- newChildren.push(child);
- }
- return node.clone({
- children: newChildren
- });
- }
- }
- return node;
- });
- }
- function mergeNodeIntoText(ast, shouldMerge, getValue) {
- return ast.map(function (node) {
- if (node.children) {
- var shouldMergeResults = node.children.map(shouldMerge);
- if (shouldMergeResults.some(Boolean)) {
- var newChildren = [];
- for (var i = 0; i < node.children.length; i++) {
- var child = node.children[i];
- if (child.type !== "text" && !shouldMergeResults[i]) {
- newChildren.push(child);
- continue;
- }
- var newChild = child.type === "text" ? child : child.clone({
- type: "text",
- value: getValue(child)
- });
- if (newChildren.length === 0 || newChildren[newChildren.length - 1].type !== "text") {
- newChildren.push(newChild);
- continue;
- }
- var lastChild = newChildren.pop();
- var ParseSourceSpan = lastChild.sourceSpan.constructor;
- newChildren.push(lastChild.clone({
- value: lastChild.value + newChild.value,
- sourceSpan: new ParseSourceSpan(lastChild.sourceSpan.start, newChild.sourceSpan.end)
- }));
- }
- return node.clone({
- children: newChildren
- });
- }
- }
- return node;
- });
- }
- function mergeCdataIntoText(ast
- /*, options */
- ) {
- return mergeNodeIntoText(ast, function (node) {
- return node.type === "cdata";
- }, function (node) {
- return `<![CDATA[${node.value}]]>`;
- });
- }
- function mergeSimpleElementIntoText(ast
- /*, options */
- ) {
- var isSimpleElement = function isSimpleElement(node) {
- return node.type === "element" && node.attrs.length === 0 && node.children.length === 1 && node.firstChild.type === "text" && // \xA0: non-breaking whitespace
- !/[^\S\xA0]/.test(node.children[0].value) && !node.firstChild.hasLeadingSpaces && !node.firstChild.hasTrailingSpaces && node.isLeadingSpaceSensitive && !node.hasLeadingSpaces && node.isTrailingSpaceSensitive && !node.hasTrailingSpaces && node.prev && node.prev.type === "text" && node.next && node.next.type === "text";
- };
- return ast.map(function (node) {
- if (node.children) {
- var isSimpleElementResults = node.children.map(isSimpleElement);
- if (isSimpleElementResults.some(Boolean)) {
- var newChildren = [];
- for (var i = 0; i < node.children.length; i++) {
- var child = node.children[i];
- if (isSimpleElementResults[i]) {
- var lastChild = newChildren.pop();
- var nextChild = node.children[++i];
- var ParseSourceSpan = node.sourceSpan.constructor;
- var isTrailingSpaceSensitive = nextChild.isTrailingSpaceSensitive,
- hasTrailingSpaces = nextChild.hasTrailingSpaces;
- newChildren.push(lastChild.clone({
- value: lastChild.value + `<${child.rawName}>` + child.firstChild.value + `</${child.rawName}>` + nextChild.value,
- sourceSpan: new ParseSourceSpan(lastChild.sourceSpan.start, nextChild.sourceSpan.end),
- isTrailingSpaceSensitive,
- hasTrailingSpaces
- }));
- } else {
- newChildren.push(child);
- }
- }
- return node.clone({
- children: newChildren
- });
- }
- }
- return node;
- });
- }
- function extractInterpolation(ast, options) {
- if (options.parser === "html") {
- return ast;
- }
- var interpolationRegex = /\{\{([\s\S]+?)\}\}/g;
- return ast.map(function (node) {
- if (!canHaveInterpolation$1(node)) {
- return node;
- }
- var newChildren = [];
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = node.children[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var child = _step.value;
- if (child.type !== "text") {
- newChildren.push(child);
- continue;
- }
- var ParseSourceSpan = child.sourceSpan.constructor;
- var startSourceSpan = child.sourceSpan.start;
- var endSourceSpan = null;
- var components = child.value.split(interpolationRegex);
- for (var i = 0; i < components.length; i++, startSourceSpan = endSourceSpan) {
- var value = components[i];
- if (i % 2 === 0) {
- endSourceSpan = startSourceSpan.moveBy(value.length);
- if (value.length !== 0) {
- newChildren.push({
- type: "text",
- value,
- sourceSpan: new ParseSourceSpan(startSourceSpan, endSourceSpan)
- });
- }
- continue;
- }
- endSourceSpan = startSourceSpan.moveBy(value.length + 4); // `{{` + `}}`
- newChildren.push({
- type: "interpolation",
- sourceSpan: new ParseSourceSpan(startSourceSpan, endSourceSpan),
- children: value.length === 0 ? [] : [{
- type: "text",
- value,
- sourceSpan: new ParseSourceSpan(startSourceSpan.moveBy(2), endSourceSpan.moveBy(-2))
- }]
- });
- }
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- return node.clone({
- children: newChildren
- });
- });
- }
- /**
- * - add `hasLeadingSpaces` field
- * - add `hasTrailingSpaces` field
- * - add `hasDanglingSpaces` field for parent nodes
- * - add `isWhitespaceSensitive`, `isIndentationSensitive` field for text nodes
- * - remove insensitive whitespaces
- */
- function extractWhitespaces(ast
- /*, options*/
- ) {
- var TYPE_WHITESPACE = "whitespace";
- return ast.map(function (node) {
- if (!node.children) {
- return node;
- }
- if (node.children.length === 0 || node.children.length === 1 && node.children[0].type === "text" && node.children[0].value.trim().length === 0) {
- return node.clone({
- children: [],
- hasDanglingSpaces: node.children.length !== 0
- });
- }
- var isWhitespaceSensitive = isWhitespaceSensitiveNode$1(node);
- var isIndentationSensitive = isIndentationSensitiveNode$1(node);
- return node.clone({
- isWhitespaceSensitive,
- isIndentationSensitive,
- children: node.children // extract whitespace nodes
- .reduce(function (newChildren, child) {
- if (child.type !== "text" || isWhitespaceSensitive) {
- return newChildren.concat(child);
- }
- var localChildren = [];
- var _child$value$match = child.value.match(/^(\s*)([\s\S]*?)(\s*)$/),
- _child$value$match2 = _slicedToArray(_child$value$match, 4),
- leadingSpaces = _child$value$match2[1],
- text = _child$value$match2[2],
- trailingSpaces = _child$value$match2[3];
- if (leadingSpaces) {
- localChildren.push({
- type: TYPE_WHITESPACE
- });
- }
- var ParseSourceSpan = child.sourceSpan.constructor;
- if (text) {
- localChildren.push({
- type: "text",
- value: text,
- sourceSpan: new ParseSourceSpan(child.sourceSpan.start.moveBy(leadingSpaces.length), child.sourceSpan.end.moveBy(-trailingSpaces.length))
- });
- }
- if (trailingSpaces) {
- localChildren.push({
- type: TYPE_WHITESPACE
- });
- }
- return newChildren.concat(localChildren);
- }, []) // set hasLeadingSpaces/hasTrailingSpaces and filter whitespace nodes
- .reduce(function (newChildren, child, i, children) {
- if (child.type === TYPE_WHITESPACE) {
- return newChildren;
- }
- var hasLeadingSpaces = i !== 0 && children[i - 1].type === TYPE_WHITESPACE;
- var hasTrailingSpaces = i !== children.length - 1 && children[i + 1].type === TYPE_WHITESPACE;
- return newChildren.concat(Object.assign({}, child, {
- hasLeadingSpaces,
- hasTrailingSpaces
- }));
- }, [])
- });
- });
- }
- function addIsSelfClosing(ast
- /*, options */
- ) {
- return ast.map(function (node) {
- return Object.assign(node, {
- isSelfClosing: !node.children || node.type === "element" && (node.tagDefinition.isVoid || // self-closing
- node.startSourceSpan === node.endSourceSpan)
- });
- });
- }
- function addHasHtmComponentClosingTag(ast, options) {
- return ast.map(function (node) {
- return node.type !== "element" ? node : Object.assign(node, {
- hasHtmComponentClosingTag: node.endSourceSpan && /^<\s*\/\s*\/\s*>$/.test(options.originalText.slice(node.endSourceSpan.start.offset, node.endSourceSpan.end.offset))
- });
- });
- }
- function addCssDisplay(ast, options) {
- return ast.map(function (node) {
- return Object.assign(node, {
- cssDisplay: getNodeCssStyleDisplay$1(node, options)
- });
- });
- }
- /**
- * - add `isLeadingSpaceSensitive` field
- * - add `isTrailingSpaceSensitive` field
- * - add `isDanglingSpaceSensitive` field for parent nodes
- */
- function addIsSpaceSensitive(ast
- /*, options */
- ) {
- return ast.map(function (node) {
- if (!node.children) {
- return node;
- }
- if (node.children.length === 0) {
- return node.clone({
- isDanglingSpaceSensitive: isDanglingSpaceSensitiveNode$1(node)
- });
- }
- return node.clone({
- children: node.children.map(function (child) {
- return Object.assign({}, child, {
- isLeadingSpaceSensitive: isLeadingSpaceSensitiveNode$1(child),
- isTrailingSpaceSensitive: isTrailingSpaceSensitiveNode$1(child)
- });
- }).map(function (child, index, children) {
- return Object.assign({}, child, {
- isLeadingSpaceSensitive: index === 0 ? child.isLeadingSpaceSensitive : children[index - 1].isTrailingSpaceSensitive && child.isLeadingSpaceSensitive,
- isTrailingSpaceSensitive: index === children.length - 1 ? child.isTrailingSpaceSensitive : children[index + 1].isLeadingSpaceSensitive && child.isTrailingSpaceSensitive
- });
- })
- });
- });
- }
- var preprocess_1$4 = preprocess$4;
- function hasPragma$3(text) {
- return /^\s*<!--\s*@(format|prettier)\s*-->/.test(text);
- }
- function insertPragma$7(text) {
- return "<!-- @format -->\n\n" + text.replace(/^\s*\n/, "");
- }
- var pragma$9 = {
- hasPragma: hasPragma$3,
- insertPragma: insertPragma$7
- };
- var _require$$0$builders$8 = doc.builders;
- var concat$15 = _require$$0$builders$8.concat;
- var group$15 = _require$$0$builders$8.group;
- /**
- * v-for="... in ..."
- * v-for="... of ..."
- * v-for="(..., ...) in ..."
- * v-for="(..., ...) of ..."
- */
- function printVueFor$1(value, textToDoc) {
- var _parseVueFor = parseVueFor(value),
- left = _parseVueFor.left,
- operator = _parseVueFor.operator,
- right = _parseVueFor.right;
- return concat$15([group$15(textToDoc(`function _(${left}) {}`, {
- parser: "babel",
- __isVueForBindingLeft: true
- })), " ", operator, " ", textToDoc(right, {
- parser: "__js_expression"
- })]);
- } // modified from https://github.com/vuejs/vue/blob/v2.5.17/src/compiler/parser/index.js#L370-L387
- function parseVueFor(value) {
- var forAliasRE = /([^]*?)\s+(in|of)\s+([^]*)/;
- var forIteratorRE = /,([^,}\]]*)(?:,([^,}\]]*))?$/;
- var stripParensRE = /^\(|\)$/g;
- var inMatch = value.match(forAliasRE);
- if (!inMatch) {
- return;
- }
- var res = {};
- res.for = inMatch[3].trim();
- var alias = inMatch[1].trim().replace(stripParensRE, "");
- var iteratorMatch = alias.match(forIteratorRE);
- if (iteratorMatch) {
- res.alias = alias.replace(forIteratorRE, "");
- res.iterator1 = iteratorMatch[1].trim();
- if (iteratorMatch[2]) {
- res.iterator2 = iteratorMatch[2].trim();
- }
- } else {
- res.alias = alias;
- }
- return {
- left: `${[res.alias, res.iterator1, res.iterator2].filter(Boolean).join(",")}`,
- operator: inMatch[2],
- right: res.for
- };
- }
- function printVueSlotScope$1(value, textToDoc) {
- return textToDoc(`function _(${value}) {}`, {
- parser: "babel",
- __isVueSlotScope: true
- });
- }
- function isVueEventBindingExpression$3(eventBindingValue) {
- // https://github.com/vuejs/vue/blob/v2.5.17/src/compiler/codegen/events.js#L3-L4
- // arrow function or anonymous function
- var fnExpRE = /^([\w$_]+|\([^)]*?\))\s*=>|^function\s*\(/; // simple member expression chain (a, a.b, a['b'], a["b"], a[0], a[b])
- var simplePathRE = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['[^']*?']|\["[^"]*?"]|\[\d+]|\[[A-Za-z_$][\w$]*])*$/; // https://github.com/vuejs/vue/blob/v2.5.17/src/compiler/helpers.js#L104
- var value = eventBindingValue.trim();
- return fnExpRE.test(value) || simplePathRE.test(value);
- }
- var syntaxVue = {
- isVueEventBindingExpression: isVueEventBindingExpression$3,
- printVueFor: printVueFor$1,
- printVueSlotScope: printVueSlotScope$1
- };
- var parseSrcset = createCommonjsModule(function (module) {
- /**
- * Srcset Parser
- *
- * By Alex Bell | MIT License
- *
- * JS Parser for the string value that appears in markup <img srcset="here">
- *
- * @returns Array [{url: _, d: _, w: _, h:_}, ...]
- *
- * Based super duper closely on the reference algorithm at:
- * https://html.spec.whatwg.org/multipage/embedded-content.html#parse-a-srcset-attribute
- *
- * Most comments are copied in directly from the spec
- * (except for comments in parens).
- */
- (function (root, factory) {
- if (typeof undefined === 'function' && undefined.amd) {
- // AMD. Register as an anonymous module.
- undefined([], factory);
- } else if ('object' === 'object' && module.exports) {
- // Node. Does not work with strict CommonJS, but
- // only CommonJS-like environments that support module.exports,
- // like Node.
- module.exports = factory();
- } else {
- // Browser globals (root is window)
- root.parseSrcset = factory();
- }
- })(commonjsGlobal, function () {
- // 1. Let input be the value passed to this algorithm.
- return function (input, options) {
- var logger = options && options.logger || console; // UTILITY FUNCTIONS
- // Manual is faster than RegEx
- // http://bjorn.tipling.com/state-and-regular-expressions-in-javascript
- // http://jsperf.com/whitespace-character/5
- function isSpace(c) {
- return c === "\u0020" || // space
- c === "\u0009" || // horizontal tab
- c === "\u000A" || // new line
- c === "\u000C" || // form feed
- c === "\u000D"; // carriage return
- }
- function collectCharacters(regEx) {
- var chars,
- match = regEx.exec(input.substring(pos));
- if (match) {
- chars = match[0];
- pos += chars.length;
- return chars;
- }
- }
- var inputLength = input.length,
- // (Don't use \s, to avoid matching non-breaking space)
- regexLeadingSpaces = /^[ \t\n\r\u000c]+/,
- regexLeadingCommasOrSpaces = /^[, \t\n\r\u000c]+/,
- regexLeadingNotSpaces = /^[^ \t\n\r\u000c]+/,
- regexTrailingCommas = /[,]+$/,
- regexNonNegativeInteger = /^\d+$/,
- // ( Positive or negative or unsigned integers or decimals, without or without exponents.
- // Must include at least one digit.
- // According to spec tests any decimal point must be followed by a digit.
- // No leading plus sign is allowed.)
- // https://html.spec.whatwg.org/multipage/infrastructure.html#valid-floating-point-number
- regexFloatingPoint = /^-?(?:[0-9]+|[0-9]*\.[0-9]+)(?:[eE][+-]?[0-9]+)?$/,
- url,
- descriptors,
- currentDescriptor,
- state,
- c,
- // 2. Let position be a pointer into input, initially pointing at the start
- // of the string.
- pos = 0,
- // 3. Let candidates be an initially empty source set.
- candidates = []; // 4. Splitting loop: Collect a sequence of characters that are space
- // characters or U+002C COMMA characters. If any U+002C COMMA characters
- // were collected, that is a parse error.
- while (true) {
- collectCharacters(regexLeadingCommasOrSpaces); // 5. If position is past the end of input, return candidates and abort these steps.
- if (pos >= inputLength) {
- return candidates; // (we're done, this is the sole return path)
- } // 6. Collect a sequence of characters that are not space characters,
- // and let that be url.
- url = collectCharacters(regexLeadingNotSpaces); // 7. Let descriptors be a new empty list.
- descriptors = []; // 8. If url ends with a U+002C COMMA character (,), follow these substeps:
- // (1). Remove all trailing U+002C COMMA characters from url. If this removed
- // more than one character, that is a parse error.
- if (url.slice(-1) === ",") {
- url = url.replace(regexTrailingCommas, ""); // (Jump ahead to step 9 to skip tokenization and just push the candidate).
- parseDescriptors(); // Otherwise, follow these substeps:
- } else {
- tokenize();
- } // (close else of step 8)
- // 16. Return to the step labeled splitting loop.
- } // (Close of big while loop.)
- /**
- * Tokenizes descriptor properties prior to parsing
- * Returns undefined.
- */
- function tokenize() {
- // 8.1. Descriptor tokeniser: Skip whitespace
- collectCharacters(regexLeadingSpaces); // 8.2. Let current descriptor be the empty string.
- currentDescriptor = ""; // 8.3. Let state be in descriptor.
- state = "in descriptor";
- while (true) {
- // 8.4. Let c be the character at position.
- c = input.charAt(pos); // Do the following depending on the value of state.
- // For the purpose of this step, "EOF" is a special character representing
- // that position is past the end of input.
- // In descriptor
- if (state === "in descriptor") {
- // Do the following, depending on the value of c:
- // Space character
- // If current descriptor is not empty, append current descriptor to
- // descriptors and let current descriptor be the empty string.
- // Set state to after descriptor.
- if (isSpace(c)) {
- if (currentDescriptor) {
- descriptors.push(currentDescriptor);
- currentDescriptor = "";
- state = "after descriptor";
- } // U+002C COMMA (,)
- // Advance position to the next character in input. If current descriptor
- // is not empty, append current descriptor to descriptors. Jump to the step
- // labeled descriptor parser.
- } else if (c === ",") {
- pos += 1;
- if (currentDescriptor) {
- descriptors.push(currentDescriptor);
- }
- parseDescriptors();
- return; // U+0028 LEFT PARENTHESIS (()
- // Append c to current descriptor. Set state to in parens.
- } else if (c === "\u0028") {
- currentDescriptor = currentDescriptor + c;
- state = "in parens"; // EOF
- // If current descriptor is not empty, append current descriptor to
- // descriptors. Jump to the step labeled descriptor parser.
- } else if (c === "") {
- if (currentDescriptor) {
- descriptors.push(currentDescriptor);
- }
- parseDescriptors();
- return; // Anything else
- // Append c to current descriptor.
- } else {
- currentDescriptor = currentDescriptor + c;
- } // (end "in descriptor"
- // In parens
- } else if (state === "in parens") {
- // U+0029 RIGHT PARENTHESIS ())
- // Append c to current descriptor. Set state to in descriptor.
- if (c === ")") {
- currentDescriptor = currentDescriptor + c;
- state = "in descriptor"; // EOF
- // Append current descriptor to descriptors. Jump to the step labeled
- // descriptor parser.
- } else if (c === "") {
- descriptors.push(currentDescriptor);
- parseDescriptors();
- return; // Anything else
- // Append c to current descriptor.
- } else {
- currentDescriptor = currentDescriptor + c;
- } // After descriptor
- } else if (state === "after descriptor") {
- // Do the following, depending on the value of c:
- // Space character: Stay in this state.
- if (isSpace(c)) {// EOF: Jump to the step labeled descriptor parser.
- } else if (c === "") {
- parseDescriptors();
- return; // Anything else
- // Set state to in descriptor. Set position to the previous character in input.
- } else {
- state = "in descriptor";
- pos -= 1;
- }
- } // Advance position to the next character in input.
- pos += 1; // Repeat this step.
- } // (close while true loop)
- }
- /**
- * Adds descriptor properties to a candidate, pushes to the candidates array
- * @return undefined
- */
- // Declared outside of the while loop so that it's only created once.
- function parseDescriptors() {
- // 9. Descriptor parser: Let error be no.
- var pError = false,
- // 10. Let width be absent.
- // 11. Let density be absent.
- // 12. Let future-compat-h be absent. (We're implementing it now as h)
- w,
- d,
- h,
- i,
- candidate = {},
- desc,
- lastChar,
- value,
- intVal,
- floatVal; // 13. For each descriptor in descriptors, run the appropriate set of steps
- // from the following list:
- for (i = 0; i < descriptors.length; i++) {
- desc = descriptors[i];
- lastChar = desc[desc.length - 1];
- value = desc.substring(0, desc.length - 1);
- intVal = parseInt(value, 10);
- floatVal = parseFloat(value); // If the descriptor consists of a valid non-negative integer followed by
- // a U+0077 LATIN SMALL LETTER W character
- if (regexNonNegativeInteger.test(value) && lastChar === "w") {
- // If width and density are not both absent, then let error be yes.
- if (w || d) {
- pError = true;
- } // Apply the rules for parsing non-negative integers to the descriptor.
- // If the result is zero, let error be yes.
- // Otherwise, let width be the result.
- if (intVal === 0) {
- pError = true;
- } else {
- w = intVal;
- } // If the descriptor consists of a valid floating-point number followed by
- // a U+0078 LATIN SMALL LETTER X character
- } else if (regexFloatingPoint.test(value) && lastChar === "x") {
- // If width, density and future-compat-h are not all absent, then let error
- // be yes.
- if (w || d || h) {
- pError = true;
- } // Apply the rules for parsing floating-point number values to the descriptor.
- // If the result is less than zero, let error be yes. Otherwise, let density
- // be the result.
- if (floatVal < 0) {
- pError = true;
- } else {
- d = floatVal;
- } // If the descriptor consists of a valid non-negative integer followed by
- // a U+0068 LATIN SMALL LETTER H character
- } else if (regexNonNegativeInteger.test(value) && lastChar === "h") {
- // If height and density are not both absent, then let error be yes.
- if (h || d) {
- pError = true;
- } // Apply the rules for parsing non-negative integers to the descriptor.
- // If the result is zero, let error be yes. Otherwise, let future-compat-h
- // be the result.
- if (intVal === 0) {
- pError = true;
- } else {
- h = intVal;
- } // Anything else, Let error be yes.
- } else {
- pError = true;
- }
- } // (close step 13 for loop)
- // 15. If error is still no, then append a new image source to candidates whose
- // URL is url, associated with a width width if not absent and a pixel
- // density density if not absent. Otherwise, there is a parse error.
- if (!pError) {
- candidate.url = url;
- if (w) {
- candidate.w = w;
- }
- if (d) {
- candidate.d = d;
- }
- if (h) {
- candidate.h = h;
- }
- candidates.push(candidate);
- } else if (logger && logger.error) {
- logger.error("Invalid srcset descriptor found in '" + input + "' at '" + desc + "'.");
- }
- } // (close parseDescriptors fn)
- };
- });
- });
- var _require$$0$builders$9 = doc.builders;
- var concat$16 = _require$$0$builders$9.concat;
- var ifBreak$6 = _require$$0$builders$9.ifBreak;
- var join$11 = _require$$0$builders$9.join;
- var line$10 = _require$$0$builders$9.line;
- function printImgSrcset$1(value) {
- var srcset = parseSrcset(value, {
- logger: {
- error(message) {
- throw new Error(message);
- }
- }
- });
- var hasW = srcset.some(function (src) {
- return src.w;
- });
- var hasH = srcset.some(function (src) {
- return src.h;
- });
- var hasX = srcset.some(function (src) {
- return src.d;
- });
- if (hasW + hasH + hasX !== 1) {
- throw new Error(`Mixed descriptor in srcset is not supported`);
- }
- var key = hasW ? "w" : hasH ? "h" : "d";
- var unit = hasW ? "w" : hasH ? "h" : "x";
- var getMax = function getMax(values) {
- return Math.max.apply(Math, values);
- };
- var urls = srcset.map(function (src) {
- return src.url;
- });
- var maxUrlLength = getMax(urls.map(function (url) {
- return url.length;
- }));
- var descriptors = srcset.map(function (src) {
- return src[key];
- }).map(function (descriptor) {
- return descriptor ? descriptor.toString() : "";
- });
- var descriptorLeftLengths = descriptors.map(function (descriptor) {
- var index = descriptor.indexOf(".");
- return index === -1 ? descriptor.length : index;
- });
- var maxDescriptorLeftLength = getMax(descriptorLeftLengths);
- return join$11(concat$16([",", line$10]), urls.map(function (url, index) {
- var parts = [url];
- var descriptor = descriptors[index];
- if (descriptor) {
- var urlPadding = maxUrlLength - url.length + 1;
- var descriptorPadding = maxDescriptorLeftLength - descriptorLeftLengths[index];
- var alignment = " ".repeat(urlPadding + descriptorPadding);
- parts.push(ifBreak$6(alignment, " "), descriptor + unit);
- }
- return concat$16(parts);
- }));
- }
- var syntaxAttribute = {
- printImgSrcset: printImgSrcset$1
- };
- var builders = doc.builders;
- var _require$$0$utils = doc.utils;
- var stripTrailingHardline$2 = _require$$0$utils.stripTrailingHardline;
- var mapDoc$7 = _require$$0$utils.mapDoc;
- var breakParent$3 = builders.breakParent;
- var dedentToRoot$2 = builders.dedentToRoot;
- var fill$5 = builders.fill;
- var group$14 = builders.group;
- var hardline$12 = builders.hardline;
- var ifBreak$5 = builders.ifBreak;
- var indent$9 = builders.indent;
- var join$10 = builders.join;
- var line$9 = builders.line;
- var literalline$6 = builders.literalline;
- var markAsRoot$4 = builders.markAsRoot;
- var softline$7 = builders.softline;
- var countChars = utils$10.countChars;
- var countParents = utils$10.countParents;
- var dedentString = utils$10.dedentString;
- var forceBreakChildren = utils$10.forceBreakChildren;
- var forceBreakContent = utils$10.forceBreakContent;
- var forceNextEmptyLine = utils$10.forceNextEmptyLine;
- var getLastDescendant = utils$10.getLastDescendant;
- var getPrettierIgnoreAttributeCommentData = utils$10.getPrettierIgnoreAttributeCommentData;
- var hasPrettierIgnore$2 = utils$10.hasPrettierIgnore;
- var inferScriptParser = utils$10.inferScriptParser;
- var isScriptLikeTag = utils$10.isScriptLikeTag;
- var isTextLikeNode = utils$10.isTextLikeNode;
- var normalizeParts$1 = utils$10.normalizeParts;
- var preferHardlineAsLeadingSpaces = utils$10.preferHardlineAsLeadingSpaces;
- var shouldNotPrintClosingTag = utils$10.shouldNotPrintClosingTag;
- var shouldPreserveContent = utils$10.shouldPreserveContent;
- var unescapeQuoteEntities = utils$10.unescapeQuoteEntities;
- var replaceEndOfLineWith$2 = util$1.replaceEndOfLineWith;
- var insertPragma$6 = pragma$9.insertPragma;
- var printVueFor = syntaxVue.printVueFor;
- var printVueSlotScope = syntaxVue.printVueSlotScope;
- var isVueEventBindingExpression$2 = syntaxVue.isVueEventBindingExpression;
- var printImgSrcset = syntaxAttribute.printImgSrcset;
- function concat$14(parts) {
- var newParts = normalizeParts$1(parts);
- return newParts.length === 0 ? "" : newParts.length === 1 ? newParts[0] : builders.concat(newParts);
- }
- function embed$6(path$$1, print, textToDoc, options) {
- var node = path$$1.getValue();
- switch (node.type) {
- case "text":
- {
- if (isScriptLikeTag(node.parent)) {
- var parser = inferScriptParser(node.parent);
- if (parser) {
- var value = parser === "markdown" ? dedentString(node.value.replace(/^[^\S\n]*?\n/, "")) : node.value;
- return builders.concat([concat$14([breakParent$3, printOpeningTagPrefix(node, options), stripTrailingHardline$2(textToDoc(value, {
- parser
- })), printClosingTagSuffix(node, options)])]);
- }
- } else if (node.parent.type === "interpolation") {
- return concat$14([indent$9(concat$14([line$9, textToDoc(node.value, Object.assign({
- __isInHtmlInterpolation: true // to avoid unexpected `}}`
- }, options.parser === "angular" ? {
- parser: "__ng_interpolation",
- trailingComma: "none"
- } : options.parser === "vue" ? {
- parser: "__vue_expression"
- } : {
- parser: "__js_expression"
- }))])), node.parent.next && needsToBorrowPrevClosingTagEndMarker(node.parent.next) ? " " : line$9]);
- }
- break;
- }
- case "attribute":
- {
- if (!node.value) {
- break;
- } // lit-html: html`<my-element obj=${obj}></my-element>`
- if (/^PRETTIER_HTML_PLACEHOLDER_\d+_IN_JS$/.test(options.originalText.slice(node.valueSpan.start.offset, node.valueSpan.end.offset))) {
- return concat$14([node.rawName, "=", node.value]);
- }
- var embeddedAttributeValueDoc = printEmbeddedAttributeValue(node, function (code, opts) {
- return (// strictly prefer single quote to avoid unnecessary html entity escape
- textToDoc(code, Object.assign({
- __isInHtmlAttribute: true
- }, opts))
- );
- }, options);
- if (embeddedAttributeValueDoc) {
- return concat$14([node.rawName, '="', group$14(mapDoc$7(embeddedAttributeValueDoc, function (doc$$2) {
- return typeof doc$$2 === "string" ? doc$$2.replace(/"/g, """) : doc$$2;
- })), '"']);
- }
- break;
- }
- case "yaml":
- return markAsRoot$4(concat$14(["---", hardline$12, node.value.trim().length === 0 ? "" : textToDoc(node.value, {
- parser: "yaml"
- }), "---"]));
- }
- }
- function genericPrint$5(path$$1, options, print) {
- var node = path$$1.getValue();
- switch (node.type) {
- case "root":
- // use original concat to not break stripTrailingHardline
- return builders.concat([group$14(printChildren$1(path$$1, options, print)), hardline$12]);
- case "element":
- case "ieConditionalComment":
- {
- /**
- * do not break:
- *
- * <div>{{
- * ~
- * interpolation
- * }}</div>
- * ~
- *
- * exception: break if the opening tag breaks
- *
- * <div
- * long
- * ~
- * >{{
- * interpolation
- * }}</div
- * ~
- * >
- */
- var shouldHugContent = node.children.length === 1 && node.firstChild.type === "interpolation" && node.firstChild.isLeadingSpaceSensitive && !node.firstChild.hasLeadingSpaces && node.lastChild.isTrailingSpaceSensitive && !node.lastChild.hasTrailingSpaces;
- var attrGroupId = Symbol("element-attr-group-id");
- return concat$14([group$14(concat$14([group$14(printOpeningTag(path$$1, options, print), {
- id: attrGroupId
- }), node.children.length === 0 ? node.hasDanglingSpaces && node.isDanglingSpaceSensitive ? line$9 : "" : concat$14([forceBreakContent(node) ? breakParent$3 : "", function (childrenDoc) {
- return shouldHugContent ? ifBreak$5(indent$9(childrenDoc), childrenDoc, {
- groupId: attrGroupId
- }) : isScriptLikeTag(node) && node.parent.type === "root" && options.parser === "vue" ? childrenDoc : indent$9(childrenDoc);
- }(concat$14([shouldHugContent ? ifBreak$5(softline$7, "", {
- groupId: attrGroupId
- }) : node.firstChild.hasLeadingSpaces && node.firstChild.isLeadingSpaceSensitive ? line$9 : node.firstChild.type === "text" && node.isWhitespaceSensitive && node.isIndentationSensitive ? dedentToRoot$2(softline$7) : softline$7, printChildren$1(path$$1, options, print)])), (node.next ? needsToBorrowPrevClosingTagEndMarker(node.next) : needsToBorrowLastChildClosingTagEndMarker(node.parent)) ? node.lastChild.hasTrailingSpaces && node.lastChild.isTrailingSpaceSensitive ? " " : "" : shouldHugContent ? ifBreak$5(softline$7, "", {
- groupId: attrGroupId
- }) : node.lastChild.hasTrailingSpaces && node.lastChild.isTrailingSpaceSensitive ? line$9 : (node.lastChild.type === "comment" || node.lastChild.type === "text" && node.isWhitespaceSensitive && node.isIndentationSensitive) && new RegExp(`\\n\\s{${options.tabWidth * countParents(path$$1, function (n) {
- return n.parent && n.parent.type !== "root";
- })}}$`).test(node.lastChild.value) ?
- /**
- * <div>
- * <pre>
- * something
- * </pre>
- * ~
- * </div>
- */
- "" : softline$7])])), printClosingTag(node, options)]);
- }
- case "ieConditionalStartComment":
- case "ieConditionalEndComment":
- return concat$14([printOpeningTagStart(node), printClosingTagEnd(node)]);
- case "interpolation":
- return concat$14([printOpeningTagStart(node, options), concat$14(path$$1.map(print, "children")), printClosingTagEnd(node, options)]);
- case "text":
- {
- if (node.parent.type === "interpolation") {
- // replace the trailing literalline with hardline for better readability
- var trailingNewlineRegex = /\n[^\S\n]*?$/;
- var hasTrailingNewline = trailingNewlineRegex.test(node.value);
- var value = hasTrailingNewline ? node.value.replace(trailingNewlineRegex, "") : node.value;
- return concat$14([concat$14(replaceEndOfLineWith$2(value, literalline$6)), hasTrailingNewline ? hardline$12 : ""]);
- }
- return fill$5(normalizeParts$1([].concat(printOpeningTagPrefix(node, options), getTextValueParts(node), printClosingTagSuffix(node, options))));
- }
- case "docType":
- return concat$14([group$14(concat$14([printOpeningTagStart(node, options), " ", node.value.replace(/^html\b/i, "html").replace(/\s+/g, " ")])), printClosingTagEnd(node, options)]);
- case "comment":
- {
- return concat$14([printOpeningTagPrefix(node, options), concat$14(replaceEndOfLineWith$2(options.originalText.slice(options.locStart(node), options.locEnd(node)), literalline$6)), printClosingTagSuffix(node, options)]);
- }
- case "attribute":
- {
- if (node.value === null) {
- return node.rawName;
- }
- var _value = unescapeQuoteEntities(node.value);
- var singleQuoteCount = countChars(_value, "'");
- var doubleQuoteCount = countChars(_value, '"');
- var quote = singleQuoteCount < doubleQuoteCount ? "'" : '"';
- return concat$14([node.rawName, concat$14(["=", quote, concat$14(replaceEndOfLineWith$2(quote === '"' ? _value.replace(/"/g, """) : _value.replace(/'/g, "'"), literalline$6)), quote])]);
- }
- case "yaml":
- case "toml":
- return concat$14(replaceEndOfLineWith$2(node.raw, literalline$6));
- default:
- throw new Error(`Unexpected node type ${node.type}`);
- }
- }
- function printChildren$1(path$$1, options, print) {
- var node = path$$1.getValue();
- if (forceBreakChildren(node)) {
- return concat$14([breakParent$3, concat$14(path$$1.map(function (childPath) {
- var childNode = childPath.getValue();
- var prevBetweenLine = !childNode.prev ? "" : printBetweenLine(childNode.prev, childNode);
- return concat$14([!prevBetweenLine ? "" : concat$14([prevBetweenLine, forceNextEmptyLine(childNode.prev) ? hardline$12 : ""]), printChild(childPath)]);
- }, "children"))]);
- }
- var groupIds = node.children.map(function () {
- return Symbol("");
- });
- return concat$14(path$$1.map(function (childPath, childIndex) {
- var childNode = childPath.getValue();
- if (isTextLikeNode(childNode)) {
- if (childNode.prev && isTextLikeNode(childNode.prev)) {
- var _prevBetweenLine = printBetweenLine(childNode.prev, childNode);
- if (_prevBetweenLine) {
- if (forceNextEmptyLine(childNode.prev)) {
- return concat$14([hardline$12, hardline$12, printChild(childPath)]);
- }
- return concat$14([_prevBetweenLine, printChild(childPath)]);
- }
- }
- return printChild(childPath);
- }
- var prevParts = [];
- var leadingParts = [];
- var trailingParts = [];
- var nextParts = [];
- var prevBetweenLine = childNode.prev ? printBetweenLine(childNode.prev, childNode) : "";
- var nextBetweenLine = childNode.next ? printBetweenLine(childNode, childNode.next) : "";
- if (prevBetweenLine) {
- if (forceNextEmptyLine(childNode.prev)) {
- prevParts.push(hardline$12, hardline$12);
- } else if (prevBetweenLine === hardline$12) {
- prevParts.push(hardline$12);
- } else {
- if (isTextLikeNode(childNode.prev)) {
- leadingParts.push(prevBetweenLine);
- } else {
- leadingParts.push(ifBreak$5("", softline$7, {
- groupId: groupIds[childIndex - 1]
- }));
- }
- }
- }
- if (nextBetweenLine) {
- if (forceNextEmptyLine(childNode)) {
- if (isTextLikeNode(childNode.next)) {
- nextParts.push(hardline$12, hardline$12);
- }
- } else if (nextBetweenLine === hardline$12) {
- if (isTextLikeNode(childNode.next)) {
- nextParts.push(hardline$12);
- }
- } else {
- trailingParts.push(nextBetweenLine);
- }
- }
- return concat$14([].concat(prevParts, group$14(concat$14([concat$14(leadingParts), group$14(concat$14([printChild(childPath), concat$14(trailingParts)]), {
- id: groupIds[childIndex]
- })])), nextParts));
- }, "children"));
- function printChild(childPath) {
- var child = childPath.getValue();
- if (hasPrettierIgnore$2(child)) {
- return concat$14([].concat(printOpeningTagPrefix(child, options), replaceEndOfLineWith$2(options.originalText.slice(options.locStart(child) + (child.prev && needsToBorrowNextOpeningTagStartMarker(child.prev) ? printOpeningTagStartMarker(child).length : 0), options.locEnd(child) - (child.next && needsToBorrowPrevClosingTagEndMarker(child.next) ? printClosingTagEndMarker(child, options).length : 0)), literalline$6), printClosingTagSuffix(child, options)));
- }
- if (shouldPreserveContent(child, options)) {
- return concat$14([].concat(printOpeningTagPrefix(child, options), group$14(printOpeningTag(childPath, options, print)), replaceEndOfLineWith$2(options.originalText.slice(child.startSourceSpan.end.offset + (child.firstChild && needsToBorrowParentOpeningTagEndMarker(child.firstChild) ? -printOpeningTagEndMarker(child).length : 0), child.endSourceSpan.start.offset + (child.lastChild && needsToBorrowParentClosingTagStartMarker(child.lastChild) ? printClosingTagStartMarker(child, options).length : needsToBorrowLastChildClosingTagEndMarker(child) ? -printClosingTagEndMarker(child.lastChild, options).length : 0)), literalline$6), printClosingTag(child, options), printClosingTagSuffix(child, options)));
- }
- return print(childPath);
- }
- function printBetweenLine(prevNode, nextNode) {
- return isTextLikeNode(prevNode) && isTextLikeNode(nextNode) ? prevNode.isTrailingSpaceSensitive ? prevNode.hasTrailingSpaces ? preferHardlineAsLeadingSpaces(nextNode) ? hardline$12 : line$9 : "" : preferHardlineAsLeadingSpaces(nextNode) ? hardline$12 : softline$7 : needsToBorrowNextOpeningTagStartMarker(prevNode) && (
- /**
- * 123<a
- * ~
- * ><b>
- */
- nextNode.firstChild ||
- /**
- * 123<!--
- * ~
- * -->
- */
- nextNode.isSelfClosing ||
- /**
- * 123<span
- * ~
- * attr
- */
- nextNode.type === "element" && nextNode.attrs.length !== 0) ||
- /**
- * <img
- * src="long"
- * ~
- * />123
- */
- prevNode.type === "element" && prevNode.isSelfClosing && needsToBorrowPrevClosingTagEndMarker(nextNode) ? "" : !nextNode.isLeadingSpaceSensitive || preferHardlineAsLeadingSpaces(nextNode) ||
- /**
- * Want to write us a letter? Use our<a
- * ><b><a>mailing address</a></b></a
- * ~
- * >.
- */
- needsToBorrowPrevClosingTagEndMarker(nextNode) && prevNode.lastChild && needsToBorrowParentClosingTagStartMarker(prevNode.lastChild) && prevNode.lastChild.lastChild && needsToBorrowParentClosingTagStartMarker(prevNode.lastChild.lastChild) ? hardline$12 : nextNode.hasLeadingSpaces ? line$9 : softline$7;
- }
- }
- function printOpeningTag(path$$1, options, print) {
- var node = path$$1.getValue();
- var forceNotToBreakAttrContent = node.type === "element" && node.fullName === "script" && node.attrs.length === 1 && node.attrs[0].fullName === "src" && node.children.length === 0;
- return concat$14([printOpeningTagStart(node, options), !node.attrs || node.attrs.length === 0 ? node.isSelfClosing ?
- /**
- * <br />
- * ^
- */
- " " : "" : concat$14([indent$9(concat$14([forceNotToBreakAttrContent ? " " : line$9, join$10(line$9, function (ignoreAttributeData) {
- var hasPrettierIgnoreAttribute = typeof ignoreAttributeData === "boolean" ? function () {
- return ignoreAttributeData;
- } : Array.isArray(ignoreAttributeData) ? function (attr) {
- return ignoreAttributeData.indexOf(attr.rawName) !== -1;
- } : function () {
- return false;
- };
- return path$$1.map(function (attrPath) {
- var attr = attrPath.getValue();
- return hasPrettierIgnoreAttribute(attr) ? concat$14(replaceEndOfLineWith$2(options.originalText.slice(options.locStart(attr), options.locEnd(attr)), literalline$6)) : print(attrPath);
- }, "attrs");
- }(node.prev && node.prev.type === "comment" && getPrettierIgnoreAttributeCommentData(node.prev.value)))])),
- /**
- * 123<a
- * attr
- * ~
- * >456
- */
- node.firstChild && needsToBorrowParentOpeningTagEndMarker(node.firstChild) ||
- /**
- * <span
- * >123<meta
- * ~
- * /></span>
- */
- node.isSelfClosing && needsToBorrowLastChildClosingTagEndMarker(node.parent) ? "" : node.isSelfClosing ? forceNotToBreakAttrContent ? " " : line$9 : forceNotToBreakAttrContent ? "" : softline$7]), node.isSelfClosing ? "" : printOpeningTagEnd(node)]);
- }
- function printOpeningTagStart(node, options) {
- return node.prev && needsToBorrowNextOpeningTagStartMarker(node.prev) ? "" : concat$14([printOpeningTagPrefix(node, options), printOpeningTagStartMarker(node)]);
- }
- function printOpeningTagEnd(node) {
- return node.firstChild && needsToBorrowParentOpeningTagEndMarker(node.firstChild) ? "" : printOpeningTagEndMarker(node);
- }
- function printClosingTag(node, options) {
- return concat$14([node.isSelfClosing ? "" : printClosingTagStart(node, options), printClosingTagEnd(node, options)]);
- }
- function printClosingTagStart(node, options) {
- return node.lastChild && needsToBorrowParentClosingTagStartMarker(node.lastChild) ? "" : concat$14([printClosingTagPrefix(node, options), printClosingTagStartMarker(node, options)]);
- }
- function printClosingTagEnd(node, options) {
- return (node.next ? needsToBorrowPrevClosingTagEndMarker(node.next) : needsToBorrowLastChildClosingTagEndMarker(node.parent)) ? "" : concat$14([printClosingTagEndMarker(node, options), printClosingTagSuffix(node, options)]);
- }
- function needsToBorrowNextOpeningTagStartMarker(node) {
- /**
- * 123<p
- * ^^
- * >
- */
- return node.next && !isTextLikeNode(node.next) && isTextLikeNode(node) && node.isTrailingSpaceSensitive && !node.hasTrailingSpaces;
- }
- function needsToBorrowParentOpeningTagEndMarker(node) {
- /**
- * <p
- * >123
- * ^
- *
- * <p
- * ><a
- * ^
- */
- return !node.prev && node.isLeadingSpaceSensitive && !node.hasLeadingSpaces;
- }
- function needsToBorrowPrevClosingTagEndMarker(node) {
- /**
- * <p></p
- * >123
- * ^
- *
- * <p></p
- * ><a
- * ^
- */
- return node.prev && !isTextLikeNode(node.prev) && node.isLeadingSpaceSensitive && !node.hasLeadingSpaces;
- }
- function needsToBorrowLastChildClosingTagEndMarker(node) {
- /**
- * <p
- * ><a></a
- * ></p
- * ^
- * >
- */
- return node.lastChild && node.lastChild.isTrailingSpaceSensitive && !node.lastChild.hasTrailingSpaces && !isTextLikeNode(getLastDescendant(node.lastChild));
- }
- function needsToBorrowParentClosingTagStartMarker(node) {
- /**
- * <p>
- * 123</p
- * ^^^
- * >
- *
- * 123</b
- * ></a
- * ^^^
- * >
- */
- return !node.next && !node.hasTrailingSpaces && node.isTrailingSpaceSensitive && isTextLikeNode(getLastDescendant(node));
- }
- function printOpeningTagPrefix(node, options) {
- return needsToBorrowParentOpeningTagEndMarker(node) ? printOpeningTagEndMarker(node.parent) : needsToBorrowPrevClosingTagEndMarker(node) ? printClosingTagEndMarker(node.prev, options) : "";
- }
- function printClosingTagPrefix(node, options) {
- return needsToBorrowLastChildClosingTagEndMarker(node) ? printClosingTagEndMarker(node.lastChild, options) : "";
- }
- function printClosingTagSuffix(node, options) {
- return needsToBorrowParentClosingTagStartMarker(node) ? printClosingTagStartMarker(node.parent, options) : needsToBorrowNextOpeningTagStartMarker(node) ? printOpeningTagStartMarker(node.next) : "";
- }
- function printOpeningTagStartMarker(node) {
- switch (node.type) {
- case "ieConditionalComment":
- case "ieConditionalStartComment":
- return `<!--[if ${node.condition}`;
- case "ieConditionalEndComment":
- return `<!--<!`;
- case "interpolation":
- return "{{";
- case "docType":
- return "<!DOCTYPE";
- case "element":
- if (node.condition) {
- return `<!--[if ${node.condition}]><!--><${node.rawName}`;
- }
- // fall through
- default:
- return `<${node.rawName}`;
- }
- }
- function printOpeningTagEndMarker(node) {
- assert(!node.isSelfClosing);
- switch (node.type) {
- case "ieConditionalComment":
- return "]>";
- case "element":
- if (node.condition) {
- return `><!--<![endif]-->`;
- }
- // fall through
- default:
- return `>`;
- }
- }
- function printClosingTagStartMarker(node, options) {
- assert(!node.isSelfClosing);
- if (shouldNotPrintClosingTag(node, options)) {
- return "";
- }
- switch (node.type) {
- case "ieConditionalComment":
- return "<!";
- case "element":
- if (node.hasHtmComponentClosingTag) {
- return "<//";
- }
- // fall through
- default:
- return `</${node.rawName}`;
- }
- }
- function printClosingTagEndMarker(node, options) {
- if (shouldNotPrintClosingTag(node, options)) {
- return "";
- }
- switch (node.type) {
- case "ieConditionalComment":
- case "ieConditionalEndComment":
- return `[endif]-->`;
- case "ieConditionalStartComment":
- return `]><!-->`;
- case "interpolation":
- return "}}";
- case "element":
- if (node.isSelfClosing) {
- return "/>";
- }
- // fall through
- default:
- return ">";
- }
- }
- function getTextValueParts(node) {
- var value = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : node.value;
- return node.parent.isWhitespaceSensitive ? node.parent.isIndentationSensitive ? replaceEndOfLineWith$2(value, literalline$6) : replaceEndOfLineWith$2(dedentString(value.replace(/^\s*?\n|\n\s*?$/g, "")), hardline$12) : // https://infra.spec.whatwg.org/#ascii-whitespace
- join$10(line$9, value.split(/[\t\n\f\r ]+/)).parts;
- }
- function printEmbeddedAttributeValue(node, originalTextToDoc, options) {
- var isKeyMatched = function isKeyMatched(patterns) {
- return new RegExp(patterns.join("|")).test(node.fullName);
- };
- var getValue = function getValue() {
- return unescapeQuoteEntities(node.value);
- };
- var shouldHug = false;
- var __onHtmlBindingRoot = function __onHtmlBindingRoot(root) {
- var rootNode = root.type === "NGRoot" ? root.node.type === "NGMicrosyntax" && root.node.body.length === 1 && root.node.body[0].type === "NGMicrosyntaxExpression" ? root.node.body[0].expression : root.node : root.type === "JsExpressionRoot" ? root.node : root;
- if (rootNode && (rootNode.type === "ObjectExpression" || rootNode.type === "ArrayExpression")) {
- shouldHug = true;
- }
- };
- var printHug = function printHug(doc$$2) {
- return group$14(doc$$2);
- };
- var printExpand = function printExpand(doc$$2) {
- return group$14(concat$14([indent$9(concat$14([softline$7, doc$$2])), softline$7]));
- };
- var printMaybeHug = function printMaybeHug(doc$$2) {
- return shouldHug ? printHug(doc$$2) : printExpand(doc$$2);
- };
- var textToDoc = function textToDoc(code, opts) {
- return originalTextToDoc(code, Object.assign({
- __onHtmlBindingRoot
- }, opts));
- };
- if (node.fullName === "srcset" && (node.parent.fullName === "img" || node.parent.fullName === "source")) {
- return printExpand(printImgSrcset(getValue()));
- }
- if (options.parser === "vue") {
- if (node.fullName === "v-for") {
- return printVueFor(getValue(), textToDoc);
- }
- if (node.fullName === "slot-scope") {
- return printVueSlotScope(getValue(), textToDoc);
- }
- /**
- * @click="jsStatement"
- * @click="jsExpression"
- * v-on:click="jsStatement"
- * v-on:click="jsExpression"
- */
- var vueEventBindingPatterns = ["^@", "^v-on:"];
- /**
- * :class="vueExpression"
- * v-bind:id="vueExpression"
- */
- var vueExpressionBindingPatterns = ["^:", "^v-bind:"];
- /**
- * v-if="jsExpression"
- */
- var jsExpressionBindingPatterns = ["^v-"];
- if (isKeyMatched(vueEventBindingPatterns)) {
- var value = getValue();
- return printMaybeHug(isVueEventBindingExpression$2(value) ? textToDoc(value, {
- parser: "__js_expression"
- }) : stripTrailingHardline$2(textToDoc(value, {
- parser: "__vue_event_binding"
- })));
- }
- if (isKeyMatched(vueExpressionBindingPatterns)) {
- return printMaybeHug(textToDoc(getValue(), {
- parser: "__vue_expression"
- }));
- }
- if (isKeyMatched(jsExpressionBindingPatterns)) {
- return printMaybeHug(textToDoc(getValue(), {
- parser: "__js_expression"
- }));
- }
- }
- if (options.parser === "angular") {
- var ngTextToDoc = function ngTextToDoc(code, opts) {
- return (// angular does not allow trailing comma
- textToDoc(code, Object.assign({
- trailingComma: "none"
- }, opts))
- );
- };
- /**
- * *directive="angularDirective"
- */
- var ngDirectiveBindingPatterns = ["^\\*"];
- /**
- * (click)="angularStatement"
- * on-click="angularStatement"
- */
- var ngStatementBindingPatterns = ["^\\(.+\\)$", "^on-"];
- /**
- * [target]="angularExpression"
- * bind-target="angularExpression"
- * [(target)]="angularExpression"
- * bindon-target="angularExpression"
- */
- var ngExpressionBindingPatterns = ["^\\[.+\\]$", "^bind(on)?-"];
- if (isKeyMatched(ngStatementBindingPatterns)) {
- return printMaybeHug(ngTextToDoc(getValue(), {
- parser: "__ng_action"
- }));
- }
- if (isKeyMatched(ngExpressionBindingPatterns)) {
- return printMaybeHug(ngTextToDoc(getValue(), {
- parser: "__ng_binding"
- }));
- }
- if (isKeyMatched(ngDirectiveBindingPatterns)) {
- return printMaybeHug(ngTextToDoc(getValue(), {
- parser: "__ng_directive"
- }));
- }
- var interpolationRegex = /\{\{([\s\S]+?)\}\}/g;
- var _value2 = getValue();
- if (interpolationRegex.test(_value2)) {
- var parts = [];
- _value2.split(interpolationRegex).forEach(function (part, index) {
- if (index % 2 === 0) {
- parts.push(concat$14(replaceEndOfLineWith$2(part, literalline$6)));
- } else {
- try {
- parts.push(group$14(concat$14(["{{", indent$9(concat$14([line$9, ngTextToDoc(part, {
- parser: "__ng_interpolation",
- __isInHtmlInterpolation: true // to avoid unexpected `}}`
- })])), line$9, "}}"])));
- } catch (e) {
- parts.push("{{", concat$14(replaceEndOfLineWith$2(part, literalline$6)), "}}");
- }
- }
- });
- return group$14(concat$14(parts));
- }
- }
- return null;
- }
- var printerHtml = {
- preprocess: preprocess_1$4,
- print: genericPrint$5,
- insertPragma: insertPragma$6,
- massageAstNode: clean$8,
- embed: embed$6
- };
- var CATEGORY_HTML = "HTML"; // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js
- var options$15 = {
- htmlWhitespaceSensitivity: {
- since: "1.15.0",
- category: CATEGORY_HTML,
- type: "choice",
- default: "css",
- description: "How to handle whitespaces in HTML.",
- choices: [{
- value: "css",
- description: "Respect the default value of CSS display property."
- }, {
- value: "strict",
- description: "Whitespaces are considered sensitive."
- }, {
- value: "ignore",
- description: "Whitespaces are considered insensitive."
- }]
- }
- };
- var name$14 = "HTML";
- var type$13 = "markup";
- var tmScope$13 = "text.html.basic";
- var aceMode$13 = "html";
- var codemirrorMode$10 = "htmlmixed";
- var codemirrorMimeType$10 = "text/html";
- var color$3 = "#e34c26";
- var aliases$5 = ["xhtml"];
- var extensions$13 = [".html", ".htm", ".html.hl", ".inc", ".st", ".xht", ".xhtml"];
- var languageId$13 = 146;
- var html$1 = {
- name: name$14,
- type: type$13,
- tmScope: tmScope$13,
- aceMode: aceMode$13,
- codemirrorMode: codemirrorMode$10,
- codemirrorMimeType: codemirrorMimeType$10,
- color: color$3,
- aliases: aliases$5,
- extensions: extensions$13,
- languageId: languageId$13
- };
- var html$2 = Object.freeze({
- name: name$14,
- type: type$13,
- tmScope: tmScope$13,
- aceMode: aceMode$13,
- codemirrorMode: codemirrorMode$10,
- codemirrorMimeType: codemirrorMimeType$10,
- color: color$3,
- aliases: aliases$5,
- extensions: extensions$13,
- languageId: languageId$13,
- default: html$1
- });
- var name$15 = "Vue";
- var type$14 = "markup";
- var color$4 = "#2c3e50";
- var extensions$14 = [".vue"];
- var tmScope$14 = "text.html.vue";
- var aceMode$14 = "html";
- var languageId$14 = 391;
- var vue = {
- name: name$15,
- type: type$14,
- color: color$4,
- extensions: extensions$14,
- tmScope: tmScope$14,
- aceMode: aceMode$14,
- languageId: languageId$14
- };
- var vue$1 = Object.freeze({
- name: name$15,
- type: type$14,
- color: color$4,
- extensions: extensions$14,
- tmScope: tmScope$14,
- aceMode: aceMode$14,
- languageId: languageId$14,
- default: vue
- });
- var require$$0$31 = ( html$2 && html$1 ) || html$2;
- var require$$1$10 = ( vue$1 && vue ) || vue$1;
- var languages$5 = [createLanguage(require$$0$31, {
- override: {
- name: "Angular",
- since: "1.15.0",
- parsers: ["angular"],
- vscodeLanguageIds: ["html"],
- extensions: [".component.html"],
- filenames: []
- }
- }), createLanguage(require$$0$31, {
- override: {
- since: "1.15.0",
- parsers: ["html"],
- vscodeLanguageIds: ["html"]
- },
- extend: {
- extensions: [".mjml" // MJML is considered XML in Linguist but it should be formatted as HTML
- ]
- }
- }), createLanguage(require$$1$10, {
- override: {
- since: "1.10.0",
- parsers: ["vue"],
- vscodeLanguageIds: ["vue"]
- }
- })];
- var printers$5 = {
- html: printerHtml
- };
- var languageHtml = {
- languages: languages$5,
- printers: printers$5,
- options: options$15
- };
- function isPragma$1(text) {
- return /^\s*@(prettier|format)\s*$/.test(text);
- }
- function hasPragma$4(text) {
- return /^\s*#[^\n\S]*@(prettier|format)\s*?(\n|$)/.test(text);
- }
- function insertPragma$9(text) {
- return `# @format\n\n${text}`;
- }
- var pragma$11 = {
- isPragma: isPragma$1,
- hasPragma: hasPragma$4,
- insertPragma: insertPragma$9
- };
- var getLast$7 = util$1.getLast;
- function getAncestorCount$1(path$$1, filter) {
- var counter = 0;
- var pathStackLength = path$$1.stack.length - 1;
- for (var i = 0; i < pathStackLength; i++) {
- var value = path$$1.stack[i];
- if (isNode$2(value) && filter(value)) {
- counter++;
- }
- }
- return counter;
- }
- /**
- * @param {any} value
- * @param {string[]=} types
- */
- function isNode$2(value, types) {
- return value && typeof value.type === "string" && (!types || types.indexOf(value.type) !== -1);
- }
- function mapNode$1(node, callback, parent) {
- return callback("children" in node ? Object.assign({}, node, {
- children: node.children.map(function (childNode) {
- return mapNode$1(childNode, callback, node);
- })
- }) : node, parent);
- }
- function defineShortcut$1(x, key, getter) {
- Object.defineProperty(x, key, {
- get: getter,
- enumerable: false
- });
- }
- function isNextLineEmpty$6(node, text) {
- var newlineCount = 0;
- var textLength = text.length;
- for (var i = node.position.end.offset - 1; i < textLength; i++) {
- var char = text[i];
- if (char === "\n") {
- newlineCount++;
- }
- if (newlineCount === 1 && /\S/.test(char)) {
- return false;
- }
- if (newlineCount === 2) {
- return true;
- }
- }
- return false;
- }
- function isLastDescendantNode$1(path$$1) {
- var node = path$$1.getValue();
- switch (node.type) {
- case "tag":
- case "anchor":
- case "comment":
- return false;
- }
- var pathStackLength = path$$1.stack.length;
- for (var i = 1; i < pathStackLength; i++) {
- var item = path$$1.stack[i];
- var parentItem = path$$1.stack[i - 1];
- if (Array.isArray(parentItem) && typeof item === "number" && item !== parentItem.length - 1) {
- return false;
- }
- }
- return true;
- }
- function getLastDescendantNode$2(node) {
- return "children" in node && node.children.length !== 0 ? getLastDescendantNode$2(getLast$7(node.children)) : node;
- }
- function isPrettierIgnore$2(comment) {
- return comment.value.trim() === "prettier-ignore";
- }
- function hasPrettierIgnore$5(path$$1) {
- var node = path$$1.getValue();
- if (node.type === "documentBody") {
- var document = path$$1.getParentNode();
- return hasEndComments$1(document.head) && isPrettierIgnore$2(getLast$7(document.head.endComments));
- }
- return hasLeadingComments$1(node) && isPrettierIgnore$2(getLast$7(node.leadingComments));
- }
- function isEmptyNode$1(node) {
- return (!node.children || node.children.length === 0) && !hasComments(node);
- }
- function hasComments(node) {
- return hasLeadingComments$1(node) || hasMiddleComments$1(node) || hasIndicatorComment$1(node) || hasTrailingComment$2(node) || hasEndComments$1(node);
- }
- function hasLeadingComments$1(node) {
- return node && node.leadingComments && node.leadingComments.length !== 0;
- }
- function hasMiddleComments$1(node) {
- return node && node.middleComments && node.middleComments.length !== 0;
- }
- function hasIndicatorComment$1(node) {
- return node && node.indicatorComment;
- }
- function hasTrailingComment$2(node) {
- return node && node.trailingComment;
- }
- function hasEndComments$1(node) {
- return node && node.endComments && node.endComments.length !== 0;
- }
- /**
- * " a b c d e f " -> [" a b", "c d", "e f "]
- */
- function splitWithSingleSpace(text) {
- var parts = [];
- var lastPart = undefined;
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = text.split(/( +)/g)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var part = _step.value;
- if (part !== " ") {
- if (lastPart === " ") {
- parts.push(part);
- } else {
- parts.push((parts.pop() || "") + part);
- }
- } else if (lastPart === undefined) {
- parts.unshift("");
- }
- lastPart = part;
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- if (lastPart === " ") {
- parts.push((parts.pop() || "") + " ");
- }
- if (parts[0] === "") {
- parts.shift();
- parts.unshift(" " + (parts.shift() || ""));
- }
- return parts;
- }
- function getFlowScalarLineContents$1(nodeType, content, options) {
- var rawLineContents = content.split("\n").map(function (lineContent, index, lineContents) {
- return index === 0 && index === lineContents.length - 1 ? lineContent : index !== 0 && index !== lineContents.length - 1 ? lineContent.trim() : index === 0 ? lineContent.trimRight() : lineContent.trimLeft();
- });
- if (options.proseWrap === "preserve") {
- return rawLineContents.map(function (lineContent) {
- return lineContent.length === 0 ? [] : [lineContent];
- });
- }
- return rawLineContents.map(function (lineContent) {
- return lineContent.length === 0 ? [] : splitWithSingleSpace(lineContent);
- }).reduce(function (reduced, lineContentWords, index) {
- return index !== 0 && rawLineContents[index - 1].length !== 0 && lineContentWords.length !== 0 && !( // trailing backslash in quoteDouble should be preserved
- nodeType === "quoteDouble" && getLast$7(getLast$7(reduced)).endsWith("\\")) ? reduced.concat([reduced.pop().concat(lineContentWords)]) : reduced.concat([lineContentWords]);
- }, []).map(function (lineContentWords) {
- return options.proseWrap === "never" ? [lineContentWords.join(" ")] : lineContentWords;
- });
- }
- function getBlockValueLineContents$1(node, _ref) {
- var parentIndent = _ref.parentIndent,
- isLastDescendant = _ref.isLastDescendant,
- options = _ref.options;
- var content = node.position.start.line === node.position.end.line ? "" : options.originalText.slice(node.position.start.offset, node.position.end.offset) // exclude open line `>` or `|`
- .match(/^[^\n]*?\n([\s\S]*)$/)[1];
- var leadingSpaceCount = node.indent === null ? function (match) {
- return match ? match[1].length : Infinity;
- }(content.match(/^( *)\S/m)) : node.indent - 1 + parentIndent;
- var rawLineContents = content.split("\n").map(function (lineContent) {
- return lineContent.slice(leadingSpaceCount);
- });
- if (options.proseWrap === "preserve" || node.type === "blockLiteral") {
- return removeUnnecessaryTrailingNewlines(rawLineContents.map(function (lineContent) {
- return lineContent.length === 0 ? [] : [lineContent];
- }));
- }
- return removeUnnecessaryTrailingNewlines(rawLineContents.map(function (lineContent) {
- return lineContent.length === 0 ? [] : splitWithSingleSpace(lineContent);
- }).reduce(function (reduced, lineContentWords, index) {
- return index !== 0 && rawLineContents[index - 1].length !== 0 && lineContentWords.length !== 0 && !/^\s/.test(lineContentWords[0]) && !/^\s|\s$/.test(getLast$7(reduced)) ? reduced.concat([reduced.pop().concat(lineContentWords)]) : reduced.concat([lineContentWords]);
- }, []).map(function (lineContentWords) {
- return lineContentWords.reduce(function (reduced, word) {
- return (// disallow trailing spaces
- reduced.length !== 0 && /\s$/.test(getLast$7(reduced)) ? reduced.concat(reduced.pop() + " " + word) : reduced.concat(word)
- );
- }, []);
- }).map(function (lineContentWords) {
- return options.proseWrap === "never" ? [lineContentWords.join(" ")] : lineContentWords;
- }));
- function removeUnnecessaryTrailingNewlines(lineContents) {
- if (node.chomping === "keep") {
- return getLast$7(lineContents).length === 0 ? lineContents.slice(0, -1) : lineContents;
- }
- var trailingNewlineCount = 0;
- for (var i = lineContents.length - 1; i >= 0; i--) {
- if (lineContents[i].length === 0) {
- trailingNewlineCount++;
- } else {
- break;
- }
- }
- return trailingNewlineCount === 0 ? lineContents : trailingNewlineCount >= 2 && !isLastDescendant ? // next empty line
- lineContents.slice(0, -(trailingNewlineCount - 1)) : lineContents.slice(0, -trailingNewlineCount);
- }
- }
- var utils$12 = {
- getLast: getLast$7,
- getAncestorCount: getAncestorCount$1,
- isNode: isNode$2,
- isEmptyNode: isEmptyNode$1,
- mapNode: mapNode$1,
- defineShortcut: defineShortcut$1,
- isNextLineEmpty: isNextLineEmpty$6,
- isLastDescendantNode: isLastDescendantNode$1,
- getBlockValueLineContents: getBlockValueLineContents$1,
- getFlowScalarLineContents: getFlowScalarLineContents$1,
- getLastDescendantNode: getLastDescendantNode$2,
- hasPrettierIgnore: hasPrettierIgnore$5,
- hasLeadingComments: hasLeadingComments$1,
- hasMiddleComments: hasMiddleComments$1,
- hasIndicatorComment: hasIndicatorComment$1,
- hasTrailingComment: hasTrailingComment$2,
- hasEndComments: hasEndComments$1
- };
- var insertPragma$8 = pragma$11.insertPragma;
- var isPragma = pragma$11.isPragma;
- var getAncestorCount = utils$12.getAncestorCount;
- var getBlockValueLineContents = utils$12.getBlockValueLineContents;
- var getFlowScalarLineContents = utils$12.getFlowScalarLineContents;
- var getLast$6 = utils$12.getLast;
- var getLastDescendantNode$1 = utils$12.getLastDescendantNode;
- var hasLeadingComments = utils$12.hasLeadingComments;
- var hasMiddleComments = utils$12.hasMiddleComments;
- var hasIndicatorComment = utils$12.hasIndicatorComment;
- var hasTrailingComment$1 = utils$12.hasTrailingComment;
- var hasEndComments = utils$12.hasEndComments;
- var hasPrettierIgnore$4 = utils$12.hasPrettierIgnore;
- var isLastDescendantNode = utils$12.isLastDescendantNode;
- var isNextLineEmpty$5 = utils$12.isNextLineEmpty;
- var isNode$1 = utils$12.isNode;
- var isEmptyNode = utils$12.isEmptyNode;
- var defineShortcut = utils$12.defineShortcut;
- var mapNode = utils$12.mapNode;
- var docBuilders$3 = doc.builders;
- var conditionalGroup$2 = docBuilders$3.conditionalGroup;
- var breakParent$4 = docBuilders$3.breakParent;
- var concat$17 = docBuilders$3.concat;
- var dedent$4 = docBuilders$3.dedent;
- var dedentToRoot$3 = docBuilders$3.dedentToRoot;
- var fill$6 = docBuilders$3.fill;
- var group$16 = docBuilders$3.group;
- var hardline$13 = docBuilders$3.hardline;
- var ifBreak$7 = docBuilders$3.ifBreak;
- var join$12 = docBuilders$3.join;
- var line$11 = docBuilders$3.line;
- var lineSuffix$2 = docBuilders$3.lineSuffix;
- var literalline$7 = docBuilders$3.literalline;
- var markAsRoot$5 = docBuilders$3.markAsRoot;
- var softline$8 = docBuilders$3.softline;
- var replaceEndOfLineWith$3 = util$1.replaceEndOfLineWith;
- function preprocess$6(ast) {
- return mapNode(ast, defineShortcuts);
- }
- function defineShortcuts(node) {
- switch (node.type) {
- case "document":
- defineShortcut(node, "head", function () {
- return node.children[0];
- });
- defineShortcut(node, "body", function () {
- return node.children[1];
- });
- break;
- case "documentBody":
- case "sequenceItem":
- case "flowSequenceItem":
- case "mappingKey":
- case "mappingValue":
- defineShortcut(node, "content", function () {
- return node.children[0];
- });
- break;
- case "mappingItem":
- case "flowMappingItem":
- defineShortcut(node, "key", function () {
- return node.children[0];
- });
- defineShortcut(node, "value", function () {
- return node.children[1];
- });
- break;
- }
- return node;
- }
- function genericPrint$6(path$$1, options, print) {
- var node = path$$1.getValue();
- var parentNode = path$$1.getParentNode();
- var tag = !node.tag ? "" : path$$1.call(print, "tag");
- var anchor = !node.anchor ? "" : path$$1.call(print, "anchor");
- var nextEmptyLine = isNode$1(node, ["mapping", "sequence", "comment", "directive", "mappingItem", "sequenceItem"]) && !isLastDescendantNode(path$$1) ? printNextEmptyLine(path$$1, options.originalText) : "";
- return concat$17([node.type !== "mappingValue" && hasLeadingComments(node) ? concat$17([join$12(hardline$13, path$$1.map(print, "leadingComments")), hardline$13]) : "", tag, tag && anchor ? " " : "", anchor, tag || anchor ? isNode$1(node, ["sequence", "mapping"]) && !hasMiddleComments(node) ? hardline$13 : " " : "", hasMiddleComments(node) ? concat$17([node.middleComments.length === 1 ? "" : hardline$13, join$12(hardline$13, path$$1.map(print, "middleComments")), hardline$13]) : "", hasPrettierIgnore$4(path$$1) ? concat$17(replaceEndOfLineWith$3(options.originalText.slice(node.position.start.offset, node.position.end.offset), literalline$7)) : group$16(_print(node, parentNode, path$$1, options, print)), hasTrailingComment$1(node) && !isNode$1(node, ["document", "documentHead"]) ? lineSuffix$2(concat$17([node.type === "mappingValue" && !node.content ? "" : " ", parentNode.type === "mappingKey" && path$$1.getParentNode(2).type === "mapping" && isInlineNode(node) ? "" : breakParent$4, path$$1.call(print, "trailingComment")])) : "", nextEmptyLine, hasEndComments(node) && !isNode$1(node, ["documentHead", "documentBody"]) ? align$3(node.type === "sequenceItem" ? 2 : 0, concat$17([hardline$13, join$12(hardline$13, path$$1.map(print, "endComments"))])) : ""]);
- }
- function _print(node, parentNode, path$$1, options, print) {
- switch (node.type) {
- case "root":
- return concat$17([join$12(hardline$13, path$$1.map(function (childPath, index) {
- var document = node.children[index];
- var nextDocument = node.children[index + 1];
- return concat$17([print(childPath), shouldPrintDocumentEndMarker(document, nextDocument) ? concat$17([hardline$13, "...", hasTrailingComment$1(document) ? concat$17([" ", path$$1.call(print, "trailingComment")]) : ""]) : !nextDocument || hasTrailingComment$1(nextDocument.head) ? "" : concat$17([hardline$13, "---"])]);
- }, "children")), node.children.length === 0 || function (lastDescendantNode) {
- return isNode$1(lastDescendantNode, ["blockLiteral", "blockFolded"]) && lastDescendantNode.chomping === "keep";
- }(getLastDescendantNode$1(node)) ? "" : hardline$13]);
- case "document":
- {
- var nextDocument = parentNode.children[path$$1.getName() + 1];
- return join$12(hardline$13, [shouldPrintDocumentHeadEndMarker(node, nextDocument, parentNode, options) === "head" ? join$12(hardline$13, [node.head.children.length === 0 && node.head.endComments.length === 0 ? "" : path$$1.call(print, "head"), concat$17(["---", hasTrailingComment$1(node.head) ? concat$17([" ", path$$1.call(print, "head", "trailingComment")]) : ""])].filter(Boolean)) : "", shouldPrintDocumentBody(node) ? path$$1.call(print, "body") : ""].filter(Boolean));
- }
- case "documentHead":
- return join$12(hardline$13, [].concat(path$$1.map(print, "children"), path$$1.map(print, "endComments")));
- case "documentBody":
- {
- var children = join$12(hardline$13, path$$1.map(print, "children")).parts;
- var endComments = join$12(hardline$13, path$$1.map(print, "endComments")).parts;
- var separator = children.length === 0 || endComments.length === 0 ? "" : function (lastDescendantNode) {
- return isNode$1(lastDescendantNode, ["blockFolded", "blockLiteral"]) ? lastDescendantNode.chomping === "keep" ? // there's already a newline printed at the end of blockValue (chomping=keep, lastDescendant=true)
- "" : // an extra newline for better readability
- concat$17([hardline$13, hardline$13]) : hardline$13;
- }(getLastDescendantNode$1(node));
- return concat$17([].concat(children, separator, endComments));
- }
- case "directive":
- return concat$17(["%", join$12(" ", [node.name].concat(node.parameters))]);
- case "comment":
- return concat$17(["#", node.value]);
- case "alias":
- return concat$17(["*", node.value]);
- case "tag":
- return options.originalText.slice(node.position.start.offset, node.position.end.offset);
- case "anchor":
- return concat$17(["&", node.value]);
- case "plain":
- return printFlowScalarContent(node.type, options.originalText.slice(node.position.start.offset, node.position.end.offset), options);
- case "quoteDouble":
- case "quoteSingle":
- {
- var singleQuote = "'";
- var doubleQuote = '"';
- var raw = options.originalText.slice(node.position.start.offset + 1, node.position.end.offset - 1);
- if (node.type === "quoteSingle" && raw.includes("\\") || node.type === "quoteDouble" && /\\[^"]/.test(raw)) {
- // only quoteDouble can use escape chars
- // and quoteSingle do not need to escape backslashes
- var originalQuote = node.type === "quoteDouble" ? doubleQuote : singleQuote;
- return concat$17([originalQuote, printFlowScalarContent(node.type, raw, options), originalQuote]);
- } else if (raw.includes(doubleQuote)) {
- return concat$17([singleQuote, printFlowScalarContent(node.type, node.type === "quoteDouble" ? raw // double quote needs to be escaped by backslash in quoteDouble
- .replace(/\\"/g, doubleQuote).replace(/'/g, singleQuote.repeat(2)) : raw, options), singleQuote]);
- }
- if (raw.includes(singleQuote)) {
- return concat$17([doubleQuote, printFlowScalarContent(node.type, node.type === "quoteSingle" ? // single quote needs to be escaped by 2 single quotes in quoteSingle
- raw.replace(/''/g, singleQuote) : raw, options), doubleQuote]);
- }
- var quote = options.singleQuote ? singleQuote : doubleQuote;
- return concat$17([quote, printFlowScalarContent(node.type, raw, options), quote]);
- }
- case "blockFolded":
- case "blockLiteral":
- {
- var parentIndent = getAncestorCount(path$$1, function (ancestorNode) {
- return isNode$1(ancestorNode, ["sequence", "mapping"]);
- });
- var isLastDescendant = isLastDescendantNode(path$$1);
- return concat$17([node.type === "blockFolded" ? ">" : "|", node.indent === null ? "" : node.indent.toString(), node.chomping === "clip" ? "" : node.chomping === "keep" ? "+" : "-", hasIndicatorComment(node) ? concat$17([" ", path$$1.call(print, "indicatorComment")]) : "", (node.indent === null ? dedent$4 : dedentToRoot$3)(align$3(node.indent === null ? options.tabWidth : node.indent - 1 + parentIndent, concat$17(getBlockValueLineContents(node, {
- parentIndent,
- isLastDescendant,
- options
- }).reduce(function (reduced, lineWords, index, lineContents) {
- return reduced.concat(index === 0 ? hardline$13 : "", fill$6(join$12(line$11, lineWords).parts), index !== lineContents.length - 1 ? lineWords.length === 0 ? hardline$13 : markAsRoot$5(literalline$7) : node.chomping === "keep" && isLastDescendant ? lineWords.length === 0 ? dedentToRoot$3(hardline$13) : dedentToRoot$3(literalline$7) : "");
- }, []))))]);
- }
- case "sequence":
- return join$12(hardline$13, path$$1.map(print, "children"));
- case "sequenceItem":
- return concat$17(["- ", align$3(2, !node.content ? "" : path$$1.call(print, "content"))]);
- case "mappingKey":
- return !node.content ? "" : path$$1.call(print, "content");
- case "mappingValue":
- return !node.content ? "" : path$$1.call(print, "content");
- case "mapping":
- return join$12(hardline$13, path$$1.map(print, "children"));
- case "mappingItem":
- case "flowMappingItem":
- {
- var isEmptyMappingKey = isEmptyNode(node.key);
- var isEmptyMappingValue = isEmptyNode(node.value);
- if (isEmptyMappingKey && isEmptyMappingValue) {
- return concat$17([": "]);
- }
- var key = path$$1.call(print, "key");
- var value = path$$1.call(print, "value");
- if (isEmptyMappingValue) {
- return node.type === "flowMappingItem" && parentNode.type === "flowMapping" ? key : node.type === "mappingItem" && isAbsolutelyPrintedAsSingleLineNode(node.key.content, options) && !hasTrailingComment$1(node.key.content) && (!parentNode.tag || parentNode.tag.value !== "tag:yaml.org,2002:set") ? concat$17([key, needsSpaceInFrontOfMappingValue(node) ? " " : "", ":"]) : concat$17(["? ", align$3(2, key)]);
- }
- if (isEmptyMappingKey) {
- return concat$17([": ", align$3(2, value)]);
- }
- var groupId = Symbol("mappingKey");
- var forceExplicitKey = hasLeadingComments(node.value) || !isInlineNode(node.key.content);
- return forceExplicitKey ? concat$17(["? ", align$3(2, key), hardline$13, join$12("", path$$1.map(print, "value", "leadingComments").map(function (comment) {
- return concat$17([comment, hardline$13]);
- })), ": ", align$3(2, value)]) : // force singleline
- isSingleLineNode(node.key.content) && !hasLeadingComments(node.key.content) && !hasMiddleComments(node.key.content) && !hasTrailingComment$1(node.key.content) && !hasEndComments(node.key) && !hasLeadingComments(node.value.content) && !hasMiddleComments(node.value.content) && !hasEndComments(node.value) && isAbsolutelyPrintedAsSingleLineNode(node.value.content, options) ? concat$17([key, needsSpaceInFrontOfMappingValue(node) ? " " : "", ": ", value]) : conditionalGroup$2([concat$17([group$16(concat$17([ifBreak$7("? "), group$16(align$3(2, key), {
- id: groupId
- })])), ifBreak$7(concat$17([hardline$13, ": ", align$3(2, value)]), indent(concat$17([needsSpaceInFrontOfMappingValue(node) ? " " : "", ":", hasLeadingComments(node.value.content) || hasEndComments(node.value) && node.value.content && !isNode$1(node.value.content, ["mapping", "sequence"]) || parentNode.type === "mapping" && hasTrailingComment$1(node.key.content) && isInlineNode(node.value.content) || isNode$1(node.value.content, ["mapping", "sequence"]) && node.value.content.tag === null && node.value.content.anchor === null ? hardline$13 : !node.value.content ? "" : line$11, value])), {
- groupId
- })])]);
- }
- case "flowMapping":
- case "flowSequence":
- {
- var openMarker = node.type === "flowMapping" ? "{" : "[";
- var closeMarker = node.type === "flowMapping" ? "}" : "]";
- var bracketSpacing = node.type === "flowMapping" && node.children.length !== 0 && options.bracketSpacing ? line$11 : softline$8;
- var isLastItemEmptyMappingItem = node.children.length !== 0 && function (lastItem) {
- return lastItem.type === "flowMappingItem" && isEmptyNode(lastItem.key) && isEmptyNode(lastItem.value);
- }(getLast$6(node.children));
- return concat$17([openMarker, indent(concat$17([bracketSpacing, concat$17(path$$1.map(function (childPath, index) {
- return concat$17([print(childPath), index === node.children.length - 1 ? "" : concat$17([",", line$11, node.children[index].position.start.line !== node.children[index + 1].position.start.line ? printNextEmptyLine(childPath, options.originalText) : ""])]);
- }, "children")), ifBreak$7(",", "")])), isLastItemEmptyMappingItem ? "" : bracketSpacing, closeMarker]);
- }
- case "flowSequenceItem":
- return path$$1.call(print, "content");
- // istanbul ignore next
- default:
- throw new Error(`Unexpected node type ${node.type}`);
- }
- function indent(doc$$2) {
- return docBuilders$3.align(" ".repeat(options.tabWidth), doc$$2);
- }
- }
- function align$3(n, doc$$2) {
- return typeof n === "number" && n > 0 ? docBuilders$3.align(" ".repeat(n), doc$$2) : docBuilders$3.align(n, doc$$2);
- }
- function isInlineNode(node) {
- if (!node) {
- return true;
- }
- switch (node.type) {
- case "plain":
- case "quoteDouble":
- case "quoteSingle":
- case "alias":
- case "flowMapping":
- case "flowSequence":
- return true;
- default:
- return false;
- }
- }
- function isSingleLineNode(node) {
- if (!node) {
- return true;
- }
- switch (node.type) {
- case "plain":
- case "quoteDouble":
- case "quoteSingle":
- return node.position.start.line === node.position.end.line;
- case "alias":
- return true;
- default:
- return false;
- }
- }
- function shouldPrintDocumentBody(document) {
- return document.body.children.length !== 0 || hasEndComments(document.body);
- }
- function shouldPrintDocumentEndMarker(document, nextDocument) {
- return (
- /**
- *... # trailingComment
- */
- hasTrailingComment$1(document) || nextDocument && (
- /**
- * ...
- * %DIRECTIVE
- * ---
- */
- nextDocument.head.children.length !== 0 ||
- /**
- * ...
- * # endComment
- * ---
- */
- hasEndComments(nextDocument.head))
- );
- }
- function shouldPrintDocumentHeadEndMarker(document, nextDocument, root, options) {
- if (
- /**
- * ---
- * preserve the first document head end marker
- */
- root.children[0] === document && /---(\s|$)/.test(options.originalText.slice(options.locStart(document), options.locStart(document) + 4)) ||
- /**
- * %DIRECTIVE
- * ---
- */
- document.head.children.length !== 0 ||
- /**
- * # end comment
- * ---
- */
- hasEndComments(document.head) ||
- /**
- * --- # trailing comment
- */
- hasTrailingComment$1(document.head)) {
- return "head";
- }
- if (shouldPrintDocumentEndMarker(document, nextDocument)) {
- return false;
- }
- return nextDocument ? "root" : false;
- }
- function isAbsolutelyPrintedAsSingleLineNode(node, options) {
- if (!node) {
- return true;
- }
- switch (node.type) {
- case "plain":
- case "quoteSingle":
- case "quoteDouble":
- break;
- case "alias":
- return true;
- default:
- return false;
- }
- if (options.proseWrap === "preserve") {
- return node.position.start.line === node.position.end.line;
- }
- if ( // backslash-newline
- /\\$/m.test(options.originalText.slice(node.position.start.offset, node.position.end.offset))) {
- return false;
- }
- switch (options.proseWrap) {
- case "never":
- return node.value.indexOf("\n") === -1;
- case "always":
- return !/[\n ]/.test(node.value);
- // istanbul ignore next
- default:
- return false;
- }
- }
- function needsSpaceInFrontOfMappingValue(node) {
- return node.key.content && node.key.content.type === "alias";
- }
- function printNextEmptyLine(path$$1, originalText) {
- var node = path$$1.getValue();
- var root = path$$1.stack[0];
- root.isNextEmptyLinePrintedChecklist = root.isNextEmptyLinePrintedChecklist || [];
- if (!root.isNextEmptyLinePrintedChecklist[node.position.end.line]) {
- if (isNextLineEmpty$5(node, originalText)) {
- root.isNextEmptyLinePrintedChecklist[node.position.end.line] = true;
- return softline$8;
- }
- }
- return "";
- }
- function printFlowScalarContent(nodeType, content, options) {
- var lineContents = getFlowScalarLineContents(nodeType, content, options);
- return join$12(hardline$13, lineContents.map(function (lineContentWords) {
- return fill$6(join$12(line$11, lineContentWords).parts);
- }));
- }
- function clean$11(node, newNode
- /*, parent */
- ) {
- if (isNode$1(newNode)) {
- delete newNode.position;
- switch (newNode.type) {
- case "comment":
- // insert pragma
- if (isPragma(newNode.value)) {
- return null;
- }
- break;
- case "quoteDouble":
- case "quoteSingle":
- newNode.type = "quote";
- break;
- }
- }
- }
- var printerYaml = {
- preprocess: preprocess$6,
- print: genericPrint$6,
- massageAstNode: clean$11,
- insertPragma: insertPragma$8
- };
- var options$18 = {
- bracketSpacing: commonOptions.bracketSpacing,
- singleQuote: commonOptions.singleQuote,
- proseWrap: commonOptions.proseWrap
- };
- var name$16 = "YAML";
- var type$15 = "data";
- var tmScope$15 = "source.yaml";
- var aliases$6 = ["yml"];
- var extensions$15 = [".yml", ".mir", ".reek", ".rviz", ".sublime-syntax", ".syntax", ".yaml", ".yaml-tmlanguage", ".yml.mysql"];
- var filenames$3 = [".clang-format", ".clang-tidy", ".gemrc", "glide.lock"];
- var aceMode$15 = "yaml";
- var codemirrorMode$11 = "yaml";
- var codemirrorMimeType$11 = "text/x-yaml";
- var languageId$15 = 407;
- var yaml = {
- name: name$16,
- type: type$15,
- tmScope: tmScope$15,
- aliases: aliases$6,
- extensions: extensions$15,
- filenames: filenames$3,
- aceMode: aceMode$15,
- codemirrorMode: codemirrorMode$11,
- codemirrorMimeType: codemirrorMimeType$11,
- languageId: languageId$15
- };
- var yaml$1 = Object.freeze({
- name: name$16,
- type: type$15,
- tmScope: tmScope$15,
- aliases: aliases$6,
- extensions: extensions$15,
- filenames: filenames$3,
- aceMode: aceMode$15,
- codemirrorMode: codemirrorMode$11,
- codemirrorMimeType: codemirrorMimeType$11,
- languageId: languageId$15,
- default: yaml
- });
- var require$$0$33 = ( yaml$1 && yaml ) || yaml$1;
- var languages$6 = [createLanguage(require$$0$33, {
- override: {
- since: "1.14.0",
- parsers: ["yaml"],
- vscodeLanguageIds: ["yaml"]
- }
- })];
- var languageYaml = {
- languages: languages$6,
- printers: {
- yaml: printerYaml
- },
- options: options$18
- };
- // plugin will look for `eval("require")()` and transform to `require()` in the bundle,
- // and rewrite the paths to require from the top-level.
- // We need to list the parsers and getters so we can load them only when necessary.
- var internalPlugins = [// JS
- languageJs, {
- parsers: {
- // JS - Babel
- get babel() {
- return require("./parser-babylon").parsers.babel;
- },
- get "babel-flow"() {
- return require("./parser-babylon").parsers["babel-flow"];
- },
- get babylon() {
- return require("./parser-babylon").parsers.babel;
- },
- get json() {
- return require("./parser-babylon").parsers.json;
- },
- get json5() {
- return require("./parser-babylon").parsers.json5;
- },
- get "json-stringify"() {
- return require("./parser-babylon").parsers["json-stringify"];
- },
- get __js_expression() {
- return require("./parser-babylon").parsers.__js_expression;
- },
- get __vue_expression() {
- return require("./parser-babylon").parsers.__vue_expression;
- },
- get __vue_event_binding() {
- return require("./parser-babylon").parsers.__vue_event_binding;
- },
- // JS - Flow
- get flow() {
- return require("./parser-flow").parsers.flow;
- },
- // JS - TypeScript
- get typescript() {
- return require("./parser-typescript").parsers.typescript;
- },
- /**
- * TODO: Remove this old alias in a major version
- */
- get "typescript-eslint"() {
- return require("./parser-typescript").parsers.typescript;
- },
- // JS - Angular Action
- get __ng_action() {
- return require("./parser-angular").parsers.__ng_action;
- },
- // JS - Angular Binding
- get __ng_binding() {
- return require("./parser-angular").parsers.__ng_binding;
- },
- // JS - Angular Interpolation
- get __ng_interpolation() {
- return require("./parser-angular").parsers.__ng_interpolation;
- },
- // JS - Angular Directive
- get __ng_directive() {
- return require("./parser-angular").parsers.__ng_directive;
- }
- }
- }, // CSS
- languageCss, {
- parsers: {
- // TODO: switch these to just `postcss` and use `language` instead.
- get css() {
- return require("./parser-postcss").parsers.css;
- },
- get less() {
- return require("./parser-postcss").parsers.css;
- },
- get scss() {
- return require("./parser-postcss").parsers.css;
- }
- }
- }, // Handlebars
- languageHandlebars, {
- parsers: {
- get glimmer() {
- return require("./parser-glimmer").parsers.glimmer;
- }
- }
- }, // GraphQL
- languageGraphql, {
- parsers: {
- get graphql() {
- return require("./parser-graphql").parsers.graphql;
- }
- }
- }, // Markdown
- languageMarkdown, {
- parsers: {
- get remark() {
- return require("./parser-markdown").parsers.remark;
- },
- // TODO: Delete this in 2.0
- get markdown() {
- return require("./parser-markdown").parsers.remark;
- },
- get mdx() {
- return require("./parser-markdown").parsers.mdx;
- }
- }
- }, languageHtml, {
- parsers: {
- // HTML
- get html() {
- return require("./parser-html").parsers.html;
- },
- // Vue
- get vue() {
- return require("./parser-html").parsers.vue;
- },
- // Angular
- get angular() {
- return require("./parser-html").parsers.angular;
- }
- }
- }, // YAML
- languageYaml, {
- parsers: {
- get yaml() {
- return require("./parser-yaml").parsers.yaml;
- }
- }
- }];
- var partition = function partition(array, fn) {
- var a = [];
- var b = [];
- array.forEach(function (item) {
- if (fn(item)) {
- a.push(item);
- } else {
- b.push(item);
- }
- });
- return [a, b];
- };
- var thirdParty$1 = ( thirdParty && thirdParty__default ) || thirdParty;
- function loadPlugins(plugins, pluginSearchDirs) {
- if (!plugins) {
- plugins = [];
- }
- if (!pluginSearchDirs) {
- pluginSearchDirs = [];
- } // unless pluginSearchDirs are provided, auto-load plugins from node_modules that are parent to Prettier
- if (!pluginSearchDirs.length) {
- var autoLoadDir = thirdParty$1.findParentDir(__dirname, "node_modules");
- if (autoLoadDir) {
- pluginSearchDirs = [autoLoadDir];
- }
- }
- var _partition = partition(plugins, function (plugin) {
- return typeof plugin === "string";
- }),
- _partition2 = _slicedToArray(_partition, 2),
- externalPluginNames = _partition2[0],
- externalPluginInstances = _partition2[1];
- var externalManualLoadPluginInfos = externalPluginNames.map(function (pluginName) {
- var requirePath;
- try {
- // try local files
- requirePath = resolve$1.sync(path.resolve(process.cwd(), pluginName));
- } catch (e) {
- // try node modules
- requirePath = resolve$1.sync(pluginName, {
- basedir: process.cwd()
- });
- }
- return {
- name: pluginName,
- requirePath
- };
- });
- var externalAutoLoadPluginInfos = pluginSearchDirs.map(function (pluginSearchDir) {
- var resolvedPluginSearchDir = path.resolve(process.cwd(), pluginSearchDir);
- if (!isDirectory(resolvedPluginSearchDir)) {
- throw new Error(`${pluginSearchDir} does not exist or is not a directory`);
- }
- var nodeModulesDir = path.resolve(resolvedPluginSearchDir, "node_modules");
- return findPluginsInNodeModules(nodeModulesDir).map(function (pluginName) {
- return {
- name: pluginName,
- requirePath: resolve$1.sync(pluginName, {
- basedir: resolvedPluginSearchDir
- })
- };
- });
- }).reduce(function (a, b) {
- return a.concat(b);
- }, []);
- var externalPlugins = lodash_uniqby(externalManualLoadPluginInfos.concat(externalAutoLoadPluginInfos), "requirePath").map(function (externalPluginInfo) {
- return Object.assign({
- name: externalPluginInfo.name
- }, require(externalPluginInfo.requirePath));
- }).concat(externalPluginInstances);
- return internalPlugins.concat(externalPlugins);
- }
- function findPluginsInNodeModules(nodeModulesDir) {
- var pluginPackageJsonPaths = globby.sync(["prettier-plugin-*/package.json", "@prettier/plugin-*/package.json"], {
- cwd: nodeModulesDir
- });
- return pluginPackageJsonPaths.map(path.dirname);
- }
- function isDirectory(dir) {
- try {
- return fs.statSync(dir).isDirectory();
- } catch (e) {
- return false;
- }
- }
- var loadPlugins_1 = loadPlugins;
- var mimicFn = function mimicFn(to, from) {
- // TODO: use `Reflect.ownKeys()` when targeting Node.js 6
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = Object.getOwnPropertyNames(from).concat(Object.getOwnPropertySymbols(from))[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var prop = _step.value;
- Object.defineProperty(to, prop, Object.getOwnPropertyDescriptor(from, prop));
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- };
- var mem = createCommonjsModule(function (module) {
- 'use strict';
- var cacheStore = new WeakMap();
- var defaultCacheKey = function defaultCacheKey(x) {
- if (arguments.length === 1 && (x === null || x === undefined || typeof x !== 'function' && typeof x !== 'object')) {
- return x;
- }
- return JSON.stringify(arguments);
- };
- module.exports = function (fn, opts) {
- opts = Object.assign({
- cacheKey: defaultCacheKey,
- cache: new Map()
- }, opts);
- var memoized = function memoized() {
- var cache = cacheStore.get(memoized);
- var key = opts.cacheKey.apply(null, arguments);
- if (cache.has(key)) {
- var c = cache.get(key);
- if (typeof opts.maxAge !== 'number' || Date.now() < c.maxAge) {
- return c.data;
- }
- }
- var ret = fn.apply(null, arguments);
- cache.set(key, {
- data: ret,
- maxAge: Date.now() + (opts.maxAge || 0)
- });
- return ret;
- };
- mimicFn(memoized, fn);
- cacheStore.set(memoized, opts.cache);
- return memoized;
- };
- module.exports.clear = function (fn) {
- var cache = cacheStore.get(fn);
- if (cache && typeof cache.clear === 'function') {
- cache.clear();
- }
- };
- });
- var semver$3 = createCommonjsModule(function (module, exports) {
- exports = module.exports = SemVer; // The debug function is excluded entirely from the minified version.
- /* nomin */
- var debug;
- /* nomin */
- if (typeof process === 'object' &&
- /* nomin */
- process.env &&
- /* nomin */
- process.env.NODE_DEBUG &&
- /* nomin */
- /\bsemver\b/i.test(process.env.NODE_DEBUG))
- /* nomin */
- debug = function debug() {
- /* nomin */
- var args = Array.prototype.slice.call(arguments, 0);
- /* nomin */
- args.unshift('SEMVER');
- /* nomin */
- console.log.apply(console, args);
- /* nomin */
- };
- /* nomin */
- else
- /* nomin */
- debug = function debug() {}; // Note: this is the semver.org version of the spec that it implements
- // Not necessarily the package version of this code.
- exports.SEMVER_SPEC_VERSION = '2.0.0';
- var MAX_LENGTH = 256;
- var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; // Max safe segment length for coercion.
- var MAX_SAFE_COMPONENT_LENGTH = 16; // The actual regexps go on exports.re
- var re = exports.re = [];
- var src = exports.src = [];
- var R = 0; // The following Regular Expressions can be used for tokenizing,
- // validating, and parsing SemVer version strings.
- // ## Numeric Identifier
- // A single `0`, or a non-zero digit followed by zero or more digits.
- var NUMERICIDENTIFIER = R++;
- src[NUMERICIDENTIFIER] = '0|[1-9]\\d*';
- var NUMERICIDENTIFIERLOOSE = R++;
- src[NUMERICIDENTIFIERLOOSE] = '[0-9]+'; // ## Non-numeric Identifier
- // Zero or more digits, followed by a letter or hyphen, and then zero or
- // more letters, digits, or hyphens.
- var NONNUMERICIDENTIFIER = R++;
- src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*'; // ## Main Version
- // Three dot-separated numeric identifiers.
- var MAINVERSION = R++;
- src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + '(' + src[NUMERICIDENTIFIER] + ')\\.' + '(' + src[NUMERICIDENTIFIER] + ')';
- var MAINVERSIONLOOSE = R++;
- src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[NUMERICIDENTIFIERLOOSE] + ')'; // ## Pre-release Version Identifier
- // A numeric identifier, or a non-numeric identifier.
- var PRERELEASEIDENTIFIER = R++;
- src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + '|' + src[NONNUMERICIDENTIFIER] + ')';
- var PRERELEASEIDENTIFIERLOOSE = R++;
- src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + '|' + src[NONNUMERICIDENTIFIER] + ')'; // ## Pre-release Version
- // Hyphen, followed by one or more dot-separated pre-release version
- // identifiers.
- var PRERELEASE = R++;
- src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))';
- var PRERELEASELOOSE = R++;
- src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))'; // ## Build Metadata Identifier
- // Any combination of digits, letters, or hyphens.
- var BUILDIDENTIFIER = R++;
- src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+'; // ## Build Metadata
- // Plus sign, followed by one or more period-separated build metadata
- // identifiers.
- var BUILD = R++;
- src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + '(?:\\.' + src[BUILDIDENTIFIER] + ')*))'; // ## Full Version String
- // A main version, followed optionally by a pre-release version and
- // build metadata.
- // Note that the only major, minor, patch, and pre-release sections of
- // the version string are capturing groups. The build metadata is not a
- // capturing group, because it should not ever be used in version
- // comparison.
- var FULL = R++;
- var FULLPLAIN = 'v?' + src[MAINVERSION] + src[PRERELEASE] + '?' + src[BUILD] + '?';
- src[FULL] = '^' + FULLPLAIN + '$'; // like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
- // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
- // common in the npm registry.
- var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + src[PRERELEASELOOSE] + '?' + src[BUILD] + '?';
- var LOOSE = R++;
- src[LOOSE] = '^' + LOOSEPLAIN + '$';
- var GTLT = R++;
- src[GTLT] = '((?:<|>)?=?)'; // Something like "2.*" or "1.2.x".
- // Note that "x.x" is a valid xRange identifer, meaning "any version"
- // Only the first item is strictly required.
- var XRANGEIDENTIFIERLOOSE = R++;
- src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*';
- var XRANGEIDENTIFIER = R++;
- src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*';
- var XRANGEPLAIN = R++;
- src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + '(?:' + src[PRERELEASE] + ')?' + src[BUILD] + '?' + ')?)?';
- var XRANGEPLAINLOOSE = R++;
- src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:' + src[PRERELEASELOOSE] + ')?' + src[BUILD] + '?' + ')?)?';
- var XRANGE = R++;
- src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$';
- var XRANGELOOSE = R++;
- src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$'; // Coercion.
- // Extract anything that could conceivably be a part of a valid semver
- var COERCE = R++;
- src[COERCE] = '(?:^|[^\\d])' + '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + '(?:$|[^\\d])'; // Tilde ranges.
- // Meaning is "reasonably at or greater than"
- var LONETILDE = R++;
- src[LONETILDE] = '(?:~>?)';
- var TILDETRIM = R++;
- src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+';
- re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g');
- var tildeTrimReplace = '$1~';
- var TILDE = R++;
- src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$';
- var TILDELOOSE = R++;
- src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$'; // Caret ranges.
- // Meaning is "at least and backwards compatible with"
- var LONECARET = R++;
- src[LONECARET] = '(?:\\^)';
- var CARETTRIM = R++;
- src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+';
- re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g');
- var caretTrimReplace = '$1^';
- var CARET = R++;
- src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$';
- var CARETLOOSE = R++;
- src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$'; // A simple gt/lt/eq thing, or just "" to indicate "any version"
- var COMPARATORLOOSE = R++;
- src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$';
- var COMPARATOR = R++;
- src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$'; // An expression to strip any whitespace between the gtlt and the thing
- // it modifies, so that `> 1.2.3` ==> `>1.2.3`
- var COMPARATORTRIM = R++;
- src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')'; // this one has to use the /g flag
- re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g');
- var comparatorTrimReplace = '$1$2$3'; // Something like `1.2.3 - 1.2.4`
- // Note that these all use the loose form, because they'll be
- // checked against either the strict or loose comparator form
- // later.
- var HYPHENRANGE = R++;
- src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + '\\s+-\\s+' + '(' + src[XRANGEPLAIN] + ')' + '\\s*$';
- var HYPHENRANGELOOSE = R++;
- src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + '\\s+-\\s+' + '(' + src[XRANGEPLAINLOOSE] + ')' + '\\s*$'; // Star ranges basically just allow anything at all.
- var STAR = R++;
- src[STAR] = '(<|>)?=?\\s*\\*'; // Compile to actual regexp objects.
- // All are flag-free, unless they were created above with a flag.
- for (var i = 0; i < R; i++) {
- debug(i, src[i]);
- if (!re[i]) re[i] = new RegExp(src[i]);
- }
- exports.parse = parse;
- function parse(version, options) {
- if (!options || typeof options !== 'object') options = {
- loose: !!options,
- includePrerelease: false
- };
- if (version instanceof SemVer) return version;
- if (typeof version !== 'string') return null;
- if (version.length > MAX_LENGTH) return null;
- var r = options.loose ? re[LOOSE] : re[FULL];
- if (!r.test(version)) return null;
- try {
- return new SemVer(version, options);
- } catch (er) {
- return null;
- }
- }
- exports.valid = valid;
- function valid(version, options) {
- var v = parse(version, options);
- return v ? v.version : null;
- }
- exports.clean = clean;
- function clean(version, options) {
- var s = parse(version.trim().replace(/^[=v]+/, ''), options);
- return s ? s.version : null;
- }
- exports.SemVer = SemVer;
- function SemVer(version, options) {
- if (!options || typeof options !== 'object') options = {
- loose: !!options,
- includePrerelease: false
- };
- if (version instanceof SemVer) {
- if (version.loose === options.loose) return version;else version = version.version;
- } else if (typeof version !== 'string') {
- throw new TypeError('Invalid Version: ' + version);
- }
- if (version.length > MAX_LENGTH) throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters');
- if (!(this instanceof SemVer)) return new SemVer(version, options);
- debug('SemVer', version, options);
- this.options = options;
- this.loose = !!options.loose;
- var m = version.trim().match(options.loose ? re[LOOSE] : re[FULL]);
- if (!m) throw new TypeError('Invalid Version: ' + version);
- this.raw = version; // these are actually numbers
- this.major = +m[1];
- this.minor = +m[2];
- this.patch = +m[3];
- if (this.major > MAX_SAFE_INTEGER || this.major < 0) throw new TypeError('Invalid major version');
- if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) throw new TypeError('Invalid minor version');
- if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) throw new TypeError('Invalid patch version'); // numberify any prerelease numeric ids
- if (!m[4]) this.prerelease = [];else this.prerelease = m[4].split('.').map(function (id) {
- if (/^[0-9]+$/.test(id)) {
- var num = +id;
- if (num >= 0 && num < MAX_SAFE_INTEGER) return num;
- }
- return id;
- });
- this.build = m[5] ? m[5].split('.') : [];
- this.format();
- }
- SemVer.prototype.format = function () {
- this.version = this.major + '.' + this.minor + '.' + this.patch;
- if (this.prerelease.length) this.version += '-' + this.prerelease.join('.');
- return this.version;
- };
- SemVer.prototype.toString = function () {
- return this.version;
- };
- SemVer.prototype.compare = function (other) {
- debug('SemVer.compare', this.version, this.options, other);
- if (!(other instanceof SemVer)) other = new SemVer(other, this.options);
- return this.compareMain(other) || this.comparePre(other);
- };
- SemVer.prototype.compareMain = function (other) {
- if (!(other instanceof SemVer)) other = new SemVer(other, this.options);
- return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch);
- };
- SemVer.prototype.comparePre = function (other) {
- if (!(other instanceof SemVer)) other = new SemVer(other, this.options); // NOT having a prerelease is > having one
- if (this.prerelease.length && !other.prerelease.length) return -1;else if (!this.prerelease.length && other.prerelease.length) return 1;else if (!this.prerelease.length && !other.prerelease.length) return 0;
- var i = 0;
- do {
- var a = this.prerelease[i];
- var b = other.prerelease[i];
- debug('prerelease compare', i, a, b);
- if (a === undefined && b === undefined) return 0;else if (b === undefined) return 1;else if (a === undefined) return -1;else if (a === b) continue;else return compareIdentifiers(a, b);
- } while (++i);
- }; // preminor will bump the version up to the next minor release, and immediately
- // down to pre-release. premajor and prepatch work the same way.
- SemVer.prototype.inc = function (release, identifier) {
- switch (release) {
- case 'premajor':
- this.prerelease.length = 0;
- this.patch = 0;
- this.minor = 0;
- this.major++;
- this.inc('pre', identifier);
- break;
- case 'preminor':
- this.prerelease.length = 0;
- this.patch = 0;
- this.minor++;
- this.inc('pre', identifier);
- break;
- case 'prepatch':
- // If this is already a prerelease, it will bump to the next version
- // drop any prereleases that might already exist, since they are not
- // relevant at this point.
- this.prerelease.length = 0;
- this.inc('patch', identifier);
- this.inc('pre', identifier);
- break;
- // If the input is a non-prerelease version, this acts the same as
- // prepatch.
- case 'prerelease':
- if (this.prerelease.length === 0) this.inc('patch', identifier);
- this.inc('pre', identifier);
- break;
- case 'major':
- // If this is a pre-major version, bump up to the same major version.
- // Otherwise increment major.
- // 1.0.0-5 bumps to 1.0.0
- // 1.1.0 bumps to 2.0.0
- if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) this.major++;
- this.minor = 0;
- this.patch = 0;
- this.prerelease = [];
- break;
- case 'minor':
- // If this is a pre-minor version, bump up to the same minor version.
- // Otherwise increment minor.
- // 1.2.0-5 bumps to 1.2.0
- // 1.2.1 bumps to 1.3.0
- if (this.patch !== 0 || this.prerelease.length === 0) this.minor++;
- this.patch = 0;
- this.prerelease = [];
- break;
- case 'patch':
- // If this is not a pre-release version, it will increment the patch.
- // If it is a pre-release it will bump up to the same patch version.
- // 1.2.0-5 patches to 1.2.0
- // 1.2.0 patches to 1.2.1
- if (this.prerelease.length === 0) this.patch++;
- this.prerelease = [];
- break;
- // This probably shouldn't be used publicly.
- // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction.
- case 'pre':
- if (this.prerelease.length === 0) this.prerelease = [0];else {
- var i = this.prerelease.length;
- while (--i >= 0) {
- if (typeof this.prerelease[i] === 'number') {
- this.prerelease[i]++;
- i = -2;
- }
- }
- if (i === -1) // didn't increment anything
- this.prerelease.push(0);
- }
- if (identifier) {
- // 1.2.0-beta.1 bumps to 1.2.0-beta.2,
- // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
- if (this.prerelease[0] === identifier) {
- if (isNaN(this.prerelease[1])) this.prerelease = [identifier, 0];
- } else this.prerelease = [identifier, 0];
- }
- break;
- default:
- throw new Error('invalid increment argument: ' + release);
- }
- this.format();
- this.raw = this.version;
- return this;
- };
- exports.inc = inc;
- function inc(version, release, loose, identifier) {
- if (typeof loose === 'string') {
- identifier = loose;
- loose = undefined;
- }
- try {
- return new SemVer(version, loose).inc(release, identifier).version;
- } catch (er) {
- return null;
- }
- }
- exports.diff = diff;
- function diff(version1, version2) {
- if (eq(version1, version2)) {
- return null;
- } else {
- var v1 = parse(version1);
- var v2 = parse(version2);
- if (v1.prerelease.length || v2.prerelease.length) {
- for (var key in v1) {
- if (key === 'major' || key === 'minor' || key === 'patch') {
- if (v1[key] !== v2[key]) {
- return 'pre' + key;
- }
- }
- }
- return 'prerelease';
- }
- for (var key in v1) {
- if (key === 'major' || key === 'minor' || key === 'patch') {
- if (v1[key] !== v2[key]) {
- return key;
- }
- }
- }
- }
- }
- exports.compareIdentifiers = compareIdentifiers;
- var numeric = /^[0-9]+$/;
- function compareIdentifiers(a, b) {
- var anum = numeric.test(a);
- var bnum = numeric.test(b);
- if (anum && bnum) {
- a = +a;
- b = +b;
- }
- return anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : a > b ? 1 : 0;
- }
- exports.rcompareIdentifiers = rcompareIdentifiers;
- function rcompareIdentifiers(a, b) {
- return compareIdentifiers(b, a);
- }
- exports.major = major;
- function major(a, loose) {
- return new SemVer(a, loose).major;
- }
- exports.minor = minor;
- function minor(a, loose) {
- return new SemVer(a, loose).minor;
- }
- exports.patch = patch;
- function patch(a, loose) {
- return new SemVer(a, loose).patch;
- }
- exports.compare = compare;
- function compare(a, b, loose) {
- return new SemVer(a, loose).compare(new SemVer(b, loose));
- }
- exports.compareLoose = compareLoose;
- function compareLoose(a, b) {
- return compare(a, b, true);
- }
- exports.rcompare = rcompare;
- function rcompare(a, b, loose) {
- return compare(b, a, loose);
- }
- exports.sort = sort;
- function sort(list, loose) {
- return list.sort(function (a, b) {
- return exports.compare(a, b, loose);
- });
- }
- exports.rsort = rsort;
- function rsort(list, loose) {
- return list.sort(function (a, b) {
- return exports.rcompare(a, b, loose);
- });
- }
- exports.gt = gt;
- function gt(a, b, loose) {
- return compare(a, b, loose) > 0;
- }
- exports.lt = lt;
- function lt(a, b, loose) {
- return compare(a, b, loose) < 0;
- }
- exports.eq = eq;
- function eq(a, b, loose) {
- return compare(a, b, loose) === 0;
- }
- exports.neq = neq;
- function neq(a, b, loose) {
- return compare(a, b, loose) !== 0;
- }
- exports.gte = gte;
- function gte(a, b, loose) {
- return compare(a, b, loose) >= 0;
- }
- exports.lte = lte;
- function lte(a, b, loose) {
- return compare(a, b, loose) <= 0;
- }
- exports.cmp = cmp;
- function cmp(a, op, b, loose) {
- var ret;
- switch (op) {
- case '===':
- if (typeof a === 'object') a = a.version;
- if (typeof b === 'object') b = b.version;
- ret = a === b;
- break;
- case '!==':
- if (typeof a === 'object') a = a.version;
- if (typeof b === 'object') b = b.version;
- ret = a !== b;
- break;
- case '':
- case '=':
- case '==':
- ret = eq(a, b, loose);
- break;
- case '!=':
- ret = neq(a, b, loose);
- break;
- case '>':
- ret = gt(a, b, loose);
- break;
- case '>=':
- ret = gte(a, b, loose);
- break;
- case '<':
- ret = lt(a, b, loose);
- break;
- case '<=':
- ret = lte(a, b, loose);
- break;
- default:
- throw new TypeError('Invalid operator: ' + op);
- }
- return ret;
- }
- exports.Comparator = Comparator;
- function Comparator(comp, options) {
- if (!options || typeof options !== 'object') options = {
- loose: !!options,
- includePrerelease: false
- };
- if (comp instanceof Comparator) {
- if (comp.loose === !!options.loose) return comp;else comp = comp.value;
- }
- if (!(this instanceof Comparator)) return new Comparator(comp, options);
- debug('comparator', comp, options);
- this.options = options;
- this.loose = !!options.loose;
- this.parse(comp);
- if (this.semver === ANY) this.value = '';else this.value = this.operator + this.semver.version;
- debug('comp', this);
- }
- var ANY = {};
- Comparator.prototype.parse = function (comp) {
- var r = this.options.loose ? re[COMPARATORLOOSE] : re[COMPARATOR];
- var m = comp.match(r);
- if (!m) throw new TypeError('Invalid comparator: ' + comp);
- this.operator = m[1];
- if (this.operator === '=') this.operator = ''; // if it literally is just '>' or '' then allow anything.
- if (!m[2]) this.semver = ANY;else this.semver = new SemVer(m[2], this.options.loose);
- };
- Comparator.prototype.toString = function () {
- return this.value;
- };
- Comparator.prototype.test = function (version) {
- debug('Comparator.test', version, this.options.loose);
- if (this.semver === ANY) return true;
- if (typeof version === 'string') version = new SemVer(version, this.options);
- return cmp(version, this.operator, this.semver, this.options);
- };
- Comparator.prototype.intersects = function (comp, options) {
- if (!(comp instanceof Comparator)) {
- throw new TypeError('a Comparator is required');
- }
- if (!options || typeof options !== 'object') options = {
- loose: !!options,
- includePrerelease: false
- };
- var rangeTmp;
- if (this.operator === '') {
- rangeTmp = new Range(comp.value, options);
- return satisfies(this.value, rangeTmp, options);
- } else if (comp.operator === '') {
- rangeTmp = new Range(this.value, options);
- return satisfies(comp.semver, rangeTmp, options);
- }
- var sameDirectionIncreasing = (this.operator === '>=' || this.operator === '>') && (comp.operator === '>=' || comp.operator === '>');
- var sameDirectionDecreasing = (this.operator === '<=' || this.operator === '<') && (comp.operator === '<=' || comp.operator === '<');
- var sameSemVer = this.semver.version === comp.semver.version;
- var differentDirectionsInclusive = (this.operator === '>=' || this.operator === '<=') && (comp.operator === '>=' || comp.operator === '<=');
- var oppositeDirectionsLessThan = cmp(this.semver, '<', comp.semver, options) && (this.operator === '>=' || this.operator === '>') && (comp.operator === '<=' || comp.operator === '<');
- var oppositeDirectionsGreaterThan = cmp(this.semver, '>', comp.semver, options) && (this.operator === '<=' || this.operator === '<') && (comp.operator === '>=' || comp.operator === '>');
- return sameDirectionIncreasing || sameDirectionDecreasing || sameSemVer && differentDirectionsInclusive || oppositeDirectionsLessThan || oppositeDirectionsGreaterThan;
- };
- exports.Range = Range;
- function Range(range, options) {
- if (!options || typeof options !== 'object') options = {
- loose: !!options,
- includePrerelease: false
- };
- if (range instanceof Range) {
- if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) {
- return range;
- } else {
- return new Range(range.raw, options);
- }
- }
- if (range instanceof Comparator) {
- return new Range(range.value, options);
- }
- if (!(this instanceof Range)) return new Range(range, options);
- this.options = options;
- this.loose = !!options.loose;
- this.includePrerelease = !!options.includePrerelease; // First, split based on boolean or ||
- this.raw = range;
- this.set = range.split(/\s*\|\|\s*/).map(function (range) {
- return this.parseRange(range.trim());
- }, this).filter(function (c) {
- // throw out any that are not relevant for whatever reason
- return c.length;
- });
- if (!this.set.length) {
- throw new TypeError('Invalid SemVer Range: ' + range);
- }
- this.format();
- }
- Range.prototype.format = function () {
- this.range = this.set.map(function (comps) {
- return comps.join(' ').trim();
- }).join('||').trim();
- return this.range;
- };
- Range.prototype.toString = function () {
- return this.range;
- };
- Range.prototype.parseRange = function (range) {
- var loose = this.options.loose;
- range = range.trim(); // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
- var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE];
- range = range.replace(hr, hyphenReplace);
- debug('hyphen replace', range); // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
- range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace);
- debug('comparator trim', range, re[COMPARATORTRIM]); // `~ 1.2.3` => `~1.2.3`
- range = range.replace(re[TILDETRIM], tildeTrimReplace); // `^ 1.2.3` => `^1.2.3`
- range = range.replace(re[CARETTRIM], caretTrimReplace); // normalize spaces
- range = range.split(/\s+/).join(' '); // At this point, the range is completely trimmed and
- // ready to be split into comparators.
- var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR];
- var set = range.split(' ').map(function (comp) {
- return parseComparator(comp, this.options);
- }, this).join(' ').split(/\s+/);
- if (this.options.loose) {
- // in loose mode, throw out any that are not valid comparators
- set = set.filter(function (comp) {
- return !!comp.match(compRe);
- });
- }
- set = set.map(function (comp) {
- return new Comparator(comp, this.options);
- }, this);
- return set;
- };
- Range.prototype.intersects = function (range, options) {
- if (!(range instanceof Range)) {
- throw new TypeError('a Range is required');
- }
- return this.set.some(function (thisComparators) {
- return thisComparators.every(function (thisComparator) {
- return range.set.some(function (rangeComparators) {
- return rangeComparators.every(function (rangeComparator) {
- return thisComparator.intersects(rangeComparator, options);
- });
- });
- });
- });
- }; // Mostly just for testing and legacy API reasons
- exports.toComparators = toComparators;
- function toComparators(range, options) {
- return new Range(range, options).set.map(function (comp) {
- return comp.map(function (c) {
- return c.value;
- }).join(' ').trim().split(' ');
- });
- } // comprised of xranges, tildes, stars, and gtlt's at this point.
- // already replaced the hyphen ranges
- // turn into a set of JUST comparators.
- function parseComparator(comp, options) {
- debug('comp', comp, options);
- comp = replaceCarets(comp, options);
- debug('caret', comp);
- comp = replaceTildes(comp, options);
- debug('tildes', comp);
- comp = replaceXRanges(comp, options);
- debug('xrange', comp);
- comp = replaceStars(comp, options);
- debug('stars', comp);
- return comp;
- }
- function isX(id) {
- return !id || id.toLowerCase() === 'x' || id === '*';
- } // ~, ~> --> * (any, kinda silly)
- // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0
- // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0
- // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0
- // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0
- // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0
- function replaceTildes(comp, options) {
- return comp.trim().split(/\s+/).map(function (comp) {
- return replaceTilde(comp, options);
- }).join(' ');
- }
- function replaceTilde(comp, options) {
- if (!options || typeof options !== 'object') options = {
- loose: !!options,
- includePrerelease: false
- };
- var r = options.loose ? re[TILDELOOSE] : re[TILDE];
- return comp.replace(r, function (_, M, m, p, pr) {
- debug('tilde', comp, _, M, m, p, pr);
- var ret;
- if (isX(M)) ret = '';else if (isX(m)) ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';else if (isX(p)) // ~1.2 == >=1.2.0 <1.3.0
- ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';else if (pr) {
- debug('replaceTilde pr', pr);
- if (pr.charAt(0) !== '-') pr = '-' + pr;
- ret = '>=' + M + '.' + m + '.' + p + pr + ' <' + M + '.' + (+m + 1) + '.0';
- } else // ~1.2.3 == >=1.2.3 <1.3.0
- ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0';
- debug('tilde return', ret);
- return ret;
- });
- } // ^ --> * (any, kinda silly)
- // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0
- // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0
- // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0
- // ^1.2.3 --> >=1.2.3 <2.0.0
- // ^1.2.0 --> >=1.2.0 <2.0.0
- function replaceCarets(comp, options) {
- return comp.trim().split(/\s+/).map(function (comp) {
- return replaceCaret(comp, options);
- }).join(' ');
- }
- function replaceCaret(comp, options) {
- debug('caret', comp, options);
- if (!options || typeof options !== 'object') options = {
- loose: !!options,
- includePrerelease: false
- };
- var r = options.loose ? re[CARETLOOSE] : re[CARET];
- return comp.replace(r, function (_, M, m, p, pr) {
- debug('caret', comp, _, M, m, p, pr);
- var ret;
- if (isX(M)) ret = '';else if (isX(m)) ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';else if (isX(p)) {
- if (M === '0') ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';else ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0';
- } else if (pr) {
- debug('replaceCaret pr', pr);
- if (pr.charAt(0) !== '-') pr = '-' + pr;
- if (M === '0') {
- if (m === '0') ret = '>=' + M + '.' + m + '.' + p + pr + ' <' + M + '.' + m + '.' + (+p + 1);else ret = '>=' + M + '.' + m + '.' + p + pr + ' <' + M + '.' + (+m + 1) + '.0';
- } else ret = '>=' + M + '.' + m + '.' + p + pr + ' <' + (+M + 1) + '.0.0';
- } else {
- debug('no pr');
- if (M === '0') {
- if (m === '0') ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + m + '.' + (+p + 1);else ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0';
- } else ret = '>=' + M + '.' + m + '.' + p + ' <' + (+M + 1) + '.0.0';
- }
- debug('caret return', ret);
- return ret;
- });
- }
- function replaceXRanges(comp, options) {
- debug('replaceXRanges', comp, options);
- return comp.split(/\s+/).map(function (comp) {
- return replaceXRange(comp, options);
- }).join(' ');
- }
- function replaceXRange(comp, options) {
- comp = comp.trim();
- if (!options || typeof options !== 'object') options = {
- loose: !!options,
- includePrerelease: false
- };
- var r = options.loose ? re[XRANGELOOSE] : re[XRANGE];
- return comp.replace(r, function (ret, gtlt, M, m, p, pr) {
- debug('xRange', comp, ret, gtlt, M, m, p, pr);
- var xM = isX(M);
- var xm = xM || isX(m);
- var xp = xm || isX(p);
- var anyX = xp;
- if (gtlt === '=' && anyX) gtlt = '';
- if (xM) {
- if (gtlt === '>' || gtlt === '<') {
- // nothing is allowed
- ret = '<0.0.0';
- } else {
- // nothing is forbidden
- ret = '*';
- }
- } else if (gtlt && anyX) {
- // replace X with 0
- if (xm) m = 0;
- if (xp) p = 0;
- if (gtlt === '>') {
- // >1 => >=2.0.0
- // >1.2 => >=1.3.0
- // >1.2.3 => >= 1.2.4
- gtlt = '>=';
- if (xm) {
- M = +M + 1;
- m = 0;
- p = 0;
- } else if (xp) {
- m = +m + 1;
- p = 0;
- }
- } else if (gtlt === '<=') {
- // <=0.7.x is actually <0.8.0, since any 0.7.x should
- // pass. Similarly, <=7.x is actually <8.0.0, etc.
- gtlt = '<';
- if (xm) M = +M + 1;else m = +m + 1;
- }
- ret = gtlt + M + '.' + m + '.' + p;
- } else if (xm) {
- ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';
- } else if (xp) {
- ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';
- }
- debug('xRange return', ret);
- return ret;
- });
- } // Because * is AND-ed with everything else in the comparator,
- // and '' means "any version", just remove the *s entirely.
- function replaceStars(comp, options) {
- debug('replaceStars', comp, options); // Looseness is ignored here. star is always as loose as it gets!
- return comp.trim().replace(re[STAR], '');
- } // This function is passed to string.replace(re[HYPHENRANGE])
- // M, m, patch, prerelease, build
- // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5
- // 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do
- // 1.2 - 3.4 => >=1.2.0 <3.5.0
- function hyphenReplace($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) {
- if (isX(fM)) from = '';else if (isX(fm)) from = '>=' + fM + '.0.0';else if (isX(fp)) from = '>=' + fM + '.' + fm + '.0';else from = '>=' + from;
- if (isX(tM)) to = '';else if (isX(tm)) to = '<' + (+tM + 1) + '.0.0';else if (isX(tp)) to = '<' + tM + '.' + (+tm + 1) + '.0';else if (tpr) to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr;else to = '<=' + to;
- return (from + ' ' + to).trim();
- } // if ANY of the sets match ALL of its comparators, then pass
- Range.prototype.test = function (version) {
- if (!version) return false;
- if (typeof version === 'string') version = new SemVer(version, this.options);
- for (var i = 0; i < this.set.length; i++) {
- if (testSet(this.set[i], version, this.options)) return true;
- }
- return false;
- };
- function testSet(set, version, options) {
- for (var i = 0; i < set.length; i++) {
- if (!set[i].test(version)) return false;
- }
- if (!options) options = {};
- if (version.prerelease.length && !options.includePrerelease) {
- // Find the set of versions that are allowed to have prereleases
- // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0
- // That should allow `1.2.3-pr.2` to pass.
- // However, `1.2.4-alpha.notready` should NOT be allowed,
- // even though it's within the range set by the comparators.
- for (var i = 0; i < set.length; i++) {
- debug(set[i].semver);
- if (set[i].semver === ANY) continue;
- if (set[i].semver.prerelease.length > 0) {
- var allowed = set[i].semver;
- if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) return true;
- }
- } // Version has a -pre, but it's not one of the ones we like.
- return false;
- }
- return true;
- }
- exports.satisfies = satisfies;
- function satisfies(version, range, options) {
- try {
- range = new Range(range, options);
- } catch (er) {
- return false;
- }
- return range.test(version);
- }
- exports.maxSatisfying = maxSatisfying;
- function maxSatisfying(versions, range, options) {
- var max = null;
- var maxSV = null;
- try {
- var rangeObj = new Range(range, options);
- } catch (er) {
- return null;
- }
- versions.forEach(function (v) {
- if (rangeObj.test(v)) {
- // satisfies(v, range, options)
- if (!max || maxSV.compare(v) === -1) {
- // compare(max, v, true)
- max = v;
- maxSV = new SemVer(max, options);
- }
- }
- });
- return max;
- }
- exports.minSatisfying = minSatisfying;
- function minSatisfying(versions, range, options) {
- var min = null;
- var minSV = null;
- try {
- var rangeObj = new Range(range, options);
- } catch (er) {
- return null;
- }
- versions.forEach(function (v) {
- if (rangeObj.test(v)) {
- // satisfies(v, range, options)
- if (!min || minSV.compare(v) === 1) {
- // compare(min, v, true)
- min = v;
- minSV = new SemVer(min, options);
- }
- }
- });
- return min;
- }
- exports.validRange = validRange;
- function validRange(range, options) {
- try {
- // Return '*' instead of '' so that truthiness works.
- // This will throw if it's invalid anyway
- return new Range(range, options).range || '*';
- } catch (er) {
- return null;
- }
- } // Determine if version is less than all the versions possible in the range
- exports.ltr = ltr;
- function ltr(version, range, options) {
- return outside(version, range, '<', options);
- } // Determine if version is greater than all the versions possible in the range.
- exports.gtr = gtr;
- function gtr(version, range, options) {
- return outside(version, range, '>', options);
- }
- exports.outside = outside;
- function outside(version, range, hilo, options) {
- version = new SemVer(version, options);
- range = new Range(range, options);
- var gtfn, ltefn, ltfn, comp, ecomp;
- switch (hilo) {
- case '>':
- gtfn = gt;
- ltefn = lte;
- ltfn = lt;
- comp = '>';
- ecomp = '>=';
- break;
- case '<':
- gtfn = lt;
- ltefn = gte;
- ltfn = gt;
- comp = '<';
- ecomp = '<=';
- break;
- default:
- throw new TypeError('Must provide a hilo val of "<" or ">"');
- } // If it satisifes the range it is not outside
- if (satisfies(version, range, options)) {
- return false;
- } // From now on, variable terms are as if we're in "gtr" mode.
- // but note that everything is flipped for the "ltr" function.
- for (var i = 0; i < range.set.length; ++i) {
- var comparators = range.set[i];
- var high = null;
- var low = null;
- comparators.forEach(function (comparator) {
- if (comparator.semver === ANY) {
- comparator = new Comparator('>=0.0.0');
- }
- high = high || comparator;
- low = low || comparator;
- if (gtfn(comparator.semver, high.semver, options)) {
- high = comparator;
- } else if (ltfn(comparator.semver, low.semver, options)) {
- low = comparator;
- }
- }); // If the edge version comparator has a operator then our version
- // isn't outside it
- if (high.operator === comp || high.operator === ecomp) {
- return false;
- } // If the lowest version comparator has an operator and our version
- // is less than it then it isn't higher than the range
- if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) {
- return false;
- } else if (low.operator === ecomp && ltfn(version, low.semver)) {
- return false;
- }
- }
- return true;
- }
- exports.prerelease = prerelease;
- function prerelease(version, options) {
- var parsed = parse(version, options);
- return parsed && parsed.prerelease.length ? parsed.prerelease : null;
- }
- exports.intersects = intersects;
- function intersects(r1, r2, options) {
- r1 = new Range(r1, options);
- r2 = new Range(r2, options);
- return r1.intersects(r2);
- }
- exports.coerce = coerce;
- function coerce(version) {
- if (version instanceof SemVer) return version;
- if (typeof version !== 'string') return null;
- var match = version.match(re[COERCE]);
- if (match == null) return null;
- return parse((match[1] || '0') + '.' + (match[2] || '0') + '.' + (match[3] || '0'));
- }
- });
- var hasOwnProperty$1 = Object.prototype.hasOwnProperty;
- var pseudomap = PseudoMap;
- function PseudoMap(set) {
- if (!(this instanceof PseudoMap)) // whyyyyyyy
- throw new TypeError("Constructor PseudoMap requires 'new'");
- this.clear();
- if (set) {
- if (set instanceof PseudoMap || typeof Map === 'function' && set instanceof Map) set.forEach(function (value, key) {
- this.set(key, value);
- }, this);else if (Array.isArray(set)) set.forEach(function (kv) {
- this.set(kv[0], kv[1]);
- }, this);else throw new TypeError('invalid argument');
- }
- }
- PseudoMap.prototype.forEach = function (fn, thisp) {
- thisp = thisp || this;
- Object.keys(this._data).forEach(function (k) {
- if (k !== 'size') fn.call(thisp, this._data[k].value, this._data[k].key);
- }, this);
- };
- PseudoMap.prototype.has = function (k) {
- return !!find(this._data, k);
- };
- PseudoMap.prototype.get = function (k) {
- var res = find(this._data, k);
- return res && res.value;
- };
- PseudoMap.prototype.set = function (k, v) {
- set$1(this._data, k, v);
- };
- PseudoMap.prototype.delete = function (k) {
- var res = find(this._data, k);
- if (res) {
- delete this._data[res._index];
- this._data.size--;
- }
- };
- PseudoMap.prototype.clear = function () {
- var data = Object.create(null);
- data.size = 0;
- Object.defineProperty(this, '_data', {
- value: data,
- enumerable: false,
- configurable: true,
- writable: false
- });
- };
- Object.defineProperty(PseudoMap.prototype, 'size', {
- get: function get() {
- return this._data.size;
- },
- set: function set(n) {},
- enumerable: true,
- configurable: true
- });
- PseudoMap.prototype.values = PseudoMap.prototype.keys = PseudoMap.prototype.entries = function () {
- throw new Error('iterators are not implemented in this version');
- }; // Either identical, or both NaN
- function same(a, b) {
- return a === b || a !== a && b !== b;
- }
- function Entry$1(k, v, i) {
- this.key = k;
- this.value = v;
- this._index = i;
- }
- function find(data, k) {
- for (var i = 0, s = '_' + k, key = s; hasOwnProperty$1.call(data, key); key = s + i++) {
- if (same(data[key].key, k)) return data[key];
- }
- }
- function set$1(data, k, v) {
- for (var i = 0, s = '_' + k, key = s; hasOwnProperty$1.call(data, key); key = s + i++) {
- if (same(data[key].key, k)) {
- data[key].value = v;
- return;
- }
- }
- data.size++;
- data[key] = new Entry$1(k, v, key);
- }
- var map$1 = createCommonjsModule(function (module) {
- if (process.env.npm_package_name === 'pseudomap' && process.env.npm_lifecycle_script === 'test') process.env.TEST_PSEUDOMAP = 'true';
- if (typeof Map === 'function' && !process.env.TEST_PSEUDOMAP) {
- module.exports = Map;
- } else {
- module.exports = pseudomap;
- }
- });
- var yallist = Yallist;
- Yallist.Node = Node;
- Yallist.create = Yallist;
- function Yallist(list) {
- var self = this;
- if (!(self instanceof Yallist)) {
- self = new Yallist();
- }
- self.tail = null;
- self.head = null;
- self.length = 0;
- if (list && typeof list.forEach === 'function') {
- list.forEach(function (item) {
- self.push(item);
- });
- } else if (arguments.length > 0) {
- for (var i = 0, l = arguments.length; i < l; i++) {
- self.push(arguments[i]);
- }
- }
- return self;
- }
- Yallist.prototype.removeNode = function (node) {
- if (node.list !== this) {
- throw new Error('removing node which does not belong to this list');
- }
- var next = node.next;
- var prev = node.prev;
- if (next) {
- next.prev = prev;
- }
- if (prev) {
- prev.next = next;
- }
- if (node === this.head) {
- this.head = next;
- }
- if (node === this.tail) {
- this.tail = prev;
- }
- node.list.length--;
- node.next = null;
- node.prev = null;
- node.list = null;
- };
- Yallist.prototype.unshiftNode = function (node) {
- if (node === this.head) {
- return;
- }
- if (node.list) {
- node.list.removeNode(node);
- }
- var head = this.head;
- node.list = this;
- node.next = head;
- if (head) {
- head.prev = node;
- }
- this.head = node;
- if (!this.tail) {
- this.tail = node;
- }
- this.length++;
- };
- Yallist.prototype.pushNode = function (node) {
- if (node === this.tail) {
- return;
- }
- if (node.list) {
- node.list.removeNode(node);
- }
- var tail = this.tail;
- node.list = this;
- node.prev = tail;
- if (tail) {
- tail.next = node;
- }
- this.tail = node;
- if (!this.head) {
- this.head = node;
- }
- this.length++;
- };
- Yallist.prototype.push = function () {
- for (var i = 0, l = arguments.length; i < l; i++) {
- push(this, arguments[i]);
- }
- return this.length;
- };
- Yallist.prototype.unshift = function () {
- for (var i = 0, l = arguments.length; i < l; i++) {
- unshift(this, arguments[i]);
- }
- return this.length;
- };
- Yallist.prototype.pop = function () {
- if (!this.tail) {
- return undefined;
- }
- var res = this.tail.value;
- this.tail = this.tail.prev;
- if (this.tail) {
- this.tail.next = null;
- } else {
- this.head = null;
- }
- this.length--;
- return res;
- };
- Yallist.prototype.shift = function () {
- if (!this.head) {
- return undefined;
- }
- var res = this.head.value;
- this.head = this.head.next;
- if (this.head) {
- this.head.prev = null;
- } else {
- this.tail = null;
- }
- this.length--;
- return res;
- };
- Yallist.prototype.forEach = function (fn, thisp) {
- thisp = thisp || this;
- for (var walker = this.head, i = 0; walker !== null; i++) {
- fn.call(thisp, walker.value, i, this);
- walker = walker.next;
- }
- };
- Yallist.prototype.forEachReverse = function (fn, thisp) {
- thisp = thisp || this;
- for (var walker = this.tail, i = this.length - 1; walker !== null; i--) {
- fn.call(thisp, walker.value, i, this);
- walker = walker.prev;
- }
- };
- Yallist.prototype.get = function (n) {
- for (var i = 0, walker = this.head; walker !== null && i < n; i++) {
- // abort out of the list early if we hit a cycle
- walker = walker.next;
- }
- if (i === n && walker !== null) {
- return walker.value;
- }
- };
- Yallist.prototype.getReverse = function (n) {
- for (var i = 0, walker = this.tail; walker !== null && i < n; i++) {
- // abort out of the list early if we hit a cycle
- walker = walker.prev;
- }
- if (i === n && walker !== null) {
- return walker.value;
- }
- };
- Yallist.prototype.map = function (fn, thisp) {
- thisp = thisp || this;
- var res = new Yallist();
- for (var walker = this.head; walker !== null;) {
- res.push(fn.call(thisp, walker.value, this));
- walker = walker.next;
- }
- return res;
- };
- Yallist.prototype.mapReverse = function (fn, thisp) {
- thisp = thisp || this;
- var res = new Yallist();
- for (var walker = this.tail; walker !== null;) {
- res.push(fn.call(thisp, walker.value, this));
- walker = walker.prev;
- }
- return res;
- };
- Yallist.prototype.reduce = function (fn, initial) {
- var acc;
- var walker = this.head;
- if (arguments.length > 1) {
- acc = initial;
- } else if (this.head) {
- walker = this.head.next;
- acc = this.head.value;
- } else {
- throw new TypeError('Reduce of empty list with no initial value');
- }
- for (var i = 0; walker !== null; i++) {
- acc = fn(acc, walker.value, i);
- walker = walker.next;
- }
- return acc;
- };
- Yallist.prototype.reduceReverse = function (fn, initial) {
- var acc;
- var walker = this.tail;
- if (arguments.length > 1) {
- acc = initial;
- } else if (this.tail) {
- walker = this.tail.prev;
- acc = this.tail.value;
- } else {
- throw new TypeError('Reduce of empty list with no initial value');
- }
- for (var i = this.length - 1; walker !== null; i--) {
- acc = fn(acc, walker.value, i);
- walker = walker.prev;
- }
- return acc;
- };
- Yallist.prototype.toArray = function () {
- var arr = new Array(this.length);
- for (var i = 0, walker = this.head; walker !== null; i++) {
- arr[i] = walker.value;
- walker = walker.next;
- }
- return arr;
- };
- Yallist.prototype.toArrayReverse = function () {
- var arr = new Array(this.length);
- for (var i = 0, walker = this.tail; walker !== null; i++) {
- arr[i] = walker.value;
- walker = walker.prev;
- }
- return arr;
- };
- Yallist.prototype.slice = function (from, to) {
- to = to || this.length;
- if (to < 0) {
- to += this.length;
- }
- from = from || 0;
- if (from < 0) {
- from += this.length;
- }
- var ret = new Yallist();
- if (to < from || to < 0) {
- return ret;
- }
- if (from < 0) {
- from = 0;
- }
- if (to > this.length) {
- to = this.length;
- }
- for (var i = 0, walker = this.head; walker !== null && i < from; i++) {
- walker = walker.next;
- }
- for (; walker !== null && i < to; i++, walker = walker.next) {
- ret.push(walker.value);
- }
- return ret;
- };
- Yallist.prototype.sliceReverse = function (from, to) {
- to = to || this.length;
- if (to < 0) {
- to += this.length;
- }
- from = from || 0;
- if (from < 0) {
- from += this.length;
- }
- var ret = new Yallist();
- if (to < from || to < 0) {
- return ret;
- }
- if (from < 0) {
- from = 0;
- }
- if (to > this.length) {
- to = this.length;
- }
- for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) {
- walker = walker.prev;
- }
- for (; walker !== null && i > from; i--, walker = walker.prev) {
- ret.push(walker.value);
- }
- return ret;
- };
- Yallist.prototype.reverse = function () {
- var head = this.head;
- var tail = this.tail;
- for (var walker = head; walker !== null; walker = walker.prev) {
- var p = walker.prev;
- walker.prev = walker.next;
- walker.next = p;
- }
- this.head = tail;
- this.tail = head;
- return this;
- };
- function push(self, item) {
- self.tail = new Node(item, self.tail, null, self);
- if (!self.head) {
- self.head = self.tail;
- }
- self.length++;
- }
- function unshift(self, item) {
- self.head = new Node(item, null, self.head, self);
- if (!self.tail) {
- self.tail = self.head;
- }
- self.length++;
- }
- function Node(value, prev, next, list) {
- if (!(this instanceof Node)) {
- return new Node(value, prev, next, list);
- }
- this.list = list;
- this.value = value;
- if (prev) {
- prev.next = this;
- this.prev = prev;
- } else {
- this.prev = null;
- }
- if (next) {
- next.prev = this;
- this.next = next;
- } else {
- this.next = null;
- }
- }
- var lruCache = LRUCache; // This will be a proper iterable 'Map' in engines that support it,
- // or a fakey-fake PseudoMap in older versions.
- // A linked list to keep track of recently-used-ness
- // use symbols if possible, otherwise just _props
- var hasSymbol = typeof Symbol === 'function';
- var makeSymbol;
- if (hasSymbol) {
- makeSymbol = function makeSymbol(key) {
- return Symbol(key);
- };
- } else {
- makeSymbol = function makeSymbol(key) {
- return '_' + key;
- };
- }
- var MAX = makeSymbol('max');
- var LENGTH = makeSymbol('length');
- var LENGTH_CALCULATOR = makeSymbol('lengthCalculator');
- var ALLOW_STALE = makeSymbol('allowStale');
- var MAX_AGE = makeSymbol('maxAge');
- var DISPOSE = makeSymbol('dispose');
- var NO_DISPOSE_ON_SET = makeSymbol('noDisposeOnSet');
- var LRU_LIST = makeSymbol('lruList');
- var CACHE = makeSymbol('cache');
- function naiveLength() {
- return 1;
- } // lruList is a yallist where the head is the youngest
- // item, and the tail is the oldest. the list contains the Hit
- // objects as the entries.
- // Each Hit object has a reference to its Yallist.Node. This
- // never changes.
- //
- // cache is a Map (or PseudoMap) that matches the keys to
- // the Yallist.Node object.
- function LRUCache(options) {
- if (!(this instanceof LRUCache)) {
- return new LRUCache(options);
- }
- if (typeof options === 'number') {
- options = {
- max: options
- };
- }
- if (!options) {
- options = {};
- }
- var max = this[MAX] = options.max; // Kind of weird to have a default max of Infinity, but oh well.
- if (!max || !(typeof max === 'number') || max <= 0) {
- this[MAX] = Infinity;
- }
- var lc = options.length || naiveLength;
- if (typeof lc !== 'function') {
- lc = naiveLength;
- }
- this[LENGTH_CALCULATOR] = lc;
- this[ALLOW_STALE] = options.stale || false;
- this[MAX_AGE] = options.maxAge || 0;
- this[DISPOSE] = options.dispose;
- this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false;
- this.reset();
- } // resize the cache when the max changes.
- Object.defineProperty(LRUCache.prototype, 'max', {
- set: function set(mL) {
- if (!mL || !(typeof mL === 'number') || mL <= 0) {
- mL = Infinity;
- }
- this[MAX] = mL;
- trim$2(this);
- },
- get: function get() {
- return this[MAX];
- },
- enumerable: true
- });
- Object.defineProperty(LRUCache.prototype, 'allowStale', {
- set: function set(allowStale) {
- this[ALLOW_STALE] = !!allowStale;
- },
- get: function get() {
- return this[ALLOW_STALE];
- },
- enumerable: true
- });
- Object.defineProperty(LRUCache.prototype, 'maxAge', {
- set: function set(mA) {
- if (!mA || !(typeof mA === 'number') || mA < 0) {
- mA = 0;
- }
- this[MAX_AGE] = mA;
- trim$2(this);
- },
- get: function get() {
- return this[MAX_AGE];
- },
- enumerable: true
- }); // resize the cache when the lengthCalculator changes.
- Object.defineProperty(LRUCache.prototype, 'lengthCalculator', {
- set: function set(lC) {
- if (typeof lC !== 'function') {
- lC = naiveLength;
- }
- if (lC !== this[LENGTH_CALCULATOR]) {
- this[LENGTH_CALCULATOR] = lC;
- this[LENGTH] = 0;
- this[LRU_LIST].forEach(function (hit) {
- hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key);
- this[LENGTH] += hit.length;
- }, this);
- }
- trim$2(this);
- },
- get: function get() {
- return this[LENGTH_CALCULATOR];
- },
- enumerable: true
- });
- Object.defineProperty(LRUCache.prototype, 'length', {
- get: function get() {
- return this[LENGTH];
- },
- enumerable: true
- });
- Object.defineProperty(LRUCache.prototype, 'itemCount', {
- get: function get() {
- return this[LRU_LIST].length;
- },
- enumerable: true
- });
- LRUCache.prototype.rforEach = function (fn, thisp) {
- thisp = thisp || this;
- for (var walker = this[LRU_LIST].tail; walker !== null;) {
- var prev = walker.prev;
- forEachStep(this, fn, walker, thisp);
- walker = prev;
- }
- };
- function forEachStep(self, fn, node, thisp) {
- var hit = node.value;
- if (isStale(self, hit)) {
- del$1(self, node);
- if (!self[ALLOW_STALE]) {
- hit = undefined;
- }
- }
- if (hit) {
- fn.call(thisp, hit.value, hit.key, self);
- }
- }
- LRUCache.prototype.forEach = function (fn, thisp) {
- thisp = thisp || this;
- for (var walker = this[LRU_LIST].head; walker !== null;) {
- var next = walker.next;
- forEachStep(this, fn, walker, thisp);
- walker = next;
- }
- };
- LRUCache.prototype.keys = function () {
- return this[LRU_LIST].toArray().map(function (k) {
- return k.key;
- }, this);
- };
- LRUCache.prototype.values = function () {
- return this[LRU_LIST].toArray().map(function (k) {
- return k.value;
- }, this);
- };
- LRUCache.prototype.reset = function () {
- if (this[DISPOSE] && this[LRU_LIST] && this[LRU_LIST].length) {
- this[LRU_LIST].forEach(function (hit) {
- this[DISPOSE](hit.key, hit.value);
- }, this);
- }
- this[CACHE] = new map$1(); // hash of items by key
- this[LRU_LIST] = new yallist(); // list of items in order of use recency
- this[LENGTH] = 0; // length of items in the list
- };
- LRUCache.prototype.dump = function () {
- return this[LRU_LIST].map(function (hit) {
- if (!isStale(this, hit)) {
- return {
- k: hit.key,
- v: hit.value,
- e: hit.now + (hit.maxAge || 0)
- };
- }
- }, this).toArray().filter(function (h) {
- return h;
- });
- };
- LRUCache.prototype.dumpLru = function () {
- return this[LRU_LIST];
- };
- LRUCache.prototype.inspect = function (n, opts) {
- var str = 'LRUCache {';
- var extras = false;
- var as = this[ALLOW_STALE];
- if (as) {
- str += '\n allowStale: true';
- extras = true;
- }
- var max = this[MAX];
- if (max && max !== Infinity) {
- if (extras) {
- str += ',';
- }
- str += '\n max: ' + util.inspect(max, opts);
- extras = true;
- }
- var maxAge = this[MAX_AGE];
- if (maxAge) {
- if (extras) {
- str += ',';
- }
- str += '\n maxAge: ' + util.inspect(maxAge, opts);
- extras = true;
- }
- var lc = this[LENGTH_CALCULATOR];
- if (lc && lc !== naiveLength) {
- if (extras) {
- str += ',';
- }
- str += '\n length: ' + util.inspect(this[LENGTH], opts);
- extras = true;
- }
- var didFirst = false;
- this[LRU_LIST].forEach(function (item) {
- if (didFirst) {
- str += ',\n ';
- } else {
- if (extras) {
- str += ',\n';
- }
- didFirst = true;
- str += '\n ';
- }
- var key = util.inspect(item.key).split('\n').join('\n ');
- var val = {
- value: item.value
- };
- if (item.maxAge !== maxAge) {
- val.maxAge = item.maxAge;
- }
- if (lc !== naiveLength) {
- val.length = item.length;
- }
- if (isStale(this, item)) {
- val.stale = true;
- }
- val = util.inspect(val, opts).split('\n').join('\n ');
- str += key + ' => ' + val;
- });
- if (didFirst || extras) {
- str += '\n';
- }
- str += '}';
- return str;
- };
- LRUCache.prototype.set = function (key, value, maxAge) {
- maxAge = maxAge || this[MAX_AGE];
- var now = maxAge ? Date.now() : 0;
- var len = this[LENGTH_CALCULATOR](value, key);
- if (this[CACHE].has(key)) {
- if (len > this[MAX]) {
- del$1(this, this[CACHE].get(key));
- return false;
- }
- var node = this[CACHE].get(key);
- var item = node.value; // dispose of the old one before overwriting
- // split out into 2 ifs for better coverage tracking
- if (this[DISPOSE]) {
- if (!this[NO_DISPOSE_ON_SET]) {
- this[DISPOSE](key, item.value);
- }
- }
- item.now = now;
- item.maxAge = maxAge;
- item.value = value;
- this[LENGTH] += len - item.length;
- item.length = len;
- this.get(key);
- trim$2(this);
- return true;
- }
- var hit = new Entry(key, value, len, now, maxAge); // oversized objects fall out of cache automatically.
- if (hit.length > this[MAX]) {
- if (this[DISPOSE]) {
- this[DISPOSE](key, value);
- }
- return false;
- }
- this[LENGTH] += hit.length;
- this[LRU_LIST].unshift(hit);
- this[CACHE].set(key, this[LRU_LIST].head);
- trim$2(this);
- return true;
- };
- LRUCache.prototype.has = function (key) {
- if (!this[CACHE].has(key)) return false;
- var hit = this[CACHE].get(key).value;
- if (isStale(this, hit)) {
- return false;
- }
- return true;
- };
- LRUCache.prototype.get = function (key) {
- return get(this, key, true);
- };
- LRUCache.prototype.peek = function (key) {
- return get(this, key, false);
- };
- LRUCache.prototype.pop = function () {
- var node = this[LRU_LIST].tail;
- if (!node) return null;
- del$1(this, node);
- return node.value;
- };
- LRUCache.prototype.del = function (key) {
- del$1(this, this[CACHE].get(key));
- };
- LRUCache.prototype.load = function (arr) {
- // reset the cache
- this.reset();
- var now = Date.now(); // A previous serialized cache has the most recent items first
- for (var l = arr.length - 1; l >= 0; l--) {
- var hit = arr[l];
- var expiresAt = hit.e || 0;
- if (expiresAt === 0) {
- // the item was created without expiration in a non aged cache
- this.set(hit.k, hit.v);
- } else {
- var maxAge = expiresAt - now; // dont add already expired items
- if (maxAge > 0) {
- this.set(hit.k, hit.v, maxAge);
- }
- }
- }
- };
- LRUCache.prototype.prune = function () {
- var self = this;
- this[CACHE].forEach(function (value, key) {
- get(self, key, false);
- });
- };
- function get(self, key, doUse) {
- var node = self[CACHE].get(key);
- if (node) {
- var hit = node.value;
- if (isStale(self, hit)) {
- del$1(self, node);
- if (!self[ALLOW_STALE]) hit = undefined;
- } else {
- if (doUse) {
- self[LRU_LIST].unshiftNode(node);
- }
- }
- if (hit) hit = hit.value;
- }
- return hit;
- }
- function isStale(self, hit) {
- if (!hit || !hit.maxAge && !self[MAX_AGE]) {
- return false;
- }
- var stale = false;
- var diff = Date.now() - hit.now;
- if (hit.maxAge) {
- stale = diff > hit.maxAge;
- } else {
- stale = self[MAX_AGE] && diff > self[MAX_AGE];
- }
- return stale;
- }
- function trim$2(self) {
- if (self[LENGTH] > self[MAX]) {
- for (var walker = self[LRU_LIST].tail; self[LENGTH] > self[MAX] && walker !== null;) {
- // We know that we're about to delete this one, and also
- // what the next least recently used key will be, so just
- // go ahead and set it now.
- var prev = walker.prev;
- del$1(self, walker);
- walker = prev;
- }
- }
- }
- function del$1(self, node) {
- if (node) {
- var hit = node.value;
- if (self[DISPOSE]) {
- self[DISPOSE](hit.key, hit.value);
- }
- self[LENGTH] -= hit.length;
- self[CACHE].delete(hit.key);
- self[LRU_LIST].removeNode(node);
- }
- } // classy, since V8 prefers predictable objects.
- function Entry(key, value, length, now, maxAge) {
- this.key = key;
- this.value = value;
- this.length = length;
- this.now = now;
- this.maxAge = maxAge || 0;
- }
- var sigmund_1 = sigmund;
- function sigmund(subject, maxSessions) {
- maxSessions = maxSessions || 10;
- var notes = [];
- var analysis = '';
- var RE = RegExp;
- function psychoAnalyze(subject, session) {
- if (session > maxSessions) return;
- if (typeof subject === 'function' || typeof subject === 'undefined') {
- return;
- }
- if (typeof subject !== 'object' || !subject || subject instanceof RE) {
- analysis += subject;
- return;
- }
- if (notes.indexOf(subject) !== -1 || session === maxSessions) return;
- notes.push(subject);
- analysis += '{';
- Object.keys(subject).forEach(function (issue, _, __) {
- // pseudo-private values. skip those.
- if (issue.charAt(0) === '_') return;
- var to = typeof subject[issue];
- if (to === 'function' || to === 'undefined') return;
- analysis += issue;
- psychoAnalyze(subject[issue], session + 1);
- });
- }
- psychoAnalyze(subject, 0);
- return analysis;
- } // vim: set softtabstop=4 shiftwidth=4:
- var fnmatch = createCommonjsModule(function (module, exports) {
- // Based on minimatch.js by isaacs <https://npmjs.org/package/minimatch>
- var platform = typeof process === "object" ? process.platform : "win32";
- if (module) module.exports = minimatch;else exports.minimatch = minimatch;
- minimatch.Minimatch = Minimatch;
- var cache = minimatch.cache = new lruCache({
- max: 100
- }),
- GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {};
- var qmark = "[^/]" // * => any number of characters
- ,
- star = qmark + "*?" // ** when dots are allowed. Anything goes, except .. and .
- // not (^ or / followed by one or two dots followed by $ or /),
- // followed by anything, any number of times.
- ,
- twoStarDot = "(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?" // not a ^ or / followed by a dot,
- // followed by anything, any number of times.
- ,
- twoStarNoDot = "(?:(?!(?:\\\/|^)\\.).)*?" // characters that need to be escaped in RegExp.
- ,
- reSpecials = charSet("().*{}+?[]^$\\!"); // "abc" -> { a:true, b:true, c:true }
- function charSet(s) {
- return s.split("").reduce(function (set, c) {
- set[c] = true;
- return set;
- }, {});
- } // normalizes slashes.
- var slashSplit = /\/+/;
- minimatch.monkeyPatch = monkeyPatch;
- function monkeyPatch() {
- var desc = Object.getOwnPropertyDescriptor(String.prototype, "match");
- var orig = desc.value;
- desc.value = function (p) {
- if (p instanceof Minimatch) return p.match(this);
- return orig.call(this, p);
- };
- Object.defineProperty(String.prototype, desc);
- }
- minimatch.filter = filter;
- function filter(pattern, options) {
- options = options || {};
- return function (p, i, list) {
- return minimatch(p, pattern, options);
- };
- }
- function ext(a, b) {
- a = a || {};
- b = b || {};
- var t = {};
- Object.keys(b).forEach(function (k) {
- t[k] = b[k];
- });
- Object.keys(a).forEach(function (k) {
- t[k] = a[k];
- });
- return t;
- }
- minimatch.defaults = function (def) {
- if (!def || !Object.keys(def).length) return minimatch;
- var orig = minimatch;
- var m = function minimatch(p, pattern, options) {
- return orig.minimatch(p, pattern, ext(def, options));
- };
- m.Minimatch = function Minimatch(pattern, options) {
- return new orig.Minimatch(pattern, ext(def, options));
- };
- return m;
- };
- Minimatch.defaults = function (def) {
- if (!def || !Object.keys(def).length) return Minimatch;
- return minimatch.defaults(def).Minimatch;
- };
- function minimatch(p, pattern, options) {
- if (typeof pattern !== "string") {
- throw new TypeError("glob pattern string required");
- }
- if (!options) options = {}; // shortcut: comments match nothing.
- if (!options.nocomment && pattern.charAt(0) === "#") {
- return false;
- } // "" only matches ""
- if (pattern.trim() === "") return p === "";
- return new Minimatch(pattern, options).match(p);
- }
- function Minimatch(pattern, options) {
- if (!(this instanceof Minimatch)) {
- return new Minimatch(pattern, options, cache);
- }
- if (typeof pattern !== "string") {
- throw new TypeError("glob pattern string required");
- }
- if (!options) options = {}; // windows: need to use /, not \
- // On other platforms, \ is a valid (albeit bad) filename char.
- if (platform === "win32") {
- pattern = pattern.split("\\").join("/");
- } // lru storage.
- // these things aren't particularly big, but walking down the string
- // and turning it into a regexp can get pretty costly.
- var cacheKey = pattern + "\n" + sigmund_1(options);
- var cached = minimatch.cache.get(cacheKey);
- if (cached) return cached;
- minimatch.cache.set(cacheKey, this);
- this.options = options;
- this.set = [];
- this.pattern = pattern;
- this.regexp = null;
- this.negate = false;
- this.comment = false;
- this.empty = false; // make the set of regexps etc.
- this.make();
- }
- Minimatch.prototype.make = make;
- function make() {
- // don't do it more than once.
- if (this._made) return;
- var pattern = this.pattern;
- var options = this.options; // empty patterns and comments match nothing.
- if (!options.nocomment && pattern.charAt(0) === "#") {
- this.comment = true;
- return;
- }
- if (!pattern) {
- this.empty = true;
- return;
- } // step 1: figure out negation, etc.
- this.parseNegate(); // step 2: expand braces
- var set = this.globSet = this.braceExpand();
- if (options.debug) console.error(this.pattern, set); // step 3: now we have a set, so turn each one into a series of path-portion
- // matching patterns.
- // These will be regexps, except in the case of "**", which is
- // set to the GLOBSTAR object for globstar behavior,
- // and will not contain any / characters
- set = this.globParts = set.map(function (s) {
- return s.split(slashSplit);
- });
- if (options.debug) console.error(this.pattern, set); // glob --> regexps
- set = set.map(function (s, si, set) {
- return s.map(this.parse, this);
- }, this);
- if (options.debug) console.error(this.pattern, set); // filter out everything that didn't compile properly.
- set = set.filter(function (s) {
- return -1 === s.indexOf(false);
- });
- if (options.debug) console.error(this.pattern, set);
- this.set = set;
- }
- Minimatch.prototype.parseNegate = parseNegate;
- function parseNegate() {
- var pattern = this.pattern,
- negate = false,
- options = this.options,
- negateOffset = 0;
- if (options.nonegate) return;
- for (var i = 0, l = pattern.length; i < l && pattern.charAt(i) === "!"; i++) {
- negate = !negate;
- negateOffset++;
- }
- if (negateOffset) this.pattern = pattern.substr(negateOffset);
- this.negate = negate;
- } // Brace expansion:
- // a{b,c}d -> abd acd
- // a{b,}c -> abc ac
- // a{0..3}d -> a0d a1d a2d a3d
- // a{b,c{d,e}f}g -> abg acdfg acefg
- // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
- //
- // Invalid sets are not expanded.
- // a{2..}b -> a{2..}b
- // a{b}c -> a{b}c
- minimatch.braceExpand = function (pattern, options) {
- return new Minimatch(pattern, options).braceExpand();
- };
- Minimatch.prototype.braceExpand = braceExpand;
- function braceExpand(pattern, options) {
- options = options || this.options;
- pattern = typeof pattern === "undefined" ? this.pattern : pattern;
- if (typeof pattern === "undefined") {
- throw new Error("undefined pattern");
- }
- if (options.nobrace || !pattern.match(/\{.*\}/)) {
- // shortcut. no need to expand.
- return [pattern];
- }
- var escaping = false; // examples and comments refer to this crazy pattern:
- // a{b,c{d,e},{f,g}h}x{y,z}
- // expected:
- // abxy
- // abxz
- // acdxy
- // acdxz
- // acexy
- // acexz
- // afhxy
- // afhxz
- // aghxy
- // aghxz
- // everything before the first \{ is just a prefix.
- // So, we pluck that off, and work with the rest,
- // and then prepend it to everything we find.
- if (pattern.charAt(0) !== "{") {
- // console.error(pattern)
- var prefix = null;
- for (var i = 0, l = pattern.length; i < l; i++) {
- var c = pattern.charAt(i); // console.error(i, c)
- if (c === "\\") {
- escaping = !escaping;
- } else if (c === "{" && !escaping) {
- prefix = pattern.substr(0, i);
- break;
- }
- } // actually no sets, all { were escaped.
- if (prefix === null) {
- // console.error("no sets")
- return [pattern];
- }
- var tail = braceExpand(pattern.substr(i), options);
- return tail.map(function (t) {
- return prefix + t;
- });
- } // now we have something like:
- // {b,c{d,e},{f,g}h}x{y,z}
- // walk through the set, expanding each part, until
- // the set ends. then, we'll expand the suffix.
- // If the set only has a single member, then'll put the {} back
- // first, handle numeric sets, since they're easier
- var numset = pattern.match(/^\{(-?[0-9]+)\.\.(-?[0-9]+)\}/);
- if (numset) {
- // console.error("numset", numset[1], numset[2])
- var suf = braceExpand(pattern.substr(numset[0].length), options),
- start = +numset[1],
- end = +numset[2],
- inc = start > end ? -1 : 1,
- set = [];
- for (var i = start; i != end + inc; i += inc) {
- // append all the suffixes
- for (var ii = 0, ll = suf.length; ii < ll; ii++) {
- set.push(i + suf[ii]);
- }
- }
- return set;
- } // ok, walk through the set
- // We hope, somewhat optimistically, that there
- // will be a } at the end.
- // If the closing brace isn't found, then the pattern is
- // interpreted as braceExpand("\\" + pattern) so that
- // the leading \{ will be interpreted literally.
- var i = 1 // skip the \{
- ,
- depth = 1,
- set = [],
- member = "",
- sawEnd = false,
- escaping = false;
- function addMember() {
- set.push(member);
- member = "";
- } // console.error("Entering for")
- FOR: for (i = 1, l = pattern.length; i < l; i++) {
- var c = pattern.charAt(i); // console.error("", i, c)
- if (escaping) {
- escaping = false;
- member += "\\" + c;
- } else {
- switch (c) {
- case "\\":
- escaping = true;
- continue;
- case "{":
- depth++;
- member += "{";
- continue;
- case "}":
- depth--; // if this closes the actual set, then we're done
- if (depth === 0) {
- addMember(); // pluck off the close-brace
- i++;
- break FOR;
- } else {
- member += c;
- continue;
- }
- case ",":
- if (depth === 1) {
- addMember();
- } else {
- member += c;
- }
- continue;
- default:
- member += c;
- continue;
- } // switch
- } // else
- } // for
- // now we've either finished the set, and the suffix is
- // pattern.substr(i), or we have *not* closed the set,
- // and need to escape the leading brace
- if (depth !== 0) {
- // console.error("didn't close", pattern)
- return braceExpand("\\" + pattern, options);
- } // x{y,z} -> ["xy", "xz"]
- // console.error("set", set)
- // console.error("suffix", pattern.substr(i))
- var suf = braceExpand(pattern.substr(i), options); // ["b", "c{d,e}","{f,g}h"] ->
- // [["b"], ["cd", "ce"], ["fh", "gh"]]
- var addBraces = set.length === 1; // console.error("set pre-expanded", set)
- set = set.map(function (p) {
- return braceExpand(p, options);
- }); // console.error("set expanded", set)
- // [["b"], ["cd", "ce"], ["fh", "gh"]] ->
- // ["b", "cd", "ce", "fh", "gh"]
- set = set.reduce(function (l, r) {
- return l.concat(r);
- });
- if (addBraces) {
- set = set.map(function (s) {
- return "{" + s + "}";
- });
- } // now attach the suffixes.
- var ret = [];
- for (var i = 0, l = set.length; i < l; i++) {
- for (var ii = 0, ll = suf.length; ii < ll; ii++) {
- ret.push(set[i] + suf[ii]);
- }
- }
- return ret;
- } // parse a component of the expanded set.
- // At this point, no pattern may contain "/" in it
- // so we're going to return a 2d array, where each entry is the full
- // pattern, split on '/', and then turned into a regular expression.
- // A regexp is made at the end which joins each array with an
- // escaped /, and another full one which joins each regexp with |.
- //
- // Following the lead of Bash 4.1, note that "**" only has special meaning
- // when it is the *only* thing in a path portion. Otherwise, any series
- // of * is equivalent to a single *. Globstar behavior is enabled by
- // default, and can be disabled by setting options.noglobstar.
- Minimatch.prototype.parse = parse;
- var SUBPARSE = {};
- function parse(pattern, isSub) {
- var options = this.options; // shortcuts
- if (!options.noglobstar && pattern === "**") return GLOBSTAR;
- if (pattern === "") return "";
- var re = "",
- hasMagic = !!options.nocase,
- escaping = false // ? => one single character
- ,
- patternListStack = [],
- plType,
- stateChar,
- inClass = false,
- reClassStart = -1,
- classStart = -1 // . and .. never match anything that doesn't start with .,
- // even when options.dot is set.
- ,
- patternStart = pattern.charAt(0) === "." ? "" // anything
- // not (start or / followed by . or .. followed by / or end)
- : options.dot ? "(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))" : "(?!\\.)";
- function clearStateChar() {
- if (stateChar) {
- // we had some state-tracking character
- // that wasn't consumed by this pass.
- switch (stateChar) {
- case "*":
- re += star;
- hasMagic = true;
- break;
- case "?":
- re += qmark;
- hasMagic = true;
- break;
- default:
- re += "\\" + stateChar;
- break;
- }
- stateChar = false;
- }
- }
- for (var i = 0, len = pattern.length, c; i < len && (c = pattern.charAt(i)); i++) {
- if (options.debug) {
- console.error("%s\t%s %s %j", pattern, i, re, c);
- } // skip over any that are escaped.
- if (escaping && reSpecials[c]) {
- re += "\\" + c;
- escaping = false;
- continue;
- }
- SWITCH: switch (c) {
- case "/":
- // completely not allowed, even escaped.
- // Should already be path-split by now.
- return false;
- case "\\":
- clearStateChar();
- escaping = true;
- continue;
- // the various stateChar values
- // for the "extglob" stuff.
- case "?":
- case "*":
- case "+":
- case "@":
- case "!":
- if (options.debug) {
- console.error("%s\t%s %s %j <-- stateChar", pattern, i, re, c);
- } // all of those are literals inside a class, except that
- // the glob [!a] means [^a] in regexp
- if (inClass) {
- if (c === "!" && i === classStart + 1) c = "^";
- re += c;
- continue;
- } // if we already have a stateChar, then it means
- // that there was something like ** or +? in there.
- // Handle the stateChar, then proceed with this one.
- clearStateChar();
- stateChar = c; // if extglob is disabled, then +(asdf|foo) isn't a thing.
- // just clear the statechar *now*, rather than even diving into
- // the patternList stuff.
- if (options.noext) clearStateChar();
- continue;
- case "(":
- if (inClass) {
- re += "(";
- continue;
- }
- if (!stateChar) {
- re += "\\(";
- continue;
- }
- plType = stateChar;
- patternListStack.push({
- type: plType,
- start: i - 1,
- reStart: re.length
- }); // negation is (?:(?!js)[^/]*)
- re += stateChar === "!" ? "(?:(?!" : "(?:";
- stateChar = false;
- continue;
- case ")":
- if (inClass || !patternListStack.length) {
- re += "\\)";
- continue;
- }
- hasMagic = true;
- re += ")";
- plType = patternListStack.pop().type; // negation is (?:(?!js)[^/]*)
- // The others are (?:<pattern>)<type>
- switch (plType) {
- case "!":
- re += "[^/]*?)";
- break;
- case "?":
- case "+":
- case "*":
- re += plType;
- case "@":
- break;
- // the default anyway
- }
- continue;
- case "|":
- if (inClass || !patternListStack.length || escaping) {
- re += "\\|";
- escaping = false;
- continue;
- }
- re += "|";
- continue;
- // these are mostly the same in regexp and glob
- case "[":
- // swallow any state-tracking char before the [
- clearStateChar();
- if (inClass) {
- re += "\\" + c;
- continue;
- }
- inClass = true;
- classStart = i;
- reClassStart = re.length;
- re += c;
- continue;
- case "]":
- // a right bracket shall lose its special
- // meaning and represent itself in
- // a bracket expression if it occurs
- // first in the list. -- POSIX.2 2.8.3.2
- if (i === classStart + 1 || !inClass) {
- re += "\\" + c;
- escaping = false;
- continue;
- } // finish up the class.
- hasMagic = true;
- inClass = false;
- re += c;
- continue;
- default:
- // swallow any state char that wasn't consumed
- clearStateChar();
- if (escaping) {
- // no need
- escaping = false;
- } else if (reSpecials[c] && !(c === "^" && inClass)) {
- re += "\\";
- }
- re += c;
- } // switch
- } // for
- // handle the case where we left a class open.
- // "[abc" is valid, equivalent to "\[abc"
- if (inClass) {
- // split where the last [ was, and escape it
- // this is a huge pita. We now have to re-walk
- // the contents of the would-be class to re-translate
- // any characters that were passed through as-is
- var cs = pattern.substr(classStart + 1),
- sp = this.parse(cs, SUBPARSE);
- re = re.substr(0, reClassStart) + "\\[" + sp[0];
- hasMagic = hasMagic || sp[1];
- } // handle the case where we had a +( thing at the *end*
- // of the pattern.
- // each pattern list stack adds 3 chars, and we need to go through
- // and escape any | chars that were passed through as-is for the regexp.
- // Go through and escape them, taking care not to double-escape any
- // | chars that were already escaped.
- var pl;
- while (pl = patternListStack.pop()) {
- var tail = re.slice(pl.reStart + 3); // maybe some even number of \, then maybe 1 \, followed by a |
- tail = tail.replace(/((?:\\{2})*)(\\?)\|/g, function (_, $1, $2) {
- if (!$2) {
- // the | isn't already escaped, so escape it.
- $2 = "\\";
- } // need to escape all those slashes *again*, without escaping the
- // one that we need for escaping the | character. As it works out,
- // escaping an even number of slashes can be done by simply repeating
- // it exactly after itself. That's why this trick works.
- //
- // I am sorry that you have to see this.
- return $1 + $1 + $2 + "|";
- }); // console.error("tail=%j\n %s", tail, tail)
- var t = pl.type === "*" ? star : pl.type === "?" ? qmark : "\\" + pl.type;
- hasMagic = true;
- re = re.slice(0, pl.reStart) + t + "\\(" + tail;
- } // handle trailing things that only matter at the very end.
- clearStateChar();
- if (escaping) {
- // trailing \\
- re += "\\\\";
- } // only need to apply the nodot start if the re starts with
- // something that could conceivably capture a dot
- var addPatternStart = false;
- switch (re.charAt(0)) {
- case ".":
- case "[":
- case "(":
- addPatternStart = true;
- } // if the re is not "" at this point, then we need to make sure
- // it doesn't match against an empty path part.
- // Otherwise a/* will match a/, which it should not.
- if (re !== "" && hasMagic) re = "(?=.)" + re;
- if (addPatternStart) re = patternStart + re; // parsing just a piece of a larger pattern.
- if (isSub === SUBPARSE) {
- return [re, hasMagic];
- } // skip the regexp for non-magical patterns
- // unescape anything in it, though, so that it'll be
- // an exact match against a file etc.
- if (!hasMagic) {
- return globUnescape(pattern);
- }
- var flags = options.nocase ? "i" : "",
- regExp = new RegExp("^" + re + "$", flags);
- regExp._glob = pattern;
- regExp._src = re;
- return regExp;
- }
- minimatch.makeRe = function (pattern, options) {
- return new Minimatch(pattern, options || {}).makeRe();
- };
- Minimatch.prototype.makeRe = makeRe;
- function makeRe() {
- if (this.regexp || this.regexp === false) return this.regexp; // at this point, this.set is a 2d array of partial
- // pattern strings, or "**".
- //
- // It's better to use .match(). This function shouldn't
- // be used, really, but it's pretty convenient sometimes,
- // when you just want to work with a regex.
- var set = this.set;
- if (!set.length) return this.regexp = false;
- var options = this.options;
- var twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot,
- flags = options.nocase ? "i" : "";
- var re = set.map(function (pattern) {
- return pattern.map(function (p) {
- return p === GLOBSTAR ? twoStar : typeof p === "string" ? regExpEscape(p) : p._src;
- }).join("\\\/");
- }).join("|"); // must match entire pattern
- // ending in a * or ** will make it less strict.
- re = "^(?:" + re + ")$"; // can match anything, as long as it's not this.
- if (this.negate) re = "^(?!" + re + ").*$";
- try {
- return this.regexp = new RegExp(re, flags);
- } catch (ex) {
- return this.regexp = false;
- }
- }
- minimatch.match = function (list, pattern, options) {
- var mm = new Minimatch(pattern, options);
- list = list.filter(function (f) {
- return mm.match(f);
- });
- if (options.nonull && !list.length) {
- list.push(pattern);
- }
- return list;
- };
- Minimatch.prototype.match = match;
- function match(f, partial) {
- // console.error("match", f, this.pattern)
- // short-circuit in the case of busted things.
- // comments, etc.
- if (this.comment) return false;
- if (this.empty) return f === "";
- if (f === "/" && partial) return true;
- var options = this.options; // windows: need to use /, not \
- // On other platforms, \ is a valid (albeit bad) filename char.
- if (platform === "win32") {
- f = f.split("\\").join("/");
- } // treat the test path as a set of pathparts.
- f = f.split(slashSplit);
- if (options.debug) {
- console.error(this.pattern, "split", f);
- } // just ONE of the pattern sets in this.set needs to match
- // in order for it to be valid. If negating, then just one
- // match means that we have failed.
- // Either way, return on the first hit.
- var set = this.set; // console.error(this.pattern, "set", set)
- for (var i = 0, l = set.length; i < l; i++) {
- var pattern = set[i];
- var hit = this.matchOne(f, pattern, partial);
- if (hit) {
- if (options.flipNegate) return true;
- return !this.negate;
- }
- } // didn't get any hits. this is success if it's a negative
- // pattern, failure otherwise.
- if (options.flipNegate) return false;
- return this.negate;
- } // set partial to true to test if, for example,
- // "/a/b" matches the start of "/*/b/*/d"
- // Partial means, if you run out of file before you run
- // out of pattern, then that's fine, as long as all
- // the parts match.
- Minimatch.prototype.matchOne = function (file, pattern, partial) {
- var options = this.options;
- if (options.debug) {
- console.error("matchOne", {
- "this": this,
- file: file,
- pattern: pattern
- });
- }
- if (options.matchBase && pattern.length === 1) {
- file = path.basename(file.join("/")).split("/");
- }
- if (options.debug) {
- console.error("matchOne", file.length, pattern.length);
- }
- for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
- if (options.debug) {
- console.error("matchOne loop");
- }
- var p = pattern[pi],
- f = file[fi];
- if (options.debug) {
- console.error(pattern, p, f);
- } // should be impossible.
- // some invalid regexp stuff in the set.
- if (p === false) return false;
- if (p === GLOBSTAR) {
- if (options.debug) console.error('GLOBSTAR', [pattern, p, f]); // "**"
- // a/**/b/**/c would match the following:
- // a/b/x/y/z/c
- // a/x/y/z/b/c
- // a/b/x/b/x/c
- // a/b/c
- // To do this, take the rest of the pattern after
- // the **, and see if it would match the file remainder.
- // If so, return success.
- // If not, the ** "swallows" a segment, and try again.
- // This is recursively awful.
- //
- // a/**/b/**/c matching a/b/x/y/z/c
- // - a matches a
- // - doublestar
- // - matchOne(b/x/y/z/c, b/**/c)
- // - b matches b
- // - doublestar
- // - matchOne(x/y/z/c, c) -> no
- // - matchOne(y/z/c, c) -> no
- // - matchOne(z/c, c) -> no
- // - matchOne(c, c) yes, hit
- var fr = fi,
- pr = pi + 1;
- if (pr === pl) {
- if (options.debug) console.error('** at the end'); // a ** at the end will just swallow the rest.
- // We have found a match.
- // however, it will not swallow /.x, unless
- // options.dot is set.
- // . and .. are *never* matched by **, for explosively
- // exponential reasons.
- for (; fi < fl; fi++) {
- if (file[fi] === "." || file[fi] === ".." || !options.dot && file[fi].charAt(0) === ".") return false;
- }
- return true;
- } // ok, let's see if we can swallow whatever we can.
- WHILE: while (fr < fl) {
- var swallowee = file[fr];
- if (options.debug) {
- console.error('\nglobstar while', file, fr, pattern, pr, swallowee);
- } // XXX remove this slice. Just pass the start index.
- if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
- if (options.debug) console.error('globstar found match!', fr, fl, swallowee); // found a match.
- return true;
- } else {
- // can't swallow "." or ".." ever.
- // can only swallow ".foo" when explicitly asked.
- if (swallowee === "." || swallowee === ".." || !options.dot && swallowee.charAt(0) === ".") {
- if (options.debug) console.error("dot detected!", file, fr, pattern, pr);
- break WHILE;
- } // ** swallows a segment, and continue.
- if (options.debug) console.error('globstar swallow a segment, and continue');
- fr++;
- }
- } // no match was found.
- // However, in partial mode, we can't say this is necessarily over.
- // If there's more *pattern* left, then
- if (partial) {
- // ran out of file
- // console.error("\n>>> no match, partial?", file, fr, pattern, pr)
- if (fr === fl) return true;
- }
- return false;
- } // something other than **
- // non-magic patterns just have to match exactly
- // patterns with magic have been turned into regexps.
- var hit;
- if (typeof p === "string") {
- if (options.nocase) {
- hit = f.toLowerCase() === p.toLowerCase();
- } else {
- hit = f === p;
- }
- if (options.debug) {
- console.error("string match", p, f, hit);
- }
- } else {
- hit = f.match(p);
- if (options.debug) {
- console.error("pattern match", p, f, hit);
- }
- }
- if (!hit) return false;
- } // Note: ending in / means that we'll get a final ""
- // at the end of the pattern. This can only match a
- // corresponding "" at the end of the file.
- // If the file ends in /, then it can only match a
- // a pattern that ends in /, unless the pattern just
- // doesn't have any more for it. But, a/b/ should *not*
- // match "a/b/*", even though "" matches against the
- // [^/]*? pattern, except in partial mode, where it might
- // simply not be reached yet.
- // However, a/b/ should still satisfy a/*
- // now either we fell off the end of the pattern, or we're done.
- if (fi === fl && pi === pl) {
- // ran out of pattern and filename at the same time.
- // an exact hit!
- return true;
- } else if (fi === fl) {
- // ran out of file, but still had pattern left.
- // this is ok if we're doing the match as part of
- // a glob fs traversal.
- return partial;
- } else if (pi === pl) {
- // ran out of pattern, still have file left.
- // this is only acceptable if we're on the very last
- // empty segment of a file with a trailing slash.
- // a/* should match a/b/
- var emptyFileEnd = fi === fl - 1 && file[fi] === "";
- return emptyFileEnd;
- } // should be unreachable.
- throw new Error("wtf?");
- }; // replace stuff like \* with *
- function globUnescape(s) {
- return s.replace(/\\(.)/g, "$1");
- }
- function regExpEscape(s) {
- return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
- }
- });
- var ini = createCommonjsModule(function (module, exports) {
- "use strict"; // Based on iniparser by shockie <https://npmjs.org/package/iniparser>
- var __awaiter = commonjsGlobal && commonjsGlobal.__awaiter || function (thisArg, _arguments, P, generator) {
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) {
- try {
- step(generator.next(value));
- } catch (e) {
- reject(e);
- }
- }
- function rejected(value) {
- try {
- step(generator["throw"](value));
- } catch (e) {
- reject(e);
- }
- }
- function step(result) {
- result.done ? resolve(result.value) : new P(function (resolve) {
- resolve(result.value);
- }).then(fulfilled, rejected);
- }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- var __generator = commonjsGlobal && commonjsGlobal.__generator || function (thisArg, body) {
- var _ = {
- label: 0,
- sent: function sent() {
- if (t[0] & 1) throw t[1];
- return t[1];
- },
- trys: [],
- ops: []
- },
- f,
- y,
- t,
- g;
- return g = {
- next: verb(0),
- "throw": verb(1),
- "return": verb(2)
- }, typeof Symbol === "function" && (g[Symbol.iterator] = function () {
- return this;
- }), g;
- function verb(n) {
- return function (v) {
- return step([n, v]);
- };
- }
- function step(op) {
- if (f) throw new TypeError("Generator is already executing.");
- while (_) {
- try {
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
- if (y = 0, t) op = [op[0] & 2, t.value];
- switch (op[0]) {
- case 0:
- case 1:
- t = op;
- break;
- case 4:
- _.label++;
- return {
- value: op[1],
- done: false
- };
- case 5:
- _.label++;
- y = op[1];
- op = [0];
- continue;
- case 7:
- op = _.ops.pop();
- _.trys.pop();
- continue;
- default:
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
- _ = 0;
- continue;
- }
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
- _.label = op[1];
- break;
- }
- if (op[0] === 6 && _.label < t[1]) {
- _.label = t[1];
- t = op;
- break;
- }
- if (t && _.label < t[2]) {
- _.label = t[2];
- _.ops.push(op);
- break;
- }
- if (t[2]) _.ops.pop();
- _.trys.pop();
- continue;
- }
- op = body.call(thisArg, _);
- } catch (e) {
- op = [6, e];
- y = 0;
- } finally {
- f = t = 0;
- }
- }
- if (op[0] & 5) throw op[1];
- return {
- value: op[0] ? op[1] : void 0,
- done: true
- };
- }
- };
- var __importStar = commonjsGlobal && commonjsGlobal.__importStar || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) {
- if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
- }
- result["default"] = mod;
- return result;
- };
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- var fs$$2 = __importStar(fs);
- /**
- * define the possible values:
- * section: [section]
- * param: key=value
- * comment: ;this is a comment
- */
- var regex = {
- section: /^\s*\[(([^#;]|\\#|\\;)+)\]\s*([#;].*)?$/,
- param: /^\s*([\w\.\-\_]+)\s*[=:]\s*(.*?)\s*([#;].*)?$/,
- comment: /^\s*[#;].*$/
- };
- /**
- * Parses an .ini file
- * @param file The location of the .ini file
- */
- function parse(file) {
- return __awaiter(this, void 0, void 0, function () {
- return __generator(this, function (_a) {
- return [2
- /*return*/
- , new Promise(function (resolve, reject) {
- fs$$2.readFile(file, 'utf8', function (err, data) {
- if (err) {
- reject(err);
- return;
- }
- resolve(parseString(data));
- });
- })];
- });
- });
- }
- exports.parse = parse;
- function parseSync(file) {
- return parseString(fs$$2.readFileSync(file, 'utf8'));
- }
- exports.parseSync = parseSync;
- function parseString(data) {
- var sectionBody = {};
- var sectionName = null;
- var value = [[sectionName, sectionBody]];
- var lines = data.split(/\r\n|\r|\n/);
- lines.forEach(function (line) {
- var match;
- if (regex.comment.test(line)) {
- return;
- }
- if (regex.param.test(line)) {
- match = line.match(regex.param);
- sectionBody[match[1]] = match[2];
- } else if (regex.section.test(line)) {
- match = line.match(regex.section);
- sectionName = match[1];
- sectionBody = {};
- value.push([sectionName, sectionBody]);
- }
- });
- return value;
- }
- exports.parseString = parseString;
- });
- unwrapExports(ini);
- var name$17 = "editorconfig";
- var version$3 = "0.15.2";
- var description$1 = "EditorConfig File Locator and Interpreter for Node.js";
- var keywords = ["editorconfig", "core"];
- var main$1 = "src/index.js";
- var contributors = ["Hong Xu (topbug.net)", "Jed Mao (https://github.com/jedmao/)", "Trey Hunner (http://treyhunner.com)"];
- var directories = {
- "bin": "./bin",
- "lib": "./lib"
- };
- var scripts$1 = {
- "clean": "rimraf dist",
- "prebuild": "npm run clean",
- "build": "tsc",
- "pretest": "npm run lint && npm run build && npm run copy && cmake .",
- "test": "ctest .",
- "pretest:ci": "npm run pretest",
- "test:ci": "ctest -VV --output-on-failure .",
- "lint": "npm run eclint && npm run tslint",
- "eclint": "eclint check --indent_size ignore \"src/**\"",
- "tslint": "tslint --project tsconfig.json --exclude package.json",
- "copy": "cpy .npmignore LICENSE README.md CHANGELOG.md dist && cpy bin/* dist/bin && cpy src/lib/fnmatch*.* dist/src/lib",
- "prepub": "npm run lint && npm run build && npm run copy",
- "pub": "npm publish ./dist"
- };
- var repository$1 = {
- "type": "git",
- "url": "git://github.com/editorconfig/editorconfig-core-js.git"
- };
- var bugs = "https://github.com/editorconfig/editorconfig-core-js/issues";
- var author$1 = "EditorConfig Team";
- var license$1 = "MIT";
- var dependencies$1 = {
- "@types/node": "^10.11.7",
- "@types/semver": "^5.5.0",
- "commander": "^2.19.0",
- "lru-cache": "^4.1.3",
- "semver": "^5.6.0",
- "sigmund": "^1.0.1"
- };
- var devDependencies$1 = {
- "@types/mocha": "^5.2.5",
- "cpy-cli": "^2.0.0",
- "eclint": "^2.8.0",
- "mocha": "^5.2.0",
- "rimraf": "^2.6.2",
- "should": "^13.2.3",
- "tslint": "^5.11.0",
- "typescript": "^3.1.3"
- };
- var _package$2 = {
- name: name$17,
- version: version$3,
- description: description$1,
- keywords: keywords,
- main: main$1,
- contributors: contributors,
- directories: directories,
- scripts: scripts$1,
- repository: repository$1,
- bugs: bugs,
- author: author$1,
- license: license$1,
- dependencies: dependencies$1,
- devDependencies: devDependencies$1
- };
- var _package$3 = Object.freeze({
- name: name$17,
- version: version$3,
- description: description$1,
- keywords: keywords,
- main: main$1,
- contributors: contributors,
- directories: directories,
- scripts: scripts$1,
- repository: repository$1,
- bugs: bugs,
- author: author$1,
- license: license$1,
- dependencies: dependencies$1,
- devDependencies: devDependencies$1,
- default: _package$2
- });
- var require$$4$6 = ( _package$3 && _package$2 ) || _package$3;
- var src$2 = createCommonjsModule(function (module, exports) {
- "use strict";
- var __awaiter = commonjsGlobal && commonjsGlobal.__awaiter || function (thisArg, _arguments, P, generator) {
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) {
- try {
- step(generator.next(value));
- } catch (e) {
- reject(e);
- }
- }
- function rejected(value) {
- try {
- step(generator["throw"](value));
- } catch (e) {
- reject(e);
- }
- }
- function step(result) {
- result.done ? resolve(result.value) : new P(function (resolve) {
- resolve(result.value);
- }).then(fulfilled, rejected);
- }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- var __generator = commonjsGlobal && commonjsGlobal.__generator || function (thisArg, body) {
- var _ = {
- label: 0,
- sent: function sent() {
- if (t[0] & 1) throw t[1];
- return t[1];
- },
- trys: [],
- ops: []
- },
- f,
- y,
- t,
- g;
- return g = {
- next: verb(0),
- "throw": verb(1),
- "return": verb(2)
- }, typeof Symbol === "function" && (g[Symbol.iterator] = function () {
- return this;
- }), g;
- function verb(n) {
- return function (v) {
- return step([n, v]);
- };
- }
- function step(op) {
- if (f) throw new TypeError("Generator is already executing.");
- while (_) {
- try {
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
- if (y = 0, t) op = [op[0] & 2, t.value];
- switch (op[0]) {
- case 0:
- case 1:
- t = op;
- break;
- case 4:
- _.label++;
- return {
- value: op[1],
- done: false
- };
- case 5:
- _.label++;
- y = op[1];
- op = [0];
- continue;
- case 7:
- op = _.ops.pop();
- _.trys.pop();
- continue;
- default:
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
- _ = 0;
- continue;
- }
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
- _.label = op[1];
- break;
- }
- if (op[0] === 6 && _.label < t[1]) {
- _.label = t[1];
- t = op;
- break;
- }
- if (t && _.label < t[2]) {
- _.label = t[2];
- _.ops.push(op);
- break;
- }
- if (t[2]) _.ops.pop();
- _.trys.pop();
- continue;
- }
- op = body.call(thisArg, _);
- } catch (e) {
- op = [6, e];
- y = 0;
- } finally {
- f = t = 0;
- }
- }
- if (op[0] & 5) throw op[1];
- return {
- value: op[0] ? op[1] : void 0,
- done: true
- };
- }
- };
- var __importStar = commonjsGlobal && commonjsGlobal.__importStar || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) {
- if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
- }
- result["default"] = mod;
- return result;
- };
- var __importDefault = commonjsGlobal && commonjsGlobal.__importDefault || function (mod) {
- return mod && mod.__esModule ? mod : {
- "default": mod
- };
- };
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- var fs$$2 = __importStar(fs);
- var path$$2 = __importStar(path);
- var semver = __importStar(semver$3);
- var fnmatch_1 = __importDefault(fnmatch);
- exports.parseString = ini.parseString;
- var package_json_1 = __importDefault(require$$4$6);
- var knownProps = {
- end_of_line: true,
- indent_style: true,
- indent_size: true,
- insert_final_newline: true,
- trim_trailing_whitespace: true,
- charset: true
- };
- function fnmatch$$1(filepath, glob) {
- var matchOptions = {
- matchBase: true,
- dot: true,
- noext: true
- };
- glob = glob.replace(/\*\*/g, '{*,**/**/**}');
- return fnmatch_1.default(filepath, glob, matchOptions);
- }
- function getConfigFileNames(filepath, options) {
- var paths = [];
- do {
- filepath = path$$2.dirname(filepath);
- paths.push(path$$2.join(filepath, options.config));
- } while (filepath !== options.root);
- return paths;
- }
- function processMatches(matches, version) {
- // Set indent_size to 'tab' if indent_size is unspecified and
- // indent_style is set to 'tab'.
- if ('indent_style' in matches && matches.indent_style === 'tab' && !('indent_size' in matches) && semver.gte(version, '0.10.0')) {
- matches.indent_size = 'tab';
- } // Set tab_width to indent_size if indent_size is specified and
- // tab_width is unspecified
- if ('indent_size' in matches && !('tab_width' in matches) && matches.indent_size !== 'tab') {
- matches.tab_width = matches.indent_size;
- } // Set indent_size to tab_width if indent_size is 'tab'
- if ('indent_size' in matches && 'tab_width' in matches && matches.indent_size === 'tab') {
- matches.indent_size = matches.tab_width;
- }
- return matches;
- }
- function processOptions(options, filepath) {
- if (options === void 0) {
- options = {};
- }
- return {
- config: options.config || '.editorconfig',
- version: options.version || package_json_1.default.version,
- root: path$$2.resolve(options.root || path$$2.parse(filepath).root)
- };
- }
- function buildFullGlob(pathPrefix, glob) {
- switch (glob.indexOf('/')) {
- case -1:
- glob = '**/' + glob;
- break;
- case 0:
- glob = glob.substring(1);
- break;
- default:
- break;
- }
- return path$$2.join(pathPrefix, glob);
- }
- function extendProps(props, options) {
- if (props === void 0) {
- props = {};
- }
- if (options === void 0) {
- options = {};
- }
- for (var key in options) {
- if (options.hasOwnProperty(key)) {
- var value = options[key];
- var key2 = key.toLowerCase();
- var value2 = value;
- if (knownProps[key2]) {
- value2 = value.toLowerCase();
- }
- try {
- value2 = JSON.parse(value);
- } catch (e) {}
- if (typeof value === 'undefined' || value === null) {
- // null and undefined are values specific to JSON (no special meaning
- // in editorconfig) & should just be returned as regular strings.
- value2 = String(value);
- }
- props[key2] = value2;
- }
- }
- return props;
- }
- function parseFromConfigs(configs, filepath, options) {
- return processMatches(configs.reverse().reduce(function (matches, file) {
- var pathPrefix = path$$2.dirname(file.name);
- file.contents.forEach(function (section) {
- var glob = section[0];
- var options2 = section[1];
- if (!glob) {
- return;
- }
- var fullGlob = buildFullGlob(pathPrefix, glob);
- if (!fnmatch$$1(filepath, fullGlob)) {
- return;
- }
- matches = extendProps(matches, options2);
- });
- return matches;
- }, {}), options.version);
- }
- function getConfigsForFiles(files) {
- var configs = [];
- for (var i in files) {
- if (files.hasOwnProperty(i)) {
- var file = files[i];
- var contents = ini.parseString(file.contents);
- configs.push({
- name: file.name,
- contents: contents
- });
- if ((contents[0][1].root || '').toLowerCase() === 'true') {
- break;
- }
- }
- }
- return configs;
- }
- function readConfigFiles(filepaths) {
- return __awaiter(this, void 0, void 0, function () {
- return __generator(this, function (_a) {
- return [2
- /*return*/
- , Promise.all(filepaths.map(function (name) {
- return new Promise(function (resolve) {
- fs$$2.readFile(name, 'utf8', function (err, data) {
- resolve({
- name: name,
- contents: err ? '' : data
- });
- });
- });
- }))];
- });
- });
- }
- function readConfigFilesSync(filepaths) {
- var files = [];
- var file;
- filepaths.forEach(function (filepath) {
- try {
- file = fs$$2.readFileSync(filepath, 'utf8');
- } catch (e) {
- file = '';
- }
- files.push({
- name: filepath,
- contents: file
- });
- });
- return files;
- }
- function opts(filepath, options) {
- if (options === void 0) {
- options = {};
- }
- var resolvedFilePath = path$$2.resolve(filepath);
- return [resolvedFilePath, processOptions(options, resolvedFilePath)];
- }
- function parseFromFiles(filepath, files, options) {
- if (options === void 0) {
- options = {};
- }
- return __awaiter(this, void 0, void 0, function () {
- var _a, resolvedFilePath, processedOptions;
- return __generator(this, function (_b) {
- _a = opts(filepath, options), resolvedFilePath = _a[0], processedOptions = _a[1];
- return [2
- /*return*/
- , files.then(getConfigsForFiles).then(function (configs) {
- return parseFromConfigs(configs, resolvedFilePath, processedOptions);
- })];
- });
- });
- }
- exports.parseFromFiles = parseFromFiles;
- function parseFromFilesSync(filepath, files, options) {
- if (options === void 0) {
- options = {};
- }
- var _a = opts(filepath, options),
- resolvedFilePath = _a[0],
- processedOptions = _a[1];
- return parseFromConfigs(getConfigsForFiles(files), resolvedFilePath, processedOptions);
- }
- exports.parseFromFilesSync = parseFromFilesSync;
- function parse(_filepath, _options) {
- if (_options === void 0) {
- _options = {};
- }
- return __awaiter(this, void 0, void 0, function () {
- var _a, resolvedFilePath, processedOptions, filepaths;
- return __generator(this, function (_b) {
- _a = opts(_filepath, _options), resolvedFilePath = _a[0], processedOptions = _a[1];
- filepaths = getConfigFileNames(resolvedFilePath, processedOptions);
- return [2
- /*return*/
- , readConfigFiles(filepaths).then(getConfigsForFiles).then(function (configs) {
- return parseFromConfigs(configs, resolvedFilePath, processedOptions);
- })];
- });
- });
- }
- exports.parse = parse;
- function parseSync(_filepath, _options) {
- if (_options === void 0) {
- _options = {};
- }
- var _a = opts(_filepath, _options),
- resolvedFilePath = _a[0],
- processedOptions = _a[1];
- var filepaths = getConfigFileNames(resolvedFilePath, processedOptions);
- var files = readConfigFilesSync(filepaths);
- return parseFromConfigs(getConfigsForFiles(files), resolvedFilePath, processedOptions);
- }
- exports.parseSync = parseSync;
- });
- unwrapExports(src$2);
- var editorconfigToPrettier = editorConfigToPrettier;
- function removeUnset(editorConfig) {
- var result = {};
- var keys = Object.keys(editorConfig);
- for (var i = 0; i < keys.length; i++) {
- var key = keys[i];
- if (editorConfig[key] === "unset") {
- continue;
- }
- result[key] = editorConfig[key];
- }
- return result;
- }
- function editorConfigToPrettier(editorConfig) {
- if (!editorConfig) {
- return null;
- }
- editorConfig = removeUnset(editorConfig);
- if (Object.keys(editorConfig).length === 0) {
- return null;
- }
- var result = {};
- if (editorConfig.indent_style) {
- result.useTabs = editorConfig.indent_style === "tab";
- }
- if (editorConfig.indent_size === "tab") {
- result.useTabs = true;
- }
- if (result.useTabs && editorConfig.tab_width) {
- result.tabWidth = editorConfig.tab_width;
- } else if (editorConfig.indent_style === "space" && editorConfig.indent_size && editorConfig.indent_size !== "tab") {
- result.tabWidth = editorConfig.indent_size;
- } else if (editorConfig.tab_width !== undefined) {
- result.tabWidth = editorConfig.tab_width;
- }
- if (editorConfig.max_line_length && editorConfig.max_line_length !== "off") {
- result.printWidth = editorConfig.max_line_length;
- }
- if (editorConfig.quote_type === "single") {
- result.singleQuote = true;
- } else if (editorConfig.quote_type === "double") {
- result.singleQuote = false;
- }
- if (["cr", "crlf", "lf"].indexOf(editorConfig.end_of_line) !== -1) {
- result.endOfLine = editorConfig.end_of_line;
- }
- return result;
- }
- function markerExists(files, markers) {
- return markers.some(function (marker) {
- return files.some(function (file) {
- return file === marker;
- });
- });
- }
- function traverseFolder(directory, levels, markers) {
- var files = fs.readdirSync(directory);
- if (levels === 0) {
- return null;
- } else if (markerExists(files, markers)) {
- return directory;
- } else {
- return traverseFolder(path.resolve(directory, '..'), levels - 1, markers);
- }
- }
- var findProjectRoot = function findRoot(dir, opts) {
- if (!dir) throw new Error("Directory not defined");
- opts = opts || {};
- var levels = opts.maxDepth || findRoot.MAX_DEPTH;
- var markers = opts.markers || findRoot.MARKERS;
- return traverseFolder(dir, levels, markers);
- };
- var MAX_DEPTH = 9;
- var MARKERS = ['.git', '.hg'];
- findProjectRoot.MAX_DEPTH = MAX_DEPTH;
- findProjectRoot.MARKERS = MARKERS;
- var resolveConfigEditorconfig = createCommonjsModule(function (module) {
- "use strict";
- var maybeParse = function maybeParse(filePath, config, parse) {
- var root = findProjectRoot(path.dirname(path.resolve(filePath)));
- return filePath && parse(filePath, {
- root
- });
- };
- var editorconfigAsyncNoCache = function editorconfigAsyncNoCache(filePath, config) {
- return Promise.resolve(maybeParse(filePath, config, src$2.parse)).then(editorconfigToPrettier);
- };
- var editorconfigAsyncWithCache = mem(editorconfigAsyncNoCache);
- var editorconfigSyncNoCache = function editorconfigSyncNoCache(filePath, config) {
- return editorconfigToPrettier(maybeParse(filePath, config, src$2.parseSync));
- };
- var editorconfigSyncWithCache = mem(editorconfigSyncNoCache);
- function getLoadFunction(opts) {
- if (!opts.editorconfig) {
- return function () {
- return null;
- };
- }
- if (opts.sync) {
- return opts.cache ? editorconfigSyncWithCache : editorconfigSyncNoCache;
- }
- return opts.cache ? editorconfigAsyncWithCache : editorconfigAsyncNoCache;
- }
- function clearCache() {
- mem.clear(editorconfigSyncWithCache);
- mem.clear(editorconfigAsyncWithCache);
- }
- module.exports = {
- getLoadFunction,
- clearCache
- };
- });
- var ParserEND = 0x110000;
- var ParserError =
- /*#__PURE__*/
- function (_Error) {
- _inherits(ParserError, _Error);
- /* istanbul ignore next */
- function ParserError(msg, filename, linenumber) {
- var _this;
- _classCallCheck(this, ParserError);
- _this = _possibleConstructorReturn(this, _getPrototypeOf(ParserError).call(this, '[ParserError] ' + msg, filename, linenumber));
- _this.code = 'ParserError';
- if (Error.captureStackTrace) Error.captureStackTrace(_assertThisInitialized(_assertThisInitialized(_this)), ParserError);
- return _this;
- }
- return ParserError;
- }(_wrapNativeSuper(Error));
- var State = function State(parser) {
- _classCallCheck(this, State);
- this.parser = parser;
- this.buf = '';
- this.returned = null;
- this.result = null;
- this.resultTable = null;
- this.resultArr = null;
- };
- var Parser =
- /*#__PURE__*/
- function () {
- function Parser() {
- _classCallCheck(this, Parser);
- this.pos = 0;
- this.col = 0;
- this.line = 0;
- this.obj = {};
- this.ctx = this.obj;
- this.stack = [];
- this._buf = '';
- this.char = null;
- this.ii = 0;
- this.state = new State(this.parseStart);
- }
- _createClass(Parser, [{
- key: "parse",
- value: function parse(str) {
- /* istanbul ignore next */
- if (str.length === 0 || str.length == null) return;
- this._buf = String(str);
- this.ii = -1;
- this.char = -1;
- var getNext;
- while (getNext === false || this.nextChar()) {
- getNext = this.runOne();
- }
- this._buf = null;
- }
- }, {
- key: "nextChar",
- value: function nextChar() {
- if (this.char === 0x0A) {
- ++this.line;
- this.col = -1;
- }
- ++this.ii;
- this.char = this._buf.codePointAt(this.ii);
- ++this.pos;
- ++this.col;
- return this.haveBuffer();
- }
- }, {
- key: "haveBuffer",
- value: function haveBuffer() {
- return this.ii < this._buf.length;
- }
- }, {
- key: "runOne",
- value: function runOne() {
- return this.state.parser.call(this, this.state.returned);
- }
- }, {
- key: "finish",
- value: function finish() {
- this.char = ParserEND;
- var last;
- do {
- last = this.state.parser;
- this.runOne();
- } while (this.state.parser !== last);
- this.ctx = null;
- this.state = null;
- this._buf = null;
- return this.obj;
- }
- }, {
- key: "next",
- value: function next(fn) {
- /* istanbul ignore next */
- if (typeof fn !== 'function') throw new ParserError('Tried to set state to non-existent state: ' + JSON.stringify(fn));
- this.state.parser = fn;
- }
- }, {
- key: "goto",
- value: function goto(fn) {
- this.next(fn);
- return this.runOne();
- }
- }, {
- key: "call",
- value: function call(fn, returnWith) {
- if (returnWith) this.next(returnWith);
- this.stack.push(this.state);
- this.state = new State(fn);
- }
- }, {
- key: "callNow",
- value: function callNow(fn, returnWith) {
- this.call(fn, returnWith);
- return this.runOne();
- }
- }, {
- key: "return",
- value: function _return(value) {
- /* istanbul ignore next */
- if (!this.stack.length) throw this.error(new ParserError('Stack underflow'));
- if (value === undefined) value = this.state.buf;
- this.state = this.stack.pop();
- this.state.returned = value;
- }
- }, {
- key: "returnNow",
- value: function returnNow(value) {
- this.return(value);
- return this.runOne();
- }
- }, {
- key: "consume",
- value: function consume() {
- /* istanbul ignore next */
- if (this.char === ParserEND) throw this.error(new ParserError('Unexpected end-of-buffer'));
- this.state.buf += this._buf[this.ii];
- }
- }, {
- key: "error",
- value: function error(err) {
- err.line = this.line;
- err.col = this.col;
- err.pos = this.pos;
- return err;
- }
- /* istanbul ignore next */
- }, {
- key: "parseStart",
- value: function parseStart() {
- throw new ParserError('Must declare a parseStart method');
- }
- }]);
- return Parser;
- }();
- Parser.END = ParserEND;
- Parser.Error = ParserError;
- var parser$2 = Parser;
- var createDatetime = createCommonjsModule(function (module) {
- 'use strict';
- module.exports = function (value) {
- var date = new Date(value);
- /* istanbul ignore if */
- if (isNaN(date)) {
- throw new TypeError('Invalid Datetime');
- } else {
- return date;
- }
- };
- });
- var formatNum = createCommonjsModule(function (module) {
- 'use strict';
- module.exports = function (d, num) {
- num = String(num);
- while (num.length < d) {
- num = '0' + num;
- }
- return num;
- };
- });
- var createDatetimeFloat = createCommonjsModule(function (module) {
- 'use strict';
- var FloatingDateTime =
- /*#__PURE__*/
- function (_Date) {
- _inherits(FloatingDateTime, _Date);
- function FloatingDateTime(value) {
- var _this;
- _classCallCheck(this, FloatingDateTime);
- _this = _possibleConstructorReturn(this, _getPrototypeOf(FloatingDateTime).call(this, value + 'Z'));
- _this.isFloating = true;
- return _this;
- }
- _createClass(FloatingDateTime, [{
- key: "toISOString",
- value: function toISOString() {
- var date = `${this.getUTCFullYear()}-${formatNum(2, this.getUTCMonth() + 1)}-${formatNum(2, this.getUTCDate())}`;
- var time = `${formatNum(2, this.getUTCHours())}:${formatNum(2, this.getUTCMinutes())}:${formatNum(2, this.getUTCSeconds())}.${formatNum(3, this.getUTCMilliseconds())}`;
- return `${date}T${time}`;
- }
- }]);
- return FloatingDateTime;
- }(_wrapNativeSuper(Date));
- module.exports = function (value) {
- var date = new FloatingDateTime(value);
- /* istanbul ignore if */
- if (isNaN(date)) {
- throw new TypeError('Invalid Datetime');
- } else {
- return date;
- }
- };
- });
- var createDate = createCommonjsModule(function (module) {
- 'use strict';
- var DateTime = commonjsGlobal.Date;
- var Date =
- /*#__PURE__*/
- function (_DateTime) {
- _inherits(Date, _DateTime);
- function Date(value) {
- var _this;
- _classCallCheck(this, Date);
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Date).call(this, value));
- _this.isDate = true;
- return _this;
- }
- _createClass(Date, [{
- key: "toISOString",
- value: function toISOString() {
- return `${this.getUTCFullYear()}-${formatNum(2, this.getUTCMonth() + 1)}-${formatNum(2, this.getUTCDate())}`;
- }
- }]);
- return Date;
- }(DateTime);
- module.exports = function (value) {
- var date = new Date(value);
- /* istanbul ignore if */
- if (isNaN(date)) {
- throw new TypeError('Invalid Datetime');
- } else {
- return date;
- }
- };
- });
- var createTime = createCommonjsModule(function (module) {
- 'use strict';
- var Time =
- /*#__PURE__*/
- function (_Date) {
- _inherits(Time, _Date);
- function Time(value) {
- var _this;
- _classCallCheck(this, Time);
- _this = _possibleConstructorReturn(this, _getPrototypeOf(Time).call(this, `0000-01-01T${value}Z`));
- _this.isTime = true;
- return _this;
- }
- _createClass(Time, [{
- key: "toISOString",
- value: function toISOString() {
- return `${formatNum(2, this.getUTCHours())}:${formatNum(2, this.getUTCMinutes())}:${formatNum(2, this.getUTCSeconds())}.${formatNum(3, this.getUTCMilliseconds())}`;
- }
- }]);
- return Time;
- }(_wrapNativeSuper(Date));
- module.exports = function (value) {
- var date = new Time(value);
- /* istanbul ignore if */
- if (isNaN(date)) {
- throw new TypeError('Invalid Datetime');
- } else {
- return date;
- }
- };
- });
- var tomlParser = createCommonjsModule(function (module) {
- 'use strict';
- /* eslint-disable no-new-wrappers, no-eval, camelcase, operator-linebreak */
- module.exports = makeParserClass(parser$2);
- module.exports.makeParserClass = makeParserClass;
- var TomlError =
- /*#__PURE__*/
- function (_Error) {
- _inherits(TomlError, _Error);
- function TomlError(msg) {
- var _this;
- _classCallCheck(this, TomlError);
- _this = _possibleConstructorReturn(this, _getPrototypeOf(TomlError).call(this, msg));
- /* istanbul ignore next */
- if (Error.captureStackTrace) Error.captureStackTrace(_assertThisInitialized(_assertThisInitialized(_this)), TomlError);
- _this.fromTOML = true;
- _this.wrapped = null;
- return _this;
- }
- return TomlError;
- }(_wrapNativeSuper(Error));
- TomlError.wrap = function (err) {
- var terr = new TomlError(err.message);
- terr.code = err.code;
- terr.wrapped = err;
- return terr;
- };
- module.exports.TomlError = TomlError;
- var CTRL_I = 0x09;
- var CTRL_J = 0x0A;
- var CTRL_M = 0x0D;
- var CTRL_CHAR_BOUNDARY = 0x1F; // the last non-character in the latin1 region of unicode, except DEL
- var CHAR_SP = 0x20;
- var CHAR_QUOT = 0x22;
- var CHAR_NUM = 0x23;
- var CHAR_APOS = 0x27;
- var CHAR_PLUS = 0x2B;
- var CHAR_COMMA = 0x2C;
- var CHAR_HYPHEN = 0x2D;
- var CHAR_PERIOD = 0x2E;
- var CHAR_0 = 0x30;
- var CHAR_1 = 0x31;
- var CHAR_7 = 0x37;
- var CHAR_9 = 0x39;
- var CHAR_COLON = 0x3A;
- var CHAR_EQUALS = 0x3D;
- var CHAR_A = 0x41;
- var CHAR_E = 0x45;
- var CHAR_F = 0x46;
- var CHAR_T = 0x54;
- var CHAR_U = 0x55;
- var CHAR_Z = 0x5A;
- var CHAR_LOWBAR = 0x5F;
- var CHAR_a = 0x61;
- var CHAR_b = 0x62;
- var CHAR_e = 0x65;
- var CHAR_f = 0x66;
- var CHAR_i = 0x69;
- var CHAR_l = 0x6C;
- var CHAR_n = 0x6E;
- var CHAR_o = 0x6F;
- var CHAR_r = 0x72;
- var CHAR_s = 0x73;
- var CHAR_t = 0x74;
- var CHAR_u = 0x75;
- var CHAR_x = 0x78;
- var CHAR_z = 0x7A;
- var CHAR_LCUB = 0x7B;
- var CHAR_RCUB = 0x7D;
- var CHAR_LSQB = 0x5B;
- var CHAR_BSOL = 0x5C;
- var CHAR_RSQB = 0x5D;
- var CHAR_DEL = 0x7F;
- var SURROGATE_FIRST = 0xD800;
- var SURROGATE_LAST = 0xDFFF;
- var escapes = {
- [CHAR_b]: '\x08',
- [CHAR_t]: '\x09',
- [CHAR_n]: '\x0a',
- [CHAR_f]: '\x0c',
- [CHAR_r]: '\x0d',
- [CHAR_QUOT]: '\x22',
- [CHAR_BSOL]: '\x5c'
- };
- function isDigit(cp) {
- return cp >= CHAR_0 && cp <= CHAR_9;
- }
- function isHexit(cp) {
- return cp >= CHAR_A && cp <= CHAR_F || cp >= CHAR_a && cp <= CHAR_f || cp >= CHAR_0 && cp <= CHAR_9;
- }
- function isBit(cp) {
- return cp === CHAR_1 || cp === CHAR_0;
- }
- function isOctit(cp) {
- return cp >= CHAR_0 && cp <= CHAR_7;
- }
- function isAlphaNumQuoteHyphen(cp) {
- return cp >= CHAR_A && cp <= CHAR_Z || cp >= CHAR_a && cp <= CHAR_z || cp >= CHAR_0 && cp <= CHAR_9 || cp === CHAR_APOS || cp === CHAR_QUOT || cp === CHAR_LOWBAR || cp === CHAR_HYPHEN;
- }
- function isAlphaNumHyphen(cp) {
- return cp >= CHAR_A && cp <= CHAR_Z || cp >= CHAR_a && cp <= CHAR_z || cp >= CHAR_0 && cp <= CHAR_9 || cp === CHAR_LOWBAR || cp === CHAR_HYPHEN;
- }
- var _type = Symbol('type');
- var _declared = Symbol('declared');
- var INLINE_TABLE = Symbol('inline-table');
- function InlineTable() {
- return Object.defineProperties({}, {
- [_type]: {
- value: INLINE_TABLE
- }
- });
- }
- function isInlineTable(obj) {
- if (obj === null || typeof obj !== 'object') return false;
- return obj[_type] === INLINE_TABLE;
- }
- var TABLE = Symbol('table');
- function Table() {
- return Object.defineProperties({}, {
- [_type]: {
- value: TABLE
- },
- [_declared]: {
- value: false,
- writable: true
- }
- });
- }
- function isTable(obj) {
- if (obj === null || typeof obj !== 'object') return false;
- return obj[_type] === TABLE;
- }
- var _contentType = Symbol('content-type');
- var INLINE_LIST = Symbol('inline-list');
- function InlineList(type) {
- return Object.defineProperties([], {
- [_type]: {
- value: INLINE_LIST
- },
- [_contentType]: {
- value: type
- }
- });
- }
- function isInlineList(obj) {
- if (obj === null || typeof obj !== 'object') return false;
- return obj[_type] === INLINE_LIST;
- }
- var LIST = Symbol('list');
- function List() {
- return Object.defineProperties([], {
- [_type]: {
- value: LIST
- }
- });
- }
- function isList(obj) {
- if (obj === null || typeof obj !== 'object') return false;
- return obj[_type] === LIST;
- } // in an eval, to let bundlers not slurp in a util proxy
- var utilInspect = eval(`require('util').inspect`);
- /* istanbul ignore next */
- var _inspect = utilInspect && utilInspect.custom || 'inspect';
- var BoxedBigInt =
- /*#__PURE__*/
- function () {
- function BoxedBigInt(value) {
- _classCallCheck(this, BoxedBigInt);
- try {
- this.value = commonjsGlobal.BigInt(value);
- } catch (_) {
- /* istanbul ignore next */
- this.value = null;
- }
- Object.defineProperty(this, _type, {
- value: INTEGER
- });
- }
- _createClass(BoxedBigInt, [{
- key: "isNaN",
- value: function isNaN() {
- return this.value === null;
- }
- /* istanbul ignore next */
- }, {
- key: "toString",
- value: function toString() {
- return String(this.value);
- }
- /* istanbul ignore next */
- }, {
- key: _inspect,
- value: function value() {
- return `[BigInt: ${this.toString()}]}`;
- }
- }, {
- key: "valueOf",
- value: function valueOf() {
- return this.value;
- }
- }]);
- return BoxedBigInt;
- }();
- var INTEGER = Symbol('integer');
- function Integer(_value) {
- var num = Number(_value); // -0 is a float thing, not an int thing
- if (Object.is(num, -0)) num = 0;
- /* istanbul ignore else */
- if (commonjsGlobal.BigInt && !Number.isSafeInteger(num)) {
- return new BoxedBigInt(_value);
- } else {
- /* istanbul ignore next */
- return Object.defineProperties(new Number(num), {
- isNaN: {
- value: function value() {
- return isNaN(this);
- }
- },
- [_type]: {
- value: INTEGER
- },
- [_inspect]: {
- value: function value() {
- return `[Integer: ${_value}]`;
- }
- }
- });
- }
- }
- function isInteger(obj) {
- if (obj === null || typeof obj !== 'object') return false;
- return obj[_type] === INTEGER;
- }
- var FLOAT = Symbol('float');
- function Float(_value2) {
- /* istanbul ignore next */
- return Object.defineProperties(new Number(_value2), {
- [_type]: {
- value: FLOAT
- },
- [_inspect]: {
- value: function value() {
- return `[Float: ${_value2}]`;
- }
- }
- });
- }
- function isFloat(obj) {
- if (obj === null || typeof obj !== 'object') return false;
- return obj[_type] === FLOAT;
- }
- function tomlType(value) {
- var type = typeof value;
- if (type === 'object') {
- /* istanbul ignore if */
- if (value === null) return 'null';
- if (value instanceof Date) return 'datetime';
- /* istanbul ignore else */
- if (_type in value) {
- switch (value[_type]) {
- case INLINE_TABLE:
- return 'inline-table';
- case INLINE_LIST:
- return 'inline-list';
- /* istanbul ignore next */
- case TABLE:
- return 'table';
- /* istanbul ignore next */
- case LIST:
- return 'list';
- case FLOAT:
- return 'float';
- case INTEGER:
- return 'integer';
- }
- }
- }
- return type;
- }
- function makeParserClass(Parser) {
- var TOMLParser =
- /*#__PURE__*/
- function (_Parser) {
- _inherits(TOMLParser, _Parser);
- function TOMLParser() {
- var _this2;
- _classCallCheck(this, TOMLParser);
- _this2 = _possibleConstructorReturn(this, _getPrototypeOf(TOMLParser).call(this));
- _this2.ctx = _this2.obj = Table();
- return _this2;
- }
- /* MATCH HELPER */
- _createClass(TOMLParser, [{
- key: "atEndOfWord",
- value: function atEndOfWord() {
- return this.char === CHAR_NUM || this.char === CTRL_I || this.char === CHAR_SP || this.atEndOfLine();
- }
- }, {
- key: "atEndOfLine",
- value: function atEndOfLine() {
- return this.char === Parser.END || this.char === CTRL_J || this.char === CTRL_M;
- }
- }, {
- key: "parseStart",
- value: function parseStart() {
- if (this.char === Parser.END) {
- return null;
- } else if (this.char === CHAR_LSQB) {
- return this.call(this.parseTableOrList);
- } else if (this.char === CHAR_NUM) {
- return this.call(this.parseComment);
- } else if (this.char === CTRL_J || this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) {
- return null;
- } else if (isAlphaNumQuoteHyphen(this.char)) {
- return this.callNow(this.parseAssignStatement);
- } else {
- throw this.error(new TomlError(`Unknown character "${this.char}"`));
- }
- } // HELPER, this strips any whitespace and comments to the end of the line
- // then RETURNS. Last state in a production.
- }, {
- key: "parseWhitespaceToEOL",
- value: function parseWhitespaceToEOL() {
- if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) {
- return null;
- } else if (this.char === CHAR_NUM) {
- return this.goto(this.parseComment);
- } else if (this.char === Parser.END || this.char === CTRL_J) {
- return this.return();
- } else {
- throw this.error(new TomlError('Unexpected character, expected only whitespace or comments till end of line'));
- }
- }
- /* ASSIGNMENT: key = value */
- }, {
- key: "parseAssignStatement",
- value: function parseAssignStatement() {
- return this.callNow(this.parseAssign, this.recordAssignStatement);
- }
- }, {
- key: "recordAssignStatement",
- value: function recordAssignStatement(kv) {
- var target = this.ctx;
- var finalKey = kv.key.pop();
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = kv.key[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var kw = _step.value;
- if (kw in target && (!isTable(target[kw]) || target[kw][_declared])) {
- throw this.error(new TomlError("Can't redefine existing key"));
- }
- target = target[kw] = target[kw] || Table();
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- if (finalKey in target) {
- throw this.error(new TomlError("Can't redefine existing key"));
- } // unbox our numbers
- if (isInteger(kv.value) || isFloat(kv.value)) {
- target[finalKey] = kv.value.valueOf();
- } else {
- target[finalKey] = kv.value;
- }
- return this.goto(this.parseWhitespaceToEOL);
- }
- /* ASSSIGNMENT expression, key = value possibly inside an inline table */
- }, {
- key: "parseAssign",
- value: function parseAssign() {
- return this.callNow(this.parseKeyword, this.recordAssignKeyword);
- }
- }, {
- key: "recordAssignKeyword",
- value: function recordAssignKeyword(key) {
- if (this.state.resultTable) {
- this.state.resultTable.push(key);
- } else {
- this.state.resultTable = [key];
- }
- return this.goto(this.parseAssignKeywordPreDot);
- }
- }, {
- key: "parseAssignKeywordPreDot",
- value: function parseAssignKeywordPreDot() {
- if (this.char === CHAR_PERIOD) {
- return this.next(this.parseAssignKeywordPostDot);
- } else if (this.char !== CHAR_SP && this.char !== CTRL_I) {
- return this.goto(this.parseAssignEqual);
- }
- }
- }, {
- key: "parseAssignKeywordPostDot",
- value: function parseAssignKeywordPostDot() {
- if (this.char !== CHAR_SP && this.char !== CTRL_I) {
- return this.callNow(this.parseKeyword, this.recordAssignKeyword);
- }
- }
- }, {
- key: "parseAssignEqual",
- value: function parseAssignEqual() {
- if (this.char === CHAR_EQUALS) {
- return this.next(this.parseAssignPreValue);
- } else {
- throw this.error(new TomlError('Invalid character, expected "="'));
- }
- }
- }, {
- key: "parseAssignPreValue",
- value: function parseAssignPreValue() {
- if (this.char === CHAR_SP || this.char === CTRL_I) {
- return null;
- } else {
- return this.callNow(this.parseValue, this.recordAssignValue);
- }
- }
- }, {
- key: "recordAssignValue",
- value: function recordAssignValue(value) {
- return this.returnNow({
- key: this.state.resultTable,
- value: value
- });
- }
- /* COMMENTS: #...eol */
- }, {
- key: "parseComment",
- value: function parseComment() {
- do {
- if (this.char === Parser.END || this.char === CTRL_J) {
- return this.return();
- }
- } while (this.nextChar());
- }
- /* TABLES AND LISTS, [foo] and [[foo]] */
- }, {
- key: "parseTableOrList",
- value: function parseTableOrList() {
- if (this.char === CHAR_LSQB) {
- this.next(this.parseList);
- } else {
- return this.goto(this.parseTable);
- }
- }
- /* TABLE [foo.bar.baz] */
- }, {
- key: "parseTable",
- value: function parseTable() {
- this.ctx = this.obj;
- return this.goto(this.parseTableNext);
- }
- }, {
- key: "parseTableNext",
- value: function parseTableNext() {
- if (this.char === CHAR_SP || this.char === CTRL_I) {
- return null;
- } else {
- return this.callNow(this.parseKeyword, this.parseTableMore);
- }
- }
- }, {
- key: "parseTableMore",
- value: function parseTableMore(keyword) {
- if (this.char === CHAR_SP || this.char === CTRL_I) {
- return null;
- } else if (this.char === CHAR_RSQB) {
- if (keyword in this.ctx && (!isTable(this.ctx[keyword]) || this.ctx[keyword][_declared])) {
- throw this.error(new TomlError("Can't redefine existing key"));
- } else {
- this.ctx = this.ctx[keyword] = this.ctx[keyword] || Table();
- this.ctx[_declared] = true;
- }
- return this.next(this.parseWhitespaceToEOL);
- } else if (this.char === CHAR_PERIOD) {
- if (!(keyword in this.ctx)) {
- this.ctx = this.ctx[keyword] = Table();
- } else if (isTable(this.ctx[keyword])) {
- this.ctx = this.ctx[keyword];
- } else if (isList(this.ctx[keyword])) {
- this.ctx = this.ctx[keyword][this.ctx[keyword].length - 1];
- } else {
- throw this.error(new TomlError("Can't redefine existing key"));
- }
- return this.next(this.parseTableNext);
- } else {
- throw this.error(new TomlError('Unexpected character, expected whitespace, . or ]'));
- }
- }
- /* LIST [[a.b.c]] */
- }, {
- key: "parseList",
- value: function parseList() {
- this.ctx = this.obj;
- return this.goto(this.parseListNext);
- }
- }, {
- key: "parseListNext",
- value: function parseListNext() {
- if (this.char === CHAR_SP || this.char === CTRL_I) {
- return null;
- } else {
- return this.callNow(this.parseKeyword, this.parseListMore);
- }
- }
- }, {
- key: "parseListMore",
- value: function parseListMore(keyword) {
- if (this.char === CHAR_SP || this.char === CTRL_I) {
- return null;
- } else if (this.char === CHAR_RSQB) {
- if (!(keyword in this.ctx)) {
- this.ctx[keyword] = List();
- }
- if (isInlineList(this.ctx[keyword])) {
- throw this.error(new TomlError("Can't extend an inline array"));
- } else if (isList(this.ctx[keyword])) {
- var next = Table();
- this.ctx[keyword].push(next);
- this.ctx = next;
- } else {
- throw this.error(new TomlError("Can't redefine an existing key"));
- }
- return this.next(this.parseListEnd);
- } else if (this.char === CHAR_PERIOD) {
- if (!(keyword in this.ctx)) {
- this.ctx = this.ctx[keyword] = Table();
- } else if (isInlineList(this.ctx[keyword])) {
- throw this.error(new TomlError("Can't extend an inline array"));
- } else if (isInlineTable(this.ctx[keyword])) {
- throw this.error(new TomlError("Can't extend an inline table"));
- } else if (isList(this.ctx[keyword])) {
- this.ctx = this.ctx[keyword][this.ctx[keyword].length - 1];
- } else if (isTable(this.ctx[keyword])) {
- this.ctx = this.ctx[keyword];
- } else {
- throw this.error(new TomlError("Can't redefine an existing key"));
- }
- return this.next(this.parseListNext);
- } else {
- throw this.error(new TomlError('Unexpected character, expected whitespace, . or ]'));
- }
- }
- }, {
- key: "parseListEnd",
- value: function parseListEnd(keyword) {
- if (this.char === CHAR_RSQB) {
- return this.next(this.parseWhitespaceToEOL);
- } else {
- throw this.error(new TomlError('Unexpected character, expected whitespace, . or ]'));
- }
- }
- /* VALUE string, number, boolean, inline list, inline object */
- }, {
- key: "parseValue",
- value: function parseValue() {
- if (this.char === Parser.END) {
- throw this.error(new TomlError('Key without value'));
- } else if (this.char === CHAR_QUOT) {
- return this.next(this.parseDoubleString);
- }
- if (this.char === CHAR_APOS) {
- return this.next(this.parseSingleString);
- } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {
- return this.goto(this.parseNumberSign);
- } else if (this.char === CHAR_i) {
- return this.next(this.parseInf);
- } else if (this.char === CHAR_n) {
- return this.next(this.parseNan);
- } else if (isDigit(this.char)) {
- return this.goto(this.parseNumberOrDateTime);
- } else if (this.char === CHAR_t || this.char === CHAR_f) {
- return this.goto(this.parseBoolean);
- } else if (this.char === CHAR_LSQB) {
- return this.call(this.parseInlineList, this.recordValue);
- } else if (this.char === CHAR_LCUB) {
- return this.call(this.parseInlineTable, this.recordValue);
- } else {
- throw this.error(new TomlError('Unexpected character, expecting string, number, datetime, boolean, inline array or inline table'));
- }
- }
- }, {
- key: "recordValue",
- value: function recordValue(value) {
- return this.returnNow(value);
- }
- }, {
- key: "parseInf",
- value: function parseInf() {
- if (this.char === CHAR_n) {
- return this.next(this.parseInf2);
- } else {
- throw this.error(new TomlError('Unexpected character, expected "inf", "+inf" or "-inf"'));
- }
- }
- }, {
- key: "parseInf2",
- value: function parseInf2() {
- if (this.char === CHAR_f) {
- if (this.state.buf === '-') {
- return this.return(-Infinity);
- } else {
- return this.return(Infinity);
- }
- } else {
- throw this.error(new TomlError('Unexpected character, expected "inf", "+inf" or "-inf"'));
- }
- }
- }, {
- key: "parseNan",
- value: function parseNan() {
- if (this.char === CHAR_a) {
- return this.next(this.parseNan2);
- } else {
- throw this.error(new TomlError('Unexpected character, expected "nan"'));
- }
- }
- }, {
- key: "parseNan2",
- value: function parseNan2() {
- if (this.char === CHAR_n) {
- return this.return(NaN);
- } else {
- throw this.error(new TomlError('Unexpected character, expected "nan"'));
- }
- }
- /* KEYS, barewords or basic, literal, or dotted */
- }, {
- key: "parseKeyword",
- value: function parseKeyword() {
- if (this.char === CHAR_QUOT) {
- return this.next(this.parseBasicString);
- } else if (this.char === CHAR_APOS) {
- return this.next(this.parseLiteralString);
- } else {
- return this.goto(this.parseBareKey);
- }
- }
- /* KEYS: barewords */
- }, {
- key: "parseBareKey",
- value: function parseBareKey() {
- do {
- if (this.char === Parser.END) {
- throw this.error(new TomlError('Key ended without value'));
- } else if (isAlphaNumHyphen(this.char)) {
- this.consume();
- } else if (this.state.buf.length === 0) {
- throw this.error(new TomlError('Empty bare keys are not allowed'));
- } else {
- return this.returnNow();
- }
- } while (this.nextChar());
- }
- /* STRINGS, single quoted (literal) */
- }, {
- key: "parseSingleString",
- value: function parseSingleString() {
- if (this.char === CHAR_APOS) {
- return this.next(this.parseLiteralMultiStringMaybe);
- } else {
- return this.goto(this.parseLiteralString);
- }
- }
- }, {
- key: "parseLiteralString",
- value: function parseLiteralString() {
- do {
- if (this.char === CHAR_APOS) {
- return this.return();
- } else if (this.atEndOfLine()) {
- throw this.error(new TomlError('Unterminated string'));
- } else if (this.char === CHAR_DEL || this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I) {
- throw this.errorControlCharInString();
- } else {
- this.consume();
- }
- } while (this.nextChar());
- }
- }, {
- key: "parseLiteralMultiStringMaybe",
- value: function parseLiteralMultiStringMaybe() {
- if (this.char === CHAR_APOS) {
- return this.next(this.parseLiteralMultiString);
- } else {
- return this.returnNow();
- }
- }
- }, {
- key: "parseLiteralMultiString",
- value: function parseLiteralMultiString() {
- if (this.char === CTRL_M) {
- return null;
- } else if (this.char === CTRL_J) {
- return this.next(this.parseLiteralMultiStringContent);
- } else {
- return this.goto(this.parseLiteralMultiStringContent);
- }
- }
- }, {
- key: "parseLiteralMultiStringContent",
- value: function parseLiteralMultiStringContent() {
- do {
- if (this.char === CHAR_APOS) {
- return this.next(this.parseLiteralMultiEnd);
- } else if (this.char === Parser.END) {
- throw this.error(new TomlError('Unterminated multi-line string'));
- } else if (this.char === CHAR_DEL || this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I && this.char !== CTRL_J && this.char !== CTRL_M) {
- throw this.errorControlCharInString();
- } else {
- this.consume();
- }
- } while (this.nextChar());
- }
- }, {
- key: "parseLiteralMultiEnd",
- value: function parseLiteralMultiEnd() {
- if (this.char === CHAR_APOS) {
- return this.next(this.parseLiteralMultiEnd2);
- } else {
- this.state.buf += "'";
- return this.goto(this.parseLiteralMultiStringContent);
- }
- }
- }, {
- key: "parseLiteralMultiEnd2",
- value: function parseLiteralMultiEnd2() {
- if (this.char === CHAR_APOS) {
- return this.return();
- } else {
- this.state.buf += "''";
- return this.goto(this.parseLiteralMultiStringContent);
- }
- }
- /* STRINGS double quoted */
- }, {
- key: "parseDoubleString",
- value: function parseDoubleString() {
- if (this.char === CHAR_QUOT) {
- return this.next(this.parseMultiStringMaybe);
- } else {
- return this.goto(this.parseBasicString);
- }
- }
- }, {
- key: "parseBasicString",
- value: function parseBasicString() {
- do {
- if (this.char === CHAR_BSOL) {
- return this.call(this.parseEscape, this.recordEscapeReplacement);
- } else if (this.char === CHAR_QUOT) {
- return this.return();
- } else if (this.atEndOfLine()) {
- throw this.error(new TomlError('Unterminated string'));
- } else if (this.char === CHAR_DEL || this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I) {
- throw this.errorControlCharInString();
- } else {
- this.consume();
- }
- } while (this.nextChar());
- }
- }, {
- key: "recordEscapeReplacement",
- value: function recordEscapeReplacement(replacement) {
- this.state.buf += replacement;
- return this.goto(this.parseBasicString);
- }
- }, {
- key: "parseMultiStringMaybe",
- value: function parseMultiStringMaybe() {
- if (this.char === CHAR_QUOT) {
- return this.next(this.parseMultiString);
- } else {
- return this.returnNow();
- }
- }
- }, {
- key: "parseMultiString",
- value: function parseMultiString() {
- if (this.char === CTRL_M) {
- return null;
- } else if (this.char === CTRL_J) {
- return this.next(this.parseMultiStringContent);
- } else {
- return this.goto(this.parseMultiStringContent);
- }
- }
- }, {
- key: "parseMultiStringContent",
- value: function parseMultiStringContent() {
- do {
- if (this.char === CHAR_BSOL) {
- return this.call(this.parseMultiEscape, this.recordMultiEscapeReplacement);
- } else if (this.char === CHAR_QUOT) {
- return this.next(this.parseMultiEnd);
- } else if (this.char === Parser.END) {
- throw this.error(new TomlError('Unterminated multi-line string'));
- } else if (this.char === CHAR_DEL || this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I && this.char !== CTRL_J && this.char !== CTRL_M) {
- throw this.errorControlCharInString();
- } else {
- this.consume();
- }
- } while (this.nextChar());
- }
- }, {
- key: "errorControlCharInString",
- value: function errorControlCharInString() {
- var displayCode = '\\u00';
- if (this.char < 16) {
- displayCode += '0';
- }
- displayCode += this.char.toString(16);
- return this.error(new TomlError(`Control characters (codes < 0x1f and 0x7f) are not allowed in strings, use ${displayCode} instead`));
- }
- }, {
- key: "recordMultiEscapeReplacement",
- value: function recordMultiEscapeReplacement(replacement) {
- this.state.buf += replacement;
- return this.goto(this.parseMultiStringContent);
- }
- }, {
- key: "parseMultiEnd",
- value: function parseMultiEnd() {
- if (this.char === CHAR_QUOT) {
- return this.next(this.parseMultiEnd2);
- } else {
- this.state.buf += '"';
- return this.goto(this.parseMultiStringContent);
- }
- }
- }, {
- key: "parseMultiEnd2",
- value: function parseMultiEnd2() {
- if (this.char === CHAR_QUOT) {
- return this.return();
- } else {
- this.state.buf += '""';
- return this.goto(this.parseMultiStringContent);
- }
- }
- }, {
- key: "parseMultiEscape",
- value: function parseMultiEscape() {
- if (this.char === CTRL_M || this.char === CTRL_J) {
- return this.next(this.parseMultiTrim);
- } else if (this.char === CHAR_SP || this.char === CTRL_I) {
- return this.next(this.parsePreMultiTrim);
- } else {
- return this.goto(this.parseEscape);
- }
- }
- }, {
- key: "parsePreMultiTrim",
- value: function parsePreMultiTrim() {
- if (this.char === CHAR_SP || this.char === CTRL_I) {
- return null;
- } else if (this.char === CTRL_M || this.char === CTRL_J) {
- return this.next(this.parseMultiTrim);
- } else {
- throw this.error(new TomlError("Can't escape whitespace"));
- }
- }
- }, {
- key: "parseMultiTrim",
- value: function parseMultiTrim() {
- // explicitly whitespace here, END should follow the same path as chars
- if (this.char === CTRL_J || this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) {
- return null;
- } else {
- return this.returnNow();
- }
- }
- }, {
- key: "parseEscape",
- value: function parseEscape() {
- if (this.char in escapes) {
- return this.return(escapes[this.char]);
- } else if (this.char === CHAR_u) {
- return this.call(this.parseSmallUnicode, this.parseUnicodeReturn);
- } else if (this.char === CHAR_U) {
- return this.call(this.parseLargeUnicode, this.parseUnicodeReturn);
- } else {
- throw this.error(new TomlError('Unknown escape character: ' + this.char));
- }
- }
- }, {
- key: "parseUnicodeReturn",
- value: function parseUnicodeReturn(char) {
- try {
- var codePoint = parseInt(char, 16);
- if (codePoint >= SURROGATE_FIRST && codePoint <= SURROGATE_LAST) {
- throw this.error(new TomlError('Invalid unicode, character in range 0xD800 - 0xDFFF is reserved'));
- }
- return this.returnNow(String.fromCodePoint(codePoint));
- } catch (ex) {
- throw this.error(TomlError.wrap(ex));
- }
- }
- }, {
- key: "parseSmallUnicode",
- value: function parseSmallUnicode() {
- if (!isHexit(this.char)) {
- throw this.error(new TomlError('Invalid character in unicode sequence, expected hex'));
- } else {
- this.consume();
- if (this.state.buf.length >= 4) return this.return();
- }
- }
- }, {
- key: "parseLargeUnicode",
- value: function parseLargeUnicode() {
- if (!isHexit(this.char)) {
- throw this.error(new TomlError('Invalid character in unicode sequence, expected hex'));
- } else {
- this.consume();
- if (this.state.buf.length >= 8) return this.return();
- }
- }
- /* NUMBERS */
- }, {
- key: "parseNumberSign",
- value: function parseNumberSign() {
- this.consume();
- return this.next(this.parseMaybeSignedInfOrNan);
- }
- }, {
- key: "parseMaybeSignedInfOrNan",
- value: function parseMaybeSignedInfOrNan() {
- if (this.char === CHAR_i) {
- return this.next(this.parseInf);
- } else if (this.char === CHAR_n) {
- return this.next(this.parseNan);
- } else {
- return this.callNow(this.parseNoUnder, this.parseNumberInteger);
- }
- }
- }, {
- key: "parseNumberInteger",
- value: function parseNumberInteger() {
- if (isDigit(this.char)) {
- this.consume();
- } else if (this.char === CHAR_LOWBAR) {
- return this.call(this.parseNoUnder);
- } else if (this.char === CHAR_E || this.char === CHAR_e) {
- this.consume();
- return this.next(this.parseNumberExponentSign);
- } else if (this.char === CHAR_PERIOD) {
- this.consume();
- return this.call(this.parseNoUnder, this.parseNumberFloat);
- } else {
- var result = Integer(this.state.buf);
- /* istanbul ignore if */
- if (result.isNaN()) {
- throw this.error(new TomlError('Invalid number'));
- } else {
- return this.returnNow(result);
- }
- }
- }
- }, {
- key: "parseNoUnder",
- value: function parseNoUnder() {
- if (this.char === CHAR_LOWBAR) {
- throw this.error(new TomlError('Unexpected character, expected digit, exponent marker(e) or whitespace'));
- } else if (this.atEndOfWord() || this.char === CHAR_E || this.char === CHAR_e) {
- throw this.error(new TomlError('Incomplete number'));
- }
- return this.returnNow();
- }
- }, {
- key: "parseNumberFloat",
- value: function parseNumberFloat() {
- if (this.char === CHAR_LOWBAR) {
- return this.call(this.parseNoUnder, this.parseNumberFloat);
- } else if (isDigit(this.char)) {
- this.consume();
- } else if (this.char === CHAR_E || this.char === CHAR_e) {
- this.consume();
- return this.next(this.parseNumberExponentSign);
- } else {
- return this.returnNow(Float(this.state.buf));
- }
- }
- }, {
- key: "parseNumberExponentSign",
- value: function parseNumberExponentSign() {
- if (isDigit(this.char)) {
- return this.goto(this.parseNumberExponent);
- } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {
- this.consume();
- this.call(this.parseNoUnder, this.parseNumberExponent);
- } else {
- throw this.error(new TomlError('Unexpected character, expected -, + or digit'));
- }
- }
- }, {
- key: "parseNumberExponent",
- value: function parseNumberExponent() {
- if (isDigit(this.char)) {
- this.consume();
- } else if (this.char === CHAR_LOWBAR) {
- return this.call(this.parseNoUnder);
- } else {
- return this.returnNow(Float(this.state.buf));
- }
- }
- /* NUMBERS or DATETIMES */
- }, {
- key: "parseNumberOrDateTime",
- value: function parseNumberOrDateTime() {
- if (this.char === CHAR_0) {
- this.consume();
- return this.next(this.parseNumberBaseOrDateTime);
- } else {
- return this.goto(this.parseNumberOrDateTimeOnly);
- }
- }
- }, {
- key: "parseNumberOrDateTimeOnly",
- value: function parseNumberOrDateTimeOnly() {
- // note, if two zeros are in a row then it MUST be a date
- if (this.char === CHAR_LOWBAR) {
- return this.call(this.parseNoUnder, this.parseNumberInteger);
- } else if (isDigit(this.char)) {
- this.consume();
- if (this.state.buf.length > 4) this.next(this.parseNumberInteger);
- } else if (this.char === CHAR_E || this.char === CHAR_e) {
- this.consume();
- return this.next(this.parseNumberExponentSign);
- } else if (this.char === CHAR_PERIOD) {
- this.consume();
- return this.call(this.parseNoUnder, this.parseNumberFloat);
- } else if (this.char === CHAR_HYPHEN) {
- return this.goto(this.parseDateTime);
- } else if (this.char === CHAR_COLON) {
- return this.goto(this.parseOnlyTimeHour);
- } else {
- return this.returnNow(Integer(this.state.buf));
- }
- }
- }, {
- key: "parseDateTimeOnly",
- value: function parseDateTimeOnly() {
- if (this.state.buf.length < 4) {
- if (isDigit(this.char)) {
- return this.consume();
- } else if (this.char === CHAR_COLON) {
- return this.goto(this.parseOnlyTimeHour);
- } else {
- throw this.error(new TomlError('Expected digit while parsing year part of a date'));
- }
- } else {
- if (this.char === CHAR_HYPHEN) {
- return this.goto(this.parseDateTime);
- } else {
- throw this.error(new TomlError('Expected hyphen (-) while parsing year part of date'));
- }
- }
- }
- }, {
- key: "parseNumberBaseOrDateTime",
- value: function parseNumberBaseOrDateTime() {
- if (this.char === CHAR_b) {
- this.consume();
- return this.call(this.parseNoUnder, this.parseIntegerBin);
- } else if (this.char === CHAR_o) {
- this.consume();
- return this.call(this.parseNoUnder, this.parseIntegerOct);
- } else if (this.char === CHAR_x) {
- this.consume();
- return this.call(this.parseNoUnder, this.parseIntegerHex);
- } else if (this.char === CHAR_PERIOD) {
- return this.goto(this.parseNumberInteger);
- } else if (isDigit(this.char)) {
- return this.goto(this.parseDateTimeOnly);
- } else {
- return this.returnNow(Integer(this.state.buf));
- }
- }
- }, {
- key: "parseIntegerHex",
- value: function parseIntegerHex() {
- if (isHexit(this.char)) {
- this.consume();
- } else if (this.char === CHAR_LOWBAR) {
- return this.call(this.parseNoUnder);
- } else {
- var result = Integer(this.state.buf);
- /* istanbul ignore if */
- if (result.isNaN()) {
- throw this.error(new TomlError('Invalid number'));
- } else {
- return this.returnNow(result);
- }
- }
- }
- }, {
- key: "parseIntegerOct",
- value: function parseIntegerOct() {
- if (isOctit(this.char)) {
- this.consume();
- } else if (this.char === CHAR_LOWBAR) {
- return this.call(this.parseNoUnder);
- } else {
- var result = Integer(this.state.buf);
- /* istanbul ignore if */
- if (result.isNaN()) {
- throw this.error(new TomlError('Invalid number'));
- } else {
- return this.returnNow(result);
- }
- }
- }
- }, {
- key: "parseIntegerBin",
- value: function parseIntegerBin() {
- if (isBit(this.char)) {
- this.consume();
- } else if (this.char === CHAR_LOWBAR) {
- return this.call(this.parseNoUnder);
- } else {
- var result = Integer(this.state.buf);
- /* istanbul ignore if */
- if (result.isNaN()) {
- throw this.error(new TomlError('Invalid number'));
- } else {
- return this.returnNow(result);
- }
- }
- }
- /* DATETIME */
- }, {
- key: "parseDateTime",
- value: function parseDateTime() {
- // we enter here having just consumed the year and about to consume the hyphen
- if (this.state.buf.length < 4) {
- throw this.error(new TomlError('Years less than 1000 must be zero padded to four characters'));
- }
- this.state.result = this.state.buf;
- this.state.buf = '';
- return this.next(this.parseDateMonth);
- }
- }, {
- key: "parseDateMonth",
- value: function parseDateMonth() {
- if (this.char === CHAR_HYPHEN) {
- if (this.state.buf.length < 2) {
- throw this.error(new TomlError('Months less than 10 must be zero padded to two characters'));
- }
- this.state.result += '-' + this.state.buf;
- this.state.buf = '';
- return this.next(this.parseDateDay);
- } else if (isDigit(this.char)) {
- this.consume();
- } else {
- throw this.error(new TomlError('Incomplete datetime'));
- }
- }
- }, {
- key: "parseDateDay",
- value: function parseDateDay() {
- if (this.char === CHAR_T || this.char === CHAR_SP) {
- if (this.state.buf.length < 2) {
- throw this.error(new TomlError('Days less than 10 must be zero padded to two characters'));
- }
- this.state.result += '-' + this.state.buf;
- this.state.buf = '';
- return this.next(this.parseStartTimeHour);
- } else if (this.atEndOfWord()) {
- return this.return(createDate(this.state.result + '-' + this.state.buf));
- } else if (isDigit(this.char)) {
- this.consume();
- } else {
- throw this.error(new TomlError('Incomplete datetime'));
- }
- }
- }, {
- key: "parseStartTimeHour",
- value: function parseStartTimeHour() {
- if (this.atEndOfWord()) {
- return this.returnNow(createDate(this.state.result));
- } else {
- return this.goto(this.parseTimeHour);
- }
- }
- }, {
- key: "parseTimeHour",
- value: function parseTimeHour() {
- if (this.char === CHAR_COLON) {
- if (this.state.buf.length < 2) {
- throw this.error(new TomlError('Hours less than 10 must be zero padded to two characters'));
- }
- this.state.result += 'T' + this.state.buf;
- this.state.buf = '';
- return this.next(this.parseTimeMin);
- } else if (isDigit(this.char)) {
- this.consume();
- } else {
- throw this.error(new TomlError('Incomplete datetime'));
- }
- }
- }, {
- key: "parseTimeMin",
- value: function parseTimeMin() {
- if (this.state.buf.length < 2 && isDigit(this.char)) {
- this.consume();
- } else if (this.state.buf.length === 2 && this.char === CHAR_COLON) {
- this.state.result += ':' + this.state.buf;
- this.state.buf = '';
- return this.next(this.parseTimeSec);
- } else {
- throw this.error(new TomlError('Incomplete datetime'));
- }
- }
- }, {
- key: "parseTimeSec",
- value: function parseTimeSec() {
- if (isDigit(this.char)) {
- this.consume();
- if (this.state.buf.length === 2) {
- this.state.result += ':' + this.state.buf;
- this.state.buf = '';
- return this.next(this.parseTimeZoneOrFraction);
- }
- } else {
- throw this.error(new TomlError('Incomplete datetime'));
- }
- }
- }, {
- key: "parseOnlyTimeHour",
- value: function parseOnlyTimeHour() {
- /* istanbul ignore else */
- if (this.char === CHAR_COLON) {
- if (this.state.buf.length < 2) {
- throw this.error(new TomlError('Hours less than 10 must be zero padded to two characters'));
- }
- this.state.result = this.state.buf;
- this.state.buf = '';
- return this.next(this.parseOnlyTimeMin);
- } else {
- throw this.error(new TomlError('Incomplete time'));
- }
- }
- }, {
- key: "parseOnlyTimeMin",
- value: function parseOnlyTimeMin() {
- if (this.state.buf.length < 2 && isDigit(this.char)) {
- this.consume();
- } else if (this.state.buf.length === 2 && this.char === CHAR_COLON) {
- this.state.result += ':' + this.state.buf;
- this.state.buf = '';
- return this.next(this.parseOnlyTimeSec);
- } else {
- throw this.error(new TomlError('Incomplete time'));
- }
- }
- }, {
- key: "parseOnlyTimeSec",
- value: function parseOnlyTimeSec() {
- if (isDigit(this.char)) {
- this.consume();
- if (this.state.buf.length === 2) {
- return this.next(this.parseOnlyTimeFractionMaybe);
- }
- } else {
- throw this.error(new TomlError('Incomplete time'));
- }
- }
- }, {
- key: "parseOnlyTimeFractionMaybe",
- value: function parseOnlyTimeFractionMaybe() {
- this.state.result += ':' + this.state.buf;
- if (this.char === CHAR_PERIOD) {
- this.state.buf = '';
- this.next(this.parseOnlyTimeFraction);
- } else {
- return this.return(createTime(this.state.result));
- }
- }
- }, {
- key: "parseOnlyTimeFraction",
- value: function parseOnlyTimeFraction() {
- if (isDigit(this.char)) {
- this.consume();
- } else if (this.atEndOfWord()) {
- if (this.state.buf.length === 0) throw this.error(new TomlError('Expected digit in milliseconds'));
- return this.returnNow(createTime(this.state.result + '.' + this.state.buf));
- } else {
- throw this.error(new TomlError('Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z'));
- }
- }
- }, {
- key: "parseTimeZoneOrFraction",
- value: function parseTimeZoneOrFraction() {
- if (this.char === CHAR_PERIOD) {
- this.consume();
- this.next(this.parseDateTimeFraction);
- } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {
- this.consume();
- this.next(this.parseTimeZoneHour);
- } else if (this.char === CHAR_Z) {
- this.consume();
- return this.return(createDatetime(this.state.result + this.state.buf));
- } else if (this.atEndOfWord()) {
- return this.returnNow(createDatetimeFloat(this.state.result + this.state.buf));
- } else {
- throw this.error(new TomlError('Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z'));
- }
- }
- }, {
- key: "parseDateTimeFraction",
- value: function parseDateTimeFraction() {
- if (isDigit(this.char)) {
- this.consume();
- } else if (this.state.buf.length === 1) {
- throw this.error(new TomlError('Expected digit in milliseconds'));
- } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {
- this.consume();
- this.next(this.parseTimeZoneHour);
- } else if (this.char === CHAR_Z) {
- this.consume();
- return this.return(createDatetime(this.state.result + this.state.buf));
- } else if (this.atEndOfWord()) {
- return this.returnNow(createDatetimeFloat(this.state.result + this.state.buf));
- } else {
- throw this.error(new TomlError('Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z'));
- }
- }
- }, {
- key: "parseTimeZoneHour",
- value: function parseTimeZoneHour() {
- if (isDigit(this.char)) {
- this.consume(); // FIXME: No more regexps
- if (/\d\d$/.test(this.state.buf)) return this.next(this.parseTimeZoneSep);
- } else {
- throw this.error(new TomlError('Unexpected character in datetime, expected digit'));
- }
- }
- }, {
- key: "parseTimeZoneSep",
- value: function parseTimeZoneSep() {
- if (this.char === CHAR_COLON) {
- this.consume();
- this.next(this.parseTimeZoneMin);
- } else {
- throw this.error(new TomlError('Unexpected character in datetime, expected colon'));
- }
- }
- }, {
- key: "parseTimeZoneMin",
- value: function parseTimeZoneMin() {
- if (isDigit(this.char)) {
- this.consume();
- if (/\d\d$/.test(this.state.buf)) return this.return(createDatetime(this.state.result + this.state.buf));
- } else {
- throw this.error(new TomlError('Unexpected character in datetime, expected digit'));
- }
- }
- /* BOOLEAN */
- }, {
- key: "parseBoolean",
- value: function parseBoolean() {
- /* istanbul ignore else */
- if (this.char === CHAR_t) {
- this.consume();
- return this.next(this.parseTrue_r);
- } else if (this.char === CHAR_f) {
- this.consume();
- return this.next(this.parseFalse_a);
- }
- }
- }, {
- key: "parseTrue_r",
- value: function parseTrue_r() {
- if (this.char === CHAR_r) {
- this.consume();
- return this.next(this.parseTrue_u);
- } else {
- throw this.error(new TomlError('Invalid boolean, expected true or false'));
- }
- }
- }, {
- key: "parseTrue_u",
- value: function parseTrue_u() {
- if (this.char === CHAR_u) {
- this.consume();
- return this.next(this.parseTrue_e);
- } else {
- throw this.error(new TomlError('Invalid boolean, expected true or false'));
- }
- }
- }, {
- key: "parseTrue_e",
- value: function parseTrue_e() {
- if (this.char === CHAR_e) {
- return this.return(true);
- } else {
- throw this.error(new TomlError('Invalid boolean, expected true or false'));
- }
- }
- }, {
- key: "parseFalse_a",
- value: function parseFalse_a() {
- if (this.char === CHAR_a) {
- this.consume();
- return this.next(this.parseFalse_l);
- } else {
- throw this.error(new TomlError('Invalid boolean, expected true or false'));
- }
- }
- }, {
- key: "parseFalse_l",
- value: function parseFalse_l() {
- if (this.char === CHAR_l) {
- this.consume();
- return this.next(this.parseFalse_s);
- } else {
- throw this.error(new TomlError('Invalid boolean, expected true or false'));
- }
- }
- }, {
- key: "parseFalse_s",
- value: function parseFalse_s() {
- if (this.char === CHAR_s) {
- this.consume();
- return this.next(this.parseFalse_e);
- } else {
- throw this.error(new TomlError('Invalid boolean, expected true or false'));
- }
- }
- }, {
- key: "parseFalse_e",
- value: function parseFalse_e() {
- if (this.char === CHAR_e) {
- return this.return(false);
- } else {
- throw this.error(new TomlError('Invalid boolean, expected true or false'));
- }
- }
- /* INLINE LISTS */
- }, {
- key: "parseInlineList",
- value: function parseInlineList() {
- if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M || this.char === CTRL_J) {
- return null;
- } else if (this.char === Parser.END) {
- throw this.error(new TomlError('Unterminated inline array'));
- } else if (this.char === CHAR_NUM) {
- return this.call(this.parseComment);
- } else if (this.char === CHAR_RSQB) {
- return this.return(this.state.resultArr || InlineList());
- } else {
- return this.callNow(this.parseValue, this.recordInlineListValue);
- }
- }
- }, {
- key: "recordInlineListValue",
- value: function recordInlineListValue(value) {
- if (this.state.resultArr) {
- var listType = this.state.resultArr[_contentType];
- var valueType = tomlType(value);
- if (listType !== valueType) {
- throw this.error(new TomlError(`Inline lists must be a single type, not a mix of ${listType} and ${valueType}`));
- }
- } else {
- this.state.resultArr = InlineList(tomlType(value));
- }
- if (isFloat(value) || isInteger(value)) {
- // unbox now that we've verified they're ok
- this.state.resultArr.push(value.valueOf());
- } else {
- this.state.resultArr.push(value);
- }
- return this.goto(this.parseInlineListNext);
- }
- }, {
- key: "parseInlineListNext",
- value: function parseInlineListNext() {
- if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M || this.char === CTRL_J) {
- return null;
- } else if (this.char === CHAR_NUM) {
- return this.call(this.parseComment);
- } else if (this.char === CHAR_COMMA) {
- return this.next(this.parseInlineList);
- } else if (this.char === CHAR_RSQB) {
- return this.goto(this.parseInlineList);
- } else {
- throw this.error(new TomlError('Invalid character, expected whitespace, comma (,) or close bracket (])'));
- }
- }
- /* INLINE TABLE */
- }, {
- key: "parseInlineTable",
- value: function parseInlineTable() {
- if (this.char === CHAR_SP || this.char === CTRL_I) {
- return null;
- } else if (this.char === Parser.END || this.char === CHAR_NUM || this.char === CTRL_J || this.char === CTRL_M) {
- throw this.error(new TomlError('Unterminated inline array'));
- } else if (this.char === CHAR_RCUB) {
- return this.return(this.state.resultTable || InlineTable());
- } else {
- if (!this.state.resultTable) this.state.resultTable = InlineTable();
- return this.callNow(this.parseAssign, this.recordInlineTableValue);
- }
- }
- }, {
- key: "recordInlineTableValue",
- value: function recordInlineTableValue(kv) {
- var target = this.state.resultTable;
- var finalKey = kv.key.pop();
- var _iteratorNormalCompletion2 = true;
- var _didIteratorError2 = false;
- var _iteratorError2 = undefined;
- try {
- for (var _iterator2 = kv.key[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
- var kw = _step2.value;
- if (kw in target && (!isTable(target[kw]) || target[kw][_declared])) {
- throw this.error(new TomlError("Can't redefine existing key"));
- }
- target = target[kw] = target[kw] || Table();
- }
- } catch (err) {
- _didIteratorError2 = true;
- _iteratorError2 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
- _iterator2.return();
- }
- } finally {
- if (_didIteratorError2) {
- throw _iteratorError2;
- }
- }
- }
- if (finalKey in target) {
- throw this.error(new TomlError("Can't redefine existing key"));
- }
- if (isInteger(kv.value) || isFloat(kv.value)) {
- target[finalKey] = kv.value.valueOf();
- } else {
- target[finalKey] = kv.value;
- }
- return this.goto(this.parseInlineTableNext);
- }
- }, {
- key: "parseInlineTableNext",
- value: function parseInlineTableNext() {
- if (this.char === CHAR_SP || this.char === CTRL_I) {
- return null;
- } else if (this.char === Parser.END || this.char === CHAR_NUM || this.char === CTRL_J || this.char === CTRL_M) {
- throw this.error(new TomlError('Unterminated inline array'));
- } else if (this.char === CHAR_COMMA) {
- return this.next(this.parseInlineTable);
- } else if (this.char === CHAR_RCUB) {
- return this.goto(this.parseInlineTable);
- } else {
- throw this.error(new TomlError('Invalid character, expected whitespace, comma (,) or close bracket (])'));
- }
- }
- }]);
- return TOMLParser;
- }(Parser);
- return TOMLParser;
- }
- });
- var parsePrettyError = prettyError;
- function prettyError(err, buf) {
- /* istanbul ignore if */
- if (err.pos == null || err.line == null) return err;
- var msg = err.message;
- msg += ` at row ${err.line + 1}, col ${err.col + 1}, pos ${err.pos}:\n`;
- /* istanbul ignore else */
- if (buf && buf.split) {
- var lines = buf.split(/\n/);
- var lineNumWidth = String(Math.min(lines.length, err.line + 3)).length;
- var linePadding = ' ';
- while (linePadding.length < lineNumWidth) {
- linePadding += ' ';
- }
- for (var ii = Math.max(0, err.line - 1); ii < Math.min(lines.length, err.line + 2); ++ii) {
- var lineNum = String(ii + 1);
- if (lineNum.length < lineNumWidth) lineNum = ' ' + lineNum;
- if (err.line === ii) {
- msg += lineNum + '> ' + lines[ii] + '\n';
- msg += linePadding + ' ';
- for (var hh = 0; hh < err.col; ++hh) {
- msg += ' ';
- }
- msg += '^\n';
- } else {
- msg += lineNum + ': ' + lines[ii] + '\n';
- }
- }
- }
- err.message = msg + '\n';
- return err;
- }
- var parseString_1 = parseString;
- function parseString(str) {
- if (commonjsGlobal.Buffer && commonjsGlobal.Buffer.isBuffer(str)) {
- str = str.toString('utf8');
- }
- var parser = new tomlParser();
- try {
- parser.parse(str);
- return parser.finish();
- } catch (ex) {
- throw parsePrettyError(ex, str);
- }
- }
- var loadToml = function loadToml(filePath, content) {
- try {
- return parseString_1(content);
- } catch (error) {
- error.message = `TOML Error in ${filePath}:\n${error.message}`;
- throw error;
- }
- };
- var resolveConfig_1 = createCommonjsModule(function (module) {
- "use strict";
- var getExplorerMemoized = mem(function (opts) {
- var explorer = thirdParty$1.cosmiconfig("prettier", {
- cache: opts.cache,
- transform: function transform(result) {
- if (result && result.config) {
- if (typeof result.config !== "object") {
- throw new Error(`Config is only allowed to be an object, ` + `but received ${typeof result.config} in "${result.filepath}"`);
- }
- delete result.config.$schema;
- }
- return result;
- },
- searchPlaces: ["package.json", ".prettierrc", ".prettierrc.json", ".prettierrc.yaml", ".prettierrc.yml", ".prettierrc.js", "prettier.config.js", ".prettierrc.toml"],
- loaders: {
- ".toml": loadToml
- }
- });
- var _load = opts.sync ? explorer.loadSync : explorer.load;
- var search = opts.sync ? explorer.searchSync : explorer.search;
- return {
- // cosmiconfig v4 interface
- load: function load(searchPath, configPath) {
- return configPath ? _load(configPath) : search(searchPath);
- }
- };
- });
- /** @param {{ cache: boolean, sync: boolean }} opts */
- function getLoadFunction(opts) {
- // Normalize opts before passing to a memoized function
- opts = Object.assign({
- sync: false,
- cache: false
- }, opts);
- return getExplorerMemoized(opts).load;
- }
- function _resolveConfig(filePath, opts, sync) {
- opts = Object.assign({
- useCache: true
- }, opts);
- var loadOpts = {
- cache: !!opts.useCache,
- sync: !!sync,
- editorconfig: !!opts.editorconfig
- };
- var load = getLoadFunction(loadOpts);
- var loadEditorConfig = resolveConfigEditorconfig.getLoadFunction(loadOpts);
- var arr = [load, loadEditorConfig].map(function (l) {
- return l(filePath, opts.config);
- });
- var unwrapAndMerge = function unwrapAndMerge(arr) {
- var result = arr[0];
- var editorConfigured = arr[1];
- var merged = Object.assign({}, editorConfigured, mergeOverrides(Object.assign({}, result), filePath));
- ["plugins", "pluginSearchDirs"].forEach(function (optionName) {
- if (Array.isArray(merged[optionName])) {
- merged[optionName] = merged[optionName].map(function (value) {
- return typeof value === "string" && value.startsWith(".") // relative path
- ? path.resolve(path.dirname(result.filepath), value) : value;
- });
- }
- });
- if (!result && !editorConfigured) {
- return null;
- }
- return merged;
- };
- if (loadOpts.sync) {
- return unwrapAndMerge(arr);
- }
- return Promise.all(arr).then(unwrapAndMerge);
- }
- var resolveConfig = function resolveConfig(filePath, opts) {
- return _resolveConfig(filePath, opts, false);
- };
- resolveConfig.sync = function (filePath, opts) {
- return _resolveConfig(filePath, opts, true);
- };
- function clearCache() {
- mem.clear(getExplorerMemoized);
- resolveConfigEditorconfig.clearCache();
- }
- function resolveConfigFile(filePath) {
- var load = getLoadFunction({
- sync: false
- });
- return load(filePath).then(function (result) {
- return result ? result.filepath : null;
- });
- }
- resolveConfigFile.sync = function (filePath) {
- var load = getLoadFunction({
- sync: true
- });
- var result = load(filePath);
- return result ? result.filepath : null;
- };
- function mergeOverrides(configResult, filePath) {
- var options = Object.assign({}, configResult.config);
- if (filePath && options.overrides) {
- var relativeFilePath = path.relative(path.dirname(configResult.filepath), filePath);
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = options.overrides[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var override = _step.value;
- if (pathMatchesGlobs(relativeFilePath, override.files, override.excludeFiles)) {
- Object.assign(options, override.options);
- }
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return != null) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- }
- delete options.overrides;
- return options;
- } // Based on eslint: https://github.com/eslint/eslint/blob/master/lib/config/config-ops.js
- function pathMatchesGlobs(filePath, patterns, excludedPatterns) {
- var patternList = [].concat(patterns);
- var excludedPatternList = [].concat(excludedPatterns || []);
- var opts = {
- matchBase: true
- };
- return patternList.some(function (pattern) {
- return minimatch_1(filePath, pattern, opts);
- }) && !excludedPatternList.some(function (excludedPattern) {
- return minimatch_1(filePath, excludedPattern, opts);
- });
- }
- module.exports = {
- resolveConfig,
- resolveConfigFile,
- clearCache
- };
- });
- var version = require$$0.version;
- var getSupportInfo = support.getSupportInfo; // Luckily `opts` is always the 2nd argument
- function _withPlugins(fn) {
- return function () {
- var args = Array.from(arguments);
- var opts = args[1] || {};
- args[1] = Object.assign({}, opts, {
- plugins: loadPlugins_1(opts.plugins, opts.pluginSearchDirs)
- });
- return fn.apply(null, args);
- };
- }
- function withPlugins(fn) {
- var resultingFn = _withPlugins(fn);
- if (fn.sync) {
- resultingFn.sync = _withPlugins(fn.sync);
- }
- return resultingFn;
- }
- var formatWithCursor = withPlugins(core.formatWithCursor);
- var src = {
- formatWithCursor,
- format(text, opts) {
- return formatWithCursor(text, opts).formatted;
- },
- check: function check(text, opts) {
- var formatted = formatWithCursor(text, opts).formatted;
- return formatted === text;
- },
- doc,
- resolveConfig: resolveConfig_1.resolveConfig,
- resolveConfigFile: resolveConfig_1.resolveConfigFile,
- clearConfigCache: resolveConfig_1.clearCache,
- getFileInfo: withPlugins(getFileInfo_1),
- getSupportInfo: withPlugins(getSupportInfo),
- version,
- util: utilShared,
- /* istanbul ignore next */
- __debug: {
- parse: withPlugins(core.parse),
- formatAST: withPlugins(core.formatAST),
- formatDoc: withPlugins(core.formatDoc),
- printToDoc: withPlugins(core.printToDoc),
- printDocToString: withPlugins(core.printDocToString)
- }
- };
- var prettier$2 = src;
- var at;
- var ch;
- var escapee = {
- '"': '"',
- '\\': '\\',
- '/': '/',
- b: '\b',
- f: '\f',
- n: '\n',
- r: '\r',
- t: '\t'
- };
- var text;
- var error = function error(m) {
- // Call error when something is wrong.
- throw {
- name: 'SyntaxError',
- message: m,
- at: at,
- text: text
- };
- };
- var next = function next(c) {
- // If a c parameter is provided, verify that it matches the current character.
- if (c && c !== ch) {
- error("Expected '" + c + "' instead of '" + ch + "'");
- } // Get the next character. When there are no more characters,
- // return the empty string.
- ch = text.charAt(at);
- at += 1;
- return ch;
- };
- var number$2 = function number() {
- // Parse a number value.
- var number,
- string = '';
- if (ch === '-') {
- string = '-';
- next('-');
- }
- while (ch >= '0' && ch <= '9') {
- string += ch;
- next();
- }
- if (ch === '.') {
- string += '.';
- while (next() && ch >= '0' && ch <= '9') {
- string += ch;
- }
- }
- if (ch === 'e' || ch === 'E') {
- string += ch;
- next();
- if (ch === '-' || ch === '+') {
- string += ch;
- next();
- }
- while (ch >= '0' && ch <= '9') {
- string += ch;
- next();
- }
- }
- number = +string;
- if (!isFinite(number)) {
- error("Bad number");
- } else {
- return number;
- }
- };
- var string$2 = function string() {
- // Parse a string value.
- var hex,
- i,
- string = '',
- uffff; // When parsing for string values, we must look for " and \ characters.
- if (ch === '"') {
- while (next()) {
- if (ch === '"') {
- next();
- return string;
- } else if (ch === '\\') {
- next();
- if (ch === 'u') {
- uffff = 0;
- for (i = 0; i < 4; i += 1) {
- hex = parseInt(next(), 16);
- if (!isFinite(hex)) {
- break;
- }
- uffff = uffff * 16 + hex;
- }
- string += String.fromCharCode(uffff);
- } else if (typeof escapee[ch] === 'string') {
- string += escapee[ch];
- } else {
- break;
- }
- } else {
- string += ch;
- }
- }
- }
- error("Bad string");
- };
- var white = function white() {
- // Skip whitespace.
- while (ch && ch <= ' ') {
- next();
- }
- };
- var word$2 = function word() {
- // true, false, or null.
- switch (ch) {
- case 't':
- next('t');
- next('r');
- next('u');
- next('e');
- return true;
- case 'f':
- next('f');
- next('a');
- next('l');
- next('s');
- next('e');
- return false;
- case 'n':
- next('n');
- next('u');
- next('l');
- next('l');
- return null;
- }
- error("Unexpected '" + ch + "'");
- };
- var value;
- var array$4 = function array() {
- // Parse an array value.
- var array = [];
- if (ch === '[') {
- next('[');
- white();
- if (ch === ']') {
- next(']');
- return array; // empty array
- }
- while (ch) {
- array.push(value());
- white();
- if (ch === ']') {
- next(']');
- return array;
- }
- next(',');
- white();
- }
- }
- error("Bad array");
- };
- var object$1 = function object() {
- // Parse an object value.
- var key,
- object = {};
- if (ch === '{') {
- next('{');
- white();
- if (ch === '}') {
- next('}');
- return object; // empty object
- }
- while (ch) {
- key = string$2();
- white();
- next(':');
- if (Object.hasOwnProperty.call(object, key)) {
- error('Duplicate key "' + key + '"');
- }
- object[key] = value();
- white();
- if (ch === '}') {
- next('}');
- return object;
- }
- next(',');
- white();
- }
- }
- error("Bad object");
- };
- value = function value() {
- // Parse a JSON value. It could be an object, an array, a string, a number,
- // or a word.
- white();
- switch (ch) {
- case '{':
- return object$1();
- case '[':
- return array$4();
- case '"':
- return string$2();
- case '-':
- return number$2();
- default:
- return ch >= '0' && ch <= '9' ? number$2() : word$2();
- }
- }; // Return the json_parse function. It will have access to all of the above
- // functions and variables.
- var parse$8 = function parse(source, reviver) {
- var result;
- text = source;
- at = 0;
- ch = ' ';
- result = value();
- white();
- if (ch) {
- error("Syntax error");
- } // If there is a reviver function, we recursively walk the new structure,
- // passing each name/value pair to the reviver function for possible
- // transformation, starting with a temporary root object that holds the result
- // in an empty key. If there is not a reviver function, we simply return the
- // result.
- return typeof reviver === 'function' ? function walk(holder, key) {
- var k,
- v,
- value = holder[key];
- if (value && typeof value === 'object') {
- for (k in value) {
- if (Object.prototype.hasOwnProperty.call(value, k)) {
- v = walk(value, k);
- if (v !== undefined) {
- value[k] = v;
- } else {
- delete value[k];
- }
- }
- }
- }
- return reviver.call(holder, key, value);
- }({
- '': result
- }, '') : result;
- };
- var escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
- var gap;
- var indent$10;
- var meta$1 = {
- // table of character substitutions
- '\b': '\\b',
- '\t': '\\t',
- '\n': '\\n',
- '\f': '\\f',
- '\r': '\\r',
- '"': '\\"',
- '\\': '\\\\'
- };
- var rep;
- function quote(string) {
- // If the string contains no control characters, no quote characters, and no
- // backslash characters, then we can safely slap some quotes around it.
- // Otherwise we must also replace the offending characters with safe escape
- // sequences.
- escapable.lastIndex = 0;
- return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
- var c = meta$1[a];
- return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
- }) + '"' : '"' + string + '"';
- }
- function str(key, holder) {
- // Produce a string from holder[key].
- var i,
- // The loop counter.
- k,
- // The member key.
- v,
- // The member value.
- length,
- mind = gap,
- partial,
- value = holder[key]; // If the value has a toJSON method, call it to obtain a replacement value.
- if (value && typeof value === 'object' && typeof value.toJSON === 'function') {
- value = value.toJSON(key);
- } // If we were called with a replacer function, then call the replacer to
- // obtain a replacement value.
- if (typeof rep === 'function') {
- value = rep.call(holder, key, value);
- } // What happens next depends on the value's type.
- switch (typeof value) {
- case 'string':
- return quote(value);
- case 'number':
- // JSON numbers must be finite. Encode non-finite numbers as null.
- return isFinite(value) ? String(value) : 'null';
- case 'boolean':
- case 'null':
- // If the value is a boolean or null, convert it to a string. Note:
- // typeof null does not produce 'null'. The case is included here in
- // the remote chance that this gets fixed someday.
- return String(value);
- case 'object':
- if (!value) return 'null';
- gap += indent$10;
- partial = []; // Array.isArray
- if (Object.prototype.toString.apply(value) === '[object Array]') {
- length = value.length;
- for (i = 0; i < length; i += 1) {
- partial[i] = str(i, value) || 'null';
- } // Join all of the elements together, separated with commas, and
- // wrap them in brackets.
- v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']';
- gap = mind;
- return v;
- } // If the replacer is an array, use it to select the members to be
- // stringified.
- if (rep && typeof rep === 'object') {
- length = rep.length;
- for (i = 0; i < length; i += 1) {
- k = rep[i];
- if (typeof k === 'string') {
- v = str(k, value);
- if (v) {
- partial.push(quote(k) + (gap ? ': ' : ':') + v);
- }
- }
- }
- } else {
- // Otherwise, iterate through all of the keys in the object.
- for (k in value) {
- if (Object.prototype.hasOwnProperty.call(value, k)) {
- v = str(k, value);
- if (v) {
- partial.push(quote(k) + (gap ? ': ' : ':') + v);
- }
- }
- }
- } // Join all of the member texts together, separated with commas,
- // and wrap them in braces.
- v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}';
- gap = mind;
- return v;
- }
- }
- var stringify$1 = function stringify(value, replacer, space) {
- var i;
- gap = '';
- indent$10 = ''; // If the space parameter is a number, make an indent string containing that
- // many spaces.
- if (typeof space === 'number') {
- for (i = 0; i < space; i += 1) {
- indent$10 += ' ';
- }
- } // If the space parameter is a string, it will be used as the indent string.
- else if (typeof space === 'string') {
- indent$10 = space;
- } // If there is a replacer, it must be a function or an array.
- // Otherwise, throw an error.
- rep = replacer;
- if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) {
- throw new Error('JSON.stringify');
- } // Make a fake root object containing our value under the key of ''.
- // Return the result of stringifying the value.
- return str('', {
- '': value
- });
- };
- var parse$7 = parse$8;
- var stringify = stringify$1;
- var jsonify = {
- parse: parse$7,
- stringify: stringify
- };
- var json$10 = typeof JSON !== 'undefined' ? JSON : jsonify;
- var jsonStableStringify = function jsonStableStringify(obj, opts) {
- if (!opts) opts = {};
- if (typeof opts === 'function') opts = {
- cmp: opts
- };
- var space = opts.space || '';
- if (typeof space === 'number') space = Array(space + 1).join(' ');
- var cycles = typeof opts.cycles === 'boolean' ? opts.cycles : false;
- var replacer = opts.replacer || function (key, value) {
- return value;
- };
- var cmp = opts.cmp && function (f) {
- return function (node) {
- return function (a, b) {
- var aobj = {
- key: a,
- value: node[a]
- };
- var bobj = {
- key: b,
- value: node[b]
- };
- return f(aobj, bobj);
- };
- };
- }(opts.cmp);
- var seen = [];
- return function stringify(parent, key, node, level) {
- var indent = space ? '\n' + new Array(level + 1).join(space) : '';
- var colonSeparator = space ? ': ' : ':';
- if (node && node.toJSON && typeof node.toJSON === 'function') {
- node = node.toJSON();
- }
- node = replacer.call(parent, key, node);
- if (node === undefined) {
- return;
- }
- if (typeof node !== 'object' || node === null) {
- return json$10.stringify(node);
- }
- if (isArray$1(node)) {
- var out = [];
- for (var i = 0; i < node.length; i++) {
- var item = stringify(node, i, node[i], level + 1) || json$10.stringify(null);
- out.push(indent + space + item);
- }
- return '[' + out.join(',') + indent + ']';
- } else {
- if (seen.indexOf(node) !== -1) {
- if (cycles) return json$10.stringify('__cycle__');
- throw new TypeError('Converting circular structure to JSON');
- } else seen.push(node);
- var keys = objectKeys(node).sort(cmp && cmp(node));
- var out = [];
- for (var i = 0; i < keys.length; i++) {
- var key = keys[i];
- var value = stringify(node, key, node[key], level + 1);
- if (!value) continue;
- var keyValue = json$10.stringify(key) + colonSeparator + value;
-
- out.push(indent + space + keyValue);
- }
- seen.splice(seen.indexOf(node), 1);
- return '{' + out.join(',') + indent + '}';
- }
- }({
- '': obj
- }, '', obj, 0);
- };
- var isArray$1 = Array.isArray || function (x) {
- return {}.toString.call(x) === '[object Array]';
- };
- var objectKeys = Object.keys || function (obj) {
- var has = Object.prototype.hasOwnProperty || function () {
- return true;
- };
- var keys = [];
- for (var key in obj) {
- if (has.call(obj, key)) keys.push(key);
- }
- return keys;
- };
- function preserveCamelCase(str) {
- var isLastCharLower = false;
- var isLastCharUpper = false;
- var isLastLastCharUpper = false;
- for (var i = 0; i < str.length; i++) {
- var c = str[i];
- if (isLastCharLower && /[a-zA-Z]/.test(c) && c.toUpperCase() === c) {
- str = str.substr(0, i) + '-' + str.substr(i);
- isLastCharLower = false;
- isLastLastCharUpper = isLastCharUpper;
- isLastCharUpper = true;
- i++;
- } else if (isLastCharUpper && isLastLastCharUpper && /[a-zA-Z]/.test(c) && c.toLowerCase() === c) {
- str = str.substr(0, i - 1) + '-' + str.substr(i - 1);
- isLastLastCharUpper = isLastCharUpper;
- isLastCharUpper = false;
- isLastCharLower = true;
- } else {
- isLastCharLower = c.toLowerCase() === c;
- isLastLastCharUpper = isLastCharUpper;
- isLastCharUpper = c.toUpperCase() === c;
- }
- }
- return str;
- }
- var camelcase = function camelcase(str) {
- if (arguments.length > 1) {
- str = Array.from(arguments).map(function (x) {
- return x.trim();
- }).filter(function (x) {
- return x.length;
- }).join('-');
- } else {
- str = str.trim();
- }
- if (str.length === 0) {
- return '';
- }
- if (str.length === 1) {
- return str.toLowerCase();
- }
- if (/^[a-z0-9]+$/.test(str)) {
- return str;
- }
- var hasUpperCase = str !== str.toLowerCase();
- if (hasUpperCase) {
- str = preserveCamelCase(str);
- }
- return str.replace(/^[_.\- ]+/, '').toLowerCase().replace(/[_.\- ]+(\w|$)/g, function (m, p1) {
- return p1.toUpperCase();
- });
- };
- /*!
- * dashify <https://github.com/jonschlinkert/dashify>
- *
- * Copyright (c) 2015 Jon Schlinkert.
- * Licensed under the MIT license.
- */
- var dashify = function dashify(str) {
- if (typeof str !== 'string') {
- throw new TypeError('expected a string');
- }
- str = str.replace(/([a-z])([A-Z])/g, '$1-$2');
- str = str.replace(/[ \t\W]/g, '-');
- str = str.replace(/^-+|-+$/g, '');
- return str.toLowerCase();
- };
- var minimist = function minimist(args, opts) {
- if (!opts) opts = {};
- var flags = {
- bools: {},
- strings: {},
- unknownFn: null
- };
- if (typeof opts['unknown'] === 'function') {
- flags.unknownFn = opts['unknown'];
- }
- if (typeof opts['boolean'] === 'boolean' && opts['boolean']) {
- flags.allBools = true;
- } else {
- [].concat(opts['boolean']).filter(Boolean).forEach(function (key) {
- flags.bools[key] = true;
- });
- }
- var aliases = {};
- Object.keys(opts.alias || {}).forEach(function (key) {
- aliases[key] = [].concat(opts.alias[key]);
- aliases[key].forEach(function (x) {
- aliases[x] = [key].concat(aliases[key].filter(function (y) {
- return x !== y;
- }));
- });
- });
- [].concat(opts.string).filter(Boolean).forEach(function (key) {
- flags.strings[key] = true;
- if (aliases[key]) {
- flags.strings[aliases[key]] = true;
- }
- });
- var defaults = opts['default'] || {};
- var argv = {
- _: []
- };
- Object.keys(flags.bools).forEach(function (key) {
- setArg(key, defaults[key] === undefined ? false : defaults[key]);
- });
- var notFlags = [];
- if (args.indexOf('--') !== -1) {
- notFlags = args.slice(args.indexOf('--') + 1);
- args = args.slice(0, args.indexOf('--'));
- }
- function argDefined(key, arg) {
- return flags.allBools && /^--[^=]+$/.test(arg) || flags.strings[key] || flags.bools[key] || aliases[key];
- }
- function setArg(key, val, arg) {
- if (arg && flags.unknownFn && !argDefined(key, arg)) {
- if (flags.unknownFn(arg) === false) return;
- }
- var value = !flags.strings[key] && isNumber(val) ? Number(val) : val;
- setKey(argv, key.split('.'), value);
- (aliases[key] || []).forEach(function (x) {
- setKey(argv, x.split('.'), value);
- });
- }
- function setKey(obj, keys, value) {
- var o = obj;
- keys.slice(0, -1).forEach(function (key) {
- if (o[key] === undefined) o[key] = {};
- o = o[key];
- });
- var key = keys[keys.length - 1];
- if (o[key] === undefined || flags.bools[key] || typeof o[key] === 'boolean') {
- o[key] = value;
- } else if (Array.isArray(o[key])) {
- o[key].push(value);
- } else {
- o[key] = [o[key], value];
- }
- }
- function aliasIsBoolean(key) {
- return aliases[key].some(function (x) {
- return flags.bools[x];
- });
- }
- for (var i = 0; i < args.length; i++) {
- var arg = args[i];
- if (/^--.+=/.test(arg)) {
- // Using [\s\S] instead of . because js doesn't support the
- // 'dotall' regex modifier. See:
- // http://stackoverflow.com/a/1068308/13216
- var m = arg.match(/^--([^=]+)=([\s\S]*)$/);
- var key = m[1];
- var value = m[2];
- if (flags.bools[key]) {
- value = value !== 'false';
- }
- setArg(key, value, arg);
- } else if (/^--no-.+/.test(arg)) {
- var key = arg.match(/^--no-(.+)/)[1];
- setArg(key, false, arg);
- } else if (/^--.+/.test(arg)) {
- var key = arg.match(/^--(.+)/)[1];
- var next = args[i + 1];
- if (next !== undefined && !/^-/.test(next) && !flags.bools[key] && !flags.allBools && (aliases[key] ? !aliasIsBoolean(key) : true)) {
- setArg(key, next, arg);
- i++;
- } else if (/^(true|false)$/.test(next)) {
- setArg(key, next === 'true', arg);
- i++;
- } else {
- setArg(key, flags.strings[key] ? '' : true, arg);
- }
- } else if (/^-[^-]+/.test(arg)) {
- var letters = arg.slice(1, -1).split('');
- var broken = false;
- for (var j = 0; j < letters.length; j++) {
- var next = arg.slice(j + 2);
- if (next === '-') {
- setArg(letters[j], next, arg);
- continue;
- }
- if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) {
- setArg(letters[j], next.split('=')[1], arg);
- broken = true;
- break;
- }
- if (/[A-Za-z]/.test(letters[j]) && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
- setArg(letters[j], next, arg);
- broken = true;
- break;
- }
- if (letters[j + 1] && letters[j + 1].match(/\W/)) {
- setArg(letters[j], arg.slice(j + 2), arg);
- broken = true;
- break;
- } else {
- setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg);
- }
- }
- var key = arg.slice(-1)[0];
- if (!broken && key !== '-') {
- if (args[i + 1] && !/^(-|--)[^-]/.test(args[i + 1]) && !flags.bools[key] && (aliases[key] ? !aliasIsBoolean(key) : true)) {
- setArg(key, args[i + 1], arg);
- i++;
- } else if (args[i + 1] && /true|false/.test(args[i + 1])) {
- setArg(key, args[i + 1] === 'true', arg);
- i++;
- } else {
- setArg(key, flags.strings[key] ? '' : true, arg);
- }
- }
- } else {
- if (!flags.unknownFn || flags.unknownFn(arg) !== false) {
- argv._.push(flags.strings['_'] || !isNumber(arg) ? arg : Number(arg));
- }
- if (opts.stopEarly) {
- argv._.push.apply(argv._, args.slice(i + 1));
- break;
- }
- }
- }
- Object.keys(defaults).forEach(function (key) {
- if (!hasKey(argv, key.split('.'))) {
- setKey(argv, key.split('.'), defaults[key]);
- (aliases[key] || []).forEach(function (x) {
- setKey(argv, x.split('.'), defaults[key]);
- });
- }
- });
- if (opts['--']) {
- argv['--'] = new Array();
- notFlags.forEach(function (key) {
- argv['--'].push(key);
- });
- } else {
- notFlags.forEach(function (key) {
- argv._.push(key);
- });
- }
- return argv;
- };
- function hasKey(obj, keys) {
- var o = obj;
- keys.slice(0, -1).forEach(function (key) {
- o = o[key] || {};
- });
- var key = keys[keys.length - 1];
- return key in o;
- }
- function isNumber(x) {
- if (typeof x === 'number') return true;
- if (/^0x[0-9a-f]+$/i.test(x)) return true;
- return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
- }
- var PLACEHOLDER = null;
- /**
- * unspecified boolean flag without default value is parsed as `undefined` instead of `false`
- */
- var minimist_1 = function minimist_1(args, options) {
- var boolean = options.boolean || [];
- var defaults = options.default || {};
- var booleanWithoutDefault = boolean.filter(function (key) {
- return !(key in defaults);
- });
- var newDefaults = Object.assign({}, defaults, booleanWithoutDefault.reduce(function (reduced, key) {
- return Object.assign(reduced, {
- [key]: PLACEHOLDER
- });
- }, {}));
- var parsed = minimist(args, Object.assign({}, options, {
- default: newDefaults
- }));
- return Object.keys(parsed).reduce(function (reduced, key) {
- if (parsed[key] !== PLACEHOLDER) {
- reduced[key] = parsed[key];
- }
- return reduced;
- }, {});
- };
- var categoryOrder = [coreOptions$1.CATEGORY_OUTPUT, coreOptions$1.CATEGORY_FORMAT, coreOptions$1.CATEGORY_CONFIG, coreOptions$1.CATEGORY_EDITOR, coreOptions$1.CATEGORY_OTHER];
- /**
- * {
- * [optionName]: {
- * // The type of the option. For 'choice', see also `choices` below.
- * // When passing a type other than the ones listed below, the option is
- * // treated as taking any string as argument, and `--option <${type}>` will
- * // be displayed in --help.
- * type: "boolean" | "choice" | "int" | string;
- *
- * // Default value to be passed to the minimist option `default`.
- * default?: any;
- *
- * // Alias name to be passed to the minimist option `alias`.
- * alias?: string;
- *
- * // For grouping options by category in --help.
- * category?: string;
- *
- * // Description to be displayed in --help. If omitted, the option won't be
- * // shown at all in --help (but see also `oppositeDescription` below).
- * description?: string;
- *
- * // Description for `--no-${name}` to be displayed in --help. If omitted,
- * // `--no-${name}` won't be shown.
- * oppositeDescription?: string;
- *
- * // Indicate if this option is simply passed to the API.
- * // true: use camelified name as the API option name.
- * // string: use this value as the API option name.
- * forwardToApi?: boolean | string;
- *
- * // Indicate that a CLI flag should be an array when forwarded to the API.
- * array?: boolean;
- *
- * // Specify available choices for validation. They will also be displayed
- * // in --help as <a|b|c>.
- * // Use an object instead of a string if a choice is deprecated and should
- * // be treated as `redirect` instead, or if you'd like to add description for
- * // the choice.
- * choices?: Array<
- * | string
- * | { value: string, description?: string, deprecated?: boolean, redirect?: string }
- * >;
- *
- * // If the option has a value that is an exception to the regular value
- * // constraints, indicate that value here (or use a function for more
- * // flexibility).
- * exception?: ((value: any) => boolean);
- *
- * // Indicate that the option is deprecated. Use a string to add an extra
- * // message to --help for the option, for example to suggest a replacement
- * // option.
- * deprecated?: true | string;
- * }
- * }
- *
- * Note: The options below are sorted alphabetically.
- */
- var options$21 = {
- check: {
- type: "boolean",
- category: coreOptions$1.CATEGORY_OUTPUT,
- alias: "c",
- description: dedent_1`
- Check if the given files are formatted, print a human-friendly summary
- message and paths to unformatted files (see also --list-different).
- `
- },
- color: {
- // The supports-color package (a sub sub dependency) looks directly at
- // `process.argv` for `--no-color` and such-like options. The reason it is
- // listed here is to avoid "Ignored unknown option: --no-color" warnings.
- // See https://github.com/chalk/supports-color/#info for more information.
- type: "boolean",
- default: true,
- description: "Colorize error messages.",
- oppositeDescription: "Do not colorize error messages."
- },
- config: {
- type: "path",
- category: coreOptions$1.CATEGORY_CONFIG,
- description: "Path to a Prettier configuration file (.prettierrc, package.json, prettier.config.js).",
- oppositeDescription: "Do not look for a configuration file.",
- exception: function exception(value) {
- return value === false;
- }
- },
- "config-precedence": {
- type: "choice",
- category: coreOptions$1.CATEGORY_CONFIG,
- default: "cli-override",
- choices: [{
- value: "cli-override",
- description: "CLI options take precedence over config file"
- }, {
- value: "file-override",
- description: "Config file take precedence over CLI options"
- }, {
- value: "prefer-file",
- description: dedent_1`
- If a config file is found will evaluate it and ignore other CLI options.
- If no config file is found CLI options will evaluate as normal.
- `
- }],
- description: "Define in which order config files and CLI options should be evaluated."
- },
- "debug-benchmark": {
- // Run the formatting benchmarks. Requires 'benchmark' module to be installed.
- type: "boolean"
- },
- "debug-check": {
- // Run the formatting once again on the formatted output, throw if different.
- type: "boolean"
- },
- "debug-print-doc": {
- type: "boolean"
- },
- "debug-repeat": {
- // Repeat the formatting a few times and measure the average duration.
- type: "int",
- default: 0
- },
- editorconfig: {
- type: "boolean",
- category: coreOptions$1.CATEGORY_CONFIG,
- description: "Take .editorconfig into account when parsing configuration.",
- oppositeDescription: "Don't take .editorconfig into account when parsing configuration.",
- default: true
- },
- "find-config-path": {
- type: "path",
- category: coreOptions$1.CATEGORY_CONFIG,
- description: "Find and print the path to a configuration file for the given input file."
- },
- "file-info": {
- type: "path",
- description: dedent_1`
- Extract the following info (as JSON) for a given file path. Reported fields:
- * ignored (boolean) - true if file path is filtered by --ignore-path
- * inferredParser (string | null) - name of parser inferred from file path
- `
- },
- help: {
- type: "flag",
- alias: "h",
- description: dedent_1`
- Show CLI usage, or details about the given flag.
- Example: --help write
- `,
- exception: function exception(value) {
- return value === "";
- }
- },
- "ignore-path": {
- type: "path",
- category: coreOptions$1.CATEGORY_CONFIG,
- default: ".prettierignore",
- description: "Path to a file with patterns describing files to ignore."
- },
- "list-different": {
- type: "boolean",
- category: coreOptions$1.CATEGORY_OUTPUT,
- alias: "l",
- description: "Print the names of files that are different from Prettier's formatting (see also --check)."
- },
- loglevel: {
- type: "choice",
- description: "What level of logs to report.",
- default: "log",
- choices: ["silent", "error", "warn", "log", "debug"]
- },
- stdin: {
- type: "boolean",
- description: "Force reading input from stdin."
- },
- "support-info": {
- type: "boolean",
- description: "Print support information as JSON."
- },
- version: {
- type: "boolean",
- alias: "v",
- description: "Print Prettier version."
- },
- "with-node-modules": {
- type: "boolean",
- category: coreOptions$1.CATEGORY_CONFIG,
- description: "Process files inside 'node_modules' directory."
- },
- write: {
- type: "boolean",
- category: coreOptions$1.CATEGORY_OUTPUT,
- description: "Edit files in-place. (Beware!)"
- }
- };
- var usageSummary = dedent_1`
- Usage: prettier [options] [file/glob ...]
- By default, output is written to stdout.
- Stdin is read if it is piped to Prettier and no files are given.
- `;
- var constant = {
- categoryOrder,
- options: options$21,
- usageSummary
- };
- // which causes unwanted lines in the output. An additional check for isCI() helps.
- // See https://github.com/prettier/prettier/issues/5801
- var isTty = function isTTY() {
- return process.stdout.isTTY && !thirdParty$1.isCI();
- };
- var OPTION_USAGE_THRESHOLD = 25;
- var CHOICE_USAGE_MARGIN = 3;
- var CHOICE_USAGE_INDENTATION = 2;
- function getOptions(argv, detailedOptions) {
- return detailedOptions.filter(function (option) {
- return option.forwardToApi;
- }).reduce(function (current, option) {
- return Object.assign(current, {
- [option.forwardToApi]: argv[option.name]
- });
- }, {});
- }
- function cliifyOptions(object, apiDetailedOptionMap) {
- return Object.keys(object || {}).reduce(function (output, key) {
- var apiOption = apiDetailedOptionMap[key];
- var cliKey = apiOption ? apiOption.name : key;
- output[dashify(cliKey)] = object[key];
- return output;
- }, {});
- }
- function diff(a, b) {
- return lib.createTwoFilesPatch("", "", a, b, "", "", {
- context: 2
- });
- }
- function handleError(context, filename, error) {
- if (error instanceof errors.UndefinedParserError) {
- if (context.argv["write"] && isTty()) {
- readline.clearLine(process.stdout, 0);
- readline.cursorTo(process.stdout, 0, null);
- }
- if (!context.argv["check"] && !context.argv["list-different"]) {
- process.exitCode = 2;
- }
- context.logger.error(error.message);
- return;
- }
- if (context.argv["write"]) {
- // Add newline to split errors from filename line.
- process.stdout.write("\n");
- }
- var isParseError = Boolean(error && error.loc);
- var isValidationError = /Validation Error/.test(error && error.message); // For parse errors and validation errors, we only want to show the error
- // message formatted in a nice way. `String(error)` takes care of that. Other
- // (unexpected) errors are passed as-is as a separate argument to
- // `console.error`. That includes the stack trace (if any), and shows a nice
- // `util.inspect` of throws things that aren't `Error` objects. (The Flow
- // parser has mistakenly thrown arrays sometimes.)
- if (isParseError) {
- context.logger.error(`${filename}: ${String(error)}`);
- } else if (isValidationError || error instanceof errors.ConfigError) {
- context.logger.error(String(error)); // If validation fails for one file, it will fail for all of them.
- process.exit(1);
- } else if (error instanceof errors.DebugError) {
- context.logger.error(`${filename}: ${error.message}`);
- } else {
- context.logger.error(filename + ": " + (error.stack || error));
- } // Don't exit the process if one file failed
- process.exitCode = 2;
- }
- function logResolvedConfigPathOrDie(context) {
- var configFile = prettier$2.resolveConfigFile.sync(context.argv["find-config-path"]);
- if (configFile) {
- context.logger.log(path.relative(process.cwd(), configFile));
- } else {
- process.exit(1);
- }
- }
- function logFileInfoOrDie(context) {
- var options$$2 = {
- ignorePath: context.argv["ignore-path"],
- withNodeModules: context.argv["with-node-modules"],
- plugins: context.argv["plugin"],
- pluginSearchDirs: context.argv["plugin-search-dir"]
- };
- context.logger.log(prettier$2.format(jsonStableStringify(prettier$2.getFileInfo.sync(context.argv["file-info"], options$$2)), {
- parser: "json"
- }));
- }
- function writeOutput(context, result, options$$2) {
- // Don't use `console.log` here since it adds an extra newline at the end.
- process.stdout.write(context.argv["debug-check"] ? result.filepath : result.formatted);
- if (options$$2 && options$$2.cursorOffset >= 0) {
- process.stderr.write(result.cursorOffset + "\n");
- }
- }
- function listDifferent(context, input, options$$2, filename) {
- if (!context.argv["check"] && !context.argv["list-different"]) {
- return;
- }
- try {
- if (!options$$2.filepath && !options$$2.parser) {
- throw new errors.UndefinedParserError("No parser and no file path given, couldn't infer a parser.");
- }
- if (!prettier$2.check(input, options$$2)) {
- if (!context.argv["write"]) {
- context.logger.log(filename);
- process.exitCode = 1;
- }
- }
- } catch (error) {
- context.logger.error(error.message);
- }
- return true;
- }
- function format$1(context, input, opt) {
- if (!opt.parser && !opt.filepath) {
- throw new errors.UndefinedParserError("No parser and no file path given, couldn't infer a parser.");
- }
- if (context.argv["debug-print-doc"]) {
- var doc = prettier$2.__debug.printToDoc(input, opt);
- return {
- formatted: prettier$2.__debug.formatDoc(doc)
- };
- }
- if (context.argv["debug-check"]) {
- var pp = prettier$2.format(input, opt);
- var pppp = prettier$2.format(pp, opt);
- if (pp !== pppp) {
- throw new errors.DebugError("prettier(input) !== prettier(prettier(input))\n" + diff(pp, pppp));
- } else {
- var _stringify = function _stringify(obj) {
- return JSON.stringify(obj, null, 2);
- };
- var ast = _stringify(prettier$2.__debug.parse(input, opt,
- /* massage */
- true).ast);
- var past = _stringify(prettier$2.__debug.parse(pp, opt,
- /* massage */
- true).ast);
- if (ast !== past) {
- var MAX_AST_SIZE = 2097152; // 2MB
- var astDiff = ast.length > MAX_AST_SIZE || past.length > MAX_AST_SIZE ? "AST diff too large to render" : diff(ast, past);
- throw new errors.DebugError("ast(input) !== ast(prettier(input))\n" + astDiff + "\n" + diff(input, pp));
- }
- }
- return {
- formatted: pp,
- filepath: opt.filepath || "(stdin)\n"
- };
- }
- /* istanbul ignore if */
- if (context.argv["debug-benchmark"]) {
- var benchmark;
- try {
- benchmark = require("benchmark");
- } catch (err) {
- context.logger.debug("'--debug-benchmark' requires the 'benchmark' package to be installed.");
- process.exit(2);
- }
- context.logger.debug("'--debug-benchmark' option found, measuring formatWithCursor with 'benchmark' module.");
- var suite = new benchmark.Suite();
- suite.add("format", function () {
- prettier$2.formatWithCursor(input, opt);
- }).on("cycle", function (event) {
- var results = {
- benchmark: String(event.target),
- hz: event.target.hz,
- ms: event.target.times.cycle * 1000
- };
- context.logger.debug("'--debug-benchmark' measurements for formatWithCursor: " + JSON.stringify(results, null, 2));
- }).run({
- async: false
- });
- } else if (context.argv["debug-repeat"] > 0) {
- var repeat = context.argv["debug-repeat"];
- context.logger.debug("'--debug-repeat' option found, running formatWithCursor " + repeat + " times."); // should be using `performance.now()`, but only `Date` is cross-platform enough
- var now = Date.now ? function () {
- return Date.now();
- } : function () {
- return +new Date();
- };
- var totalMs = 0;
- for (var i = 0; i < repeat; ++i) {
- var startMs = now();
- prettier$2.formatWithCursor(input, opt);
- totalMs += now() - startMs;
- }
- var averageMs = totalMs / repeat;
- var results = {
- repeat,
- hz: 1000 / averageMs,
- ms: averageMs
- };
- context.logger.debug("'--debug-repeat' measurements for formatWithCursor: " + JSON.stringify(results, null, 2));
- }
- return prettier$2.formatWithCursor(input, opt);
- }
- function getOptionsOrDie(context, filePath) {
- try {
- if (context.argv["config"] === false) {
- context.logger.debug("'--no-config' option found, skip loading config file.");
- return null;
- }
- context.logger.debug(context.argv["config"] ? `load config file from '${context.argv["config"]}'` : `resolve config from '${filePath}'`);
- var options$$2 = prettier$2.resolveConfig.sync(filePath, {
- editorconfig: context.argv["editorconfig"],
- config: context.argv["config"]
- });
- context.logger.debug("loaded options `" + JSON.stringify(options$$2) + "`");
- return options$$2;
- } catch (error) {
- context.logger.error("Invalid configuration file: " + error.message);
- process.exit(2);
- }
- }
- function getOptionsForFile(context, filepath) {
- var options$$2 = getOptionsOrDie(context, filepath);
- var hasPlugins = options$$2 && options$$2.plugins;
- if (hasPlugins) {
- pushContextPlugins(context, options$$2.plugins);
- }
- var appliedOptions = Object.assign({
- filepath
- }, applyConfigPrecedence(context, options$$2 && optionsNormalizer.normalizeApiOptions(options$$2, context.supportOptions, {
- logger: context.logger
- })));
- context.logger.debug(`applied config-precedence (${context.argv["config-precedence"]}): ` + `${JSON.stringify(appliedOptions)}`);
- if (hasPlugins) {
- popContextPlugins(context);
- }
- return appliedOptions;
- }
- function parseArgsToOptions(context, overrideDefaults) {
- var minimistOptions = createMinimistOptions(context.detailedOptions);
- var apiDetailedOptionMap = createApiDetailedOptionMap(context.detailedOptions);
- return getOptions(optionsNormalizer.normalizeCliOptions(minimist_1(context.args, Object.assign({
- string: minimistOptions.string,
- boolean: minimistOptions.boolean,
- default: cliifyOptions(overrideDefaults, apiDetailedOptionMap)
- })), context.detailedOptions, {
- logger: false
- }), context.detailedOptions);
- }
- function applyConfigPrecedence(context, options$$2) {
- try {
- switch (context.argv["config-precedence"]) {
- case "cli-override":
- return parseArgsToOptions(context, options$$2);
- case "file-override":
- return Object.assign({}, parseArgsToOptions(context), options$$2);
- case "prefer-file":
- return options$$2 || parseArgsToOptions(context);
- }
- } catch (error) {
- context.logger.error(error.toString());
- process.exit(2);
- }
- }
- function formatStdin(context) {
- var filepath = context.argv["stdin-filepath"] ? path.resolve(process.cwd(), context.argv["stdin-filepath"]) : process.cwd();
- var ignorer = createIgnorerFromContextOrDie(context);
- var relativeFilepath = path.relative(process.cwd(), filepath);
- thirdParty$1.getStream(process.stdin).then(function (input) {
- if (relativeFilepath && ignorer.filter([relativeFilepath]).length === 0) {
- writeOutput(context, {
- formatted: input
- });
- return;
- }
- var options$$2 = getOptionsForFile(context, filepath);
- try {
- if (listDifferent(context, input, options$$2, "(stdin)")) {
- return;
- }
- writeOutput(context, format$1(context, input, options$$2), options$$2);
- } catch (error) {
- handleError(context, "stdin", error);
- }
- });
- }
- function createIgnorerFromContextOrDie(context) {
- try {
- return createIgnorer_1.sync(context.argv["ignore-path"], context.argv["with-node-modules"]);
- } catch (e) {
- context.logger.error(e.message);
- process.exit(2);
- }
- }
- function eachFilename(context, patterns, callback) {
- // The '!./' globs are due to https://github.com/prettier/prettier/issues/2110
- var ignoreNodeModules = context.argv["with-node-modules"] !== true;
- if (ignoreNodeModules) {
- patterns = patterns.concat(["!**/node_modules/**", "!./node_modules/**"]);
- }
- patterns = patterns.concat(["!**/.{git,svn,hg}/**", "!./.{git,svn,hg}/**"]);
- try {
- var filePaths = globby.sync(patterns, {
- dot: true,
- nodir: true
- }).map(function (filePath) {
- return path.relative(process.cwd(), filePath);
- });
- if (filePaths.length === 0) {
- context.logger.error(`No matching files. Patterns tried: ${patterns.join(" ")}`);
- process.exitCode = 2;
- return;
- }
- filePaths.forEach(function (filePath) {
- return callback(filePath, Object.assign(getOptionsForFile(context, filePath), {
- filepath: filePath
- }));
- });
- } catch (error) {
- context.logger.error(`Unable to expand glob patterns: ${patterns.join(" ")}\n${error.message}`); // Don't exit the process if one pattern failed
- process.exitCode = 2;
- }
- }
- function formatFiles(context) {
- // The ignorer will be used to filter file paths after the glob is checked,
- // before any files are actually written
- var ignorer = createIgnorerFromContextOrDie(context);
- var numberOfUnformattedFilesFound = 0;
- if (context.argv["check"]) {
- context.logger.log("Checking formatting...");
- }
- eachFilename(context, context.filePatterns, function (filename, options$$2) {
- var fileIgnored = ignorer.filter([filename]).length === 0;
- if (fileIgnored && (context.argv["debug-check"] || context.argv["write"] || context.argv["check"] || context.argv["list-different"])) {
- return;
- }
- if (isTty()) {
- // Don't use `console.log` here since we need to replace this line.
- context.logger.log(filename, {
- newline: false
- });
- }
- var input;
- try {
- input = fs.readFileSync(filename, "utf8");
- } catch (error) {
- // Add newline to split errors from filename line.
- context.logger.log("");
- context.logger.error(`Unable to read file: ${filename}\n${error.message}`); // Don't exit the process if one file failed
- process.exitCode = 2;
- return;
- }
- if (fileIgnored) {
- writeOutput(context, {
- formatted: input
- }, options$$2);
- return;
- }
- var start = Date.now();
- var result;
- var output;
- try {
- result = format$1(context, input, Object.assign({}, options$$2, {
- filepath: filename
- }));
- output = result.formatted;
- } catch (error) {
- handleError(context, filename, error);
- return;
- }
- var isDifferent = output !== input;
- if (isTty()) {
- // Remove previously printed filename to log it with duration.
- readline.clearLine(process.stdout, 0);
- readline.cursorTo(process.stdout, 0, null);
- }
- if (context.argv["write"]) {
- // Don't write the file if it won't change in order not to invalidate
- // mtime based caches.
- if (isDifferent) {
- if (!context.argv["check"] && !context.argv["list-different"]) {
- context.logger.log(`${filename} ${Date.now() - start}ms`);
- }
- try {
- fs.writeFileSync(filename, output, "utf8");
- } catch (error) {
- context.logger.error(`Unable to write file: ${filename}\n${error.message}`); // Don't exit the process if one file failed
- process.exitCode = 2;
- }
- } else if (!context.argv["check"] && !context.argv["list-different"]) {
- context.logger.log(`${chalk$2.grey(filename)} ${Date.now() - start}ms`);
- }
- } else if (context.argv["debug-check"]) {
- if (result.filepath) {
- context.logger.log(result.filepath);
- } else {
- process.exitCode = 2;
- }
- } else if (!context.argv["check"] && !context.argv["list-different"]) {
- writeOutput(context, result, options$$2);
- }
- if ((context.argv["check"] || context.argv["list-different"]) && isDifferent) {
- context.logger.log(filename);
- numberOfUnformattedFilesFound += 1;
- }
- }); // Print check summary based on expected exit code
- if (context.argv["check"]) {
- context.logger.log(numberOfUnformattedFilesFound === 0 ? "All matched files use Prettier code style!" : 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?");
- } // Ensure non-zero exitCode when using --check/list-different is not combined with --write
- if ((context.argv["check"] || context.argv["list-different"]) && numberOfUnformattedFilesFound > 0 && !process.exitCode && !context.argv["write"]) {
- process.exitCode = 1;
- }
- }
- function getOptionsWithOpposites(options$$2) {
- // Add --no-foo after --foo.
- var optionsWithOpposites = options$$2.map(function (option) {
- return [option.description ? option : null, option.oppositeDescription ? Object.assign({}, option, {
- name: `no-${option.name}`,
- type: "boolean",
- description: option.oppositeDescription
- }) : null];
- });
- return flattenArray(optionsWithOpposites).filter(Boolean);
- }
- function createUsage(context) {
- var options$$2 = getOptionsWithOpposites(context.detailedOptions).filter( // remove unnecessary option (e.g. `semi`, `color`, etc.), which is only used for --help <flag>
- function (option) {
- return !(option.type === "boolean" && option.oppositeDescription && !option.name.startsWith("no-"));
- });
- var groupedOptions = groupBy(options$$2, function (option) {
- return option.category;
- });
- var firstCategories = constant.categoryOrder.slice(0, -1);
- var lastCategories = constant.categoryOrder.slice(-1);
- var restCategories = Object.keys(groupedOptions).filter(function (category) {
- return firstCategories.indexOf(category) === -1 && lastCategories.indexOf(category) === -1;
- });
- var allCategories = firstCategories.concat(restCategories, lastCategories);
- var optionsUsage = allCategories.map(function (category) {
- var categoryOptions = groupedOptions[category].map(function (option) {
- return createOptionUsage(context, option, OPTION_USAGE_THRESHOLD);
- }).join("\n");
- return `${category} options:\n\n${indent$11(categoryOptions, 2)}`;
- });
- return [constant.usageSummary].concat(optionsUsage, [""]).join("\n\n");
- }
- function createOptionUsage(context, option, threshold) {
- var header = createOptionUsageHeader(option);
- var optionDefaultValue = getOptionDefaultValue(context, option.name);
- return createOptionUsageRow(header, `${option.description}${optionDefaultValue === undefined ? "" : `\nDefaults to ${createDefaultValueDisplay(optionDefaultValue)}.`}`, threshold);
- }
- function createDefaultValueDisplay(value) {
- return Array.isArray(value) ? `[${value.map(createDefaultValueDisplay).join(", ")}]` : value;
- }
- function createOptionUsageHeader(option) {
- var name = `--${option.name}`;
- var alias = option.alias ? `-${option.alias},` : null;
- var type = createOptionUsageType(option);
- return [alias, name, type].filter(Boolean).join(" ");
- }
- function createOptionUsageRow(header, content, threshold) {
- var separator = header.length >= threshold ? `\n${" ".repeat(threshold)}` : " ".repeat(threshold - header.length);
- var description = content.replace(/\n/g, `\n${" ".repeat(threshold)}`);
- return `${header}${separator}${description}`;
- }
- function createOptionUsageType(option) {
- switch (option.type) {
- case "boolean":
- return null;
- case "choice":
- return `<${option.choices.filter(function (choice) {
- return choice.since !== null;
- }).filter(function (choice) {
- return !choice.deprecated;
- }).map(function (choice) {
- return choice.value;
- }).join("|")}>`;
- default:
- return `<${option.type}>`;
- }
- }
- function flattenArray(array) {
- return [].concat.apply([], array);
- }
- function createChoiceUsages(choices, margin, indentation) {
- var activeChoices = choices.filter(function (choice) {
- return !choice.deprecated && choice.since !== null;
- });
- var threshold = activeChoices.map(function (choice) {
- return choice.value.length;
- }).reduce(function (current, length) {
- return Math.max(current, length);
- }, 0) + margin;
- return activeChoices.map(function (choice) {
- return indent$11(createOptionUsageRow(choice.value, choice.description, threshold), indentation);
- });
- }
- function createDetailedUsage(context, flag) {
- var option = getOptionsWithOpposites(context.detailedOptions).find(function (option) {
- return option.name === flag || option.alias === flag;
- });
- var header = createOptionUsageHeader(option);
- var description = `\n\n${indent$11(option.description, 2)}`;
- var choices = option.type !== "choice" ? "" : `\n\nValid options:\n\n${createChoiceUsages(option.choices, CHOICE_USAGE_MARGIN, CHOICE_USAGE_INDENTATION).join("\n")}`;
- var optionDefaultValue = getOptionDefaultValue(context, option.name);
- var defaults = optionDefaultValue !== undefined ? `\n\nDefault: ${createDefaultValueDisplay(optionDefaultValue)}` : "";
- var pluginDefaults = option.pluginDefaults && Object.keys(option.pluginDefaults).length ? `\nPlugin defaults:${Object.keys(option.pluginDefaults).map(function (key) {
- return `\n* ${key}: ${createDefaultValueDisplay(option.pluginDefaults[key])}`;
- })}` : "";
- return `${header}${description}${choices}${defaults}${pluginDefaults}`;
- }
- function getOptionDefaultValue(context, optionName) {
- // --no-option
- if (!(optionName in context.detailedOptionMap)) {
- return undefined;
- }
- var option = context.detailedOptionMap[optionName];
- if (option.default !== undefined) {
- return option.default;
- }
- var optionCamelName = camelcase(optionName);
- if (optionCamelName in context.apiDefaultOptions) {
- return context.apiDefaultOptions[optionCamelName];
- }
- return undefined;
- }
- function indent$11(str, spaces) {
- return str.replace(/^/gm, " ".repeat(spaces));
- }
- function groupBy(array, getKey) {
- return array.reduce(function (obj, item) {
- var key = getKey(item);
- var previousItems = key in obj ? obj[key] : [];
- return Object.assign({}, obj, {
- [key]: previousItems.concat(item)
- });
- }, Object.create(null));
- }
- function pick(object, keys) {
- return !keys ? object : keys.reduce(function (reduced, key) {
- return Object.assign(reduced, {
- [key]: object[key]
- });
- }, {});
- }
- function createLogger(logLevel) {
- return {
- warn: createLogFunc("warn", "yellow"),
- error: createLogFunc("error", "red"),
- debug: createLogFunc("debug", "blue"),
- log: createLogFunc("log")
- };
- function createLogFunc(loggerName, color) {
- if (!shouldLog(loggerName)) {
- return function () {};
- }
- var prefix = color ? `[${chalk$2[color](loggerName)}] ` : "";
- return function (message, opts) {
- opts = Object.assign({
- newline: true
- }, opts);
- var stream = process[loggerName === "log" ? "stdout" : "stderr"];
- stream.write(message.replace(/^/gm, prefix) + (opts.newline ? "\n" : ""));
- };
- }
- function shouldLog(loggerName) {
- switch (logLevel) {
- case "silent":
- return false;
- default:
- return true;
- case "debug":
- if (loggerName === "debug") {
- return true;
- }
- // fall through
- case "log":
- if (loggerName === "log") {
- return true;
- }
- // fall through
- case "warn":
- if (loggerName === "warn") {
- return true;
- }
- // fall through
- case "error":
- return loggerName === "error";
- }
- }
- }
- function normalizeDetailedOption(name, option) {
- return Object.assign({
- category: coreOptions$1.CATEGORY_OTHER
- }, option, {
- choices: option.choices && option.choices.map(function (choice) {
- var newChoice = Object.assign({
- description: "",
- deprecated: false
- }, typeof choice === "object" ? choice : {
- value: choice
- });
- if (newChoice.value === true) {
- newChoice.value = ""; // backward compability for original boolean option
- }
- return newChoice;
- })
- });
- }
- function normalizeDetailedOptionMap(detailedOptionMap) {
- return Object.keys(detailedOptionMap).sort().reduce(function (normalized, name) {
- var option = detailedOptionMap[name];
- return Object.assign(normalized, {
- [name]: normalizeDetailedOption(name, option)
- });
- }, {});
- }
- function createMinimistOptions(detailedOptions) {
- return {
- // we use vnopts' AliasSchema to handle aliases for better error messages
- alias: {},
- boolean: detailedOptions.filter(function (option) {
- return option.type === "boolean";
- }).map(function (option) {
- return [option.name].concat(option.alias || []);
- }).reduce(function (a, b) {
- return a.concat(b);
- }),
- string: detailedOptions.filter(function (option) {
- return option.type !== "boolean";
- }).map(function (option) {
- return [option.name].concat(option.alias || []);
- }).reduce(function (a, b) {
- return a.concat(b);
- }),
- default: detailedOptions.filter(function (option) {
- return !option.deprecated;
- }).filter(function (option) {
- return !option.forwardToApi || option.name === "plugin" || option.name === "plugin-search-dir";
- }).filter(function (option) {
- return option.default !== undefined;
- }).reduce(function (current, option) {
- return Object.assign({
- [option.name]: option.default
- }, current);
- }, {})
- };
- }
- function createApiDetailedOptionMap(detailedOptions) {
- return detailedOptions.reduce(function (current, option) {
- return option.forwardToApi && option.forwardToApi !== option.name ? Object.assign(current, {
- [option.forwardToApi]: option
- }) : current;
- }, {});
- }
- function createDetailedOptionMap(supportOptions) {
- return supportOptions.reduce(function (reduced, option) {
- var newOption = Object.assign({}, option, {
- name: option.cliName || dashify(option.name),
- description: option.cliDescription || option.description,
- category: option.cliCategory || coreOptions$1.CATEGORY_FORMAT,
- forwardToApi: option.name
- });
- if (option.deprecated) {
- delete newOption.forwardToApi;
- delete newOption.description;
- delete newOption.oppositeDescription;
- newOption.deprecated = true;
- }
- return Object.assign(reduced, {
- [newOption.name]: newOption
- });
- }, {});
- } //-----------------------------context-util-start-------------------------------
- /**
- * @typedef {Object} Context
- * @property logger
- * @property args
- * @property argv
- * @property filePatterns
- * @property supportOptions
- * @property detailedOptions
- * @property detailedOptionMap
- * @property apiDefaultOptions
- */
- function createContext(args) {
- var context = {
- args
- };
- updateContextArgv(context);
- normalizeContextArgv(context, ["loglevel", "plugin", "plugin-search-dir"]);
- context.logger = createLogger(context.argv["loglevel"]);
- updateContextArgv(context, context.argv["plugin"], context.argv["plugin-search-dir"]);
- return context;
- }
- function initContext(context) {
- // split into 2 step so that we could wrap this in a `try..catch` in cli/index.js
- normalizeContextArgv(context);
- }
- function updateContextOptions(context, plugins, pluginSearchDirs) {
- var supportOptions = prettier$2.getSupportInfo(null, {
- showDeprecated: true,
- showUnreleased: true,
- showInternal: true,
- plugins,
- pluginSearchDirs
- }).options;
- var detailedOptionMap = normalizeDetailedOptionMap(Object.assign({}, createDetailedOptionMap(supportOptions), constant.options));
- var detailedOptions = arrayify(detailedOptionMap, "name");
- var apiDefaultOptions = supportOptions.filter(function (optionInfo) {
- return !optionInfo.deprecated;
- }).reduce(function (reduced, optionInfo) {
- return Object.assign(reduced, {
- [optionInfo.name]: optionInfo.default
- });
- }, Object.assign({}, options.hiddenDefaults));
- context.supportOptions = supportOptions;
- context.detailedOptions = detailedOptions;
- context.detailedOptionMap = detailedOptionMap;
- context.apiDefaultOptions = apiDefaultOptions;
- }
- function pushContextPlugins(context, plugins, pluginSearchDirs) {
- context._supportOptions = context.supportOptions;
- context._detailedOptions = context.detailedOptions;
- context._detailedOptionMap = context.detailedOptionMap;
- context._apiDefaultOptions = context.apiDefaultOptions;
- updateContextOptions(context, plugins, pluginSearchDirs);
- }
- function popContextPlugins(context) {
- context.supportOptions = context._supportOptions;
- context.detailedOptions = context._detailedOptions;
- context.detailedOptionMap = context._detailedOptionMap;
- context.apiDefaultOptions = context._apiDefaultOptions;
- }
- function updateContextArgv(context, plugins, pluginSearchDirs) {
- pushContextPlugins(context, plugins, pluginSearchDirs);
- var minimistOptions = createMinimistOptions(context.detailedOptions);
- var argv = minimist_1(context.args, minimistOptions);
- context.argv = argv;
- context.filePatterns = argv["_"];
- }
- function normalizeContextArgv(context, keys) {
- var detailedOptions = !keys ? context.detailedOptions : context.detailedOptions.filter(function (option) {
- return keys.indexOf(option.name) !== -1;
- });
- var argv = !keys ? context.argv : pick(context.argv, keys);
- context.argv = optionsNormalizer.normalizeCliOptions(argv, detailedOptions, {
- logger: context.logger
- });
- } //------------------------------context-util-end--------------------------------
- var util$5 = {
- createContext,
- createDetailedOptionMap,
- createDetailedUsage,
- createUsage,
- format: format$1,
- formatFiles,
- formatStdin,
- initContext,
- logResolvedConfigPathOrDie,
- logFileInfoOrDie,
- normalizeDetailedOptionMap
- };
- function run(args) {
- var context = util$5.createContext(args);
- try {
- util$5.initContext(context);
- context.logger.debug(`normalized argv: ${JSON.stringify(context.argv)}`);
- if (context.argv["check"] && context.argv["list-different"]) {
- context.logger.error("Cannot use --check and --list-different together.");
- process.exit(1);
- }
- if (context.argv["write"] && context.argv["debug-check"]) {
- context.logger.error("Cannot use --write and --debug-check together.");
- process.exit(1);
- }
- if (context.argv["find-config-path"] && context.filePatterns.length) {
- context.logger.error("Cannot use --find-config-path with multiple files");
- process.exit(1);
- }
- if (context.argv["file-info"] && context.filePatterns.length) {
- context.logger.error("Cannot use --file-info with multiple files");
- process.exit(1);
- }
- if (context.argv["version"]) {
- context.logger.log(prettier$2.version);
- process.exit(0);
- }
- if (context.argv["help"] !== undefined) {
- context.logger.log(typeof context.argv["help"] === "string" && context.argv["help"] !== "" ? util$5.createDetailedUsage(context, context.argv["help"]) : util$5.createUsage(context));
- process.exit(0);
- }
- if (context.argv["support-info"]) {
- context.logger.log(prettier$2.format(jsonStableStringify(prettier$2.getSupportInfo()), {
- parser: "json"
- }));
- process.exit(0);
- }
- var hasFilePatterns = context.filePatterns.length !== 0;
- var useStdin = context.argv["stdin"] || !hasFilePatterns && !process.stdin.isTTY;
- if (context.argv["find-config-path"]) {
- util$5.logResolvedConfigPathOrDie(context);
- } else if (context.argv["file-info"]) {
- util$5.logFileInfoOrDie(context);
- } else if (useStdin) {
- util$5.formatStdin(context);
- } else if (hasFilePatterns) {
- util$5.formatFiles(context);
- } else {
- context.logger.log(util$5.createUsage(context));
- process.exit(1);
- }
- } catch (error) {
- context.logger.error(error.message);
- process.exit(1);
- }
- }
- var cli = {
- run
- };
- cli.run(process.argv.slice(2));
- var prettier = {};
- module.exports = prettier;
|