dep-689425f3.js 1.9 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105
  1. 'use strict';
  2. var fs$n = require('fs');
  3. var path$r = require('path');
  4. var require$$0$6 = require('url');
  5. var perf_hooks = require('perf_hooks');
  6. var require$$0$2 = require('tty');
  7. var require$$2 = require('os');
  8. var esbuild = require('esbuild');
  9. var require$$0$3 = require('events');
  10. var require$$5 = require('assert');
  11. var resolve$4 = require('resolve');
  12. var require$$0$4 = require('util');
  13. var require$$0$5 = require('stream');
  14. var require$$3 = require('net');
  15. var require$$1$2 = require('http');
  16. var require$$2$1 = require('child_process');
  17. var require$$0$7 = require('module');
  18. var require$$1$1 = require('crypto');
  19. var require$$0$8 = require('buffer');
  20. var qs = require('querystring');
  21. var zlib$1 = require('zlib');
  22. var require$$1$3 = require('https');
  23. var require$$4 = require('tls');
  24. var require$$1 = require('worker_threads');
  25. var readline = require('readline');
  26. function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e["default"] : e; }
  27. function _interopNamespace(e) {
  28. if (e && e.__esModule) return e;
  29. var n = Object.create(null);
  30. if (e) {
  31. for (var k in e) {
  32. n[k] = e[k];
  33. }
  34. }
  35. n["default"] = e;
  36. return n;
  37. }
  38. var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs$n);
  39. var fs__namespace = /*#__PURE__*/_interopNamespace(fs$n);
  40. var path__default = /*#__PURE__*/_interopDefaultLegacy(path$r);
  41. var require$$0__default$5 = /*#__PURE__*/_interopDefaultLegacy(require$$0$6);
  42. var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0$2);
  43. var require$$2__default = /*#__PURE__*/_interopDefaultLegacy(require$$2);
  44. var require$$0__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$0$3);
  45. var require$$5__default = /*#__PURE__*/_interopDefaultLegacy(require$$5);
  46. var resolve__default = /*#__PURE__*/_interopDefaultLegacy(resolve$4);
  47. var require$$0__default$2 = /*#__PURE__*/_interopDefaultLegacy(require$$0$4);
  48. var require$$0__default$3 = /*#__PURE__*/_interopDefaultLegacy(require$$0$5);
  49. var require$$3__default = /*#__PURE__*/_interopDefaultLegacy(require$$3);
  50. var require$$1__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$1$2);
  51. var require$$2__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$2$1);
  52. var require$$0__default$4 = /*#__PURE__*/_interopDefaultLegacy(require$$0$7);
  53. var require$$1__default$2 = /*#__PURE__*/_interopDefaultLegacy(require$$1$1);
  54. var require$$0__default$6 = /*#__PURE__*/_interopDefaultLegacy(require$$0$8);
  55. var qs__namespace = /*#__PURE__*/_interopNamespace(qs);
  56. var zlib__default = /*#__PURE__*/_interopDefaultLegacy(zlib$1);
  57. var require$$1__default$3 = /*#__PURE__*/_interopDefaultLegacy(require$$1$3);
  58. var require$$4__default = /*#__PURE__*/_interopDefaultLegacy(require$$4);
  59. var require$$1__default = /*#__PURE__*/_interopDefaultLegacy(require$$1);
  60. var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);
  61. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  62. function getDefaultExportFromCjs (x) {
  63. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  64. }
  65. function getAugmentedNamespace(n) {
  66. if (n.__esModule) return n;
  67. var a = Object.defineProperty({}, '__esModule', {value: true});
  68. Object.keys(n).forEach(function (k) {
  69. var d = Object.getOwnPropertyDescriptor(n, k);
  70. Object.defineProperty(a, k, d.get ? d : {
  71. enumerable: true,
  72. get: function () {
  73. return n[k];
  74. }
  75. });
  76. });
  77. return a;
  78. }
  79. var picocolors = {exports: {}};
  80. let tty = require$$0__default;
  81. let isColorSupported =
  82. !("NO_COLOR" in process.env || process.argv.includes("--no-color")) &&
  83. ("FORCE_COLOR" in process.env ||
  84. process.argv.includes("--color") ||
  85. process.platform === "win32" ||
  86. (tty.isatty(1) && process.env.TERM !== "dumb") ||
  87. "CI" in process.env);
  88. let formatter =
  89. (open, close, replace = open) =>
  90. input => {
  91. let string = "" + input;
  92. let index = string.indexOf(close, open.length);
  93. return ~index
  94. ? open + replaceClose(string, close, replace, index) + close
  95. : open + string + close
  96. };
  97. let replaceClose = (string, close, replace, index) => {
  98. let start = string.substring(0, index) + replace;
  99. let end = string.substring(index + close.length);
  100. let nextIndex = end.indexOf(close);
  101. return ~nextIndex ? start + replaceClose(end, close, replace, nextIndex) : start + end
  102. };
  103. let createColors = (enabled = isColorSupported) => ({
  104. isColorSupported: enabled,
  105. reset: enabled ? s => `\x1b[0m${s}\x1b[0m` : String,
  106. bold: enabled ? formatter("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m") : String,
  107. dim: enabled ? formatter("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m") : String,
  108. italic: enabled ? formatter("\x1b[3m", "\x1b[23m") : String,
  109. underline: enabled ? formatter("\x1b[4m", "\x1b[24m") : String,
  110. inverse: enabled ? formatter("\x1b[7m", "\x1b[27m") : String,
  111. hidden: enabled ? formatter("\x1b[8m", "\x1b[28m") : String,
  112. strikethrough: enabled ? formatter("\x1b[9m", "\x1b[29m") : String,
  113. black: enabled ? formatter("\x1b[30m", "\x1b[39m") : String,
  114. red: enabled ? formatter("\x1b[31m", "\x1b[39m") : String,
  115. green: enabled ? formatter("\x1b[32m", "\x1b[39m") : String,
  116. yellow: enabled ? formatter("\x1b[33m", "\x1b[39m") : String,
  117. blue: enabled ? formatter("\x1b[34m", "\x1b[39m") : String,
  118. magenta: enabled ? formatter("\x1b[35m", "\x1b[39m") : String,
  119. cyan: enabled ? formatter("\x1b[36m", "\x1b[39m") : String,
  120. white: enabled ? formatter("\x1b[37m", "\x1b[39m") : String,
  121. gray: enabled ? formatter("\x1b[90m", "\x1b[39m") : String,
  122. bgBlack: enabled ? formatter("\x1b[40m", "\x1b[49m") : String,
  123. bgRed: enabled ? formatter("\x1b[41m", "\x1b[49m") : String,
  124. bgGreen: enabled ? formatter("\x1b[42m", "\x1b[49m") : String,
  125. bgYellow: enabled ? formatter("\x1b[43m", "\x1b[49m") : String,
  126. bgBlue: enabled ? formatter("\x1b[44m", "\x1b[49m") : String,
  127. bgMagenta: enabled ? formatter("\x1b[45m", "\x1b[49m") : String,
  128. bgCyan: enabled ? formatter("\x1b[46m", "\x1b[49m") : String,
  129. bgWhite: enabled ? formatter("\x1b[47m", "\x1b[49m") : String,
  130. });
  131. picocolors.exports = createColors();
  132. picocolors.exports.createColors = createColors;
  133. var colors$1 = picocolors.exports;
  134. var main$1 = {exports: {}};
  135. const fs$m = fs__default;
  136. const path$q = path__default;
  137. const os$2 = require$$2__default;
  138. function log (message) {
  139. console.log(`[dotenv][DEBUG] ${message}`);
  140. }
  141. const NEWLINE = '\n';
  142. const RE_INI_KEY_VAL = /^\s*([\w.-]+)\s*=\s*("[^"]*"|'[^']*'|.*?)(\s+#.*)?$/;
  143. const RE_NEWLINES = /\\n/g;
  144. const NEWLINES_MATCH = /\r\n|\n|\r/;
  145. // Parses src into an Object
  146. function parse$o (src, options) {
  147. const debug = Boolean(options && options.debug);
  148. const multiline = Boolean(options && options.multiline);
  149. const obj = {};
  150. // convert Buffers before splitting into lines and processing
  151. const lines = src.toString().split(NEWLINES_MATCH);
  152. for (let idx = 0; idx < lines.length; idx++) {
  153. let line = lines[idx];
  154. // matching "KEY' and 'VAL' in 'KEY=VAL'
  155. const keyValueArr = line.match(RE_INI_KEY_VAL);
  156. // matched?
  157. if (keyValueArr != null) {
  158. const key = keyValueArr[1];
  159. // default undefined or missing values to empty string
  160. let val = (keyValueArr[2] || '');
  161. let end = val.length - 1;
  162. const isDoubleQuoted = val[0] === '"' && val[end] === '"';
  163. const isSingleQuoted = val[0] === "'" && val[end] === "'";
  164. const isMultilineDoubleQuoted = val[0] === '"' && val[end] !== '"';
  165. const isMultilineSingleQuoted = val[0] === "'" && val[end] !== "'";
  166. // if parsing line breaks and the value starts with a quote
  167. if (multiline && (isMultilineDoubleQuoted || isMultilineSingleQuoted)) {
  168. const quoteChar = isMultilineDoubleQuoted ? '"' : "'";
  169. val = val.substring(1);
  170. while (idx++ < lines.length - 1) {
  171. line = lines[idx];
  172. end = line.length - 1;
  173. if (line[end] === quoteChar) {
  174. val += NEWLINE + line.substring(0, end);
  175. break
  176. }
  177. val += NEWLINE + line;
  178. }
  179. // if single or double quoted, remove quotes
  180. } else if (isSingleQuoted || isDoubleQuoted) {
  181. val = val.substring(1, end);
  182. // if double quoted, expand newlines
  183. if (isDoubleQuoted) {
  184. val = val.replace(RE_NEWLINES, NEWLINE);
  185. }
  186. } else {
  187. // remove surrounding whitespace
  188. val = val.trim();
  189. }
  190. obj[key] = val;
  191. } else if (debug) {
  192. const trimmedLine = line.trim();
  193. // ignore empty and commented lines
  194. if (trimmedLine.length && trimmedLine[0] !== '#') {
  195. log(`Failed to match key and value when parsing line ${idx + 1}: ${line}`);
  196. }
  197. }
  198. }
  199. return obj
  200. }
  201. function resolveHome (envPath) {
  202. return envPath[0] === '~' ? path$q.join(os$2.homedir(), envPath.slice(1)) : envPath
  203. }
  204. // Populates process.env from .env file
  205. function config$1 (options) {
  206. let dotenvPath = path$q.resolve(process.cwd(), '.env');
  207. let encoding = 'utf8';
  208. const debug = Boolean(options && options.debug);
  209. const override = Boolean(options && options.override);
  210. const multiline = Boolean(options && options.multiline);
  211. if (options) {
  212. if (options.path != null) {
  213. dotenvPath = resolveHome(options.path);
  214. }
  215. if (options.encoding != null) {
  216. encoding = options.encoding;
  217. }
  218. }
  219. try {
  220. // specifying an encoding returns a string instead of a buffer
  221. const parsed = DotenvModule.parse(fs$m.readFileSync(dotenvPath, { encoding }), { debug, multiline });
  222. Object.keys(parsed).forEach(function (key) {
  223. if (!Object.prototype.hasOwnProperty.call(process.env, key)) {
  224. process.env[key] = parsed[key];
  225. } else {
  226. if (override === true) {
  227. process.env[key] = parsed[key];
  228. }
  229. if (debug) {
  230. if (override === true) {
  231. log(`"${key}" is already defined in \`process.env\` and WAS overwritten`);
  232. } else {
  233. log(`"${key}" is already defined in \`process.env\` and was NOT overwritten`);
  234. }
  235. }
  236. }
  237. });
  238. return { parsed }
  239. } catch (e) {
  240. if (debug) {
  241. log(`Failed to load ${dotenvPath} ${e.message}`);
  242. }
  243. return { error: e }
  244. }
  245. }
  246. const DotenvModule = {
  247. config: config$1,
  248. parse: parse$o
  249. };
  250. main$1.exports.config = DotenvModule.config;
  251. main$1.exports.parse = DotenvModule.parse;
  252. main$1.exports = DotenvModule;
  253. var dotenv = main$1.exports;
  254. var dotenvExpand = function (config) {
  255. // if ignoring process.env, use a blank object
  256. var environment = config.ignoreProcessEnv ? {} : process.env;
  257. var interpolate = function (envValue) {
  258. var matches = envValue.match(/(.?\${?(?:[a-zA-Z0-9_]+)?}?)/g) || [];
  259. return matches.reduce(function (newEnv, match) {
  260. var parts = /(.?)\${?([a-zA-Z0-9_]+)?}?/g.exec(match);
  261. var prefix = parts[1];
  262. var value, replacePart;
  263. if (prefix === '\\') {
  264. replacePart = parts[0];
  265. value = replacePart.replace('\\$', '$');
  266. } else {
  267. var key = parts[2];
  268. replacePart = parts[0].substring(prefix.length);
  269. // process.env value 'wins' over .env file's value
  270. value = environment.hasOwnProperty(key) ? environment[key] : (config.parsed[key] || '');
  271. // Resolve recursive interpolations
  272. value = interpolate(value);
  273. }
  274. return newEnv.replace(replacePart, value)
  275. }, envValue)
  276. };
  277. for (var configKey in config.parsed) {
  278. var value = environment.hasOwnProperty(configKey) ? environment[configKey] : config.parsed[configKey];
  279. config.parsed[configKey] = interpolate(value);
  280. }
  281. for (var processKey in config.parsed) {
  282. environment[processKey] = config.parsed[processKey];
  283. }
  284. return config
  285. };
  286. var main = dotenvExpand;
  287. var utils$p = {};
  288. const path$p = path__default;
  289. const WIN_SLASH$1 = '\\\\/';
  290. const WIN_NO_SLASH$1 = `[^${WIN_SLASH$1}]`;
  291. /**
  292. * Posix glob regex
  293. */
  294. const DOT_LITERAL$1 = '\\.';
  295. const PLUS_LITERAL$1 = '\\+';
  296. const QMARK_LITERAL$1 = '\\?';
  297. const SLASH_LITERAL$1 = '\\/';
  298. const ONE_CHAR$1 = '(?=.)';
  299. const QMARK$1 = '[^/]';
  300. const END_ANCHOR$1 = `(?:${SLASH_LITERAL$1}|$)`;
  301. const START_ANCHOR$1 = `(?:^|${SLASH_LITERAL$1})`;
  302. const DOTS_SLASH$1 = `${DOT_LITERAL$1}{1,2}${END_ANCHOR$1}`;
  303. const NO_DOT$1 = `(?!${DOT_LITERAL$1})`;
  304. const NO_DOTS$1 = `(?!${START_ANCHOR$1}${DOTS_SLASH$1})`;
  305. const NO_DOT_SLASH$1 = `(?!${DOT_LITERAL$1}{0,1}${END_ANCHOR$1})`;
  306. const NO_DOTS_SLASH$1 = `(?!${DOTS_SLASH$1})`;
  307. const QMARK_NO_DOT$1 = `[^.${SLASH_LITERAL$1}]`;
  308. const STAR$2 = `${QMARK$1}*?`;
  309. const POSIX_CHARS$1 = {
  310. DOT_LITERAL: DOT_LITERAL$1,
  311. PLUS_LITERAL: PLUS_LITERAL$1,
  312. QMARK_LITERAL: QMARK_LITERAL$1,
  313. SLASH_LITERAL: SLASH_LITERAL$1,
  314. ONE_CHAR: ONE_CHAR$1,
  315. QMARK: QMARK$1,
  316. END_ANCHOR: END_ANCHOR$1,
  317. DOTS_SLASH: DOTS_SLASH$1,
  318. NO_DOT: NO_DOT$1,
  319. NO_DOTS: NO_DOTS$1,
  320. NO_DOT_SLASH: NO_DOT_SLASH$1,
  321. NO_DOTS_SLASH: NO_DOTS_SLASH$1,
  322. QMARK_NO_DOT: QMARK_NO_DOT$1,
  323. STAR: STAR$2,
  324. START_ANCHOR: START_ANCHOR$1
  325. };
  326. /**
  327. * Windows glob regex
  328. */
  329. const WINDOWS_CHARS$1 = {
  330. ...POSIX_CHARS$1,
  331. SLASH_LITERAL: `[${WIN_SLASH$1}]`,
  332. QMARK: WIN_NO_SLASH$1,
  333. STAR: `${WIN_NO_SLASH$1}*?`,
  334. DOTS_SLASH: `${DOT_LITERAL$1}{1,2}(?:[${WIN_SLASH$1}]|$)`,
  335. NO_DOT: `(?!${DOT_LITERAL$1})`,
  336. NO_DOTS: `(?!(?:^|[${WIN_SLASH$1}])${DOT_LITERAL$1}{1,2}(?:[${WIN_SLASH$1}]|$))`,
  337. NO_DOT_SLASH: `(?!${DOT_LITERAL$1}{0,1}(?:[${WIN_SLASH$1}]|$))`,
  338. NO_DOTS_SLASH: `(?!${DOT_LITERAL$1}{1,2}(?:[${WIN_SLASH$1}]|$))`,
  339. QMARK_NO_DOT: `[^.${WIN_SLASH$1}]`,
  340. START_ANCHOR: `(?:^|[${WIN_SLASH$1}])`,
  341. END_ANCHOR: `(?:[${WIN_SLASH$1}]|$)`
  342. };
  343. /**
  344. * POSIX Bracket Regex
  345. */
  346. const POSIX_REGEX_SOURCE$3 = {
  347. alnum: 'a-zA-Z0-9',
  348. alpha: 'a-zA-Z',
  349. ascii: '\\x00-\\x7F',
  350. blank: ' \\t',
  351. cntrl: '\\x00-\\x1F\\x7F',
  352. digit: '0-9',
  353. graph: '\\x21-\\x7E',
  354. lower: 'a-z',
  355. print: '\\x20-\\x7E ',
  356. punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
  357. space: ' \\t\\r\\n\\v\\f',
  358. upper: 'A-Z',
  359. word: 'A-Za-z0-9_',
  360. xdigit: 'A-Fa-f0-9'
  361. };
  362. var constants$9 = {
  363. MAX_LENGTH: 1024 * 64,
  364. POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$3,
  365. // regular expressions
  366. REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
  367. REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
  368. REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
  369. REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
  370. REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
  371. REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
  372. // Replace globs with equivalent patterns to reduce parsing time.
  373. REPLACEMENTS: {
  374. '***': '*',
  375. '**/**': '**',
  376. '**/**/**': '**'
  377. },
  378. // Digits
  379. CHAR_0: 48, /* 0 */
  380. CHAR_9: 57, /* 9 */
  381. // Alphabet chars.
  382. CHAR_UPPERCASE_A: 65, /* A */
  383. CHAR_LOWERCASE_A: 97, /* a */
  384. CHAR_UPPERCASE_Z: 90, /* Z */
  385. CHAR_LOWERCASE_Z: 122, /* z */
  386. CHAR_LEFT_PARENTHESES: 40, /* ( */
  387. CHAR_RIGHT_PARENTHESES: 41, /* ) */
  388. CHAR_ASTERISK: 42, /* * */
  389. // Non-alphabetic chars.
  390. CHAR_AMPERSAND: 38, /* & */
  391. CHAR_AT: 64, /* @ */
  392. CHAR_BACKWARD_SLASH: 92, /* \ */
  393. CHAR_CARRIAGE_RETURN: 13, /* \r */
  394. CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */
  395. CHAR_COLON: 58, /* : */
  396. CHAR_COMMA: 44, /* , */
  397. CHAR_DOT: 46, /* . */
  398. CHAR_DOUBLE_QUOTE: 34, /* " */
  399. CHAR_EQUAL: 61, /* = */
  400. CHAR_EXCLAMATION_MARK: 33, /* ! */
  401. CHAR_FORM_FEED: 12, /* \f */
  402. CHAR_FORWARD_SLASH: 47, /* / */
  403. CHAR_GRAVE_ACCENT: 96, /* ` */
  404. CHAR_HASH: 35, /* # */
  405. CHAR_HYPHEN_MINUS: 45, /* - */
  406. CHAR_LEFT_ANGLE_BRACKET: 60, /* < */
  407. CHAR_LEFT_CURLY_BRACE: 123, /* { */
  408. CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */
  409. CHAR_LINE_FEED: 10, /* \n */
  410. CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
  411. CHAR_PERCENT: 37, /* % */
  412. CHAR_PLUS: 43, /* + */
  413. CHAR_QUESTION_MARK: 63, /* ? */
  414. CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */
  415. CHAR_RIGHT_CURLY_BRACE: 125, /* } */
  416. CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */
  417. CHAR_SEMICOLON: 59, /* ; */
  418. CHAR_SINGLE_QUOTE: 39, /* ' */
  419. CHAR_SPACE: 32, /* */
  420. CHAR_TAB: 9, /* \t */
  421. CHAR_UNDERSCORE: 95, /* _ */
  422. CHAR_VERTICAL_LINE: 124, /* | */
  423. CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
  424. SEP: path$p.sep,
  425. /**
  426. * Create EXTGLOB_CHARS
  427. */
  428. extglobChars(chars) {
  429. return {
  430. '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
  431. '?': { type: 'qmark', open: '(?:', close: ')?' },
  432. '+': { type: 'plus', open: '(?:', close: ')+' },
  433. '*': { type: 'star', open: '(?:', close: ')*' },
  434. '@': { type: 'at', open: '(?:', close: ')' }
  435. };
  436. },
  437. /**
  438. * Create GLOB_CHARS
  439. */
  440. globChars(win32) {
  441. return win32 === true ? WINDOWS_CHARS$1 : POSIX_CHARS$1;
  442. }
  443. };
  444. (function (exports) {
  445. const path = path__default;
  446. const win32 = process.platform === 'win32';
  447. const {
  448. REGEX_BACKSLASH,
  449. REGEX_REMOVE_BACKSLASH,
  450. REGEX_SPECIAL_CHARS,
  451. REGEX_SPECIAL_CHARS_GLOBAL
  452. } = constants$9;
  453. exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  454. exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
  455. exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
  456. exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
  457. exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
  458. exports.removeBackslashes = str => {
  459. return str.replace(REGEX_REMOVE_BACKSLASH, match => {
  460. return match === '\\' ? '' : match;
  461. });
  462. };
  463. exports.supportsLookbehinds = () => {
  464. const segs = process.version.slice(1).split('.').map(Number);
  465. if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) {
  466. return true;
  467. }
  468. return false;
  469. };
  470. exports.isWindows = options => {
  471. if (options && typeof options.windows === 'boolean') {
  472. return options.windows;
  473. }
  474. return win32 === true || path.sep === '\\';
  475. };
  476. exports.escapeLast = (input, char, lastIdx) => {
  477. const idx = input.lastIndexOf(char, lastIdx);
  478. if (idx === -1) return input;
  479. if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
  480. return `${input.slice(0, idx)}\\${input.slice(idx)}`;
  481. };
  482. exports.removePrefix = (input, state = {}) => {
  483. let output = input;
  484. if (output.startsWith('./')) {
  485. output = output.slice(2);
  486. state.prefix = './';
  487. }
  488. return output;
  489. };
  490. exports.wrapOutput = (input, state = {}, options = {}) => {
  491. const prepend = options.contains ? '' : '^';
  492. const append = options.contains ? '' : '$';
  493. let output = `${prepend}(?:${input})${append}`;
  494. if (state.negated === true) {
  495. output = `(?:^(?!${output}).*$)`;
  496. }
  497. return output;
  498. };
  499. }(utils$p));
  500. const utils$o = utils$p;
  501. const {
  502. CHAR_ASTERISK: CHAR_ASTERISK$1, /* * */
  503. CHAR_AT: CHAR_AT$1, /* @ */
  504. CHAR_BACKWARD_SLASH: CHAR_BACKWARD_SLASH$1, /* \ */
  505. CHAR_COMMA: CHAR_COMMA$2, /* , */
  506. CHAR_DOT: CHAR_DOT$2, /* . */
  507. CHAR_EXCLAMATION_MARK: CHAR_EXCLAMATION_MARK$1, /* ! */
  508. CHAR_FORWARD_SLASH: CHAR_FORWARD_SLASH$1, /* / */
  509. CHAR_LEFT_CURLY_BRACE: CHAR_LEFT_CURLY_BRACE$2, /* { */
  510. CHAR_LEFT_PARENTHESES: CHAR_LEFT_PARENTHESES$2, /* ( */
  511. CHAR_LEFT_SQUARE_BRACKET: CHAR_LEFT_SQUARE_BRACKET$2, /* [ */
  512. CHAR_PLUS: CHAR_PLUS$1, /* + */
  513. CHAR_QUESTION_MARK: CHAR_QUESTION_MARK$1, /* ? */
  514. CHAR_RIGHT_CURLY_BRACE: CHAR_RIGHT_CURLY_BRACE$2, /* } */
  515. CHAR_RIGHT_PARENTHESES: CHAR_RIGHT_PARENTHESES$2, /* ) */
  516. CHAR_RIGHT_SQUARE_BRACKET: CHAR_RIGHT_SQUARE_BRACKET$2 /* ] */
  517. } = constants$9;
  518. const isPathSeparator$1 = code => {
  519. return code === CHAR_FORWARD_SLASH$1 || code === CHAR_BACKWARD_SLASH$1;
  520. };
  521. const depth$1 = token => {
  522. if (token.isPrefix !== true) {
  523. token.depth = token.isGlobstar ? Infinity : 1;
  524. }
  525. };
  526. /**
  527. * Quickly scans a glob pattern and returns an object with a handful of
  528. * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
  529. * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
  530. * with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
  531. *
  532. * ```js
  533. * const pm = require('picomatch');
  534. * console.log(pm.scan('foo/bar/*.js'));
  535. * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
  536. * ```
  537. * @param {String} `str`
  538. * @param {Object} `options`
  539. * @return {Object} Returns an object with tokens and regex source string.
  540. * @api public
  541. */
  542. const scan$3 = (input, options) => {
  543. const opts = options || {};
  544. const length = input.length - 1;
  545. const scanToEnd = opts.parts === true || opts.scanToEnd === true;
  546. const slashes = [];
  547. const tokens = [];
  548. const parts = [];
  549. let str = input;
  550. let index = -1;
  551. let start = 0;
  552. let lastIndex = 0;
  553. let isBrace = false;
  554. let isBracket = false;
  555. let isGlob = false;
  556. let isExtglob = false;
  557. let isGlobstar = false;
  558. let braceEscaped = false;
  559. let backslashes = false;
  560. let negated = false;
  561. let negatedExtglob = false;
  562. let finished = false;
  563. let braces = 0;
  564. let prev;
  565. let code;
  566. let token = { value: '', depth: 0, isGlob: false };
  567. const eos = () => index >= length;
  568. const peek = () => str.charCodeAt(index + 1);
  569. const advance = () => {
  570. prev = code;
  571. return str.charCodeAt(++index);
  572. };
  573. while (index < length) {
  574. code = advance();
  575. let next;
  576. if (code === CHAR_BACKWARD_SLASH$1) {
  577. backslashes = token.backslashes = true;
  578. code = advance();
  579. if (code === CHAR_LEFT_CURLY_BRACE$2) {
  580. braceEscaped = true;
  581. }
  582. continue;
  583. }
  584. if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE$2) {
  585. braces++;
  586. while (eos() !== true && (code = advance())) {
  587. if (code === CHAR_BACKWARD_SLASH$1) {
  588. backslashes = token.backslashes = true;
  589. advance();
  590. continue;
  591. }
  592. if (code === CHAR_LEFT_CURLY_BRACE$2) {
  593. braces++;
  594. continue;
  595. }
  596. if (braceEscaped !== true && code === CHAR_DOT$2 && (code = advance()) === CHAR_DOT$2) {
  597. isBrace = token.isBrace = true;
  598. isGlob = token.isGlob = true;
  599. finished = true;
  600. if (scanToEnd === true) {
  601. continue;
  602. }
  603. break;
  604. }
  605. if (braceEscaped !== true && code === CHAR_COMMA$2) {
  606. isBrace = token.isBrace = true;
  607. isGlob = token.isGlob = true;
  608. finished = true;
  609. if (scanToEnd === true) {
  610. continue;
  611. }
  612. break;
  613. }
  614. if (code === CHAR_RIGHT_CURLY_BRACE$2) {
  615. braces--;
  616. if (braces === 0) {
  617. braceEscaped = false;
  618. isBrace = token.isBrace = true;
  619. finished = true;
  620. break;
  621. }
  622. }
  623. }
  624. if (scanToEnd === true) {
  625. continue;
  626. }
  627. break;
  628. }
  629. if (code === CHAR_FORWARD_SLASH$1) {
  630. slashes.push(index);
  631. tokens.push(token);
  632. token = { value: '', depth: 0, isGlob: false };
  633. if (finished === true) continue;
  634. if (prev === CHAR_DOT$2 && index === (start + 1)) {
  635. start += 2;
  636. continue;
  637. }
  638. lastIndex = index + 1;
  639. continue;
  640. }
  641. if (opts.noext !== true) {
  642. const isExtglobChar = code === CHAR_PLUS$1
  643. || code === CHAR_AT$1
  644. || code === CHAR_ASTERISK$1
  645. || code === CHAR_QUESTION_MARK$1
  646. || code === CHAR_EXCLAMATION_MARK$1;
  647. if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES$2) {
  648. isGlob = token.isGlob = true;
  649. isExtglob = token.isExtglob = true;
  650. finished = true;
  651. if (code === CHAR_EXCLAMATION_MARK$1 && index === start) {
  652. negatedExtglob = true;
  653. }
  654. if (scanToEnd === true) {
  655. while (eos() !== true && (code = advance())) {
  656. if (code === CHAR_BACKWARD_SLASH$1) {
  657. backslashes = token.backslashes = true;
  658. code = advance();
  659. continue;
  660. }
  661. if (code === CHAR_RIGHT_PARENTHESES$2) {
  662. isGlob = token.isGlob = true;
  663. finished = true;
  664. break;
  665. }
  666. }
  667. continue;
  668. }
  669. break;
  670. }
  671. }
  672. if (code === CHAR_ASTERISK$1) {
  673. if (prev === CHAR_ASTERISK$1) isGlobstar = token.isGlobstar = true;
  674. isGlob = token.isGlob = true;
  675. finished = true;
  676. if (scanToEnd === true) {
  677. continue;
  678. }
  679. break;
  680. }
  681. if (code === CHAR_QUESTION_MARK$1) {
  682. isGlob = token.isGlob = true;
  683. finished = true;
  684. if (scanToEnd === true) {
  685. continue;
  686. }
  687. break;
  688. }
  689. if (code === CHAR_LEFT_SQUARE_BRACKET$2) {
  690. while (eos() !== true && (next = advance())) {
  691. if (next === CHAR_BACKWARD_SLASH$1) {
  692. backslashes = token.backslashes = true;
  693. advance();
  694. continue;
  695. }
  696. if (next === CHAR_RIGHT_SQUARE_BRACKET$2) {
  697. isBracket = token.isBracket = true;
  698. isGlob = token.isGlob = true;
  699. finished = true;
  700. break;
  701. }
  702. }
  703. if (scanToEnd === true) {
  704. continue;
  705. }
  706. break;
  707. }
  708. if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK$1 && index === start) {
  709. negated = token.negated = true;
  710. start++;
  711. continue;
  712. }
  713. if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES$2) {
  714. isGlob = token.isGlob = true;
  715. if (scanToEnd === true) {
  716. while (eos() !== true && (code = advance())) {
  717. if (code === CHAR_LEFT_PARENTHESES$2) {
  718. backslashes = token.backslashes = true;
  719. code = advance();
  720. continue;
  721. }
  722. if (code === CHAR_RIGHT_PARENTHESES$2) {
  723. finished = true;
  724. break;
  725. }
  726. }
  727. continue;
  728. }
  729. break;
  730. }
  731. if (isGlob === true) {
  732. finished = true;
  733. if (scanToEnd === true) {
  734. continue;
  735. }
  736. break;
  737. }
  738. }
  739. if (opts.noext === true) {
  740. isExtglob = false;
  741. isGlob = false;
  742. }
  743. let base = str;
  744. let prefix = '';
  745. let glob = '';
  746. if (start > 0) {
  747. prefix = str.slice(0, start);
  748. str = str.slice(start);
  749. lastIndex -= start;
  750. }
  751. if (base && isGlob === true && lastIndex > 0) {
  752. base = str.slice(0, lastIndex);
  753. glob = str.slice(lastIndex);
  754. } else if (isGlob === true) {
  755. base = '';
  756. glob = str;
  757. } else {
  758. base = str;
  759. }
  760. if (base && base !== '' && base !== '/' && base !== str) {
  761. if (isPathSeparator$1(base.charCodeAt(base.length - 1))) {
  762. base = base.slice(0, -1);
  763. }
  764. }
  765. if (opts.unescape === true) {
  766. if (glob) glob = utils$o.removeBackslashes(glob);
  767. if (base && backslashes === true) {
  768. base = utils$o.removeBackslashes(base);
  769. }
  770. }
  771. const state = {
  772. prefix,
  773. input,
  774. start,
  775. base,
  776. glob,
  777. isBrace,
  778. isBracket,
  779. isGlob,
  780. isExtglob,
  781. isGlobstar,
  782. negated,
  783. negatedExtglob
  784. };
  785. if (opts.tokens === true) {
  786. state.maxDepth = 0;
  787. if (!isPathSeparator$1(code)) {
  788. tokens.push(token);
  789. }
  790. state.tokens = tokens;
  791. }
  792. if (opts.parts === true || opts.tokens === true) {
  793. let prevIndex;
  794. for (let idx = 0; idx < slashes.length; idx++) {
  795. const n = prevIndex ? prevIndex + 1 : start;
  796. const i = slashes[idx];
  797. const value = input.slice(n, i);
  798. if (opts.tokens) {
  799. if (idx === 0 && start !== 0) {
  800. tokens[idx].isPrefix = true;
  801. tokens[idx].value = prefix;
  802. } else {
  803. tokens[idx].value = value;
  804. }
  805. depth$1(tokens[idx]);
  806. state.maxDepth += tokens[idx].depth;
  807. }
  808. if (idx !== 0 || value !== '') {
  809. parts.push(value);
  810. }
  811. prevIndex = i;
  812. }
  813. if (prevIndex && prevIndex + 1 < input.length) {
  814. const value = input.slice(prevIndex + 1);
  815. parts.push(value);
  816. if (opts.tokens) {
  817. tokens[tokens.length - 1].value = value;
  818. depth$1(tokens[tokens.length - 1]);
  819. state.maxDepth += tokens[tokens.length - 1].depth;
  820. }
  821. }
  822. state.slashes = slashes;
  823. state.parts = parts;
  824. }
  825. return state;
  826. };
  827. var scan_1$1 = scan$3;
  828. const constants$8 = constants$9;
  829. const utils$n = utils$p;
  830. /**
  831. * Constants
  832. */
  833. const {
  834. MAX_LENGTH: MAX_LENGTH$2,
  835. POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$2,
  836. REGEX_NON_SPECIAL_CHARS: REGEX_NON_SPECIAL_CHARS$1,
  837. REGEX_SPECIAL_CHARS_BACKREF: REGEX_SPECIAL_CHARS_BACKREF$1,
  838. REPLACEMENTS: REPLACEMENTS$1
  839. } = constants$8;
  840. /**
  841. * Helpers
  842. */
  843. const expandRange$1 = (args, options) => {
  844. if (typeof options.expandRange === 'function') {
  845. return options.expandRange(...args, options);
  846. }
  847. args.sort();
  848. const value = `[${args.join('-')}]`;
  849. return value;
  850. };
  851. /**
  852. * Create the message for a syntax error
  853. */
  854. const syntaxError$2 = (type, char) => {
  855. return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
  856. };
  857. /**
  858. * Parse the given input string.
  859. * @param {String} input
  860. * @param {Object} options
  861. * @return {Object}
  862. */
  863. const parse$n = (input, options) => {
  864. if (typeof input !== 'string') {
  865. throw new TypeError('Expected a string');
  866. }
  867. input = REPLACEMENTS$1[input] || input;
  868. const opts = { ...options };
  869. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$2, opts.maxLength) : MAX_LENGTH$2;
  870. let len = input.length;
  871. if (len > max) {
  872. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  873. }
  874. const bos = { type: 'bos', value: '', output: opts.prepend || '' };
  875. const tokens = [bos];
  876. const capture = opts.capture ? '' : '?:';
  877. const win32 = utils$n.isWindows(options);
  878. // create constants based on platform, for windows or posix
  879. const PLATFORM_CHARS = constants$8.globChars(win32);
  880. const EXTGLOB_CHARS = constants$8.extglobChars(PLATFORM_CHARS);
  881. const {
  882. DOT_LITERAL,
  883. PLUS_LITERAL,
  884. SLASH_LITERAL,
  885. ONE_CHAR,
  886. DOTS_SLASH,
  887. NO_DOT,
  888. NO_DOT_SLASH,
  889. NO_DOTS_SLASH,
  890. QMARK,
  891. QMARK_NO_DOT,
  892. STAR,
  893. START_ANCHOR
  894. } = PLATFORM_CHARS;
  895. const globstar = opts => {
  896. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  897. };
  898. const nodot = opts.dot ? '' : NO_DOT;
  899. const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
  900. let star = opts.bash === true ? globstar(opts) : STAR;
  901. if (opts.capture) {
  902. star = `(${star})`;
  903. }
  904. // minimatch options support
  905. if (typeof opts.noext === 'boolean') {
  906. opts.noextglob = opts.noext;
  907. }
  908. const state = {
  909. input,
  910. index: -1,
  911. start: 0,
  912. dot: opts.dot === true,
  913. consumed: '',
  914. output: '',
  915. prefix: '',
  916. backtrack: false,
  917. negated: false,
  918. brackets: 0,
  919. braces: 0,
  920. parens: 0,
  921. quotes: 0,
  922. globstar: false,
  923. tokens
  924. };
  925. input = utils$n.removePrefix(input, state);
  926. len = input.length;
  927. const extglobs = [];
  928. const braces = [];
  929. const stack = [];
  930. let prev = bos;
  931. let value;
  932. /**
  933. * Tokenizing helpers
  934. */
  935. const eos = () => state.index === len - 1;
  936. const peek = state.peek = (n = 1) => input[state.index + n];
  937. const advance = state.advance = () => input[++state.index] || '';
  938. const remaining = () => input.slice(state.index + 1);
  939. const consume = (value = '', num = 0) => {
  940. state.consumed += value;
  941. state.index += num;
  942. };
  943. const append = token => {
  944. state.output += token.output != null ? token.output : token.value;
  945. consume(token.value);
  946. };
  947. const negate = () => {
  948. let count = 1;
  949. while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
  950. advance();
  951. state.start++;
  952. count++;
  953. }
  954. if (count % 2 === 0) {
  955. return false;
  956. }
  957. state.negated = true;
  958. state.start++;
  959. return true;
  960. };
  961. const increment = type => {
  962. state[type]++;
  963. stack.push(type);
  964. };
  965. const decrement = type => {
  966. state[type]--;
  967. stack.pop();
  968. };
  969. /**
  970. * Push tokens onto the tokens array. This helper speeds up
  971. * tokenizing by 1) helping us avoid backtracking as much as possible,
  972. * and 2) helping us avoid creating extra tokens when consecutive
  973. * characters are plain text. This improves performance and simplifies
  974. * lookbehinds.
  975. */
  976. const push = tok => {
  977. if (prev.type === 'globstar') {
  978. const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
  979. const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));
  980. if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
  981. state.output = state.output.slice(0, -prev.output.length);
  982. prev.type = 'star';
  983. prev.value = '*';
  984. prev.output = star;
  985. state.output += prev.output;
  986. }
  987. }
  988. if (extglobs.length && tok.type !== 'paren') {
  989. extglobs[extglobs.length - 1].inner += tok.value;
  990. }
  991. if (tok.value || tok.output) append(tok);
  992. if (prev && prev.type === 'text' && tok.type === 'text') {
  993. prev.value += tok.value;
  994. prev.output = (prev.output || '') + tok.value;
  995. return;
  996. }
  997. tok.prev = prev;
  998. tokens.push(tok);
  999. prev = tok;
  1000. };
  1001. const extglobOpen = (type, value) => {
  1002. const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };
  1003. token.prev = prev;
  1004. token.parens = state.parens;
  1005. token.output = state.output;
  1006. const output = (opts.capture ? '(' : '') + token.open;
  1007. increment('parens');
  1008. push({ type, value, output: state.output ? '' : ONE_CHAR });
  1009. push({ type: 'paren', extglob: true, value: advance(), output });
  1010. extglobs.push(token);
  1011. };
  1012. const extglobClose = token => {
  1013. let output = token.close + (opts.capture ? ')' : '');
  1014. let rest;
  1015. if (token.type === 'negate') {
  1016. let extglobStar = star;
  1017. if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
  1018. extglobStar = globstar(opts);
  1019. }
  1020. if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
  1021. output = token.close = `)$))${extglobStar}`;
  1022. }
  1023. if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
  1024. // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis.
  1025. // In this case, we need to parse the string and use it in the output of the original pattern.
  1026. // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`.
  1027. //
  1028. // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`.
  1029. const expression = parse$n(rest, { ...options, fastpaths: false }).output;
  1030. output = token.close = `)${expression})${extglobStar})`;
  1031. }
  1032. if (token.prev.type === 'bos') {
  1033. state.negatedExtglob = true;
  1034. }
  1035. }
  1036. push({ type: 'paren', extglob: true, value, output });
  1037. decrement('parens');
  1038. };
  1039. /**
  1040. * Fast paths
  1041. */
  1042. if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
  1043. let backslashes = false;
  1044. let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF$1, (m, esc, chars, first, rest, index) => {
  1045. if (first === '\\') {
  1046. backslashes = true;
  1047. return m;
  1048. }
  1049. if (first === '?') {
  1050. if (esc) {
  1051. return esc + first + (rest ? QMARK.repeat(rest.length) : '');
  1052. }
  1053. if (index === 0) {
  1054. return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
  1055. }
  1056. return QMARK.repeat(chars.length);
  1057. }
  1058. if (first === '.') {
  1059. return DOT_LITERAL.repeat(chars.length);
  1060. }
  1061. if (first === '*') {
  1062. if (esc) {
  1063. return esc + first + (rest ? star : '');
  1064. }
  1065. return star;
  1066. }
  1067. return esc ? m : `\\${m}`;
  1068. });
  1069. if (backslashes === true) {
  1070. if (opts.unescape === true) {
  1071. output = output.replace(/\\/g, '');
  1072. } else {
  1073. output = output.replace(/\\+/g, m => {
  1074. return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
  1075. });
  1076. }
  1077. }
  1078. if (output === input && opts.contains === true) {
  1079. state.output = input;
  1080. return state;
  1081. }
  1082. state.output = utils$n.wrapOutput(output, state, options);
  1083. return state;
  1084. }
  1085. /**
  1086. * Tokenize input until we reach end-of-string
  1087. */
  1088. while (!eos()) {
  1089. value = advance();
  1090. if (value === '\u0000') {
  1091. continue;
  1092. }
  1093. /**
  1094. * Escaped characters
  1095. */
  1096. if (value === '\\') {
  1097. const next = peek();
  1098. if (next === '/' && opts.bash !== true) {
  1099. continue;
  1100. }
  1101. if (next === '.' || next === ';') {
  1102. continue;
  1103. }
  1104. if (!next) {
  1105. value += '\\';
  1106. push({ type: 'text', value });
  1107. continue;
  1108. }
  1109. // collapse slashes to reduce potential for exploits
  1110. const match = /^\\+/.exec(remaining());
  1111. let slashes = 0;
  1112. if (match && match[0].length > 2) {
  1113. slashes = match[0].length;
  1114. state.index += slashes;
  1115. if (slashes % 2 !== 0) {
  1116. value += '\\';
  1117. }
  1118. }
  1119. if (opts.unescape === true) {
  1120. value = advance();
  1121. } else {
  1122. value += advance();
  1123. }
  1124. if (state.brackets === 0) {
  1125. push({ type: 'text', value });
  1126. continue;
  1127. }
  1128. }
  1129. /**
  1130. * If we're inside a regex character class, continue
  1131. * until we reach the closing bracket.
  1132. */
  1133. if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
  1134. if (opts.posix !== false && value === ':') {
  1135. const inner = prev.value.slice(1);
  1136. if (inner.includes('[')) {
  1137. prev.posix = true;
  1138. if (inner.includes(':')) {
  1139. const idx = prev.value.lastIndexOf('[');
  1140. const pre = prev.value.slice(0, idx);
  1141. const rest = prev.value.slice(idx + 2);
  1142. const posix = POSIX_REGEX_SOURCE$2[rest];
  1143. if (posix) {
  1144. prev.value = pre + posix;
  1145. state.backtrack = true;
  1146. advance();
  1147. if (!bos.output && tokens.indexOf(prev) === 1) {
  1148. bos.output = ONE_CHAR;
  1149. }
  1150. continue;
  1151. }
  1152. }
  1153. }
  1154. }
  1155. if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
  1156. value = `\\${value}`;
  1157. }
  1158. if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
  1159. value = `\\${value}`;
  1160. }
  1161. if (opts.posix === true && value === '!' && prev.value === '[') {
  1162. value = '^';
  1163. }
  1164. prev.value += value;
  1165. append({ value });
  1166. continue;
  1167. }
  1168. /**
  1169. * If we're inside a quoted string, continue
  1170. * until we reach the closing double quote.
  1171. */
  1172. if (state.quotes === 1 && value !== '"') {
  1173. value = utils$n.escapeRegex(value);
  1174. prev.value += value;
  1175. append({ value });
  1176. continue;
  1177. }
  1178. /**
  1179. * Double quotes
  1180. */
  1181. if (value === '"') {
  1182. state.quotes = state.quotes === 1 ? 0 : 1;
  1183. if (opts.keepQuotes === true) {
  1184. push({ type: 'text', value });
  1185. }
  1186. continue;
  1187. }
  1188. /**
  1189. * Parentheses
  1190. */
  1191. if (value === '(') {
  1192. increment('parens');
  1193. push({ type: 'paren', value });
  1194. continue;
  1195. }
  1196. if (value === ')') {
  1197. if (state.parens === 0 && opts.strictBrackets === true) {
  1198. throw new SyntaxError(syntaxError$2('opening', '('));
  1199. }
  1200. const extglob = extglobs[extglobs.length - 1];
  1201. if (extglob && state.parens === extglob.parens + 1) {
  1202. extglobClose(extglobs.pop());
  1203. continue;
  1204. }
  1205. push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
  1206. decrement('parens');
  1207. continue;
  1208. }
  1209. /**
  1210. * Square brackets
  1211. */
  1212. if (value === '[') {
  1213. if (opts.nobracket === true || !remaining().includes(']')) {
  1214. if (opts.nobracket !== true && opts.strictBrackets === true) {
  1215. throw new SyntaxError(syntaxError$2('closing', ']'));
  1216. }
  1217. value = `\\${value}`;
  1218. } else {
  1219. increment('brackets');
  1220. }
  1221. push({ type: 'bracket', value });
  1222. continue;
  1223. }
  1224. if (value === ']') {
  1225. if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
  1226. push({ type: 'text', value, output: `\\${value}` });
  1227. continue;
  1228. }
  1229. if (state.brackets === 0) {
  1230. if (opts.strictBrackets === true) {
  1231. throw new SyntaxError(syntaxError$2('opening', '['));
  1232. }
  1233. push({ type: 'text', value, output: `\\${value}` });
  1234. continue;
  1235. }
  1236. decrement('brackets');
  1237. const prevValue = prev.value.slice(1);
  1238. if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
  1239. value = `/${value}`;
  1240. }
  1241. prev.value += value;
  1242. append({ value });
  1243. // when literal brackets are explicitly disabled
  1244. // assume we should match with a regex character class
  1245. if (opts.literalBrackets === false || utils$n.hasRegexChars(prevValue)) {
  1246. continue;
  1247. }
  1248. const escaped = utils$n.escapeRegex(prev.value);
  1249. state.output = state.output.slice(0, -prev.value.length);
  1250. // when literal brackets are explicitly enabled
  1251. // assume we should escape the brackets to match literal characters
  1252. if (opts.literalBrackets === true) {
  1253. state.output += escaped;
  1254. prev.value = escaped;
  1255. continue;
  1256. }
  1257. // when the user specifies nothing, try to match both
  1258. prev.value = `(${capture}${escaped}|${prev.value})`;
  1259. state.output += prev.value;
  1260. continue;
  1261. }
  1262. /**
  1263. * Braces
  1264. */
  1265. if (value === '{' && opts.nobrace !== true) {
  1266. increment('braces');
  1267. const open = {
  1268. type: 'brace',
  1269. value,
  1270. output: '(',
  1271. outputIndex: state.output.length,
  1272. tokensIndex: state.tokens.length
  1273. };
  1274. braces.push(open);
  1275. push(open);
  1276. continue;
  1277. }
  1278. if (value === '}') {
  1279. const brace = braces[braces.length - 1];
  1280. if (opts.nobrace === true || !brace) {
  1281. push({ type: 'text', value, output: value });
  1282. continue;
  1283. }
  1284. let output = ')';
  1285. if (brace.dots === true) {
  1286. const arr = tokens.slice();
  1287. const range = [];
  1288. for (let i = arr.length - 1; i >= 0; i--) {
  1289. tokens.pop();
  1290. if (arr[i].type === 'brace') {
  1291. break;
  1292. }
  1293. if (arr[i].type !== 'dots') {
  1294. range.unshift(arr[i].value);
  1295. }
  1296. }
  1297. output = expandRange$1(range, opts);
  1298. state.backtrack = true;
  1299. }
  1300. if (brace.comma !== true && brace.dots !== true) {
  1301. const out = state.output.slice(0, brace.outputIndex);
  1302. const toks = state.tokens.slice(brace.tokensIndex);
  1303. brace.value = brace.output = '\\{';
  1304. value = output = '\\}';
  1305. state.output = out;
  1306. for (const t of toks) {
  1307. state.output += (t.output || t.value);
  1308. }
  1309. }
  1310. push({ type: 'brace', value, output });
  1311. decrement('braces');
  1312. braces.pop();
  1313. continue;
  1314. }
  1315. /**
  1316. * Pipes
  1317. */
  1318. if (value === '|') {
  1319. if (extglobs.length > 0) {
  1320. extglobs[extglobs.length - 1].conditions++;
  1321. }
  1322. push({ type: 'text', value });
  1323. continue;
  1324. }
  1325. /**
  1326. * Commas
  1327. */
  1328. if (value === ',') {
  1329. let output = value;
  1330. const brace = braces[braces.length - 1];
  1331. if (brace && stack[stack.length - 1] === 'braces') {
  1332. brace.comma = true;
  1333. output = '|';
  1334. }
  1335. push({ type: 'comma', value, output });
  1336. continue;
  1337. }
  1338. /**
  1339. * Slashes
  1340. */
  1341. if (value === '/') {
  1342. // if the beginning of the glob is "./", advance the start
  1343. // to the current index, and don't add the "./" characters
  1344. // to the state. This greatly simplifies lookbehinds when
  1345. // checking for BOS characters like "!" and "." (not "./")
  1346. if (prev.type === 'dot' && state.index === state.start + 1) {
  1347. state.start = state.index + 1;
  1348. state.consumed = '';
  1349. state.output = '';
  1350. tokens.pop();
  1351. prev = bos; // reset "prev" to the first token
  1352. continue;
  1353. }
  1354. push({ type: 'slash', value, output: SLASH_LITERAL });
  1355. continue;
  1356. }
  1357. /**
  1358. * Dots
  1359. */
  1360. if (value === '.') {
  1361. if (state.braces > 0 && prev.type === 'dot') {
  1362. if (prev.value === '.') prev.output = DOT_LITERAL;
  1363. const brace = braces[braces.length - 1];
  1364. prev.type = 'dots';
  1365. prev.output += value;
  1366. prev.value += value;
  1367. brace.dots = true;
  1368. continue;
  1369. }
  1370. if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
  1371. push({ type: 'text', value, output: DOT_LITERAL });
  1372. continue;
  1373. }
  1374. push({ type: 'dot', value, output: DOT_LITERAL });
  1375. continue;
  1376. }
  1377. /**
  1378. * Question marks
  1379. */
  1380. if (value === '?') {
  1381. const isGroup = prev && prev.value === '(';
  1382. if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  1383. extglobOpen('qmark', value);
  1384. continue;
  1385. }
  1386. if (prev && prev.type === 'paren') {
  1387. const next = peek();
  1388. let output = value;
  1389. if (next === '<' && !utils$n.supportsLookbehinds()) {
  1390. throw new Error('Node.js v10 or higher is required for regex lookbehinds');
  1391. }
  1392. if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {
  1393. output = `\\${value}`;
  1394. }
  1395. push({ type: 'text', value, output });
  1396. continue;
  1397. }
  1398. if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
  1399. push({ type: 'qmark', value, output: QMARK_NO_DOT });
  1400. continue;
  1401. }
  1402. push({ type: 'qmark', value, output: QMARK });
  1403. continue;
  1404. }
  1405. /**
  1406. * Exclamation
  1407. */
  1408. if (value === '!') {
  1409. if (opts.noextglob !== true && peek() === '(') {
  1410. if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
  1411. extglobOpen('negate', value);
  1412. continue;
  1413. }
  1414. }
  1415. if (opts.nonegate !== true && state.index === 0) {
  1416. negate();
  1417. continue;
  1418. }
  1419. }
  1420. /**
  1421. * Plus
  1422. */
  1423. if (value === '+') {
  1424. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  1425. extglobOpen('plus', value);
  1426. continue;
  1427. }
  1428. if ((prev && prev.value === '(') || opts.regex === false) {
  1429. push({ type: 'plus', value, output: PLUS_LITERAL });
  1430. continue;
  1431. }
  1432. if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {
  1433. push({ type: 'plus', value });
  1434. continue;
  1435. }
  1436. push({ type: 'plus', value: PLUS_LITERAL });
  1437. continue;
  1438. }
  1439. /**
  1440. * Plain text
  1441. */
  1442. if (value === '@') {
  1443. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  1444. push({ type: 'at', extglob: true, value, output: '' });
  1445. continue;
  1446. }
  1447. push({ type: 'text', value });
  1448. continue;
  1449. }
  1450. /**
  1451. * Plain text
  1452. */
  1453. if (value !== '*') {
  1454. if (value === '$' || value === '^') {
  1455. value = `\\${value}`;
  1456. }
  1457. const match = REGEX_NON_SPECIAL_CHARS$1.exec(remaining());
  1458. if (match) {
  1459. value += match[0];
  1460. state.index += match[0].length;
  1461. }
  1462. push({ type: 'text', value });
  1463. continue;
  1464. }
  1465. /**
  1466. * Stars
  1467. */
  1468. if (prev && (prev.type === 'globstar' || prev.star === true)) {
  1469. prev.type = 'star';
  1470. prev.star = true;
  1471. prev.value += value;
  1472. prev.output = star;
  1473. state.backtrack = true;
  1474. state.globstar = true;
  1475. consume(value);
  1476. continue;
  1477. }
  1478. let rest = remaining();
  1479. if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
  1480. extglobOpen('star', value);
  1481. continue;
  1482. }
  1483. if (prev.type === 'star') {
  1484. if (opts.noglobstar === true) {
  1485. consume(value);
  1486. continue;
  1487. }
  1488. const prior = prev.prev;
  1489. const before = prior.prev;
  1490. const isStart = prior.type === 'slash' || prior.type === 'bos';
  1491. const afterStar = before && (before.type === 'star' || before.type === 'globstar');
  1492. if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {
  1493. push({ type: 'star', value, output: '' });
  1494. continue;
  1495. }
  1496. const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
  1497. const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
  1498. if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
  1499. push({ type: 'star', value, output: '' });
  1500. continue;
  1501. }
  1502. // strip consecutive `/**/`
  1503. while (rest.slice(0, 3) === '/**') {
  1504. const after = input[state.index + 4];
  1505. if (after && after !== '/') {
  1506. break;
  1507. }
  1508. rest = rest.slice(3);
  1509. consume('/**', 3);
  1510. }
  1511. if (prior.type === 'bos' && eos()) {
  1512. prev.type = 'globstar';
  1513. prev.value += value;
  1514. prev.output = globstar(opts);
  1515. state.output = prev.output;
  1516. state.globstar = true;
  1517. consume(value);
  1518. continue;
  1519. }
  1520. if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
  1521. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  1522. prior.output = `(?:${prior.output}`;
  1523. prev.type = 'globstar';
  1524. prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
  1525. prev.value += value;
  1526. state.globstar = true;
  1527. state.output += prior.output + prev.output;
  1528. consume(value);
  1529. continue;
  1530. }
  1531. if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
  1532. const end = rest[1] !== void 0 ? '|$' : '';
  1533. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  1534. prior.output = `(?:${prior.output}`;
  1535. prev.type = 'globstar';
  1536. prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
  1537. prev.value += value;
  1538. state.output += prior.output + prev.output;
  1539. state.globstar = true;
  1540. consume(value + advance());
  1541. push({ type: 'slash', value: '/', output: '' });
  1542. continue;
  1543. }
  1544. if (prior.type === 'bos' && rest[0] === '/') {
  1545. prev.type = 'globstar';
  1546. prev.value += value;
  1547. prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
  1548. state.output = prev.output;
  1549. state.globstar = true;
  1550. consume(value + advance());
  1551. push({ type: 'slash', value: '/', output: '' });
  1552. continue;
  1553. }
  1554. // remove single star from output
  1555. state.output = state.output.slice(0, -prev.output.length);
  1556. // reset previous token to globstar
  1557. prev.type = 'globstar';
  1558. prev.output = globstar(opts);
  1559. prev.value += value;
  1560. // reset output with globstar
  1561. state.output += prev.output;
  1562. state.globstar = true;
  1563. consume(value);
  1564. continue;
  1565. }
  1566. const token = { type: 'star', value, output: star };
  1567. if (opts.bash === true) {
  1568. token.output = '.*?';
  1569. if (prev.type === 'bos' || prev.type === 'slash') {
  1570. token.output = nodot + token.output;
  1571. }
  1572. push(token);
  1573. continue;
  1574. }
  1575. if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
  1576. token.output = value;
  1577. push(token);
  1578. continue;
  1579. }
  1580. if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
  1581. if (prev.type === 'dot') {
  1582. state.output += NO_DOT_SLASH;
  1583. prev.output += NO_DOT_SLASH;
  1584. } else if (opts.dot === true) {
  1585. state.output += NO_DOTS_SLASH;
  1586. prev.output += NO_DOTS_SLASH;
  1587. } else {
  1588. state.output += nodot;
  1589. prev.output += nodot;
  1590. }
  1591. if (peek() !== '*') {
  1592. state.output += ONE_CHAR;
  1593. prev.output += ONE_CHAR;
  1594. }
  1595. }
  1596. push(token);
  1597. }
  1598. while (state.brackets > 0) {
  1599. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError$2('closing', ']'));
  1600. state.output = utils$n.escapeLast(state.output, '[');
  1601. decrement('brackets');
  1602. }
  1603. while (state.parens > 0) {
  1604. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError$2('closing', ')'));
  1605. state.output = utils$n.escapeLast(state.output, '(');
  1606. decrement('parens');
  1607. }
  1608. while (state.braces > 0) {
  1609. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError$2('closing', '}'));
  1610. state.output = utils$n.escapeLast(state.output, '{');
  1611. decrement('braces');
  1612. }
  1613. if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
  1614. push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
  1615. }
  1616. // rebuild the output if we had to backtrack at any point
  1617. if (state.backtrack === true) {
  1618. state.output = '';
  1619. for (const token of state.tokens) {
  1620. state.output += token.output != null ? token.output : token.value;
  1621. if (token.suffix) {
  1622. state.output += token.suffix;
  1623. }
  1624. }
  1625. }
  1626. return state;
  1627. };
  1628. /**
  1629. * Fast paths for creating regular expressions for common glob patterns.
  1630. * This can significantly speed up processing and has very little downside
  1631. * impact when none of the fast paths match.
  1632. */
  1633. parse$n.fastpaths = (input, options) => {
  1634. const opts = { ...options };
  1635. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$2, opts.maxLength) : MAX_LENGTH$2;
  1636. const len = input.length;
  1637. if (len > max) {
  1638. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  1639. }
  1640. input = REPLACEMENTS$1[input] || input;
  1641. const win32 = utils$n.isWindows(options);
  1642. // create constants based on platform, for windows or posix
  1643. const {
  1644. DOT_LITERAL,
  1645. SLASH_LITERAL,
  1646. ONE_CHAR,
  1647. DOTS_SLASH,
  1648. NO_DOT,
  1649. NO_DOTS,
  1650. NO_DOTS_SLASH,
  1651. STAR,
  1652. START_ANCHOR
  1653. } = constants$8.globChars(win32);
  1654. const nodot = opts.dot ? NO_DOTS : NO_DOT;
  1655. const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
  1656. const capture = opts.capture ? '' : '?:';
  1657. const state = { negated: false, prefix: '' };
  1658. let star = opts.bash === true ? '.*?' : STAR;
  1659. if (opts.capture) {
  1660. star = `(${star})`;
  1661. }
  1662. const globstar = opts => {
  1663. if (opts.noglobstar === true) return star;
  1664. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  1665. };
  1666. const create = str => {
  1667. switch (str) {
  1668. case '*':
  1669. return `${nodot}${ONE_CHAR}${star}`;
  1670. case '.*':
  1671. return `${DOT_LITERAL}${ONE_CHAR}${star}`;
  1672. case '*.*':
  1673. return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  1674. case '*/*':
  1675. return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
  1676. case '**':
  1677. return nodot + globstar(opts);
  1678. case '**/*':
  1679. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
  1680. case '**/*.*':
  1681. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  1682. case '**/.*':
  1683. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
  1684. default: {
  1685. const match = /^(.*?)\.(\w+)$/.exec(str);
  1686. if (!match) return;
  1687. const source = create(match[1]);
  1688. if (!source) return;
  1689. return source + DOT_LITERAL + match[2];
  1690. }
  1691. }
  1692. };
  1693. const output = utils$n.removePrefix(input, state);
  1694. let source = create(output);
  1695. if (source && opts.strictSlashes !== true) {
  1696. source += `${SLASH_LITERAL}?`;
  1697. }
  1698. return source;
  1699. };
  1700. var parse_1$3 = parse$n;
  1701. const path$o = path__default;
  1702. const scan$2 = scan_1$1;
  1703. const parse$m = parse_1$3;
  1704. const utils$m = utils$p;
  1705. const constants$7 = constants$9;
  1706. const isObject$5 = val => val && typeof val === 'object' && !Array.isArray(val);
  1707. /**
  1708. * Creates a matcher function from one or more glob patterns. The
  1709. * returned function takes a string to match as its first argument,
  1710. * and returns true if the string is a match. The returned matcher
  1711. * function also takes a boolean as the second argument that, when true,
  1712. * returns an object with additional information.
  1713. *
  1714. * ```js
  1715. * const picomatch = require('picomatch');
  1716. * // picomatch(glob[, options]);
  1717. *
  1718. * const isMatch = picomatch('*.!(*a)');
  1719. * console.log(isMatch('a.a')); //=> false
  1720. * console.log(isMatch('a.b')); //=> true
  1721. * ```
  1722. * @name picomatch
  1723. * @param {String|Array} `globs` One or more glob patterns.
  1724. * @param {Object=} `options`
  1725. * @return {Function=} Returns a matcher function.
  1726. * @api public
  1727. */
  1728. const picomatch$7 = (glob, options, returnState = false) => {
  1729. if (Array.isArray(glob)) {
  1730. const fns = glob.map(input => picomatch$7(input, options, returnState));
  1731. const arrayMatcher = str => {
  1732. for (const isMatch of fns) {
  1733. const state = isMatch(str);
  1734. if (state) return state;
  1735. }
  1736. return false;
  1737. };
  1738. return arrayMatcher;
  1739. }
  1740. const isState = isObject$5(glob) && glob.tokens && glob.input;
  1741. if (glob === '' || (typeof glob !== 'string' && !isState)) {
  1742. throw new TypeError('Expected pattern to be a non-empty string');
  1743. }
  1744. const opts = options || {};
  1745. const posix = utils$m.isWindows(options);
  1746. const regex = isState
  1747. ? picomatch$7.compileRe(glob, options)
  1748. : picomatch$7.makeRe(glob, options, false, true);
  1749. const state = regex.state;
  1750. delete regex.state;
  1751. let isIgnored = () => false;
  1752. if (opts.ignore) {
  1753. const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
  1754. isIgnored = picomatch$7(opts.ignore, ignoreOpts, returnState);
  1755. }
  1756. const matcher = (input, returnObject = false) => {
  1757. const { isMatch, match, output } = picomatch$7.test(input, regex, options, { glob, posix });
  1758. const result = { glob, state, regex, posix, input, output, match, isMatch };
  1759. if (typeof opts.onResult === 'function') {
  1760. opts.onResult(result);
  1761. }
  1762. if (isMatch === false) {
  1763. result.isMatch = false;
  1764. return returnObject ? result : false;
  1765. }
  1766. if (isIgnored(input)) {
  1767. if (typeof opts.onIgnore === 'function') {
  1768. opts.onIgnore(result);
  1769. }
  1770. result.isMatch = false;
  1771. return returnObject ? result : false;
  1772. }
  1773. if (typeof opts.onMatch === 'function') {
  1774. opts.onMatch(result);
  1775. }
  1776. return returnObject ? result : true;
  1777. };
  1778. if (returnState) {
  1779. matcher.state = state;
  1780. }
  1781. return matcher;
  1782. };
  1783. /**
  1784. * Test `input` with the given `regex`. This is used by the main
  1785. * `picomatch()` function to test the input string.
  1786. *
  1787. * ```js
  1788. * const picomatch = require('picomatch');
  1789. * // picomatch.test(input, regex[, options]);
  1790. *
  1791. * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
  1792. * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
  1793. * ```
  1794. * @param {String} `input` String to test.
  1795. * @param {RegExp} `regex`
  1796. * @return {Object} Returns an object with matching info.
  1797. * @api public
  1798. */
  1799. picomatch$7.test = (input, regex, options, { glob, posix } = {}) => {
  1800. if (typeof input !== 'string') {
  1801. throw new TypeError('Expected input to be a string');
  1802. }
  1803. if (input === '') {
  1804. return { isMatch: false, output: '' };
  1805. }
  1806. const opts = options || {};
  1807. const format = opts.format || (posix ? utils$m.toPosixSlashes : null);
  1808. let match = input === glob;
  1809. let output = (match && format) ? format(input) : input;
  1810. if (match === false) {
  1811. output = format ? format(input) : input;
  1812. match = output === glob;
  1813. }
  1814. if (match === false || opts.capture === true) {
  1815. if (opts.matchBase === true || opts.basename === true) {
  1816. match = picomatch$7.matchBase(input, regex, options, posix);
  1817. } else {
  1818. match = regex.exec(output);
  1819. }
  1820. }
  1821. return { isMatch: Boolean(match), match, output };
  1822. };
  1823. /**
  1824. * Match the basename of a filepath.
  1825. *
  1826. * ```js
  1827. * const picomatch = require('picomatch');
  1828. * // picomatch.matchBase(input, glob[, options]);
  1829. * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
  1830. * ```
  1831. * @param {String} `input` String to test.
  1832. * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
  1833. * @return {Boolean}
  1834. * @api public
  1835. */
  1836. picomatch$7.matchBase = (input, glob, options, posix = utils$m.isWindows(options)) => {
  1837. const regex = glob instanceof RegExp ? glob : picomatch$7.makeRe(glob, options);
  1838. return regex.test(path$o.basename(input));
  1839. };
  1840. /**
  1841. * Returns true if **any** of the given glob `patterns` match the specified `string`.
  1842. *
  1843. * ```js
  1844. * const picomatch = require('picomatch');
  1845. * // picomatch.isMatch(string, patterns[, options]);
  1846. *
  1847. * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
  1848. * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
  1849. * ```
  1850. * @param {String|Array} str The string to test.
  1851. * @param {String|Array} patterns One or more glob patterns to use for matching.
  1852. * @param {Object} [options] See available [options](#options).
  1853. * @return {Boolean} Returns true if any patterns match `str`
  1854. * @api public
  1855. */
  1856. picomatch$7.isMatch = (str, patterns, options) => picomatch$7(patterns, options)(str);
  1857. /**
  1858. * Parse a glob pattern to create the source string for a regular
  1859. * expression.
  1860. *
  1861. * ```js
  1862. * const picomatch = require('picomatch');
  1863. * const result = picomatch.parse(pattern[, options]);
  1864. * ```
  1865. * @param {String} `pattern`
  1866. * @param {Object} `options`
  1867. * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
  1868. * @api public
  1869. */
  1870. picomatch$7.parse = (pattern, options) => {
  1871. if (Array.isArray(pattern)) return pattern.map(p => picomatch$7.parse(p, options));
  1872. return parse$m(pattern, { ...options, fastpaths: false });
  1873. };
  1874. /**
  1875. * Scan a glob pattern to separate the pattern into segments.
  1876. *
  1877. * ```js
  1878. * const picomatch = require('picomatch');
  1879. * // picomatch.scan(input[, options]);
  1880. *
  1881. * const result = picomatch.scan('!./foo/*.js');
  1882. * console.log(result);
  1883. * { prefix: '!./',
  1884. * input: '!./foo/*.js',
  1885. * start: 3,
  1886. * base: 'foo',
  1887. * glob: '*.js',
  1888. * isBrace: false,
  1889. * isBracket: false,
  1890. * isGlob: true,
  1891. * isExtglob: false,
  1892. * isGlobstar: false,
  1893. * negated: true }
  1894. * ```
  1895. * @param {String} `input` Glob pattern to scan.
  1896. * @param {Object} `options`
  1897. * @return {Object} Returns an object with
  1898. * @api public
  1899. */
  1900. picomatch$7.scan = (input, options) => scan$2(input, options);
  1901. /**
  1902. * Compile a regular expression from the `state` object returned by the
  1903. * [parse()](#parse) method.
  1904. *
  1905. * @param {Object} `state`
  1906. * @param {Object} `options`
  1907. * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
  1908. * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
  1909. * @return {RegExp}
  1910. * @api public
  1911. */
  1912. picomatch$7.compileRe = (state, options, returnOutput = false, returnState = false) => {
  1913. if (returnOutput === true) {
  1914. return state.output;
  1915. }
  1916. const opts = options || {};
  1917. const prepend = opts.contains ? '' : '^';
  1918. const append = opts.contains ? '' : '$';
  1919. let source = `${prepend}(?:${state.output})${append}`;
  1920. if (state && state.negated === true) {
  1921. source = `^(?!${source}).*$`;
  1922. }
  1923. const regex = picomatch$7.toRegex(source, options);
  1924. if (returnState === true) {
  1925. regex.state = state;
  1926. }
  1927. return regex;
  1928. };
  1929. /**
  1930. * Create a regular expression from a parsed glob pattern.
  1931. *
  1932. * ```js
  1933. * const picomatch = require('picomatch');
  1934. * const state = picomatch.parse('*.js');
  1935. * // picomatch.compileRe(state[, options]);
  1936. *
  1937. * console.log(picomatch.compileRe(state));
  1938. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  1939. * ```
  1940. * @param {String} `state` The object returned from the `.parse` method.
  1941. * @param {Object} `options`
  1942. * @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result.
  1943. * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
  1944. * @return {RegExp} Returns a regex created from the given pattern.
  1945. * @api public
  1946. */
  1947. picomatch$7.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
  1948. if (!input || typeof input !== 'string') {
  1949. throw new TypeError('Expected a non-empty string');
  1950. }
  1951. let parsed = { negated: false, fastpaths: true };
  1952. if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
  1953. parsed.output = parse$m.fastpaths(input, options);
  1954. }
  1955. if (!parsed.output) {
  1956. parsed = parse$m(input, options);
  1957. }
  1958. return picomatch$7.compileRe(parsed, options, returnOutput, returnState);
  1959. };
  1960. /**
  1961. * Create a regular expression from the given regex source string.
  1962. *
  1963. * ```js
  1964. * const picomatch = require('picomatch');
  1965. * // picomatch.toRegex(source[, options]);
  1966. *
  1967. * const { output } = picomatch.parse('*.js');
  1968. * console.log(picomatch.toRegex(output));
  1969. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  1970. * ```
  1971. * @param {String} `source` Regular expression source string.
  1972. * @param {Object} `options`
  1973. * @return {RegExp}
  1974. * @api public
  1975. */
  1976. picomatch$7.toRegex = (source, options) => {
  1977. try {
  1978. const opts = options || {};
  1979. return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
  1980. } catch (err) {
  1981. if (options && options.debug === true) throw err;
  1982. return /$^/;
  1983. }
  1984. };
  1985. /**
  1986. * Picomatch constants.
  1987. * @return {Object}
  1988. */
  1989. picomatch$7.constants = constants$7;
  1990. /**
  1991. * Expose "picomatch"
  1992. */
  1993. var picomatch_1$1 = picomatch$7;
  1994. var picomatch$6 = picomatch_1$1;
  1995. // Helper since Typescript can't detect readonly arrays with Array.isArray
  1996. function isArray$3(arg) {
  1997. return Array.isArray(arg);
  1998. }
  1999. function ensureArray$1(thing) {
  2000. if (isArray$3(thing))
  2001. return thing;
  2002. if (thing == null)
  2003. return [];
  2004. return [thing];
  2005. }
  2006. const normalizePath$5 = function normalizePath(filename) {
  2007. return filename.split(path$r.win32.sep).join(path$r.posix.sep);
  2008. };
  2009. function getMatcherString$1(id, resolutionBase) {
  2010. if (resolutionBase === false || path$r.isAbsolute(id) || id.startsWith('*')) {
  2011. return normalizePath$5(id);
  2012. }
  2013. // resolve('') is valid and will default to process.cwd()
  2014. const basePath = normalizePath$5(path$r.resolve(resolutionBase || ''))
  2015. // escape all possible (posix + win) path characters that might interfere with regex
  2016. .replace(/[-^$*+?.()|[\]{}]/g, '\\$&');
  2017. // Note that we use posix.join because:
  2018. // 1. the basePath has been normalized to use /
  2019. // 2. the incoming glob (id) matcher, also uses /
  2020. // otherwise Node will force backslash (\) on windows
  2021. return path$r.posix.join(basePath, normalizePath$5(id));
  2022. }
  2023. const createFilter$1 = function createFilter(include, exclude, options) {
  2024. const resolutionBase = options && options.resolve;
  2025. const getMatcher = (id) => id instanceof RegExp
  2026. ? id
  2027. : {
  2028. test: (what) => {
  2029. // this refactor is a tad overly verbose but makes for easy debugging
  2030. const pattern = getMatcherString$1(id, resolutionBase);
  2031. const fn = picomatch$6(pattern, { dot: true });
  2032. const result = fn(what);
  2033. return result;
  2034. }
  2035. };
  2036. const includeMatchers = ensureArray$1(include).map(getMatcher);
  2037. const excludeMatchers = ensureArray$1(exclude).map(getMatcher);
  2038. return function result(id) {
  2039. if (typeof id !== 'string')
  2040. return false;
  2041. if (/\0/.test(id))
  2042. return false;
  2043. const pathId = normalizePath$5(id);
  2044. for (let i = 0; i < excludeMatchers.length; ++i) {
  2045. const matcher = excludeMatchers[i];
  2046. if (matcher.test(pathId))
  2047. return false;
  2048. }
  2049. for (let i = 0; i < includeMatchers.length; ++i) {
  2050. const matcher = includeMatchers[i];
  2051. if (matcher.test(pathId))
  2052. return true;
  2053. }
  2054. return !includeMatchers.length;
  2055. };
  2056. };
  2057. const reservedWords$2 = 'break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public';
  2058. const builtins$2 = 'arguments Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl';
  2059. const forbiddenIdentifiers$1 = new Set(`${reservedWords$2} ${builtins$2}`.split(' '));
  2060. forbiddenIdentifiers$1.add('');
  2061. const makeLegalIdentifier$1 = function makeLegalIdentifier(str) {
  2062. let identifier = str
  2063. .replace(/-(\w)/g, (_, letter) => letter.toUpperCase())
  2064. .replace(/[^$_a-zA-Z0-9]/g, '_');
  2065. if (/\d/.test(identifier[0]) || forbiddenIdentifiers$1.has(identifier)) {
  2066. identifier = `_${identifier}`;
  2067. }
  2068. return identifier || '_';
  2069. };
  2070. function stringify$8(obj) {
  2071. return (JSON.stringify(obj) || 'undefined').replace(/[\u2028\u2029]/g, (char) => `\\u${`000${char.charCodeAt(0).toString(16)}`.slice(-4)}`);
  2072. }
  2073. function serializeArray(arr, indent, baseIndent) {
  2074. let output = '[';
  2075. const separator = indent ? `\n${baseIndent}${indent}` : '';
  2076. for (let i = 0; i < arr.length; i++) {
  2077. const key = arr[i];
  2078. output += `${i > 0 ? ',' : ''}${separator}${serialize(key, indent, baseIndent + indent)}`;
  2079. }
  2080. return `${output}${indent ? `\n${baseIndent}` : ''}]`;
  2081. }
  2082. function serializeObject(obj, indent, baseIndent) {
  2083. let output = '{';
  2084. const separator = indent ? `\n${baseIndent}${indent}` : '';
  2085. const entries = Object.entries(obj);
  2086. for (let i = 0; i < entries.length; i++) {
  2087. const [key, value] = entries[i];
  2088. const stringKey = makeLegalIdentifier$1(key) === key ? key : stringify$8(key);
  2089. output += `${i > 0 ? ',' : ''}${separator}${stringKey}:${indent ? ' ' : ''}${serialize(value, indent, baseIndent + indent)}`;
  2090. }
  2091. return `${output}${indent ? `\n${baseIndent}` : ''}}`;
  2092. }
  2093. function serialize(obj, indent, baseIndent) {
  2094. if (typeof obj === 'object' && obj !== null) {
  2095. if (Array.isArray(obj))
  2096. return serializeArray(obj, indent, baseIndent);
  2097. if (obj instanceof Date)
  2098. return `new Date(${obj.getTime()})`;
  2099. if (obj instanceof RegExp)
  2100. return obj.toString();
  2101. return serializeObject(obj, indent, baseIndent);
  2102. }
  2103. if (typeof obj === 'number') {
  2104. if (obj === Infinity)
  2105. return 'Infinity';
  2106. if (obj === -Infinity)
  2107. return '-Infinity';
  2108. if (obj === 0)
  2109. return 1 / obj === Infinity ? '0' : '-0';
  2110. if (obj !== obj)
  2111. return 'NaN'; // eslint-disable-line no-self-compare
  2112. }
  2113. if (typeof obj === 'symbol') {
  2114. const key = Symbol.keyFor(obj);
  2115. if (key !== undefined)
  2116. return `Symbol.for(${stringify$8(key)})`;
  2117. }
  2118. if (typeof obj === 'bigint')
  2119. return `${obj}n`;
  2120. return stringify$8(obj);
  2121. }
  2122. const dataToEsm = function dataToEsm(data, options = {}) {
  2123. const t = options.compact ? '' : 'indent' in options ? options.indent : '\t';
  2124. const _ = options.compact ? '' : ' ';
  2125. const n = options.compact ? '' : '\n';
  2126. const declarationType = options.preferConst ? 'const' : 'var';
  2127. if (options.namedExports === false ||
  2128. typeof data !== 'object' ||
  2129. Array.isArray(data) ||
  2130. data instanceof Date ||
  2131. data instanceof RegExp ||
  2132. data === null) {
  2133. const code = serialize(data, options.compact ? null : t, '');
  2134. const magic = _ || (/^[{[\-\/]/.test(code) ? '' : ' '); // eslint-disable-line no-useless-escape
  2135. return `export default${magic}${code};`;
  2136. }
  2137. let namedExportCode = '';
  2138. const defaultExportRows = [];
  2139. for (const [key, value] of Object.entries(data)) {
  2140. if (key === makeLegalIdentifier$1(key)) {
  2141. if (options.objectShorthand)
  2142. defaultExportRows.push(key);
  2143. else
  2144. defaultExportRows.push(`${key}:${_}${key}`);
  2145. namedExportCode += `export ${declarationType} ${key}${_}=${_}${serialize(value, options.compact ? null : t, '')};${n}`;
  2146. }
  2147. else {
  2148. defaultExportRows.push(`${stringify$8(key)}:${_}${serialize(value, options.compact ? null : t, '')}`);
  2149. }
  2150. }
  2151. return `${namedExportCode}export default${_}{${n}${t}${defaultExportRows.join(`,${n}${t}`)}${n}};${n}`;
  2152. };
  2153. function matches(pattern, importee) {
  2154. if (pattern instanceof RegExp) {
  2155. return pattern.test(importee);
  2156. }
  2157. if (importee.length < pattern.length) {
  2158. return false;
  2159. }
  2160. if (importee === pattern) {
  2161. return true;
  2162. }
  2163. // eslint-disable-next-line prefer-template
  2164. return importee.startsWith(pattern + '/');
  2165. }
  2166. function getEntries({ entries, customResolver }) {
  2167. if (!entries) {
  2168. return [];
  2169. }
  2170. const resolverFunctionFromOptions = resolveCustomResolver(customResolver);
  2171. if (Array.isArray(entries)) {
  2172. return entries.map((entry) => {
  2173. return {
  2174. find: entry.find,
  2175. replacement: entry.replacement,
  2176. resolverFunction: resolveCustomResolver(entry.customResolver) || resolverFunctionFromOptions
  2177. };
  2178. });
  2179. }
  2180. return Object.entries(entries).map(([key, value]) => {
  2181. return { find: key, replacement: value, resolverFunction: resolverFunctionFromOptions };
  2182. });
  2183. }
  2184. function resolveCustomResolver(customResolver) {
  2185. if (customResolver) {
  2186. if (typeof customResolver === 'function') {
  2187. return customResolver;
  2188. }
  2189. if (typeof customResolver.resolveId === 'function') {
  2190. return customResolver.resolveId;
  2191. }
  2192. }
  2193. return null;
  2194. }
  2195. function alias$1(options = {}) {
  2196. const entries = getEntries(options);
  2197. if (entries.length === 0) {
  2198. return {
  2199. name: 'alias',
  2200. resolveId: () => null
  2201. };
  2202. }
  2203. return {
  2204. name: 'alias',
  2205. async buildStart(inputOptions) {
  2206. await Promise.all([...(Array.isArray(options.entries) ? options.entries : []), options].map(({ customResolver }) => customResolver &&
  2207. typeof customResolver === 'object' &&
  2208. typeof customResolver.buildStart === 'function' &&
  2209. customResolver.buildStart.call(this, inputOptions)));
  2210. },
  2211. resolveId(importee, importer, resolveOptions) {
  2212. if (!importer) {
  2213. return null;
  2214. }
  2215. // First match is supposed to be the correct one
  2216. const matchedEntry = entries.find((entry) => matches(entry.find, importee));
  2217. if (!matchedEntry) {
  2218. return null;
  2219. }
  2220. const updatedId = importee.replace(matchedEntry.find, matchedEntry.replacement);
  2221. if (matchedEntry.resolverFunction) {
  2222. return matchedEntry.resolverFunction.call(this, updatedId, importer, resolveOptions);
  2223. }
  2224. return this.resolve(updatedId, importer, Object.assign({ skipSelf: true }, resolveOptions)).then((resolved) => resolved || { id: updatedId });
  2225. }
  2226. };
  2227. }
  2228. var utils$l = {};
  2229. const path$n = path__default;
  2230. const WIN_SLASH = '\\\\/';
  2231. const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
  2232. /**
  2233. * Posix glob regex
  2234. */
  2235. const DOT_LITERAL = '\\.';
  2236. const PLUS_LITERAL = '\\+';
  2237. const QMARK_LITERAL = '\\?';
  2238. const SLASH_LITERAL = '\\/';
  2239. const ONE_CHAR = '(?=.)';
  2240. const QMARK = '[^/]';
  2241. const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
  2242. const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
  2243. const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
  2244. const NO_DOT = `(?!${DOT_LITERAL})`;
  2245. const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
  2246. const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
  2247. const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
  2248. const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
  2249. const STAR$1 = `${QMARK}*?`;
  2250. const POSIX_CHARS = {
  2251. DOT_LITERAL,
  2252. PLUS_LITERAL,
  2253. QMARK_LITERAL,
  2254. SLASH_LITERAL,
  2255. ONE_CHAR,
  2256. QMARK,
  2257. END_ANCHOR,
  2258. DOTS_SLASH,
  2259. NO_DOT,
  2260. NO_DOTS,
  2261. NO_DOT_SLASH,
  2262. NO_DOTS_SLASH,
  2263. QMARK_NO_DOT,
  2264. STAR: STAR$1,
  2265. START_ANCHOR
  2266. };
  2267. /**
  2268. * Windows glob regex
  2269. */
  2270. const WINDOWS_CHARS = {
  2271. ...POSIX_CHARS,
  2272. SLASH_LITERAL: `[${WIN_SLASH}]`,
  2273. QMARK: WIN_NO_SLASH,
  2274. STAR: `${WIN_NO_SLASH}*?`,
  2275. DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
  2276. NO_DOT: `(?!${DOT_LITERAL})`,
  2277. NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  2278. NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
  2279. NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  2280. QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
  2281. START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
  2282. END_ANCHOR: `(?:[${WIN_SLASH}]|$)`
  2283. };
  2284. /**
  2285. * POSIX Bracket Regex
  2286. */
  2287. const POSIX_REGEX_SOURCE$1 = {
  2288. alnum: 'a-zA-Z0-9',
  2289. alpha: 'a-zA-Z',
  2290. ascii: '\\x00-\\x7F',
  2291. blank: ' \\t',
  2292. cntrl: '\\x00-\\x1F\\x7F',
  2293. digit: '0-9',
  2294. graph: '\\x21-\\x7E',
  2295. lower: 'a-z',
  2296. print: '\\x20-\\x7E ',
  2297. punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
  2298. space: ' \\t\\r\\n\\v\\f',
  2299. upper: 'A-Z',
  2300. word: 'A-Za-z0-9_',
  2301. xdigit: 'A-Fa-f0-9'
  2302. };
  2303. var constants$6 = {
  2304. MAX_LENGTH: 1024 * 64,
  2305. POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1,
  2306. // regular expressions
  2307. REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
  2308. REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
  2309. REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
  2310. REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
  2311. REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
  2312. REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
  2313. // Replace globs with equivalent patterns to reduce parsing time.
  2314. REPLACEMENTS: {
  2315. '***': '*',
  2316. '**/**': '**',
  2317. '**/**/**': '**'
  2318. },
  2319. // Digits
  2320. CHAR_0: 48, /* 0 */
  2321. CHAR_9: 57, /* 9 */
  2322. // Alphabet chars.
  2323. CHAR_UPPERCASE_A: 65, /* A */
  2324. CHAR_LOWERCASE_A: 97, /* a */
  2325. CHAR_UPPERCASE_Z: 90, /* Z */
  2326. CHAR_LOWERCASE_Z: 122, /* z */
  2327. CHAR_LEFT_PARENTHESES: 40, /* ( */
  2328. CHAR_RIGHT_PARENTHESES: 41, /* ) */
  2329. CHAR_ASTERISK: 42, /* * */
  2330. // Non-alphabetic chars.
  2331. CHAR_AMPERSAND: 38, /* & */
  2332. CHAR_AT: 64, /* @ */
  2333. CHAR_BACKWARD_SLASH: 92, /* \ */
  2334. CHAR_CARRIAGE_RETURN: 13, /* \r */
  2335. CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */
  2336. CHAR_COLON: 58, /* : */
  2337. CHAR_COMMA: 44, /* , */
  2338. CHAR_DOT: 46, /* . */
  2339. CHAR_DOUBLE_QUOTE: 34, /* " */
  2340. CHAR_EQUAL: 61, /* = */
  2341. CHAR_EXCLAMATION_MARK: 33, /* ! */
  2342. CHAR_FORM_FEED: 12, /* \f */
  2343. CHAR_FORWARD_SLASH: 47, /* / */
  2344. CHAR_GRAVE_ACCENT: 96, /* ` */
  2345. CHAR_HASH: 35, /* # */
  2346. CHAR_HYPHEN_MINUS: 45, /* - */
  2347. CHAR_LEFT_ANGLE_BRACKET: 60, /* < */
  2348. CHAR_LEFT_CURLY_BRACE: 123, /* { */
  2349. CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */
  2350. CHAR_LINE_FEED: 10, /* \n */
  2351. CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
  2352. CHAR_PERCENT: 37, /* % */
  2353. CHAR_PLUS: 43, /* + */
  2354. CHAR_QUESTION_MARK: 63, /* ? */
  2355. CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */
  2356. CHAR_RIGHT_CURLY_BRACE: 125, /* } */
  2357. CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */
  2358. CHAR_SEMICOLON: 59, /* ; */
  2359. CHAR_SINGLE_QUOTE: 39, /* ' */
  2360. CHAR_SPACE: 32, /* */
  2361. CHAR_TAB: 9, /* \t */
  2362. CHAR_UNDERSCORE: 95, /* _ */
  2363. CHAR_VERTICAL_LINE: 124, /* | */
  2364. CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
  2365. SEP: path$n.sep,
  2366. /**
  2367. * Create EXTGLOB_CHARS
  2368. */
  2369. extglobChars(chars) {
  2370. return {
  2371. '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
  2372. '?': { type: 'qmark', open: '(?:', close: ')?' },
  2373. '+': { type: 'plus', open: '(?:', close: ')+' },
  2374. '*': { type: 'star', open: '(?:', close: ')*' },
  2375. '@': { type: 'at', open: '(?:', close: ')' }
  2376. };
  2377. },
  2378. /**
  2379. * Create GLOB_CHARS
  2380. */
  2381. globChars(win32) {
  2382. return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
  2383. }
  2384. };
  2385. (function (exports) {
  2386. const path = path__default;
  2387. const win32 = process.platform === 'win32';
  2388. const {
  2389. REGEX_BACKSLASH,
  2390. REGEX_REMOVE_BACKSLASH,
  2391. REGEX_SPECIAL_CHARS,
  2392. REGEX_SPECIAL_CHARS_GLOBAL
  2393. } = constants$6;
  2394. exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  2395. exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
  2396. exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
  2397. exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
  2398. exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
  2399. exports.removeBackslashes = str => {
  2400. return str.replace(REGEX_REMOVE_BACKSLASH, match => {
  2401. return match === '\\' ? '' : match;
  2402. });
  2403. };
  2404. exports.supportsLookbehinds = () => {
  2405. const segs = process.version.slice(1).split('.').map(Number);
  2406. if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) {
  2407. return true;
  2408. }
  2409. return false;
  2410. };
  2411. exports.isWindows = options => {
  2412. if (options && typeof options.windows === 'boolean') {
  2413. return options.windows;
  2414. }
  2415. return win32 === true || path.sep === '\\';
  2416. };
  2417. exports.escapeLast = (input, char, lastIdx) => {
  2418. const idx = input.lastIndexOf(char, lastIdx);
  2419. if (idx === -1) return input;
  2420. if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
  2421. return `${input.slice(0, idx)}\\${input.slice(idx)}`;
  2422. };
  2423. exports.removePrefix = (input, state = {}) => {
  2424. let output = input;
  2425. if (output.startsWith('./')) {
  2426. output = output.slice(2);
  2427. state.prefix = './';
  2428. }
  2429. return output;
  2430. };
  2431. exports.wrapOutput = (input, state = {}, options = {}) => {
  2432. const prepend = options.contains ? '' : '^';
  2433. const append = options.contains ? '' : '$';
  2434. let output = `${prepend}(?:${input})${append}`;
  2435. if (state.negated === true) {
  2436. output = `(?:^(?!${output}).*$)`;
  2437. }
  2438. return output;
  2439. };
  2440. }(utils$l));
  2441. const utils$k = utils$l;
  2442. const {
  2443. CHAR_ASTERISK, /* * */
  2444. CHAR_AT, /* @ */
  2445. CHAR_BACKWARD_SLASH, /* \ */
  2446. CHAR_COMMA: CHAR_COMMA$1, /* , */
  2447. CHAR_DOT: CHAR_DOT$1, /* . */
  2448. CHAR_EXCLAMATION_MARK, /* ! */
  2449. CHAR_FORWARD_SLASH, /* / */
  2450. CHAR_LEFT_CURLY_BRACE: CHAR_LEFT_CURLY_BRACE$1, /* { */
  2451. CHAR_LEFT_PARENTHESES: CHAR_LEFT_PARENTHESES$1, /* ( */
  2452. CHAR_LEFT_SQUARE_BRACKET: CHAR_LEFT_SQUARE_BRACKET$1, /* [ */
  2453. CHAR_PLUS, /* + */
  2454. CHAR_QUESTION_MARK, /* ? */
  2455. CHAR_RIGHT_CURLY_BRACE: CHAR_RIGHT_CURLY_BRACE$1, /* } */
  2456. CHAR_RIGHT_PARENTHESES: CHAR_RIGHT_PARENTHESES$1, /* ) */
  2457. CHAR_RIGHT_SQUARE_BRACKET: CHAR_RIGHT_SQUARE_BRACKET$1 /* ] */
  2458. } = constants$6;
  2459. const isPathSeparator = code => {
  2460. return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
  2461. };
  2462. const depth = token => {
  2463. if (token.isPrefix !== true) {
  2464. token.depth = token.isGlobstar ? Infinity : 1;
  2465. }
  2466. };
  2467. /**
  2468. * Quickly scans a glob pattern and returns an object with a handful of
  2469. * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
  2470. * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
  2471. * with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
  2472. *
  2473. * ```js
  2474. * const pm = require('picomatch');
  2475. * console.log(pm.scan('foo/bar/*.js'));
  2476. * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
  2477. * ```
  2478. * @param {String} `str`
  2479. * @param {Object} `options`
  2480. * @return {Object} Returns an object with tokens and regex source string.
  2481. * @api public
  2482. */
  2483. const scan$1 = (input, options) => {
  2484. const opts = options || {};
  2485. const length = input.length - 1;
  2486. const scanToEnd = opts.parts === true || opts.scanToEnd === true;
  2487. const slashes = [];
  2488. const tokens = [];
  2489. const parts = [];
  2490. let str = input;
  2491. let index = -1;
  2492. let start = 0;
  2493. let lastIndex = 0;
  2494. let isBrace = false;
  2495. let isBracket = false;
  2496. let isGlob = false;
  2497. let isExtglob = false;
  2498. let isGlobstar = false;
  2499. let braceEscaped = false;
  2500. let backslashes = false;
  2501. let negated = false;
  2502. let negatedExtglob = false;
  2503. let finished = false;
  2504. let braces = 0;
  2505. let prev;
  2506. let code;
  2507. let token = { value: '', depth: 0, isGlob: false };
  2508. const eos = () => index >= length;
  2509. const peek = () => str.charCodeAt(index + 1);
  2510. const advance = () => {
  2511. prev = code;
  2512. return str.charCodeAt(++index);
  2513. };
  2514. while (index < length) {
  2515. code = advance();
  2516. let next;
  2517. if (code === CHAR_BACKWARD_SLASH) {
  2518. backslashes = token.backslashes = true;
  2519. code = advance();
  2520. if (code === CHAR_LEFT_CURLY_BRACE$1) {
  2521. braceEscaped = true;
  2522. }
  2523. continue;
  2524. }
  2525. if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE$1) {
  2526. braces++;
  2527. while (eos() !== true && (code = advance())) {
  2528. if (code === CHAR_BACKWARD_SLASH) {
  2529. backslashes = token.backslashes = true;
  2530. advance();
  2531. continue;
  2532. }
  2533. if (code === CHAR_LEFT_CURLY_BRACE$1) {
  2534. braces++;
  2535. continue;
  2536. }
  2537. if (braceEscaped !== true && code === CHAR_DOT$1 && (code = advance()) === CHAR_DOT$1) {
  2538. isBrace = token.isBrace = true;
  2539. isGlob = token.isGlob = true;
  2540. finished = true;
  2541. if (scanToEnd === true) {
  2542. continue;
  2543. }
  2544. break;
  2545. }
  2546. if (braceEscaped !== true && code === CHAR_COMMA$1) {
  2547. isBrace = token.isBrace = true;
  2548. isGlob = token.isGlob = true;
  2549. finished = true;
  2550. if (scanToEnd === true) {
  2551. continue;
  2552. }
  2553. break;
  2554. }
  2555. if (code === CHAR_RIGHT_CURLY_BRACE$1) {
  2556. braces--;
  2557. if (braces === 0) {
  2558. braceEscaped = false;
  2559. isBrace = token.isBrace = true;
  2560. finished = true;
  2561. break;
  2562. }
  2563. }
  2564. }
  2565. if (scanToEnd === true) {
  2566. continue;
  2567. }
  2568. break;
  2569. }
  2570. if (code === CHAR_FORWARD_SLASH) {
  2571. slashes.push(index);
  2572. tokens.push(token);
  2573. token = { value: '', depth: 0, isGlob: false };
  2574. if (finished === true) continue;
  2575. if (prev === CHAR_DOT$1 && index === (start + 1)) {
  2576. start += 2;
  2577. continue;
  2578. }
  2579. lastIndex = index + 1;
  2580. continue;
  2581. }
  2582. if (opts.noext !== true) {
  2583. const isExtglobChar = code === CHAR_PLUS
  2584. || code === CHAR_AT
  2585. || code === CHAR_ASTERISK
  2586. || code === CHAR_QUESTION_MARK
  2587. || code === CHAR_EXCLAMATION_MARK;
  2588. if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES$1) {
  2589. isGlob = token.isGlob = true;
  2590. isExtglob = token.isExtglob = true;
  2591. finished = true;
  2592. if (code === CHAR_EXCLAMATION_MARK && index === start) {
  2593. negatedExtglob = true;
  2594. }
  2595. if (scanToEnd === true) {
  2596. while (eos() !== true && (code = advance())) {
  2597. if (code === CHAR_BACKWARD_SLASH) {
  2598. backslashes = token.backslashes = true;
  2599. code = advance();
  2600. continue;
  2601. }
  2602. if (code === CHAR_RIGHT_PARENTHESES$1) {
  2603. isGlob = token.isGlob = true;
  2604. finished = true;
  2605. break;
  2606. }
  2607. }
  2608. continue;
  2609. }
  2610. break;
  2611. }
  2612. }
  2613. if (code === CHAR_ASTERISK) {
  2614. if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
  2615. isGlob = token.isGlob = true;
  2616. finished = true;
  2617. if (scanToEnd === true) {
  2618. continue;
  2619. }
  2620. break;
  2621. }
  2622. if (code === CHAR_QUESTION_MARK) {
  2623. isGlob = token.isGlob = true;
  2624. finished = true;
  2625. if (scanToEnd === true) {
  2626. continue;
  2627. }
  2628. break;
  2629. }
  2630. if (code === CHAR_LEFT_SQUARE_BRACKET$1) {
  2631. while (eos() !== true && (next = advance())) {
  2632. if (next === CHAR_BACKWARD_SLASH) {
  2633. backslashes = token.backslashes = true;
  2634. advance();
  2635. continue;
  2636. }
  2637. if (next === CHAR_RIGHT_SQUARE_BRACKET$1) {
  2638. isBracket = token.isBracket = true;
  2639. isGlob = token.isGlob = true;
  2640. finished = true;
  2641. break;
  2642. }
  2643. }
  2644. if (scanToEnd === true) {
  2645. continue;
  2646. }
  2647. break;
  2648. }
  2649. if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
  2650. negated = token.negated = true;
  2651. start++;
  2652. continue;
  2653. }
  2654. if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES$1) {
  2655. isGlob = token.isGlob = true;
  2656. if (scanToEnd === true) {
  2657. while (eos() !== true && (code = advance())) {
  2658. if (code === CHAR_LEFT_PARENTHESES$1) {
  2659. backslashes = token.backslashes = true;
  2660. code = advance();
  2661. continue;
  2662. }
  2663. if (code === CHAR_RIGHT_PARENTHESES$1) {
  2664. finished = true;
  2665. break;
  2666. }
  2667. }
  2668. continue;
  2669. }
  2670. break;
  2671. }
  2672. if (isGlob === true) {
  2673. finished = true;
  2674. if (scanToEnd === true) {
  2675. continue;
  2676. }
  2677. break;
  2678. }
  2679. }
  2680. if (opts.noext === true) {
  2681. isExtglob = false;
  2682. isGlob = false;
  2683. }
  2684. let base = str;
  2685. let prefix = '';
  2686. let glob = '';
  2687. if (start > 0) {
  2688. prefix = str.slice(0, start);
  2689. str = str.slice(start);
  2690. lastIndex -= start;
  2691. }
  2692. if (base && isGlob === true && lastIndex > 0) {
  2693. base = str.slice(0, lastIndex);
  2694. glob = str.slice(lastIndex);
  2695. } else if (isGlob === true) {
  2696. base = '';
  2697. glob = str;
  2698. } else {
  2699. base = str;
  2700. }
  2701. if (base && base !== '' && base !== '/' && base !== str) {
  2702. if (isPathSeparator(base.charCodeAt(base.length - 1))) {
  2703. base = base.slice(0, -1);
  2704. }
  2705. }
  2706. if (opts.unescape === true) {
  2707. if (glob) glob = utils$k.removeBackslashes(glob);
  2708. if (base && backslashes === true) {
  2709. base = utils$k.removeBackslashes(base);
  2710. }
  2711. }
  2712. const state = {
  2713. prefix,
  2714. input,
  2715. start,
  2716. base,
  2717. glob,
  2718. isBrace,
  2719. isBracket,
  2720. isGlob,
  2721. isExtglob,
  2722. isGlobstar,
  2723. negated,
  2724. negatedExtglob
  2725. };
  2726. if (opts.tokens === true) {
  2727. state.maxDepth = 0;
  2728. if (!isPathSeparator(code)) {
  2729. tokens.push(token);
  2730. }
  2731. state.tokens = tokens;
  2732. }
  2733. if (opts.parts === true || opts.tokens === true) {
  2734. let prevIndex;
  2735. for (let idx = 0; idx < slashes.length; idx++) {
  2736. const n = prevIndex ? prevIndex + 1 : start;
  2737. const i = slashes[idx];
  2738. const value = input.slice(n, i);
  2739. if (opts.tokens) {
  2740. if (idx === 0 && start !== 0) {
  2741. tokens[idx].isPrefix = true;
  2742. tokens[idx].value = prefix;
  2743. } else {
  2744. tokens[idx].value = value;
  2745. }
  2746. depth(tokens[idx]);
  2747. state.maxDepth += tokens[idx].depth;
  2748. }
  2749. if (idx !== 0 || value !== '') {
  2750. parts.push(value);
  2751. }
  2752. prevIndex = i;
  2753. }
  2754. if (prevIndex && prevIndex + 1 < input.length) {
  2755. const value = input.slice(prevIndex + 1);
  2756. parts.push(value);
  2757. if (opts.tokens) {
  2758. tokens[tokens.length - 1].value = value;
  2759. depth(tokens[tokens.length - 1]);
  2760. state.maxDepth += tokens[tokens.length - 1].depth;
  2761. }
  2762. }
  2763. state.slashes = slashes;
  2764. state.parts = parts;
  2765. }
  2766. return state;
  2767. };
  2768. var scan_1 = scan$1;
  2769. const constants$5 = constants$6;
  2770. const utils$j = utils$l;
  2771. /**
  2772. * Constants
  2773. */
  2774. const {
  2775. MAX_LENGTH: MAX_LENGTH$1,
  2776. POSIX_REGEX_SOURCE,
  2777. REGEX_NON_SPECIAL_CHARS,
  2778. REGEX_SPECIAL_CHARS_BACKREF,
  2779. REPLACEMENTS
  2780. } = constants$5;
  2781. /**
  2782. * Helpers
  2783. */
  2784. const expandRange = (args, options) => {
  2785. if (typeof options.expandRange === 'function') {
  2786. return options.expandRange(...args, options);
  2787. }
  2788. args.sort();
  2789. const value = `[${args.join('-')}]`;
  2790. return value;
  2791. };
  2792. /**
  2793. * Create the message for a syntax error
  2794. */
  2795. const syntaxError$1 = (type, char) => {
  2796. return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
  2797. };
  2798. /**
  2799. * Parse the given input string.
  2800. * @param {String} input
  2801. * @param {Object} options
  2802. * @return {Object}
  2803. */
  2804. const parse$l = (input, options) => {
  2805. if (typeof input !== 'string') {
  2806. throw new TypeError('Expected a string');
  2807. }
  2808. input = REPLACEMENTS[input] || input;
  2809. const opts = { ...options };
  2810. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1;
  2811. let len = input.length;
  2812. if (len > max) {
  2813. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  2814. }
  2815. const bos = { type: 'bos', value: '', output: opts.prepend || '' };
  2816. const tokens = [bos];
  2817. const capture = opts.capture ? '' : '?:';
  2818. const win32 = utils$j.isWindows(options);
  2819. // create constants based on platform, for windows or posix
  2820. const PLATFORM_CHARS = constants$5.globChars(win32);
  2821. const EXTGLOB_CHARS = constants$5.extglobChars(PLATFORM_CHARS);
  2822. const {
  2823. DOT_LITERAL,
  2824. PLUS_LITERAL,
  2825. SLASH_LITERAL,
  2826. ONE_CHAR,
  2827. DOTS_SLASH,
  2828. NO_DOT,
  2829. NO_DOT_SLASH,
  2830. NO_DOTS_SLASH,
  2831. QMARK,
  2832. QMARK_NO_DOT,
  2833. STAR,
  2834. START_ANCHOR
  2835. } = PLATFORM_CHARS;
  2836. const globstar = opts => {
  2837. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  2838. };
  2839. const nodot = opts.dot ? '' : NO_DOT;
  2840. const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
  2841. let star = opts.bash === true ? globstar(opts) : STAR;
  2842. if (opts.capture) {
  2843. star = `(${star})`;
  2844. }
  2845. // minimatch options support
  2846. if (typeof opts.noext === 'boolean') {
  2847. opts.noextglob = opts.noext;
  2848. }
  2849. const state = {
  2850. input,
  2851. index: -1,
  2852. start: 0,
  2853. dot: opts.dot === true,
  2854. consumed: '',
  2855. output: '',
  2856. prefix: '',
  2857. backtrack: false,
  2858. negated: false,
  2859. brackets: 0,
  2860. braces: 0,
  2861. parens: 0,
  2862. quotes: 0,
  2863. globstar: false,
  2864. tokens
  2865. };
  2866. input = utils$j.removePrefix(input, state);
  2867. len = input.length;
  2868. const extglobs = [];
  2869. const braces = [];
  2870. const stack = [];
  2871. let prev = bos;
  2872. let value;
  2873. /**
  2874. * Tokenizing helpers
  2875. */
  2876. const eos = () => state.index === len - 1;
  2877. const peek = state.peek = (n = 1) => input[state.index + n];
  2878. const advance = state.advance = () => input[++state.index] || '';
  2879. const remaining = () => input.slice(state.index + 1);
  2880. const consume = (value = '', num = 0) => {
  2881. state.consumed += value;
  2882. state.index += num;
  2883. };
  2884. const append = token => {
  2885. state.output += token.output != null ? token.output : token.value;
  2886. consume(token.value);
  2887. };
  2888. const negate = () => {
  2889. let count = 1;
  2890. while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
  2891. advance();
  2892. state.start++;
  2893. count++;
  2894. }
  2895. if (count % 2 === 0) {
  2896. return false;
  2897. }
  2898. state.negated = true;
  2899. state.start++;
  2900. return true;
  2901. };
  2902. const increment = type => {
  2903. state[type]++;
  2904. stack.push(type);
  2905. };
  2906. const decrement = type => {
  2907. state[type]--;
  2908. stack.pop();
  2909. };
  2910. /**
  2911. * Push tokens onto the tokens array. This helper speeds up
  2912. * tokenizing by 1) helping us avoid backtracking as much as possible,
  2913. * and 2) helping us avoid creating extra tokens when consecutive
  2914. * characters are plain text. This improves performance and simplifies
  2915. * lookbehinds.
  2916. */
  2917. const push = tok => {
  2918. if (prev.type === 'globstar') {
  2919. const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
  2920. const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));
  2921. if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
  2922. state.output = state.output.slice(0, -prev.output.length);
  2923. prev.type = 'star';
  2924. prev.value = '*';
  2925. prev.output = star;
  2926. state.output += prev.output;
  2927. }
  2928. }
  2929. if (extglobs.length && tok.type !== 'paren') {
  2930. extglobs[extglobs.length - 1].inner += tok.value;
  2931. }
  2932. if (tok.value || tok.output) append(tok);
  2933. if (prev && prev.type === 'text' && tok.type === 'text') {
  2934. prev.value += tok.value;
  2935. prev.output = (prev.output || '') + tok.value;
  2936. return;
  2937. }
  2938. tok.prev = prev;
  2939. tokens.push(tok);
  2940. prev = tok;
  2941. };
  2942. const extglobOpen = (type, value) => {
  2943. const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };
  2944. token.prev = prev;
  2945. token.parens = state.parens;
  2946. token.output = state.output;
  2947. const output = (opts.capture ? '(' : '') + token.open;
  2948. increment('parens');
  2949. push({ type, value, output: state.output ? '' : ONE_CHAR });
  2950. push({ type: 'paren', extglob: true, value: advance(), output });
  2951. extglobs.push(token);
  2952. };
  2953. const extglobClose = token => {
  2954. let output = token.close + (opts.capture ? ')' : '');
  2955. let rest;
  2956. if (token.type === 'negate') {
  2957. let extglobStar = star;
  2958. if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
  2959. extglobStar = globstar(opts);
  2960. }
  2961. if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
  2962. output = token.close = `)$))${extglobStar}`;
  2963. }
  2964. if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
  2965. output = token.close = `)${rest})${extglobStar})`;
  2966. }
  2967. if (token.prev.type === 'bos') {
  2968. state.negatedExtglob = true;
  2969. }
  2970. }
  2971. push({ type: 'paren', extglob: true, value, output });
  2972. decrement('parens');
  2973. };
  2974. /**
  2975. * Fast paths
  2976. */
  2977. if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
  2978. let backslashes = false;
  2979. let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
  2980. if (first === '\\') {
  2981. backslashes = true;
  2982. return m;
  2983. }
  2984. if (first === '?') {
  2985. if (esc) {
  2986. return esc + first + (rest ? QMARK.repeat(rest.length) : '');
  2987. }
  2988. if (index === 0) {
  2989. return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
  2990. }
  2991. return QMARK.repeat(chars.length);
  2992. }
  2993. if (first === '.') {
  2994. return DOT_LITERAL.repeat(chars.length);
  2995. }
  2996. if (first === '*') {
  2997. if (esc) {
  2998. return esc + first + (rest ? star : '');
  2999. }
  3000. return star;
  3001. }
  3002. return esc ? m : `\\${m}`;
  3003. });
  3004. if (backslashes === true) {
  3005. if (opts.unescape === true) {
  3006. output = output.replace(/\\/g, '');
  3007. } else {
  3008. output = output.replace(/\\+/g, m => {
  3009. return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
  3010. });
  3011. }
  3012. }
  3013. if (output === input && opts.contains === true) {
  3014. state.output = input;
  3015. return state;
  3016. }
  3017. state.output = utils$j.wrapOutput(output, state, options);
  3018. return state;
  3019. }
  3020. /**
  3021. * Tokenize input until we reach end-of-string
  3022. */
  3023. while (!eos()) {
  3024. value = advance();
  3025. if (value === '\u0000') {
  3026. continue;
  3027. }
  3028. /**
  3029. * Escaped characters
  3030. */
  3031. if (value === '\\') {
  3032. const next = peek();
  3033. if (next === '/' && opts.bash !== true) {
  3034. continue;
  3035. }
  3036. if (next === '.' || next === ';') {
  3037. continue;
  3038. }
  3039. if (!next) {
  3040. value += '\\';
  3041. push({ type: 'text', value });
  3042. continue;
  3043. }
  3044. // collapse slashes to reduce potential for exploits
  3045. const match = /^\\+/.exec(remaining());
  3046. let slashes = 0;
  3047. if (match && match[0].length > 2) {
  3048. slashes = match[0].length;
  3049. state.index += slashes;
  3050. if (slashes % 2 !== 0) {
  3051. value += '\\';
  3052. }
  3053. }
  3054. if (opts.unescape === true) {
  3055. value = advance();
  3056. } else {
  3057. value += advance();
  3058. }
  3059. if (state.brackets === 0) {
  3060. push({ type: 'text', value });
  3061. continue;
  3062. }
  3063. }
  3064. /**
  3065. * If we're inside a regex character class, continue
  3066. * until we reach the closing bracket.
  3067. */
  3068. if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
  3069. if (opts.posix !== false && value === ':') {
  3070. const inner = prev.value.slice(1);
  3071. if (inner.includes('[')) {
  3072. prev.posix = true;
  3073. if (inner.includes(':')) {
  3074. const idx = prev.value.lastIndexOf('[');
  3075. const pre = prev.value.slice(0, idx);
  3076. const rest = prev.value.slice(idx + 2);
  3077. const posix = POSIX_REGEX_SOURCE[rest];
  3078. if (posix) {
  3079. prev.value = pre + posix;
  3080. state.backtrack = true;
  3081. advance();
  3082. if (!bos.output && tokens.indexOf(prev) === 1) {
  3083. bos.output = ONE_CHAR;
  3084. }
  3085. continue;
  3086. }
  3087. }
  3088. }
  3089. }
  3090. if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
  3091. value = `\\${value}`;
  3092. }
  3093. if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
  3094. value = `\\${value}`;
  3095. }
  3096. if (opts.posix === true && value === '!' && prev.value === '[') {
  3097. value = '^';
  3098. }
  3099. prev.value += value;
  3100. append({ value });
  3101. continue;
  3102. }
  3103. /**
  3104. * If we're inside a quoted string, continue
  3105. * until we reach the closing double quote.
  3106. */
  3107. if (state.quotes === 1 && value !== '"') {
  3108. value = utils$j.escapeRegex(value);
  3109. prev.value += value;
  3110. append({ value });
  3111. continue;
  3112. }
  3113. /**
  3114. * Double quotes
  3115. */
  3116. if (value === '"') {
  3117. state.quotes = state.quotes === 1 ? 0 : 1;
  3118. if (opts.keepQuotes === true) {
  3119. push({ type: 'text', value });
  3120. }
  3121. continue;
  3122. }
  3123. /**
  3124. * Parentheses
  3125. */
  3126. if (value === '(') {
  3127. increment('parens');
  3128. push({ type: 'paren', value });
  3129. continue;
  3130. }
  3131. if (value === ')') {
  3132. if (state.parens === 0 && opts.strictBrackets === true) {
  3133. throw new SyntaxError(syntaxError$1('opening', '('));
  3134. }
  3135. const extglob = extglobs[extglobs.length - 1];
  3136. if (extglob && state.parens === extglob.parens + 1) {
  3137. extglobClose(extglobs.pop());
  3138. continue;
  3139. }
  3140. push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
  3141. decrement('parens');
  3142. continue;
  3143. }
  3144. /**
  3145. * Square brackets
  3146. */
  3147. if (value === '[') {
  3148. if (opts.nobracket === true || !remaining().includes(']')) {
  3149. if (opts.nobracket !== true && opts.strictBrackets === true) {
  3150. throw new SyntaxError(syntaxError$1('closing', ']'));
  3151. }
  3152. value = `\\${value}`;
  3153. } else {
  3154. increment('brackets');
  3155. }
  3156. push({ type: 'bracket', value });
  3157. continue;
  3158. }
  3159. if (value === ']') {
  3160. if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
  3161. push({ type: 'text', value, output: `\\${value}` });
  3162. continue;
  3163. }
  3164. if (state.brackets === 0) {
  3165. if (opts.strictBrackets === true) {
  3166. throw new SyntaxError(syntaxError$1('opening', '['));
  3167. }
  3168. push({ type: 'text', value, output: `\\${value}` });
  3169. continue;
  3170. }
  3171. decrement('brackets');
  3172. const prevValue = prev.value.slice(1);
  3173. if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
  3174. value = `/${value}`;
  3175. }
  3176. prev.value += value;
  3177. append({ value });
  3178. // when literal brackets are explicitly disabled
  3179. // assume we should match with a regex character class
  3180. if (opts.literalBrackets === false || utils$j.hasRegexChars(prevValue)) {
  3181. continue;
  3182. }
  3183. const escaped = utils$j.escapeRegex(prev.value);
  3184. state.output = state.output.slice(0, -prev.value.length);
  3185. // when literal brackets are explicitly enabled
  3186. // assume we should escape the brackets to match literal characters
  3187. if (opts.literalBrackets === true) {
  3188. state.output += escaped;
  3189. prev.value = escaped;
  3190. continue;
  3191. }
  3192. // when the user specifies nothing, try to match both
  3193. prev.value = `(${capture}${escaped}|${prev.value})`;
  3194. state.output += prev.value;
  3195. continue;
  3196. }
  3197. /**
  3198. * Braces
  3199. */
  3200. if (value === '{' && opts.nobrace !== true) {
  3201. increment('braces');
  3202. const open = {
  3203. type: 'brace',
  3204. value,
  3205. output: '(',
  3206. outputIndex: state.output.length,
  3207. tokensIndex: state.tokens.length
  3208. };
  3209. braces.push(open);
  3210. push(open);
  3211. continue;
  3212. }
  3213. if (value === '}') {
  3214. const brace = braces[braces.length - 1];
  3215. if (opts.nobrace === true || !brace) {
  3216. push({ type: 'text', value, output: value });
  3217. continue;
  3218. }
  3219. let output = ')';
  3220. if (brace.dots === true) {
  3221. const arr = tokens.slice();
  3222. const range = [];
  3223. for (let i = arr.length - 1; i >= 0; i--) {
  3224. tokens.pop();
  3225. if (arr[i].type === 'brace') {
  3226. break;
  3227. }
  3228. if (arr[i].type !== 'dots') {
  3229. range.unshift(arr[i].value);
  3230. }
  3231. }
  3232. output = expandRange(range, opts);
  3233. state.backtrack = true;
  3234. }
  3235. if (brace.comma !== true && brace.dots !== true) {
  3236. const out = state.output.slice(0, brace.outputIndex);
  3237. const toks = state.tokens.slice(brace.tokensIndex);
  3238. brace.value = brace.output = '\\{';
  3239. value = output = '\\}';
  3240. state.output = out;
  3241. for (const t of toks) {
  3242. state.output += (t.output || t.value);
  3243. }
  3244. }
  3245. push({ type: 'brace', value, output });
  3246. decrement('braces');
  3247. braces.pop();
  3248. continue;
  3249. }
  3250. /**
  3251. * Pipes
  3252. */
  3253. if (value === '|') {
  3254. if (extglobs.length > 0) {
  3255. extglobs[extglobs.length - 1].conditions++;
  3256. }
  3257. push({ type: 'text', value });
  3258. continue;
  3259. }
  3260. /**
  3261. * Commas
  3262. */
  3263. if (value === ',') {
  3264. let output = value;
  3265. const brace = braces[braces.length - 1];
  3266. if (brace && stack[stack.length - 1] === 'braces') {
  3267. brace.comma = true;
  3268. output = '|';
  3269. }
  3270. push({ type: 'comma', value, output });
  3271. continue;
  3272. }
  3273. /**
  3274. * Slashes
  3275. */
  3276. if (value === '/') {
  3277. // if the beginning of the glob is "./", advance the start
  3278. // to the current index, and don't add the "./" characters
  3279. // to the state. This greatly simplifies lookbehinds when
  3280. // checking for BOS characters like "!" and "." (not "./")
  3281. if (prev.type === 'dot' && state.index === state.start + 1) {
  3282. state.start = state.index + 1;
  3283. state.consumed = '';
  3284. state.output = '';
  3285. tokens.pop();
  3286. prev = bos; // reset "prev" to the first token
  3287. continue;
  3288. }
  3289. push({ type: 'slash', value, output: SLASH_LITERAL });
  3290. continue;
  3291. }
  3292. /**
  3293. * Dots
  3294. */
  3295. if (value === '.') {
  3296. if (state.braces > 0 && prev.type === 'dot') {
  3297. if (prev.value === '.') prev.output = DOT_LITERAL;
  3298. const brace = braces[braces.length - 1];
  3299. prev.type = 'dots';
  3300. prev.output += value;
  3301. prev.value += value;
  3302. brace.dots = true;
  3303. continue;
  3304. }
  3305. if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
  3306. push({ type: 'text', value, output: DOT_LITERAL });
  3307. continue;
  3308. }
  3309. push({ type: 'dot', value, output: DOT_LITERAL });
  3310. continue;
  3311. }
  3312. /**
  3313. * Question marks
  3314. */
  3315. if (value === '?') {
  3316. const isGroup = prev && prev.value === '(';
  3317. if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  3318. extglobOpen('qmark', value);
  3319. continue;
  3320. }
  3321. if (prev && prev.type === 'paren') {
  3322. const next = peek();
  3323. let output = value;
  3324. if (next === '<' && !utils$j.supportsLookbehinds()) {
  3325. throw new Error('Node.js v10 or higher is required for regex lookbehinds');
  3326. }
  3327. if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {
  3328. output = `\\${value}`;
  3329. }
  3330. push({ type: 'text', value, output });
  3331. continue;
  3332. }
  3333. if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
  3334. push({ type: 'qmark', value, output: QMARK_NO_DOT });
  3335. continue;
  3336. }
  3337. push({ type: 'qmark', value, output: QMARK });
  3338. continue;
  3339. }
  3340. /**
  3341. * Exclamation
  3342. */
  3343. if (value === '!') {
  3344. if (opts.noextglob !== true && peek() === '(') {
  3345. if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
  3346. extglobOpen('negate', value);
  3347. continue;
  3348. }
  3349. }
  3350. if (opts.nonegate !== true && state.index === 0) {
  3351. negate();
  3352. continue;
  3353. }
  3354. }
  3355. /**
  3356. * Plus
  3357. */
  3358. if (value === '+') {
  3359. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  3360. extglobOpen('plus', value);
  3361. continue;
  3362. }
  3363. if ((prev && prev.value === '(') || opts.regex === false) {
  3364. push({ type: 'plus', value, output: PLUS_LITERAL });
  3365. continue;
  3366. }
  3367. if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {
  3368. push({ type: 'plus', value });
  3369. continue;
  3370. }
  3371. push({ type: 'plus', value: PLUS_LITERAL });
  3372. continue;
  3373. }
  3374. /**
  3375. * Plain text
  3376. */
  3377. if (value === '@') {
  3378. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  3379. push({ type: 'at', extglob: true, value, output: '' });
  3380. continue;
  3381. }
  3382. push({ type: 'text', value });
  3383. continue;
  3384. }
  3385. /**
  3386. * Plain text
  3387. */
  3388. if (value !== '*') {
  3389. if (value === '$' || value === '^') {
  3390. value = `\\${value}`;
  3391. }
  3392. const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
  3393. if (match) {
  3394. value += match[0];
  3395. state.index += match[0].length;
  3396. }
  3397. push({ type: 'text', value });
  3398. continue;
  3399. }
  3400. /**
  3401. * Stars
  3402. */
  3403. if (prev && (prev.type === 'globstar' || prev.star === true)) {
  3404. prev.type = 'star';
  3405. prev.star = true;
  3406. prev.value += value;
  3407. prev.output = star;
  3408. state.backtrack = true;
  3409. state.globstar = true;
  3410. consume(value);
  3411. continue;
  3412. }
  3413. let rest = remaining();
  3414. if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
  3415. extglobOpen('star', value);
  3416. continue;
  3417. }
  3418. if (prev.type === 'star') {
  3419. if (opts.noglobstar === true) {
  3420. consume(value);
  3421. continue;
  3422. }
  3423. const prior = prev.prev;
  3424. const before = prior.prev;
  3425. const isStart = prior.type === 'slash' || prior.type === 'bos';
  3426. const afterStar = before && (before.type === 'star' || before.type === 'globstar');
  3427. if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {
  3428. push({ type: 'star', value, output: '' });
  3429. continue;
  3430. }
  3431. const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
  3432. const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
  3433. if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
  3434. push({ type: 'star', value, output: '' });
  3435. continue;
  3436. }
  3437. // strip consecutive `/**/`
  3438. while (rest.slice(0, 3) === '/**') {
  3439. const after = input[state.index + 4];
  3440. if (after && after !== '/') {
  3441. break;
  3442. }
  3443. rest = rest.slice(3);
  3444. consume('/**', 3);
  3445. }
  3446. if (prior.type === 'bos' && eos()) {
  3447. prev.type = 'globstar';
  3448. prev.value += value;
  3449. prev.output = globstar(opts);
  3450. state.output = prev.output;
  3451. state.globstar = true;
  3452. consume(value);
  3453. continue;
  3454. }
  3455. if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
  3456. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  3457. prior.output = `(?:${prior.output}`;
  3458. prev.type = 'globstar';
  3459. prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
  3460. prev.value += value;
  3461. state.globstar = true;
  3462. state.output += prior.output + prev.output;
  3463. consume(value);
  3464. continue;
  3465. }
  3466. if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
  3467. const end = rest[1] !== void 0 ? '|$' : '';
  3468. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  3469. prior.output = `(?:${prior.output}`;
  3470. prev.type = 'globstar';
  3471. prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
  3472. prev.value += value;
  3473. state.output += prior.output + prev.output;
  3474. state.globstar = true;
  3475. consume(value + advance());
  3476. push({ type: 'slash', value: '/', output: '' });
  3477. continue;
  3478. }
  3479. if (prior.type === 'bos' && rest[0] === '/') {
  3480. prev.type = 'globstar';
  3481. prev.value += value;
  3482. prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
  3483. state.output = prev.output;
  3484. state.globstar = true;
  3485. consume(value + advance());
  3486. push({ type: 'slash', value: '/', output: '' });
  3487. continue;
  3488. }
  3489. // remove single star from output
  3490. state.output = state.output.slice(0, -prev.output.length);
  3491. // reset previous token to globstar
  3492. prev.type = 'globstar';
  3493. prev.output = globstar(opts);
  3494. prev.value += value;
  3495. // reset output with globstar
  3496. state.output += prev.output;
  3497. state.globstar = true;
  3498. consume(value);
  3499. continue;
  3500. }
  3501. const token = { type: 'star', value, output: star };
  3502. if (opts.bash === true) {
  3503. token.output = '.*?';
  3504. if (prev.type === 'bos' || prev.type === 'slash') {
  3505. token.output = nodot + token.output;
  3506. }
  3507. push(token);
  3508. continue;
  3509. }
  3510. if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
  3511. token.output = value;
  3512. push(token);
  3513. continue;
  3514. }
  3515. if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
  3516. if (prev.type === 'dot') {
  3517. state.output += NO_DOT_SLASH;
  3518. prev.output += NO_DOT_SLASH;
  3519. } else if (opts.dot === true) {
  3520. state.output += NO_DOTS_SLASH;
  3521. prev.output += NO_DOTS_SLASH;
  3522. } else {
  3523. state.output += nodot;
  3524. prev.output += nodot;
  3525. }
  3526. if (peek() !== '*') {
  3527. state.output += ONE_CHAR;
  3528. prev.output += ONE_CHAR;
  3529. }
  3530. }
  3531. push(token);
  3532. }
  3533. while (state.brackets > 0) {
  3534. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError$1('closing', ']'));
  3535. state.output = utils$j.escapeLast(state.output, '[');
  3536. decrement('brackets');
  3537. }
  3538. while (state.parens > 0) {
  3539. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError$1('closing', ')'));
  3540. state.output = utils$j.escapeLast(state.output, '(');
  3541. decrement('parens');
  3542. }
  3543. while (state.braces > 0) {
  3544. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError$1('closing', '}'));
  3545. state.output = utils$j.escapeLast(state.output, '{');
  3546. decrement('braces');
  3547. }
  3548. if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
  3549. push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
  3550. }
  3551. // rebuild the output if we had to backtrack at any point
  3552. if (state.backtrack === true) {
  3553. state.output = '';
  3554. for (const token of state.tokens) {
  3555. state.output += token.output != null ? token.output : token.value;
  3556. if (token.suffix) {
  3557. state.output += token.suffix;
  3558. }
  3559. }
  3560. }
  3561. return state;
  3562. };
  3563. /**
  3564. * Fast paths for creating regular expressions for common glob patterns.
  3565. * This can significantly speed up processing and has very little downside
  3566. * impact when none of the fast paths match.
  3567. */
  3568. parse$l.fastpaths = (input, options) => {
  3569. const opts = { ...options };
  3570. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1;
  3571. const len = input.length;
  3572. if (len > max) {
  3573. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  3574. }
  3575. input = REPLACEMENTS[input] || input;
  3576. const win32 = utils$j.isWindows(options);
  3577. // create constants based on platform, for windows or posix
  3578. const {
  3579. DOT_LITERAL,
  3580. SLASH_LITERAL,
  3581. ONE_CHAR,
  3582. DOTS_SLASH,
  3583. NO_DOT,
  3584. NO_DOTS,
  3585. NO_DOTS_SLASH,
  3586. STAR,
  3587. START_ANCHOR
  3588. } = constants$5.globChars(win32);
  3589. const nodot = opts.dot ? NO_DOTS : NO_DOT;
  3590. const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
  3591. const capture = opts.capture ? '' : '?:';
  3592. const state = { negated: false, prefix: '' };
  3593. let star = opts.bash === true ? '.*?' : STAR;
  3594. if (opts.capture) {
  3595. star = `(${star})`;
  3596. }
  3597. const globstar = opts => {
  3598. if (opts.noglobstar === true) return star;
  3599. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  3600. };
  3601. const create = str => {
  3602. switch (str) {
  3603. case '*':
  3604. return `${nodot}${ONE_CHAR}${star}`;
  3605. case '.*':
  3606. return `${DOT_LITERAL}${ONE_CHAR}${star}`;
  3607. case '*.*':
  3608. return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  3609. case '*/*':
  3610. return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
  3611. case '**':
  3612. return nodot + globstar(opts);
  3613. case '**/*':
  3614. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
  3615. case '**/*.*':
  3616. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  3617. case '**/.*':
  3618. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
  3619. default: {
  3620. const match = /^(.*?)\.(\w+)$/.exec(str);
  3621. if (!match) return;
  3622. const source = create(match[1]);
  3623. if (!source) return;
  3624. return source + DOT_LITERAL + match[2];
  3625. }
  3626. }
  3627. };
  3628. const output = utils$j.removePrefix(input, state);
  3629. let source = create(output);
  3630. if (source && opts.strictSlashes !== true) {
  3631. source += `${SLASH_LITERAL}?`;
  3632. }
  3633. return source;
  3634. };
  3635. var parse_1$2 = parse$l;
  3636. const path$m = path__default;
  3637. const scan = scan_1;
  3638. const parse$k = parse_1$2;
  3639. const utils$i = utils$l;
  3640. const constants$4 = constants$6;
  3641. const isObject$4 = val => val && typeof val === 'object' && !Array.isArray(val);
  3642. /**
  3643. * Creates a matcher function from one or more glob patterns. The
  3644. * returned function takes a string to match as its first argument,
  3645. * and returns true if the string is a match. The returned matcher
  3646. * function also takes a boolean as the second argument that, when true,
  3647. * returns an object with additional information.
  3648. *
  3649. * ```js
  3650. * const picomatch = require('picomatch');
  3651. * // picomatch(glob[, options]);
  3652. *
  3653. * const isMatch = picomatch('*.!(*a)');
  3654. * console.log(isMatch('a.a')); //=> false
  3655. * console.log(isMatch('a.b')); //=> true
  3656. * ```
  3657. * @name picomatch
  3658. * @param {String|Array} `globs` One or more glob patterns.
  3659. * @param {Object=} `options`
  3660. * @return {Function=} Returns a matcher function.
  3661. * @api public
  3662. */
  3663. const picomatch$5 = (glob, options, returnState = false) => {
  3664. if (Array.isArray(glob)) {
  3665. const fns = glob.map(input => picomatch$5(input, options, returnState));
  3666. const arrayMatcher = str => {
  3667. for (const isMatch of fns) {
  3668. const state = isMatch(str);
  3669. if (state) return state;
  3670. }
  3671. return false;
  3672. };
  3673. return arrayMatcher;
  3674. }
  3675. const isState = isObject$4(glob) && glob.tokens && glob.input;
  3676. if (glob === '' || (typeof glob !== 'string' && !isState)) {
  3677. throw new TypeError('Expected pattern to be a non-empty string');
  3678. }
  3679. const opts = options || {};
  3680. const posix = utils$i.isWindows(options);
  3681. const regex = isState
  3682. ? picomatch$5.compileRe(glob, options)
  3683. : picomatch$5.makeRe(glob, options, false, true);
  3684. const state = regex.state;
  3685. delete regex.state;
  3686. let isIgnored = () => false;
  3687. if (opts.ignore) {
  3688. const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
  3689. isIgnored = picomatch$5(opts.ignore, ignoreOpts, returnState);
  3690. }
  3691. const matcher = (input, returnObject = false) => {
  3692. const { isMatch, match, output } = picomatch$5.test(input, regex, options, { glob, posix });
  3693. const result = { glob, state, regex, posix, input, output, match, isMatch };
  3694. if (typeof opts.onResult === 'function') {
  3695. opts.onResult(result);
  3696. }
  3697. if (isMatch === false) {
  3698. result.isMatch = false;
  3699. return returnObject ? result : false;
  3700. }
  3701. if (isIgnored(input)) {
  3702. if (typeof opts.onIgnore === 'function') {
  3703. opts.onIgnore(result);
  3704. }
  3705. result.isMatch = false;
  3706. return returnObject ? result : false;
  3707. }
  3708. if (typeof opts.onMatch === 'function') {
  3709. opts.onMatch(result);
  3710. }
  3711. return returnObject ? result : true;
  3712. };
  3713. if (returnState) {
  3714. matcher.state = state;
  3715. }
  3716. return matcher;
  3717. };
  3718. /**
  3719. * Test `input` with the given `regex`. This is used by the main
  3720. * `picomatch()` function to test the input string.
  3721. *
  3722. * ```js
  3723. * const picomatch = require('picomatch');
  3724. * // picomatch.test(input, regex[, options]);
  3725. *
  3726. * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
  3727. * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
  3728. * ```
  3729. * @param {String} `input` String to test.
  3730. * @param {RegExp} `regex`
  3731. * @return {Object} Returns an object with matching info.
  3732. * @api public
  3733. */
  3734. picomatch$5.test = (input, regex, options, { glob, posix } = {}) => {
  3735. if (typeof input !== 'string') {
  3736. throw new TypeError('Expected input to be a string');
  3737. }
  3738. if (input === '') {
  3739. return { isMatch: false, output: '' };
  3740. }
  3741. const opts = options || {};
  3742. const format = opts.format || (posix ? utils$i.toPosixSlashes : null);
  3743. let match = input === glob;
  3744. let output = (match && format) ? format(input) : input;
  3745. if (match === false) {
  3746. output = format ? format(input) : input;
  3747. match = output === glob;
  3748. }
  3749. if (match === false || opts.capture === true) {
  3750. if (opts.matchBase === true || opts.basename === true) {
  3751. match = picomatch$5.matchBase(input, regex, options, posix);
  3752. } else {
  3753. match = regex.exec(output);
  3754. }
  3755. }
  3756. return { isMatch: Boolean(match), match, output };
  3757. };
  3758. /**
  3759. * Match the basename of a filepath.
  3760. *
  3761. * ```js
  3762. * const picomatch = require('picomatch');
  3763. * // picomatch.matchBase(input, glob[, options]);
  3764. * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
  3765. * ```
  3766. * @param {String} `input` String to test.
  3767. * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
  3768. * @return {Boolean}
  3769. * @api public
  3770. */
  3771. picomatch$5.matchBase = (input, glob, options, posix = utils$i.isWindows(options)) => {
  3772. const regex = glob instanceof RegExp ? glob : picomatch$5.makeRe(glob, options);
  3773. return regex.test(path$m.basename(input));
  3774. };
  3775. /**
  3776. * Returns true if **any** of the given glob `patterns` match the specified `string`.
  3777. *
  3778. * ```js
  3779. * const picomatch = require('picomatch');
  3780. * // picomatch.isMatch(string, patterns[, options]);
  3781. *
  3782. * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
  3783. * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
  3784. * ```
  3785. * @param {String|Array} str The string to test.
  3786. * @param {String|Array} patterns One or more glob patterns to use for matching.
  3787. * @param {Object} [options] See available [options](#options).
  3788. * @return {Boolean} Returns true if any patterns match `str`
  3789. * @api public
  3790. */
  3791. picomatch$5.isMatch = (str, patterns, options) => picomatch$5(patterns, options)(str);
  3792. /**
  3793. * Parse a glob pattern to create the source string for a regular
  3794. * expression.
  3795. *
  3796. * ```js
  3797. * const picomatch = require('picomatch');
  3798. * const result = picomatch.parse(pattern[, options]);
  3799. * ```
  3800. * @param {String} `pattern`
  3801. * @param {Object} `options`
  3802. * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
  3803. * @api public
  3804. */
  3805. picomatch$5.parse = (pattern, options) => {
  3806. if (Array.isArray(pattern)) return pattern.map(p => picomatch$5.parse(p, options));
  3807. return parse$k(pattern, { ...options, fastpaths: false });
  3808. };
  3809. /**
  3810. * Scan a glob pattern to separate the pattern into segments.
  3811. *
  3812. * ```js
  3813. * const picomatch = require('picomatch');
  3814. * // picomatch.scan(input[, options]);
  3815. *
  3816. * const result = picomatch.scan('!./foo/*.js');
  3817. * console.log(result);
  3818. * { prefix: '!./',
  3819. * input: '!./foo/*.js',
  3820. * start: 3,
  3821. * base: 'foo',
  3822. * glob: '*.js',
  3823. * isBrace: false,
  3824. * isBracket: false,
  3825. * isGlob: true,
  3826. * isExtglob: false,
  3827. * isGlobstar: false,
  3828. * negated: true }
  3829. * ```
  3830. * @param {String} `input` Glob pattern to scan.
  3831. * @param {Object} `options`
  3832. * @return {Object} Returns an object with
  3833. * @api public
  3834. */
  3835. picomatch$5.scan = (input, options) => scan(input, options);
  3836. /**
  3837. * Compile a regular expression from the `state` object returned by the
  3838. * [parse()](#parse) method.
  3839. *
  3840. * @param {Object} `state`
  3841. * @param {Object} `options`
  3842. * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
  3843. * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
  3844. * @return {RegExp}
  3845. * @api public
  3846. */
  3847. picomatch$5.compileRe = (state, options, returnOutput = false, returnState = false) => {
  3848. if (returnOutput === true) {
  3849. return state.output;
  3850. }
  3851. const opts = options || {};
  3852. const prepend = opts.contains ? '' : '^';
  3853. const append = opts.contains ? '' : '$';
  3854. let source = `${prepend}(?:${state.output})${append}`;
  3855. if (state && state.negated === true) {
  3856. source = `^(?!${source}).*$`;
  3857. }
  3858. const regex = picomatch$5.toRegex(source, options);
  3859. if (returnState === true) {
  3860. regex.state = state;
  3861. }
  3862. return regex;
  3863. };
  3864. /**
  3865. * Create a regular expression from a parsed glob pattern.
  3866. *
  3867. * ```js
  3868. * const picomatch = require('picomatch');
  3869. * const state = picomatch.parse('*.js');
  3870. * // picomatch.compileRe(state[, options]);
  3871. *
  3872. * console.log(picomatch.compileRe(state));
  3873. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  3874. * ```
  3875. * @param {String} `state` The object returned from the `.parse` method.
  3876. * @param {Object} `options`
  3877. * @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result.
  3878. * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
  3879. * @return {RegExp} Returns a regex created from the given pattern.
  3880. * @api public
  3881. */
  3882. picomatch$5.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
  3883. if (!input || typeof input !== 'string') {
  3884. throw new TypeError('Expected a non-empty string');
  3885. }
  3886. let parsed = { negated: false, fastpaths: true };
  3887. if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
  3888. parsed.output = parse$k.fastpaths(input, options);
  3889. }
  3890. if (!parsed.output) {
  3891. parsed = parse$k(input, options);
  3892. }
  3893. return picomatch$5.compileRe(parsed, options, returnOutput, returnState);
  3894. };
  3895. /**
  3896. * Create a regular expression from the given regex source string.
  3897. *
  3898. * ```js
  3899. * const picomatch = require('picomatch');
  3900. * // picomatch.toRegex(source[, options]);
  3901. *
  3902. * const { output } = picomatch.parse('*.js');
  3903. * console.log(picomatch.toRegex(output));
  3904. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  3905. * ```
  3906. * @param {String} `source` Regular expression source string.
  3907. * @param {Object} `options`
  3908. * @return {RegExp}
  3909. * @api public
  3910. */
  3911. picomatch$5.toRegex = (source, options) => {
  3912. try {
  3913. const opts = options || {};
  3914. return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
  3915. } catch (err) {
  3916. if (options && options.debug === true) throw err;
  3917. return /$^/;
  3918. }
  3919. };
  3920. /**
  3921. * Picomatch constants.
  3922. * @return {Object}
  3923. */
  3924. picomatch$5.constants = constants$4;
  3925. /**
  3926. * Expose "picomatch"
  3927. */
  3928. var picomatch_1 = picomatch$5;
  3929. var picomatch$4 = picomatch_1;
  3930. function walk$3(ast, { enter, leave }) {
  3931. return visit$1(ast, null, enter, leave);
  3932. }
  3933. let should_skip = false;
  3934. let should_remove = false;
  3935. let replacement = null;
  3936. const context = {
  3937. skip: () => should_skip = true,
  3938. remove: () => should_remove = true,
  3939. replace: (node) => replacement = node
  3940. };
  3941. function replace(parent, prop, index, node) {
  3942. if (parent) {
  3943. if (index !== null) {
  3944. parent[prop][index] = node;
  3945. } else {
  3946. parent[prop] = node;
  3947. }
  3948. }
  3949. }
  3950. function remove(parent, prop, index) {
  3951. if (parent) {
  3952. if (index !== null) {
  3953. parent[prop].splice(index, 1);
  3954. } else {
  3955. delete parent[prop];
  3956. }
  3957. }
  3958. }
  3959. function visit$1(
  3960. node,
  3961. parent,
  3962. enter,
  3963. leave,
  3964. prop,
  3965. index
  3966. ) {
  3967. if (node) {
  3968. if (enter) {
  3969. const _should_skip = should_skip;
  3970. const _should_remove = should_remove;
  3971. const _replacement = replacement;
  3972. should_skip = false;
  3973. should_remove = false;
  3974. replacement = null;
  3975. enter.call(context, node, parent, prop, index);
  3976. if (replacement) {
  3977. node = replacement;
  3978. replace(parent, prop, index, node);
  3979. }
  3980. if (should_remove) {
  3981. remove(parent, prop, index);
  3982. }
  3983. const skipped = should_skip;
  3984. const removed = should_remove;
  3985. should_skip = _should_skip;
  3986. should_remove = _should_remove;
  3987. replacement = _replacement;
  3988. if (skipped) return node;
  3989. if (removed) return null;
  3990. }
  3991. for (const key in node) {
  3992. const value = (node )[key];
  3993. if (typeof value !== 'object') {
  3994. continue;
  3995. }
  3996. else if (Array.isArray(value)) {
  3997. for (let j = 0, k = 0; j < value.length; j += 1, k += 1) {
  3998. if (value[j] !== null && typeof value[j].type === 'string') {
  3999. if (!visit$1(value[j], node, enter, leave, key, k)) {
  4000. // removed
  4001. j--;
  4002. }
  4003. }
  4004. }
  4005. }
  4006. else if (value !== null && typeof value.type === 'string') {
  4007. visit$1(value, node, enter, leave, key, null);
  4008. }
  4009. }
  4010. if (leave) {
  4011. const _replacement = replacement;
  4012. const _should_remove = should_remove;
  4013. replacement = null;
  4014. should_remove = false;
  4015. leave.call(context, node, parent, prop, index);
  4016. if (replacement) {
  4017. node = replacement;
  4018. replace(parent, prop, index, node);
  4019. }
  4020. if (should_remove) {
  4021. remove(parent, prop, index);
  4022. }
  4023. const removed = should_remove;
  4024. replacement = _replacement;
  4025. should_remove = _should_remove;
  4026. if (removed) return null;
  4027. }
  4028. }
  4029. return node;
  4030. }
  4031. const extractors = {
  4032. ArrayPattern(names, param) {
  4033. for (const element of param.elements) {
  4034. if (element)
  4035. extractors[element.type](names, element);
  4036. }
  4037. },
  4038. AssignmentPattern(names, param) {
  4039. extractors[param.left.type](names, param.left);
  4040. },
  4041. Identifier(names, param) {
  4042. names.push(param.name);
  4043. },
  4044. MemberExpression() { },
  4045. ObjectPattern(names, param) {
  4046. for (const prop of param.properties) {
  4047. // @ts-ignore Typescript reports that this is not a valid type
  4048. if (prop.type === 'RestElement') {
  4049. extractors.RestElement(names, prop);
  4050. }
  4051. else {
  4052. extractors[prop.value.type](names, prop.value);
  4053. }
  4054. }
  4055. },
  4056. RestElement(names, param) {
  4057. extractors[param.argument.type](names, param.argument);
  4058. }
  4059. };
  4060. const extractAssignedNames = function extractAssignedNames(param) {
  4061. const names = [];
  4062. extractors[param.type](names, param);
  4063. return names;
  4064. };
  4065. const blockDeclarations = {
  4066. const: true,
  4067. let: true
  4068. };
  4069. class Scope$1 {
  4070. constructor(options = {}) {
  4071. this.parent = options.parent;
  4072. this.isBlockScope = !!options.block;
  4073. this.declarations = Object.create(null);
  4074. if (options.params) {
  4075. options.params.forEach((param) => {
  4076. extractAssignedNames(param).forEach((name) => {
  4077. this.declarations[name] = true;
  4078. });
  4079. });
  4080. }
  4081. }
  4082. addDeclaration(node, isBlockDeclaration, isVar) {
  4083. if (!isBlockDeclaration && this.isBlockScope) {
  4084. // it's a `var` or function node, and this
  4085. // is a block scope, so we need to go up
  4086. this.parent.addDeclaration(node, isBlockDeclaration, isVar);
  4087. }
  4088. else if (node.id) {
  4089. extractAssignedNames(node.id).forEach((name) => {
  4090. this.declarations[name] = true;
  4091. });
  4092. }
  4093. }
  4094. contains(name) {
  4095. return this.declarations[name] || (this.parent ? this.parent.contains(name) : false);
  4096. }
  4097. }
  4098. const attachScopes = function attachScopes(ast, propertyName = 'scope') {
  4099. let scope = new Scope$1();
  4100. walk$3(ast, {
  4101. enter(n, parent) {
  4102. const node = n;
  4103. // function foo () {...}
  4104. // class Foo {...}
  4105. if (/(Function|Class)Declaration/.test(node.type)) {
  4106. scope.addDeclaration(node, false, false);
  4107. }
  4108. // var foo = 1
  4109. if (node.type === 'VariableDeclaration') {
  4110. const { kind } = node;
  4111. const isBlockDeclaration = blockDeclarations[kind];
  4112. // don't add const/let declarations in the body of a for loop #113
  4113. const parentType = parent ? parent.type : '';
  4114. if (!(isBlockDeclaration && /ForOfStatement/.test(parentType))) {
  4115. node.declarations.forEach((declaration) => {
  4116. scope.addDeclaration(declaration, isBlockDeclaration, true);
  4117. });
  4118. }
  4119. }
  4120. let newScope;
  4121. // create new function scope
  4122. if (/Function/.test(node.type)) {
  4123. const func = node;
  4124. newScope = new Scope$1({
  4125. parent: scope,
  4126. block: false,
  4127. params: func.params
  4128. });
  4129. // named function expressions - the name is considered
  4130. // part of the function's scope
  4131. if (func.type === 'FunctionExpression' && func.id) {
  4132. newScope.addDeclaration(func, false, false);
  4133. }
  4134. }
  4135. // create new block scope
  4136. if (node.type === 'BlockStatement' && !/Function/.test(parent.type)) {
  4137. newScope = new Scope$1({
  4138. parent: scope,
  4139. block: true
  4140. });
  4141. }
  4142. // catch clause has its own block scope
  4143. if (node.type === 'CatchClause') {
  4144. newScope = new Scope$1({
  4145. parent: scope,
  4146. params: node.param ? [node.param] : [],
  4147. block: true
  4148. });
  4149. }
  4150. if (newScope) {
  4151. Object.defineProperty(node, propertyName, {
  4152. value: newScope,
  4153. configurable: true
  4154. });
  4155. scope = newScope;
  4156. }
  4157. },
  4158. leave(n) {
  4159. const node = n;
  4160. if (node[propertyName])
  4161. scope = scope.parent;
  4162. }
  4163. });
  4164. return scope;
  4165. };
  4166. // Helper since Typescript can't detect readonly arrays with Array.isArray
  4167. function isArray$2(arg) {
  4168. return Array.isArray(arg);
  4169. }
  4170. function ensureArray(thing) {
  4171. if (isArray$2(thing))
  4172. return thing;
  4173. if (thing == null)
  4174. return [];
  4175. return [thing];
  4176. }
  4177. function getMatcherString(id, resolutionBase) {
  4178. if (resolutionBase === false) {
  4179. return id;
  4180. }
  4181. // resolve('') is valid and will default to process.cwd()
  4182. const basePath = path$r.resolve(resolutionBase || '')
  4183. .split(path$r.sep)
  4184. .join('/')
  4185. // escape all possible (posix + win) path characters that might interfere with regex
  4186. .replace(/[-^$*+?.()|[\]{}]/g, '\\$&');
  4187. // Note that we use posix.join because:
  4188. // 1. the basePath has been normalized to use /
  4189. // 2. the incoming glob (id) matcher, also uses /
  4190. // otherwise Node will force backslash (\) on windows
  4191. return path$r.posix.join(basePath, id);
  4192. }
  4193. const createFilter = function createFilter(include, exclude, options) {
  4194. const resolutionBase = options && options.resolve;
  4195. const getMatcher = (id) => id instanceof RegExp
  4196. ? id
  4197. : {
  4198. test: (what) => {
  4199. // this refactor is a tad overly verbose but makes for easy debugging
  4200. const pattern = getMatcherString(id, resolutionBase);
  4201. const fn = picomatch$4(pattern, { dot: true });
  4202. const result = fn(what);
  4203. return result;
  4204. }
  4205. };
  4206. const includeMatchers = ensureArray(include).map(getMatcher);
  4207. const excludeMatchers = ensureArray(exclude).map(getMatcher);
  4208. return function result(id) {
  4209. if (typeof id !== 'string')
  4210. return false;
  4211. if (/\0/.test(id))
  4212. return false;
  4213. const pathId = id.split(path$r.sep).join('/');
  4214. for (let i = 0; i < excludeMatchers.length; ++i) {
  4215. const matcher = excludeMatchers[i];
  4216. if (matcher.test(pathId))
  4217. return false;
  4218. }
  4219. for (let i = 0; i < includeMatchers.length; ++i) {
  4220. const matcher = includeMatchers[i];
  4221. if (matcher.test(pathId))
  4222. return true;
  4223. }
  4224. return !includeMatchers.length;
  4225. };
  4226. };
  4227. const reservedWords$1 = 'break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public';
  4228. const builtins$1 = 'arguments Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl';
  4229. const forbiddenIdentifiers = new Set(`${reservedWords$1} ${builtins$1}`.split(' '));
  4230. forbiddenIdentifiers.add('');
  4231. const makeLegalIdentifier = function makeLegalIdentifier(str) {
  4232. let identifier = str
  4233. .replace(/-(\w)/g, (_, letter) => letter.toUpperCase())
  4234. .replace(/[^$_a-zA-Z0-9]/g, '_');
  4235. if (/\d/.test(identifier[0]) || forbiddenIdentifiers.has(identifier)) {
  4236. identifier = `_${identifier}`;
  4237. }
  4238. return identifier || '_';
  4239. };
  4240. var path$l = path__default;
  4241. var commondir = function (basedir, relfiles) {
  4242. if (relfiles) {
  4243. var files = relfiles.map(function (r) {
  4244. return path$l.resolve(basedir, r);
  4245. });
  4246. }
  4247. else {
  4248. var files = basedir;
  4249. }
  4250. var res = files.slice(1).reduce(function (ps, file) {
  4251. if (!file.match(/^([A-Za-z]:)?\/|\\/)) {
  4252. throw new Error('relative path without a basedir');
  4253. }
  4254. var xs = file.split(/\/+|\\+/);
  4255. for (
  4256. var i = 0;
  4257. ps[i] === xs[i] && i < Math.min(ps.length, xs.length);
  4258. i++
  4259. );
  4260. return ps.slice(0, i);
  4261. }, files[0].split(/\/+|\\+/));
  4262. // Windows correctly handles paths with forward-slashes
  4263. return res.length > 1 ? res.join('/') : '/'
  4264. };
  4265. var old$1 = {};
  4266. // Copyright Joyent, Inc. and other Node contributors.
  4267. //
  4268. // Permission is hereby granted, free of charge, to any person obtaining a
  4269. // copy of this software and associated documentation files (the
  4270. // "Software"), to deal in the Software without restriction, including
  4271. // without limitation the rights to use, copy, modify, merge, publish,
  4272. // distribute, sublicense, and/or sell copies of the Software, and to permit
  4273. // persons to whom the Software is furnished to do so, subject to the
  4274. // following conditions:
  4275. //
  4276. // The above copyright notice and this permission notice shall be included
  4277. // in all copies or substantial portions of the Software.
  4278. //
  4279. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  4280. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  4281. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  4282. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  4283. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  4284. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  4285. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  4286. var pathModule = path__default;
  4287. var isWindows$4 = process.platform === 'win32';
  4288. var fs$l = fs__default;
  4289. // JavaScript implementation of realpath, ported from node pre-v6
  4290. var DEBUG$1 = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG);
  4291. function rethrow() {
  4292. // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and
  4293. // is fairly slow to generate.
  4294. var callback;
  4295. if (DEBUG$1) {
  4296. var backtrace = new Error;
  4297. callback = debugCallback;
  4298. } else
  4299. callback = missingCallback;
  4300. return callback;
  4301. function debugCallback(err) {
  4302. if (err) {
  4303. backtrace.message = err.message;
  4304. err = backtrace;
  4305. missingCallback(err);
  4306. }
  4307. }
  4308. function missingCallback(err) {
  4309. if (err) {
  4310. if (process.throwDeprecation)
  4311. throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs
  4312. else if (!process.noDeprecation) {
  4313. var msg = 'fs: missing callback ' + (err.stack || err.message);
  4314. if (process.traceDeprecation)
  4315. console.trace(msg);
  4316. else
  4317. console.error(msg);
  4318. }
  4319. }
  4320. }
  4321. }
  4322. function maybeCallback(cb) {
  4323. return typeof cb === 'function' ? cb : rethrow();
  4324. }
  4325. // Regexp that finds the next partion of a (partial) path
  4326. // result is [base_with_slash, base], e.g. ['somedir/', 'somedir']
  4327. if (isWindows$4) {
  4328. var nextPartRe = /(.*?)(?:[\/\\]+|$)/g;
  4329. } else {
  4330. var nextPartRe = /(.*?)(?:[\/]+|$)/g;
  4331. }
  4332. // Regex to find the device root, including trailing slash. E.g. 'c:\\'.
  4333. if (isWindows$4) {
  4334. var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/;
  4335. } else {
  4336. var splitRootRe = /^[\/]*/;
  4337. }
  4338. old$1.realpathSync = function realpathSync(p, cache) {
  4339. // make p is absolute
  4340. p = pathModule.resolve(p);
  4341. if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
  4342. return cache[p];
  4343. }
  4344. var original = p,
  4345. seenLinks = {},
  4346. knownHard = {};
  4347. // current character position in p
  4348. var pos;
  4349. // the partial path so far, including a trailing slash if any
  4350. var current;
  4351. // the partial path without a trailing slash (except when pointing at a root)
  4352. var base;
  4353. // the partial path scanned in the previous round, with slash
  4354. var previous;
  4355. start();
  4356. function start() {
  4357. // Skip over roots
  4358. var m = splitRootRe.exec(p);
  4359. pos = m[0].length;
  4360. current = m[0];
  4361. base = m[0];
  4362. previous = '';
  4363. // On windows, check that the root exists. On unix there is no need.
  4364. if (isWindows$4 && !knownHard[base]) {
  4365. fs$l.lstatSync(base);
  4366. knownHard[base] = true;
  4367. }
  4368. }
  4369. // walk down the path, swapping out linked pathparts for their real
  4370. // values
  4371. // NB: p.length changes.
  4372. while (pos < p.length) {
  4373. // find the next part
  4374. nextPartRe.lastIndex = pos;
  4375. var result = nextPartRe.exec(p);
  4376. previous = current;
  4377. current += result[0];
  4378. base = previous + result[1];
  4379. pos = nextPartRe.lastIndex;
  4380. // continue if not a symlink
  4381. if (knownHard[base] || (cache && cache[base] === base)) {
  4382. continue;
  4383. }
  4384. var resolvedLink;
  4385. if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
  4386. // some known symbolic link. no need to stat again.
  4387. resolvedLink = cache[base];
  4388. } else {
  4389. var stat = fs$l.lstatSync(base);
  4390. if (!stat.isSymbolicLink()) {
  4391. knownHard[base] = true;
  4392. if (cache) cache[base] = base;
  4393. continue;
  4394. }
  4395. // read the link if it wasn't read before
  4396. // dev/ino always return 0 on windows, so skip the check.
  4397. var linkTarget = null;
  4398. if (!isWindows$4) {
  4399. var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
  4400. if (seenLinks.hasOwnProperty(id)) {
  4401. linkTarget = seenLinks[id];
  4402. }
  4403. }
  4404. if (linkTarget === null) {
  4405. fs$l.statSync(base);
  4406. linkTarget = fs$l.readlinkSync(base);
  4407. }
  4408. resolvedLink = pathModule.resolve(previous, linkTarget);
  4409. // track this, if given a cache.
  4410. if (cache) cache[base] = resolvedLink;
  4411. if (!isWindows$4) seenLinks[id] = linkTarget;
  4412. }
  4413. // resolve the link, then start over
  4414. p = pathModule.resolve(resolvedLink, p.slice(pos));
  4415. start();
  4416. }
  4417. if (cache) cache[original] = p;
  4418. return p;
  4419. };
  4420. old$1.realpath = function realpath(p, cache, cb) {
  4421. if (typeof cb !== 'function') {
  4422. cb = maybeCallback(cache);
  4423. cache = null;
  4424. }
  4425. // make p is absolute
  4426. p = pathModule.resolve(p);
  4427. if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
  4428. return process.nextTick(cb.bind(null, null, cache[p]));
  4429. }
  4430. var original = p,
  4431. seenLinks = {},
  4432. knownHard = {};
  4433. // current character position in p
  4434. var pos;
  4435. // the partial path so far, including a trailing slash if any
  4436. var current;
  4437. // the partial path without a trailing slash (except when pointing at a root)
  4438. var base;
  4439. // the partial path scanned in the previous round, with slash
  4440. var previous;
  4441. start();
  4442. function start() {
  4443. // Skip over roots
  4444. var m = splitRootRe.exec(p);
  4445. pos = m[0].length;
  4446. current = m[0];
  4447. base = m[0];
  4448. previous = '';
  4449. // On windows, check that the root exists. On unix there is no need.
  4450. if (isWindows$4 && !knownHard[base]) {
  4451. fs$l.lstat(base, function(err) {
  4452. if (err) return cb(err);
  4453. knownHard[base] = true;
  4454. LOOP();
  4455. });
  4456. } else {
  4457. process.nextTick(LOOP);
  4458. }
  4459. }
  4460. // walk down the path, swapping out linked pathparts for their real
  4461. // values
  4462. function LOOP() {
  4463. // stop if scanned past end of path
  4464. if (pos >= p.length) {
  4465. if (cache) cache[original] = p;
  4466. return cb(null, p);
  4467. }
  4468. // find the next part
  4469. nextPartRe.lastIndex = pos;
  4470. var result = nextPartRe.exec(p);
  4471. previous = current;
  4472. current += result[0];
  4473. base = previous + result[1];
  4474. pos = nextPartRe.lastIndex;
  4475. // continue if not a symlink
  4476. if (knownHard[base] || (cache && cache[base] === base)) {
  4477. return process.nextTick(LOOP);
  4478. }
  4479. if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
  4480. // known symbolic link. no need to stat again.
  4481. return gotResolvedLink(cache[base]);
  4482. }
  4483. return fs$l.lstat(base, gotStat);
  4484. }
  4485. function gotStat(err, stat) {
  4486. if (err) return cb(err);
  4487. // if not a symlink, skip to the next path part
  4488. if (!stat.isSymbolicLink()) {
  4489. knownHard[base] = true;
  4490. if (cache) cache[base] = base;
  4491. return process.nextTick(LOOP);
  4492. }
  4493. // stat & read the link if not read before
  4494. // call gotTarget as soon as the link target is known
  4495. // dev/ino always return 0 on windows, so skip the check.
  4496. if (!isWindows$4) {
  4497. var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
  4498. if (seenLinks.hasOwnProperty(id)) {
  4499. return gotTarget(null, seenLinks[id], base);
  4500. }
  4501. }
  4502. fs$l.stat(base, function(err) {
  4503. if (err) return cb(err);
  4504. fs$l.readlink(base, function(err, target) {
  4505. if (!isWindows$4) seenLinks[id] = target;
  4506. gotTarget(err, target);
  4507. });
  4508. });
  4509. }
  4510. function gotTarget(err, target, base) {
  4511. if (err) return cb(err);
  4512. var resolvedLink = pathModule.resolve(previous, target);
  4513. if (cache) cache[base] = resolvedLink;
  4514. gotResolvedLink(resolvedLink);
  4515. }
  4516. function gotResolvedLink(resolvedLink) {
  4517. // resolve the link, then start over
  4518. p = pathModule.resolve(resolvedLink, p.slice(pos));
  4519. start();
  4520. }
  4521. };
  4522. var fs_realpath = realpath$2;
  4523. realpath$2.realpath = realpath$2;
  4524. realpath$2.sync = realpathSync;
  4525. realpath$2.realpathSync = realpathSync;
  4526. realpath$2.monkeypatch = monkeypatch;
  4527. realpath$2.unmonkeypatch = unmonkeypatch;
  4528. var fs$k = fs__default;
  4529. var origRealpath = fs$k.realpath;
  4530. var origRealpathSync = fs$k.realpathSync;
  4531. var version$1 = process.version;
  4532. var ok = /^v[0-5]\./.test(version$1);
  4533. var old = old$1;
  4534. function newError (er) {
  4535. return er && er.syscall === 'realpath' && (
  4536. er.code === 'ELOOP' ||
  4537. er.code === 'ENOMEM' ||
  4538. er.code === 'ENAMETOOLONG'
  4539. )
  4540. }
  4541. function realpath$2 (p, cache, cb) {
  4542. if (ok) {
  4543. return origRealpath(p, cache, cb)
  4544. }
  4545. if (typeof cache === 'function') {
  4546. cb = cache;
  4547. cache = null;
  4548. }
  4549. origRealpath(p, cache, function (er, result) {
  4550. if (newError(er)) {
  4551. old.realpath(p, cache, cb);
  4552. } else {
  4553. cb(er, result);
  4554. }
  4555. });
  4556. }
  4557. function realpathSync (p, cache) {
  4558. if (ok) {
  4559. return origRealpathSync(p, cache)
  4560. }
  4561. try {
  4562. return origRealpathSync(p, cache)
  4563. } catch (er) {
  4564. if (newError(er)) {
  4565. return old.realpathSync(p, cache)
  4566. } else {
  4567. throw er
  4568. }
  4569. }
  4570. }
  4571. function monkeypatch () {
  4572. fs$k.realpath = realpath$2;
  4573. fs$k.realpathSync = realpathSync;
  4574. }
  4575. function unmonkeypatch () {
  4576. fs$k.realpath = origRealpath;
  4577. fs$k.realpathSync = origRealpathSync;
  4578. }
  4579. var concatMap$1 = function (xs, fn) {
  4580. var res = [];
  4581. for (var i = 0; i < xs.length; i++) {
  4582. var x = fn(xs[i], i);
  4583. if (isArray$1(x)) res.push.apply(res, x);
  4584. else res.push(x);
  4585. }
  4586. return res;
  4587. };
  4588. var isArray$1 = Array.isArray || function (xs) {
  4589. return Object.prototype.toString.call(xs) === '[object Array]';
  4590. };
  4591. var balancedMatch = balanced$1;
  4592. function balanced$1(a, b, str) {
  4593. if (a instanceof RegExp) a = maybeMatch(a, str);
  4594. if (b instanceof RegExp) b = maybeMatch(b, str);
  4595. var r = range$1(a, b, str);
  4596. return r && {
  4597. start: r[0],
  4598. end: r[1],
  4599. pre: str.slice(0, r[0]),
  4600. body: str.slice(r[0] + a.length, r[1]),
  4601. post: str.slice(r[1] + b.length)
  4602. };
  4603. }
  4604. function maybeMatch(reg, str) {
  4605. var m = str.match(reg);
  4606. return m ? m[0] : null;
  4607. }
  4608. balanced$1.range = range$1;
  4609. function range$1(a, b, str) {
  4610. var begs, beg, left, right, result;
  4611. var ai = str.indexOf(a);
  4612. var bi = str.indexOf(b, ai + 1);
  4613. var i = ai;
  4614. if (ai >= 0 && bi > 0) {
  4615. if(a===b) {
  4616. return [ai, bi];
  4617. }
  4618. begs = [];
  4619. left = str.length;
  4620. while (i >= 0 && !result) {
  4621. if (i == ai) {
  4622. begs.push(i);
  4623. ai = str.indexOf(a, i + 1);
  4624. } else if (begs.length == 1) {
  4625. result = [ begs.pop(), bi ];
  4626. } else {
  4627. beg = begs.pop();
  4628. if (beg < left) {
  4629. left = beg;
  4630. right = bi;
  4631. }
  4632. bi = str.indexOf(b, i + 1);
  4633. }
  4634. i = ai < bi && ai >= 0 ? ai : bi;
  4635. }
  4636. if (begs.length) {
  4637. result = [ left, right ];
  4638. }
  4639. }
  4640. return result;
  4641. }
  4642. var concatMap = concatMap$1;
  4643. var balanced = balancedMatch;
  4644. var braceExpansion = expandTop;
  4645. var escSlash = '\0SLASH'+Math.random()+'\0';
  4646. var escOpen = '\0OPEN'+Math.random()+'\0';
  4647. var escClose = '\0CLOSE'+Math.random()+'\0';
  4648. var escComma = '\0COMMA'+Math.random()+'\0';
  4649. var escPeriod = '\0PERIOD'+Math.random()+'\0';
  4650. function numeric(str) {
  4651. return parseInt(str, 10) == str
  4652. ? parseInt(str, 10)
  4653. : str.charCodeAt(0);
  4654. }
  4655. function escapeBraces(str) {
  4656. return str.split('\\\\').join(escSlash)
  4657. .split('\\{').join(escOpen)
  4658. .split('\\}').join(escClose)
  4659. .split('\\,').join(escComma)
  4660. .split('\\.').join(escPeriod);
  4661. }
  4662. function unescapeBraces(str) {
  4663. return str.split(escSlash).join('\\')
  4664. .split(escOpen).join('{')
  4665. .split(escClose).join('}')
  4666. .split(escComma).join(',')
  4667. .split(escPeriod).join('.');
  4668. }
  4669. // Basically just str.split(","), but handling cases
  4670. // where we have nested braced sections, which should be
  4671. // treated as individual members, like {a,{b,c},d}
  4672. function parseCommaParts(str) {
  4673. if (!str)
  4674. return [''];
  4675. var parts = [];
  4676. var m = balanced('{', '}', str);
  4677. if (!m)
  4678. return str.split(',');
  4679. var pre = m.pre;
  4680. var body = m.body;
  4681. var post = m.post;
  4682. var p = pre.split(',');
  4683. p[p.length-1] += '{' + body + '}';
  4684. var postParts = parseCommaParts(post);
  4685. if (post.length) {
  4686. p[p.length-1] += postParts.shift();
  4687. p.push.apply(p, postParts);
  4688. }
  4689. parts.push.apply(parts, p);
  4690. return parts;
  4691. }
  4692. function expandTop(str) {
  4693. if (!str)
  4694. return [];
  4695. // I don't know why Bash 4.3 does this, but it does.
  4696. // Anything starting with {} will have the first two bytes preserved
  4697. // but *only* at the top level, so {},a}b will not expand to anything,
  4698. // but a{},b}c will be expanded to [a}c,abc].
  4699. // One could argue that this is a bug in Bash, but since the goal of
  4700. // this module is to match Bash's rules, we escape a leading {}
  4701. if (str.substr(0, 2) === '{}') {
  4702. str = '\\{\\}' + str.substr(2);
  4703. }
  4704. return expand$3(escapeBraces(str), true).map(unescapeBraces);
  4705. }
  4706. function embrace(str) {
  4707. return '{' + str + '}';
  4708. }
  4709. function isPadded(el) {
  4710. return /^-?0\d/.test(el);
  4711. }
  4712. function lte(i, y) {
  4713. return i <= y;
  4714. }
  4715. function gte(i, y) {
  4716. return i >= y;
  4717. }
  4718. function expand$3(str, isTop) {
  4719. var expansions = [];
  4720. var m = balanced('{', '}', str);
  4721. if (!m || /\$$/.test(m.pre)) return [str];
  4722. var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
  4723. var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
  4724. var isSequence = isNumericSequence || isAlphaSequence;
  4725. var isOptions = m.body.indexOf(',') >= 0;
  4726. if (!isSequence && !isOptions) {
  4727. // {a},b}
  4728. if (m.post.match(/,.*\}/)) {
  4729. str = m.pre + '{' + m.body + escClose + m.post;
  4730. return expand$3(str);
  4731. }
  4732. return [str];
  4733. }
  4734. var n;
  4735. if (isSequence) {
  4736. n = m.body.split(/\.\./);
  4737. } else {
  4738. n = parseCommaParts(m.body);
  4739. if (n.length === 1) {
  4740. // x{{a,b}}y ==> x{a}y x{b}y
  4741. n = expand$3(n[0], false).map(embrace);
  4742. if (n.length === 1) {
  4743. var post = m.post.length
  4744. ? expand$3(m.post, false)
  4745. : [''];
  4746. return post.map(function(p) {
  4747. return m.pre + n[0] + p;
  4748. });
  4749. }
  4750. }
  4751. }
  4752. // at this point, n is the parts, and we know it's not a comma set
  4753. // with a single entry.
  4754. // no need to expand pre, since it is guaranteed to be free of brace-sets
  4755. var pre = m.pre;
  4756. var post = m.post.length
  4757. ? expand$3(m.post, false)
  4758. : [''];
  4759. var N;
  4760. if (isSequence) {
  4761. var x = numeric(n[0]);
  4762. var y = numeric(n[1]);
  4763. var width = Math.max(n[0].length, n[1].length);
  4764. var incr = n.length == 3
  4765. ? Math.abs(numeric(n[2]))
  4766. : 1;
  4767. var test = lte;
  4768. var reverse = y < x;
  4769. if (reverse) {
  4770. incr *= -1;
  4771. test = gte;
  4772. }
  4773. var pad = n.some(isPadded);
  4774. N = [];
  4775. for (var i = x; test(i, y); i += incr) {
  4776. var c;
  4777. if (isAlphaSequence) {
  4778. c = String.fromCharCode(i);
  4779. if (c === '\\')
  4780. c = '';
  4781. } else {
  4782. c = String(i);
  4783. if (pad) {
  4784. var need = width - c.length;
  4785. if (need > 0) {
  4786. var z = new Array(need + 1).join('0');
  4787. if (i < 0)
  4788. c = '-' + z + c.slice(1);
  4789. else
  4790. c = z + c;
  4791. }
  4792. }
  4793. }
  4794. N.push(c);
  4795. }
  4796. } else {
  4797. N = concatMap(n, function(el) { return expand$3(el, false) });
  4798. }
  4799. for (var j = 0; j < N.length; j++) {
  4800. for (var k = 0; k < post.length; k++) {
  4801. var expansion = pre + N[j] + post[k];
  4802. if (!isTop || isSequence || expansion)
  4803. expansions.push(expansion);
  4804. }
  4805. }
  4806. return expansions;
  4807. }
  4808. var minimatch_1 = minimatch$3;
  4809. minimatch$3.Minimatch = Minimatch$1;
  4810. var path$k = { sep: '/' };
  4811. try {
  4812. path$k = require('path');
  4813. } catch (er) {}
  4814. var GLOBSTAR$2 = minimatch$3.GLOBSTAR = Minimatch$1.GLOBSTAR = {};
  4815. var expand$2 = braceExpansion;
  4816. var plTypes = {
  4817. '!': { open: '(?:(?!(?:', close: '))[^/]*?)'},
  4818. '?': { open: '(?:', close: ')?' },
  4819. '+': { open: '(?:', close: ')+' },
  4820. '*': { open: '(?:', close: ')*' },
  4821. '@': { open: '(?:', close: ')' }
  4822. };
  4823. // any single thing other than /
  4824. // don't need to escape / when using new RegExp()
  4825. var qmark = '[^/]';
  4826. // * => any number of characters
  4827. var star = qmark + '*?';
  4828. // ** when dots are allowed. Anything goes, except .. and .
  4829. // not (^ or / followed by one or two dots followed by $ or /),
  4830. // followed by anything, any number of times.
  4831. var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?';
  4832. // not a ^ or / followed by a dot,
  4833. // followed by anything, any number of times.
  4834. var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?';
  4835. // characters that need to be escaped in RegExp.
  4836. var reSpecials = charSet('().*{}+?[]^$\\!');
  4837. // "abc" -> { a:true, b:true, c:true }
  4838. function charSet (s) {
  4839. return s.split('').reduce(function (set, c) {
  4840. set[c] = true;
  4841. return set
  4842. }, {})
  4843. }
  4844. // normalizes slashes.
  4845. var slashSplit = /\/+/;
  4846. minimatch$3.filter = filter$1;
  4847. function filter$1 (pattern, options) {
  4848. options = options || {};
  4849. return function (p, i, list) {
  4850. return minimatch$3(p, pattern, options)
  4851. }
  4852. }
  4853. function ext (a, b) {
  4854. a = a || {};
  4855. b = b || {};
  4856. var t = {};
  4857. Object.keys(b).forEach(function (k) {
  4858. t[k] = b[k];
  4859. });
  4860. Object.keys(a).forEach(function (k) {
  4861. t[k] = a[k];
  4862. });
  4863. return t
  4864. }
  4865. minimatch$3.defaults = function (def) {
  4866. if (!def || !Object.keys(def).length) return minimatch$3
  4867. var orig = minimatch$3;
  4868. var m = function minimatch (p, pattern, options) {
  4869. return orig.minimatch(p, pattern, ext(def, options))
  4870. };
  4871. m.Minimatch = function Minimatch (pattern, options) {
  4872. return new orig.Minimatch(pattern, ext(def, options))
  4873. };
  4874. return m
  4875. };
  4876. Minimatch$1.defaults = function (def) {
  4877. if (!def || !Object.keys(def).length) return Minimatch$1
  4878. return minimatch$3.defaults(def).Minimatch
  4879. };
  4880. function minimatch$3 (p, pattern, options) {
  4881. if (typeof pattern !== 'string') {
  4882. throw new TypeError('glob pattern string required')
  4883. }
  4884. if (!options) options = {};
  4885. // shortcut: comments match nothing.
  4886. if (!options.nocomment && pattern.charAt(0) === '#') {
  4887. return false
  4888. }
  4889. // "" only matches ""
  4890. if (pattern.trim() === '') return p === ''
  4891. return new Minimatch$1(pattern, options).match(p)
  4892. }
  4893. function Minimatch$1 (pattern, options) {
  4894. if (!(this instanceof Minimatch$1)) {
  4895. return new Minimatch$1(pattern, options)
  4896. }
  4897. if (typeof pattern !== 'string') {
  4898. throw new TypeError('glob pattern string required')
  4899. }
  4900. if (!options) options = {};
  4901. pattern = pattern.trim();
  4902. // windows support: need to use /, not \
  4903. if (path$k.sep !== '/') {
  4904. pattern = pattern.split(path$k.sep).join('/');
  4905. }
  4906. this.options = options;
  4907. this.set = [];
  4908. this.pattern = pattern;
  4909. this.regexp = null;
  4910. this.negate = false;
  4911. this.comment = false;
  4912. this.empty = false;
  4913. // make the set of regexps etc.
  4914. this.make();
  4915. }
  4916. Minimatch$1.prototype.debug = function () {};
  4917. Minimatch$1.prototype.make = make;
  4918. function make () {
  4919. // don't do it more than once.
  4920. if (this._made) return
  4921. var pattern = this.pattern;
  4922. var options = this.options;
  4923. // empty patterns and comments match nothing.
  4924. if (!options.nocomment && pattern.charAt(0) === '#') {
  4925. this.comment = true;
  4926. return
  4927. }
  4928. if (!pattern) {
  4929. this.empty = true;
  4930. return
  4931. }
  4932. // step 1: figure out negation, etc.
  4933. this.parseNegate();
  4934. // step 2: expand braces
  4935. var set = this.globSet = this.braceExpand();
  4936. if (options.debug) this.debug = console.error;
  4937. this.debug(this.pattern, set);
  4938. // step 3: now we have a set, so turn each one into a series of path-portion
  4939. // matching patterns.
  4940. // These will be regexps, except in the case of "**", which is
  4941. // set to the GLOBSTAR object for globstar behavior,
  4942. // and will not contain any / characters
  4943. set = this.globParts = set.map(function (s) {
  4944. return s.split(slashSplit)
  4945. });
  4946. this.debug(this.pattern, set);
  4947. // glob --> regexps
  4948. set = set.map(function (s, si, set) {
  4949. return s.map(this.parse, this)
  4950. }, this);
  4951. this.debug(this.pattern, set);
  4952. // filter out everything that didn't compile properly.
  4953. set = set.filter(function (s) {
  4954. return s.indexOf(false) === -1
  4955. });
  4956. this.debug(this.pattern, set);
  4957. this.set = set;
  4958. }
  4959. Minimatch$1.prototype.parseNegate = parseNegate;
  4960. function parseNegate () {
  4961. var pattern = this.pattern;
  4962. var negate = false;
  4963. var options = this.options;
  4964. var negateOffset = 0;
  4965. if (options.nonegate) return
  4966. for (var i = 0, l = pattern.length
  4967. ; i < l && pattern.charAt(i) === '!'
  4968. ; i++) {
  4969. negate = !negate;
  4970. negateOffset++;
  4971. }
  4972. if (negateOffset) this.pattern = pattern.substr(negateOffset);
  4973. this.negate = negate;
  4974. }
  4975. // Brace expansion:
  4976. // a{b,c}d -> abd acd
  4977. // a{b,}c -> abc ac
  4978. // a{0..3}d -> a0d a1d a2d a3d
  4979. // a{b,c{d,e}f}g -> abg acdfg acefg
  4980. // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
  4981. //
  4982. // Invalid sets are not expanded.
  4983. // a{2..}b -> a{2..}b
  4984. // a{b}c -> a{b}c
  4985. minimatch$3.braceExpand = function (pattern, options) {
  4986. return braceExpand(pattern, options)
  4987. };
  4988. Minimatch$1.prototype.braceExpand = braceExpand;
  4989. function braceExpand (pattern, options) {
  4990. if (!options) {
  4991. if (this instanceof Minimatch$1) {
  4992. options = this.options;
  4993. } else {
  4994. options = {};
  4995. }
  4996. }
  4997. pattern = typeof pattern === 'undefined'
  4998. ? this.pattern : pattern;
  4999. if (typeof pattern === 'undefined') {
  5000. throw new TypeError('undefined pattern')
  5001. }
  5002. if (options.nobrace ||
  5003. !pattern.match(/\{.*\}/)) {
  5004. // shortcut. no need to expand.
  5005. return [pattern]
  5006. }
  5007. return expand$2(pattern)
  5008. }
  5009. // parse a component of the expanded set.
  5010. // At this point, no pattern may contain "/" in it
  5011. // so we're going to return a 2d array, where each entry is the full
  5012. // pattern, split on '/', and then turned into a regular expression.
  5013. // A regexp is made at the end which joins each array with an
  5014. // escaped /, and another full one which joins each regexp with |.
  5015. //
  5016. // Following the lead of Bash 4.1, note that "**" only has special meaning
  5017. // when it is the *only* thing in a path portion. Otherwise, any series
  5018. // of * is equivalent to a single *. Globstar behavior is enabled by
  5019. // default, and can be disabled by setting options.noglobstar.
  5020. Minimatch$1.prototype.parse = parse$j;
  5021. var SUBPARSE = {};
  5022. function parse$j (pattern, isSub) {
  5023. if (pattern.length > 1024 * 64) {
  5024. throw new TypeError('pattern is too long')
  5025. }
  5026. var options = this.options;
  5027. // shortcuts
  5028. if (!options.noglobstar && pattern === '**') return GLOBSTAR$2
  5029. if (pattern === '') return ''
  5030. var re = '';
  5031. var hasMagic = !!options.nocase;
  5032. var escaping = false;
  5033. // ? => one single character
  5034. var patternListStack = [];
  5035. var negativeLists = [];
  5036. var stateChar;
  5037. var inClass = false;
  5038. var reClassStart = -1;
  5039. var classStart = -1;
  5040. // . and .. never match anything that doesn't start with .,
  5041. // even when options.dot is set.
  5042. var patternStart = pattern.charAt(0) === '.' ? '' // anything
  5043. // not (start or / followed by . or .. followed by / or end)
  5044. : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))'
  5045. : '(?!\\.)';
  5046. var self = this;
  5047. function clearStateChar () {
  5048. if (stateChar) {
  5049. // we had some state-tracking character
  5050. // that wasn't consumed by this pass.
  5051. switch (stateChar) {
  5052. case '*':
  5053. re += star;
  5054. hasMagic = true;
  5055. break
  5056. case '?':
  5057. re += qmark;
  5058. hasMagic = true;
  5059. break
  5060. default:
  5061. re += '\\' + stateChar;
  5062. break
  5063. }
  5064. self.debug('clearStateChar %j %j', stateChar, re);
  5065. stateChar = false;
  5066. }
  5067. }
  5068. for (var i = 0, len = pattern.length, c
  5069. ; (i < len) && (c = pattern.charAt(i))
  5070. ; i++) {
  5071. this.debug('%s\t%s %s %j', pattern, i, re, c);
  5072. // skip over any that are escaped.
  5073. if (escaping && reSpecials[c]) {
  5074. re += '\\' + c;
  5075. escaping = false;
  5076. continue
  5077. }
  5078. switch (c) {
  5079. case '/':
  5080. // completely not allowed, even escaped.
  5081. // Should already be path-split by now.
  5082. return false
  5083. case '\\':
  5084. clearStateChar();
  5085. escaping = true;
  5086. continue
  5087. // the various stateChar values
  5088. // for the "extglob" stuff.
  5089. case '?':
  5090. case '*':
  5091. case '+':
  5092. case '@':
  5093. case '!':
  5094. this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c);
  5095. // all of those are literals inside a class, except that
  5096. // the glob [!a] means [^a] in regexp
  5097. if (inClass) {
  5098. this.debug(' in class');
  5099. if (c === '!' && i === classStart + 1) c = '^';
  5100. re += c;
  5101. continue
  5102. }
  5103. // if we already have a stateChar, then it means
  5104. // that there was something like ** or +? in there.
  5105. // Handle the stateChar, then proceed with this one.
  5106. self.debug('call clearStateChar %j', stateChar);
  5107. clearStateChar();
  5108. stateChar = c;
  5109. // if extglob is disabled, then +(asdf|foo) isn't a thing.
  5110. // just clear the statechar *now*, rather than even diving into
  5111. // the patternList stuff.
  5112. if (options.noext) clearStateChar();
  5113. continue
  5114. case '(':
  5115. if (inClass) {
  5116. re += '(';
  5117. continue
  5118. }
  5119. if (!stateChar) {
  5120. re += '\\(';
  5121. continue
  5122. }
  5123. patternListStack.push({
  5124. type: stateChar,
  5125. start: i - 1,
  5126. reStart: re.length,
  5127. open: plTypes[stateChar].open,
  5128. close: plTypes[stateChar].close
  5129. });
  5130. // negation is (?:(?!js)[^/]*)
  5131. re += stateChar === '!' ? '(?:(?!(?:' : '(?:';
  5132. this.debug('plType %j %j', stateChar, re);
  5133. stateChar = false;
  5134. continue
  5135. case ')':
  5136. if (inClass || !patternListStack.length) {
  5137. re += '\\)';
  5138. continue
  5139. }
  5140. clearStateChar();
  5141. hasMagic = true;
  5142. var pl = patternListStack.pop();
  5143. // negation is (?:(?!js)[^/]*)
  5144. // The others are (?:<pattern>)<type>
  5145. re += pl.close;
  5146. if (pl.type === '!') {
  5147. negativeLists.push(pl);
  5148. }
  5149. pl.reEnd = re.length;
  5150. continue
  5151. case '|':
  5152. if (inClass || !patternListStack.length || escaping) {
  5153. re += '\\|';
  5154. escaping = false;
  5155. continue
  5156. }
  5157. clearStateChar();
  5158. re += '|';
  5159. continue
  5160. // these are mostly the same in regexp and glob
  5161. case '[':
  5162. // swallow any state-tracking char before the [
  5163. clearStateChar();
  5164. if (inClass) {
  5165. re += '\\' + c;
  5166. continue
  5167. }
  5168. inClass = true;
  5169. classStart = i;
  5170. reClassStart = re.length;
  5171. re += c;
  5172. continue
  5173. case ']':
  5174. // a right bracket shall lose its special
  5175. // meaning and represent itself in
  5176. // a bracket expression if it occurs
  5177. // first in the list. -- POSIX.2 2.8.3.2
  5178. if (i === classStart + 1 || !inClass) {
  5179. re += '\\' + c;
  5180. escaping = false;
  5181. continue
  5182. }
  5183. // handle the case where we left a class open.
  5184. // "[z-a]" is valid, equivalent to "\[z-a\]"
  5185. if (inClass) {
  5186. // split where the last [ was, make sure we don't have
  5187. // an invalid re. if so, re-walk the contents of the
  5188. // would-be class to re-translate any characters that
  5189. // were passed through as-is
  5190. // TODO: It would probably be faster to determine this
  5191. // without a try/catch and a new RegExp, but it's tricky
  5192. // to do safely. For now, this is safe and works.
  5193. var cs = pattern.substring(classStart + 1, i);
  5194. try {
  5195. } catch (er) {
  5196. // not a valid class!
  5197. var sp = this.parse(cs, SUBPARSE);
  5198. re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]';
  5199. hasMagic = hasMagic || sp[1];
  5200. inClass = false;
  5201. continue
  5202. }
  5203. }
  5204. // finish up the class.
  5205. hasMagic = true;
  5206. inClass = false;
  5207. re += c;
  5208. continue
  5209. default:
  5210. // swallow any state char that wasn't consumed
  5211. clearStateChar();
  5212. if (escaping) {
  5213. // no need
  5214. escaping = false;
  5215. } else if (reSpecials[c]
  5216. && !(c === '^' && inClass)) {
  5217. re += '\\';
  5218. }
  5219. re += c;
  5220. } // switch
  5221. } // for
  5222. // handle the case where we left a class open.
  5223. // "[abc" is valid, equivalent to "\[abc"
  5224. if (inClass) {
  5225. // split where the last [ was, and escape it
  5226. // this is a huge pita. We now have to re-walk
  5227. // the contents of the would-be class to re-translate
  5228. // any characters that were passed through as-is
  5229. cs = pattern.substr(classStart + 1);
  5230. sp = this.parse(cs, SUBPARSE);
  5231. re = re.substr(0, reClassStart) + '\\[' + sp[0];
  5232. hasMagic = hasMagic || sp[1];
  5233. }
  5234. // handle the case where we had a +( thing at the *end*
  5235. // of the pattern.
  5236. // each pattern list stack adds 3 chars, and we need to go through
  5237. // and escape any | chars that were passed through as-is for the regexp.
  5238. // Go through and escape them, taking care not to double-escape any
  5239. // | chars that were already escaped.
  5240. for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
  5241. var tail = re.slice(pl.reStart + pl.open.length);
  5242. this.debug('setting tail', re, pl);
  5243. // maybe some even number of \, then maybe 1 \, followed by a |
  5244. tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) {
  5245. if (!$2) {
  5246. // the | isn't already escaped, so escape it.
  5247. $2 = '\\';
  5248. }
  5249. // need to escape all those slashes *again*, without escaping the
  5250. // one that we need for escaping the | character. As it works out,
  5251. // escaping an even number of slashes can be done by simply repeating
  5252. // it exactly after itself. That's why this trick works.
  5253. //
  5254. // I am sorry that you have to see this.
  5255. return $1 + $1 + $2 + '|'
  5256. });
  5257. this.debug('tail=%j\n %s', tail, tail, pl, re);
  5258. var t = pl.type === '*' ? star
  5259. : pl.type === '?' ? qmark
  5260. : '\\' + pl.type;
  5261. hasMagic = true;
  5262. re = re.slice(0, pl.reStart) + t + '\\(' + tail;
  5263. }
  5264. // handle trailing things that only matter at the very end.
  5265. clearStateChar();
  5266. if (escaping) {
  5267. // trailing \\
  5268. re += '\\\\';
  5269. }
  5270. // only need to apply the nodot start if the re starts with
  5271. // something that could conceivably capture a dot
  5272. var addPatternStart = false;
  5273. switch (re.charAt(0)) {
  5274. case '.':
  5275. case '[':
  5276. case '(': addPatternStart = true;
  5277. }
  5278. // Hack to work around lack of negative lookbehind in JS
  5279. // A pattern like: *.!(x).!(y|z) needs to ensure that a name
  5280. // like 'a.xyz.yz' doesn't match. So, the first negative
  5281. // lookahead, has to look ALL the way ahead, to the end of
  5282. // the pattern.
  5283. for (var n = negativeLists.length - 1; n > -1; n--) {
  5284. var nl = negativeLists[n];
  5285. var nlBefore = re.slice(0, nl.reStart);
  5286. var nlFirst = re.slice(nl.reStart, nl.reEnd - 8);
  5287. var nlLast = re.slice(nl.reEnd - 8, nl.reEnd);
  5288. var nlAfter = re.slice(nl.reEnd);
  5289. nlLast += nlAfter;
  5290. // Handle nested stuff like *(*.js|!(*.json)), where open parens
  5291. // mean that we should *not* include the ) in the bit that is considered
  5292. // "after" the negated section.
  5293. var openParensBefore = nlBefore.split('(').length - 1;
  5294. var cleanAfter = nlAfter;
  5295. for (i = 0; i < openParensBefore; i++) {
  5296. cleanAfter = cleanAfter.replace(/\)[+*?]?/, '');
  5297. }
  5298. nlAfter = cleanAfter;
  5299. var dollar = '';
  5300. if (nlAfter === '' && isSub !== SUBPARSE) {
  5301. dollar = '$';
  5302. }
  5303. var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast;
  5304. re = newRe;
  5305. }
  5306. // if the re is not "" at this point, then we need to make sure
  5307. // it doesn't match against an empty path part.
  5308. // Otherwise a/* will match a/, which it should not.
  5309. if (re !== '' && hasMagic) {
  5310. re = '(?=.)' + re;
  5311. }
  5312. if (addPatternStart) {
  5313. re = patternStart + re;
  5314. }
  5315. // parsing just a piece of a larger pattern.
  5316. if (isSub === SUBPARSE) {
  5317. return [re, hasMagic]
  5318. }
  5319. // skip the regexp for non-magical patterns
  5320. // unescape anything in it, though, so that it'll be
  5321. // an exact match against a file etc.
  5322. if (!hasMagic) {
  5323. return globUnescape(pattern)
  5324. }
  5325. var flags = options.nocase ? 'i' : '';
  5326. try {
  5327. var regExp = new RegExp('^' + re + '$', flags);
  5328. } catch (er) {
  5329. // If it was an invalid regular expression, then it can't match
  5330. // anything. This trick looks for a character after the end of
  5331. // the string, which is of course impossible, except in multi-line
  5332. // mode, but it's not a /m regex.
  5333. return new RegExp('$.')
  5334. }
  5335. regExp._glob = pattern;
  5336. regExp._src = re;
  5337. return regExp
  5338. }
  5339. minimatch$3.makeRe = function (pattern, options) {
  5340. return new Minimatch$1(pattern, options || {}).makeRe()
  5341. };
  5342. Minimatch$1.prototype.makeRe = makeRe$1;
  5343. function makeRe$1 () {
  5344. if (this.regexp || this.regexp === false) return this.regexp
  5345. // at this point, this.set is a 2d array of partial
  5346. // pattern strings, or "**".
  5347. //
  5348. // It's better to use .match(). This function shouldn't
  5349. // be used, really, but it's pretty convenient sometimes,
  5350. // when you just want to work with a regex.
  5351. var set = this.set;
  5352. if (!set.length) {
  5353. this.regexp = false;
  5354. return this.regexp
  5355. }
  5356. var options = this.options;
  5357. var twoStar = options.noglobstar ? star
  5358. : options.dot ? twoStarDot
  5359. : twoStarNoDot;
  5360. var flags = options.nocase ? 'i' : '';
  5361. var re = set.map(function (pattern) {
  5362. return pattern.map(function (p) {
  5363. return (p === GLOBSTAR$2) ? twoStar
  5364. : (typeof p === 'string') ? regExpEscape(p)
  5365. : p._src
  5366. }).join('\\\/')
  5367. }).join('|');
  5368. // must match entire pattern
  5369. // ending in a * or ** will make it less strict.
  5370. re = '^(?:' + re + ')$';
  5371. // can match anything, as long as it's not this.
  5372. if (this.negate) re = '^(?!' + re + ').*$';
  5373. try {
  5374. this.regexp = new RegExp(re, flags);
  5375. } catch (ex) {
  5376. this.regexp = false;
  5377. }
  5378. return this.regexp
  5379. }
  5380. minimatch$3.match = function (list, pattern, options) {
  5381. options = options || {};
  5382. var mm = new Minimatch$1(pattern, options);
  5383. list = list.filter(function (f) {
  5384. return mm.match(f)
  5385. });
  5386. if (mm.options.nonull && !list.length) {
  5387. list.push(pattern);
  5388. }
  5389. return list
  5390. };
  5391. Minimatch$1.prototype.match = match;
  5392. function match (f, partial) {
  5393. this.debug('match', f, this.pattern);
  5394. // short-circuit in the case of busted things.
  5395. // comments, etc.
  5396. if (this.comment) return false
  5397. if (this.empty) return f === ''
  5398. if (f === '/' && partial) return true
  5399. var options = this.options;
  5400. // windows: need to use /, not \
  5401. if (path$k.sep !== '/') {
  5402. f = f.split(path$k.sep).join('/');
  5403. }
  5404. // treat the test path as a set of pathparts.
  5405. f = f.split(slashSplit);
  5406. this.debug(this.pattern, 'split', f);
  5407. // just ONE of the pattern sets in this.set needs to match
  5408. // in order for it to be valid. If negating, then just one
  5409. // match means that we have failed.
  5410. // Either way, return on the first hit.
  5411. var set = this.set;
  5412. this.debug(this.pattern, 'set', set);
  5413. // Find the basename of the path by looking for the last non-empty segment
  5414. var filename;
  5415. var i;
  5416. for (i = f.length - 1; i >= 0; i--) {
  5417. filename = f[i];
  5418. if (filename) break
  5419. }
  5420. for (i = 0; i < set.length; i++) {
  5421. var pattern = set[i];
  5422. var file = f;
  5423. if (options.matchBase && pattern.length === 1) {
  5424. file = [filename];
  5425. }
  5426. var hit = this.matchOne(file, pattern, partial);
  5427. if (hit) {
  5428. if (options.flipNegate) return true
  5429. return !this.negate
  5430. }
  5431. }
  5432. // didn't get any hits. this is success if it's a negative
  5433. // pattern, failure otherwise.
  5434. if (options.flipNegate) return false
  5435. return this.negate
  5436. }
  5437. // set partial to true to test if, for example,
  5438. // "/a/b" matches the start of "/*/b/*/d"
  5439. // Partial means, if you run out of file before you run
  5440. // out of pattern, then that's fine, as long as all
  5441. // the parts match.
  5442. Minimatch$1.prototype.matchOne = function (file, pattern, partial) {
  5443. var options = this.options;
  5444. this.debug('matchOne',
  5445. { 'this': this, file: file, pattern: pattern });
  5446. this.debug('matchOne', file.length, pattern.length);
  5447. for (var fi = 0,
  5448. pi = 0,
  5449. fl = file.length,
  5450. pl = pattern.length
  5451. ; (fi < fl) && (pi < pl)
  5452. ; fi++, pi++) {
  5453. this.debug('matchOne loop');
  5454. var p = pattern[pi];
  5455. var f = file[fi];
  5456. this.debug(pattern, p, f);
  5457. // should be impossible.
  5458. // some invalid regexp stuff in the set.
  5459. if (p === false) return false
  5460. if (p === GLOBSTAR$2) {
  5461. this.debug('GLOBSTAR', [pattern, p, f]);
  5462. // "**"
  5463. // a/**/b/**/c would match the following:
  5464. // a/b/x/y/z/c
  5465. // a/x/y/z/b/c
  5466. // a/b/x/b/x/c
  5467. // a/b/c
  5468. // To do this, take the rest of the pattern after
  5469. // the **, and see if it would match the file remainder.
  5470. // If so, return success.
  5471. // If not, the ** "swallows" a segment, and try again.
  5472. // This is recursively awful.
  5473. //
  5474. // a/**/b/**/c matching a/b/x/y/z/c
  5475. // - a matches a
  5476. // - doublestar
  5477. // - matchOne(b/x/y/z/c, b/**/c)
  5478. // - b matches b
  5479. // - doublestar
  5480. // - matchOne(x/y/z/c, c) -> no
  5481. // - matchOne(y/z/c, c) -> no
  5482. // - matchOne(z/c, c) -> no
  5483. // - matchOne(c, c) yes, hit
  5484. var fr = fi;
  5485. var pr = pi + 1;
  5486. if (pr === pl) {
  5487. this.debug('** at the end');
  5488. // a ** at the end will just swallow the rest.
  5489. // We have found a match.
  5490. // however, it will not swallow /.x, unless
  5491. // options.dot is set.
  5492. // . and .. are *never* matched by **, for explosively
  5493. // exponential reasons.
  5494. for (; fi < fl; fi++) {
  5495. if (file[fi] === '.' || file[fi] === '..' ||
  5496. (!options.dot && file[fi].charAt(0) === '.')) return false
  5497. }
  5498. return true
  5499. }
  5500. // ok, let's see if we can swallow whatever we can.
  5501. while (fr < fl) {
  5502. var swallowee = file[fr];
  5503. this.debug('\nglobstar while', file, fr, pattern, pr, swallowee);
  5504. // XXX remove this slice. Just pass the start index.
  5505. if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
  5506. this.debug('globstar found match!', fr, fl, swallowee);
  5507. // found a match.
  5508. return true
  5509. } else {
  5510. // can't swallow "." or ".." ever.
  5511. // can only swallow ".foo" when explicitly asked.
  5512. if (swallowee === '.' || swallowee === '..' ||
  5513. (!options.dot && swallowee.charAt(0) === '.')) {
  5514. this.debug('dot detected!', file, fr, pattern, pr);
  5515. break
  5516. }
  5517. // ** swallows a segment, and continue.
  5518. this.debug('globstar swallow a segment, and continue');
  5519. fr++;
  5520. }
  5521. }
  5522. // no match was found.
  5523. // However, in partial mode, we can't say this is necessarily over.
  5524. // If there's more *pattern* left, then
  5525. if (partial) {
  5526. // ran out of file
  5527. this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
  5528. if (fr === fl) return true
  5529. }
  5530. return false
  5531. }
  5532. // something other than **
  5533. // non-magic patterns just have to match exactly
  5534. // patterns with magic have been turned into regexps.
  5535. var hit;
  5536. if (typeof p === 'string') {
  5537. if (options.nocase) {
  5538. hit = f.toLowerCase() === p.toLowerCase();
  5539. } else {
  5540. hit = f === p;
  5541. }
  5542. this.debug('string match', p, f, hit);
  5543. } else {
  5544. hit = f.match(p);
  5545. this.debug('pattern match', p, f, hit);
  5546. }
  5547. if (!hit) return false
  5548. }
  5549. // Note: ending in / means that we'll get a final ""
  5550. // at the end of the pattern. This can only match a
  5551. // corresponding "" at the end of the file.
  5552. // If the file ends in /, then it can only match a
  5553. // a pattern that ends in /, unless the pattern just
  5554. // doesn't have any more for it. But, a/b/ should *not*
  5555. // match "a/b/*", even though "" matches against the
  5556. // [^/]*? pattern, except in partial mode, where it might
  5557. // simply not be reached yet.
  5558. // However, a/b/ should still satisfy a/*
  5559. // now either we fell off the end of the pattern, or we're done.
  5560. if (fi === fl && pi === pl) {
  5561. // ran out of pattern and filename at the same time.
  5562. // an exact hit!
  5563. return true
  5564. } else if (fi === fl) {
  5565. // ran out of file, but still had pattern left.
  5566. // this is ok if we're doing the match as part of
  5567. // a glob fs traversal.
  5568. return partial
  5569. } else if (pi === pl) {
  5570. // ran out of pattern, still have file left.
  5571. // this is only acceptable if we're on the very last
  5572. // empty segment of a file with a trailing slash.
  5573. // a/* should match a/b/
  5574. var emptyFileEnd = (fi === fl - 1) && (file[fi] === '');
  5575. return emptyFileEnd
  5576. }
  5577. // should be unreachable.
  5578. throw new Error('wtf?')
  5579. };
  5580. // replace stuff like \* with *
  5581. function globUnescape (s) {
  5582. return s.replace(/\\(.)/g, '$1')
  5583. }
  5584. function regExpEscape (s) {
  5585. return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
  5586. }
  5587. var inherits$1 = {exports: {}};
  5588. var inherits_browser = {exports: {}};
  5589. if (typeof Object.create === 'function') {
  5590. // implementation from standard node.js 'util' module
  5591. inherits_browser.exports = function inherits(ctor, superCtor) {
  5592. if (superCtor) {
  5593. ctor.super_ = superCtor;
  5594. ctor.prototype = Object.create(superCtor.prototype, {
  5595. constructor: {
  5596. value: ctor,
  5597. enumerable: false,
  5598. writable: true,
  5599. configurable: true
  5600. }
  5601. });
  5602. }
  5603. };
  5604. } else {
  5605. // old school shim for old browsers
  5606. inherits_browser.exports = function inherits(ctor, superCtor) {
  5607. if (superCtor) {
  5608. ctor.super_ = superCtor;
  5609. var TempCtor = function () {};
  5610. TempCtor.prototype = superCtor.prototype;
  5611. ctor.prototype = new TempCtor();
  5612. ctor.prototype.constructor = ctor;
  5613. }
  5614. };
  5615. }
  5616. try {
  5617. var util$4 = require('util');
  5618. /* istanbul ignore next */
  5619. if (typeof util$4.inherits !== 'function') throw '';
  5620. inherits$1.exports = util$4.inherits;
  5621. } catch (e) {
  5622. /* istanbul ignore next */
  5623. inherits$1.exports = inherits_browser.exports;
  5624. }
  5625. var pathIsAbsolute = {exports: {}};
  5626. function posix(path) {
  5627. return path.charAt(0) === '/';
  5628. }
  5629. function win32(path) {
  5630. // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56
  5631. var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/;
  5632. var result = splitDeviceRe.exec(path);
  5633. var device = result[1] || '';
  5634. var isUnc = Boolean(device && device.charAt(1) !== ':');
  5635. // UNC paths are always absolute
  5636. return Boolean(result[2] || isUnc);
  5637. }
  5638. pathIsAbsolute.exports = process.platform === 'win32' ? win32 : posix;
  5639. pathIsAbsolute.exports.posix = posix;
  5640. pathIsAbsolute.exports.win32 = win32;
  5641. var common$e = {};
  5642. common$e.setopts = setopts$2;
  5643. common$e.ownProp = ownProp$2;
  5644. common$e.makeAbs = makeAbs;
  5645. common$e.finish = finish;
  5646. common$e.mark = mark;
  5647. common$e.isIgnored = isIgnored$2;
  5648. common$e.childrenIgnored = childrenIgnored$2;
  5649. function ownProp$2 (obj, field) {
  5650. return Object.prototype.hasOwnProperty.call(obj, field)
  5651. }
  5652. var fs$j = fs__default;
  5653. var path$j = path__default;
  5654. var minimatch$2 = minimatch_1;
  5655. var isAbsolute$2 = pathIsAbsolute.exports;
  5656. var Minimatch = minimatch$2.Minimatch;
  5657. function alphasort (a, b) {
  5658. return a.localeCompare(b, 'en')
  5659. }
  5660. function setupIgnores (self, options) {
  5661. self.ignore = options.ignore || [];
  5662. if (!Array.isArray(self.ignore))
  5663. self.ignore = [self.ignore];
  5664. if (self.ignore.length) {
  5665. self.ignore = self.ignore.map(ignoreMap);
  5666. }
  5667. }
  5668. // ignore patterns are always in dot:true mode.
  5669. function ignoreMap (pattern) {
  5670. var gmatcher = null;
  5671. if (pattern.slice(-3) === '/**') {
  5672. var gpattern = pattern.replace(/(\/\*\*)+$/, '');
  5673. gmatcher = new Minimatch(gpattern, { dot: true });
  5674. }
  5675. return {
  5676. matcher: new Minimatch(pattern, { dot: true }),
  5677. gmatcher: gmatcher
  5678. }
  5679. }
  5680. function setopts$2 (self, pattern, options) {
  5681. if (!options)
  5682. options = {};
  5683. // base-matching: just use globstar for that.
  5684. if (options.matchBase && -1 === pattern.indexOf("/")) {
  5685. if (options.noglobstar) {
  5686. throw new Error("base matching requires globstar")
  5687. }
  5688. pattern = "**/" + pattern;
  5689. }
  5690. self.silent = !!options.silent;
  5691. self.pattern = pattern;
  5692. self.strict = options.strict !== false;
  5693. self.realpath = !!options.realpath;
  5694. self.realpathCache = options.realpathCache || Object.create(null);
  5695. self.follow = !!options.follow;
  5696. self.dot = !!options.dot;
  5697. self.mark = !!options.mark;
  5698. self.nodir = !!options.nodir;
  5699. if (self.nodir)
  5700. self.mark = true;
  5701. self.sync = !!options.sync;
  5702. self.nounique = !!options.nounique;
  5703. self.nonull = !!options.nonull;
  5704. self.nosort = !!options.nosort;
  5705. self.nocase = !!options.nocase;
  5706. self.stat = !!options.stat;
  5707. self.noprocess = !!options.noprocess;
  5708. self.absolute = !!options.absolute;
  5709. self.fs = options.fs || fs$j;
  5710. self.maxLength = options.maxLength || Infinity;
  5711. self.cache = options.cache || Object.create(null);
  5712. self.statCache = options.statCache || Object.create(null);
  5713. self.symlinks = options.symlinks || Object.create(null);
  5714. setupIgnores(self, options);
  5715. self.changedCwd = false;
  5716. var cwd = process.cwd();
  5717. if (!ownProp$2(options, "cwd"))
  5718. self.cwd = cwd;
  5719. else {
  5720. self.cwd = path$j.resolve(options.cwd);
  5721. self.changedCwd = self.cwd !== cwd;
  5722. }
  5723. self.root = options.root || path$j.resolve(self.cwd, "/");
  5724. self.root = path$j.resolve(self.root);
  5725. if (process.platform === "win32")
  5726. self.root = self.root.replace(/\\/g, "/");
  5727. // TODO: is an absolute `cwd` supposed to be resolved against `root`?
  5728. // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test')
  5729. self.cwdAbs = isAbsolute$2(self.cwd) ? self.cwd : makeAbs(self, self.cwd);
  5730. if (process.platform === "win32")
  5731. self.cwdAbs = self.cwdAbs.replace(/\\/g, "/");
  5732. self.nomount = !!options.nomount;
  5733. // disable comments and negation in Minimatch.
  5734. // Note that they are not supported in Glob itself anyway.
  5735. options.nonegate = true;
  5736. options.nocomment = true;
  5737. self.minimatch = new Minimatch(pattern, options);
  5738. self.options = self.minimatch.options;
  5739. }
  5740. function finish (self) {
  5741. var nou = self.nounique;
  5742. var all = nou ? [] : Object.create(null);
  5743. for (var i = 0, l = self.matches.length; i < l; i ++) {
  5744. var matches = self.matches[i];
  5745. if (!matches || Object.keys(matches).length === 0) {
  5746. if (self.nonull) {
  5747. // do like the shell, and spit out the literal glob
  5748. var literal = self.minimatch.globSet[i];
  5749. if (nou)
  5750. all.push(literal);
  5751. else
  5752. all[literal] = true;
  5753. }
  5754. } else {
  5755. // had matches
  5756. var m = Object.keys(matches);
  5757. if (nou)
  5758. all.push.apply(all, m);
  5759. else
  5760. m.forEach(function (m) {
  5761. all[m] = true;
  5762. });
  5763. }
  5764. }
  5765. if (!nou)
  5766. all = Object.keys(all);
  5767. if (!self.nosort)
  5768. all = all.sort(alphasort);
  5769. // at *some* point we statted all of these
  5770. if (self.mark) {
  5771. for (var i = 0; i < all.length; i++) {
  5772. all[i] = self._mark(all[i]);
  5773. }
  5774. if (self.nodir) {
  5775. all = all.filter(function (e) {
  5776. var notDir = !(/\/$/.test(e));
  5777. var c = self.cache[e] || self.cache[makeAbs(self, e)];
  5778. if (notDir && c)
  5779. notDir = c !== 'DIR' && !Array.isArray(c);
  5780. return notDir
  5781. });
  5782. }
  5783. }
  5784. if (self.ignore.length)
  5785. all = all.filter(function(m) {
  5786. return !isIgnored$2(self, m)
  5787. });
  5788. self.found = all;
  5789. }
  5790. function mark (self, p) {
  5791. var abs = makeAbs(self, p);
  5792. var c = self.cache[abs];
  5793. var m = p;
  5794. if (c) {
  5795. var isDir = c === 'DIR' || Array.isArray(c);
  5796. var slash = p.slice(-1) === '/';
  5797. if (isDir && !slash)
  5798. m += '/';
  5799. else if (!isDir && slash)
  5800. m = m.slice(0, -1);
  5801. if (m !== p) {
  5802. var mabs = makeAbs(self, m);
  5803. self.statCache[mabs] = self.statCache[abs];
  5804. self.cache[mabs] = self.cache[abs];
  5805. }
  5806. }
  5807. return m
  5808. }
  5809. // lotta situps...
  5810. function makeAbs (self, f) {
  5811. var abs = f;
  5812. if (f.charAt(0) === '/') {
  5813. abs = path$j.join(self.root, f);
  5814. } else if (isAbsolute$2(f) || f === '') {
  5815. abs = f;
  5816. } else if (self.changedCwd) {
  5817. abs = path$j.resolve(self.cwd, f);
  5818. } else {
  5819. abs = path$j.resolve(f);
  5820. }
  5821. if (process.platform === 'win32')
  5822. abs = abs.replace(/\\/g, '/');
  5823. return abs
  5824. }
  5825. // Return true, if pattern ends with globstar '**', for the accompanying parent directory.
  5826. // Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents
  5827. function isIgnored$2 (self, path) {
  5828. if (!self.ignore.length)
  5829. return false
  5830. return self.ignore.some(function(item) {
  5831. return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path))
  5832. })
  5833. }
  5834. function childrenIgnored$2 (self, path) {
  5835. if (!self.ignore.length)
  5836. return false
  5837. return self.ignore.some(function(item) {
  5838. return !!(item.gmatcher && item.gmatcher.match(path))
  5839. })
  5840. }
  5841. var sync$b = globSync$1;
  5842. globSync$1.GlobSync = GlobSync$1;
  5843. var rp$1 = fs_realpath;
  5844. var minimatch$1 = minimatch_1;
  5845. var path$i = path__default;
  5846. var assert$2 = require$$5__default;
  5847. var isAbsolute$1 = pathIsAbsolute.exports;
  5848. var common$d = common$e;
  5849. var setopts$1 = common$d.setopts;
  5850. var ownProp$1 = common$d.ownProp;
  5851. var childrenIgnored$1 = common$d.childrenIgnored;
  5852. var isIgnored$1 = common$d.isIgnored;
  5853. function globSync$1 (pattern, options) {
  5854. if (typeof options === 'function' || arguments.length === 3)
  5855. throw new TypeError('callback provided to sync glob\n'+
  5856. 'See: https://github.com/isaacs/node-glob/issues/167')
  5857. return new GlobSync$1(pattern, options).found
  5858. }
  5859. function GlobSync$1 (pattern, options) {
  5860. if (!pattern)
  5861. throw new Error('must provide pattern')
  5862. if (typeof options === 'function' || arguments.length === 3)
  5863. throw new TypeError('callback provided to sync glob\n'+
  5864. 'See: https://github.com/isaacs/node-glob/issues/167')
  5865. if (!(this instanceof GlobSync$1))
  5866. return new GlobSync$1(pattern, options)
  5867. setopts$1(this, pattern, options);
  5868. if (this.noprocess)
  5869. return this
  5870. var n = this.minimatch.set.length;
  5871. this.matches = new Array(n);
  5872. for (var i = 0; i < n; i ++) {
  5873. this._process(this.minimatch.set[i], i, false);
  5874. }
  5875. this._finish();
  5876. }
  5877. GlobSync$1.prototype._finish = function () {
  5878. assert$2(this instanceof GlobSync$1);
  5879. if (this.realpath) {
  5880. var self = this;
  5881. this.matches.forEach(function (matchset, index) {
  5882. var set = self.matches[index] = Object.create(null);
  5883. for (var p in matchset) {
  5884. try {
  5885. p = self._makeAbs(p);
  5886. var real = rp$1.realpathSync(p, self.realpathCache);
  5887. set[real] = true;
  5888. } catch (er) {
  5889. if (er.syscall === 'stat')
  5890. set[self._makeAbs(p)] = true;
  5891. else
  5892. throw er
  5893. }
  5894. }
  5895. });
  5896. }
  5897. common$d.finish(this);
  5898. };
  5899. GlobSync$1.prototype._process = function (pattern, index, inGlobStar) {
  5900. assert$2(this instanceof GlobSync$1);
  5901. // Get the first [n] parts of pattern that are all strings.
  5902. var n = 0;
  5903. while (typeof pattern[n] === 'string') {
  5904. n ++;
  5905. }
  5906. // now n is the index of the first one that is *not* a string.
  5907. // See if there's anything else
  5908. var prefix;
  5909. switch (n) {
  5910. // if not, then this is rather simple
  5911. case pattern.length:
  5912. this._processSimple(pattern.join('/'), index);
  5913. return
  5914. case 0:
  5915. // pattern *starts* with some non-trivial item.
  5916. // going to readdir(cwd), but not include the prefix in matches.
  5917. prefix = null;
  5918. break
  5919. default:
  5920. // pattern has some string bits in the front.
  5921. // whatever it starts with, whether that's 'absolute' like /foo/bar,
  5922. // or 'relative' like '../baz'
  5923. prefix = pattern.slice(0, n).join('/');
  5924. break
  5925. }
  5926. var remain = pattern.slice(n);
  5927. // get the list of entries.
  5928. var read;
  5929. if (prefix === null)
  5930. read = '.';
  5931. else if (isAbsolute$1(prefix) || isAbsolute$1(pattern.join('/'))) {
  5932. if (!prefix || !isAbsolute$1(prefix))
  5933. prefix = '/' + prefix;
  5934. read = prefix;
  5935. } else
  5936. read = prefix;
  5937. var abs = this._makeAbs(read);
  5938. //if ignored, skip processing
  5939. if (childrenIgnored$1(this, read))
  5940. return
  5941. var isGlobStar = remain[0] === minimatch$1.GLOBSTAR;
  5942. if (isGlobStar)
  5943. this._processGlobStar(prefix, read, abs, remain, index, inGlobStar);
  5944. else
  5945. this._processReaddir(prefix, read, abs, remain, index, inGlobStar);
  5946. };
  5947. GlobSync$1.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) {
  5948. var entries = this._readdir(abs, inGlobStar);
  5949. // if the abs isn't a dir, then nothing can match!
  5950. if (!entries)
  5951. return
  5952. // It will only match dot entries if it starts with a dot, or if
  5953. // dot is set. Stuff like @(.foo|.bar) isn't allowed.
  5954. var pn = remain[0];
  5955. var negate = !!this.minimatch.negate;
  5956. var rawGlob = pn._glob;
  5957. var dotOk = this.dot || rawGlob.charAt(0) === '.';
  5958. var matchedEntries = [];
  5959. for (var i = 0; i < entries.length; i++) {
  5960. var e = entries[i];
  5961. if (e.charAt(0) !== '.' || dotOk) {
  5962. var m;
  5963. if (negate && !prefix) {
  5964. m = !e.match(pn);
  5965. } else {
  5966. m = e.match(pn);
  5967. }
  5968. if (m)
  5969. matchedEntries.push(e);
  5970. }
  5971. }
  5972. var len = matchedEntries.length;
  5973. // If there are no matched entries, then nothing matches.
  5974. if (len === 0)
  5975. return
  5976. // if this is the last remaining pattern bit, then no need for
  5977. // an additional stat *unless* the user has specified mark or
  5978. // stat explicitly. We know they exist, since readdir returned
  5979. // them.
  5980. if (remain.length === 1 && !this.mark && !this.stat) {
  5981. if (!this.matches[index])
  5982. this.matches[index] = Object.create(null);
  5983. for (var i = 0; i < len; i ++) {
  5984. var e = matchedEntries[i];
  5985. if (prefix) {
  5986. if (prefix.slice(-1) !== '/')
  5987. e = prefix + '/' + e;
  5988. else
  5989. e = prefix + e;
  5990. }
  5991. if (e.charAt(0) === '/' && !this.nomount) {
  5992. e = path$i.join(this.root, e);
  5993. }
  5994. this._emitMatch(index, e);
  5995. }
  5996. // This was the last one, and no stats were needed
  5997. return
  5998. }
  5999. // now test all matched entries as stand-ins for that part
  6000. // of the pattern.
  6001. remain.shift();
  6002. for (var i = 0; i < len; i ++) {
  6003. var e = matchedEntries[i];
  6004. var newPattern;
  6005. if (prefix)
  6006. newPattern = [prefix, e];
  6007. else
  6008. newPattern = [e];
  6009. this._process(newPattern.concat(remain), index, inGlobStar);
  6010. }
  6011. };
  6012. GlobSync$1.prototype._emitMatch = function (index, e) {
  6013. if (isIgnored$1(this, e))
  6014. return
  6015. var abs = this._makeAbs(e);
  6016. if (this.mark)
  6017. e = this._mark(e);
  6018. if (this.absolute) {
  6019. e = abs;
  6020. }
  6021. if (this.matches[index][e])
  6022. return
  6023. if (this.nodir) {
  6024. var c = this.cache[abs];
  6025. if (c === 'DIR' || Array.isArray(c))
  6026. return
  6027. }
  6028. this.matches[index][e] = true;
  6029. if (this.stat)
  6030. this._stat(e);
  6031. };
  6032. GlobSync$1.prototype._readdirInGlobStar = function (abs) {
  6033. // follow all symlinked directories forever
  6034. // just proceed as if this is a non-globstar situation
  6035. if (this.follow)
  6036. return this._readdir(abs, false)
  6037. var entries;
  6038. var lstat;
  6039. try {
  6040. lstat = this.fs.lstatSync(abs);
  6041. } catch (er) {
  6042. if (er.code === 'ENOENT') {
  6043. // lstat failed, doesn't exist
  6044. return null
  6045. }
  6046. }
  6047. var isSym = lstat && lstat.isSymbolicLink();
  6048. this.symlinks[abs] = isSym;
  6049. // If it's not a symlink or a dir, then it's definitely a regular file.
  6050. // don't bother doing a readdir in that case.
  6051. if (!isSym && lstat && !lstat.isDirectory())
  6052. this.cache[abs] = 'FILE';
  6053. else
  6054. entries = this._readdir(abs, false);
  6055. return entries
  6056. };
  6057. GlobSync$1.prototype._readdir = function (abs, inGlobStar) {
  6058. if (inGlobStar && !ownProp$1(this.symlinks, abs))
  6059. return this._readdirInGlobStar(abs)
  6060. if (ownProp$1(this.cache, abs)) {
  6061. var c = this.cache[abs];
  6062. if (!c || c === 'FILE')
  6063. return null
  6064. if (Array.isArray(c))
  6065. return c
  6066. }
  6067. try {
  6068. return this._readdirEntries(abs, this.fs.readdirSync(abs))
  6069. } catch (er) {
  6070. this._readdirError(abs, er);
  6071. return null
  6072. }
  6073. };
  6074. GlobSync$1.prototype._readdirEntries = function (abs, entries) {
  6075. // if we haven't asked to stat everything, then just
  6076. // assume that everything in there exists, so we can avoid
  6077. // having to stat it a second time.
  6078. if (!this.mark && !this.stat) {
  6079. for (var i = 0; i < entries.length; i ++) {
  6080. var e = entries[i];
  6081. if (abs === '/')
  6082. e = abs + e;
  6083. else
  6084. e = abs + '/' + e;
  6085. this.cache[e] = true;
  6086. }
  6087. }
  6088. this.cache[abs] = entries;
  6089. // mark and cache dir-ness
  6090. return entries
  6091. };
  6092. GlobSync$1.prototype._readdirError = function (f, er) {
  6093. // handle errors, and cache the information
  6094. switch (er.code) {
  6095. case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
  6096. case 'ENOTDIR': // totally normal. means it *does* exist.
  6097. var abs = this._makeAbs(f);
  6098. this.cache[abs] = 'FILE';
  6099. if (abs === this.cwdAbs) {
  6100. var error = new Error(er.code + ' invalid cwd ' + this.cwd);
  6101. error.path = this.cwd;
  6102. error.code = er.code;
  6103. throw error
  6104. }
  6105. break
  6106. case 'ENOENT': // not terribly unusual
  6107. case 'ELOOP':
  6108. case 'ENAMETOOLONG':
  6109. case 'UNKNOWN':
  6110. this.cache[this._makeAbs(f)] = false;
  6111. break
  6112. default: // some unusual error. Treat as failure.
  6113. this.cache[this._makeAbs(f)] = false;
  6114. if (this.strict)
  6115. throw er
  6116. if (!this.silent)
  6117. console.error('glob error', er);
  6118. break
  6119. }
  6120. };
  6121. GlobSync$1.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) {
  6122. var entries = this._readdir(abs, inGlobStar);
  6123. // no entries means not a dir, so it can never have matches
  6124. // foo.txt/** doesn't match foo.txt
  6125. if (!entries)
  6126. return
  6127. // test without the globstar, and with every child both below
  6128. // and replacing the globstar.
  6129. var remainWithoutGlobStar = remain.slice(1);
  6130. var gspref = prefix ? [ prefix ] : [];
  6131. var noGlobStar = gspref.concat(remainWithoutGlobStar);
  6132. // the noGlobStar pattern exits the inGlobStar state
  6133. this._process(noGlobStar, index, false);
  6134. var len = entries.length;
  6135. var isSym = this.symlinks[abs];
  6136. // If it's a symlink, and we're in a globstar, then stop
  6137. if (isSym && inGlobStar)
  6138. return
  6139. for (var i = 0; i < len; i++) {
  6140. var e = entries[i];
  6141. if (e.charAt(0) === '.' && !this.dot)
  6142. continue
  6143. // these two cases enter the inGlobStar state
  6144. var instead = gspref.concat(entries[i], remainWithoutGlobStar);
  6145. this._process(instead, index, true);
  6146. var below = gspref.concat(entries[i], remain);
  6147. this._process(below, index, true);
  6148. }
  6149. };
  6150. GlobSync$1.prototype._processSimple = function (prefix, index) {
  6151. // XXX review this. Shouldn't it be doing the mounting etc
  6152. // before doing stat? kinda weird?
  6153. var exists = this._stat(prefix);
  6154. if (!this.matches[index])
  6155. this.matches[index] = Object.create(null);
  6156. // If it doesn't exist, then just mark the lack of results
  6157. if (!exists)
  6158. return
  6159. if (prefix && isAbsolute$1(prefix) && !this.nomount) {
  6160. var trail = /[\/\\]$/.test(prefix);
  6161. if (prefix.charAt(0) === '/') {
  6162. prefix = path$i.join(this.root, prefix);
  6163. } else {
  6164. prefix = path$i.resolve(this.root, prefix);
  6165. if (trail)
  6166. prefix += '/';
  6167. }
  6168. }
  6169. if (process.platform === 'win32')
  6170. prefix = prefix.replace(/\\/g, '/');
  6171. // Mark this as a match
  6172. this._emitMatch(index, prefix);
  6173. };
  6174. // Returns either 'DIR', 'FILE', or false
  6175. GlobSync$1.prototype._stat = function (f) {
  6176. var abs = this._makeAbs(f);
  6177. var needDir = f.slice(-1) === '/';
  6178. if (f.length > this.maxLength)
  6179. return false
  6180. if (!this.stat && ownProp$1(this.cache, abs)) {
  6181. var c = this.cache[abs];
  6182. if (Array.isArray(c))
  6183. c = 'DIR';
  6184. // It exists, but maybe not how we need it
  6185. if (!needDir || c === 'DIR')
  6186. return c
  6187. if (needDir && c === 'FILE')
  6188. return false
  6189. // otherwise we have to stat, because maybe c=true
  6190. // if we know it exists, but not what it is.
  6191. }
  6192. var stat = this.statCache[abs];
  6193. if (!stat) {
  6194. var lstat;
  6195. try {
  6196. lstat = this.fs.lstatSync(abs);
  6197. } catch (er) {
  6198. if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
  6199. this.statCache[abs] = false;
  6200. return false
  6201. }
  6202. }
  6203. if (lstat && lstat.isSymbolicLink()) {
  6204. try {
  6205. stat = this.fs.statSync(abs);
  6206. } catch (er) {
  6207. stat = lstat;
  6208. }
  6209. } else {
  6210. stat = lstat;
  6211. }
  6212. }
  6213. this.statCache[abs] = stat;
  6214. var c = true;
  6215. if (stat)
  6216. c = stat.isDirectory() ? 'DIR' : 'FILE';
  6217. this.cache[abs] = this.cache[abs] || c;
  6218. if (needDir && c === 'FILE')
  6219. return false
  6220. return c
  6221. };
  6222. GlobSync$1.prototype._mark = function (p) {
  6223. return common$d.mark(this, p)
  6224. };
  6225. GlobSync$1.prototype._makeAbs = function (f) {
  6226. return common$d.makeAbs(this, f)
  6227. };
  6228. // Returns a wrapper function that returns a wrapped callback
  6229. // The wrapper function should do some stuff, and return a
  6230. // presumably different callback function.
  6231. // This makes sure that own properties are retained, so that
  6232. // decorations and such are not lost along the way.
  6233. var wrappy_1 = wrappy$2;
  6234. function wrappy$2 (fn, cb) {
  6235. if (fn && cb) return wrappy$2(fn)(cb)
  6236. if (typeof fn !== 'function')
  6237. throw new TypeError('need wrapper function')
  6238. Object.keys(fn).forEach(function (k) {
  6239. wrapper[k] = fn[k];
  6240. });
  6241. return wrapper
  6242. function wrapper() {
  6243. var args = new Array(arguments.length);
  6244. for (var i = 0; i < args.length; i++) {
  6245. args[i] = arguments[i];
  6246. }
  6247. var ret = fn.apply(this, args);
  6248. var cb = args[args.length-1];
  6249. if (typeof ret === 'function' && ret !== cb) {
  6250. Object.keys(cb).forEach(function (k) {
  6251. ret[k] = cb[k];
  6252. });
  6253. }
  6254. return ret
  6255. }
  6256. }
  6257. var once$3 = {exports: {}};
  6258. var wrappy$1 = wrappy_1;
  6259. once$3.exports = wrappy$1(once$2);
  6260. once$3.exports.strict = wrappy$1(onceStrict);
  6261. once$2.proto = once$2(function () {
  6262. Object.defineProperty(Function.prototype, 'once', {
  6263. value: function () {
  6264. return once$2(this)
  6265. },
  6266. configurable: true
  6267. });
  6268. Object.defineProperty(Function.prototype, 'onceStrict', {
  6269. value: function () {
  6270. return onceStrict(this)
  6271. },
  6272. configurable: true
  6273. });
  6274. });
  6275. function once$2 (fn) {
  6276. var f = function () {
  6277. if (f.called) return f.value
  6278. f.called = true;
  6279. return f.value = fn.apply(this, arguments)
  6280. };
  6281. f.called = false;
  6282. return f
  6283. }
  6284. function onceStrict (fn) {
  6285. var f = function () {
  6286. if (f.called)
  6287. throw new Error(f.onceError)
  6288. f.called = true;
  6289. return f.value = fn.apply(this, arguments)
  6290. };
  6291. var name = fn.name || 'Function wrapped with `once`';
  6292. f.onceError = name + " shouldn't be called more than once";
  6293. f.called = false;
  6294. return f
  6295. }
  6296. var wrappy = wrappy_1;
  6297. var reqs = Object.create(null);
  6298. var once$1 = once$3.exports;
  6299. var inflight_1 = wrappy(inflight$1);
  6300. function inflight$1 (key, cb) {
  6301. if (reqs[key]) {
  6302. reqs[key].push(cb);
  6303. return null
  6304. } else {
  6305. reqs[key] = [cb];
  6306. return makeres(key)
  6307. }
  6308. }
  6309. function makeres (key) {
  6310. return once$1(function RES () {
  6311. var cbs = reqs[key];
  6312. var len = cbs.length;
  6313. var args = slice$1(arguments);
  6314. // XXX It's somewhat ambiguous whether a new callback added in this
  6315. // pass should be queued for later execution if something in the
  6316. // list of callbacks throws, or if it should just be discarded.
  6317. // However, it's such an edge case that it hardly matters, and either
  6318. // choice is likely as surprising as the other.
  6319. // As it happens, we do go ahead and schedule it for later execution.
  6320. try {
  6321. for (var i = 0; i < len; i++) {
  6322. cbs[i].apply(null, args);
  6323. }
  6324. } finally {
  6325. if (cbs.length > len) {
  6326. // added more in the interim.
  6327. // de-zalgo, just in case, but don't call again.
  6328. cbs.splice(0, len);
  6329. process.nextTick(function () {
  6330. RES.apply(null, args);
  6331. });
  6332. } else {
  6333. delete reqs[key];
  6334. }
  6335. }
  6336. })
  6337. }
  6338. function slice$1 (args) {
  6339. var length = args.length;
  6340. var array = [];
  6341. for (var i = 0; i < length; i++) array[i] = args[i];
  6342. return array
  6343. }
  6344. // Approach:
  6345. //
  6346. // 1. Get the minimatch set
  6347. // 2. For each pattern in the set, PROCESS(pattern, false)
  6348. // 3. Store matches per-set, then uniq them
  6349. //
  6350. // PROCESS(pattern, inGlobStar)
  6351. // Get the first [n] items from pattern that are all strings
  6352. // Join these together. This is PREFIX.
  6353. // If there is no more remaining, then stat(PREFIX) and
  6354. // add to matches if it succeeds. END.
  6355. //
  6356. // If inGlobStar and PREFIX is symlink and points to dir
  6357. // set ENTRIES = []
  6358. // else readdir(PREFIX) as ENTRIES
  6359. // If fail, END
  6360. //
  6361. // with ENTRIES
  6362. // If pattern[n] is GLOBSTAR
  6363. // // handle the case where the globstar match is empty
  6364. // // by pruning it out, and testing the resulting pattern
  6365. // PROCESS(pattern[0..n] + pattern[n+1 .. $], false)
  6366. // // handle other cases.
  6367. // for ENTRY in ENTRIES (not dotfiles)
  6368. // // attach globstar + tail onto the entry
  6369. // // Mark that this entry is a globstar match
  6370. // PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true)
  6371. //
  6372. // else // not globstar
  6373. // for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot)
  6374. // Test ENTRY against pattern[n]
  6375. // If fails, continue
  6376. // If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $])
  6377. //
  6378. // Caveat:
  6379. // Cache all stats and readdirs results to minimize syscall. Since all
  6380. // we ever care about is existence and directory-ness, we can just keep
  6381. // `true` for files, and [children,...] for directories, or `false` for
  6382. // things that don't exist.
  6383. var glob_1 = glob;
  6384. var rp = fs_realpath;
  6385. var minimatch = minimatch_1;
  6386. var inherits = inherits$1.exports;
  6387. var EE = require$$0__default$1.EventEmitter;
  6388. var path$h = path__default;
  6389. var assert$1 = require$$5__default;
  6390. var isAbsolute = pathIsAbsolute.exports;
  6391. var globSync = sync$b;
  6392. var common$c = common$e;
  6393. var setopts = common$c.setopts;
  6394. var ownProp = common$c.ownProp;
  6395. var inflight = inflight_1;
  6396. var childrenIgnored = common$c.childrenIgnored;
  6397. var isIgnored = common$c.isIgnored;
  6398. var once = once$3.exports;
  6399. function glob (pattern, options, cb) {
  6400. if (typeof options === 'function') cb = options, options = {};
  6401. if (!options) options = {};
  6402. if (options.sync) {
  6403. if (cb)
  6404. throw new TypeError('callback provided to sync glob')
  6405. return globSync(pattern, options)
  6406. }
  6407. return new Glob(pattern, options, cb)
  6408. }
  6409. glob.sync = globSync;
  6410. var GlobSync = glob.GlobSync = globSync.GlobSync;
  6411. // old api surface
  6412. glob.glob = glob;
  6413. function extend (origin, add) {
  6414. if (add === null || typeof add !== 'object') {
  6415. return origin
  6416. }
  6417. var keys = Object.keys(add);
  6418. var i = keys.length;
  6419. while (i--) {
  6420. origin[keys[i]] = add[keys[i]];
  6421. }
  6422. return origin
  6423. }
  6424. glob.hasMagic = function (pattern, options_) {
  6425. var options = extend({}, options_);
  6426. options.noprocess = true;
  6427. var g = new Glob(pattern, options);
  6428. var set = g.minimatch.set;
  6429. if (!pattern)
  6430. return false
  6431. if (set.length > 1)
  6432. return true
  6433. for (var j = 0; j < set[0].length; j++) {
  6434. if (typeof set[0][j] !== 'string')
  6435. return true
  6436. }
  6437. return false
  6438. };
  6439. glob.Glob = Glob;
  6440. inherits(Glob, EE);
  6441. function Glob (pattern, options, cb) {
  6442. if (typeof options === 'function') {
  6443. cb = options;
  6444. options = null;
  6445. }
  6446. if (options && options.sync) {
  6447. if (cb)
  6448. throw new TypeError('callback provided to sync glob')
  6449. return new GlobSync(pattern, options)
  6450. }
  6451. if (!(this instanceof Glob))
  6452. return new Glob(pattern, options, cb)
  6453. setopts(this, pattern, options);
  6454. this._didRealPath = false;
  6455. // process each pattern in the minimatch set
  6456. var n = this.minimatch.set.length;
  6457. // The matches are stored as {<filename>: true,...} so that
  6458. // duplicates are automagically pruned.
  6459. // Later, we do an Object.keys() on these.
  6460. // Keep them as a list so we can fill in when nonull is set.
  6461. this.matches = new Array(n);
  6462. if (typeof cb === 'function') {
  6463. cb = once(cb);
  6464. this.on('error', cb);
  6465. this.on('end', function (matches) {
  6466. cb(null, matches);
  6467. });
  6468. }
  6469. var self = this;
  6470. this._processing = 0;
  6471. this._emitQueue = [];
  6472. this._processQueue = [];
  6473. this.paused = false;
  6474. if (this.noprocess)
  6475. return this
  6476. if (n === 0)
  6477. return done()
  6478. var sync = true;
  6479. for (var i = 0; i < n; i ++) {
  6480. this._process(this.minimatch.set[i], i, false, done);
  6481. }
  6482. sync = false;
  6483. function done () {
  6484. --self._processing;
  6485. if (self._processing <= 0) {
  6486. if (sync) {
  6487. process.nextTick(function () {
  6488. self._finish();
  6489. });
  6490. } else {
  6491. self._finish();
  6492. }
  6493. }
  6494. }
  6495. }
  6496. Glob.prototype._finish = function () {
  6497. assert$1(this instanceof Glob);
  6498. if (this.aborted)
  6499. return
  6500. if (this.realpath && !this._didRealpath)
  6501. return this._realpath()
  6502. common$c.finish(this);
  6503. this.emit('end', this.found);
  6504. };
  6505. Glob.prototype._realpath = function () {
  6506. if (this._didRealpath)
  6507. return
  6508. this._didRealpath = true;
  6509. var n = this.matches.length;
  6510. if (n === 0)
  6511. return this._finish()
  6512. var self = this;
  6513. for (var i = 0; i < this.matches.length; i++)
  6514. this._realpathSet(i, next);
  6515. function next () {
  6516. if (--n === 0)
  6517. self._finish();
  6518. }
  6519. };
  6520. Glob.prototype._realpathSet = function (index, cb) {
  6521. var matchset = this.matches[index];
  6522. if (!matchset)
  6523. return cb()
  6524. var found = Object.keys(matchset);
  6525. var self = this;
  6526. var n = found.length;
  6527. if (n === 0)
  6528. return cb()
  6529. var set = this.matches[index] = Object.create(null);
  6530. found.forEach(function (p, i) {
  6531. // If there's a problem with the stat, then it means that
  6532. // one or more of the links in the realpath couldn't be
  6533. // resolved. just return the abs value in that case.
  6534. p = self._makeAbs(p);
  6535. rp.realpath(p, self.realpathCache, function (er, real) {
  6536. if (!er)
  6537. set[real] = true;
  6538. else if (er.syscall === 'stat')
  6539. set[p] = true;
  6540. else
  6541. self.emit('error', er); // srsly wtf right here
  6542. if (--n === 0) {
  6543. self.matches[index] = set;
  6544. cb();
  6545. }
  6546. });
  6547. });
  6548. };
  6549. Glob.prototype._mark = function (p) {
  6550. return common$c.mark(this, p)
  6551. };
  6552. Glob.prototype._makeAbs = function (f) {
  6553. return common$c.makeAbs(this, f)
  6554. };
  6555. Glob.prototype.abort = function () {
  6556. this.aborted = true;
  6557. this.emit('abort');
  6558. };
  6559. Glob.prototype.pause = function () {
  6560. if (!this.paused) {
  6561. this.paused = true;
  6562. this.emit('pause');
  6563. }
  6564. };
  6565. Glob.prototype.resume = function () {
  6566. if (this.paused) {
  6567. this.emit('resume');
  6568. this.paused = false;
  6569. if (this._emitQueue.length) {
  6570. var eq = this._emitQueue.slice(0);
  6571. this._emitQueue.length = 0;
  6572. for (var i = 0; i < eq.length; i ++) {
  6573. var e = eq[i];
  6574. this._emitMatch(e[0], e[1]);
  6575. }
  6576. }
  6577. if (this._processQueue.length) {
  6578. var pq = this._processQueue.slice(0);
  6579. this._processQueue.length = 0;
  6580. for (var i = 0; i < pq.length; i ++) {
  6581. var p = pq[i];
  6582. this._processing--;
  6583. this._process(p[0], p[1], p[2], p[3]);
  6584. }
  6585. }
  6586. }
  6587. };
  6588. Glob.prototype._process = function (pattern, index, inGlobStar, cb) {
  6589. assert$1(this instanceof Glob);
  6590. assert$1(typeof cb === 'function');
  6591. if (this.aborted)
  6592. return
  6593. this._processing++;
  6594. if (this.paused) {
  6595. this._processQueue.push([pattern, index, inGlobStar, cb]);
  6596. return
  6597. }
  6598. //console.error('PROCESS %d', this._processing, pattern)
  6599. // Get the first [n] parts of pattern that are all strings.
  6600. var n = 0;
  6601. while (typeof pattern[n] === 'string') {
  6602. n ++;
  6603. }
  6604. // now n is the index of the first one that is *not* a string.
  6605. // see if there's anything else
  6606. var prefix;
  6607. switch (n) {
  6608. // if not, then this is rather simple
  6609. case pattern.length:
  6610. this._processSimple(pattern.join('/'), index, cb);
  6611. return
  6612. case 0:
  6613. // pattern *starts* with some non-trivial item.
  6614. // going to readdir(cwd), but not include the prefix in matches.
  6615. prefix = null;
  6616. break
  6617. default:
  6618. // pattern has some string bits in the front.
  6619. // whatever it starts with, whether that's 'absolute' like /foo/bar,
  6620. // or 'relative' like '../baz'
  6621. prefix = pattern.slice(0, n).join('/');
  6622. break
  6623. }
  6624. var remain = pattern.slice(n);
  6625. // get the list of entries.
  6626. var read;
  6627. if (prefix === null)
  6628. read = '.';
  6629. else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) {
  6630. if (!prefix || !isAbsolute(prefix))
  6631. prefix = '/' + prefix;
  6632. read = prefix;
  6633. } else
  6634. read = prefix;
  6635. var abs = this._makeAbs(read);
  6636. //if ignored, skip _processing
  6637. if (childrenIgnored(this, read))
  6638. return cb()
  6639. var isGlobStar = remain[0] === minimatch.GLOBSTAR;
  6640. if (isGlobStar)
  6641. this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb);
  6642. else
  6643. this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb);
  6644. };
  6645. Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) {
  6646. var self = this;
  6647. this._readdir(abs, inGlobStar, function (er, entries) {
  6648. return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb)
  6649. });
  6650. };
  6651. Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
  6652. // if the abs isn't a dir, then nothing can match!
  6653. if (!entries)
  6654. return cb()
  6655. // It will only match dot entries if it starts with a dot, or if
  6656. // dot is set. Stuff like @(.foo|.bar) isn't allowed.
  6657. var pn = remain[0];
  6658. var negate = !!this.minimatch.negate;
  6659. var rawGlob = pn._glob;
  6660. var dotOk = this.dot || rawGlob.charAt(0) === '.';
  6661. var matchedEntries = [];
  6662. for (var i = 0; i < entries.length; i++) {
  6663. var e = entries[i];
  6664. if (e.charAt(0) !== '.' || dotOk) {
  6665. var m;
  6666. if (negate && !prefix) {
  6667. m = !e.match(pn);
  6668. } else {
  6669. m = e.match(pn);
  6670. }
  6671. if (m)
  6672. matchedEntries.push(e);
  6673. }
  6674. }
  6675. //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries)
  6676. var len = matchedEntries.length;
  6677. // If there are no matched entries, then nothing matches.
  6678. if (len === 0)
  6679. return cb()
  6680. // if this is the last remaining pattern bit, then no need for
  6681. // an additional stat *unless* the user has specified mark or
  6682. // stat explicitly. We know they exist, since readdir returned
  6683. // them.
  6684. if (remain.length === 1 && !this.mark && !this.stat) {
  6685. if (!this.matches[index])
  6686. this.matches[index] = Object.create(null);
  6687. for (var i = 0; i < len; i ++) {
  6688. var e = matchedEntries[i];
  6689. if (prefix) {
  6690. if (prefix !== '/')
  6691. e = prefix + '/' + e;
  6692. else
  6693. e = prefix + e;
  6694. }
  6695. if (e.charAt(0) === '/' && !this.nomount) {
  6696. e = path$h.join(this.root, e);
  6697. }
  6698. this._emitMatch(index, e);
  6699. }
  6700. // This was the last one, and no stats were needed
  6701. return cb()
  6702. }
  6703. // now test all matched entries as stand-ins for that part
  6704. // of the pattern.
  6705. remain.shift();
  6706. for (var i = 0; i < len; i ++) {
  6707. var e = matchedEntries[i];
  6708. if (prefix) {
  6709. if (prefix !== '/')
  6710. e = prefix + '/' + e;
  6711. else
  6712. e = prefix + e;
  6713. }
  6714. this._process([e].concat(remain), index, inGlobStar, cb);
  6715. }
  6716. cb();
  6717. };
  6718. Glob.prototype._emitMatch = function (index, e) {
  6719. if (this.aborted)
  6720. return
  6721. if (isIgnored(this, e))
  6722. return
  6723. if (this.paused) {
  6724. this._emitQueue.push([index, e]);
  6725. return
  6726. }
  6727. var abs = isAbsolute(e) ? e : this._makeAbs(e);
  6728. if (this.mark)
  6729. e = this._mark(e);
  6730. if (this.absolute)
  6731. e = abs;
  6732. if (this.matches[index][e])
  6733. return
  6734. if (this.nodir) {
  6735. var c = this.cache[abs];
  6736. if (c === 'DIR' || Array.isArray(c))
  6737. return
  6738. }
  6739. this.matches[index][e] = true;
  6740. var st = this.statCache[abs];
  6741. if (st)
  6742. this.emit('stat', e, st);
  6743. this.emit('match', e);
  6744. };
  6745. Glob.prototype._readdirInGlobStar = function (abs, cb) {
  6746. if (this.aborted)
  6747. return
  6748. // follow all symlinked directories forever
  6749. // just proceed as if this is a non-globstar situation
  6750. if (this.follow)
  6751. return this._readdir(abs, false, cb)
  6752. var lstatkey = 'lstat\0' + abs;
  6753. var self = this;
  6754. var lstatcb = inflight(lstatkey, lstatcb_);
  6755. if (lstatcb)
  6756. self.fs.lstat(abs, lstatcb);
  6757. function lstatcb_ (er, lstat) {
  6758. if (er && er.code === 'ENOENT')
  6759. return cb()
  6760. var isSym = lstat && lstat.isSymbolicLink();
  6761. self.symlinks[abs] = isSym;
  6762. // If it's not a symlink or a dir, then it's definitely a regular file.
  6763. // don't bother doing a readdir in that case.
  6764. if (!isSym && lstat && !lstat.isDirectory()) {
  6765. self.cache[abs] = 'FILE';
  6766. cb();
  6767. } else
  6768. self._readdir(abs, false, cb);
  6769. }
  6770. };
  6771. Glob.prototype._readdir = function (abs, inGlobStar, cb) {
  6772. if (this.aborted)
  6773. return
  6774. cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb);
  6775. if (!cb)
  6776. return
  6777. //console.error('RD %j %j', +inGlobStar, abs)
  6778. if (inGlobStar && !ownProp(this.symlinks, abs))
  6779. return this._readdirInGlobStar(abs, cb)
  6780. if (ownProp(this.cache, abs)) {
  6781. var c = this.cache[abs];
  6782. if (!c || c === 'FILE')
  6783. return cb()
  6784. if (Array.isArray(c))
  6785. return cb(null, c)
  6786. }
  6787. var self = this;
  6788. self.fs.readdir(abs, readdirCb(this, abs, cb));
  6789. };
  6790. function readdirCb (self, abs, cb) {
  6791. return function (er, entries) {
  6792. if (er)
  6793. self._readdirError(abs, er, cb);
  6794. else
  6795. self._readdirEntries(abs, entries, cb);
  6796. }
  6797. }
  6798. Glob.prototype._readdirEntries = function (abs, entries, cb) {
  6799. if (this.aborted)
  6800. return
  6801. // if we haven't asked to stat everything, then just
  6802. // assume that everything in there exists, so we can avoid
  6803. // having to stat it a second time.
  6804. if (!this.mark && !this.stat) {
  6805. for (var i = 0; i < entries.length; i ++) {
  6806. var e = entries[i];
  6807. if (abs === '/')
  6808. e = abs + e;
  6809. else
  6810. e = abs + '/' + e;
  6811. this.cache[e] = true;
  6812. }
  6813. }
  6814. this.cache[abs] = entries;
  6815. return cb(null, entries)
  6816. };
  6817. Glob.prototype._readdirError = function (f, er, cb) {
  6818. if (this.aborted)
  6819. return
  6820. // handle errors, and cache the information
  6821. switch (er.code) {
  6822. case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
  6823. case 'ENOTDIR': // totally normal. means it *does* exist.
  6824. var abs = this._makeAbs(f);
  6825. this.cache[abs] = 'FILE';
  6826. if (abs === this.cwdAbs) {
  6827. var error = new Error(er.code + ' invalid cwd ' + this.cwd);
  6828. error.path = this.cwd;
  6829. error.code = er.code;
  6830. this.emit('error', error);
  6831. this.abort();
  6832. }
  6833. break
  6834. case 'ENOENT': // not terribly unusual
  6835. case 'ELOOP':
  6836. case 'ENAMETOOLONG':
  6837. case 'UNKNOWN':
  6838. this.cache[this._makeAbs(f)] = false;
  6839. break
  6840. default: // some unusual error. Treat as failure.
  6841. this.cache[this._makeAbs(f)] = false;
  6842. if (this.strict) {
  6843. this.emit('error', er);
  6844. // If the error is handled, then we abort
  6845. // if not, we threw out of here
  6846. this.abort();
  6847. }
  6848. if (!this.silent)
  6849. console.error('glob error', er);
  6850. break
  6851. }
  6852. return cb()
  6853. };
  6854. Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) {
  6855. var self = this;
  6856. this._readdir(abs, inGlobStar, function (er, entries) {
  6857. self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb);
  6858. });
  6859. };
  6860. Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
  6861. //console.error('pgs2', prefix, remain[0], entries)
  6862. // no entries means not a dir, so it can never have matches
  6863. // foo.txt/** doesn't match foo.txt
  6864. if (!entries)
  6865. return cb()
  6866. // test without the globstar, and with every child both below
  6867. // and replacing the globstar.
  6868. var remainWithoutGlobStar = remain.slice(1);
  6869. var gspref = prefix ? [ prefix ] : [];
  6870. var noGlobStar = gspref.concat(remainWithoutGlobStar);
  6871. // the noGlobStar pattern exits the inGlobStar state
  6872. this._process(noGlobStar, index, false, cb);
  6873. var isSym = this.symlinks[abs];
  6874. var len = entries.length;
  6875. // If it's a symlink, and we're in a globstar, then stop
  6876. if (isSym && inGlobStar)
  6877. return cb()
  6878. for (var i = 0; i < len; i++) {
  6879. var e = entries[i];
  6880. if (e.charAt(0) === '.' && !this.dot)
  6881. continue
  6882. // these two cases enter the inGlobStar state
  6883. var instead = gspref.concat(entries[i], remainWithoutGlobStar);
  6884. this._process(instead, index, true, cb);
  6885. var below = gspref.concat(entries[i], remain);
  6886. this._process(below, index, true, cb);
  6887. }
  6888. cb();
  6889. };
  6890. Glob.prototype._processSimple = function (prefix, index, cb) {
  6891. // XXX review this. Shouldn't it be doing the mounting etc
  6892. // before doing stat? kinda weird?
  6893. var self = this;
  6894. this._stat(prefix, function (er, exists) {
  6895. self._processSimple2(prefix, index, er, exists, cb);
  6896. });
  6897. };
  6898. Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) {
  6899. //console.error('ps2', prefix, exists)
  6900. if (!this.matches[index])
  6901. this.matches[index] = Object.create(null);
  6902. // If it doesn't exist, then just mark the lack of results
  6903. if (!exists)
  6904. return cb()
  6905. if (prefix && isAbsolute(prefix) && !this.nomount) {
  6906. var trail = /[\/\\]$/.test(prefix);
  6907. if (prefix.charAt(0) === '/') {
  6908. prefix = path$h.join(this.root, prefix);
  6909. } else {
  6910. prefix = path$h.resolve(this.root, prefix);
  6911. if (trail)
  6912. prefix += '/';
  6913. }
  6914. }
  6915. if (process.platform === 'win32')
  6916. prefix = prefix.replace(/\\/g, '/');
  6917. // Mark this as a match
  6918. this._emitMatch(index, prefix);
  6919. cb();
  6920. };
  6921. // Returns either 'DIR', 'FILE', or false
  6922. Glob.prototype._stat = function (f, cb) {
  6923. var abs = this._makeAbs(f);
  6924. var needDir = f.slice(-1) === '/';
  6925. if (f.length > this.maxLength)
  6926. return cb()
  6927. if (!this.stat && ownProp(this.cache, abs)) {
  6928. var c = this.cache[abs];
  6929. if (Array.isArray(c))
  6930. c = 'DIR';
  6931. // It exists, but maybe not how we need it
  6932. if (!needDir || c === 'DIR')
  6933. return cb(null, c)
  6934. if (needDir && c === 'FILE')
  6935. return cb()
  6936. // otherwise we have to stat, because maybe c=true
  6937. // if we know it exists, but not what it is.
  6938. }
  6939. var stat = this.statCache[abs];
  6940. if (stat !== undefined) {
  6941. if (stat === false)
  6942. return cb(null, stat)
  6943. else {
  6944. var type = stat.isDirectory() ? 'DIR' : 'FILE';
  6945. if (needDir && type === 'FILE')
  6946. return cb()
  6947. else
  6948. return cb(null, type, stat)
  6949. }
  6950. }
  6951. var self = this;
  6952. var statcb = inflight('stat\0' + abs, lstatcb_);
  6953. if (statcb)
  6954. self.fs.lstat(abs, statcb);
  6955. function lstatcb_ (er, lstat) {
  6956. if (lstat && lstat.isSymbolicLink()) {
  6957. // If it's a symlink, then treat it as the target, unless
  6958. // the target does not exist, then treat it as a file.
  6959. return self.fs.stat(abs, function (er, stat) {
  6960. if (er)
  6961. self._stat2(f, abs, null, lstat, cb);
  6962. else
  6963. self._stat2(f, abs, er, stat, cb);
  6964. })
  6965. } else {
  6966. self._stat2(f, abs, er, lstat, cb);
  6967. }
  6968. }
  6969. };
  6970. Glob.prototype._stat2 = function (f, abs, er, stat, cb) {
  6971. if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
  6972. this.statCache[abs] = false;
  6973. return cb()
  6974. }
  6975. var needDir = f.slice(-1) === '/';
  6976. this.statCache[abs] = stat;
  6977. if (abs.slice(-1) === '/' && stat && !stat.isDirectory())
  6978. return cb(null, false, stat)
  6979. var c = true;
  6980. if (stat)
  6981. c = stat.isDirectory() ? 'DIR' : 'FILE';
  6982. this.cache[abs] = this.cache[abs] || c;
  6983. if (needDir && c === 'FILE')
  6984. return cb()
  6985. return cb(null, c, stat)
  6986. };
  6987. // @ts-check
  6988. /** @typedef { import('estree').BaseNode} BaseNode */
  6989. /** @typedef {{
  6990. skip: () => void;
  6991. remove: () => void;
  6992. replace: (node: BaseNode) => void;
  6993. }} WalkerContext */
  6994. class WalkerBase {
  6995. constructor() {
  6996. /** @type {boolean} */
  6997. this.should_skip = false;
  6998. /** @type {boolean} */
  6999. this.should_remove = false;
  7000. /** @type {BaseNode | null} */
  7001. this.replacement = null;
  7002. /** @type {WalkerContext} */
  7003. this.context = {
  7004. skip: () => (this.should_skip = true),
  7005. remove: () => (this.should_remove = true),
  7006. replace: (node) => (this.replacement = node)
  7007. };
  7008. }
  7009. /**
  7010. *
  7011. * @param {any} parent
  7012. * @param {string} prop
  7013. * @param {number} index
  7014. * @param {BaseNode} node
  7015. */
  7016. replace(parent, prop, index, node) {
  7017. if (parent) {
  7018. if (index !== null) {
  7019. parent[prop][index] = node;
  7020. } else {
  7021. parent[prop] = node;
  7022. }
  7023. }
  7024. }
  7025. /**
  7026. *
  7027. * @param {any} parent
  7028. * @param {string} prop
  7029. * @param {number} index
  7030. */
  7031. remove(parent, prop, index) {
  7032. if (parent) {
  7033. if (index !== null) {
  7034. parent[prop].splice(index, 1);
  7035. } else {
  7036. delete parent[prop];
  7037. }
  7038. }
  7039. }
  7040. }
  7041. // @ts-check
  7042. /** @typedef { import('estree').BaseNode} BaseNode */
  7043. /** @typedef { import('./walker.js').WalkerContext} WalkerContext */
  7044. /** @typedef {(
  7045. * this: WalkerContext,
  7046. * node: BaseNode,
  7047. * parent: BaseNode,
  7048. * key: string,
  7049. * index: number
  7050. * ) => void} SyncHandler */
  7051. class SyncWalker extends WalkerBase {
  7052. /**
  7053. *
  7054. * @param {SyncHandler} enter
  7055. * @param {SyncHandler} leave
  7056. */
  7057. constructor(enter, leave) {
  7058. super();
  7059. /** @type {SyncHandler} */
  7060. this.enter = enter;
  7061. /** @type {SyncHandler} */
  7062. this.leave = leave;
  7063. }
  7064. /**
  7065. *
  7066. * @param {BaseNode} node
  7067. * @param {BaseNode} parent
  7068. * @param {string} [prop]
  7069. * @param {number} [index]
  7070. * @returns {BaseNode}
  7071. */
  7072. visit(node, parent, prop, index) {
  7073. if (node) {
  7074. if (this.enter) {
  7075. const _should_skip = this.should_skip;
  7076. const _should_remove = this.should_remove;
  7077. const _replacement = this.replacement;
  7078. this.should_skip = false;
  7079. this.should_remove = false;
  7080. this.replacement = null;
  7081. this.enter.call(this.context, node, parent, prop, index);
  7082. if (this.replacement) {
  7083. node = this.replacement;
  7084. this.replace(parent, prop, index, node);
  7085. }
  7086. if (this.should_remove) {
  7087. this.remove(parent, prop, index);
  7088. }
  7089. const skipped = this.should_skip;
  7090. const removed = this.should_remove;
  7091. this.should_skip = _should_skip;
  7092. this.should_remove = _should_remove;
  7093. this.replacement = _replacement;
  7094. if (skipped) return node;
  7095. if (removed) return null;
  7096. }
  7097. for (const key in node) {
  7098. const value = node[key];
  7099. if (typeof value !== "object") {
  7100. continue;
  7101. } else if (Array.isArray(value)) {
  7102. for (let i = 0; i < value.length; i += 1) {
  7103. if (value[i] !== null && typeof value[i].type === 'string') {
  7104. if (!this.visit(value[i], node, key, i)) {
  7105. // removed
  7106. i--;
  7107. }
  7108. }
  7109. }
  7110. } else if (value !== null && typeof value.type === "string") {
  7111. this.visit(value, node, key, null);
  7112. }
  7113. }
  7114. if (this.leave) {
  7115. const _replacement = this.replacement;
  7116. const _should_remove = this.should_remove;
  7117. this.replacement = null;
  7118. this.should_remove = false;
  7119. this.leave.call(this.context, node, parent, prop, index);
  7120. if (this.replacement) {
  7121. node = this.replacement;
  7122. this.replace(parent, prop, index, node);
  7123. }
  7124. if (this.should_remove) {
  7125. this.remove(parent, prop, index);
  7126. }
  7127. const removed = this.should_remove;
  7128. this.replacement = _replacement;
  7129. this.should_remove = _should_remove;
  7130. if (removed) return null;
  7131. }
  7132. }
  7133. return node;
  7134. }
  7135. }
  7136. // @ts-check
  7137. /** @typedef { import('estree').BaseNode} BaseNode */
  7138. /** @typedef { import('./sync.js').SyncHandler} SyncHandler */
  7139. /** @typedef { import('./async.js').AsyncHandler} AsyncHandler */
  7140. /**
  7141. *
  7142. * @param {BaseNode} ast
  7143. * @param {{
  7144. * enter?: SyncHandler
  7145. * leave?: SyncHandler
  7146. * }} walker
  7147. * @returns {BaseNode}
  7148. */
  7149. function walk$2(ast, { enter, leave }) {
  7150. const instance = new SyncWalker(enter, leave);
  7151. return instance.visit(ast, null);
  7152. }
  7153. var charToInteger$1 = {};
  7154. var chars$2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  7155. for (var i$2 = 0; i$2 < chars$2.length; i$2++) {
  7156. charToInteger$1[chars$2.charCodeAt(i$2)] = i$2;
  7157. }
  7158. function encode$1(decoded) {
  7159. var sourceFileIndex = 0; // second field
  7160. var sourceCodeLine = 0; // third field
  7161. var sourceCodeColumn = 0; // fourth field
  7162. var nameIndex = 0; // fifth field
  7163. var mappings = '';
  7164. for (var i = 0; i < decoded.length; i++) {
  7165. var line = decoded[i];
  7166. if (i > 0)
  7167. mappings += ';';
  7168. if (line.length === 0)
  7169. continue;
  7170. var generatedCodeColumn = 0; // first field
  7171. var lineMappings = [];
  7172. for (var _i = 0, line_1 = line; _i < line_1.length; _i++) {
  7173. var segment = line_1[_i];
  7174. var segmentMappings = encodeInteger$1(segment[0] - generatedCodeColumn);
  7175. generatedCodeColumn = segment[0];
  7176. if (segment.length > 1) {
  7177. segmentMappings +=
  7178. encodeInteger$1(segment[1] - sourceFileIndex) +
  7179. encodeInteger$1(segment[2] - sourceCodeLine) +
  7180. encodeInteger$1(segment[3] - sourceCodeColumn);
  7181. sourceFileIndex = segment[1];
  7182. sourceCodeLine = segment[2];
  7183. sourceCodeColumn = segment[3];
  7184. }
  7185. if (segment.length === 5) {
  7186. segmentMappings += encodeInteger$1(segment[4] - nameIndex);
  7187. nameIndex = segment[4];
  7188. }
  7189. lineMappings.push(segmentMappings);
  7190. }
  7191. mappings += lineMappings.join(',');
  7192. }
  7193. return mappings;
  7194. }
  7195. function encodeInteger$1(num) {
  7196. var result = '';
  7197. num = num < 0 ? (-num << 1) | 1 : num << 1;
  7198. do {
  7199. var clamped = num & 31;
  7200. num >>>= 5;
  7201. if (num > 0) {
  7202. clamped |= 32;
  7203. }
  7204. result += chars$2[clamped];
  7205. } while (num > 0);
  7206. return result;
  7207. }
  7208. var BitSet$1 = function BitSet(arg) {
  7209. this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
  7210. };
  7211. BitSet$1.prototype.add = function add (n) {
  7212. this.bits[n >> 5] |= 1 << (n & 31);
  7213. };
  7214. BitSet$1.prototype.has = function has (n) {
  7215. return !!(this.bits[n >> 5] & (1 << (n & 31)));
  7216. };
  7217. var Chunk$1 = function Chunk(start, end, content) {
  7218. this.start = start;
  7219. this.end = end;
  7220. this.original = content;
  7221. this.intro = '';
  7222. this.outro = '';
  7223. this.content = content;
  7224. this.storeName = false;
  7225. this.edited = false;
  7226. // we make these non-enumerable, for sanity while debugging
  7227. Object.defineProperties(this, {
  7228. previous: { writable: true, value: null },
  7229. next: { writable: true, value: null }
  7230. });
  7231. };
  7232. Chunk$1.prototype.appendLeft = function appendLeft (content) {
  7233. this.outro += content;
  7234. };
  7235. Chunk$1.prototype.appendRight = function appendRight (content) {
  7236. this.intro = this.intro + content;
  7237. };
  7238. Chunk$1.prototype.clone = function clone () {
  7239. var chunk = new Chunk$1(this.start, this.end, this.original);
  7240. chunk.intro = this.intro;
  7241. chunk.outro = this.outro;
  7242. chunk.content = this.content;
  7243. chunk.storeName = this.storeName;
  7244. chunk.edited = this.edited;
  7245. return chunk;
  7246. };
  7247. Chunk$1.prototype.contains = function contains (index) {
  7248. return this.start < index && index < this.end;
  7249. };
  7250. Chunk$1.prototype.eachNext = function eachNext (fn) {
  7251. var chunk = this;
  7252. while (chunk) {
  7253. fn(chunk);
  7254. chunk = chunk.next;
  7255. }
  7256. };
  7257. Chunk$1.prototype.eachPrevious = function eachPrevious (fn) {
  7258. var chunk = this;
  7259. while (chunk) {
  7260. fn(chunk);
  7261. chunk = chunk.previous;
  7262. }
  7263. };
  7264. Chunk$1.prototype.edit = function edit (content, storeName, contentOnly) {
  7265. this.content = content;
  7266. if (!contentOnly) {
  7267. this.intro = '';
  7268. this.outro = '';
  7269. }
  7270. this.storeName = storeName;
  7271. this.edited = true;
  7272. return this;
  7273. };
  7274. Chunk$1.prototype.prependLeft = function prependLeft (content) {
  7275. this.outro = content + this.outro;
  7276. };
  7277. Chunk$1.prototype.prependRight = function prependRight (content) {
  7278. this.intro = content + this.intro;
  7279. };
  7280. Chunk$1.prototype.split = function split (index) {
  7281. var sliceIndex = index - this.start;
  7282. var originalBefore = this.original.slice(0, sliceIndex);
  7283. var originalAfter = this.original.slice(sliceIndex);
  7284. this.original = originalBefore;
  7285. var newChunk = new Chunk$1(index, this.end, originalAfter);
  7286. newChunk.outro = this.outro;
  7287. this.outro = '';
  7288. this.end = index;
  7289. if (this.edited) {
  7290. // TODO is this block necessary?...
  7291. newChunk.edit('', false);
  7292. this.content = '';
  7293. } else {
  7294. this.content = originalBefore;
  7295. }
  7296. newChunk.next = this.next;
  7297. if (newChunk.next) { newChunk.next.previous = newChunk; }
  7298. newChunk.previous = this;
  7299. this.next = newChunk;
  7300. return newChunk;
  7301. };
  7302. Chunk$1.prototype.toString = function toString () {
  7303. return this.intro + this.content + this.outro;
  7304. };
  7305. Chunk$1.prototype.trimEnd = function trimEnd (rx) {
  7306. this.outro = this.outro.replace(rx, '');
  7307. if (this.outro.length) { return true; }
  7308. var trimmed = this.content.replace(rx, '');
  7309. if (trimmed.length) {
  7310. if (trimmed !== this.content) {
  7311. this.split(this.start + trimmed.length).edit('', undefined, true);
  7312. }
  7313. return true;
  7314. } else {
  7315. this.edit('', undefined, true);
  7316. this.intro = this.intro.replace(rx, '');
  7317. if (this.intro.length) { return true; }
  7318. }
  7319. };
  7320. Chunk$1.prototype.trimStart = function trimStart (rx) {
  7321. this.intro = this.intro.replace(rx, '');
  7322. if (this.intro.length) { return true; }
  7323. var trimmed = this.content.replace(rx, '');
  7324. if (trimmed.length) {
  7325. if (trimmed !== this.content) {
  7326. this.split(this.end - trimmed.length);
  7327. this.edit('', undefined, true);
  7328. }
  7329. return true;
  7330. } else {
  7331. this.edit('', undefined, true);
  7332. this.outro = this.outro.replace(rx, '');
  7333. if (this.outro.length) { return true; }
  7334. }
  7335. };
  7336. var btoa$2 = function () {
  7337. throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
  7338. };
  7339. if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
  7340. btoa$2 = function (str) { return window.btoa(unescape(encodeURIComponent(str))); };
  7341. } else if (typeof Buffer === 'function') {
  7342. btoa$2 = function (str) { return Buffer.from(str, 'utf-8').toString('base64'); };
  7343. }
  7344. var SourceMap$2 = function SourceMap(properties) {
  7345. this.version = 3;
  7346. this.file = properties.file;
  7347. this.sources = properties.sources;
  7348. this.sourcesContent = properties.sourcesContent;
  7349. this.names = properties.names;
  7350. this.mappings = encode$1(properties.mappings);
  7351. };
  7352. SourceMap$2.prototype.toString = function toString () {
  7353. return JSON.stringify(this);
  7354. };
  7355. SourceMap$2.prototype.toUrl = function toUrl () {
  7356. return 'data:application/json;charset=utf-8;base64,' + btoa$2(this.toString());
  7357. };
  7358. function guessIndent$1(code) {
  7359. var lines = code.split('\n');
  7360. var tabbed = lines.filter(function (line) { return /^\t+/.test(line); });
  7361. var spaced = lines.filter(function (line) { return /^ {2,}/.test(line); });
  7362. if (tabbed.length === 0 && spaced.length === 0) {
  7363. return null;
  7364. }
  7365. // More lines tabbed than spaced? Assume tabs, and
  7366. // default to tabs in the case of a tie (or nothing
  7367. // to go on)
  7368. if (tabbed.length >= spaced.length) {
  7369. return '\t';
  7370. }
  7371. // Otherwise, we need to guess the multiple
  7372. var min = spaced.reduce(function (previous, current) {
  7373. var numSpaces = /^ +/.exec(current)[0].length;
  7374. return Math.min(numSpaces, previous);
  7375. }, Infinity);
  7376. return new Array(min + 1).join(' ');
  7377. }
  7378. function getRelativePath$1(from, to) {
  7379. var fromParts = from.split(/[/\\]/);
  7380. var toParts = to.split(/[/\\]/);
  7381. fromParts.pop(); // get dirname
  7382. while (fromParts[0] === toParts[0]) {
  7383. fromParts.shift();
  7384. toParts.shift();
  7385. }
  7386. if (fromParts.length) {
  7387. var i = fromParts.length;
  7388. while (i--) { fromParts[i] = '..'; }
  7389. }
  7390. return fromParts.concat(toParts).join('/');
  7391. }
  7392. var toString$3 = Object.prototype.toString;
  7393. function isObject$3(thing) {
  7394. return toString$3.call(thing) === '[object Object]';
  7395. }
  7396. function getLocator$1(source) {
  7397. var originalLines = source.split('\n');
  7398. var lineOffsets = [];
  7399. for (var i = 0, pos = 0; i < originalLines.length; i++) {
  7400. lineOffsets.push(pos);
  7401. pos += originalLines[i].length + 1;
  7402. }
  7403. return function locate(index) {
  7404. var i = 0;
  7405. var j = lineOffsets.length;
  7406. while (i < j) {
  7407. var m = (i + j) >> 1;
  7408. if (index < lineOffsets[m]) {
  7409. j = m;
  7410. } else {
  7411. i = m + 1;
  7412. }
  7413. }
  7414. var line = i - 1;
  7415. var column = index - lineOffsets[line];
  7416. return { line: line, column: column };
  7417. };
  7418. }
  7419. var Mappings$1 = function Mappings(hires) {
  7420. this.hires = hires;
  7421. this.generatedCodeLine = 0;
  7422. this.generatedCodeColumn = 0;
  7423. this.raw = [];
  7424. this.rawSegments = this.raw[this.generatedCodeLine] = [];
  7425. this.pending = null;
  7426. };
  7427. Mappings$1.prototype.addEdit = function addEdit (sourceIndex, content, loc, nameIndex) {
  7428. if (content.length) {
  7429. var segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  7430. if (nameIndex >= 0) {
  7431. segment.push(nameIndex);
  7432. }
  7433. this.rawSegments.push(segment);
  7434. } else if (this.pending) {
  7435. this.rawSegments.push(this.pending);
  7436. }
  7437. this.advance(content);
  7438. this.pending = null;
  7439. };
  7440. Mappings$1.prototype.addUneditedChunk = function addUneditedChunk (sourceIndex, chunk, original, loc, sourcemapLocations) {
  7441. var originalCharIndex = chunk.start;
  7442. var first = true;
  7443. while (originalCharIndex < chunk.end) {
  7444. if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
  7445. this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]);
  7446. }
  7447. if (original[originalCharIndex] === '\n') {
  7448. loc.line += 1;
  7449. loc.column = 0;
  7450. this.generatedCodeLine += 1;
  7451. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  7452. this.generatedCodeColumn = 0;
  7453. first = true;
  7454. } else {
  7455. loc.column += 1;
  7456. this.generatedCodeColumn += 1;
  7457. first = false;
  7458. }
  7459. originalCharIndex += 1;
  7460. }
  7461. this.pending = null;
  7462. };
  7463. Mappings$1.prototype.advance = function advance (str) {
  7464. if (!str) { return; }
  7465. var lines = str.split('\n');
  7466. if (lines.length > 1) {
  7467. for (var i = 0; i < lines.length - 1; i++) {
  7468. this.generatedCodeLine++;
  7469. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  7470. }
  7471. this.generatedCodeColumn = 0;
  7472. }
  7473. this.generatedCodeColumn += lines[lines.length - 1].length;
  7474. };
  7475. var n$1 = '\n';
  7476. var warned$2 = {
  7477. insertLeft: false,
  7478. insertRight: false,
  7479. storeName: false
  7480. };
  7481. var MagicString$1 = function MagicString(string, options) {
  7482. if ( options === void 0 ) options = {};
  7483. var chunk = new Chunk$1(0, string.length, string);
  7484. Object.defineProperties(this, {
  7485. original: { writable: true, value: string },
  7486. outro: { writable: true, value: '' },
  7487. intro: { writable: true, value: '' },
  7488. firstChunk: { writable: true, value: chunk },
  7489. lastChunk: { writable: true, value: chunk },
  7490. lastSearchedChunk: { writable: true, value: chunk },
  7491. byStart: { writable: true, value: {} },
  7492. byEnd: { writable: true, value: {} },
  7493. filename: { writable: true, value: options.filename },
  7494. indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
  7495. sourcemapLocations: { writable: true, value: new BitSet$1() },
  7496. storedNames: { writable: true, value: {} },
  7497. indentStr: { writable: true, value: guessIndent$1(string) }
  7498. });
  7499. this.byStart[0] = chunk;
  7500. this.byEnd[string.length] = chunk;
  7501. };
  7502. MagicString$1.prototype.addSourcemapLocation = function addSourcemapLocation (char) {
  7503. this.sourcemapLocations.add(char);
  7504. };
  7505. MagicString$1.prototype.append = function append (content) {
  7506. if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); }
  7507. this.outro += content;
  7508. return this;
  7509. };
  7510. MagicString$1.prototype.appendLeft = function appendLeft (index, content) {
  7511. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  7512. this._split(index);
  7513. var chunk = this.byEnd[index];
  7514. if (chunk) {
  7515. chunk.appendLeft(content);
  7516. } else {
  7517. this.intro += content;
  7518. }
  7519. return this;
  7520. };
  7521. MagicString$1.prototype.appendRight = function appendRight (index, content) {
  7522. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  7523. this._split(index);
  7524. var chunk = this.byStart[index];
  7525. if (chunk) {
  7526. chunk.appendRight(content);
  7527. } else {
  7528. this.outro += content;
  7529. }
  7530. return this;
  7531. };
  7532. MagicString$1.prototype.clone = function clone () {
  7533. var cloned = new MagicString$1(this.original, { filename: this.filename });
  7534. var originalChunk = this.firstChunk;
  7535. var clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
  7536. while (originalChunk) {
  7537. cloned.byStart[clonedChunk.start] = clonedChunk;
  7538. cloned.byEnd[clonedChunk.end] = clonedChunk;
  7539. var nextOriginalChunk = originalChunk.next;
  7540. var nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
  7541. if (nextClonedChunk) {
  7542. clonedChunk.next = nextClonedChunk;
  7543. nextClonedChunk.previous = clonedChunk;
  7544. clonedChunk = nextClonedChunk;
  7545. }
  7546. originalChunk = nextOriginalChunk;
  7547. }
  7548. cloned.lastChunk = clonedChunk;
  7549. if (this.indentExclusionRanges) {
  7550. cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
  7551. }
  7552. cloned.sourcemapLocations = new BitSet$1(this.sourcemapLocations);
  7553. cloned.intro = this.intro;
  7554. cloned.outro = this.outro;
  7555. return cloned;
  7556. };
  7557. MagicString$1.prototype.generateDecodedMap = function generateDecodedMap (options) {
  7558. var this$1$1 = this;
  7559. options = options || {};
  7560. var sourceIndex = 0;
  7561. var names = Object.keys(this.storedNames);
  7562. var mappings = new Mappings$1(options.hires);
  7563. var locate = getLocator$1(this.original);
  7564. if (this.intro) {
  7565. mappings.advance(this.intro);
  7566. }
  7567. this.firstChunk.eachNext(function (chunk) {
  7568. var loc = locate(chunk.start);
  7569. if (chunk.intro.length) { mappings.advance(chunk.intro); }
  7570. if (chunk.edited) {
  7571. mappings.addEdit(
  7572. sourceIndex,
  7573. chunk.content,
  7574. loc,
  7575. chunk.storeName ? names.indexOf(chunk.original) : -1
  7576. );
  7577. } else {
  7578. mappings.addUneditedChunk(sourceIndex, chunk, this$1$1.original, loc, this$1$1.sourcemapLocations);
  7579. }
  7580. if (chunk.outro.length) { mappings.advance(chunk.outro); }
  7581. });
  7582. return {
  7583. file: options.file ? options.file.split(/[/\\]/).pop() : null,
  7584. sources: [options.source ? getRelativePath$1(options.file || '', options.source) : null],
  7585. sourcesContent: options.includeContent ? [this.original] : [null],
  7586. names: names,
  7587. mappings: mappings.raw
  7588. };
  7589. };
  7590. MagicString$1.prototype.generateMap = function generateMap (options) {
  7591. return new SourceMap$2(this.generateDecodedMap(options));
  7592. };
  7593. MagicString$1.prototype.getIndentString = function getIndentString () {
  7594. return this.indentStr === null ? '\t' : this.indentStr;
  7595. };
  7596. MagicString$1.prototype.indent = function indent (indentStr, options) {
  7597. var pattern = /^[^\r\n]/gm;
  7598. if (isObject$3(indentStr)) {
  7599. options = indentStr;
  7600. indentStr = undefined;
  7601. }
  7602. indentStr = indentStr !== undefined ? indentStr : this.indentStr || '\t';
  7603. if (indentStr === '') { return this; } // noop
  7604. options = options || {};
  7605. // Process exclusion ranges
  7606. var isExcluded = {};
  7607. if (options.exclude) {
  7608. var exclusions =
  7609. typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
  7610. exclusions.forEach(function (exclusion) {
  7611. for (var i = exclusion[0]; i < exclusion[1]; i += 1) {
  7612. isExcluded[i] = true;
  7613. }
  7614. });
  7615. }
  7616. var shouldIndentNextCharacter = options.indentStart !== false;
  7617. var replacer = function (match) {
  7618. if (shouldIndentNextCharacter) { return ("" + indentStr + match); }
  7619. shouldIndentNextCharacter = true;
  7620. return match;
  7621. };
  7622. this.intro = this.intro.replace(pattern, replacer);
  7623. var charIndex = 0;
  7624. var chunk = this.firstChunk;
  7625. while (chunk) {
  7626. var end = chunk.end;
  7627. if (chunk.edited) {
  7628. if (!isExcluded[charIndex]) {
  7629. chunk.content = chunk.content.replace(pattern, replacer);
  7630. if (chunk.content.length) {
  7631. shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
  7632. }
  7633. }
  7634. } else {
  7635. charIndex = chunk.start;
  7636. while (charIndex < end) {
  7637. if (!isExcluded[charIndex]) {
  7638. var char = this.original[charIndex];
  7639. if (char === '\n') {
  7640. shouldIndentNextCharacter = true;
  7641. } else if (char !== '\r' && shouldIndentNextCharacter) {
  7642. shouldIndentNextCharacter = false;
  7643. if (charIndex === chunk.start) {
  7644. chunk.prependRight(indentStr);
  7645. } else {
  7646. this._splitChunk(chunk, charIndex);
  7647. chunk = chunk.next;
  7648. chunk.prependRight(indentStr);
  7649. }
  7650. }
  7651. }
  7652. charIndex += 1;
  7653. }
  7654. }
  7655. charIndex = chunk.end;
  7656. chunk = chunk.next;
  7657. }
  7658. this.outro = this.outro.replace(pattern, replacer);
  7659. return this;
  7660. };
  7661. MagicString$1.prototype.insert = function insert () {
  7662. throw new Error('magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)');
  7663. };
  7664. MagicString$1.prototype.insertLeft = function insertLeft (index, content) {
  7665. if (!warned$2.insertLeft) {
  7666. console.warn('magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead'); // eslint-disable-line no-console
  7667. warned$2.insertLeft = true;
  7668. }
  7669. return this.appendLeft(index, content);
  7670. };
  7671. MagicString$1.prototype.insertRight = function insertRight (index, content) {
  7672. if (!warned$2.insertRight) {
  7673. console.warn('magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead'); // eslint-disable-line no-console
  7674. warned$2.insertRight = true;
  7675. }
  7676. return this.prependRight(index, content);
  7677. };
  7678. MagicString$1.prototype.move = function move (start, end, index) {
  7679. if (index >= start && index <= end) { throw new Error('Cannot move a selection inside itself'); }
  7680. this._split(start);
  7681. this._split(end);
  7682. this._split(index);
  7683. var first = this.byStart[start];
  7684. var last = this.byEnd[end];
  7685. var oldLeft = first.previous;
  7686. var oldRight = last.next;
  7687. var newRight = this.byStart[index];
  7688. if (!newRight && last === this.lastChunk) { return this; }
  7689. var newLeft = newRight ? newRight.previous : this.lastChunk;
  7690. if (oldLeft) { oldLeft.next = oldRight; }
  7691. if (oldRight) { oldRight.previous = oldLeft; }
  7692. if (newLeft) { newLeft.next = first; }
  7693. if (newRight) { newRight.previous = last; }
  7694. if (!first.previous) { this.firstChunk = last.next; }
  7695. if (!last.next) {
  7696. this.lastChunk = first.previous;
  7697. this.lastChunk.next = null;
  7698. }
  7699. first.previous = newLeft;
  7700. last.next = newRight || null;
  7701. if (!newLeft) { this.firstChunk = first; }
  7702. if (!newRight) { this.lastChunk = last; }
  7703. return this;
  7704. };
  7705. MagicString$1.prototype.overwrite = function overwrite (start, end, content, options) {
  7706. if (typeof content !== 'string') { throw new TypeError('replacement content must be a string'); }
  7707. while (start < 0) { start += this.original.length; }
  7708. while (end < 0) { end += this.original.length; }
  7709. if (end > this.original.length) { throw new Error('end is out of bounds'); }
  7710. if (start === end)
  7711. { throw new Error('Cannot overwrite a zero-length range – use appendLeft or prependRight instead'); }
  7712. this._split(start);
  7713. this._split(end);
  7714. if (options === true) {
  7715. if (!warned$2.storeName) {
  7716. console.warn('The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string'); // eslint-disable-line no-console
  7717. warned$2.storeName = true;
  7718. }
  7719. options = { storeName: true };
  7720. }
  7721. var storeName = options !== undefined ? options.storeName : false;
  7722. var contentOnly = options !== undefined ? options.contentOnly : false;
  7723. if (storeName) {
  7724. var original = this.original.slice(start, end);
  7725. this.storedNames[original] = true;
  7726. }
  7727. var first = this.byStart[start];
  7728. var last = this.byEnd[end];
  7729. if (first) {
  7730. if (end > first.end && first.next !== this.byStart[first.end]) {
  7731. throw new Error('Cannot overwrite across a split point');
  7732. }
  7733. first.edit(content, storeName, contentOnly);
  7734. if (first !== last) {
  7735. var chunk = first.next;
  7736. while (chunk !== last) {
  7737. chunk.edit('', false);
  7738. chunk = chunk.next;
  7739. }
  7740. chunk.edit('', false);
  7741. }
  7742. } else {
  7743. // must be inserting at the end
  7744. var newChunk = new Chunk$1(start, end, '').edit(content, storeName);
  7745. // TODO last chunk in the array may not be the last chunk, if it's moved...
  7746. last.next = newChunk;
  7747. newChunk.previous = last;
  7748. }
  7749. return this;
  7750. };
  7751. MagicString$1.prototype.prepend = function prepend (content) {
  7752. if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); }
  7753. this.intro = content + this.intro;
  7754. return this;
  7755. };
  7756. MagicString$1.prototype.prependLeft = function prependLeft (index, content) {
  7757. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  7758. this._split(index);
  7759. var chunk = this.byEnd[index];
  7760. if (chunk) {
  7761. chunk.prependLeft(content);
  7762. } else {
  7763. this.intro = content + this.intro;
  7764. }
  7765. return this;
  7766. };
  7767. MagicString$1.prototype.prependRight = function prependRight (index, content) {
  7768. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  7769. this._split(index);
  7770. var chunk = this.byStart[index];
  7771. if (chunk) {
  7772. chunk.prependRight(content);
  7773. } else {
  7774. this.outro = content + this.outro;
  7775. }
  7776. return this;
  7777. };
  7778. MagicString$1.prototype.remove = function remove (start, end) {
  7779. while (start < 0) { start += this.original.length; }
  7780. while (end < 0) { end += this.original.length; }
  7781. if (start === end) { return this; }
  7782. if (start < 0 || end > this.original.length) { throw new Error('Character is out of bounds'); }
  7783. if (start > end) { throw new Error('end must be greater than start'); }
  7784. this._split(start);
  7785. this._split(end);
  7786. var chunk = this.byStart[start];
  7787. while (chunk) {
  7788. chunk.intro = '';
  7789. chunk.outro = '';
  7790. chunk.edit('');
  7791. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  7792. }
  7793. return this;
  7794. };
  7795. MagicString$1.prototype.lastChar = function lastChar () {
  7796. if (this.outro.length)
  7797. { return this.outro[this.outro.length - 1]; }
  7798. var chunk = this.lastChunk;
  7799. do {
  7800. if (chunk.outro.length)
  7801. { return chunk.outro[chunk.outro.length - 1]; }
  7802. if (chunk.content.length)
  7803. { return chunk.content[chunk.content.length - 1]; }
  7804. if (chunk.intro.length)
  7805. { return chunk.intro[chunk.intro.length - 1]; }
  7806. } while (chunk = chunk.previous);
  7807. if (this.intro.length)
  7808. { return this.intro[this.intro.length - 1]; }
  7809. return '';
  7810. };
  7811. MagicString$1.prototype.lastLine = function lastLine () {
  7812. var lineIndex = this.outro.lastIndexOf(n$1);
  7813. if (lineIndex !== -1)
  7814. { return this.outro.substr(lineIndex + 1); }
  7815. var lineStr = this.outro;
  7816. var chunk = this.lastChunk;
  7817. do {
  7818. if (chunk.outro.length > 0) {
  7819. lineIndex = chunk.outro.lastIndexOf(n$1);
  7820. if (lineIndex !== -1)
  7821. { return chunk.outro.substr(lineIndex + 1) + lineStr; }
  7822. lineStr = chunk.outro + lineStr;
  7823. }
  7824. if (chunk.content.length > 0) {
  7825. lineIndex = chunk.content.lastIndexOf(n$1);
  7826. if (lineIndex !== -1)
  7827. { return chunk.content.substr(lineIndex + 1) + lineStr; }
  7828. lineStr = chunk.content + lineStr;
  7829. }
  7830. if (chunk.intro.length > 0) {
  7831. lineIndex = chunk.intro.lastIndexOf(n$1);
  7832. if (lineIndex !== -1)
  7833. { return chunk.intro.substr(lineIndex + 1) + lineStr; }
  7834. lineStr = chunk.intro + lineStr;
  7835. }
  7836. } while (chunk = chunk.previous);
  7837. lineIndex = this.intro.lastIndexOf(n$1);
  7838. if (lineIndex !== -1)
  7839. { return this.intro.substr(lineIndex + 1) + lineStr; }
  7840. return this.intro + lineStr;
  7841. };
  7842. MagicString$1.prototype.slice = function slice (start, end) {
  7843. if ( start === void 0 ) start = 0;
  7844. if ( end === void 0 ) end = this.original.length;
  7845. while (start < 0) { start += this.original.length; }
  7846. while (end < 0) { end += this.original.length; }
  7847. var result = '';
  7848. // find start chunk
  7849. var chunk = this.firstChunk;
  7850. while (chunk && (chunk.start > start || chunk.end <= start)) {
  7851. // found end chunk before start
  7852. if (chunk.start < end && chunk.end >= end) {
  7853. return result;
  7854. }
  7855. chunk = chunk.next;
  7856. }
  7857. if (chunk && chunk.edited && chunk.start !== start)
  7858. { throw new Error(("Cannot use replaced character " + start + " as slice start anchor.")); }
  7859. var startChunk = chunk;
  7860. while (chunk) {
  7861. if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
  7862. result += chunk.intro;
  7863. }
  7864. var containsEnd = chunk.start < end && chunk.end >= end;
  7865. if (containsEnd && chunk.edited && chunk.end !== end)
  7866. { throw new Error(("Cannot use replaced character " + end + " as slice end anchor.")); }
  7867. var sliceStart = startChunk === chunk ? start - chunk.start : 0;
  7868. var sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
  7869. result += chunk.content.slice(sliceStart, sliceEnd);
  7870. if (chunk.outro && (!containsEnd || chunk.end === end)) {
  7871. result += chunk.outro;
  7872. }
  7873. if (containsEnd) {
  7874. break;
  7875. }
  7876. chunk = chunk.next;
  7877. }
  7878. return result;
  7879. };
  7880. // TODO deprecate this? not really very useful
  7881. MagicString$1.prototype.snip = function snip (start, end) {
  7882. var clone = this.clone();
  7883. clone.remove(0, start);
  7884. clone.remove(end, clone.original.length);
  7885. return clone;
  7886. };
  7887. MagicString$1.prototype._split = function _split (index) {
  7888. if (this.byStart[index] || this.byEnd[index]) { return; }
  7889. var chunk = this.lastSearchedChunk;
  7890. var searchForward = index > chunk.end;
  7891. while (chunk) {
  7892. if (chunk.contains(index)) { return this._splitChunk(chunk, index); }
  7893. chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
  7894. }
  7895. };
  7896. MagicString$1.prototype._splitChunk = function _splitChunk (chunk, index) {
  7897. if (chunk.edited && chunk.content.length) {
  7898. // zero-length edited chunks are a special case (overlapping replacements)
  7899. var loc = getLocator$1(this.original)(index);
  7900. throw new Error(
  7901. ("Cannot split a chunk that has already been edited (" + (loc.line) + ":" + (loc.column) + " – \"" + (chunk.original) + "\")")
  7902. );
  7903. }
  7904. var newChunk = chunk.split(index);
  7905. this.byEnd[index] = chunk;
  7906. this.byStart[index] = newChunk;
  7907. this.byEnd[newChunk.end] = newChunk;
  7908. if (chunk === this.lastChunk) { this.lastChunk = newChunk; }
  7909. this.lastSearchedChunk = chunk;
  7910. return true;
  7911. };
  7912. MagicString$1.prototype.toString = function toString () {
  7913. var str = this.intro;
  7914. var chunk = this.firstChunk;
  7915. while (chunk) {
  7916. str += chunk.toString();
  7917. chunk = chunk.next;
  7918. }
  7919. return str + this.outro;
  7920. };
  7921. MagicString$1.prototype.isEmpty = function isEmpty () {
  7922. var chunk = this.firstChunk;
  7923. do {
  7924. if (chunk.intro.length && chunk.intro.trim() ||
  7925. chunk.content.length && chunk.content.trim() ||
  7926. chunk.outro.length && chunk.outro.trim())
  7927. { return false; }
  7928. } while (chunk = chunk.next);
  7929. return true;
  7930. };
  7931. MagicString$1.prototype.length = function length () {
  7932. var chunk = this.firstChunk;
  7933. var length = 0;
  7934. do {
  7935. length += chunk.intro.length + chunk.content.length + chunk.outro.length;
  7936. } while (chunk = chunk.next);
  7937. return length;
  7938. };
  7939. MagicString$1.prototype.trimLines = function trimLines () {
  7940. return this.trim('[\\r\\n]');
  7941. };
  7942. MagicString$1.prototype.trim = function trim (charType) {
  7943. return this.trimStart(charType).trimEnd(charType);
  7944. };
  7945. MagicString$1.prototype.trimEndAborted = function trimEndAborted (charType) {
  7946. var rx = new RegExp((charType || '\\s') + '+$');
  7947. this.outro = this.outro.replace(rx, '');
  7948. if (this.outro.length) { return true; }
  7949. var chunk = this.lastChunk;
  7950. do {
  7951. var end = chunk.end;
  7952. var aborted = chunk.trimEnd(rx);
  7953. // if chunk was trimmed, we have a new lastChunk
  7954. if (chunk.end !== end) {
  7955. if (this.lastChunk === chunk) {
  7956. this.lastChunk = chunk.next;
  7957. }
  7958. this.byEnd[chunk.end] = chunk;
  7959. this.byStart[chunk.next.start] = chunk.next;
  7960. this.byEnd[chunk.next.end] = chunk.next;
  7961. }
  7962. if (aborted) { return true; }
  7963. chunk = chunk.previous;
  7964. } while (chunk);
  7965. return false;
  7966. };
  7967. MagicString$1.prototype.trimEnd = function trimEnd (charType) {
  7968. this.trimEndAborted(charType);
  7969. return this;
  7970. };
  7971. MagicString$1.prototype.trimStartAborted = function trimStartAborted (charType) {
  7972. var rx = new RegExp('^' + (charType || '\\s') + '+');
  7973. this.intro = this.intro.replace(rx, '');
  7974. if (this.intro.length) { return true; }
  7975. var chunk = this.firstChunk;
  7976. do {
  7977. var end = chunk.end;
  7978. var aborted = chunk.trimStart(rx);
  7979. if (chunk.end !== end) {
  7980. // special case...
  7981. if (chunk === this.lastChunk) { this.lastChunk = chunk.next; }
  7982. this.byEnd[chunk.end] = chunk;
  7983. this.byStart[chunk.next.start] = chunk.next;
  7984. this.byEnd[chunk.next.end] = chunk.next;
  7985. }
  7986. if (aborted) { return true; }
  7987. chunk = chunk.next;
  7988. } while (chunk);
  7989. return false;
  7990. };
  7991. MagicString$1.prototype.trimStart = function trimStart (charType) {
  7992. this.trimStartAborted(charType);
  7993. return this;
  7994. };
  7995. function isReference(node, parent) {
  7996. if (node.type === 'MemberExpression') {
  7997. return !node.computed && isReference(node.object, node);
  7998. }
  7999. if (node.type === 'Identifier') {
  8000. if (!parent)
  8001. return true;
  8002. switch (parent.type) {
  8003. // disregard `bar` in `foo.bar`
  8004. case 'MemberExpression': return parent.computed || node === parent.object;
  8005. // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}`
  8006. case 'MethodDefinition': return parent.computed;
  8007. // disregard the `foo` in `class {foo=bar}` but keep it in `class {[foo]=bar}` and `class {bar=foo}`
  8008. case 'FieldDefinition': return parent.computed || node === parent.value;
  8009. // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
  8010. case 'Property': return parent.computed || node === parent.value;
  8011. // disregard the `bar` in `export { foo as bar }` or
  8012. // the foo in `import { foo as bar }`
  8013. case 'ExportSpecifier':
  8014. case 'ImportSpecifier': return node === parent.local;
  8015. // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}`
  8016. case 'LabeledStatement':
  8017. case 'BreakStatement':
  8018. case 'ContinueStatement': return false;
  8019. default: return true;
  8020. }
  8021. }
  8022. return false;
  8023. }
  8024. var peerDependencies = {
  8025. rollup: "^2.38.3"
  8026. };
  8027. function tryParse(parse, code, id) {
  8028. try {
  8029. return parse(code, { allowReturnOutsideFunction: true });
  8030. } catch (err) {
  8031. err.message += ` in ${id}`;
  8032. throw err;
  8033. }
  8034. }
  8035. const firstpassGlobal = /\b(?:require|module|exports|global)\b/;
  8036. const firstpassNoGlobal = /\b(?:require|module|exports)\b/;
  8037. function hasCjsKeywords(code, ignoreGlobal) {
  8038. const firstpass = ignoreGlobal ? firstpassNoGlobal : firstpassGlobal;
  8039. return firstpass.test(code);
  8040. }
  8041. /* eslint-disable no-underscore-dangle */
  8042. function analyzeTopLevelStatements(parse, code, id) {
  8043. const ast = tryParse(parse, code, id);
  8044. let isEsModule = false;
  8045. let hasDefaultExport = false;
  8046. let hasNamedExports = false;
  8047. for (const node of ast.body) {
  8048. switch (node.type) {
  8049. case 'ExportDefaultDeclaration':
  8050. isEsModule = true;
  8051. hasDefaultExport = true;
  8052. break;
  8053. case 'ExportNamedDeclaration':
  8054. isEsModule = true;
  8055. if (node.declaration) {
  8056. hasNamedExports = true;
  8057. } else {
  8058. for (const specifier of node.specifiers) {
  8059. if (specifier.exported.name === 'default') {
  8060. hasDefaultExport = true;
  8061. } else {
  8062. hasNamedExports = true;
  8063. }
  8064. }
  8065. }
  8066. break;
  8067. case 'ExportAllDeclaration':
  8068. isEsModule = true;
  8069. if (node.exported && node.exported.name === 'default') {
  8070. hasDefaultExport = true;
  8071. } else {
  8072. hasNamedExports = true;
  8073. }
  8074. break;
  8075. case 'ImportDeclaration':
  8076. isEsModule = true;
  8077. break;
  8078. }
  8079. }
  8080. return { isEsModule, hasDefaultExport, hasNamedExports, ast };
  8081. }
  8082. const isWrappedId = (id, suffix) => id.endsWith(suffix);
  8083. const wrapId = (id, suffix) => `\0${id}${suffix}`;
  8084. const unwrapId$1 = (wrappedId, suffix) => wrappedId.slice(1, -suffix.length);
  8085. const PROXY_SUFFIX = '?commonjs-proxy';
  8086. const REQUIRE_SUFFIX = '?commonjs-require';
  8087. const EXTERNAL_SUFFIX = '?commonjs-external';
  8088. const EXPORTS_SUFFIX = '?commonjs-exports';
  8089. const MODULE_SUFFIX = '?commonjs-module';
  8090. const DYNAMIC_REGISTER_SUFFIX = '?commonjs-dynamic-register';
  8091. const DYNAMIC_JSON_PREFIX = '\0commonjs-dynamic-json:';
  8092. const DYNAMIC_PACKAGES_ID = '\0commonjs-dynamic-packages';
  8093. const HELPERS_ID = '\0commonjsHelpers.js';
  8094. // `x['default']` is used instead of `x.default` for backward compatibility with ES3 browsers.
  8095. // Minifiers like uglify will usually transpile it back if compatibility with ES3 is not enabled.
  8096. // This will no longer be necessary once Rollup switches to ES6 output, likely
  8097. // in Rollup 3
  8098. const HELPERS = `
  8099. export var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  8100. export function getDefaultExportFromCjs (x) {
  8101. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  8102. }
  8103. export function getDefaultExportFromNamespaceIfPresent (n) {
  8104. return n && Object.prototype.hasOwnProperty.call(n, 'default') ? n['default'] : n;
  8105. }
  8106. export function getDefaultExportFromNamespaceIfNotNamed (n) {
  8107. return n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1 ? n['default'] : n;
  8108. }
  8109. export function getAugmentedNamespace(n) {
  8110. if (n.__esModule) return n;
  8111. var a = Object.defineProperty({}, '__esModule', {value: true});
  8112. Object.keys(n).forEach(function (k) {
  8113. var d = Object.getOwnPropertyDescriptor(n, k);
  8114. Object.defineProperty(a, k, d.get ? d : {
  8115. enumerable: true,
  8116. get: function () {
  8117. return n[k];
  8118. }
  8119. });
  8120. });
  8121. return a;
  8122. }
  8123. `;
  8124. const FAILED_REQUIRE_ERROR = `throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');`;
  8125. const HELPER_NON_DYNAMIC = `
  8126. export function commonjsRequire (path) {
  8127. ${FAILED_REQUIRE_ERROR}
  8128. }
  8129. `;
  8130. const getDynamicHelpers = (ignoreDynamicRequires) => `
  8131. export function createModule(modulePath) {
  8132. return {
  8133. path: modulePath,
  8134. exports: {},
  8135. require: function (path, base) {
  8136. return commonjsRequire(path, base == null ? modulePath : base);
  8137. }
  8138. };
  8139. }
  8140. export function commonjsRegister (path, loader) {
  8141. DYNAMIC_REQUIRE_LOADERS[path] = loader;
  8142. }
  8143. export function commonjsRegisterOrShort (path, to) {
  8144. var resolvedPath = commonjsResolveImpl(path, null, true);
  8145. if (resolvedPath !== null && DYNAMIC_REQUIRE_CACHE[resolvedPath]) {
  8146. DYNAMIC_REQUIRE_CACHE[path] = DYNAMIC_REQUIRE_CACHE[resolvedPath];
  8147. } else {
  8148. DYNAMIC_REQUIRE_SHORTS[path] = to;
  8149. }
  8150. }
  8151. var DYNAMIC_REQUIRE_LOADERS = Object.create(null);
  8152. var DYNAMIC_REQUIRE_CACHE = Object.create(null);
  8153. var DYNAMIC_REQUIRE_SHORTS = Object.create(null);
  8154. var DEFAULT_PARENT_MODULE = {
  8155. id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: []
  8156. };
  8157. var CHECKED_EXTENSIONS = ['', '.js', '.json'];
  8158. function normalize (path) {
  8159. path = path.replace(/\\\\/g, '/');
  8160. var parts = path.split('/');
  8161. var slashed = parts[0] === '';
  8162. for (var i = 1; i < parts.length; i++) {
  8163. if (parts[i] === '.' || parts[i] === '') {
  8164. parts.splice(i--, 1);
  8165. }
  8166. }
  8167. for (var i = 1; i < parts.length; i++) {
  8168. if (parts[i] !== '..') continue;
  8169. if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {
  8170. parts.splice(--i, 2);
  8171. i--;
  8172. }
  8173. }
  8174. path = parts.join('/');
  8175. if (slashed && path[0] !== '/')
  8176. path = '/' + path;
  8177. else if (path.length === 0)
  8178. path = '.';
  8179. return path;
  8180. }
  8181. function join () {
  8182. if (arguments.length === 0)
  8183. return '.';
  8184. var joined;
  8185. for (var i = 0; i < arguments.length; ++i) {
  8186. var arg = arguments[i];
  8187. if (arg.length > 0) {
  8188. if (joined === undefined)
  8189. joined = arg;
  8190. else
  8191. joined += '/' + arg;
  8192. }
  8193. }
  8194. if (joined === undefined)
  8195. return '.';
  8196. return joined;
  8197. }
  8198. function isPossibleNodeModulesPath (modulePath) {
  8199. var c0 = modulePath[0];
  8200. if (c0 === '/' || c0 === '\\\\') return false;
  8201. var c1 = modulePath[1], c2 = modulePath[2];
  8202. if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||
  8203. (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;
  8204. if (c1 === ':' && (c2 === '/' || c2 === '\\\\'))
  8205. return false;
  8206. return true;
  8207. }
  8208. function dirname (path) {
  8209. if (path.length === 0)
  8210. return '.';
  8211. var i = path.length - 1;
  8212. while (i > 0) {
  8213. var c = path.charCodeAt(i);
  8214. if ((c === 47 || c === 92) && i !== path.length - 1)
  8215. break;
  8216. i--;
  8217. }
  8218. if (i > 0)
  8219. return path.substr(0, i);
  8220. if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92)
  8221. return path.charAt(0);
  8222. return '.';
  8223. }
  8224. export function commonjsResolveImpl (path, originalModuleDir, testCache) {
  8225. var shouldTryNodeModules = isPossibleNodeModulesPath(path);
  8226. path = normalize(path);
  8227. var relPath;
  8228. if (path[0] === '/') {
  8229. originalModuleDir = '/';
  8230. }
  8231. while (true) {
  8232. if (!shouldTryNodeModules) {
  8233. relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path;
  8234. } else if (originalModuleDir) {
  8235. relPath = normalize(originalModuleDir + '/node_modules/' + path);
  8236. } else {
  8237. relPath = normalize(join('node_modules', path));
  8238. }
  8239. if (relPath.endsWith('/..')) {
  8240. break; // Travelled too far up, avoid infinite loop
  8241. }
  8242. for (var extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) {
  8243. var resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex];
  8244. if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) {
  8245. return resolvedPath;
  8246. }
  8247. if (DYNAMIC_REQUIRE_SHORTS[resolvedPath]) {
  8248. return resolvedPath;
  8249. }
  8250. if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) {
  8251. return resolvedPath;
  8252. }
  8253. }
  8254. if (!shouldTryNodeModules) break;
  8255. var nextDir = normalize(originalModuleDir + '/..');
  8256. if (nextDir === originalModuleDir) break;
  8257. originalModuleDir = nextDir;
  8258. }
  8259. return null;
  8260. }
  8261. export function commonjsResolve (path, originalModuleDir) {
  8262. var resolvedPath = commonjsResolveImpl(path, originalModuleDir);
  8263. if (resolvedPath !== null) {
  8264. return resolvedPath;
  8265. }
  8266. return require.resolve(path);
  8267. }
  8268. export function commonjsRequire (path, originalModuleDir) {
  8269. var resolvedPath = commonjsResolveImpl(path, originalModuleDir, true);
  8270. if (resolvedPath !== null) {
  8271. var cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath];
  8272. if (cachedModule) return cachedModule.exports;
  8273. var shortTo = DYNAMIC_REQUIRE_SHORTS[resolvedPath];
  8274. if (shortTo) {
  8275. cachedModule = DYNAMIC_REQUIRE_CACHE[shortTo];
  8276. if (cachedModule)
  8277. return cachedModule.exports;
  8278. resolvedPath = commonjsResolveImpl(shortTo, null, true);
  8279. }
  8280. var loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath];
  8281. if (loader) {
  8282. DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = {
  8283. id: resolvedPath,
  8284. filename: resolvedPath,
  8285. path: dirname(resolvedPath),
  8286. exports: {},
  8287. parent: DEFAULT_PARENT_MODULE,
  8288. loaded: false,
  8289. children: [],
  8290. paths: [],
  8291. require: function (path, base) {
  8292. return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base);
  8293. }
  8294. };
  8295. try {
  8296. loader.call(commonjsGlobal, cachedModule, cachedModule.exports);
  8297. } catch (error) {
  8298. delete DYNAMIC_REQUIRE_CACHE[resolvedPath];
  8299. throw error;
  8300. }
  8301. cachedModule.loaded = true;
  8302. return cachedModule.exports;
  8303. };
  8304. }
  8305. ${ignoreDynamicRequires ? 'return require(path);' : FAILED_REQUIRE_ERROR}
  8306. }
  8307. commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE;
  8308. commonjsRequire.resolve = commonjsResolve;
  8309. `;
  8310. function getHelpersModule(isDynamicRequireModulesEnabled, ignoreDynamicRequires) {
  8311. return `${HELPERS}${
  8312. isDynamicRequireModulesEnabled ? getDynamicHelpers(ignoreDynamicRequires) : HELPER_NON_DYNAMIC
  8313. }`;
  8314. }
  8315. /* eslint-disable import/prefer-default-export */
  8316. function deconflict(scopes, globals, identifier) {
  8317. let i = 1;
  8318. let deconflicted = makeLegalIdentifier(identifier);
  8319. const hasConflicts = () =>
  8320. scopes.some((scope) => scope.contains(deconflicted)) || globals.has(deconflicted);
  8321. while (hasConflicts()) {
  8322. deconflicted = makeLegalIdentifier(`${identifier}_${i}`);
  8323. i += 1;
  8324. }
  8325. for (const scope of scopes) {
  8326. scope.declarations[deconflicted] = true;
  8327. }
  8328. return deconflicted;
  8329. }
  8330. function getName(id) {
  8331. const name = makeLegalIdentifier(path$r.basename(id, path$r.extname(id)));
  8332. if (name !== 'index') {
  8333. return name;
  8334. }
  8335. return makeLegalIdentifier(path$r.basename(path$r.dirname(id)));
  8336. }
  8337. function normalizePathSlashes(path) {
  8338. return path.replace(/\\/g, '/');
  8339. }
  8340. const VIRTUAL_PATH_BASE = '/$$rollup_base$$';
  8341. const getVirtualPathForDynamicRequirePath = (path, commonDir) => {
  8342. const normalizedPath = normalizePathSlashes(path);
  8343. return normalizedPath.startsWith(commonDir)
  8344. ? VIRTUAL_PATH_BASE + normalizedPath.slice(commonDir.length)
  8345. : normalizedPath;
  8346. };
  8347. function getPackageEntryPoint(dirPath) {
  8348. let entryPoint = 'index.js';
  8349. try {
  8350. if (fs$n.existsSync(path$r.join(dirPath, 'package.json'))) {
  8351. entryPoint =
  8352. JSON.parse(fs$n.readFileSync(path$r.join(dirPath, 'package.json'), { encoding: 'utf8' })).main ||
  8353. entryPoint;
  8354. }
  8355. } catch (ignored) {
  8356. // ignored
  8357. }
  8358. return entryPoint;
  8359. }
  8360. function getDynamicPackagesModule(dynamicRequireModuleDirPaths, commonDir) {
  8361. let code = `const commonjsRegisterOrShort = require('${HELPERS_ID}?commonjsRegisterOrShort');`;
  8362. for (const dir of dynamicRequireModuleDirPaths) {
  8363. const entryPoint = getPackageEntryPoint(dir);
  8364. code += `\ncommonjsRegisterOrShort(${JSON.stringify(
  8365. getVirtualPathForDynamicRequirePath(dir, commonDir)
  8366. )}, ${JSON.stringify(getVirtualPathForDynamicRequirePath(path$r.join(dir, entryPoint), commonDir))});`;
  8367. }
  8368. return code;
  8369. }
  8370. function getDynamicPackagesEntryIntro(
  8371. dynamicRequireModuleDirPaths,
  8372. dynamicRequireModuleSet
  8373. ) {
  8374. let dynamicImports = Array.from(
  8375. dynamicRequireModuleSet,
  8376. (dynamicId) => `require(${JSON.stringify(wrapId(dynamicId, DYNAMIC_REGISTER_SUFFIX))});`
  8377. ).join('\n');
  8378. if (dynamicRequireModuleDirPaths.length) {
  8379. dynamicImports += `require(${JSON.stringify(
  8380. wrapId(DYNAMIC_PACKAGES_ID, DYNAMIC_REGISTER_SUFFIX)
  8381. )});`;
  8382. }
  8383. return dynamicImports;
  8384. }
  8385. function isDynamicModuleImport(id, dynamicRequireModuleSet) {
  8386. const normalizedPath = normalizePathSlashes(id);
  8387. return dynamicRequireModuleSet.has(normalizedPath) && !normalizedPath.endsWith('.json');
  8388. }
  8389. function isDirectory(path) {
  8390. try {
  8391. if (fs$n.statSync(path).isDirectory()) return true;
  8392. } catch (ignored) {
  8393. // Nothing to do here
  8394. }
  8395. return false;
  8396. }
  8397. function getDynamicRequirePaths(patterns) {
  8398. const dynamicRequireModuleSet = new Set();
  8399. for (const pattern of !patterns || Array.isArray(patterns) ? patterns || [] : [patterns]) {
  8400. const isNegated = pattern.startsWith('!');
  8401. const modifySet = Set.prototype[isNegated ? 'delete' : 'add'].bind(dynamicRequireModuleSet);
  8402. for (const path of glob_1.sync(isNegated ? pattern.substr(1) : pattern)) {
  8403. modifySet(normalizePathSlashes(path$r.resolve(path)));
  8404. if (isDirectory(path)) {
  8405. modifySet(normalizePathSlashes(path$r.resolve(path$r.join(path, getPackageEntryPoint(path)))));
  8406. }
  8407. }
  8408. }
  8409. const dynamicRequireModuleDirPaths = Array.from(dynamicRequireModuleSet.values()).filter((path) =>
  8410. isDirectory(path)
  8411. );
  8412. return { dynamicRequireModuleSet, dynamicRequireModuleDirPaths };
  8413. }
  8414. function getCommonJSMetaPromise(commonJSMetaPromises, id) {
  8415. let commonJSMetaPromise = commonJSMetaPromises.get(id);
  8416. if (commonJSMetaPromise) return commonJSMetaPromise.promise;
  8417. const promise = new Promise((resolve) => {
  8418. commonJSMetaPromise = {
  8419. resolve,
  8420. promise: null
  8421. };
  8422. commonJSMetaPromises.set(id, commonJSMetaPromise);
  8423. });
  8424. commonJSMetaPromise.promise = promise;
  8425. return promise;
  8426. }
  8427. function setCommonJSMetaPromise(commonJSMetaPromises, id, commonjsMeta) {
  8428. const commonJSMetaPromise = commonJSMetaPromises.get(id);
  8429. if (commonJSMetaPromise) {
  8430. if (commonJSMetaPromise.resolve) {
  8431. commonJSMetaPromise.resolve(commonjsMeta);
  8432. commonJSMetaPromise.resolve = null;
  8433. }
  8434. } else {
  8435. commonJSMetaPromises.set(id, { promise: Promise.resolve(commonjsMeta), resolve: null });
  8436. }
  8437. }
  8438. // e.g. id === "commonjsHelpers?commonjsRegister"
  8439. function getSpecificHelperProxy(id) {
  8440. return `export {${id.split('?')[1]} as default} from "${HELPERS_ID}";`;
  8441. }
  8442. function getUnknownRequireProxy(id, requireReturnsDefault) {
  8443. if (requireReturnsDefault === true || id.endsWith('.json')) {
  8444. return `export {default} from ${JSON.stringify(id)};`;
  8445. }
  8446. const name = getName(id);
  8447. const exported =
  8448. requireReturnsDefault === 'auto'
  8449. ? `import {getDefaultExportFromNamespaceIfNotNamed} from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfNotNamed(${name});`
  8450. : requireReturnsDefault === 'preferred'
  8451. ? `import {getDefaultExportFromNamespaceIfPresent} from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfPresent(${name});`
  8452. : !requireReturnsDefault
  8453. ? `import {getAugmentedNamespace} from "${HELPERS_ID}"; export default /*@__PURE__*/getAugmentedNamespace(${name});`
  8454. : `export default ${name};`;
  8455. return `import * as ${name} from ${JSON.stringify(id)}; ${exported}`;
  8456. }
  8457. function getDynamicJsonProxy(id, commonDir) {
  8458. const normalizedPath = normalizePathSlashes(id.slice(DYNAMIC_JSON_PREFIX.length));
  8459. return `const commonjsRegister = require('${HELPERS_ID}?commonjsRegister');\ncommonjsRegister(${JSON.stringify(
  8460. getVirtualPathForDynamicRequirePath(normalizedPath, commonDir)
  8461. )}, function (module, exports) {
  8462. module.exports = require(${JSON.stringify(normalizedPath)});
  8463. });`;
  8464. }
  8465. function getDynamicRequireProxy(normalizedPath, commonDir) {
  8466. return `const commonjsRegister = require('${HELPERS_ID}?commonjsRegister');\ncommonjsRegister(${JSON.stringify(
  8467. getVirtualPathForDynamicRequirePath(normalizedPath, commonDir)
  8468. )}, function (module, exports) {
  8469. ${fs$n.readFileSync(normalizedPath, { encoding: 'utf8' })}
  8470. });`;
  8471. }
  8472. async function getStaticRequireProxy(
  8473. id,
  8474. requireReturnsDefault,
  8475. esModulesWithDefaultExport,
  8476. esModulesWithNamedExports,
  8477. commonJsMetaPromises
  8478. ) {
  8479. const name = getName(id);
  8480. const commonjsMeta = await getCommonJSMetaPromise(commonJsMetaPromises, id);
  8481. if (commonjsMeta && commonjsMeta.isCommonJS) {
  8482. return `export { __moduleExports as default } from ${JSON.stringify(id)};`;
  8483. } else if (commonjsMeta === null) {
  8484. return getUnknownRequireProxy(id, requireReturnsDefault);
  8485. } else if (!requireReturnsDefault) {
  8486. return `import { getAugmentedNamespace } from "${HELPERS_ID}"; import * as ${name} from ${JSON.stringify(
  8487. id
  8488. )}; export default /*@__PURE__*/getAugmentedNamespace(${name});`;
  8489. } else if (
  8490. requireReturnsDefault !== true &&
  8491. (requireReturnsDefault === 'namespace' ||
  8492. !esModulesWithDefaultExport.has(id) ||
  8493. (requireReturnsDefault === 'auto' && esModulesWithNamedExports.has(id)))
  8494. ) {
  8495. return `import * as ${name} from ${JSON.stringify(id)}; export default ${name};`;
  8496. }
  8497. return `export { default } from ${JSON.stringify(id)};`;
  8498. }
  8499. /* eslint-disable no-param-reassign, no-undefined */
  8500. function getCandidatesForExtension(resolved, extension) {
  8501. return [resolved + extension, `${resolved}${path$r.sep}index${extension}`];
  8502. }
  8503. function getCandidates(resolved, extensions) {
  8504. return extensions.reduce(
  8505. (paths, extension) => paths.concat(getCandidatesForExtension(resolved, extension)),
  8506. [resolved]
  8507. );
  8508. }
  8509. function getResolveId(extensions) {
  8510. function resolveExtensions(importee, importer) {
  8511. // not our problem
  8512. if (importee[0] !== '.' || !importer) return undefined;
  8513. const resolved = path$r.resolve(path$r.dirname(importer), importee);
  8514. const candidates = getCandidates(resolved, extensions);
  8515. for (let i = 0; i < candidates.length; i += 1) {
  8516. try {
  8517. const stats = fs$n.statSync(candidates[i]);
  8518. if (stats.isFile()) return { id: candidates[i] };
  8519. } catch (err) {
  8520. /* noop */
  8521. }
  8522. }
  8523. return undefined;
  8524. }
  8525. return function resolveId(importee, rawImporter, resolveOptions) {
  8526. if (isWrappedId(importee, MODULE_SUFFIX) || isWrappedId(importee, EXPORTS_SUFFIX)) {
  8527. return importee;
  8528. }
  8529. const importer =
  8530. rawImporter && isWrappedId(rawImporter, DYNAMIC_REGISTER_SUFFIX)
  8531. ? unwrapId$1(rawImporter, DYNAMIC_REGISTER_SUFFIX)
  8532. : rawImporter;
  8533. // Except for exports, proxies are only importing resolved ids,
  8534. // no need to resolve again
  8535. if (importer && isWrappedId(importer, PROXY_SUFFIX)) {
  8536. return importee;
  8537. }
  8538. const isProxyModule = isWrappedId(importee, PROXY_SUFFIX);
  8539. const isRequiredModule = isWrappedId(importee, REQUIRE_SUFFIX);
  8540. let isModuleRegistration = false;
  8541. if (isProxyModule) {
  8542. importee = unwrapId$1(importee, PROXY_SUFFIX);
  8543. } else if (isRequiredModule) {
  8544. importee = unwrapId$1(importee, REQUIRE_SUFFIX);
  8545. isModuleRegistration = isWrappedId(importee, DYNAMIC_REGISTER_SUFFIX);
  8546. if (isModuleRegistration) {
  8547. importee = unwrapId$1(importee, DYNAMIC_REGISTER_SUFFIX);
  8548. }
  8549. }
  8550. if (
  8551. importee.startsWith(HELPERS_ID) ||
  8552. importee === DYNAMIC_PACKAGES_ID ||
  8553. importee.startsWith(DYNAMIC_JSON_PREFIX)
  8554. ) {
  8555. return importee;
  8556. }
  8557. if (importee.startsWith('\0')) {
  8558. return null;
  8559. }
  8560. return this.resolve(
  8561. importee,
  8562. importer,
  8563. Object.assign({}, resolveOptions, {
  8564. skipSelf: true,
  8565. custom: Object.assign({}, resolveOptions.custom, {
  8566. 'node-resolve': { isRequire: isProxyModule || isRequiredModule }
  8567. })
  8568. })
  8569. ).then((resolved) => {
  8570. if (!resolved) {
  8571. resolved = resolveExtensions(importee, importer);
  8572. }
  8573. if (resolved && isProxyModule) {
  8574. resolved.id = wrapId(resolved.id, resolved.external ? EXTERNAL_SUFFIX : PROXY_SUFFIX);
  8575. resolved.external = false;
  8576. } else if (resolved && isModuleRegistration) {
  8577. resolved.id = wrapId(resolved.id, DYNAMIC_REGISTER_SUFFIX);
  8578. } else if (!resolved && (isProxyModule || isRequiredModule)) {
  8579. return { id: wrapId(importee, EXTERNAL_SUFFIX), external: false };
  8580. }
  8581. return resolved;
  8582. });
  8583. };
  8584. }
  8585. function validateRollupVersion(rollupVersion, peerDependencyVersion) {
  8586. const [major, minor] = rollupVersion.split('.').map(Number);
  8587. const versionRegexp = /\^(\d+\.\d+)\.\d+/g;
  8588. let minMajor = Infinity;
  8589. let minMinor = Infinity;
  8590. let foundVersion;
  8591. // eslint-disable-next-line no-cond-assign
  8592. while ((foundVersion = versionRegexp.exec(peerDependencyVersion))) {
  8593. const [foundMajor, foundMinor] = foundVersion[1].split('.').map(Number);
  8594. if (foundMajor < minMajor) {
  8595. minMajor = foundMajor;
  8596. minMinor = foundMinor;
  8597. }
  8598. }
  8599. if (major < minMajor || (major === minMajor && minor < minMinor)) {
  8600. throw new Error(
  8601. `Insufficient Rollup version: "@rollup/plugin-commonjs" requires at least rollup@${minMajor}.${minMinor} but found rollup@${rollupVersion}.`
  8602. );
  8603. }
  8604. }
  8605. const operators = {
  8606. '==': (x) => equals(x.left, x.right, false),
  8607. '!=': (x) => not(operators['=='](x)),
  8608. '===': (x) => equals(x.left, x.right, true),
  8609. '!==': (x) => not(operators['==='](x)),
  8610. '!': (x) => isFalsy(x.argument),
  8611. '&&': (x) => isTruthy(x.left) && isTruthy(x.right),
  8612. '||': (x) => isTruthy(x.left) || isTruthy(x.right)
  8613. };
  8614. function not(value) {
  8615. return value === null ? value : !value;
  8616. }
  8617. function equals(a, b, strict) {
  8618. if (a.type !== b.type) return null;
  8619. // eslint-disable-next-line eqeqeq
  8620. if (a.type === 'Literal') return strict ? a.value === b.value : a.value == b.value;
  8621. return null;
  8622. }
  8623. function isTruthy(node) {
  8624. if (!node) return false;
  8625. if (node.type === 'Literal') return !!node.value;
  8626. if (node.type === 'ParenthesizedExpression') return isTruthy(node.expression);
  8627. if (node.operator in operators) return operators[node.operator](node);
  8628. return null;
  8629. }
  8630. function isFalsy(node) {
  8631. return not(isTruthy(node));
  8632. }
  8633. function getKeypath(node) {
  8634. const parts = [];
  8635. while (node.type === 'MemberExpression') {
  8636. if (node.computed) return null;
  8637. parts.unshift(node.property.name);
  8638. // eslint-disable-next-line no-param-reassign
  8639. node = node.object;
  8640. }
  8641. if (node.type !== 'Identifier') return null;
  8642. const { name } = node;
  8643. parts.unshift(name);
  8644. return { name, keypath: parts.join('.') };
  8645. }
  8646. const KEY_COMPILED_ESM = '__esModule';
  8647. function isDefineCompiledEsm(node) {
  8648. const definedProperty =
  8649. getDefinePropertyCallName(node, 'exports') || getDefinePropertyCallName(node, 'module.exports');
  8650. if (definedProperty && definedProperty.key === KEY_COMPILED_ESM) {
  8651. return isTruthy(definedProperty.value);
  8652. }
  8653. return false;
  8654. }
  8655. function getDefinePropertyCallName(node, targetName) {
  8656. const {
  8657. callee: { object, property }
  8658. } = node;
  8659. if (!object || object.type !== 'Identifier' || object.name !== 'Object') return;
  8660. if (!property || property.type !== 'Identifier' || property.name !== 'defineProperty') return;
  8661. if (node.arguments.length !== 3) return;
  8662. const targetNames = targetName.split('.');
  8663. const [target, key, value] = node.arguments;
  8664. if (targetNames.length === 1) {
  8665. if (target.type !== 'Identifier' || target.name !== targetNames[0]) {
  8666. return;
  8667. }
  8668. }
  8669. if (targetNames.length === 2) {
  8670. if (
  8671. target.type !== 'MemberExpression' ||
  8672. target.object.name !== targetNames[0] ||
  8673. target.property.name !== targetNames[1]
  8674. ) {
  8675. return;
  8676. }
  8677. }
  8678. if (value.type !== 'ObjectExpression' || !value.properties) return;
  8679. const valueProperty = value.properties.find((p) => p.key && p.key.name === 'value');
  8680. if (!valueProperty || !valueProperty.value) return;
  8681. // eslint-disable-next-line consistent-return
  8682. return { key: key.value, value: valueProperty.value };
  8683. }
  8684. function isShorthandProperty(parent) {
  8685. return parent && parent.type === 'Property' && parent.shorthand;
  8686. }
  8687. function hasDefineEsmProperty(node) {
  8688. return node.properties.some((property) => {
  8689. if (
  8690. property.type === 'Property' &&
  8691. property.key.type === 'Identifier' &&
  8692. property.key.name === '__esModule' &&
  8693. isTruthy(property.value)
  8694. ) {
  8695. return true;
  8696. }
  8697. return false;
  8698. });
  8699. }
  8700. function wrapCode(magicString, uses, moduleName, exportsName) {
  8701. const args = [];
  8702. const passedArgs = [];
  8703. if (uses.module) {
  8704. args.push('module');
  8705. passedArgs.push(moduleName);
  8706. }
  8707. if (uses.exports) {
  8708. args.push('exports');
  8709. passedArgs.push(exportsName);
  8710. }
  8711. magicString
  8712. .trim()
  8713. .prepend(`(function (${args.join(', ')}) {\n`)
  8714. .append(`\n}(${passedArgs.join(', ')}));`);
  8715. }
  8716. function rewriteExportsAndGetExportsBlock(
  8717. magicString,
  8718. moduleName,
  8719. exportsName,
  8720. wrapped,
  8721. moduleExportsAssignments,
  8722. firstTopLevelModuleExportsAssignment,
  8723. exportsAssignmentsByName,
  8724. topLevelAssignments,
  8725. defineCompiledEsmExpressions,
  8726. deconflictedExportNames,
  8727. code,
  8728. HELPERS_NAME,
  8729. exportMode,
  8730. detectWrappedDefault,
  8731. defaultIsModuleExports
  8732. ) {
  8733. const exports = [];
  8734. const exportDeclarations = [];
  8735. if (exportMode === 'replace') {
  8736. getExportsForReplacedModuleExports(
  8737. magicString,
  8738. exports,
  8739. exportDeclarations,
  8740. moduleExportsAssignments,
  8741. firstTopLevelModuleExportsAssignment,
  8742. exportsName
  8743. );
  8744. } else {
  8745. exports.push(`${exportsName} as __moduleExports`);
  8746. if (wrapped) {
  8747. getExportsWhenWrapping(
  8748. exportDeclarations,
  8749. exportsName,
  8750. detectWrappedDefault,
  8751. HELPERS_NAME,
  8752. defaultIsModuleExports
  8753. );
  8754. } else {
  8755. getExports(
  8756. magicString,
  8757. exports,
  8758. exportDeclarations,
  8759. moduleExportsAssignments,
  8760. exportsAssignmentsByName,
  8761. deconflictedExportNames,
  8762. topLevelAssignments,
  8763. moduleName,
  8764. exportsName,
  8765. defineCompiledEsmExpressions,
  8766. HELPERS_NAME,
  8767. defaultIsModuleExports
  8768. );
  8769. }
  8770. }
  8771. if (exports.length) {
  8772. exportDeclarations.push(`export { ${exports.join(', ')} };`);
  8773. }
  8774. return `\n\n${exportDeclarations.join('\n')}`;
  8775. }
  8776. function getExportsForReplacedModuleExports(
  8777. magicString,
  8778. exports,
  8779. exportDeclarations,
  8780. moduleExportsAssignments,
  8781. firstTopLevelModuleExportsAssignment,
  8782. exportsName
  8783. ) {
  8784. for (const { left } of moduleExportsAssignments) {
  8785. magicString.overwrite(left.start, left.end, exportsName);
  8786. }
  8787. magicString.prependRight(firstTopLevelModuleExportsAssignment.left.start, 'var ');
  8788. exports.push(`${exportsName} as __moduleExports`);
  8789. exportDeclarations.push(`export default ${exportsName};`);
  8790. }
  8791. function getExportsWhenWrapping(
  8792. exportDeclarations,
  8793. exportsName,
  8794. detectWrappedDefault,
  8795. HELPERS_NAME,
  8796. defaultIsModuleExports
  8797. ) {
  8798. exportDeclarations.push(
  8799. `export default ${
  8800. detectWrappedDefault && defaultIsModuleExports === 'auto'
  8801. ? `/*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${exportsName})`
  8802. : defaultIsModuleExports === false
  8803. ? `${exportsName}.default`
  8804. : exportsName
  8805. };`
  8806. );
  8807. }
  8808. function getExports(
  8809. magicString,
  8810. exports,
  8811. exportDeclarations,
  8812. moduleExportsAssignments,
  8813. exportsAssignmentsByName,
  8814. deconflictedExportNames,
  8815. topLevelAssignments,
  8816. moduleName,
  8817. exportsName,
  8818. defineCompiledEsmExpressions,
  8819. HELPERS_NAME,
  8820. defaultIsModuleExports
  8821. ) {
  8822. let deconflictedDefaultExportName;
  8823. // Collect and rewrite module.exports assignments
  8824. for (const { left } of moduleExportsAssignments) {
  8825. magicString.overwrite(left.start, left.end, `${moduleName}.exports`);
  8826. }
  8827. // Collect and rewrite named exports
  8828. for (const [exportName, { nodes }] of exportsAssignmentsByName) {
  8829. const deconflicted = deconflictedExportNames[exportName];
  8830. let needsDeclaration = true;
  8831. for (const node of nodes) {
  8832. let replacement = `${deconflicted} = ${exportsName}.${exportName}`;
  8833. if (needsDeclaration && topLevelAssignments.has(node)) {
  8834. replacement = `var ${replacement}`;
  8835. needsDeclaration = false;
  8836. }
  8837. magicString.overwrite(node.start, node.left.end, replacement);
  8838. }
  8839. if (needsDeclaration) {
  8840. magicString.prepend(`var ${deconflicted};\n`);
  8841. }
  8842. if (exportName === 'default') {
  8843. deconflictedDefaultExportName = deconflicted;
  8844. } else {
  8845. exports.push(exportName === deconflicted ? exportName : `${deconflicted} as ${exportName}`);
  8846. }
  8847. }
  8848. // Collect and rewrite exports.__esModule assignments
  8849. let isRestorableCompiledEsm = false;
  8850. for (const expression of defineCompiledEsmExpressions) {
  8851. isRestorableCompiledEsm = true;
  8852. const moduleExportsExpression =
  8853. expression.type === 'CallExpression' ? expression.arguments[0] : expression.left.object;
  8854. magicString.overwrite(moduleExportsExpression.start, moduleExportsExpression.end, exportsName);
  8855. }
  8856. if (!isRestorableCompiledEsm || defaultIsModuleExports === true) {
  8857. exportDeclarations.push(`export default ${exportsName};`);
  8858. } else if (moduleExportsAssignments.length === 0 || defaultIsModuleExports === false) {
  8859. exports.push(`${deconflictedDefaultExportName || exportsName} as default`);
  8860. } else {
  8861. exportDeclarations.push(
  8862. `export default /*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${exportsName});`
  8863. );
  8864. }
  8865. }
  8866. function isRequireStatement(node, scope) {
  8867. if (!node) return false;
  8868. if (node.type !== 'CallExpression') return false;
  8869. // Weird case of `require()` or `module.require()` without arguments
  8870. if (node.arguments.length === 0) return false;
  8871. return isRequire(node.callee, scope);
  8872. }
  8873. function isRequire(node, scope) {
  8874. return (
  8875. (node.type === 'Identifier' && node.name === 'require' && !scope.contains('require')) ||
  8876. (node.type === 'MemberExpression' && isModuleRequire(node, scope))
  8877. );
  8878. }
  8879. function isModuleRequire({ object, property }, scope) {
  8880. return (
  8881. object.type === 'Identifier' &&
  8882. object.name === 'module' &&
  8883. property.type === 'Identifier' &&
  8884. property.name === 'require' &&
  8885. !scope.contains('module')
  8886. );
  8887. }
  8888. function isStaticRequireStatement(node, scope) {
  8889. if (!isRequireStatement(node, scope)) return false;
  8890. return !hasDynamicArguments(node);
  8891. }
  8892. function hasDynamicArguments(node) {
  8893. return (
  8894. node.arguments.length > 1 ||
  8895. (node.arguments[0].type !== 'Literal' &&
  8896. (node.arguments[0].type !== 'TemplateLiteral' || node.arguments[0].expressions.length > 0))
  8897. );
  8898. }
  8899. const reservedMethod = { resolve: true, cache: true, main: true };
  8900. function isNodeRequirePropertyAccess(parent) {
  8901. return parent && parent.property && reservedMethod[parent.property.name];
  8902. }
  8903. function isIgnoredRequireStatement(requiredNode, ignoreRequire) {
  8904. return ignoreRequire(requiredNode.arguments[0].value);
  8905. }
  8906. function getRequireStringArg(node) {
  8907. return node.arguments[0].type === 'Literal'
  8908. ? node.arguments[0].value
  8909. : node.arguments[0].quasis[0].value.cooked;
  8910. }
  8911. function hasDynamicModuleForPath(source, id, dynamicRequireModuleSet) {
  8912. if (!/^(?:\.{0,2}[/\\]|[A-Za-z]:[/\\])/.test(source)) {
  8913. try {
  8914. const resolvedPath = normalizePathSlashes(resolve$4.sync(source, { basedir: path$r.dirname(id) }));
  8915. if (dynamicRequireModuleSet.has(resolvedPath)) {
  8916. return true;
  8917. }
  8918. } catch (ex) {
  8919. // Probably a node.js internal module
  8920. return false;
  8921. }
  8922. return false;
  8923. }
  8924. for (const attemptExt of ['', '.js', '.json']) {
  8925. const resolvedPath = normalizePathSlashes(path$r.resolve(path$r.dirname(id), source + attemptExt));
  8926. if (dynamicRequireModuleSet.has(resolvedPath)) {
  8927. return true;
  8928. }
  8929. }
  8930. return false;
  8931. }
  8932. function getRequireHandlers() {
  8933. const requiredSources = [];
  8934. const requiredBySource = Object.create(null);
  8935. const requiredByNode = new Map();
  8936. const requireExpressionsWithUsedReturnValue = [];
  8937. function addRequireStatement(sourceId, node, scope, usesReturnValue) {
  8938. const required = getRequired(sourceId);
  8939. requiredByNode.set(node, { scope, required });
  8940. if (usesReturnValue) {
  8941. required.nodesUsingRequired.push(node);
  8942. requireExpressionsWithUsedReturnValue.push(node);
  8943. }
  8944. }
  8945. function getRequired(sourceId) {
  8946. if (!requiredBySource[sourceId]) {
  8947. requiredSources.push(sourceId);
  8948. requiredBySource[sourceId] = {
  8949. source: sourceId,
  8950. name: null,
  8951. nodesUsingRequired: []
  8952. };
  8953. }
  8954. return requiredBySource[sourceId];
  8955. }
  8956. function rewriteRequireExpressionsAndGetImportBlock(
  8957. magicString,
  8958. topLevelDeclarations,
  8959. topLevelRequireDeclarators,
  8960. reassignedNames,
  8961. helpersName,
  8962. dynamicRegisterSources,
  8963. moduleName,
  8964. exportsName,
  8965. id,
  8966. exportMode
  8967. ) {
  8968. setRemainingImportNamesAndRewriteRequires(
  8969. requireExpressionsWithUsedReturnValue,
  8970. requiredByNode,
  8971. magicString
  8972. );
  8973. const imports = [];
  8974. imports.push(`import * as ${helpersName} from "${HELPERS_ID}";`);
  8975. if (exportMode === 'module') {
  8976. imports.push(
  8977. `import { __module as ${moduleName}, exports as ${exportsName} } from ${JSON.stringify(
  8978. wrapId(id, MODULE_SUFFIX)
  8979. )}`
  8980. );
  8981. } else if (exportMode === 'exports') {
  8982. imports.push(
  8983. `import { __exports as ${exportsName} } from ${JSON.stringify(wrapId(id, EXPORTS_SUFFIX))}`
  8984. );
  8985. }
  8986. for (const source of dynamicRegisterSources) {
  8987. imports.push(`import ${JSON.stringify(wrapId(source, REQUIRE_SUFFIX))};`);
  8988. }
  8989. for (const source of requiredSources) {
  8990. if (!source.startsWith('\0')) {
  8991. imports.push(`import ${JSON.stringify(wrapId(source, REQUIRE_SUFFIX))};`);
  8992. }
  8993. const { name, nodesUsingRequired } = requiredBySource[source];
  8994. imports.push(
  8995. `import ${nodesUsingRequired.length ? `${name} from ` : ''}${JSON.stringify(
  8996. source.startsWith('\0') ? source : wrapId(source, PROXY_SUFFIX)
  8997. )};`
  8998. );
  8999. }
  9000. return imports.length ? `${imports.join('\n')}\n\n` : '';
  9001. }
  9002. return {
  9003. addRequireStatement,
  9004. requiredSources,
  9005. rewriteRequireExpressionsAndGetImportBlock
  9006. };
  9007. }
  9008. function setRemainingImportNamesAndRewriteRequires(
  9009. requireExpressionsWithUsedReturnValue,
  9010. requiredByNode,
  9011. magicString
  9012. ) {
  9013. let uid = 0;
  9014. for (const requireExpression of requireExpressionsWithUsedReturnValue) {
  9015. const { required } = requiredByNode.get(requireExpression);
  9016. if (!required.name) {
  9017. let potentialName;
  9018. const isUsedName = (node) => requiredByNode.get(node).scope.contains(potentialName);
  9019. do {
  9020. potentialName = `require$$${uid}`;
  9021. uid += 1;
  9022. } while (required.nodesUsingRequired.some(isUsedName));
  9023. required.name = potentialName;
  9024. }
  9025. magicString.overwrite(requireExpression.start, requireExpression.end, required.name);
  9026. }
  9027. }
  9028. /* eslint-disable no-param-reassign, no-shadow, no-underscore-dangle, no-continue */
  9029. const exportsPattern = /^(?:module\.)?exports(?:\.([a-zA-Z_$][a-zA-Z_$0-9]*))?$/;
  9030. const functionType = /^(?:FunctionDeclaration|FunctionExpression|ArrowFunctionExpression)$/;
  9031. function transformCommonjs(
  9032. parse,
  9033. code,
  9034. id,
  9035. isEsModule,
  9036. ignoreGlobal,
  9037. ignoreRequire,
  9038. ignoreDynamicRequires,
  9039. getIgnoreTryCatchRequireStatementMode,
  9040. sourceMap,
  9041. isDynamicRequireModulesEnabled,
  9042. dynamicRequireModuleSet,
  9043. disableWrap,
  9044. commonDir,
  9045. astCache,
  9046. defaultIsModuleExports
  9047. ) {
  9048. const ast = astCache || tryParse(parse, code, id);
  9049. const magicString = new MagicString$1(code);
  9050. const uses = {
  9051. module: false,
  9052. exports: false,
  9053. global: false,
  9054. require: false
  9055. };
  9056. let usesDynamicRequire = false;
  9057. const virtualDynamicRequirePath =
  9058. isDynamicRequireModulesEnabled && getVirtualPathForDynamicRequirePath(path$r.dirname(id), commonDir);
  9059. let scope = attachScopes(ast, 'scope');
  9060. let lexicalDepth = 0;
  9061. let programDepth = 0;
  9062. let currentTryBlockEnd = null;
  9063. let shouldWrap = false;
  9064. const globals = new Set();
  9065. // TODO technically wrong since globals isn't populated yet, but ¯\_(ツ)_/¯
  9066. const HELPERS_NAME = deconflict([scope], globals, 'commonjsHelpers');
  9067. const dynamicRegisterSources = new Set();
  9068. let hasRemovedRequire = false;
  9069. const {
  9070. addRequireStatement,
  9071. requiredSources,
  9072. rewriteRequireExpressionsAndGetImportBlock
  9073. } = getRequireHandlers();
  9074. // See which names are assigned to. This is necessary to prevent
  9075. // illegally replacing `var foo = require('foo')` with `import foo from 'foo'`,
  9076. // where `foo` is later reassigned. (This happens in the wild. CommonJS, sigh)
  9077. const reassignedNames = new Set();
  9078. const topLevelDeclarations = [];
  9079. const topLevelRequireDeclarators = new Set();
  9080. const skippedNodes = new Set();
  9081. const moduleAccessScopes = new Set([scope]);
  9082. const exportsAccessScopes = new Set([scope]);
  9083. const moduleExportsAssignments = [];
  9084. let firstTopLevelModuleExportsAssignment = null;
  9085. const exportsAssignmentsByName = new Map();
  9086. const topLevelAssignments = new Set();
  9087. const topLevelDefineCompiledEsmExpressions = [];
  9088. walk$2(ast, {
  9089. enter(node, parent) {
  9090. if (skippedNodes.has(node)) {
  9091. this.skip();
  9092. return;
  9093. }
  9094. if (currentTryBlockEnd !== null && node.start > currentTryBlockEnd) {
  9095. currentTryBlockEnd = null;
  9096. }
  9097. programDepth += 1;
  9098. if (node.scope) ({ scope } = node);
  9099. if (functionType.test(node.type)) lexicalDepth += 1;
  9100. if (sourceMap) {
  9101. magicString.addSourcemapLocation(node.start);
  9102. magicString.addSourcemapLocation(node.end);
  9103. }
  9104. // eslint-disable-next-line default-case
  9105. switch (node.type) {
  9106. case 'TryStatement':
  9107. if (currentTryBlockEnd === null) {
  9108. currentTryBlockEnd = node.block.end;
  9109. }
  9110. return;
  9111. case 'AssignmentExpression':
  9112. if (node.left.type === 'MemberExpression') {
  9113. const flattened = getKeypath(node.left);
  9114. if (!flattened || scope.contains(flattened.name)) return;
  9115. const exportsPatternMatch = exportsPattern.exec(flattened.keypath);
  9116. if (!exportsPatternMatch || flattened.keypath === 'exports') return;
  9117. const [, exportName] = exportsPatternMatch;
  9118. uses[flattened.name] = true;
  9119. // we're dealing with `module.exports = ...` or `[module.]exports.foo = ...` –
  9120. if (flattened.keypath === 'module.exports') {
  9121. moduleExportsAssignments.push(node);
  9122. if (programDepth > 3) {
  9123. moduleAccessScopes.add(scope);
  9124. } else if (!firstTopLevelModuleExportsAssignment) {
  9125. firstTopLevelModuleExportsAssignment = node;
  9126. }
  9127. if (defaultIsModuleExports === false) {
  9128. shouldWrap = true;
  9129. } else if (defaultIsModuleExports === 'auto') {
  9130. if (node.right.type === 'ObjectExpression') {
  9131. if (hasDefineEsmProperty(node.right)) {
  9132. shouldWrap = true;
  9133. }
  9134. } else if (defaultIsModuleExports === false) {
  9135. shouldWrap = true;
  9136. }
  9137. }
  9138. } else if (exportName === KEY_COMPILED_ESM) {
  9139. if (programDepth > 3) {
  9140. shouldWrap = true;
  9141. } else {
  9142. topLevelDefineCompiledEsmExpressions.push(node);
  9143. }
  9144. } else {
  9145. const exportsAssignments = exportsAssignmentsByName.get(exportName) || {
  9146. nodes: [],
  9147. scopes: new Set()
  9148. };
  9149. exportsAssignments.nodes.push(node);
  9150. exportsAssignments.scopes.add(scope);
  9151. exportsAccessScopes.add(scope);
  9152. exportsAssignmentsByName.set(exportName, exportsAssignments);
  9153. if (programDepth <= 3) {
  9154. topLevelAssignments.add(node);
  9155. }
  9156. }
  9157. skippedNodes.add(node.left);
  9158. } else {
  9159. for (const name of extractAssignedNames(node.left)) {
  9160. reassignedNames.add(name);
  9161. }
  9162. }
  9163. return;
  9164. case 'CallExpression': {
  9165. if (isDefineCompiledEsm(node)) {
  9166. if (programDepth === 3 && parent.type === 'ExpressionStatement') {
  9167. // skip special handling for [module.]exports until we know we render this
  9168. skippedNodes.add(node.arguments[0]);
  9169. topLevelDefineCompiledEsmExpressions.push(node);
  9170. } else {
  9171. shouldWrap = true;
  9172. }
  9173. return;
  9174. }
  9175. if (
  9176. node.callee.object &&
  9177. node.callee.object.name === 'require' &&
  9178. node.callee.property.name === 'resolve' &&
  9179. hasDynamicModuleForPath(id, '/', dynamicRequireModuleSet)
  9180. ) {
  9181. const requireNode = node.callee.object;
  9182. magicString.appendLeft(
  9183. node.end - 1,
  9184. `,${JSON.stringify(
  9185. path$r.dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
  9186. )}`
  9187. );
  9188. magicString.overwrite(
  9189. requireNode.start,
  9190. requireNode.end,
  9191. `${HELPERS_NAME}.commonjsRequire`,
  9192. {
  9193. storeName: true
  9194. }
  9195. );
  9196. return;
  9197. }
  9198. if (!isStaticRequireStatement(node, scope)) return;
  9199. if (!isDynamicRequireModulesEnabled) {
  9200. skippedNodes.add(node.callee);
  9201. }
  9202. if (!isIgnoredRequireStatement(node, ignoreRequire)) {
  9203. skippedNodes.add(node.callee);
  9204. const usesReturnValue = parent.type !== 'ExpressionStatement';
  9205. let canConvertRequire = true;
  9206. let shouldRemoveRequireStatement = false;
  9207. if (currentTryBlockEnd !== null) {
  9208. ({
  9209. canConvertRequire,
  9210. shouldRemoveRequireStatement
  9211. } = getIgnoreTryCatchRequireStatementMode(node.arguments[0].value));
  9212. if (shouldRemoveRequireStatement) {
  9213. hasRemovedRequire = true;
  9214. }
  9215. }
  9216. let sourceId = getRequireStringArg(node);
  9217. const isDynamicRegister = isWrappedId(sourceId, DYNAMIC_REGISTER_SUFFIX);
  9218. if (isDynamicRegister) {
  9219. sourceId = unwrapId$1(sourceId, DYNAMIC_REGISTER_SUFFIX);
  9220. if (sourceId.endsWith('.json')) {
  9221. sourceId = DYNAMIC_JSON_PREFIX + sourceId;
  9222. }
  9223. dynamicRegisterSources.add(wrapId(sourceId, DYNAMIC_REGISTER_SUFFIX));
  9224. } else {
  9225. if (
  9226. !sourceId.endsWith('.json') &&
  9227. hasDynamicModuleForPath(sourceId, id, dynamicRequireModuleSet)
  9228. ) {
  9229. if (shouldRemoveRequireStatement) {
  9230. magicString.overwrite(node.start, node.end, `undefined`);
  9231. } else if (canConvertRequire) {
  9232. magicString.overwrite(
  9233. node.start,
  9234. node.end,
  9235. `${HELPERS_NAME}.commonjsRequire(${JSON.stringify(
  9236. getVirtualPathForDynamicRequirePath(sourceId, commonDir)
  9237. )}, ${JSON.stringify(
  9238. path$r.dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
  9239. )})`
  9240. );
  9241. usesDynamicRequire = true;
  9242. }
  9243. return;
  9244. }
  9245. if (canConvertRequire) {
  9246. addRequireStatement(sourceId, node, scope, usesReturnValue);
  9247. }
  9248. }
  9249. if (usesReturnValue) {
  9250. if (shouldRemoveRequireStatement) {
  9251. magicString.overwrite(node.start, node.end, `undefined`);
  9252. return;
  9253. }
  9254. if (
  9255. parent.type === 'VariableDeclarator' &&
  9256. !scope.parent &&
  9257. parent.id.type === 'Identifier'
  9258. ) {
  9259. // This will allow us to reuse this variable name as the imported variable if it is not reassigned
  9260. // and does not conflict with variables in other places where this is imported
  9261. topLevelRequireDeclarators.add(parent);
  9262. }
  9263. } else {
  9264. // This is a bare import, e.g. `require('foo');`
  9265. if (!canConvertRequire && !shouldRemoveRequireStatement) {
  9266. return;
  9267. }
  9268. magicString.remove(parent.start, parent.end);
  9269. }
  9270. }
  9271. return;
  9272. }
  9273. case 'ConditionalExpression':
  9274. case 'IfStatement':
  9275. // skip dead branches
  9276. if (isFalsy(node.test)) {
  9277. skippedNodes.add(node.consequent);
  9278. } else if (node.alternate && isTruthy(node.test)) {
  9279. skippedNodes.add(node.alternate);
  9280. }
  9281. return;
  9282. case 'Identifier': {
  9283. const { name } = node;
  9284. if (!(isReference(node, parent) && !scope.contains(name))) return;
  9285. switch (name) {
  9286. case 'require':
  9287. if (isNodeRequirePropertyAccess(parent)) {
  9288. if (hasDynamicModuleForPath(id, '/', dynamicRequireModuleSet)) {
  9289. if (parent.property.name === 'cache') {
  9290. magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
  9291. storeName: true
  9292. });
  9293. }
  9294. }
  9295. return;
  9296. }
  9297. if (isDynamicRequireModulesEnabled && isRequireStatement(parent, scope)) {
  9298. magicString.appendLeft(
  9299. parent.end - 1,
  9300. `,${JSON.stringify(
  9301. path$r.dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath
  9302. )}`
  9303. );
  9304. }
  9305. if (!ignoreDynamicRequires) {
  9306. if (isShorthandProperty(parent)) {
  9307. magicString.appendRight(node.end, `: ${HELPERS_NAME}.commonjsRequire`);
  9308. } else {
  9309. magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
  9310. storeName: true
  9311. });
  9312. }
  9313. }
  9314. usesDynamicRequire = true;
  9315. return;
  9316. case 'module':
  9317. case 'exports':
  9318. shouldWrap = true;
  9319. uses[name] = true;
  9320. return;
  9321. case 'global':
  9322. uses.global = true;
  9323. if (!ignoreGlobal) {
  9324. magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, {
  9325. storeName: true
  9326. });
  9327. }
  9328. return;
  9329. case 'define':
  9330. magicString.overwrite(node.start, node.end, 'undefined', {
  9331. storeName: true
  9332. });
  9333. return;
  9334. default:
  9335. globals.add(name);
  9336. return;
  9337. }
  9338. }
  9339. case 'MemberExpression':
  9340. if (!isDynamicRequireModulesEnabled && isModuleRequire(node, scope)) {
  9341. magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
  9342. storeName: true
  9343. });
  9344. skippedNodes.add(node.object);
  9345. skippedNodes.add(node.property);
  9346. }
  9347. return;
  9348. case 'ReturnStatement':
  9349. // if top-level return, we need to wrap it
  9350. if (lexicalDepth === 0) {
  9351. shouldWrap = true;
  9352. }
  9353. return;
  9354. case 'ThisExpression':
  9355. // rewrite top-level `this` as `commonjsHelpers.commonjsGlobal`
  9356. if (lexicalDepth === 0) {
  9357. uses.global = true;
  9358. if (!ignoreGlobal) {
  9359. magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, {
  9360. storeName: true
  9361. });
  9362. }
  9363. }
  9364. return;
  9365. case 'UnaryExpression':
  9366. // rewrite `typeof module`, `typeof module.exports` and `typeof exports` (https://github.com/rollup/rollup-plugin-commonjs/issues/151)
  9367. if (node.operator === 'typeof') {
  9368. const flattened = getKeypath(node.argument);
  9369. if (!flattened) return;
  9370. if (scope.contains(flattened.name)) return;
  9371. if (
  9372. flattened.keypath === 'module.exports' ||
  9373. flattened.keypath === 'module' ||
  9374. flattened.keypath === 'exports'
  9375. ) {
  9376. magicString.overwrite(node.start, node.end, `'object'`, {
  9377. storeName: false
  9378. });
  9379. }
  9380. }
  9381. return;
  9382. case 'VariableDeclaration':
  9383. if (!scope.parent) {
  9384. topLevelDeclarations.push(node);
  9385. }
  9386. }
  9387. },
  9388. leave(node) {
  9389. programDepth -= 1;
  9390. if (node.scope) scope = scope.parent;
  9391. if (functionType.test(node.type)) lexicalDepth -= 1;
  9392. }
  9393. });
  9394. const nameBase = getName(id);
  9395. const exportsName = deconflict([...exportsAccessScopes], globals, nameBase);
  9396. const moduleName = deconflict([...moduleAccessScopes], globals, `${nameBase}Module`);
  9397. const deconflictedExportNames = Object.create(null);
  9398. for (const [exportName, { scopes }] of exportsAssignmentsByName) {
  9399. deconflictedExportNames[exportName] = deconflict([...scopes], globals, exportName);
  9400. }
  9401. // We cannot wrap ES/mixed modules
  9402. shouldWrap =
  9403. !isEsModule &&
  9404. !disableWrap &&
  9405. (shouldWrap || (uses.exports && moduleExportsAssignments.length > 0));
  9406. const detectWrappedDefault =
  9407. shouldWrap &&
  9408. (topLevelDefineCompiledEsmExpressions.length > 0 || code.indexOf('__esModule') >= 0);
  9409. if (
  9410. !(
  9411. requiredSources.length ||
  9412. dynamicRegisterSources.size ||
  9413. uses.module ||
  9414. uses.exports ||
  9415. uses.require ||
  9416. usesDynamicRequire ||
  9417. hasRemovedRequire ||
  9418. topLevelDefineCompiledEsmExpressions.length > 0
  9419. ) &&
  9420. (ignoreGlobal || !uses.global)
  9421. ) {
  9422. return { meta: { commonjs: { isCommonJS: false } } };
  9423. }
  9424. let leadingComment = '';
  9425. if (code.startsWith('/*')) {
  9426. const commentEnd = code.indexOf('*/', 2) + 2;
  9427. leadingComment = `${code.slice(0, commentEnd)}\n`;
  9428. magicString.remove(0, commentEnd).trim();
  9429. }
  9430. const exportMode = shouldWrap
  9431. ? uses.module
  9432. ? 'module'
  9433. : 'exports'
  9434. : firstTopLevelModuleExportsAssignment
  9435. ? exportsAssignmentsByName.size === 0 && topLevelDefineCompiledEsmExpressions.length === 0
  9436. ? 'replace'
  9437. : 'module'
  9438. : moduleExportsAssignments.length === 0
  9439. ? 'exports'
  9440. : 'module';
  9441. const importBlock = rewriteRequireExpressionsAndGetImportBlock(
  9442. magicString,
  9443. topLevelDeclarations,
  9444. topLevelRequireDeclarators,
  9445. reassignedNames,
  9446. HELPERS_NAME,
  9447. dynamicRegisterSources,
  9448. moduleName,
  9449. exportsName,
  9450. id,
  9451. exportMode
  9452. );
  9453. const exportBlock = isEsModule
  9454. ? ''
  9455. : rewriteExportsAndGetExportsBlock(
  9456. magicString,
  9457. moduleName,
  9458. exportsName,
  9459. shouldWrap,
  9460. moduleExportsAssignments,
  9461. firstTopLevelModuleExportsAssignment,
  9462. exportsAssignmentsByName,
  9463. topLevelAssignments,
  9464. topLevelDefineCompiledEsmExpressions,
  9465. deconflictedExportNames,
  9466. code,
  9467. HELPERS_NAME,
  9468. exportMode,
  9469. detectWrappedDefault,
  9470. defaultIsModuleExports
  9471. );
  9472. if (shouldWrap) {
  9473. wrapCode(magicString, uses, moduleName, exportsName);
  9474. }
  9475. magicString
  9476. .trim()
  9477. .prepend(leadingComment + importBlock)
  9478. .append(exportBlock);
  9479. return {
  9480. code: magicString.toString(),
  9481. map: sourceMap ? magicString.generateMap() : null,
  9482. syntheticNamedExports: isEsModule ? false : '__moduleExports',
  9483. meta: { commonjs: { isCommonJS: !isEsModule } }
  9484. };
  9485. }
  9486. function commonjs(options = {}) {
  9487. const extensions = options.extensions || ['.js'];
  9488. const filter = createFilter(options.include, options.exclude);
  9489. const {
  9490. ignoreGlobal,
  9491. ignoreDynamicRequires,
  9492. requireReturnsDefault: requireReturnsDefaultOption,
  9493. defaultIsModuleExports: defaultIsModuleExportsOption,
  9494. esmExternals
  9495. } = options;
  9496. const getRequireReturnsDefault =
  9497. typeof requireReturnsDefaultOption === 'function'
  9498. ? requireReturnsDefaultOption
  9499. : () => requireReturnsDefaultOption;
  9500. let esmExternalIds;
  9501. const isEsmExternal =
  9502. typeof esmExternals === 'function'
  9503. ? esmExternals
  9504. : Array.isArray(esmExternals)
  9505. ? ((esmExternalIds = new Set(esmExternals)), (id) => esmExternalIds.has(id))
  9506. : () => esmExternals;
  9507. const getDefaultIsModuleExports =
  9508. typeof defaultIsModuleExportsOption === 'function'
  9509. ? defaultIsModuleExportsOption
  9510. : () =>
  9511. typeof defaultIsModuleExportsOption === 'boolean' ? defaultIsModuleExportsOption : 'auto';
  9512. const { dynamicRequireModuleSet, dynamicRequireModuleDirPaths } = getDynamicRequirePaths(
  9513. options.dynamicRequireTargets
  9514. );
  9515. const isDynamicRequireModulesEnabled = dynamicRequireModuleSet.size > 0;
  9516. const commonDir = isDynamicRequireModulesEnabled
  9517. ? commondir(null, Array.from(dynamicRequireModuleSet).concat(process.cwd()))
  9518. : null;
  9519. const esModulesWithDefaultExport = new Set();
  9520. const esModulesWithNamedExports = new Set();
  9521. const commonJsMetaPromises = new Map();
  9522. const ignoreRequire =
  9523. typeof options.ignore === 'function'
  9524. ? options.ignore
  9525. : Array.isArray(options.ignore)
  9526. ? (id) => options.ignore.includes(id)
  9527. : () => false;
  9528. const getIgnoreTryCatchRequireStatementMode = (id) => {
  9529. const mode =
  9530. typeof options.ignoreTryCatch === 'function'
  9531. ? options.ignoreTryCatch(id)
  9532. : Array.isArray(options.ignoreTryCatch)
  9533. ? options.ignoreTryCatch.includes(id)
  9534. : typeof options.ignoreTryCatch !== 'undefined'
  9535. ? options.ignoreTryCatch
  9536. : true;
  9537. return {
  9538. canConvertRequire: mode !== 'remove' && mode !== true,
  9539. shouldRemoveRequireStatement: mode === 'remove'
  9540. };
  9541. };
  9542. const resolveId = getResolveId(extensions);
  9543. const sourceMap = options.sourceMap !== false;
  9544. function transformAndCheckExports(code, id) {
  9545. if (isDynamicRequireModulesEnabled && this.getModuleInfo(id).isEntry) {
  9546. // eslint-disable-next-line no-param-reassign
  9547. code =
  9548. getDynamicPackagesEntryIntro(dynamicRequireModuleDirPaths, dynamicRequireModuleSet) + code;
  9549. }
  9550. const { isEsModule, hasDefaultExport, hasNamedExports, ast } = analyzeTopLevelStatements(
  9551. this.parse,
  9552. code,
  9553. id
  9554. );
  9555. if (hasDefaultExport) {
  9556. esModulesWithDefaultExport.add(id);
  9557. }
  9558. if (hasNamedExports) {
  9559. esModulesWithNamedExports.add(id);
  9560. }
  9561. if (
  9562. !dynamicRequireModuleSet.has(normalizePathSlashes(id)) &&
  9563. (!hasCjsKeywords(code, ignoreGlobal) || (isEsModule && !options.transformMixedEsModules))
  9564. ) {
  9565. return { meta: { commonjs: { isCommonJS: false } } };
  9566. }
  9567. // avoid wrapping as this is a commonjsRegister call
  9568. const disableWrap = isWrappedId(id, DYNAMIC_REGISTER_SUFFIX);
  9569. if (disableWrap) {
  9570. // eslint-disable-next-line no-param-reassign
  9571. id = unwrapId$1(id, DYNAMIC_REGISTER_SUFFIX);
  9572. }
  9573. return transformCommonjs(
  9574. this.parse,
  9575. code,
  9576. id,
  9577. isEsModule,
  9578. ignoreGlobal || isEsModule,
  9579. ignoreRequire,
  9580. ignoreDynamicRequires && !isDynamicRequireModulesEnabled,
  9581. getIgnoreTryCatchRequireStatementMode,
  9582. sourceMap,
  9583. isDynamicRequireModulesEnabled,
  9584. dynamicRequireModuleSet,
  9585. disableWrap,
  9586. commonDir,
  9587. ast,
  9588. getDefaultIsModuleExports(id)
  9589. );
  9590. }
  9591. return {
  9592. name: 'commonjs',
  9593. buildStart() {
  9594. validateRollupVersion(this.meta.rollupVersion, peerDependencies.rollup);
  9595. if (options.namedExports != null) {
  9596. this.warn(
  9597. 'The namedExports option from "@rollup/plugin-commonjs" is deprecated. Named exports are now handled automatically.'
  9598. );
  9599. }
  9600. },
  9601. resolveId,
  9602. load(id) {
  9603. if (id === HELPERS_ID) {
  9604. return getHelpersModule(isDynamicRequireModulesEnabled, ignoreDynamicRequires);
  9605. }
  9606. if (id.startsWith(HELPERS_ID)) {
  9607. return getSpecificHelperProxy(id);
  9608. }
  9609. if (isWrappedId(id, MODULE_SUFFIX)) {
  9610. const actualId = unwrapId$1(id, MODULE_SUFFIX);
  9611. let name = getName(actualId);
  9612. let code;
  9613. if (isDynamicRequireModulesEnabled) {
  9614. if (['modulePath', 'commonjsRequire', 'createModule'].includes(name)) {
  9615. name = `${name}_`;
  9616. }
  9617. code =
  9618. `import {commonjsRequire, createModule} from "${HELPERS_ID}";\n` +
  9619. `var ${name} = createModule(${JSON.stringify(
  9620. getVirtualPathForDynamicRequirePath(path$r.dirname(actualId), commonDir)
  9621. )});\n` +
  9622. `export {${name} as __module}`;
  9623. } else {
  9624. code = `var ${name} = {exports: {}}; export {${name} as __module}`;
  9625. }
  9626. return {
  9627. code,
  9628. syntheticNamedExports: '__module',
  9629. meta: { commonjs: { isCommonJS: false } }
  9630. };
  9631. }
  9632. if (isWrappedId(id, EXPORTS_SUFFIX)) {
  9633. const actualId = unwrapId$1(id, EXPORTS_SUFFIX);
  9634. const name = getName(actualId);
  9635. return {
  9636. code: `var ${name} = {}; export {${name} as __exports}`,
  9637. meta: { commonjs: { isCommonJS: false } }
  9638. };
  9639. }
  9640. if (isWrappedId(id, EXTERNAL_SUFFIX)) {
  9641. const actualId = unwrapId$1(id, EXTERNAL_SUFFIX);
  9642. return getUnknownRequireProxy(
  9643. actualId,
  9644. isEsmExternal(actualId) ? getRequireReturnsDefault(actualId) : true
  9645. );
  9646. }
  9647. if (id === DYNAMIC_PACKAGES_ID) {
  9648. return getDynamicPackagesModule(dynamicRequireModuleDirPaths, commonDir);
  9649. }
  9650. if (id.startsWith(DYNAMIC_JSON_PREFIX)) {
  9651. return getDynamicJsonProxy(id, commonDir);
  9652. }
  9653. if (isDynamicModuleImport(id, dynamicRequireModuleSet)) {
  9654. return `export default require(${JSON.stringify(normalizePathSlashes(id))});`;
  9655. }
  9656. if (isWrappedId(id, DYNAMIC_REGISTER_SUFFIX)) {
  9657. return getDynamicRequireProxy(
  9658. normalizePathSlashes(unwrapId$1(id, DYNAMIC_REGISTER_SUFFIX)),
  9659. commonDir
  9660. );
  9661. }
  9662. if (isWrappedId(id, PROXY_SUFFIX)) {
  9663. const actualId = unwrapId$1(id, PROXY_SUFFIX);
  9664. return getStaticRequireProxy(
  9665. actualId,
  9666. getRequireReturnsDefault(actualId),
  9667. esModulesWithDefaultExport,
  9668. esModulesWithNamedExports,
  9669. commonJsMetaPromises
  9670. );
  9671. }
  9672. return null;
  9673. },
  9674. transform(code, rawId) {
  9675. let id = rawId;
  9676. if (isWrappedId(id, DYNAMIC_REGISTER_SUFFIX)) {
  9677. id = unwrapId$1(id, DYNAMIC_REGISTER_SUFFIX);
  9678. }
  9679. const extName = path$r.extname(id);
  9680. if (
  9681. extName !== '.cjs' &&
  9682. id !== DYNAMIC_PACKAGES_ID &&
  9683. !id.startsWith(DYNAMIC_JSON_PREFIX) &&
  9684. (!filter(id) || !extensions.includes(extName))
  9685. ) {
  9686. return null;
  9687. }
  9688. try {
  9689. return transformAndCheckExports.call(this, code, rawId);
  9690. } catch (err) {
  9691. return this.error(err, err.loc);
  9692. }
  9693. },
  9694. moduleParsed({ id, meta: { commonjs: commonjsMeta } }) {
  9695. if (commonjsMeta && commonjsMeta.isCommonJS != null) {
  9696. setCommonJSMetaPromise(commonJsMetaPromises, id, commonjsMeta);
  9697. return;
  9698. }
  9699. setCommonJSMetaPromise(commonJsMetaPromises, id, null);
  9700. }
  9701. };
  9702. }
  9703. var tasks = {};
  9704. var utils$h = {};
  9705. var array$1 = {};
  9706. Object.defineProperty(array$1, "__esModule", { value: true });
  9707. array$1.splitWhen = array$1.flatten = void 0;
  9708. function flatten$1(items) {
  9709. return items.reduce((collection, item) => [].concat(collection, item), []);
  9710. }
  9711. array$1.flatten = flatten$1;
  9712. function splitWhen(items, predicate) {
  9713. const result = [[]];
  9714. let groupIndex = 0;
  9715. for (const item of items) {
  9716. if (predicate(item)) {
  9717. groupIndex++;
  9718. result[groupIndex] = [];
  9719. }
  9720. else {
  9721. result[groupIndex].push(item);
  9722. }
  9723. }
  9724. return result;
  9725. }
  9726. array$1.splitWhen = splitWhen;
  9727. var errno$1 = {};
  9728. Object.defineProperty(errno$1, "__esModule", { value: true });
  9729. errno$1.isEnoentCodeError = void 0;
  9730. function isEnoentCodeError(error) {
  9731. return error.code === 'ENOENT';
  9732. }
  9733. errno$1.isEnoentCodeError = isEnoentCodeError;
  9734. var fs$i = {};
  9735. Object.defineProperty(fs$i, "__esModule", { value: true });
  9736. fs$i.createDirentFromStats = void 0;
  9737. class DirentFromStats$1 {
  9738. constructor(name, stats) {
  9739. this.name = name;
  9740. this.isBlockDevice = stats.isBlockDevice.bind(stats);
  9741. this.isCharacterDevice = stats.isCharacterDevice.bind(stats);
  9742. this.isDirectory = stats.isDirectory.bind(stats);
  9743. this.isFIFO = stats.isFIFO.bind(stats);
  9744. this.isFile = stats.isFile.bind(stats);
  9745. this.isSocket = stats.isSocket.bind(stats);
  9746. this.isSymbolicLink = stats.isSymbolicLink.bind(stats);
  9747. }
  9748. }
  9749. function createDirentFromStats$1(name, stats) {
  9750. return new DirentFromStats$1(name, stats);
  9751. }
  9752. fs$i.createDirentFromStats = createDirentFromStats$1;
  9753. var path$g = {};
  9754. Object.defineProperty(path$g, "__esModule", { value: true });
  9755. path$g.removeLeadingDotSegment = path$g.escape = path$g.makeAbsolute = path$g.unixify = void 0;
  9756. const path$f = path__default;
  9757. const LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2; // ./ or .\\
  9758. const UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\())/g;
  9759. /**
  9760. * Designed to work only with simple paths: `dir\\file`.
  9761. */
  9762. function unixify(filepath) {
  9763. return filepath.replace(/\\/g, '/');
  9764. }
  9765. path$g.unixify = unixify;
  9766. function makeAbsolute(cwd, filepath) {
  9767. return path$f.resolve(cwd, filepath);
  9768. }
  9769. path$g.makeAbsolute = makeAbsolute;
  9770. function escape$2(pattern) {
  9771. return pattern.replace(UNESCAPED_GLOB_SYMBOLS_RE, '\\$2');
  9772. }
  9773. path$g.escape = escape$2;
  9774. function removeLeadingDotSegment(entry) {
  9775. // We do not use `startsWith` because this is 10x slower than current implementation for some cases.
  9776. // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with
  9777. if (entry.charAt(0) === '.') {
  9778. const secondCharactery = entry.charAt(1);
  9779. if (secondCharactery === '/' || secondCharactery === '\\') {
  9780. return entry.slice(LEADING_DOT_SEGMENT_CHARACTERS_COUNT);
  9781. }
  9782. }
  9783. return entry;
  9784. }
  9785. path$g.removeLeadingDotSegment = removeLeadingDotSegment;
  9786. var pattern$1 = {};
  9787. /*!
  9788. * is-extglob <https://github.com/jonschlinkert/is-extglob>
  9789. *
  9790. * Copyright (c) 2014-2016, Jon Schlinkert.
  9791. * Licensed under the MIT License.
  9792. */
  9793. var isExtglob$1 = function isExtglob(str) {
  9794. if (typeof str !== 'string' || str === '') {
  9795. return false;
  9796. }
  9797. var match;
  9798. while ((match = /(\\).|([@?!+*]\(.*\))/g.exec(str))) {
  9799. if (match[2]) return true;
  9800. str = str.slice(match.index + match[0].length);
  9801. }
  9802. return false;
  9803. };
  9804. /*!
  9805. * is-glob <https://github.com/jonschlinkert/is-glob>
  9806. *
  9807. * Copyright (c) 2014-2017, Jon Schlinkert.
  9808. * Released under the MIT License.
  9809. */
  9810. var isExtglob = isExtglob$1;
  9811. var chars$1 = { '{': '}', '(': ')', '[': ']'};
  9812. var strictCheck = function(str) {
  9813. if (str[0] === '!') {
  9814. return true;
  9815. }
  9816. var index = 0;
  9817. var pipeIndex = -2;
  9818. var closeSquareIndex = -2;
  9819. var closeCurlyIndex = -2;
  9820. var closeParenIndex = -2;
  9821. var backSlashIndex = -2;
  9822. while (index < str.length) {
  9823. if (str[index] === '*') {
  9824. return true;
  9825. }
  9826. if (str[index + 1] === '?' && /[\].+)]/.test(str[index])) {
  9827. return true;
  9828. }
  9829. if (closeSquareIndex !== -1 && str[index] === '[' && str[index + 1] !== ']') {
  9830. if (closeSquareIndex < index) {
  9831. closeSquareIndex = str.indexOf(']', index);
  9832. }
  9833. if (closeSquareIndex > index) {
  9834. if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) {
  9835. return true;
  9836. }
  9837. backSlashIndex = str.indexOf('\\', index);
  9838. if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) {
  9839. return true;
  9840. }
  9841. }
  9842. }
  9843. if (closeCurlyIndex !== -1 && str[index] === '{' && str[index + 1] !== '}') {
  9844. closeCurlyIndex = str.indexOf('}', index);
  9845. if (closeCurlyIndex > index) {
  9846. backSlashIndex = str.indexOf('\\', index);
  9847. if (backSlashIndex === -1 || backSlashIndex > closeCurlyIndex) {
  9848. return true;
  9849. }
  9850. }
  9851. }
  9852. if (closeParenIndex !== -1 && str[index] === '(' && str[index + 1] === '?' && /[:!=]/.test(str[index + 2]) && str[index + 3] !== ')') {
  9853. closeParenIndex = str.indexOf(')', index);
  9854. if (closeParenIndex > index) {
  9855. backSlashIndex = str.indexOf('\\', index);
  9856. if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) {
  9857. return true;
  9858. }
  9859. }
  9860. }
  9861. if (pipeIndex !== -1 && str[index] === '(' && str[index + 1] !== '|') {
  9862. if (pipeIndex < index) {
  9863. pipeIndex = str.indexOf('|', index);
  9864. }
  9865. if (pipeIndex !== -1 && str[pipeIndex + 1] !== ')') {
  9866. closeParenIndex = str.indexOf(')', pipeIndex);
  9867. if (closeParenIndex > pipeIndex) {
  9868. backSlashIndex = str.indexOf('\\', pipeIndex);
  9869. if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) {
  9870. return true;
  9871. }
  9872. }
  9873. }
  9874. }
  9875. if (str[index] === '\\') {
  9876. var open = str[index + 1];
  9877. index += 2;
  9878. var close = chars$1[open];
  9879. if (close) {
  9880. var n = str.indexOf(close, index);
  9881. if (n !== -1) {
  9882. index = n + 1;
  9883. }
  9884. }
  9885. if (str[index] === '!') {
  9886. return true;
  9887. }
  9888. } else {
  9889. index++;
  9890. }
  9891. }
  9892. return false;
  9893. };
  9894. var relaxedCheck = function(str) {
  9895. if (str[0] === '!') {
  9896. return true;
  9897. }
  9898. var index = 0;
  9899. while (index < str.length) {
  9900. if (/[*?{}()[\]]/.test(str[index])) {
  9901. return true;
  9902. }
  9903. if (str[index] === '\\') {
  9904. var open = str[index + 1];
  9905. index += 2;
  9906. var close = chars$1[open];
  9907. if (close) {
  9908. var n = str.indexOf(close, index);
  9909. if (n !== -1) {
  9910. index = n + 1;
  9911. }
  9912. }
  9913. if (str[index] === '!') {
  9914. return true;
  9915. }
  9916. } else {
  9917. index++;
  9918. }
  9919. }
  9920. return false;
  9921. };
  9922. var isGlob$2 = function isGlob(str, options) {
  9923. if (typeof str !== 'string' || str === '') {
  9924. return false;
  9925. }
  9926. if (isExtglob(str)) {
  9927. return true;
  9928. }
  9929. var check = strictCheck;
  9930. // optionally relax check
  9931. if (options && options.strict === false) {
  9932. check = relaxedCheck;
  9933. }
  9934. return check(str);
  9935. };
  9936. var isGlob$1 = isGlob$2;
  9937. var pathPosixDirname = path__default.posix.dirname;
  9938. var isWin32 = require$$2__default.platform() === 'win32';
  9939. var slash$1 = '/';
  9940. var backslash = /\\/g;
  9941. var enclosure = /[\{\[].*[\}\]]$/;
  9942. var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/;
  9943. var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g;
  9944. /**
  9945. * @param {string} str
  9946. * @param {Object} opts
  9947. * @param {boolean} [opts.flipBackslashes=true]
  9948. * @returns {string}
  9949. */
  9950. var globParent$2 = function globParent(str, opts) {
  9951. var options = Object.assign({ flipBackslashes: true }, opts);
  9952. // flip windows path separators
  9953. if (options.flipBackslashes && isWin32 && str.indexOf(slash$1) < 0) {
  9954. str = str.replace(backslash, slash$1);
  9955. }
  9956. // special case for strings ending in enclosure containing path separator
  9957. if (enclosure.test(str)) {
  9958. str += slash$1;
  9959. }
  9960. // preserves full path in case of trailing path separator
  9961. str += 'a';
  9962. // remove path parts that are globby
  9963. do {
  9964. str = pathPosixDirname(str);
  9965. } while (isGlob$1(str) || globby.test(str));
  9966. // remove escape chars and return result
  9967. return str.replace(escaped, '$1');
  9968. };
  9969. var utils$g = {};
  9970. (function (exports) {
  9971. exports.isInteger = num => {
  9972. if (typeof num === 'number') {
  9973. return Number.isInteger(num);
  9974. }
  9975. if (typeof num === 'string' && num.trim() !== '') {
  9976. return Number.isInteger(Number(num));
  9977. }
  9978. return false;
  9979. };
  9980. /**
  9981. * Find a node of the given type
  9982. */
  9983. exports.find = (node, type) => node.nodes.find(node => node.type === type);
  9984. /**
  9985. * Find a node of the given type
  9986. */
  9987. exports.exceedsLimit = (min, max, step = 1, limit) => {
  9988. if (limit === false) return false;
  9989. if (!exports.isInteger(min) || !exports.isInteger(max)) return false;
  9990. return ((Number(max) - Number(min)) / Number(step)) >= limit;
  9991. };
  9992. /**
  9993. * Escape the given node with '\\' before node.value
  9994. */
  9995. exports.escapeNode = (block, n = 0, type) => {
  9996. let node = block.nodes[n];
  9997. if (!node) return;
  9998. if ((type && node.type === type) || node.type === 'open' || node.type === 'close') {
  9999. if (node.escaped !== true) {
  10000. node.value = '\\' + node.value;
  10001. node.escaped = true;
  10002. }
  10003. }
  10004. };
  10005. /**
  10006. * Returns true if the given brace node should be enclosed in literal braces
  10007. */
  10008. exports.encloseBrace = node => {
  10009. if (node.type !== 'brace') return false;
  10010. if ((node.commas >> 0 + node.ranges >> 0) === 0) {
  10011. node.invalid = true;
  10012. return true;
  10013. }
  10014. return false;
  10015. };
  10016. /**
  10017. * Returns true if a brace node is invalid.
  10018. */
  10019. exports.isInvalidBrace = block => {
  10020. if (block.type !== 'brace') return false;
  10021. if (block.invalid === true || block.dollar) return true;
  10022. if ((block.commas >> 0 + block.ranges >> 0) === 0) {
  10023. block.invalid = true;
  10024. return true;
  10025. }
  10026. if (block.open !== true || block.close !== true) {
  10027. block.invalid = true;
  10028. return true;
  10029. }
  10030. return false;
  10031. };
  10032. /**
  10033. * Returns true if a node is an open or close node
  10034. */
  10035. exports.isOpenOrClose = node => {
  10036. if (node.type === 'open' || node.type === 'close') {
  10037. return true;
  10038. }
  10039. return node.open === true || node.close === true;
  10040. };
  10041. /**
  10042. * Reduce an array of text nodes.
  10043. */
  10044. exports.reduce = nodes => nodes.reduce((acc, node) => {
  10045. if (node.type === 'text') acc.push(node.value);
  10046. if (node.type === 'range') node.type = 'text';
  10047. return acc;
  10048. }, []);
  10049. /**
  10050. * Flatten an array
  10051. */
  10052. exports.flatten = (...args) => {
  10053. const result = [];
  10054. const flat = arr => {
  10055. for (let i = 0; i < arr.length; i++) {
  10056. let ele = arr[i];
  10057. Array.isArray(ele) ? flat(ele) : ele !== void 0 && result.push(ele);
  10058. }
  10059. return result;
  10060. };
  10061. flat(args);
  10062. return result;
  10063. };
  10064. }(utils$g));
  10065. const utils$f = utils$g;
  10066. var stringify$7 = (ast, options = {}) => {
  10067. let stringify = (node, parent = {}) => {
  10068. let invalidBlock = options.escapeInvalid && utils$f.isInvalidBrace(parent);
  10069. let invalidNode = node.invalid === true && options.escapeInvalid === true;
  10070. let output = '';
  10071. if (node.value) {
  10072. if ((invalidBlock || invalidNode) && utils$f.isOpenOrClose(node)) {
  10073. return '\\' + node.value;
  10074. }
  10075. return node.value;
  10076. }
  10077. if (node.value) {
  10078. return node.value;
  10079. }
  10080. if (node.nodes) {
  10081. for (let child of node.nodes) {
  10082. output += stringify(child);
  10083. }
  10084. }
  10085. return output;
  10086. };
  10087. return stringify(ast);
  10088. };
  10089. /*!
  10090. * is-number <https://github.com/jonschlinkert/is-number>
  10091. *
  10092. * Copyright (c) 2014-present, Jon Schlinkert.
  10093. * Released under the MIT License.
  10094. */
  10095. var isNumber$2 = function(num) {
  10096. if (typeof num === 'number') {
  10097. return num - num === 0;
  10098. }
  10099. if (typeof num === 'string' && num.trim() !== '') {
  10100. return Number.isFinite ? Number.isFinite(+num) : isFinite(+num);
  10101. }
  10102. return false;
  10103. };
  10104. /*!
  10105. * to-regex-range <https://github.com/micromatch/to-regex-range>
  10106. *
  10107. * Copyright (c) 2015-present, Jon Schlinkert.
  10108. * Released under the MIT License.
  10109. */
  10110. const isNumber$1 = isNumber$2;
  10111. const toRegexRange$1 = (min, max, options) => {
  10112. if (isNumber$1(min) === false) {
  10113. throw new TypeError('toRegexRange: expected the first argument to be a number');
  10114. }
  10115. if (max === void 0 || min === max) {
  10116. return String(min);
  10117. }
  10118. if (isNumber$1(max) === false) {
  10119. throw new TypeError('toRegexRange: expected the second argument to be a number.');
  10120. }
  10121. let opts = { relaxZeros: true, ...options };
  10122. if (typeof opts.strictZeros === 'boolean') {
  10123. opts.relaxZeros = opts.strictZeros === false;
  10124. }
  10125. let relax = String(opts.relaxZeros);
  10126. let shorthand = String(opts.shorthand);
  10127. let capture = String(opts.capture);
  10128. let wrap = String(opts.wrap);
  10129. let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap;
  10130. if (toRegexRange$1.cache.hasOwnProperty(cacheKey)) {
  10131. return toRegexRange$1.cache[cacheKey].result;
  10132. }
  10133. let a = Math.min(min, max);
  10134. let b = Math.max(min, max);
  10135. if (Math.abs(a - b) === 1) {
  10136. let result = min + '|' + max;
  10137. if (opts.capture) {
  10138. return `(${result})`;
  10139. }
  10140. if (opts.wrap === false) {
  10141. return result;
  10142. }
  10143. return `(?:${result})`;
  10144. }
  10145. let isPadded = hasPadding(min) || hasPadding(max);
  10146. let state = { min, max, a, b };
  10147. let positives = [];
  10148. let negatives = [];
  10149. if (isPadded) {
  10150. state.isPadded = isPadded;
  10151. state.maxLen = String(state.max).length;
  10152. }
  10153. if (a < 0) {
  10154. let newMin = b < 0 ? Math.abs(b) : 1;
  10155. negatives = splitToPatterns(newMin, Math.abs(a), state, opts);
  10156. a = state.a = 0;
  10157. }
  10158. if (b >= 0) {
  10159. positives = splitToPatterns(a, b, state, opts);
  10160. }
  10161. state.negatives = negatives;
  10162. state.positives = positives;
  10163. state.result = collatePatterns(negatives, positives);
  10164. if (opts.capture === true) {
  10165. state.result = `(${state.result})`;
  10166. } else if (opts.wrap !== false && (positives.length + negatives.length) > 1) {
  10167. state.result = `(?:${state.result})`;
  10168. }
  10169. toRegexRange$1.cache[cacheKey] = state;
  10170. return state.result;
  10171. };
  10172. function collatePatterns(neg, pos, options) {
  10173. let onlyNegative = filterPatterns(neg, pos, '-', false) || [];
  10174. let onlyPositive = filterPatterns(pos, neg, '', false) || [];
  10175. let intersected = filterPatterns(neg, pos, '-?', true) || [];
  10176. let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive);
  10177. return subpatterns.join('|');
  10178. }
  10179. function splitToRanges(min, max) {
  10180. let nines = 1;
  10181. let zeros = 1;
  10182. let stop = countNines(min, nines);
  10183. let stops = new Set([max]);
  10184. while (min <= stop && stop <= max) {
  10185. stops.add(stop);
  10186. nines += 1;
  10187. stop = countNines(min, nines);
  10188. }
  10189. stop = countZeros(max + 1, zeros) - 1;
  10190. while (min < stop && stop <= max) {
  10191. stops.add(stop);
  10192. zeros += 1;
  10193. stop = countZeros(max + 1, zeros) - 1;
  10194. }
  10195. stops = [...stops];
  10196. stops.sort(compare$1);
  10197. return stops;
  10198. }
  10199. /**
  10200. * Convert a range to a regex pattern
  10201. * @param {Number} `start`
  10202. * @param {Number} `stop`
  10203. * @return {String}
  10204. */
  10205. function rangeToPattern(start, stop, options) {
  10206. if (start === stop) {
  10207. return { pattern: start, count: [], digits: 0 };
  10208. }
  10209. let zipped = zip(start, stop);
  10210. let digits = zipped.length;
  10211. let pattern = '';
  10212. let count = 0;
  10213. for (let i = 0; i < digits; i++) {
  10214. let [startDigit, stopDigit] = zipped[i];
  10215. if (startDigit === stopDigit) {
  10216. pattern += startDigit;
  10217. } else if (startDigit !== '0' || stopDigit !== '9') {
  10218. pattern += toCharacterClass(startDigit, stopDigit);
  10219. } else {
  10220. count++;
  10221. }
  10222. }
  10223. if (count) {
  10224. pattern += options.shorthand === true ? '\\d' : '[0-9]';
  10225. }
  10226. return { pattern, count: [count], digits };
  10227. }
  10228. function splitToPatterns(min, max, tok, options) {
  10229. let ranges = splitToRanges(min, max);
  10230. let tokens = [];
  10231. let start = min;
  10232. let prev;
  10233. for (let i = 0; i < ranges.length; i++) {
  10234. let max = ranges[i];
  10235. let obj = rangeToPattern(String(start), String(max), options);
  10236. let zeros = '';
  10237. if (!tok.isPadded && prev && prev.pattern === obj.pattern) {
  10238. if (prev.count.length > 1) {
  10239. prev.count.pop();
  10240. }
  10241. prev.count.push(obj.count[0]);
  10242. prev.string = prev.pattern + toQuantifier(prev.count);
  10243. start = max + 1;
  10244. continue;
  10245. }
  10246. if (tok.isPadded) {
  10247. zeros = padZeros(max, tok, options);
  10248. }
  10249. obj.string = zeros + obj.pattern + toQuantifier(obj.count);
  10250. tokens.push(obj);
  10251. start = max + 1;
  10252. prev = obj;
  10253. }
  10254. return tokens;
  10255. }
  10256. function filterPatterns(arr, comparison, prefix, intersection, options) {
  10257. let result = [];
  10258. for (let ele of arr) {
  10259. let { string } = ele;
  10260. // only push if _both_ are negative...
  10261. if (!intersection && !contains(comparison, 'string', string)) {
  10262. result.push(prefix + string);
  10263. }
  10264. // or _both_ are positive
  10265. if (intersection && contains(comparison, 'string', string)) {
  10266. result.push(prefix + string);
  10267. }
  10268. }
  10269. return result;
  10270. }
  10271. /**
  10272. * Zip strings
  10273. */
  10274. function zip(a, b) {
  10275. let arr = [];
  10276. for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]);
  10277. return arr;
  10278. }
  10279. function compare$1(a, b) {
  10280. return a > b ? 1 : b > a ? -1 : 0;
  10281. }
  10282. function contains(arr, key, val) {
  10283. return arr.some(ele => ele[key] === val);
  10284. }
  10285. function countNines(min, len) {
  10286. return Number(String(min).slice(0, -len) + '9'.repeat(len));
  10287. }
  10288. function countZeros(integer, zeros) {
  10289. return integer - (integer % Math.pow(10, zeros));
  10290. }
  10291. function toQuantifier(digits) {
  10292. let [start = 0, stop = ''] = digits;
  10293. if (stop || start > 1) {
  10294. return `{${start + (stop ? ',' + stop : '')}}`;
  10295. }
  10296. return '';
  10297. }
  10298. function toCharacterClass(a, b, options) {
  10299. return `[${a}${(b - a === 1) ? '' : '-'}${b}]`;
  10300. }
  10301. function hasPadding(str) {
  10302. return /^-?(0+)\d/.test(str);
  10303. }
  10304. function padZeros(value, tok, options) {
  10305. if (!tok.isPadded) {
  10306. return value;
  10307. }
  10308. let diff = Math.abs(tok.maxLen - String(value).length);
  10309. let relax = options.relaxZeros !== false;
  10310. switch (diff) {
  10311. case 0:
  10312. return '';
  10313. case 1:
  10314. return relax ? '0?' : '0';
  10315. case 2:
  10316. return relax ? '0{0,2}' : '00';
  10317. default: {
  10318. return relax ? `0{0,${diff}}` : `0{${diff}}`;
  10319. }
  10320. }
  10321. }
  10322. /**
  10323. * Cache
  10324. */
  10325. toRegexRange$1.cache = {};
  10326. toRegexRange$1.clearCache = () => (toRegexRange$1.cache = {});
  10327. /**
  10328. * Expose `toRegexRange`
  10329. */
  10330. var toRegexRange_1 = toRegexRange$1;
  10331. /*!
  10332. * fill-range <https://github.com/jonschlinkert/fill-range>
  10333. *
  10334. * Copyright (c) 2014-present, Jon Schlinkert.
  10335. * Licensed under the MIT License.
  10336. */
  10337. const util$3 = require$$0__default$2;
  10338. const toRegexRange = toRegexRange_1;
  10339. const isObject$2 = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  10340. const transform$1 = toNumber => {
  10341. return value => toNumber === true ? Number(value) : String(value);
  10342. };
  10343. const isValidValue = value => {
  10344. return typeof value === 'number' || (typeof value === 'string' && value !== '');
  10345. };
  10346. const isNumber = num => Number.isInteger(+num);
  10347. const zeros = input => {
  10348. let value = `${input}`;
  10349. let index = -1;
  10350. if (value[0] === '-') value = value.slice(1);
  10351. if (value === '0') return false;
  10352. while (value[++index] === '0');
  10353. return index > 0;
  10354. };
  10355. const stringify$6 = (start, end, options) => {
  10356. if (typeof start === 'string' || typeof end === 'string') {
  10357. return true;
  10358. }
  10359. return options.stringify === true;
  10360. };
  10361. const pad$1 = (input, maxLength, toNumber) => {
  10362. if (maxLength > 0) {
  10363. let dash = input[0] === '-' ? '-' : '';
  10364. if (dash) input = input.slice(1);
  10365. input = (dash + input.padStart(dash ? maxLength - 1 : maxLength, '0'));
  10366. }
  10367. if (toNumber === false) {
  10368. return String(input);
  10369. }
  10370. return input;
  10371. };
  10372. const toMaxLen = (input, maxLength) => {
  10373. let negative = input[0] === '-' ? '-' : '';
  10374. if (negative) {
  10375. input = input.slice(1);
  10376. maxLength--;
  10377. }
  10378. while (input.length < maxLength) input = '0' + input;
  10379. return negative ? ('-' + input) : input;
  10380. };
  10381. const toSequence = (parts, options) => {
  10382. parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
  10383. parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
  10384. let prefix = options.capture ? '' : '?:';
  10385. let positives = '';
  10386. let negatives = '';
  10387. let result;
  10388. if (parts.positives.length) {
  10389. positives = parts.positives.join('|');
  10390. }
  10391. if (parts.negatives.length) {
  10392. negatives = `-(${prefix}${parts.negatives.join('|')})`;
  10393. }
  10394. if (positives && negatives) {
  10395. result = `${positives}|${negatives}`;
  10396. } else {
  10397. result = positives || negatives;
  10398. }
  10399. if (options.wrap) {
  10400. return `(${prefix}${result})`;
  10401. }
  10402. return result;
  10403. };
  10404. const toRange = (a, b, isNumbers, options) => {
  10405. if (isNumbers) {
  10406. return toRegexRange(a, b, { wrap: false, ...options });
  10407. }
  10408. let start = String.fromCharCode(a);
  10409. if (a === b) return start;
  10410. let stop = String.fromCharCode(b);
  10411. return `[${start}-${stop}]`;
  10412. };
  10413. const toRegex = (start, end, options) => {
  10414. if (Array.isArray(start)) {
  10415. let wrap = options.wrap === true;
  10416. let prefix = options.capture ? '' : '?:';
  10417. return wrap ? `(${prefix}${start.join('|')})` : start.join('|');
  10418. }
  10419. return toRegexRange(start, end, options);
  10420. };
  10421. const rangeError = (...args) => {
  10422. return new RangeError('Invalid range arguments: ' + util$3.inspect(...args));
  10423. };
  10424. const invalidRange = (start, end, options) => {
  10425. if (options.strictRanges === true) throw rangeError([start, end]);
  10426. return [];
  10427. };
  10428. const invalidStep = (step, options) => {
  10429. if (options.strictRanges === true) {
  10430. throw new TypeError(`Expected step "${step}" to be a number`);
  10431. }
  10432. return [];
  10433. };
  10434. const fillNumbers = (start, end, step = 1, options = {}) => {
  10435. let a = Number(start);
  10436. let b = Number(end);
  10437. if (!Number.isInteger(a) || !Number.isInteger(b)) {
  10438. if (options.strictRanges === true) throw rangeError([start, end]);
  10439. return [];
  10440. }
  10441. // fix negative zero
  10442. if (a === 0) a = 0;
  10443. if (b === 0) b = 0;
  10444. let descending = a > b;
  10445. let startString = String(start);
  10446. let endString = String(end);
  10447. let stepString = String(step);
  10448. step = Math.max(Math.abs(step), 1);
  10449. let padded = zeros(startString) || zeros(endString) || zeros(stepString);
  10450. let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0;
  10451. let toNumber = padded === false && stringify$6(start, end, options) === false;
  10452. let format = options.transform || transform$1(toNumber);
  10453. if (options.toRegex && step === 1) {
  10454. return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options);
  10455. }
  10456. let parts = { negatives: [], positives: [] };
  10457. let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num));
  10458. let range = [];
  10459. let index = 0;
  10460. while (descending ? a >= b : a <= b) {
  10461. if (options.toRegex === true && step > 1) {
  10462. push(a);
  10463. } else {
  10464. range.push(pad$1(format(a, index), maxLen, toNumber));
  10465. }
  10466. a = descending ? a - step : a + step;
  10467. index++;
  10468. }
  10469. if (options.toRegex === true) {
  10470. return step > 1
  10471. ? toSequence(parts, options)
  10472. : toRegex(range, null, { wrap: false, ...options });
  10473. }
  10474. return range;
  10475. };
  10476. const fillLetters = (start, end, step = 1, options = {}) => {
  10477. if ((!isNumber(start) && start.length > 1) || (!isNumber(end) && end.length > 1)) {
  10478. return invalidRange(start, end, options);
  10479. }
  10480. let format = options.transform || (val => String.fromCharCode(val));
  10481. let a = `${start}`.charCodeAt(0);
  10482. let b = `${end}`.charCodeAt(0);
  10483. let descending = a > b;
  10484. let min = Math.min(a, b);
  10485. let max = Math.max(a, b);
  10486. if (options.toRegex && step === 1) {
  10487. return toRange(min, max, false, options);
  10488. }
  10489. let range = [];
  10490. let index = 0;
  10491. while (descending ? a >= b : a <= b) {
  10492. range.push(format(a, index));
  10493. a = descending ? a - step : a + step;
  10494. index++;
  10495. }
  10496. if (options.toRegex === true) {
  10497. return toRegex(range, null, { wrap: false, options });
  10498. }
  10499. return range;
  10500. };
  10501. const fill$2 = (start, end, step, options = {}) => {
  10502. if (end == null && isValidValue(start)) {
  10503. return [start];
  10504. }
  10505. if (!isValidValue(start) || !isValidValue(end)) {
  10506. return invalidRange(start, end, options);
  10507. }
  10508. if (typeof step === 'function') {
  10509. return fill$2(start, end, 1, { transform: step });
  10510. }
  10511. if (isObject$2(step)) {
  10512. return fill$2(start, end, 0, step);
  10513. }
  10514. let opts = { ...options };
  10515. if (opts.capture === true) opts.wrap = true;
  10516. step = step || opts.step || 1;
  10517. if (!isNumber(step)) {
  10518. if (step != null && !isObject$2(step)) return invalidStep(step, opts);
  10519. return fill$2(start, end, 1, step);
  10520. }
  10521. if (isNumber(start) && isNumber(end)) {
  10522. return fillNumbers(start, end, step, opts);
  10523. }
  10524. return fillLetters(start, end, Math.max(Math.abs(step), 1), opts);
  10525. };
  10526. var fillRange = fill$2;
  10527. const fill$1 = fillRange;
  10528. const utils$e = utils$g;
  10529. const compile$1 = (ast, options = {}) => {
  10530. let walk = (node, parent = {}) => {
  10531. let invalidBlock = utils$e.isInvalidBrace(parent);
  10532. let invalidNode = node.invalid === true && options.escapeInvalid === true;
  10533. let invalid = invalidBlock === true || invalidNode === true;
  10534. let prefix = options.escapeInvalid === true ? '\\' : '';
  10535. let output = '';
  10536. if (node.isOpen === true) {
  10537. return prefix + node.value;
  10538. }
  10539. if (node.isClose === true) {
  10540. return prefix + node.value;
  10541. }
  10542. if (node.type === 'open') {
  10543. return invalid ? (prefix + node.value) : '(';
  10544. }
  10545. if (node.type === 'close') {
  10546. return invalid ? (prefix + node.value) : ')';
  10547. }
  10548. if (node.type === 'comma') {
  10549. return node.prev.type === 'comma' ? '' : (invalid ? node.value : '|');
  10550. }
  10551. if (node.value) {
  10552. return node.value;
  10553. }
  10554. if (node.nodes && node.ranges > 0) {
  10555. let args = utils$e.reduce(node.nodes);
  10556. let range = fill$1(...args, { ...options, wrap: false, toRegex: true });
  10557. if (range.length !== 0) {
  10558. return args.length > 1 && range.length > 1 ? `(${range})` : range;
  10559. }
  10560. }
  10561. if (node.nodes) {
  10562. for (let child of node.nodes) {
  10563. output += walk(child, node);
  10564. }
  10565. }
  10566. return output;
  10567. };
  10568. return walk(ast);
  10569. };
  10570. var compile_1 = compile$1;
  10571. const fill = fillRange;
  10572. const stringify$5 = stringify$7;
  10573. const utils$d = utils$g;
  10574. const append$1 = (queue = '', stash = '', enclose = false) => {
  10575. let result = [];
  10576. queue = [].concat(queue);
  10577. stash = [].concat(stash);
  10578. if (!stash.length) return queue;
  10579. if (!queue.length) {
  10580. return enclose ? utils$d.flatten(stash).map(ele => `{${ele}}`) : stash;
  10581. }
  10582. for (let item of queue) {
  10583. if (Array.isArray(item)) {
  10584. for (let value of item) {
  10585. result.push(append$1(value, stash, enclose));
  10586. }
  10587. } else {
  10588. for (let ele of stash) {
  10589. if (enclose === true && typeof ele === 'string') ele = `{${ele}}`;
  10590. result.push(Array.isArray(ele) ? append$1(item, ele, enclose) : (item + ele));
  10591. }
  10592. }
  10593. }
  10594. return utils$d.flatten(result);
  10595. };
  10596. const expand$1 = (ast, options = {}) => {
  10597. let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit;
  10598. let walk = (node, parent = {}) => {
  10599. node.queue = [];
  10600. let p = parent;
  10601. let q = parent.queue;
  10602. while (p.type !== 'brace' && p.type !== 'root' && p.parent) {
  10603. p = p.parent;
  10604. q = p.queue;
  10605. }
  10606. if (node.invalid || node.dollar) {
  10607. q.push(append$1(q.pop(), stringify$5(node, options)));
  10608. return;
  10609. }
  10610. if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) {
  10611. q.push(append$1(q.pop(), ['{}']));
  10612. return;
  10613. }
  10614. if (node.nodes && node.ranges > 0) {
  10615. let args = utils$d.reduce(node.nodes);
  10616. if (utils$d.exceedsLimit(...args, options.step, rangeLimit)) {
  10617. throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.');
  10618. }
  10619. let range = fill(...args, options);
  10620. if (range.length === 0) {
  10621. range = stringify$5(node, options);
  10622. }
  10623. q.push(append$1(q.pop(), range));
  10624. node.nodes = [];
  10625. return;
  10626. }
  10627. let enclose = utils$d.encloseBrace(node);
  10628. let queue = node.queue;
  10629. let block = node;
  10630. while (block.type !== 'brace' && block.type !== 'root' && block.parent) {
  10631. block = block.parent;
  10632. queue = block.queue;
  10633. }
  10634. for (let i = 0; i < node.nodes.length; i++) {
  10635. let child = node.nodes[i];
  10636. if (child.type === 'comma' && node.type === 'brace') {
  10637. if (i === 1) queue.push('');
  10638. queue.push('');
  10639. continue;
  10640. }
  10641. if (child.type === 'close') {
  10642. q.push(append$1(q.pop(), queue, enclose));
  10643. continue;
  10644. }
  10645. if (child.value && child.type !== 'open') {
  10646. queue.push(append$1(queue.pop(), child.value));
  10647. continue;
  10648. }
  10649. if (child.nodes) {
  10650. walk(child, node);
  10651. }
  10652. }
  10653. return queue;
  10654. };
  10655. return utils$d.flatten(walk(ast));
  10656. };
  10657. var expand_1 = expand$1;
  10658. var constants$3 = {
  10659. MAX_LENGTH: 1024 * 64,
  10660. // Digits
  10661. CHAR_0: '0', /* 0 */
  10662. CHAR_9: '9', /* 9 */
  10663. // Alphabet chars.
  10664. CHAR_UPPERCASE_A: 'A', /* A */
  10665. CHAR_LOWERCASE_A: 'a', /* a */
  10666. CHAR_UPPERCASE_Z: 'Z', /* Z */
  10667. CHAR_LOWERCASE_Z: 'z', /* z */
  10668. CHAR_LEFT_PARENTHESES: '(', /* ( */
  10669. CHAR_RIGHT_PARENTHESES: ')', /* ) */
  10670. CHAR_ASTERISK: '*', /* * */
  10671. // Non-alphabetic chars.
  10672. CHAR_AMPERSAND: '&', /* & */
  10673. CHAR_AT: '@', /* @ */
  10674. CHAR_BACKSLASH: '\\', /* \ */
  10675. CHAR_BACKTICK: '`', /* ` */
  10676. CHAR_CARRIAGE_RETURN: '\r', /* \r */
  10677. CHAR_CIRCUMFLEX_ACCENT: '^', /* ^ */
  10678. CHAR_COLON: ':', /* : */
  10679. CHAR_COMMA: ',', /* , */
  10680. CHAR_DOLLAR: '$', /* . */
  10681. CHAR_DOT: '.', /* . */
  10682. CHAR_DOUBLE_QUOTE: '"', /* " */
  10683. CHAR_EQUAL: '=', /* = */
  10684. CHAR_EXCLAMATION_MARK: '!', /* ! */
  10685. CHAR_FORM_FEED: '\f', /* \f */
  10686. CHAR_FORWARD_SLASH: '/', /* / */
  10687. CHAR_HASH: '#', /* # */
  10688. CHAR_HYPHEN_MINUS: '-', /* - */
  10689. CHAR_LEFT_ANGLE_BRACKET: '<', /* < */
  10690. CHAR_LEFT_CURLY_BRACE: '{', /* { */
  10691. CHAR_LEFT_SQUARE_BRACKET: '[', /* [ */
  10692. CHAR_LINE_FEED: '\n', /* \n */
  10693. CHAR_NO_BREAK_SPACE: '\u00A0', /* \u00A0 */
  10694. CHAR_PERCENT: '%', /* % */
  10695. CHAR_PLUS: '+', /* + */
  10696. CHAR_QUESTION_MARK: '?', /* ? */
  10697. CHAR_RIGHT_ANGLE_BRACKET: '>', /* > */
  10698. CHAR_RIGHT_CURLY_BRACE: '}', /* } */
  10699. CHAR_RIGHT_SQUARE_BRACKET: ']', /* ] */
  10700. CHAR_SEMICOLON: ';', /* ; */
  10701. CHAR_SINGLE_QUOTE: '\'', /* ' */
  10702. CHAR_SPACE: ' ', /* */
  10703. CHAR_TAB: '\t', /* \t */
  10704. CHAR_UNDERSCORE: '_', /* _ */
  10705. CHAR_VERTICAL_LINE: '|', /* | */
  10706. CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' /* \uFEFF */
  10707. };
  10708. const stringify$4 = stringify$7;
  10709. /**
  10710. * Constants
  10711. */
  10712. const {
  10713. MAX_LENGTH,
  10714. CHAR_BACKSLASH, /* \ */
  10715. CHAR_BACKTICK, /* ` */
  10716. CHAR_COMMA, /* , */
  10717. CHAR_DOT, /* . */
  10718. CHAR_LEFT_PARENTHESES, /* ( */
  10719. CHAR_RIGHT_PARENTHESES, /* ) */
  10720. CHAR_LEFT_CURLY_BRACE, /* { */
  10721. CHAR_RIGHT_CURLY_BRACE, /* } */
  10722. CHAR_LEFT_SQUARE_BRACKET, /* [ */
  10723. CHAR_RIGHT_SQUARE_BRACKET, /* ] */
  10724. CHAR_DOUBLE_QUOTE, /* " */
  10725. CHAR_SINGLE_QUOTE, /* ' */
  10726. CHAR_NO_BREAK_SPACE,
  10727. CHAR_ZERO_WIDTH_NOBREAK_SPACE
  10728. } = constants$3;
  10729. /**
  10730. * parse
  10731. */
  10732. const parse$i = (input, options = {}) => {
  10733. if (typeof input !== 'string') {
  10734. throw new TypeError('Expected a string');
  10735. }
  10736. let opts = options || {};
  10737. let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  10738. if (input.length > max) {
  10739. throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`);
  10740. }
  10741. let ast = { type: 'root', input, nodes: [] };
  10742. let stack = [ast];
  10743. let block = ast;
  10744. let prev = ast;
  10745. let brackets = 0;
  10746. let length = input.length;
  10747. let index = 0;
  10748. let depth = 0;
  10749. let value;
  10750. /**
  10751. * Helpers
  10752. */
  10753. const advance = () => input[index++];
  10754. const push = node => {
  10755. if (node.type === 'text' && prev.type === 'dot') {
  10756. prev.type = 'text';
  10757. }
  10758. if (prev && prev.type === 'text' && node.type === 'text') {
  10759. prev.value += node.value;
  10760. return;
  10761. }
  10762. block.nodes.push(node);
  10763. node.parent = block;
  10764. node.prev = prev;
  10765. prev = node;
  10766. return node;
  10767. };
  10768. push({ type: 'bos' });
  10769. while (index < length) {
  10770. block = stack[stack.length - 1];
  10771. value = advance();
  10772. /**
  10773. * Invalid chars
  10774. */
  10775. if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) {
  10776. continue;
  10777. }
  10778. /**
  10779. * Escaped chars
  10780. */
  10781. if (value === CHAR_BACKSLASH) {
  10782. push({ type: 'text', value: (options.keepEscaping ? value : '') + advance() });
  10783. continue;
  10784. }
  10785. /**
  10786. * Right square bracket (literal): ']'
  10787. */
  10788. if (value === CHAR_RIGHT_SQUARE_BRACKET) {
  10789. push({ type: 'text', value: '\\' + value });
  10790. continue;
  10791. }
  10792. /**
  10793. * Left square bracket: '['
  10794. */
  10795. if (value === CHAR_LEFT_SQUARE_BRACKET) {
  10796. brackets++;
  10797. let next;
  10798. while (index < length && (next = advance())) {
  10799. value += next;
  10800. if (next === CHAR_LEFT_SQUARE_BRACKET) {
  10801. brackets++;
  10802. continue;
  10803. }
  10804. if (next === CHAR_BACKSLASH) {
  10805. value += advance();
  10806. continue;
  10807. }
  10808. if (next === CHAR_RIGHT_SQUARE_BRACKET) {
  10809. brackets--;
  10810. if (brackets === 0) {
  10811. break;
  10812. }
  10813. }
  10814. }
  10815. push({ type: 'text', value });
  10816. continue;
  10817. }
  10818. /**
  10819. * Parentheses
  10820. */
  10821. if (value === CHAR_LEFT_PARENTHESES) {
  10822. block = push({ type: 'paren', nodes: [] });
  10823. stack.push(block);
  10824. push({ type: 'text', value });
  10825. continue;
  10826. }
  10827. if (value === CHAR_RIGHT_PARENTHESES) {
  10828. if (block.type !== 'paren') {
  10829. push({ type: 'text', value });
  10830. continue;
  10831. }
  10832. block = stack.pop();
  10833. push({ type: 'text', value });
  10834. block = stack[stack.length - 1];
  10835. continue;
  10836. }
  10837. /**
  10838. * Quotes: '|"|`
  10839. */
  10840. if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) {
  10841. let open = value;
  10842. let next;
  10843. if (options.keepQuotes !== true) {
  10844. value = '';
  10845. }
  10846. while (index < length && (next = advance())) {
  10847. if (next === CHAR_BACKSLASH) {
  10848. value += next + advance();
  10849. continue;
  10850. }
  10851. if (next === open) {
  10852. if (options.keepQuotes === true) value += next;
  10853. break;
  10854. }
  10855. value += next;
  10856. }
  10857. push({ type: 'text', value });
  10858. continue;
  10859. }
  10860. /**
  10861. * Left curly brace: '{'
  10862. */
  10863. if (value === CHAR_LEFT_CURLY_BRACE) {
  10864. depth++;
  10865. let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true;
  10866. let brace = {
  10867. type: 'brace',
  10868. open: true,
  10869. close: false,
  10870. dollar,
  10871. depth,
  10872. commas: 0,
  10873. ranges: 0,
  10874. nodes: []
  10875. };
  10876. block = push(brace);
  10877. stack.push(block);
  10878. push({ type: 'open', value });
  10879. continue;
  10880. }
  10881. /**
  10882. * Right curly brace: '}'
  10883. */
  10884. if (value === CHAR_RIGHT_CURLY_BRACE) {
  10885. if (block.type !== 'brace') {
  10886. push({ type: 'text', value });
  10887. continue;
  10888. }
  10889. let type = 'close';
  10890. block = stack.pop();
  10891. block.close = true;
  10892. push({ type, value });
  10893. depth--;
  10894. block = stack[stack.length - 1];
  10895. continue;
  10896. }
  10897. /**
  10898. * Comma: ','
  10899. */
  10900. if (value === CHAR_COMMA && depth > 0) {
  10901. if (block.ranges > 0) {
  10902. block.ranges = 0;
  10903. let open = block.nodes.shift();
  10904. block.nodes = [open, { type: 'text', value: stringify$4(block) }];
  10905. }
  10906. push({ type: 'comma', value });
  10907. block.commas++;
  10908. continue;
  10909. }
  10910. /**
  10911. * Dot: '.'
  10912. */
  10913. if (value === CHAR_DOT && depth > 0 && block.commas === 0) {
  10914. let siblings = block.nodes;
  10915. if (depth === 0 || siblings.length === 0) {
  10916. push({ type: 'text', value });
  10917. continue;
  10918. }
  10919. if (prev.type === 'dot') {
  10920. block.range = [];
  10921. prev.value += value;
  10922. prev.type = 'range';
  10923. if (block.nodes.length !== 3 && block.nodes.length !== 5) {
  10924. block.invalid = true;
  10925. block.ranges = 0;
  10926. prev.type = 'text';
  10927. continue;
  10928. }
  10929. block.ranges++;
  10930. block.args = [];
  10931. continue;
  10932. }
  10933. if (prev.type === 'range') {
  10934. siblings.pop();
  10935. let before = siblings[siblings.length - 1];
  10936. before.value += prev.value + value;
  10937. prev = before;
  10938. block.ranges--;
  10939. continue;
  10940. }
  10941. push({ type: 'dot', value });
  10942. continue;
  10943. }
  10944. /**
  10945. * Text
  10946. */
  10947. push({ type: 'text', value });
  10948. }
  10949. // Mark imbalanced braces and brackets as invalid
  10950. do {
  10951. block = stack.pop();
  10952. if (block.type !== 'root') {
  10953. block.nodes.forEach(node => {
  10954. if (!node.nodes) {
  10955. if (node.type === 'open') node.isOpen = true;
  10956. if (node.type === 'close') node.isClose = true;
  10957. if (!node.nodes) node.type = 'text';
  10958. node.invalid = true;
  10959. }
  10960. });
  10961. // get the location of the block on parent.nodes (block's siblings)
  10962. let parent = stack[stack.length - 1];
  10963. let index = parent.nodes.indexOf(block);
  10964. // replace the (invalid) block with it's nodes
  10965. parent.nodes.splice(index, 1, ...block.nodes);
  10966. }
  10967. } while (stack.length > 0);
  10968. push({ type: 'eos' });
  10969. return ast;
  10970. };
  10971. var parse_1$1 = parse$i;
  10972. const stringify$3 = stringify$7;
  10973. const compile = compile_1;
  10974. const expand = expand_1;
  10975. const parse$h = parse_1$1;
  10976. /**
  10977. * Expand the given pattern or create a regex-compatible string.
  10978. *
  10979. * ```js
  10980. * const braces = require('braces');
  10981. * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)']
  10982. * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c']
  10983. * ```
  10984. * @param {String} `str`
  10985. * @param {Object} `options`
  10986. * @return {String}
  10987. * @api public
  10988. */
  10989. const braces$3 = (input, options = {}) => {
  10990. let output = [];
  10991. if (Array.isArray(input)) {
  10992. for (let pattern of input) {
  10993. let result = braces$3.create(pattern, options);
  10994. if (Array.isArray(result)) {
  10995. output.push(...result);
  10996. } else {
  10997. output.push(result);
  10998. }
  10999. }
  11000. } else {
  11001. output = [].concat(braces$3.create(input, options));
  11002. }
  11003. if (options && options.expand === true && options.nodupes === true) {
  11004. output = [...new Set(output)];
  11005. }
  11006. return output;
  11007. };
  11008. /**
  11009. * Parse the given `str` with the given `options`.
  11010. *
  11011. * ```js
  11012. * // braces.parse(pattern, [, options]);
  11013. * const ast = braces.parse('a/{b,c}/d');
  11014. * console.log(ast);
  11015. * ```
  11016. * @param {String} pattern Brace pattern to parse
  11017. * @param {Object} options
  11018. * @return {Object} Returns an AST
  11019. * @api public
  11020. */
  11021. braces$3.parse = (input, options = {}) => parse$h(input, options);
  11022. /**
  11023. * Creates a braces string from an AST, or an AST node.
  11024. *
  11025. * ```js
  11026. * const braces = require('braces');
  11027. * let ast = braces.parse('foo/{a,b}/bar');
  11028. * console.log(stringify(ast.nodes[2])); //=> '{a,b}'
  11029. * ```
  11030. * @param {String} `input` Brace pattern or AST.
  11031. * @param {Object} `options`
  11032. * @return {Array} Returns an array of expanded values.
  11033. * @api public
  11034. */
  11035. braces$3.stringify = (input, options = {}) => {
  11036. if (typeof input === 'string') {
  11037. return stringify$3(braces$3.parse(input, options), options);
  11038. }
  11039. return stringify$3(input, options);
  11040. };
  11041. /**
  11042. * Compiles a brace pattern into a regex-compatible, optimized string.
  11043. * This method is called by the main [braces](#braces) function by default.
  11044. *
  11045. * ```js
  11046. * const braces = require('braces');
  11047. * console.log(braces.compile('a/{b,c}/d'));
  11048. * //=> ['a/(b|c)/d']
  11049. * ```
  11050. * @param {String} `input` Brace pattern or AST.
  11051. * @param {Object} `options`
  11052. * @return {Array} Returns an array of expanded values.
  11053. * @api public
  11054. */
  11055. braces$3.compile = (input, options = {}) => {
  11056. if (typeof input === 'string') {
  11057. input = braces$3.parse(input, options);
  11058. }
  11059. return compile(input, options);
  11060. };
  11061. /**
  11062. * Expands a brace pattern into an array. This method is called by the
  11063. * main [braces](#braces) function when `options.expand` is true. Before
  11064. * using this method it's recommended that you read the [performance notes](#performance))
  11065. * and advantages of using [.compile](#compile) instead.
  11066. *
  11067. * ```js
  11068. * const braces = require('braces');
  11069. * console.log(braces.expand('a/{b,c}/d'));
  11070. * //=> ['a/b/d', 'a/c/d'];
  11071. * ```
  11072. * @param {String} `pattern` Brace pattern
  11073. * @param {Object} `options`
  11074. * @return {Array} Returns an array of expanded values.
  11075. * @api public
  11076. */
  11077. braces$3.expand = (input, options = {}) => {
  11078. if (typeof input === 'string') {
  11079. input = braces$3.parse(input, options);
  11080. }
  11081. let result = expand(input, options);
  11082. // filter out empty strings if specified
  11083. if (options.noempty === true) {
  11084. result = result.filter(Boolean);
  11085. }
  11086. // filter out duplicates if specified
  11087. if (options.nodupes === true) {
  11088. result = [...new Set(result)];
  11089. }
  11090. return result;
  11091. };
  11092. /**
  11093. * Processes a brace pattern and returns either an expanded array
  11094. * (if `options.expand` is true), a highly optimized regex-compatible string.
  11095. * This method is called by the main [braces](#braces) function.
  11096. *
  11097. * ```js
  11098. * const braces = require('braces');
  11099. * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}'))
  11100. * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)'
  11101. * ```
  11102. * @param {String} `pattern` Brace pattern
  11103. * @param {Object} `options`
  11104. * @return {Array} Returns an array of expanded values.
  11105. * @api public
  11106. */
  11107. braces$3.create = (input, options = {}) => {
  11108. if (input === '' || input.length < 3) {
  11109. return [input];
  11110. }
  11111. return options.expand !== true
  11112. ? braces$3.compile(input, options)
  11113. : braces$3.expand(input, options);
  11114. };
  11115. /**
  11116. * Expose "braces"
  11117. */
  11118. var braces_1 = braces$3;
  11119. const util$2 = require$$0__default$2;
  11120. const braces$2 = braces_1;
  11121. const picomatch$3 = picomatch$4;
  11122. const utils$c = utils$l;
  11123. const isEmptyString$1 = val => val === '' || val === './';
  11124. /**
  11125. * Returns an array of strings that match one or more glob patterns.
  11126. *
  11127. * ```js
  11128. * const mm = require('micromatch');
  11129. * // mm(list, patterns[, options]);
  11130. *
  11131. * console.log(mm(['a.js', 'a.txt'], ['*.js']));
  11132. * //=> [ 'a.js' ]
  11133. * ```
  11134. * @param {String|Array<string>} `list` List of strings to match.
  11135. * @param {String|Array<string>} `patterns` One or more glob patterns to use for matching.
  11136. * @param {Object} `options` See available [options](#options)
  11137. * @return {Array} Returns an array of matches
  11138. * @summary false
  11139. * @api public
  11140. */
  11141. const micromatch$2 = (list, patterns, options) => {
  11142. patterns = [].concat(patterns);
  11143. list = [].concat(list);
  11144. let omit = new Set();
  11145. let keep = new Set();
  11146. let items = new Set();
  11147. let negatives = 0;
  11148. let onResult = state => {
  11149. items.add(state.output);
  11150. if (options && options.onResult) {
  11151. options.onResult(state);
  11152. }
  11153. };
  11154. for (let i = 0; i < patterns.length; i++) {
  11155. let isMatch = picomatch$3(String(patterns[i]), { ...options, onResult }, true);
  11156. let negated = isMatch.state.negated || isMatch.state.negatedExtglob;
  11157. if (negated) negatives++;
  11158. for (let item of list) {
  11159. let matched = isMatch(item, true);
  11160. let match = negated ? !matched.isMatch : matched.isMatch;
  11161. if (!match) continue;
  11162. if (negated) {
  11163. omit.add(matched.output);
  11164. } else {
  11165. omit.delete(matched.output);
  11166. keep.add(matched.output);
  11167. }
  11168. }
  11169. }
  11170. let result = negatives === patterns.length ? [...items] : [...keep];
  11171. let matches = result.filter(item => !omit.has(item));
  11172. if (options && matches.length === 0) {
  11173. if (options.failglob === true) {
  11174. throw new Error(`No matches found for "${patterns.join(', ')}"`);
  11175. }
  11176. if (options.nonull === true || options.nullglob === true) {
  11177. return options.unescape ? patterns.map(p => p.replace(/\\/g, '')) : patterns;
  11178. }
  11179. }
  11180. return matches;
  11181. };
  11182. /**
  11183. * Backwards compatibility
  11184. */
  11185. micromatch$2.match = micromatch$2;
  11186. /**
  11187. * Returns a matcher function from the given glob `pattern` and `options`.
  11188. * The returned function takes a string to match as its only argument and returns
  11189. * true if the string is a match.
  11190. *
  11191. * ```js
  11192. * const mm = require('micromatch');
  11193. * // mm.matcher(pattern[, options]);
  11194. *
  11195. * const isMatch = mm.matcher('*.!(*a)');
  11196. * console.log(isMatch('a.a')); //=> false
  11197. * console.log(isMatch('a.b')); //=> true
  11198. * ```
  11199. * @param {String} `pattern` Glob pattern
  11200. * @param {Object} `options`
  11201. * @return {Function} Returns a matcher function.
  11202. * @api public
  11203. */
  11204. micromatch$2.matcher = (pattern, options) => picomatch$3(pattern, options);
  11205. /**
  11206. * Returns true if **any** of the given glob `patterns` match the specified `string`.
  11207. *
  11208. * ```js
  11209. * const mm = require('micromatch');
  11210. * // mm.isMatch(string, patterns[, options]);
  11211. *
  11212. * console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true
  11213. * console.log(mm.isMatch('a.a', 'b.*')); //=> false
  11214. * ```
  11215. * @param {String} `str` The string to test.
  11216. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  11217. * @param {Object} `[options]` See available [options](#options).
  11218. * @return {Boolean} Returns true if any patterns match `str`
  11219. * @api public
  11220. */
  11221. micromatch$2.isMatch = (str, patterns, options) => picomatch$3(patterns, options)(str);
  11222. /**
  11223. * Backwards compatibility
  11224. */
  11225. micromatch$2.any = micromatch$2.isMatch;
  11226. /**
  11227. * Returns a list of strings that _**do not match any**_ of the given `patterns`.
  11228. *
  11229. * ```js
  11230. * const mm = require('micromatch');
  11231. * // mm.not(list, patterns[, options]);
  11232. *
  11233. * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a'));
  11234. * //=> ['b.b', 'c.c']
  11235. * ```
  11236. * @param {Array} `list` Array of strings to match.
  11237. * @param {String|Array} `patterns` One or more glob pattern to use for matching.
  11238. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  11239. * @return {Array} Returns an array of strings that **do not match** the given patterns.
  11240. * @api public
  11241. */
  11242. micromatch$2.not = (list, patterns, options = {}) => {
  11243. patterns = [].concat(patterns).map(String);
  11244. let result = new Set();
  11245. let items = [];
  11246. let onResult = state => {
  11247. if (options.onResult) options.onResult(state);
  11248. items.push(state.output);
  11249. };
  11250. let matches = micromatch$2(list, patterns, { ...options, onResult });
  11251. for (let item of items) {
  11252. if (!matches.includes(item)) {
  11253. result.add(item);
  11254. }
  11255. }
  11256. return [...result];
  11257. };
  11258. /**
  11259. * Returns true if the given `string` contains the given pattern. Similar
  11260. * to [.isMatch](#isMatch) but the pattern can match any part of the string.
  11261. *
  11262. * ```js
  11263. * var mm = require('micromatch');
  11264. * // mm.contains(string, pattern[, options]);
  11265. *
  11266. * console.log(mm.contains('aa/bb/cc', '*b'));
  11267. * //=> true
  11268. * console.log(mm.contains('aa/bb/cc', '*d'));
  11269. * //=> false
  11270. * ```
  11271. * @param {String} `str` The string to match.
  11272. * @param {String|Array} `patterns` Glob pattern to use for matching.
  11273. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  11274. * @return {Boolean} Returns true if any of the patterns matches any part of `str`.
  11275. * @api public
  11276. */
  11277. micromatch$2.contains = (str, pattern, options) => {
  11278. if (typeof str !== 'string') {
  11279. throw new TypeError(`Expected a string: "${util$2.inspect(str)}"`);
  11280. }
  11281. if (Array.isArray(pattern)) {
  11282. return pattern.some(p => micromatch$2.contains(str, p, options));
  11283. }
  11284. if (typeof pattern === 'string') {
  11285. if (isEmptyString$1(str) || isEmptyString$1(pattern)) {
  11286. return false;
  11287. }
  11288. if (str.includes(pattern) || (str.startsWith('./') && str.slice(2).includes(pattern))) {
  11289. return true;
  11290. }
  11291. }
  11292. return micromatch$2.isMatch(str, pattern, { ...options, contains: true });
  11293. };
  11294. /**
  11295. * Filter the keys of the given object with the given `glob` pattern
  11296. * and `options`. Does not attempt to match nested keys. If you need this feature,
  11297. * use [glob-object][] instead.
  11298. *
  11299. * ```js
  11300. * const mm = require('micromatch');
  11301. * // mm.matchKeys(object, patterns[, options]);
  11302. *
  11303. * const obj = { aa: 'a', ab: 'b', ac: 'c' };
  11304. * console.log(mm.matchKeys(obj, '*b'));
  11305. * //=> { ab: 'b' }
  11306. * ```
  11307. * @param {Object} `object` The object with keys to filter.
  11308. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  11309. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  11310. * @return {Object} Returns an object with only keys that match the given patterns.
  11311. * @api public
  11312. */
  11313. micromatch$2.matchKeys = (obj, patterns, options) => {
  11314. if (!utils$c.isObject(obj)) {
  11315. throw new TypeError('Expected the first argument to be an object');
  11316. }
  11317. let keys = micromatch$2(Object.keys(obj), patterns, options);
  11318. let res = {};
  11319. for (let key of keys) res[key] = obj[key];
  11320. return res;
  11321. };
  11322. /**
  11323. * Returns true if some of the strings in the given `list` match any of the given glob `patterns`.
  11324. *
  11325. * ```js
  11326. * const mm = require('micromatch');
  11327. * // mm.some(list, patterns[, options]);
  11328. *
  11329. * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
  11330. * // true
  11331. * console.log(mm.some(['foo.js'], ['*.js', '!foo.js']));
  11332. * // false
  11333. * ```
  11334. * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found.
  11335. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  11336. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  11337. * @return {Boolean} Returns true if any `patterns` matches any of the strings in `list`
  11338. * @api public
  11339. */
  11340. micromatch$2.some = (list, patterns, options) => {
  11341. let items = [].concat(list);
  11342. for (let pattern of [].concat(patterns)) {
  11343. let isMatch = picomatch$3(String(pattern), options);
  11344. if (items.some(item => isMatch(item))) {
  11345. return true;
  11346. }
  11347. }
  11348. return false;
  11349. };
  11350. /**
  11351. * Returns true if every string in the given `list` matches
  11352. * any of the given glob `patterns`.
  11353. *
  11354. * ```js
  11355. * const mm = require('micromatch');
  11356. * // mm.every(list, patterns[, options]);
  11357. *
  11358. * console.log(mm.every('foo.js', ['foo.js']));
  11359. * // true
  11360. * console.log(mm.every(['foo.js', 'bar.js'], ['*.js']));
  11361. * // true
  11362. * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
  11363. * // false
  11364. * console.log(mm.every(['foo.js'], ['*.js', '!foo.js']));
  11365. * // false
  11366. * ```
  11367. * @param {String|Array} `list` The string or array of strings to test.
  11368. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  11369. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  11370. * @return {Boolean} Returns true if all `patterns` matches all of the strings in `list`
  11371. * @api public
  11372. */
  11373. micromatch$2.every = (list, patterns, options) => {
  11374. let items = [].concat(list);
  11375. for (let pattern of [].concat(patterns)) {
  11376. let isMatch = picomatch$3(String(pattern), options);
  11377. if (!items.every(item => isMatch(item))) {
  11378. return false;
  11379. }
  11380. }
  11381. return true;
  11382. };
  11383. /**
  11384. * Returns true if **all** of the given `patterns` match
  11385. * the specified string.
  11386. *
  11387. * ```js
  11388. * const mm = require('micromatch');
  11389. * // mm.all(string, patterns[, options]);
  11390. *
  11391. * console.log(mm.all('foo.js', ['foo.js']));
  11392. * // true
  11393. *
  11394. * console.log(mm.all('foo.js', ['*.js', '!foo.js']));
  11395. * // false
  11396. *
  11397. * console.log(mm.all('foo.js', ['*.js', 'foo.js']));
  11398. * // true
  11399. *
  11400. * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js']));
  11401. * // true
  11402. * ```
  11403. * @param {String|Array} `str` The string to test.
  11404. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  11405. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  11406. * @return {Boolean} Returns true if any patterns match `str`
  11407. * @api public
  11408. */
  11409. micromatch$2.all = (str, patterns, options) => {
  11410. if (typeof str !== 'string') {
  11411. throw new TypeError(`Expected a string: "${util$2.inspect(str)}"`);
  11412. }
  11413. return [].concat(patterns).every(p => picomatch$3(p, options)(str));
  11414. };
  11415. /**
  11416. * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match.
  11417. *
  11418. * ```js
  11419. * const mm = require('micromatch');
  11420. * // mm.capture(pattern, string[, options]);
  11421. *
  11422. * console.log(mm.capture('test/*.js', 'test/foo.js'));
  11423. * //=> ['foo']
  11424. * console.log(mm.capture('test/*.js', 'foo/bar.css'));
  11425. * //=> null
  11426. * ```
  11427. * @param {String} `glob` Glob pattern to use for matching.
  11428. * @param {String} `input` String to match
  11429. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  11430. * @return {Array|null} Returns an array of captures if the input matches the glob pattern, otherwise `null`.
  11431. * @api public
  11432. */
  11433. micromatch$2.capture = (glob, input, options) => {
  11434. let posix = utils$c.isWindows(options);
  11435. let regex = picomatch$3.makeRe(String(glob), { ...options, capture: true });
  11436. let match = regex.exec(posix ? utils$c.toPosixSlashes(input) : input);
  11437. if (match) {
  11438. return match.slice(1).map(v => v === void 0 ? '' : v);
  11439. }
  11440. };
  11441. /**
  11442. * Create a regular expression from the given glob `pattern`.
  11443. *
  11444. * ```js
  11445. * const mm = require('micromatch');
  11446. * // mm.makeRe(pattern[, options]);
  11447. *
  11448. * console.log(mm.makeRe('*.js'));
  11449. * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/
  11450. * ```
  11451. * @param {String} `pattern` A glob pattern to convert to regex.
  11452. * @param {Object} `options`
  11453. * @return {RegExp} Returns a regex created from the given pattern.
  11454. * @api public
  11455. */
  11456. micromatch$2.makeRe = (...args) => picomatch$3.makeRe(...args);
  11457. /**
  11458. * Scan a glob pattern to separate the pattern into segments. Used
  11459. * by the [split](#split) method.
  11460. *
  11461. * ```js
  11462. * const mm = require('micromatch');
  11463. * const state = mm.scan(pattern[, options]);
  11464. * ```
  11465. * @param {String} `pattern`
  11466. * @param {Object} `options`
  11467. * @return {Object} Returns an object with
  11468. * @api public
  11469. */
  11470. micromatch$2.scan = (...args) => picomatch$3.scan(...args);
  11471. /**
  11472. * Parse a glob pattern to create the source string for a regular
  11473. * expression.
  11474. *
  11475. * ```js
  11476. * const mm = require('micromatch');
  11477. * const state = mm(pattern[, options]);
  11478. * ```
  11479. * @param {String} `glob`
  11480. * @param {Object} `options`
  11481. * @return {Object} Returns an object with useful properties and output to be used as regex source string.
  11482. * @api public
  11483. */
  11484. micromatch$2.parse = (patterns, options) => {
  11485. let res = [];
  11486. for (let pattern of [].concat(patterns || [])) {
  11487. for (let str of braces$2(String(pattern), options)) {
  11488. res.push(picomatch$3.parse(str, options));
  11489. }
  11490. }
  11491. return res;
  11492. };
  11493. /**
  11494. * Process the given brace `pattern`.
  11495. *
  11496. * ```js
  11497. * const { braces } = require('micromatch');
  11498. * console.log(braces('foo/{a,b,c}/bar'));
  11499. * //=> [ 'foo/(a|b|c)/bar' ]
  11500. *
  11501. * console.log(braces('foo/{a,b,c}/bar', { expand: true }));
  11502. * //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ]
  11503. * ```
  11504. * @param {String} `pattern` String with brace pattern to process.
  11505. * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options.
  11506. * @return {Array}
  11507. * @api public
  11508. */
  11509. micromatch$2.braces = (pattern, options) => {
  11510. if (typeof pattern !== 'string') throw new TypeError('Expected a string');
  11511. if ((options && options.nobrace === true) || !/\{.*\}/.test(pattern)) {
  11512. return [pattern];
  11513. }
  11514. return braces$2(pattern, options);
  11515. };
  11516. /**
  11517. * Expand braces
  11518. */
  11519. micromatch$2.braceExpand = (pattern, options) => {
  11520. if (typeof pattern !== 'string') throw new TypeError('Expected a string');
  11521. return micromatch$2.braces(pattern, { ...options, expand: true });
  11522. };
  11523. /**
  11524. * Expose micromatch
  11525. */
  11526. var micromatch_1$1 = micromatch$2;
  11527. Object.defineProperty(pattern$1, "__esModule", { value: true });
  11528. pattern$1.matchAny = pattern$1.convertPatternsToRe = pattern$1.makeRe = pattern$1.getPatternParts = pattern$1.expandBraceExpansion = pattern$1.expandPatternsWithBraceExpansion = pattern$1.isAffectDepthOfReadingPattern = pattern$1.endsWithSlashGlobStar = pattern$1.hasGlobStar = pattern$1.getBaseDirectory = pattern$1.isPatternRelatedToParentDirectory = pattern$1.getPatternsOutsideCurrentDirectory = pattern$1.getPatternsInsideCurrentDirectory = pattern$1.getPositivePatterns = pattern$1.getNegativePatterns = pattern$1.isPositivePattern = pattern$1.isNegativePattern = pattern$1.convertToNegativePattern = pattern$1.convertToPositivePattern = pattern$1.isDynamicPattern = pattern$1.isStaticPattern = void 0;
  11529. const path$e = path__default;
  11530. const globParent$1 = globParent$2;
  11531. const micromatch$1 = micromatch_1$1;
  11532. const GLOBSTAR$1 = '**';
  11533. const ESCAPE_SYMBOL = '\\';
  11534. const COMMON_GLOB_SYMBOLS_RE = /[*?]|^!/;
  11535. const REGEX_CHARACTER_CLASS_SYMBOLS_RE = /\[[^[]*]/;
  11536. const REGEX_GROUP_SYMBOLS_RE = /(?:^|[^!*+?@])\([^(]*\|[^|]*\)/;
  11537. const GLOB_EXTENSION_SYMBOLS_RE = /[!*+?@]\([^(]*\)/;
  11538. const BRACE_EXPANSION_SEPARATORS_RE = /,|\.\./;
  11539. function isStaticPattern(pattern, options = {}) {
  11540. return !isDynamicPattern(pattern, options);
  11541. }
  11542. pattern$1.isStaticPattern = isStaticPattern;
  11543. function isDynamicPattern(pattern, options = {}) {
  11544. /**
  11545. * A special case with an empty string is necessary for matching patterns that start with a forward slash.
  11546. * An empty string cannot be a dynamic pattern.
  11547. * For example, the pattern `/lib/*` will be spread into parts: '', 'lib', '*'.
  11548. */
  11549. if (pattern === '') {
  11550. return false;
  11551. }
  11552. /**
  11553. * When the `caseSensitiveMatch` option is disabled, all patterns must be marked as dynamic, because we cannot check
  11554. * filepath directly (without read directory).
  11555. */
  11556. if (options.caseSensitiveMatch === false || pattern.includes(ESCAPE_SYMBOL)) {
  11557. return true;
  11558. }
  11559. if (COMMON_GLOB_SYMBOLS_RE.test(pattern) || REGEX_CHARACTER_CLASS_SYMBOLS_RE.test(pattern) || REGEX_GROUP_SYMBOLS_RE.test(pattern)) {
  11560. return true;
  11561. }
  11562. if (options.extglob !== false && GLOB_EXTENSION_SYMBOLS_RE.test(pattern)) {
  11563. return true;
  11564. }
  11565. if (options.braceExpansion !== false && hasBraceExpansion(pattern)) {
  11566. return true;
  11567. }
  11568. return false;
  11569. }
  11570. pattern$1.isDynamicPattern = isDynamicPattern;
  11571. function hasBraceExpansion(pattern) {
  11572. const openingBraceIndex = pattern.indexOf('{');
  11573. if (openingBraceIndex === -1) {
  11574. return false;
  11575. }
  11576. const closingBraceIndex = pattern.indexOf('}', openingBraceIndex + 1);
  11577. if (closingBraceIndex === -1) {
  11578. return false;
  11579. }
  11580. const braceContent = pattern.slice(openingBraceIndex, closingBraceIndex);
  11581. return BRACE_EXPANSION_SEPARATORS_RE.test(braceContent);
  11582. }
  11583. function convertToPositivePattern(pattern) {
  11584. return isNegativePattern(pattern) ? pattern.slice(1) : pattern;
  11585. }
  11586. pattern$1.convertToPositivePattern = convertToPositivePattern;
  11587. function convertToNegativePattern(pattern) {
  11588. return '!' + pattern;
  11589. }
  11590. pattern$1.convertToNegativePattern = convertToNegativePattern;
  11591. function isNegativePattern(pattern) {
  11592. return pattern.startsWith('!') && pattern[1] !== '(';
  11593. }
  11594. pattern$1.isNegativePattern = isNegativePattern;
  11595. function isPositivePattern(pattern) {
  11596. return !isNegativePattern(pattern);
  11597. }
  11598. pattern$1.isPositivePattern = isPositivePattern;
  11599. function getNegativePatterns(patterns) {
  11600. return patterns.filter(isNegativePattern);
  11601. }
  11602. pattern$1.getNegativePatterns = getNegativePatterns;
  11603. function getPositivePatterns$1(patterns) {
  11604. return patterns.filter(isPositivePattern);
  11605. }
  11606. pattern$1.getPositivePatterns = getPositivePatterns$1;
  11607. /**
  11608. * Returns patterns that can be applied inside the current directory.
  11609. *
  11610. * @example
  11611. * // ['./*', '*', 'a/*']
  11612. * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*'])
  11613. */
  11614. function getPatternsInsideCurrentDirectory(patterns) {
  11615. return patterns.filter((pattern) => !isPatternRelatedToParentDirectory(pattern));
  11616. }
  11617. pattern$1.getPatternsInsideCurrentDirectory = getPatternsInsideCurrentDirectory;
  11618. /**
  11619. * Returns patterns to be expanded relative to (outside) the current directory.
  11620. *
  11621. * @example
  11622. * // ['../*', './../*']
  11623. * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*'])
  11624. */
  11625. function getPatternsOutsideCurrentDirectory(patterns) {
  11626. return patterns.filter(isPatternRelatedToParentDirectory);
  11627. }
  11628. pattern$1.getPatternsOutsideCurrentDirectory = getPatternsOutsideCurrentDirectory;
  11629. function isPatternRelatedToParentDirectory(pattern) {
  11630. return pattern.startsWith('..') || pattern.startsWith('./..');
  11631. }
  11632. pattern$1.isPatternRelatedToParentDirectory = isPatternRelatedToParentDirectory;
  11633. function getBaseDirectory(pattern) {
  11634. return globParent$1(pattern, { flipBackslashes: false });
  11635. }
  11636. pattern$1.getBaseDirectory = getBaseDirectory;
  11637. function hasGlobStar(pattern) {
  11638. return pattern.includes(GLOBSTAR$1);
  11639. }
  11640. pattern$1.hasGlobStar = hasGlobStar;
  11641. function endsWithSlashGlobStar(pattern) {
  11642. return pattern.endsWith('/' + GLOBSTAR$1);
  11643. }
  11644. pattern$1.endsWithSlashGlobStar = endsWithSlashGlobStar;
  11645. function isAffectDepthOfReadingPattern(pattern) {
  11646. const basename = path$e.basename(pattern);
  11647. return endsWithSlashGlobStar(pattern) || isStaticPattern(basename);
  11648. }
  11649. pattern$1.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern;
  11650. function expandPatternsWithBraceExpansion(patterns) {
  11651. return patterns.reduce((collection, pattern) => {
  11652. return collection.concat(expandBraceExpansion(pattern));
  11653. }, []);
  11654. }
  11655. pattern$1.expandPatternsWithBraceExpansion = expandPatternsWithBraceExpansion;
  11656. function expandBraceExpansion(pattern) {
  11657. return micromatch$1.braces(pattern, {
  11658. expand: true,
  11659. nodupes: true
  11660. });
  11661. }
  11662. pattern$1.expandBraceExpansion = expandBraceExpansion;
  11663. function getPatternParts(pattern, options) {
  11664. let { parts } = micromatch$1.scan(pattern, Object.assign(Object.assign({}, options), { parts: true }));
  11665. /**
  11666. * The scan method returns an empty array in some cases.
  11667. * See micromatch/picomatch#58 for more details.
  11668. */
  11669. if (parts.length === 0) {
  11670. parts = [pattern];
  11671. }
  11672. /**
  11673. * The scan method does not return an empty part for the pattern with a forward slash.
  11674. * This is another part of micromatch/picomatch#58.
  11675. */
  11676. if (parts[0].startsWith('/')) {
  11677. parts[0] = parts[0].slice(1);
  11678. parts.unshift('');
  11679. }
  11680. return parts;
  11681. }
  11682. pattern$1.getPatternParts = getPatternParts;
  11683. function makeRe(pattern, options) {
  11684. return micromatch$1.makeRe(pattern, options);
  11685. }
  11686. pattern$1.makeRe = makeRe;
  11687. function convertPatternsToRe(patterns, options) {
  11688. return patterns.map((pattern) => makeRe(pattern, options));
  11689. }
  11690. pattern$1.convertPatternsToRe = convertPatternsToRe;
  11691. function matchAny(entry, patternsRe) {
  11692. return patternsRe.some((patternRe) => patternRe.test(entry));
  11693. }
  11694. pattern$1.matchAny = matchAny;
  11695. var stream$4 = {};
  11696. /*
  11697. * merge2
  11698. * https://github.com/teambition/merge2
  11699. *
  11700. * Copyright (c) 2014-2020 Teambition
  11701. * Licensed under the MIT license.
  11702. */
  11703. const Stream = require$$0__default$3;
  11704. const PassThrough = Stream.PassThrough;
  11705. const slice = Array.prototype.slice;
  11706. var merge2_1 = merge2$1;
  11707. function merge2$1 () {
  11708. const streamsQueue = [];
  11709. const args = slice.call(arguments);
  11710. let merging = false;
  11711. let options = args[args.length - 1];
  11712. if (options && !Array.isArray(options) && options.pipe == null) {
  11713. args.pop();
  11714. } else {
  11715. options = {};
  11716. }
  11717. const doEnd = options.end !== false;
  11718. const doPipeError = options.pipeError === true;
  11719. if (options.objectMode == null) {
  11720. options.objectMode = true;
  11721. }
  11722. if (options.highWaterMark == null) {
  11723. options.highWaterMark = 64 * 1024;
  11724. }
  11725. const mergedStream = PassThrough(options);
  11726. function addStream () {
  11727. for (let i = 0, len = arguments.length; i < len; i++) {
  11728. streamsQueue.push(pauseStreams(arguments[i], options));
  11729. }
  11730. mergeStream();
  11731. return this
  11732. }
  11733. function mergeStream () {
  11734. if (merging) {
  11735. return
  11736. }
  11737. merging = true;
  11738. let streams = streamsQueue.shift();
  11739. if (!streams) {
  11740. process.nextTick(endStream);
  11741. return
  11742. }
  11743. if (!Array.isArray(streams)) {
  11744. streams = [streams];
  11745. }
  11746. let pipesCount = streams.length + 1;
  11747. function next () {
  11748. if (--pipesCount > 0) {
  11749. return
  11750. }
  11751. merging = false;
  11752. mergeStream();
  11753. }
  11754. function pipe (stream) {
  11755. function onend () {
  11756. stream.removeListener('merge2UnpipeEnd', onend);
  11757. stream.removeListener('end', onend);
  11758. if (doPipeError) {
  11759. stream.removeListener('error', onerror);
  11760. }
  11761. next();
  11762. }
  11763. function onerror (err) {
  11764. mergedStream.emit('error', err);
  11765. }
  11766. // skip ended stream
  11767. if (stream._readableState.endEmitted) {
  11768. return next()
  11769. }
  11770. stream.on('merge2UnpipeEnd', onend);
  11771. stream.on('end', onend);
  11772. if (doPipeError) {
  11773. stream.on('error', onerror);
  11774. }
  11775. stream.pipe(mergedStream, { end: false });
  11776. // compatible for old stream
  11777. stream.resume();
  11778. }
  11779. for (let i = 0; i < streams.length; i++) {
  11780. pipe(streams[i]);
  11781. }
  11782. next();
  11783. }
  11784. function endStream () {
  11785. merging = false;
  11786. // emit 'queueDrain' when all streams merged.
  11787. mergedStream.emit('queueDrain');
  11788. if (doEnd) {
  11789. mergedStream.end();
  11790. }
  11791. }
  11792. mergedStream.setMaxListeners(0);
  11793. mergedStream.add = addStream;
  11794. mergedStream.on('unpipe', function (stream) {
  11795. stream.emit('merge2UnpipeEnd');
  11796. });
  11797. if (args.length) {
  11798. addStream.apply(null, args);
  11799. }
  11800. return mergedStream
  11801. }
  11802. // check and pause streams for pipe.
  11803. function pauseStreams (streams, options) {
  11804. if (!Array.isArray(streams)) {
  11805. // Backwards-compat with old-style streams
  11806. if (!streams._readableState && streams.pipe) {
  11807. streams = streams.pipe(PassThrough(options));
  11808. }
  11809. if (!streams._readableState || !streams.pause || !streams.pipe) {
  11810. throw new Error('Only readable stream can be merged.')
  11811. }
  11812. streams.pause();
  11813. } else {
  11814. for (let i = 0, len = streams.length; i < len; i++) {
  11815. streams[i] = pauseStreams(streams[i], options);
  11816. }
  11817. }
  11818. return streams
  11819. }
  11820. Object.defineProperty(stream$4, "__esModule", { value: true });
  11821. stream$4.merge = void 0;
  11822. const merge2 = merge2_1;
  11823. function merge$1(streams) {
  11824. const mergedStream = merge2(streams);
  11825. streams.forEach((stream) => {
  11826. stream.once('error', (error) => mergedStream.emit('error', error));
  11827. });
  11828. mergedStream.once('close', () => propagateCloseEventToSources(streams));
  11829. mergedStream.once('end', () => propagateCloseEventToSources(streams));
  11830. return mergedStream;
  11831. }
  11832. stream$4.merge = merge$1;
  11833. function propagateCloseEventToSources(streams) {
  11834. streams.forEach((stream) => stream.emit('close'));
  11835. }
  11836. var string$2 = {};
  11837. Object.defineProperty(string$2, "__esModule", { value: true });
  11838. string$2.isEmpty = string$2.isString = void 0;
  11839. function isString(input) {
  11840. return typeof input === 'string';
  11841. }
  11842. string$2.isString = isString;
  11843. function isEmpty(input) {
  11844. return input === '';
  11845. }
  11846. string$2.isEmpty = isEmpty;
  11847. Object.defineProperty(utils$h, "__esModule", { value: true });
  11848. utils$h.string = utils$h.stream = utils$h.pattern = utils$h.path = utils$h.fs = utils$h.errno = utils$h.array = void 0;
  11849. const array = array$1;
  11850. utils$h.array = array;
  11851. const errno = errno$1;
  11852. utils$h.errno = errno;
  11853. const fs$h = fs$i;
  11854. utils$h.fs = fs$h;
  11855. const path$d = path$g;
  11856. utils$h.path = path$d;
  11857. const pattern = pattern$1;
  11858. utils$h.pattern = pattern;
  11859. const stream$3 = stream$4;
  11860. utils$h.stream = stream$3;
  11861. const string$1 = string$2;
  11862. utils$h.string = string$1;
  11863. Object.defineProperty(tasks, "__esModule", { value: true });
  11864. tasks.convertPatternGroupToTask = tasks.convertPatternGroupsToTasks = tasks.groupPatternsByBaseDirectory = tasks.getNegativePatternsAsPositive = tasks.getPositivePatterns = tasks.convertPatternsToTasks = tasks.generate = void 0;
  11865. const utils$b = utils$h;
  11866. function generate(patterns, settings) {
  11867. const positivePatterns = getPositivePatterns(patterns);
  11868. const negativePatterns = getNegativePatternsAsPositive(patterns, settings.ignore);
  11869. const staticPatterns = positivePatterns.filter((pattern) => utils$b.pattern.isStaticPattern(pattern, settings));
  11870. const dynamicPatterns = positivePatterns.filter((pattern) => utils$b.pattern.isDynamicPattern(pattern, settings));
  11871. const staticTasks = convertPatternsToTasks(staticPatterns, negativePatterns, /* dynamic */ false);
  11872. const dynamicTasks = convertPatternsToTasks(dynamicPatterns, negativePatterns, /* dynamic */ true);
  11873. return staticTasks.concat(dynamicTasks);
  11874. }
  11875. tasks.generate = generate;
  11876. /**
  11877. * Returns tasks grouped by basic pattern directories.
  11878. *
  11879. * Patterns that can be found inside (`./`) and outside (`../`) the current directory are handled separately.
  11880. * This is necessary because directory traversal starts at the base directory and goes deeper.
  11881. */
  11882. function convertPatternsToTasks(positive, negative, dynamic) {
  11883. const tasks = [];
  11884. const patternsOutsideCurrentDirectory = utils$b.pattern.getPatternsOutsideCurrentDirectory(positive);
  11885. const patternsInsideCurrentDirectory = utils$b.pattern.getPatternsInsideCurrentDirectory(positive);
  11886. const outsideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsOutsideCurrentDirectory);
  11887. const insideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsInsideCurrentDirectory);
  11888. tasks.push(...convertPatternGroupsToTasks(outsideCurrentDirectoryGroup, negative, dynamic));
  11889. /*
  11890. * For the sake of reducing future accesses to the file system, we merge all tasks within the current directory
  11891. * into a global task, if at least one pattern refers to the root (`.`). In this case, the global task covers the rest.
  11892. */
  11893. if ('.' in insideCurrentDirectoryGroup) {
  11894. tasks.push(convertPatternGroupToTask('.', patternsInsideCurrentDirectory, negative, dynamic));
  11895. }
  11896. else {
  11897. tasks.push(...convertPatternGroupsToTasks(insideCurrentDirectoryGroup, negative, dynamic));
  11898. }
  11899. return tasks;
  11900. }
  11901. tasks.convertPatternsToTasks = convertPatternsToTasks;
  11902. function getPositivePatterns(patterns) {
  11903. return utils$b.pattern.getPositivePatterns(patterns);
  11904. }
  11905. tasks.getPositivePatterns = getPositivePatterns;
  11906. function getNegativePatternsAsPositive(patterns, ignore) {
  11907. const negative = utils$b.pattern.getNegativePatterns(patterns).concat(ignore);
  11908. const positive = negative.map(utils$b.pattern.convertToPositivePattern);
  11909. return positive;
  11910. }
  11911. tasks.getNegativePatternsAsPositive = getNegativePatternsAsPositive;
  11912. function groupPatternsByBaseDirectory(patterns) {
  11913. const group = {};
  11914. return patterns.reduce((collection, pattern) => {
  11915. const base = utils$b.pattern.getBaseDirectory(pattern);
  11916. if (base in collection) {
  11917. collection[base].push(pattern);
  11918. }
  11919. else {
  11920. collection[base] = [pattern];
  11921. }
  11922. return collection;
  11923. }, group);
  11924. }
  11925. tasks.groupPatternsByBaseDirectory = groupPatternsByBaseDirectory;
  11926. function convertPatternGroupsToTasks(positive, negative, dynamic) {
  11927. return Object.keys(positive).map((base) => {
  11928. return convertPatternGroupToTask(base, positive[base], negative, dynamic);
  11929. });
  11930. }
  11931. tasks.convertPatternGroupsToTasks = convertPatternGroupsToTasks;
  11932. function convertPatternGroupToTask(base, positive, negative, dynamic) {
  11933. return {
  11934. dynamic,
  11935. positive,
  11936. negative,
  11937. base,
  11938. patterns: [].concat(positive, negative.map(utils$b.pattern.convertToNegativePattern))
  11939. };
  11940. }
  11941. tasks.convertPatternGroupToTask = convertPatternGroupToTask;
  11942. var patterns = {};
  11943. Object.defineProperty(patterns, "__esModule", { value: true });
  11944. patterns.removeDuplicateSlashes = patterns.transform = void 0;
  11945. /**
  11946. * Matches a sequence of two or more consecutive slashes, excluding the first two slashes at the beginning of the string.
  11947. * The latter is due to the presence of the device path at the beginning of the UNC path.
  11948. * @todo rewrite to negative lookbehind with the next major release.
  11949. */
  11950. const DOUBLE_SLASH_RE$1 = /(?!^)\/{2,}/g;
  11951. function transform(patterns) {
  11952. return patterns.map((pattern) => removeDuplicateSlashes(pattern));
  11953. }
  11954. patterns.transform = transform;
  11955. /**
  11956. * This package only works with forward slashes as a path separator.
  11957. * Because of this, we cannot use the standard `path.normalize` method, because on Windows platform it will use of backslashes.
  11958. */
  11959. function removeDuplicateSlashes(pattern) {
  11960. return pattern.replace(DOUBLE_SLASH_RE$1, '/');
  11961. }
  11962. patterns.removeDuplicateSlashes = removeDuplicateSlashes;
  11963. var async$6 = {};
  11964. var stream$2 = {};
  11965. var out$3 = {};
  11966. var async$5 = {};
  11967. Object.defineProperty(async$5, "__esModule", { value: true });
  11968. async$5.read = void 0;
  11969. function read$4(path, settings, callback) {
  11970. settings.fs.lstat(path, (lstatError, lstat) => {
  11971. if (lstatError !== null) {
  11972. callFailureCallback$2(callback, lstatError);
  11973. return;
  11974. }
  11975. if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) {
  11976. callSuccessCallback$2(callback, lstat);
  11977. return;
  11978. }
  11979. settings.fs.stat(path, (statError, stat) => {
  11980. if (statError !== null) {
  11981. if (settings.throwErrorOnBrokenSymbolicLink) {
  11982. callFailureCallback$2(callback, statError);
  11983. return;
  11984. }
  11985. callSuccessCallback$2(callback, lstat);
  11986. return;
  11987. }
  11988. if (settings.markSymbolicLink) {
  11989. stat.isSymbolicLink = () => true;
  11990. }
  11991. callSuccessCallback$2(callback, stat);
  11992. });
  11993. });
  11994. }
  11995. async$5.read = read$4;
  11996. function callFailureCallback$2(callback, error) {
  11997. callback(error);
  11998. }
  11999. function callSuccessCallback$2(callback, result) {
  12000. callback(null, result);
  12001. }
  12002. var sync$a = {};
  12003. Object.defineProperty(sync$a, "__esModule", { value: true });
  12004. sync$a.read = void 0;
  12005. function read$3(path, settings) {
  12006. const lstat = settings.fs.lstatSync(path);
  12007. if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) {
  12008. return lstat;
  12009. }
  12010. try {
  12011. const stat = settings.fs.statSync(path);
  12012. if (settings.markSymbolicLink) {
  12013. stat.isSymbolicLink = () => true;
  12014. }
  12015. return stat;
  12016. }
  12017. catch (error) {
  12018. if (!settings.throwErrorOnBrokenSymbolicLink) {
  12019. return lstat;
  12020. }
  12021. throw error;
  12022. }
  12023. }
  12024. sync$a.read = read$3;
  12025. var settings$3 = {};
  12026. var fs$g = {};
  12027. (function (exports) {
  12028. Object.defineProperty(exports, "__esModule", { value: true });
  12029. exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0;
  12030. const fs = fs__default;
  12031. exports.FILE_SYSTEM_ADAPTER = {
  12032. lstat: fs.lstat,
  12033. stat: fs.stat,
  12034. lstatSync: fs.lstatSync,
  12035. statSync: fs.statSync
  12036. };
  12037. function createFileSystemAdapter(fsMethods) {
  12038. if (fsMethods === undefined) {
  12039. return exports.FILE_SYSTEM_ADAPTER;
  12040. }
  12041. return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods);
  12042. }
  12043. exports.createFileSystemAdapter = createFileSystemAdapter;
  12044. }(fs$g));
  12045. Object.defineProperty(settings$3, "__esModule", { value: true });
  12046. const fs$f = fs$g;
  12047. class Settings$2 {
  12048. constructor(_options = {}) {
  12049. this._options = _options;
  12050. this.followSymbolicLink = this._getValue(this._options.followSymbolicLink, true);
  12051. this.fs = fs$f.createFileSystemAdapter(this._options.fs);
  12052. this.markSymbolicLink = this._getValue(this._options.markSymbolicLink, false);
  12053. this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true);
  12054. }
  12055. _getValue(option, value) {
  12056. return option !== null && option !== void 0 ? option : value;
  12057. }
  12058. }
  12059. settings$3.default = Settings$2;
  12060. Object.defineProperty(out$3, "__esModule", { value: true });
  12061. out$3.statSync = out$3.stat = out$3.Settings = void 0;
  12062. const async$4 = async$5;
  12063. const sync$9 = sync$a;
  12064. const settings_1$3 = settings$3;
  12065. out$3.Settings = settings_1$3.default;
  12066. function stat$4(path, optionsOrSettingsOrCallback, callback) {
  12067. if (typeof optionsOrSettingsOrCallback === 'function') {
  12068. async$4.read(path, getSettings$2(), optionsOrSettingsOrCallback);
  12069. return;
  12070. }
  12071. async$4.read(path, getSettings$2(optionsOrSettingsOrCallback), callback);
  12072. }
  12073. out$3.stat = stat$4;
  12074. function statSync(path, optionsOrSettings) {
  12075. const settings = getSettings$2(optionsOrSettings);
  12076. return sync$9.read(path, settings);
  12077. }
  12078. out$3.statSync = statSync;
  12079. function getSettings$2(settingsOrOptions = {}) {
  12080. if (settingsOrOptions instanceof settings_1$3.default) {
  12081. return settingsOrOptions;
  12082. }
  12083. return new settings_1$3.default(settingsOrOptions);
  12084. }
  12085. var out$2 = {};
  12086. var async$3 = {};
  12087. var async$2 = {};
  12088. var out$1 = {};
  12089. var async$1 = {};
  12090. /*! queue-microtask. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
  12091. let promise;
  12092. var queueMicrotask_1 = typeof queueMicrotask === 'function'
  12093. ? queueMicrotask.bind(typeof window !== 'undefined' ? window : commonjsGlobal)
  12094. // reuse resolved promise, and allocate it lazily
  12095. : cb => (promise || (promise = Promise.resolve()))
  12096. .then(cb)
  12097. .catch(err => setTimeout(() => { throw err }, 0));
  12098. /*! run-parallel. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
  12099. var runParallel_1 = runParallel;
  12100. const queueMicrotask$1 = queueMicrotask_1;
  12101. function runParallel (tasks, cb) {
  12102. let results, pending, keys;
  12103. let isSync = true;
  12104. if (Array.isArray(tasks)) {
  12105. results = [];
  12106. pending = tasks.length;
  12107. } else {
  12108. keys = Object.keys(tasks);
  12109. results = {};
  12110. pending = keys.length;
  12111. }
  12112. function done (err) {
  12113. function end () {
  12114. if (cb) cb(err, results);
  12115. cb = null;
  12116. }
  12117. if (isSync) queueMicrotask$1(end);
  12118. else end();
  12119. }
  12120. function each (i, err, result) {
  12121. results[i] = result;
  12122. if (--pending === 0 || err) {
  12123. done(err);
  12124. }
  12125. }
  12126. if (!pending) {
  12127. // empty
  12128. done(null);
  12129. } else if (keys) {
  12130. // object
  12131. keys.forEach(function (key) {
  12132. tasks[key](function (err, result) { each(key, err, result); });
  12133. });
  12134. } else {
  12135. // array
  12136. tasks.forEach(function (task, i) {
  12137. task(function (err, result) { each(i, err, result); });
  12138. });
  12139. }
  12140. isSync = false;
  12141. }
  12142. var constants$2 = {};
  12143. Object.defineProperty(constants$2, "__esModule", { value: true });
  12144. constants$2.IS_SUPPORT_READDIR_WITH_FILE_TYPES = void 0;
  12145. const NODE_PROCESS_VERSION_PARTS = process.versions.node.split('.');
  12146. if (NODE_PROCESS_VERSION_PARTS[0] === undefined || NODE_PROCESS_VERSION_PARTS[1] === undefined) {
  12147. throw new Error(`Unexpected behavior. The 'process.versions.node' variable has invalid value: ${process.versions.node}`);
  12148. }
  12149. const MAJOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[0], 10);
  12150. const MINOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[1], 10);
  12151. const SUPPORTED_MAJOR_VERSION = 10;
  12152. const SUPPORTED_MINOR_VERSION = 10;
  12153. const IS_MATCHED_BY_MAJOR = MAJOR_VERSION > SUPPORTED_MAJOR_VERSION;
  12154. const IS_MATCHED_BY_MAJOR_AND_MINOR = MAJOR_VERSION === SUPPORTED_MAJOR_VERSION && MINOR_VERSION >= SUPPORTED_MINOR_VERSION;
  12155. /**
  12156. * IS `true` for Node.js 10.10 and greater.
  12157. */
  12158. constants$2.IS_SUPPORT_READDIR_WITH_FILE_TYPES = IS_MATCHED_BY_MAJOR || IS_MATCHED_BY_MAJOR_AND_MINOR;
  12159. var utils$a = {};
  12160. var fs$e = {};
  12161. Object.defineProperty(fs$e, "__esModule", { value: true });
  12162. fs$e.createDirentFromStats = void 0;
  12163. class DirentFromStats {
  12164. constructor(name, stats) {
  12165. this.name = name;
  12166. this.isBlockDevice = stats.isBlockDevice.bind(stats);
  12167. this.isCharacterDevice = stats.isCharacterDevice.bind(stats);
  12168. this.isDirectory = stats.isDirectory.bind(stats);
  12169. this.isFIFO = stats.isFIFO.bind(stats);
  12170. this.isFile = stats.isFile.bind(stats);
  12171. this.isSocket = stats.isSocket.bind(stats);
  12172. this.isSymbolicLink = stats.isSymbolicLink.bind(stats);
  12173. }
  12174. }
  12175. function createDirentFromStats(name, stats) {
  12176. return new DirentFromStats(name, stats);
  12177. }
  12178. fs$e.createDirentFromStats = createDirentFromStats;
  12179. Object.defineProperty(utils$a, "__esModule", { value: true });
  12180. utils$a.fs = void 0;
  12181. const fs$d = fs$e;
  12182. utils$a.fs = fs$d;
  12183. var common$b = {};
  12184. Object.defineProperty(common$b, "__esModule", { value: true });
  12185. common$b.joinPathSegments = void 0;
  12186. function joinPathSegments$1(a, b, separator) {
  12187. /**
  12188. * The correct handling of cases when the first segment is a root (`/`, `C:/`) or UNC path (`//?/C:/`).
  12189. */
  12190. if (a.endsWith(separator)) {
  12191. return a + b;
  12192. }
  12193. return a + separator + b;
  12194. }
  12195. common$b.joinPathSegments = joinPathSegments$1;
  12196. Object.defineProperty(async$1, "__esModule", { value: true });
  12197. async$1.readdir = async$1.readdirWithFileTypes = async$1.read = void 0;
  12198. const fsStat$5 = out$3;
  12199. const rpl = runParallel_1;
  12200. const constants_1$1 = constants$2;
  12201. const utils$9 = utils$a;
  12202. const common$a = common$b;
  12203. function read$2(directory, settings, callback) {
  12204. if (!settings.stats && constants_1$1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) {
  12205. readdirWithFileTypes$1(directory, settings, callback);
  12206. return;
  12207. }
  12208. readdir$3(directory, settings, callback);
  12209. }
  12210. async$1.read = read$2;
  12211. function readdirWithFileTypes$1(directory, settings, callback) {
  12212. settings.fs.readdir(directory, { withFileTypes: true }, (readdirError, dirents) => {
  12213. if (readdirError !== null) {
  12214. callFailureCallback$1(callback, readdirError);
  12215. return;
  12216. }
  12217. const entries = dirents.map((dirent) => ({
  12218. dirent,
  12219. name: dirent.name,
  12220. path: common$a.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator)
  12221. }));
  12222. if (!settings.followSymbolicLinks) {
  12223. callSuccessCallback$1(callback, entries);
  12224. return;
  12225. }
  12226. const tasks = entries.map((entry) => makeRplTaskEntry(entry, settings));
  12227. rpl(tasks, (rplError, rplEntries) => {
  12228. if (rplError !== null) {
  12229. callFailureCallback$1(callback, rplError);
  12230. return;
  12231. }
  12232. callSuccessCallback$1(callback, rplEntries);
  12233. });
  12234. });
  12235. }
  12236. async$1.readdirWithFileTypes = readdirWithFileTypes$1;
  12237. function makeRplTaskEntry(entry, settings) {
  12238. return (done) => {
  12239. if (!entry.dirent.isSymbolicLink()) {
  12240. done(null, entry);
  12241. return;
  12242. }
  12243. settings.fs.stat(entry.path, (statError, stats) => {
  12244. if (statError !== null) {
  12245. if (settings.throwErrorOnBrokenSymbolicLink) {
  12246. done(statError);
  12247. return;
  12248. }
  12249. done(null, entry);
  12250. return;
  12251. }
  12252. entry.dirent = utils$9.fs.createDirentFromStats(entry.name, stats);
  12253. done(null, entry);
  12254. });
  12255. };
  12256. }
  12257. function readdir$3(directory, settings, callback) {
  12258. settings.fs.readdir(directory, (readdirError, names) => {
  12259. if (readdirError !== null) {
  12260. callFailureCallback$1(callback, readdirError);
  12261. return;
  12262. }
  12263. const tasks = names.map((name) => {
  12264. const path = common$a.joinPathSegments(directory, name, settings.pathSegmentSeparator);
  12265. return (done) => {
  12266. fsStat$5.stat(path, settings.fsStatSettings, (error, stats) => {
  12267. if (error !== null) {
  12268. done(error);
  12269. return;
  12270. }
  12271. const entry = {
  12272. name,
  12273. path,
  12274. dirent: utils$9.fs.createDirentFromStats(name, stats)
  12275. };
  12276. if (settings.stats) {
  12277. entry.stats = stats;
  12278. }
  12279. done(null, entry);
  12280. });
  12281. };
  12282. });
  12283. rpl(tasks, (rplError, entries) => {
  12284. if (rplError !== null) {
  12285. callFailureCallback$1(callback, rplError);
  12286. return;
  12287. }
  12288. callSuccessCallback$1(callback, entries);
  12289. });
  12290. });
  12291. }
  12292. async$1.readdir = readdir$3;
  12293. function callFailureCallback$1(callback, error) {
  12294. callback(error);
  12295. }
  12296. function callSuccessCallback$1(callback, result) {
  12297. callback(null, result);
  12298. }
  12299. var sync$8 = {};
  12300. Object.defineProperty(sync$8, "__esModule", { value: true });
  12301. sync$8.readdir = sync$8.readdirWithFileTypes = sync$8.read = void 0;
  12302. const fsStat$4 = out$3;
  12303. const constants_1 = constants$2;
  12304. const utils$8 = utils$a;
  12305. const common$9 = common$b;
  12306. function read$1(directory, settings) {
  12307. if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) {
  12308. return readdirWithFileTypes(directory, settings);
  12309. }
  12310. return readdir$2(directory, settings);
  12311. }
  12312. sync$8.read = read$1;
  12313. function readdirWithFileTypes(directory, settings) {
  12314. const dirents = settings.fs.readdirSync(directory, { withFileTypes: true });
  12315. return dirents.map((dirent) => {
  12316. const entry = {
  12317. dirent,
  12318. name: dirent.name,
  12319. path: common$9.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator)
  12320. };
  12321. if (entry.dirent.isSymbolicLink() && settings.followSymbolicLinks) {
  12322. try {
  12323. const stats = settings.fs.statSync(entry.path);
  12324. entry.dirent = utils$8.fs.createDirentFromStats(entry.name, stats);
  12325. }
  12326. catch (error) {
  12327. if (settings.throwErrorOnBrokenSymbolicLink) {
  12328. throw error;
  12329. }
  12330. }
  12331. }
  12332. return entry;
  12333. });
  12334. }
  12335. sync$8.readdirWithFileTypes = readdirWithFileTypes;
  12336. function readdir$2(directory, settings) {
  12337. const names = settings.fs.readdirSync(directory);
  12338. return names.map((name) => {
  12339. const entryPath = common$9.joinPathSegments(directory, name, settings.pathSegmentSeparator);
  12340. const stats = fsStat$4.statSync(entryPath, settings.fsStatSettings);
  12341. const entry = {
  12342. name,
  12343. path: entryPath,
  12344. dirent: utils$8.fs.createDirentFromStats(name, stats)
  12345. };
  12346. if (settings.stats) {
  12347. entry.stats = stats;
  12348. }
  12349. return entry;
  12350. });
  12351. }
  12352. sync$8.readdir = readdir$2;
  12353. var settings$2 = {};
  12354. var fs$c = {};
  12355. (function (exports) {
  12356. Object.defineProperty(exports, "__esModule", { value: true });
  12357. exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0;
  12358. const fs = fs__default;
  12359. exports.FILE_SYSTEM_ADAPTER = {
  12360. lstat: fs.lstat,
  12361. stat: fs.stat,
  12362. lstatSync: fs.lstatSync,
  12363. statSync: fs.statSync,
  12364. readdir: fs.readdir,
  12365. readdirSync: fs.readdirSync
  12366. };
  12367. function createFileSystemAdapter(fsMethods) {
  12368. if (fsMethods === undefined) {
  12369. return exports.FILE_SYSTEM_ADAPTER;
  12370. }
  12371. return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods);
  12372. }
  12373. exports.createFileSystemAdapter = createFileSystemAdapter;
  12374. }(fs$c));
  12375. Object.defineProperty(settings$2, "__esModule", { value: true });
  12376. const path$c = path__default;
  12377. const fsStat$3 = out$3;
  12378. const fs$b = fs$c;
  12379. class Settings$1 {
  12380. constructor(_options = {}) {
  12381. this._options = _options;
  12382. this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, false);
  12383. this.fs = fs$b.createFileSystemAdapter(this._options.fs);
  12384. this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path$c.sep);
  12385. this.stats = this._getValue(this._options.stats, false);
  12386. this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true);
  12387. this.fsStatSettings = new fsStat$3.Settings({
  12388. followSymbolicLink: this.followSymbolicLinks,
  12389. fs: this.fs,
  12390. throwErrorOnBrokenSymbolicLink: this.throwErrorOnBrokenSymbolicLink
  12391. });
  12392. }
  12393. _getValue(option, value) {
  12394. return option !== null && option !== void 0 ? option : value;
  12395. }
  12396. }
  12397. settings$2.default = Settings$1;
  12398. Object.defineProperty(out$1, "__esModule", { value: true });
  12399. out$1.Settings = out$1.scandirSync = out$1.scandir = void 0;
  12400. const async = async$1;
  12401. const sync$7 = sync$8;
  12402. const settings_1$2 = settings$2;
  12403. out$1.Settings = settings_1$2.default;
  12404. function scandir(path, optionsOrSettingsOrCallback, callback) {
  12405. if (typeof optionsOrSettingsOrCallback === 'function') {
  12406. async.read(path, getSettings$1(), optionsOrSettingsOrCallback);
  12407. return;
  12408. }
  12409. async.read(path, getSettings$1(optionsOrSettingsOrCallback), callback);
  12410. }
  12411. out$1.scandir = scandir;
  12412. function scandirSync(path, optionsOrSettings) {
  12413. const settings = getSettings$1(optionsOrSettings);
  12414. return sync$7.read(path, settings);
  12415. }
  12416. out$1.scandirSync = scandirSync;
  12417. function getSettings$1(settingsOrOptions = {}) {
  12418. if (settingsOrOptions instanceof settings_1$2.default) {
  12419. return settingsOrOptions;
  12420. }
  12421. return new settings_1$2.default(settingsOrOptions);
  12422. }
  12423. var queue = {exports: {}};
  12424. function reusify$1 (Constructor) {
  12425. var head = new Constructor();
  12426. var tail = head;
  12427. function get () {
  12428. var current = head;
  12429. if (current.next) {
  12430. head = current.next;
  12431. } else {
  12432. head = new Constructor();
  12433. tail = head;
  12434. }
  12435. current.next = null;
  12436. return current
  12437. }
  12438. function release (obj) {
  12439. tail.next = obj;
  12440. tail = obj;
  12441. }
  12442. return {
  12443. get: get,
  12444. release: release
  12445. }
  12446. }
  12447. var reusify_1 = reusify$1;
  12448. /* eslint-disable no-var */
  12449. var reusify = reusify_1;
  12450. function fastqueue (context, worker, concurrency) {
  12451. if (typeof context === 'function') {
  12452. concurrency = worker;
  12453. worker = context;
  12454. context = null;
  12455. }
  12456. if (concurrency < 1) {
  12457. throw new Error('fastqueue concurrency must be greater than 1')
  12458. }
  12459. var cache = reusify(Task);
  12460. var queueHead = null;
  12461. var queueTail = null;
  12462. var _running = 0;
  12463. var errorHandler = null;
  12464. var self = {
  12465. push: push,
  12466. drain: noop$3,
  12467. saturated: noop$3,
  12468. pause: pause,
  12469. paused: false,
  12470. concurrency: concurrency,
  12471. running: running,
  12472. resume: resume,
  12473. idle: idle,
  12474. length: length,
  12475. getQueue: getQueue,
  12476. unshift: unshift,
  12477. empty: noop$3,
  12478. kill: kill,
  12479. killAndDrain: killAndDrain,
  12480. error: error
  12481. };
  12482. return self
  12483. function running () {
  12484. return _running
  12485. }
  12486. function pause () {
  12487. self.paused = true;
  12488. }
  12489. function length () {
  12490. var current = queueHead;
  12491. var counter = 0;
  12492. while (current) {
  12493. current = current.next;
  12494. counter++;
  12495. }
  12496. return counter
  12497. }
  12498. function getQueue () {
  12499. var current = queueHead;
  12500. var tasks = [];
  12501. while (current) {
  12502. tasks.push(current.value);
  12503. current = current.next;
  12504. }
  12505. return tasks
  12506. }
  12507. function resume () {
  12508. if (!self.paused) return
  12509. self.paused = false;
  12510. for (var i = 0; i < self.concurrency; i++) {
  12511. _running++;
  12512. release();
  12513. }
  12514. }
  12515. function idle () {
  12516. return _running === 0 && self.length() === 0
  12517. }
  12518. function push (value, done) {
  12519. var current = cache.get();
  12520. current.context = context;
  12521. current.release = release;
  12522. current.value = value;
  12523. current.callback = done || noop$3;
  12524. current.errorHandler = errorHandler;
  12525. if (_running === self.concurrency || self.paused) {
  12526. if (queueTail) {
  12527. queueTail.next = current;
  12528. queueTail = current;
  12529. } else {
  12530. queueHead = current;
  12531. queueTail = current;
  12532. self.saturated();
  12533. }
  12534. } else {
  12535. _running++;
  12536. worker.call(context, current.value, current.worked);
  12537. }
  12538. }
  12539. function unshift (value, done) {
  12540. var current = cache.get();
  12541. current.context = context;
  12542. current.release = release;
  12543. current.value = value;
  12544. current.callback = done || noop$3;
  12545. if (_running === self.concurrency || self.paused) {
  12546. if (queueHead) {
  12547. current.next = queueHead;
  12548. queueHead = current;
  12549. } else {
  12550. queueHead = current;
  12551. queueTail = current;
  12552. self.saturated();
  12553. }
  12554. } else {
  12555. _running++;
  12556. worker.call(context, current.value, current.worked);
  12557. }
  12558. }
  12559. function release (holder) {
  12560. if (holder) {
  12561. cache.release(holder);
  12562. }
  12563. var next = queueHead;
  12564. if (next) {
  12565. if (!self.paused) {
  12566. if (queueTail === queueHead) {
  12567. queueTail = null;
  12568. }
  12569. queueHead = next.next;
  12570. next.next = null;
  12571. worker.call(context, next.value, next.worked);
  12572. if (queueTail === null) {
  12573. self.empty();
  12574. }
  12575. } else {
  12576. _running--;
  12577. }
  12578. } else if (--_running === 0) {
  12579. self.drain();
  12580. }
  12581. }
  12582. function kill () {
  12583. queueHead = null;
  12584. queueTail = null;
  12585. self.drain = noop$3;
  12586. }
  12587. function killAndDrain () {
  12588. queueHead = null;
  12589. queueTail = null;
  12590. self.drain();
  12591. self.drain = noop$3;
  12592. }
  12593. function error (handler) {
  12594. errorHandler = handler;
  12595. }
  12596. }
  12597. function noop$3 () {}
  12598. function Task () {
  12599. this.value = null;
  12600. this.callback = noop$3;
  12601. this.next = null;
  12602. this.release = noop$3;
  12603. this.context = null;
  12604. this.errorHandler = null;
  12605. var self = this;
  12606. this.worked = function worked (err, result) {
  12607. var callback = self.callback;
  12608. var errorHandler = self.errorHandler;
  12609. var val = self.value;
  12610. self.value = null;
  12611. self.callback = noop$3;
  12612. if (self.errorHandler) {
  12613. errorHandler(err, val);
  12614. }
  12615. callback.call(self.context, err, result);
  12616. self.release(self);
  12617. };
  12618. }
  12619. function queueAsPromised (context, worker, concurrency) {
  12620. if (typeof context === 'function') {
  12621. concurrency = worker;
  12622. worker = context;
  12623. context = null;
  12624. }
  12625. function asyncWrapper (arg, cb) {
  12626. worker.call(this, arg)
  12627. .then(function (res) {
  12628. cb(null, res);
  12629. }, cb);
  12630. }
  12631. var queue = fastqueue(context, asyncWrapper, concurrency);
  12632. var pushCb = queue.push;
  12633. var unshiftCb = queue.unshift;
  12634. queue.push = push;
  12635. queue.unshift = unshift;
  12636. queue.drained = drained;
  12637. return queue
  12638. function push (value) {
  12639. var p = new Promise(function (resolve, reject) {
  12640. pushCb(value, function (err, result) {
  12641. if (err) {
  12642. reject(err);
  12643. return
  12644. }
  12645. resolve(result);
  12646. });
  12647. });
  12648. // Let's fork the promise chain to
  12649. // make the error bubble up to the user but
  12650. // not lead to a unhandledRejection
  12651. p.catch(noop$3);
  12652. return p
  12653. }
  12654. function unshift (value) {
  12655. var p = new Promise(function (resolve, reject) {
  12656. unshiftCb(value, function (err, result) {
  12657. if (err) {
  12658. reject(err);
  12659. return
  12660. }
  12661. resolve(result);
  12662. });
  12663. });
  12664. // Let's fork the promise chain to
  12665. // make the error bubble up to the user but
  12666. // not lead to a unhandledRejection
  12667. p.catch(noop$3);
  12668. return p
  12669. }
  12670. function drained () {
  12671. var previousDrain = queue.drain;
  12672. var p = new Promise(function (resolve) {
  12673. queue.drain = function () {
  12674. previousDrain();
  12675. resolve();
  12676. };
  12677. });
  12678. return p
  12679. }
  12680. }
  12681. queue.exports = fastqueue;
  12682. queue.exports.promise = queueAsPromised;
  12683. var common$8 = {};
  12684. Object.defineProperty(common$8, "__esModule", { value: true });
  12685. common$8.joinPathSegments = common$8.replacePathSegmentSeparator = common$8.isAppliedFilter = common$8.isFatalError = void 0;
  12686. function isFatalError(settings, error) {
  12687. if (settings.errorFilter === null) {
  12688. return true;
  12689. }
  12690. return !settings.errorFilter(error);
  12691. }
  12692. common$8.isFatalError = isFatalError;
  12693. function isAppliedFilter(filter, value) {
  12694. return filter === null || filter(value);
  12695. }
  12696. common$8.isAppliedFilter = isAppliedFilter;
  12697. function replacePathSegmentSeparator(filepath, separator) {
  12698. return filepath.split(/[/\\]/).join(separator);
  12699. }
  12700. common$8.replacePathSegmentSeparator = replacePathSegmentSeparator;
  12701. function joinPathSegments(a, b, separator) {
  12702. if (a === '') {
  12703. return b;
  12704. }
  12705. /**
  12706. * The correct handling of cases when the first segment is a root (`/`, `C:/`) or UNC path (`//?/C:/`).
  12707. */
  12708. if (a.endsWith(separator)) {
  12709. return a + b;
  12710. }
  12711. return a + separator + b;
  12712. }
  12713. common$8.joinPathSegments = joinPathSegments;
  12714. var reader$1 = {};
  12715. Object.defineProperty(reader$1, "__esModule", { value: true });
  12716. const common$7 = common$8;
  12717. class Reader$1 {
  12718. constructor(_root, _settings) {
  12719. this._root = _root;
  12720. this._settings = _settings;
  12721. this._root = common$7.replacePathSegmentSeparator(_root, _settings.pathSegmentSeparator);
  12722. }
  12723. }
  12724. reader$1.default = Reader$1;
  12725. Object.defineProperty(async$2, "__esModule", { value: true });
  12726. const events_1 = require$$0__default$1;
  12727. const fsScandir$2 = out$1;
  12728. const fastq = queue.exports;
  12729. const common$6 = common$8;
  12730. const reader_1$3 = reader$1;
  12731. class AsyncReader extends reader_1$3.default {
  12732. constructor(_root, _settings) {
  12733. super(_root, _settings);
  12734. this._settings = _settings;
  12735. this._scandir = fsScandir$2.scandir;
  12736. this._emitter = new events_1.EventEmitter();
  12737. this._queue = fastq(this._worker.bind(this), this._settings.concurrency);
  12738. this._isFatalError = false;
  12739. this._isDestroyed = false;
  12740. this._queue.drain = () => {
  12741. if (!this._isFatalError) {
  12742. this._emitter.emit('end');
  12743. }
  12744. };
  12745. }
  12746. read() {
  12747. this._isFatalError = false;
  12748. this._isDestroyed = false;
  12749. setImmediate(() => {
  12750. this._pushToQueue(this._root, this._settings.basePath);
  12751. });
  12752. return this._emitter;
  12753. }
  12754. get isDestroyed() {
  12755. return this._isDestroyed;
  12756. }
  12757. destroy() {
  12758. if (this._isDestroyed) {
  12759. throw new Error('The reader is already destroyed');
  12760. }
  12761. this._isDestroyed = true;
  12762. this._queue.killAndDrain();
  12763. }
  12764. onEntry(callback) {
  12765. this._emitter.on('entry', callback);
  12766. }
  12767. onError(callback) {
  12768. this._emitter.once('error', callback);
  12769. }
  12770. onEnd(callback) {
  12771. this._emitter.once('end', callback);
  12772. }
  12773. _pushToQueue(directory, base) {
  12774. const queueItem = { directory, base };
  12775. this._queue.push(queueItem, (error) => {
  12776. if (error !== null) {
  12777. this._handleError(error);
  12778. }
  12779. });
  12780. }
  12781. _worker(item, done) {
  12782. this._scandir(item.directory, this._settings.fsScandirSettings, (error, entries) => {
  12783. if (error !== null) {
  12784. done(error, undefined);
  12785. return;
  12786. }
  12787. for (const entry of entries) {
  12788. this._handleEntry(entry, item.base);
  12789. }
  12790. done(null, undefined);
  12791. });
  12792. }
  12793. _handleError(error) {
  12794. if (this._isDestroyed || !common$6.isFatalError(this._settings, error)) {
  12795. return;
  12796. }
  12797. this._isFatalError = true;
  12798. this._isDestroyed = true;
  12799. this._emitter.emit('error', error);
  12800. }
  12801. _handleEntry(entry, base) {
  12802. if (this._isDestroyed || this._isFatalError) {
  12803. return;
  12804. }
  12805. const fullpath = entry.path;
  12806. if (base !== undefined) {
  12807. entry.path = common$6.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator);
  12808. }
  12809. if (common$6.isAppliedFilter(this._settings.entryFilter, entry)) {
  12810. this._emitEntry(entry);
  12811. }
  12812. if (entry.dirent.isDirectory() && common$6.isAppliedFilter(this._settings.deepFilter, entry)) {
  12813. this._pushToQueue(fullpath, base === undefined ? undefined : entry.path);
  12814. }
  12815. }
  12816. _emitEntry(entry) {
  12817. this._emitter.emit('entry', entry);
  12818. }
  12819. }
  12820. async$2.default = AsyncReader;
  12821. Object.defineProperty(async$3, "__esModule", { value: true });
  12822. const async_1$3 = async$2;
  12823. class AsyncProvider {
  12824. constructor(_root, _settings) {
  12825. this._root = _root;
  12826. this._settings = _settings;
  12827. this._reader = new async_1$3.default(this._root, this._settings);
  12828. this._storage = [];
  12829. }
  12830. read(callback) {
  12831. this._reader.onError((error) => {
  12832. callFailureCallback(callback, error);
  12833. });
  12834. this._reader.onEntry((entry) => {
  12835. this._storage.push(entry);
  12836. });
  12837. this._reader.onEnd(() => {
  12838. callSuccessCallback(callback, this._storage);
  12839. });
  12840. this._reader.read();
  12841. }
  12842. }
  12843. async$3.default = AsyncProvider;
  12844. function callFailureCallback(callback, error) {
  12845. callback(error);
  12846. }
  12847. function callSuccessCallback(callback, entries) {
  12848. callback(null, entries);
  12849. }
  12850. var stream$1 = {};
  12851. Object.defineProperty(stream$1, "__esModule", { value: true });
  12852. const stream_1$5 = require$$0__default$3;
  12853. const async_1$2 = async$2;
  12854. class StreamProvider {
  12855. constructor(_root, _settings) {
  12856. this._root = _root;
  12857. this._settings = _settings;
  12858. this._reader = new async_1$2.default(this._root, this._settings);
  12859. this._stream = new stream_1$5.Readable({
  12860. objectMode: true,
  12861. read: () => { },
  12862. destroy: () => {
  12863. if (!this._reader.isDestroyed) {
  12864. this._reader.destroy();
  12865. }
  12866. }
  12867. });
  12868. }
  12869. read() {
  12870. this._reader.onError((error) => {
  12871. this._stream.emit('error', error);
  12872. });
  12873. this._reader.onEntry((entry) => {
  12874. this._stream.push(entry);
  12875. });
  12876. this._reader.onEnd(() => {
  12877. this._stream.push(null);
  12878. });
  12879. this._reader.read();
  12880. return this._stream;
  12881. }
  12882. }
  12883. stream$1.default = StreamProvider;
  12884. var sync$6 = {};
  12885. var sync$5 = {};
  12886. Object.defineProperty(sync$5, "__esModule", { value: true });
  12887. const fsScandir$1 = out$1;
  12888. const common$5 = common$8;
  12889. const reader_1$2 = reader$1;
  12890. class SyncReader extends reader_1$2.default {
  12891. constructor() {
  12892. super(...arguments);
  12893. this._scandir = fsScandir$1.scandirSync;
  12894. this._storage = [];
  12895. this._queue = new Set();
  12896. }
  12897. read() {
  12898. this._pushToQueue(this._root, this._settings.basePath);
  12899. this._handleQueue();
  12900. return this._storage;
  12901. }
  12902. _pushToQueue(directory, base) {
  12903. this._queue.add({ directory, base });
  12904. }
  12905. _handleQueue() {
  12906. for (const item of this._queue.values()) {
  12907. this._handleDirectory(item.directory, item.base);
  12908. }
  12909. }
  12910. _handleDirectory(directory, base) {
  12911. try {
  12912. const entries = this._scandir(directory, this._settings.fsScandirSettings);
  12913. for (const entry of entries) {
  12914. this._handleEntry(entry, base);
  12915. }
  12916. }
  12917. catch (error) {
  12918. this._handleError(error);
  12919. }
  12920. }
  12921. _handleError(error) {
  12922. if (!common$5.isFatalError(this._settings, error)) {
  12923. return;
  12924. }
  12925. throw error;
  12926. }
  12927. _handleEntry(entry, base) {
  12928. const fullpath = entry.path;
  12929. if (base !== undefined) {
  12930. entry.path = common$5.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator);
  12931. }
  12932. if (common$5.isAppliedFilter(this._settings.entryFilter, entry)) {
  12933. this._pushToStorage(entry);
  12934. }
  12935. if (entry.dirent.isDirectory() && common$5.isAppliedFilter(this._settings.deepFilter, entry)) {
  12936. this._pushToQueue(fullpath, base === undefined ? undefined : entry.path);
  12937. }
  12938. }
  12939. _pushToStorage(entry) {
  12940. this._storage.push(entry);
  12941. }
  12942. }
  12943. sync$5.default = SyncReader;
  12944. Object.defineProperty(sync$6, "__esModule", { value: true });
  12945. const sync_1$3 = sync$5;
  12946. class SyncProvider {
  12947. constructor(_root, _settings) {
  12948. this._root = _root;
  12949. this._settings = _settings;
  12950. this._reader = new sync_1$3.default(this._root, this._settings);
  12951. }
  12952. read() {
  12953. return this._reader.read();
  12954. }
  12955. }
  12956. sync$6.default = SyncProvider;
  12957. var settings$1 = {};
  12958. Object.defineProperty(settings$1, "__esModule", { value: true });
  12959. const path$b = path__default;
  12960. const fsScandir = out$1;
  12961. class Settings {
  12962. constructor(_options = {}) {
  12963. this._options = _options;
  12964. this.basePath = this._getValue(this._options.basePath, undefined);
  12965. this.concurrency = this._getValue(this._options.concurrency, Number.POSITIVE_INFINITY);
  12966. this.deepFilter = this._getValue(this._options.deepFilter, null);
  12967. this.entryFilter = this._getValue(this._options.entryFilter, null);
  12968. this.errorFilter = this._getValue(this._options.errorFilter, null);
  12969. this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path$b.sep);
  12970. this.fsScandirSettings = new fsScandir.Settings({
  12971. followSymbolicLinks: this._options.followSymbolicLinks,
  12972. fs: this._options.fs,
  12973. pathSegmentSeparator: this._options.pathSegmentSeparator,
  12974. stats: this._options.stats,
  12975. throwErrorOnBrokenSymbolicLink: this._options.throwErrorOnBrokenSymbolicLink
  12976. });
  12977. }
  12978. _getValue(option, value) {
  12979. return option !== null && option !== void 0 ? option : value;
  12980. }
  12981. }
  12982. settings$1.default = Settings;
  12983. Object.defineProperty(out$2, "__esModule", { value: true });
  12984. out$2.Settings = out$2.walkStream = out$2.walkSync = out$2.walk = void 0;
  12985. const async_1$1 = async$3;
  12986. const stream_1$4 = stream$1;
  12987. const sync_1$2 = sync$6;
  12988. const settings_1$1 = settings$1;
  12989. out$2.Settings = settings_1$1.default;
  12990. function walk$1(directory, optionsOrSettingsOrCallback, callback) {
  12991. if (typeof optionsOrSettingsOrCallback === 'function') {
  12992. new async_1$1.default(directory, getSettings()).read(optionsOrSettingsOrCallback);
  12993. return;
  12994. }
  12995. new async_1$1.default(directory, getSettings(optionsOrSettingsOrCallback)).read(callback);
  12996. }
  12997. out$2.walk = walk$1;
  12998. function walkSync(directory, optionsOrSettings) {
  12999. const settings = getSettings(optionsOrSettings);
  13000. const provider = new sync_1$2.default(directory, settings);
  13001. return provider.read();
  13002. }
  13003. out$2.walkSync = walkSync;
  13004. function walkStream(directory, optionsOrSettings) {
  13005. const settings = getSettings(optionsOrSettings);
  13006. const provider = new stream_1$4.default(directory, settings);
  13007. return provider.read();
  13008. }
  13009. out$2.walkStream = walkStream;
  13010. function getSettings(settingsOrOptions = {}) {
  13011. if (settingsOrOptions instanceof settings_1$1.default) {
  13012. return settingsOrOptions;
  13013. }
  13014. return new settings_1$1.default(settingsOrOptions);
  13015. }
  13016. var reader = {};
  13017. Object.defineProperty(reader, "__esModule", { value: true });
  13018. const path$a = path__default;
  13019. const fsStat$2 = out$3;
  13020. const utils$7 = utils$h;
  13021. class Reader {
  13022. constructor(_settings) {
  13023. this._settings = _settings;
  13024. this._fsStatSettings = new fsStat$2.Settings({
  13025. followSymbolicLink: this._settings.followSymbolicLinks,
  13026. fs: this._settings.fs,
  13027. throwErrorOnBrokenSymbolicLink: this._settings.followSymbolicLinks
  13028. });
  13029. }
  13030. _getFullEntryPath(filepath) {
  13031. return path$a.resolve(this._settings.cwd, filepath);
  13032. }
  13033. _makeEntry(stats, pattern) {
  13034. const entry = {
  13035. name: pattern,
  13036. path: pattern,
  13037. dirent: utils$7.fs.createDirentFromStats(pattern, stats)
  13038. };
  13039. if (this._settings.stats) {
  13040. entry.stats = stats;
  13041. }
  13042. return entry;
  13043. }
  13044. _isFatalError(error) {
  13045. return !utils$7.errno.isEnoentCodeError(error) && !this._settings.suppressErrors;
  13046. }
  13047. }
  13048. reader.default = Reader;
  13049. Object.defineProperty(stream$2, "__esModule", { value: true });
  13050. const stream_1$3 = require$$0__default$3;
  13051. const fsStat$1 = out$3;
  13052. const fsWalk$1 = out$2;
  13053. const reader_1$1 = reader;
  13054. class ReaderStream extends reader_1$1.default {
  13055. constructor() {
  13056. super(...arguments);
  13057. this._walkStream = fsWalk$1.walkStream;
  13058. this._stat = fsStat$1.stat;
  13059. }
  13060. dynamic(root, options) {
  13061. return this._walkStream(root, options);
  13062. }
  13063. static(patterns, options) {
  13064. const filepaths = patterns.map(this._getFullEntryPath, this);
  13065. const stream = new stream_1$3.PassThrough({ objectMode: true });
  13066. stream._write = (index, _enc, done) => {
  13067. return this._getEntry(filepaths[index], patterns[index], options)
  13068. .then((entry) => {
  13069. if (entry !== null && options.entryFilter(entry)) {
  13070. stream.push(entry);
  13071. }
  13072. if (index === filepaths.length - 1) {
  13073. stream.end();
  13074. }
  13075. done();
  13076. })
  13077. .catch(done);
  13078. };
  13079. for (let i = 0; i < filepaths.length; i++) {
  13080. stream.write(i);
  13081. }
  13082. return stream;
  13083. }
  13084. _getEntry(filepath, pattern, options) {
  13085. return this._getStat(filepath)
  13086. .then((stats) => this._makeEntry(stats, pattern))
  13087. .catch((error) => {
  13088. if (options.errorFilter(error)) {
  13089. return null;
  13090. }
  13091. throw error;
  13092. });
  13093. }
  13094. _getStat(filepath) {
  13095. return new Promise((resolve, reject) => {
  13096. this._stat(filepath, this._fsStatSettings, (error, stats) => {
  13097. return error === null ? resolve(stats) : reject(error);
  13098. });
  13099. });
  13100. }
  13101. }
  13102. stream$2.default = ReaderStream;
  13103. var provider = {};
  13104. var deep = {};
  13105. var partial = {};
  13106. var matcher = {};
  13107. Object.defineProperty(matcher, "__esModule", { value: true });
  13108. const utils$6 = utils$h;
  13109. class Matcher {
  13110. constructor(_patterns, _settings, _micromatchOptions) {
  13111. this._patterns = _patterns;
  13112. this._settings = _settings;
  13113. this._micromatchOptions = _micromatchOptions;
  13114. this._storage = [];
  13115. this._fillStorage();
  13116. }
  13117. _fillStorage() {
  13118. /**
  13119. * The original pattern may include `{,*,**,a/*}`, which will lead to problems with matching (unresolved level).
  13120. * So, before expand patterns with brace expansion into separated patterns.
  13121. */
  13122. const patterns = utils$6.pattern.expandPatternsWithBraceExpansion(this._patterns);
  13123. for (const pattern of patterns) {
  13124. const segments = this._getPatternSegments(pattern);
  13125. const sections = this._splitSegmentsIntoSections(segments);
  13126. this._storage.push({
  13127. complete: sections.length <= 1,
  13128. pattern,
  13129. segments,
  13130. sections
  13131. });
  13132. }
  13133. }
  13134. _getPatternSegments(pattern) {
  13135. const parts = utils$6.pattern.getPatternParts(pattern, this._micromatchOptions);
  13136. return parts.map((part) => {
  13137. const dynamic = utils$6.pattern.isDynamicPattern(part, this._settings);
  13138. if (!dynamic) {
  13139. return {
  13140. dynamic: false,
  13141. pattern: part
  13142. };
  13143. }
  13144. return {
  13145. dynamic: true,
  13146. pattern: part,
  13147. patternRe: utils$6.pattern.makeRe(part, this._micromatchOptions)
  13148. };
  13149. });
  13150. }
  13151. _splitSegmentsIntoSections(segments) {
  13152. return utils$6.array.splitWhen(segments, (segment) => segment.dynamic && utils$6.pattern.hasGlobStar(segment.pattern));
  13153. }
  13154. }
  13155. matcher.default = Matcher;
  13156. Object.defineProperty(partial, "__esModule", { value: true });
  13157. const matcher_1 = matcher;
  13158. class PartialMatcher extends matcher_1.default {
  13159. match(filepath) {
  13160. const parts = filepath.split('/');
  13161. const levels = parts.length;
  13162. const patterns = this._storage.filter((info) => !info.complete || info.segments.length > levels);
  13163. for (const pattern of patterns) {
  13164. const section = pattern.sections[0];
  13165. /**
  13166. * In this case, the pattern has a globstar and we must read all directories unconditionally,
  13167. * but only if the level has reached the end of the first group.
  13168. *
  13169. * fixtures/{a,b}/**
  13170. * ^ true/false ^ always true
  13171. */
  13172. if (!pattern.complete && levels > section.length) {
  13173. return true;
  13174. }
  13175. const match = parts.every((part, index) => {
  13176. const segment = pattern.segments[index];
  13177. if (segment.dynamic && segment.patternRe.test(part)) {
  13178. return true;
  13179. }
  13180. if (!segment.dynamic && segment.pattern === part) {
  13181. return true;
  13182. }
  13183. return false;
  13184. });
  13185. if (match) {
  13186. return true;
  13187. }
  13188. }
  13189. return false;
  13190. }
  13191. }
  13192. partial.default = PartialMatcher;
  13193. Object.defineProperty(deep, "__esModule", { value: true });
  13194. const utils$5 = utils$h;
  13195. const partial_1 = partial;
  13196. class DeepFilter {
  13197. constructor(_settings, _micromatchOptions) {
  13198. this._settings = _settings;
  13199. this._micromatchOptions = _micromatchOptions;
  13200. }
  13201. getFilter(basePath, positive, negative) {
  13202. const matcher = this._getMatcher(positive);
  13203. const negativeRe = this._getNegativePatternsRe(negative);
  13204. return (entry) => this._filter(basePath, entry, matcher, negativeRe);
  13205. }
  13206. _getMatcher(patterns) {
  13207. return new partial_1.default(patterns, this._settings, this._micromatchOptions);
  13208. }
  13209. _getNegativePatternsRe(patterns) {
  13210. const affectDepthOfReadingPatterns = patterns.filter(utils$5.pattern.isAffectDepthOfReadingPattern);
  13211. return utils$5.pattern.convertPatternsToRe(affectDepthOfReadingPatterns, this._micromatchOptions);
  13212. }
  13213. _filter(basePath, entry, matcher, negativeRe) {
  13214. if (this._isSkippedByDeep(basePath, entry.path)) {
  13215. return false;
  13216. }
  13217. if (this._isSkippedSymbolicLink(entry)) {
  13218. return false;
  13219. }
  13220. const filepath = utils$5.path.removeLeadingDotSegment(entry.path);
  13221. if (this._isSkippedByPositivePatterns(filepath, matcher)) {
  13222. return false;
  13223. }
  13224. return this._isSkippedByNegativePatterns(filepath, negativeRe);
  13225. }
  13226. _isSkippedByDeep(basePath, entryPath) {
  13227. /**
  13228. * Avoid unnecessary depth calculations when it doesn't matter.
  13229. */
  13230. if (this._settings.deep === Infinity) {
  13231. return false;
  13232. }
  13233. return this._getEntryLevel(basePath, entryPath) >= this._settings.deep;
  13234. }
  13235. _getEntryLevel(basePath, entryPath) {
  13236. const entryPathDepth = entryPath.split('/').length;
  13237. if (basePath === '') {
  13238. return entryPathDepth;
  13239. }
  13240. const basePathDepth = basePath.split('/').length;
  13241. return entryPathDepth - basePathDepth;
  13242. }
  13243. _isSkippedSymbolicLink(entry) {
  13244. return !this._settings.followSymbolicLinks && entry.dirent.isSymbolicLink();
  13245. }
  13246. _isSkippedByPositivePatterns(entryPath, matcher) {
  13247. return !this._settings.baseNameMatch && !matcher.match(entryPath);
  13248. }
  13249. _isSkippedByNegativePatterns(entryPath, patternsRe) {
  13250. return !utils$5.pattern.matchAny(entryPath, patternsRe);
  13251. }
  13252. }
  13253. deep.default = DeepFilter;
  13254. var entry$1 = {};
  13255. Object.defineProperty(entry$1, "__esModule", { value: true });
  13256. const utils$4 = utils$h;
  13257. class EntryFilter {
  13258. constructor(_settings, _micromatchOptions) {
  13259. this._settings = _settings;
  13260. this._micromatchOptions = _micromatchOptions;
  13261. this.index = new Map();
  13262. }
  13263. getFilter(positive, negative) {
  13264. const positiveRe = utils$4.pattern.convertPatternsToRe(positive, this._micromatchOptions);
  13265. const negativeRe = utils$4.pattern.convertPatternsToRe(negative, this._micromatchOptions);
  13266. return (entry) => this._filter(entry, positiveRe, negativeRe);
  13267. }
  13268. _filter(entry, positiveRe, negativeRe) {
  13269. if (this._settings.unique && this._isDuplicateEntry(entry)) {
  13270. return false;
  13271. }
  13272. if (this._onlyFileFilter(entry) || this._onlyDirectoryFilter(entry)) {
  13273. return false;
  13274. }
  13275. if (this._isSkippedByAbsoluteNegativePatterns(entry.path, negativeRe)) {
  13276. return false;
  13277. }
  13278. const filepath = this._settings.baseNameMatch ? entry.name : entry.path;
  13279. const isMatched = this._isMatchToPatterns(filepath, positiveRe) && !this._isMatchToPatterns(entry.path, negativeRe);
  13280. if (this._settings.unique && isMatched) {
  13281. this._createIndexRecord(entry);
  13282. }
  13283. return isMatched;
  13284. }
  13285. _isDuplicateEntry(entry) {
  13286. return this.index.has(entry.path);
  13287. }
  13288. _createIndexRecord(entry) {
  13289. this.index.set(entry.path, undefined);
  13290. }
  13291. _onlyFileFilter(entry) {
  13292. return this._settings.onlyFiles && !entry.dirent.isFile();
  13293. }
  13294. _onlyDirectoryFilter(entry) {
  13295. return this._settings.onlyDirectories && !entry.dirent.isDirectory();
  13296. }
  13297. _isSkippedByAbsoluteNegativePatterns(entryPath, patternsRe) {
  13298. if (!this._settings.absolute) {
  13299. return false;
  13300. }
  13301. const fullpath = utils$4.path.makeAbsolute(this._settings.cwd, entryPath);
  13302. return utils$4.pattern.matchAny(fullpath, patternsRe);
  13303. }
  13304. /**
  13305. * First, just trying to apply patterns to the path.
  13306. * Second, trying to apply patterns to the path with final slash.
  13307. */
  13308. _isMatchToPatterns(entryPath, patternsRe) {
  13309. const filepath = utils$4.path.removeLeadingDotSegment(entryPath);
  13310. return utils$4.pattern.matchAny(filepath, patternsRe) || utils$4.pattern.matchAny(filepath + '/', patternsRe);
  13311. }
  13312. }
  13313. entry$1.default = EntryFilter;
  13314. var error$3 = {};
  13315. Object.defineProperty(error$3, "__esModule", { value: true });
  13316. const utils$3 = utils$h;
  13317. class ErrorFilter {
  13318. constructor(_settings) {
  13319. this._settings = _settings;
  13320. }
  13321. getFilter() {
  13322. return (error) => this._isNonFatalError(error);
  13323. }
  13324. _isNonFatalError(error) {
  13325. return utils$3.errno.isEnoentCodeError(error) || this._settings.suppressErrors;
  13326. }
  13327. }
  13328. error$3.default = ErrorFilter;
  13329. var entry = {};
  13330. Object.defineProperty(entry, "__esModule", { value: true });
  13331. const utils$2 = utils$h;
  13332. class EntryTransformer {
  13333. constructor(_settings) {
  13334. this._settings = _settings;
  13335. }
  13336. getTransformer() {
  13337. return (entry) => this._transform(entry);
  13338. }
  13339. _transform(entry) {
  13340. let filepath = entry.path;
  13341. if (this._settings.absolute) {
  13342. filepath = utils$2.path.makeAbsolute(this._settings.cwd, filepath);
  13343. filepath = utils$2.path.unixify(filepath);
  13344. }
  13345. if (this._settings.markDirectories && entry.dirent.isDirectory()) {
  13346. filepath += '/';
  13347. }
  13348. if (!this._settings.objectMode) {
  13349. return filepath;
  13350. }
  13351. return Object.assign(Object.assign({}, entry), { path: filepath });
  13352. }
  13353. }
  13354. entry.default = EntryTransformer;
  13355. Object.defineProperty(provider, "__esModule", { value: true });
  13356. const path$9 = path__default;
  13357. const deep_1 = deep;
  13358. const entry_1 = entry$1;
  13359. const error_1 = error$3;
  13360. const entry_2 = entry;
  13361. class Provider {
  13362. constructor(_settings) {
  13363. this._settings = _settings;
  13364. this.errorFilter = new error_1.default(this._settings);
  13365. this.entryFilter = new entry_1.default(this._settings, this._getMicromatchOptions());
  13366. this.deepFilter = new deep_1.default(this._settings, this._getMicromatchOptions());
  13367. this.entryTransformer = new entry_2.default(this._settings);
  13368. }
  13369. _getRootDirectory(task) {
  13370. return path$9.resolve(this._settings.cwd, task.base);
  13371. }
  13372. _getReaderOptions(task) {
  13373. const basePath = task.base === '.' ? '' : task.base;
  13374. return {
  13375. basePath,
  13376. pathSegmentSeparator: '/',
  13377. concurrency: this._settings.concurrency,
  13378. deepFilter: this.deepFilter.getFilter(basePath, task.positive, task.negative),
  13379. entryFilter: this.entryFilter.getFilter(task.positive, task.negative),
  13380. errorFilter: this.errorFilter.getFilter(),
  13381. followSymbolicLinks: this._settings.followSymbolicLinks,
  13382. fs: this._settings.fs,
  13383. stats: this._settings.stats,
  13384. throwErrorOnBrokenSymbolicLink: this._settings.throwErrorOnBrokenSymbolicLink,
  13385. transform: this.entryTransformer.getTransformer()
  13386. };
  13387. }
  13388. _getMicromatchOptions() {
  13389. return {
  13390. dot: this._settings.dot,
  13391. matchBase: this._settings.baseNameMatch,
  13392. nobrace: !this._settings.braceExpansion,
  13393. nocase: !this._settings.caseSensitiveMatch,
  13394. noext: !this._settings.extglob,
  13395. noglobstar: !this._settings.globstar,
  13396. posix: true,
  13397. strictSlashes: false
  13398. };
  13399. }
  13400. }
  13401. provider.default = Provider;
  13402. Object.defineProperty(async$6, "__esModule", { value: true });
  13403. const stream_1$2 = stream$2;
  13404. const provider_1$2 = provider;
  13405. class ProviderAsync extends provider_1$2.default {
  13406. constructor() {
  13407. super(...arguments);
  13408. this._reader = new stream_1$2.default(this._settings);
  13409. }
  13410. read(task) {
  13411. const root = this._getRootDirectory(task);
  13412. const options = this._getReaderOptions(task);
  13413. const entries = [];
  13414. return new Promise((resolve, reject) => {
  13415. const stream = this.api(root, task, options);
  13416. stream.once('error', reject);
  13417. stream.on('data', (entry) => entries.push(options.transform(entry)));
  13418. stream.once('end', () => resolve(entries));
  13419. });
  13420. }
  13421. api(root, task, options) {
  13422. if (task.dynamic) {
  13423. return this._reader.dynamic(root, options);
  13424. }
  13425. return this._reader.static(task.patterns, options);
  13426. }
  13427. }
  13428. async$6.default = ProviderAsync;
  13429. var stream = {};
  13430. Object.defineProperty(stream, "__esModule", { value: true });
  13431. const stream_1$1 = require$$0__default$3;
  13432. const stream_2 = stream$2;
  13433. const provider_1$1 = provider;
  13434. class ProviderStream extends provider_1$1.default {
  13435. constructor() {
  13436. super(...arguments);
  13437. this._reader = new stream_2.default(this._settings);
  13438. }
  13439. read(task) {
  13440. const root = this._getRootDirectory(task);
  13441. const options = this._getReaderOptions(task);
  13442. const source = this.api(root, task, options);
  13443. const destination = new stream_1$1.Readable({ objectMode: true, read: () => { } });
  13444. source
  13445. .once('error', (error) => destination.emit('error', error))
  13446. .on('data', (entry) => destination.emit('data', options.transform(entry)))
  13447. .once('end', () => destination.emit('end'));
  13448. destination
  13449. .once('close', () => source.destroy());
  13450. return destination;
  13451. }
  13452. api(root, task, options) {
  13453. if (task.dynamic) {
  13454. return this._reader.dynamic(root, options);
  13455. }
  13456. return this._reader.static(task.patterns, options);
  13457. }
  13458. }
  13459. stream.default = ProviderStream;
  13460. var sync$4 = {};
  13461. var sync$3 = {};
  13462. Object.defineProperty(sync$3, "__esModule", { value: true });
  13463. const fsStat = out$3;
  13464. const fsWalk = out$2;
  13465. const reader_1 = reader;
  13466. class ReaderSync extends reader_1.default {
  13467. constructor() {
  13468. super(...arguments);
  13469. this._walkSync = fsWalk.walkSync;
  13470. this._statSync = fsStat.statSync;
  13471. }
  13472. dynamic(root, options) {
  13473. return this._walkSync(root, options);
  13474. }
  13475. static(patterns, options) {
  13476. const entries = [];
  13477. for (const pattern of patterns) {
  13478. const filepath = this._getFullEntryPath(pattern);
  13479. const entry = this._getEntry(filepath, pattern, options);
  13480. if (entry === null || !options.entryFilter(entry)) {
  13481. continue;
  13482. }
  13483. entries.push(entry);
  13484. }
  13485. return entries;
  13486. }
  13487. _getEntry(filepath, pattern, options) {
  13488. try {
  13489. const stats = this._getStat(filepath);
  13490. return this._makeEntry(stats, pattern);
  13491. }
  13492. catch (error) {
  13493. if (options.errorFilter(error)) {
  13494. return null;
  13495. }
  13496. throw error;
  13497. }
  13498. }
  13499. _getStat(filepath) {
  13500. return this._statSync(filepath, this._fsStatSettings);
  13501. }
  13502. }
  13503. sync$3.default = ReaderSync;
  13504. Object.defineProperty(sync$4, "__esModule", { value: true });
  13505. const sync_1$1 = sync$3;
  13506. const provider_1 = provider;
  13507. class ProviderSync extends provider_1.default {
  13508. constructor() {
  13509. super(...arguments);
  13510. this._reader = new sync_1$1.default(this._settings);
  13511. }
  13512. read(task) {
  13513. const root = this._getRootDirectory(task);
  13514. const options = this._getReaderOptions(task);
  13515. const entries = this.api(root, task, options);
  13516. return entries.map(options.transform);
  13517. }
  13518. api(root, task, options) {
  13519. if (task.dynamic) {
  13520. return this._reader.dynamic(root, options);
  13521. }
  13522. return this._reader.static(task.patterns, options);
  13523. }
  13524. }
  13525. sync$4.default = ProviderSync;
  13526. var settings = {};
  13527. (function (exports) {
  13528. Object.defineProperty(exports, "__esModule", { value: true });
  13529. exports.DEFAULT_FILE_SYSTEM_ADAPTER = void 0;
  13530. const fs = fs__default;
  13531. const os = require$$2__default;
  13532. /**
  13533. * The `os.cpus` method can return zero. We expect the number of cores to be greater than zero.
  13534. * https://github.com/nodejs/node/blob/7faeddf23a98c53896f8b574a6e66589e8fb1eb8/lib/os.js#L106-L107
  13535. */
  13536. const CPU_COUNT = Math.max(os.cpus().length, 1);
  13537. exports.DEFAULT_FILE_SYSTEM_ADAPTER = {
  13538. lstat: fs.lstat,
  13539. lstatSync: fs.lstatSync,
  13540. stat: fs.stat,
  13541. statSync: fs.statSync,
  13542. readdir: fs.readdir,
  13543. readdirSync: fs.readdirSync
  13544. };
  13545. class Settings {
  13546. constructor(_options = {}) {
  13547. this._options = _options;
  13548. this.absolute = this._getValue(this._options.absolute, false);
  13549. this.baseNameMatch = this._getValue(this._options.baseNameMatch, false);
  13550. this.braceExpansion = this._getValue(this._options.braceExpansion, true);
  13551. this.caseSensitiveMatch = this._getValue(this._options.caseSensitiveMatch, true);
  13552. this.concurrency = this._getValue(this._options.concurrency, CPU_COUNT);
  13553. this.cwd = this._getValue(this._options.cwd, process.cwd());
  13554. this.deep = this._getValue(this._options.deep, Infinity);
  13555. this.dot = this._getValue(this._options.dot, false);
  13556. this.extglob = this._getValue(this._options.extglob, true);
  13557. this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, true);
  13558. this.fs = this._getFileSystemMethods(this._options.fs);
  13559. this.globstar = this._getValue(this._options.globstar, true);
  13560. this.ignore = this._getValue(this._options.ignore, []);
  13561. this.markDirectories = this._getValue(this._options.markDirectories, false);
  13562. this.objectMode = this._getValue(this._options.objectMode, false);
  13563. this.onlyDirectories = this._getValue(this._options.onlyDirectories, false);
  13564. this.onlyFiles = this._getValue(this._options.onlyFiles, true);
  13565. this.stats = this._getValue(this._options.stats, false);
  13566. this.suppressErrors = this._getValue(this._options.suppressErrors, false);
  13567. this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, false);
  13568. this.unique = this._getValue(this._options.unique, true);
  13569. if (this.onlyDirectories) {
  13570. this.onlyFiles = false;
  13571. }
  13572. if (this.stats) {
  13573. this.objectMode = true;
  13574. }
  13575. }
  13576. _getValue(option, value) {
  13577. return option === undefined ? value : option;
  13578. }
  13579. _getFileSystemMethods(methods = {}) {
  13580. return Object.assign(Object.assign({}, exports.DEFAULT_FILE_SYSTEM_ADAPTER), methods);
  13581. }
  13582. }
  13583. exports.default = Settings;
  13584. }(settings));
  13585. const taskManager = tasks;
  13586. const patternManager = patterns;
  13587. const async_1 = async$6;
  13588. const stream_1 = stream;
  13589. const sync_1 = sync$4;
  13590. const settings_1 = settings;
  13591. const utils$1 = utils$h;
  13592. async function FastGlob(source, options) {
  13593. assertPatternsInput(source);
  13594. const works = getWorks(source, async_1.default, options);
  13595. const result = await Promise.all(works);
  13596. return utils$1.array.flatten(result);
  13597. }
  13598. // https://github.com/typescript-eslint/typescript-eslint/issues/60
  13599. // eslint-disable-next-line no-redeclare
  13600. (function (FastGlob) {
  13601. function sync(source, options) {
  13602. assertPatternsInput(source);
  13603. const works = getWorks(source, sync_1.default, options);
  13604. return utils$1.array.flatten(works);
  13605. }
  13606. FastGlob.sync = sync;
  13607. function stream(source, options) {
  13608. assertPatternsInput(source);
  13609. const works = getWorks(source, stream_1.default, options);
  13610. /**
  13611. * The stream returned by the provider cannot work with an asynchronous iterator.
  13612. * To support asynchronous iterators, regardless of the number of tasks, we always multiplex streams.
  13613. * This affects performance (+25%). I don't see best solution right now.
  13614. */
  13615. return utils$1.stream.merge(works);
  13616. }
  13617. FastGlob.stream = stream;
  13618. function generateTasks(source, options) {
  13619. assertPatternsInput(source);
  13620. const patterns = patternManager.transform([].concat(source));
  13621. const settings = new settings_1.default(options);
  13622. return taskManager.generate(patterns, settings);
  13623. }
  13624. FastGlob.generateTasks = generateTasks;
  13625. function isDynamicPattern(source, options) {
  13626. assertPatternsInput(source);
  13627. const settings = new settings_1.default(options);
  13628. return utils$1.pattern.isDynamicPattern(source, settings);
  13629. }
  13630. FastGlob.isDynamicPattern = isDynamicPattern;
  13631. function escapePath(source) {
  13632. assertPatternsInput(source);
  13633. return utils$1.path.escape(source);
  13634. }
  13635. FastGlob.escapePath = escapePath;
  13636. })(FastGlob || (FastGlob = {}));
  13637. function getWorks(source, _Provider, options) {
  13638. const patterns = patternManager.transform([].concat(source));
  13639. const settings = new settings_1.default(options);
  13640. const tasks = taskManager.generate(patterns, settings);
  13641. const provider = new _Provider(settings);
  13642. return tasks.map(provider.read, provider);
  13643. }
  13644. function assertPatternsInput(input) {
  13645. const source = [].concat(input);
  13646. const isValidSource = source.every((item) => utils$1.string.isString(item) && !utils$1.string.isEmpty(item));
  13647. if (!isValidSource) {
  13648. throw new TypeError('Patterns must be a string (non empty) or an array of strings');
  13649. }
  13650. }
  13651. var out = FastGlob;
  13652. class VariableDynamicImportError extends Error {}
  13653. /* eslint-disable-next-line no-template-curly-in-string */
  13654. const example = 'For example: import(`./foo/${bar}.js`).';
  13655. function sanitizeString(str) {
  13656. if (str.includes('*')) {
  13657. throw new VariableDynamicImportError('A dynamic import cannot contain * characters.');
  13658. }
  13659. return str;
  13660. }
  13661. function templateLiteralToGlob(node) {
  13662. let glob = '';
  13663. for (let i = 0; i < node.quasis.length; i += 1) {
  13664. glob += sanitizeString(node.quasis[i].value.raw);
  13665. if (node.expressions[i]) {
  13666. glob += expressionToGlob(node.expressions[i]);
  13667. }
  13668. }
  13669. return glob;
  13670. }
  13671. function callExpressionToGlob(node) {
  13672. const { callee } = node;
  13673. if (
  13674. callee.type === 'MemberExpression' &&
  13675. callee.property.type === 'Identifier' &&
  13676. callee.property.name === 'concat'
  13677. ) {
  13678. return `${expressionToGlob(callee.object)}${node.arguments.map(expressionToGlob).join('')}`;
  13679. }
  13680. return '*';
  13681. }
  13682. function binaryExpressionToGlob(node) {
  13683. if (node.operator !== '+') {
  13684. throw new VariableDynamicImportError(`${node.operator} operator is not supported.`);
  13685. }
  13686. return `${expressionToGlob(node.left)}${expressionToGlob(node.right)}`;
  13687. }
  13688. function expressionToGlob(node) {
  13689. switch (node.type) {
  13690. case 'TemplateLiteral':
  13691. return templateLiteralToGlob(node);
  13692. case 'CallExpression':
  13693. return callExpressionToGlob(node);
  13694. case 'BinaryExpression':
  13695. return binaryExpressionToGlob(node);
  13696. case 'Literal': {
  13697. return sanitizeString(node.value);
  13698. }
  13699. default:
  13700. return '*';
  13701. }
  13702. }
  13703. function dynamicImportToGlob(node, sourceString) {
  13704. let glob = expressionToGlob(node);
  13705. if (!glob.includes('*') || glob.startsWith('data:')) {
  13706. return null;
  13707. }
  13708. glob = glob.replace(/\*\*/g, '*');
  13709. if (glob.startsWith('*')) {
  13710. throw new VariableDynamicImportError(
  13711. `invalid import "${sourceString}". It cannot be statically analyzed. Variable dynamic imports must start with ./ and be limited to a specific directory. ${example}`
  13712. );
  13713. }
  13714. if (glob.startsWith('/')) {
  13715. throw new VariableDynamicImportError(
  13716. `invalid import "${sourceString}". Variable absolute imports are not supported, imports must start with ./ in the static part of the import. ${example}`
  13717. );
  13718. }
  13719. if (!glob.startsWith('./') && !glob.startsWith('../')) {
  13720. throw new VariableDynamicImportError(
  13721. `invalid import "${sourceString}". Variable bare imports are not supported, imports must start with ./ in the static part of the import. ${example}`
  13722. );
  13723. }
  13724. // Disallow ./*.ext
  13725. const ownDirectoryStarExtension = /^\.\/\*\.[\w]+$/;
  13726. if (ownDirectoryStarExtension.test(glob)) {
  13727. throw new VariableDynamicImportError(
  13728. `${
  13729. `invalid import "${sourceString}". Variable imports cannot import their own directory, ` +
  13730. 'place imports in a separate directory or make the import filename more specific. '
  13731. }${example}`
  13732. );
  13733. }
  13734. if (path__default.extname(glob) === '') {
  13735. throw new VariableDynamicImportError(
  13736. `invalid import "${sourceString}". A file extension must be included in the static part of the import. ${example}`
  13737. );
  13738. }
  13739. return glob;
  13740. }
  13741. function dynamicImportVariables({ include, exclude, warnOnError } = {}) {
  13742. const filter = createFilter$1(include, exclude);
  13743. return {
  13744. name: 'rollup-plugin-dynamic-import-variables',
  13745. transform(code, id) {
  13746. if (!filter(id)) {
  13747. return null;
  13748. }
  13749. const parsed = this.parse(code);
  13750. let dynamicImportIndex = -1;
  13751. let ms;
  13752. walk$2(parsed, {
  13753. enter: (node) => {
  13754. if (node.type !== 'ImportExpression') {
  13755. return;
  13756. }
  13757. dynamicImportIndex += 1;
  13758. try {
  13759. // see if this is a variable dynamic import, and generate a glob expression
  13760. const glob = dynamicImportToGlob(node.source, code.substring(node.start, node.end));
  13761. if (!glob) {
  13762. // this was not a variable dynamic import
  13763. return;
  13764. }
  13765. // execute the glob
  13766. const result = out.sync(glob, { cwd: path__default.dirname(id) });
  13767. const paths = result.map((r) =>
  13768. r.startsWith('./') || r.startsWith('../') ? r : `./${r}`
  13769. );
  13770. // create magic string if it wasn't created already
  13771. ms = ms || new MagicString$1(code);
  13772. // unpack variable dynamic import into a function with import statements per file, rollup
  13773. // will turn these into chunks automatically
  13774. ms.prepend(
  13775. `function __variableDynamicImportRuntime${dynamicImportIndex}__(path) {
  13776. switch (path) {
  13777. ${paths.map((p) => ` case '${p}': return import('${p}');`).join('\n')}
  13778. ${` default: return new Promise(function(resolve, reject) {
  13779. (typeof queueMicrotask === 'function' ? queueMicrotask : setTimeout)(
  13780. reject.bind(null, new Error("Unknown variable dynamic import: " + path))
  13781. );
  13782. })\n`} }
  13783. }\n\n`
  13784. );
  13785. // call the runtime function instead of doing a dynamic import, the import specifier will
  13786. // be evaluated at runtime and the correct import will be returned by the injected function
  13787. ms.overwrite(
  13788. node.start,
  13789. node.start + 6,
  13790. `__variableDynamicImportRuntime${dynamicImportIndex}__`
  13791. );
  13792. } catch (error) {
  13793. if (error instanceof VariableDynamicImportError) {
  13794. // TODO: line number
  13795. if (warnOnError) {
  13796. this.warn(error);
  13797. } else {
  13798. this.error(error);
  13799. }
  13800. } else {
  13801. this.error(error);
  13802. }
  13803. }
  13804. }
  13805. });
  13806. if (ms && dynamicImportIndex !== -1) {
  13807. return {
  13808. code: ms.toString(),
  13809. map: ms.generateMap({
  13810. file: id,
  13811. includeContent: true,
  13812. hires: true
  13813. })
  13814. };
  13815. }
  13816. return null;
  13817. }
  13818. };
  13819. }
  13820. const comma = 44;
  13821. const semicolon = 59;
  13822. const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  13823. const intToChar = new Uint8Array(65); // 65 possible chars.
  13824. const charToInteger = new Uint8Array(123); // z is 122 in ASCII
  13825. for (let i = 0; i < chars.length; i++) {
  13826. const c = chars.charCodeAt(i);
  13827. charToInteger[c] = i;
  13828. intToChar[i] = c;
  13829. }
  13830. // Provide a fallback for older environments.
  13831. const td = typeof TextDecoder !== 'undefined'
  13832. ? new TextDecoder()
  13833. : typeof Buffer !== 'undefined'
  13834. ? {
  13835. decode(buf) {
  13836. const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
  13837. return out.toString();
  13838. },
  13839. }
  13840. : {
  13841. decode(buf) {
  13842. let out = '';
  13843. for (let i = 0; i < buf.length; i++) {
  13844. out += String.fromCharCode(buf[i]);
  13845. }
  13846. return out;
  13847. },
  13848. };
  13849. function decode(mappings) {
  13850. const state = new Int32Array(5);
  13851. const decoded = [];
  13852. let line = [];
  13853. let sorted = true;
  13854. let lastCol = 0;
  13855. for (let i = 0; i < mappings.length;) {
  13856. const c = mappings.charCodeAt(i);
  13857. if (c === comma) {
  13858. i++;
  13859. }
  13860. else if (c === semicolon) {
  13861. state[0] = lastCol = 0;
  13862. if (!sorted)
  13863. sort(line);
  13864. sorted = true;
  13865. decoded.push(line);
  13866. line = [];
  13867. i++;
  13868. }
  13869. else {
  13870. i = decodeInteger(mappings, i, state, 0); // generatedCodeColumn
  13871. const col = state[0];
  13872. if (col < lastCol)
  13873. sorted = false;
  13874. lastCol = col;
  13875. if (!hasMoreSegments(mappings, i)) {
  13876. line.push([col]);
  13877. continue;
  13878. }
  13879. i = decodeInteger(mappings, i, state, 1); // sourceFileIndex
  13880. i = decodeInteger(mappings, i, state, 2); // sourceCodeLine
  13881. i = decodeInteger(mappings, i, state, 3); // sourceCodeColumn
  13882. if (!hasMoreSegments(mappings, i)) {
  13883. line.push([col, state[1], state[2], state[3]]);
  13884. continue;
  13885. }
  13886. i = decodeInteger(mappings, i, state, 4); // nameIndex
  13887. line.push([col, state[1], state[2], state[3], state[4]]);
  13888. }
  13889. }
  13890. if (!sorted)
  13891. sort(line);
  13892. decoded.push(line);
  13893. return decoded;
  13894. }
  13895. function decodeInteger(mappings, pos, state, j) {
  13896. let value = 0;
  13897. let shift = 0;
  13898. let integer = 0;
  13899. do {
  13900. const c = mappings.charCodeAt(pos++);
  13901. integer = charToInteger[c];
  13902. value |= (integer & 31) << shift;
  13903. shift += 5;
  13904. } while (integer & 32);
  13905. const shouldNegate = value & 1;
  13906. value >>>= 1;
  13907. if (shouldNegate) {
  13908. value = value === 0 ? -0x80000000 : -value;
  13909. }
  13910. state[j] += value;
  13911. return pos;
  13912. }
  13913. function hasMoreSegments(mappings, i) {
  13914. if (i >= mappings.length)
  13915. return false;
  13916. const c = mappings.charCodeAt(i);
  13917. if (c === comma || c === semicolon)
  13918. return false;
  13919. return true;
  13920. }
  13921. function sort(line) {
  13922. line.sort(sortComparator$1);
  13923. }
  13924. function sortComparator$1(a, b) {
  13925. return a[0] - b[0];
  13926. }
  13927. function encode(decoded) {
  13928. const state = new Int32Array(5);
  13929. let buf = new Uint8Array(1000);
  13930. let pos = 0;
  13931. for (let i = 0; i < decoded.length; i++) {
  13932. const line = decoded[i];
  13933. if (i > 0) {
  13934. buf = reserve(buf, pos, 1);
  13935. buf[pos++] = semicolon;
  13936. }
  13937. if (line.length === 0)
  13938. continue;
  13939. state[0] = 0;
  13940. for (let j = 0; j < line.length; j++) {
  13941. const segment = line[j];
  13942. // We can push up to 5 ints, each int can take at most 7 chars, and we
  13943. // may push a comma.
  13944. buf = reserve(buf, pos, 36);
  13945. if (j > 0)
  13946. buf[pos++] = comma;
  13947. pos = encodeInteger(buf, pos, state, segment, 0); // generatedCodeColumn
  13948. if (segment.length === 1)
  13949. continue;
  13950. pos = encodeInteger(buf, pos, state, segment, 1); // sourceFileIndex
  13951. pos = encodeInteger(buf, pos, state, segment, 2); // sourceCodeLine
  13952. pos = encodeInteger(buf, pos, state, segment, 3); // sourceCodeColumn
  13953. if (segment.length === 4)
  13954. continue;
  13955. pos = encodeInteger(buf, pos, state, segment, 4); // nameIndex
  13956. }
  13957. }
  13958. return td.decode(buf.subarray(0, pos));
  13959. }
  13960. function reserve(buf, pos, count) {
  13961. if (buf.length > pos + count)
  13962. return buf;
  13963. const swap = new Uint8Array(buf.length * 2);
  13964. swap.set(buf);
  13965. return swap;
  13966. }
  13967. function encodeInteger(buf, pos, state, segment, j) {
  13968. const next = segment[j];
  13969. let num = next - state[j];
  13970. state[j] = next;
  13971. num = num < 0 ? (-num << 1) | 1 : num << 1;
  13972. do {
  13973. let clamped = num & 31;
  13974. num >>>= 5;
  13975. if (num > 0)
  13976. clamped |= 32;
  13977. buf[pos++] = intToChar[clamped];
  13978. } while (num > 0);
  13979. return pos;
  13980. }
  13981. // Matches the scheme of a URL, eg "http://"
  13982. const schemeRegex = /^[\w+.-]+:\/\//;
  13983. /**
  13984. * Matches the parts of a URL:
  13985. * 1. Scheme, including ":", guaranteed.
  13986. * 2. User/password, including "@", optional.
  13987. * 3. Host, guaranteed.
  13988. * 4. Port, including ":", optional.
  13989. * 5. Path, including "/", optional.
  13990. */
  13991. const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?/;
  13992. function isAbsoluteUrl(input) {
  13993. return schemeRegex.test(input);
  13994. }
  13995. function isSchemeRelativeUrl(input) {
  13996. return input.startsWith('//');
  13997. }
  13998. function isAbsolutePath(input) {
  13999. return input.startsWith('/');
  14000. }
  14001. function parseAbsoluteUrl(input) {
  14002. const match = urlRegex.exec(input);
  14003. return {
  14004. scheme: match[1],
  14005. user: match[2] || '',
  14006. host: match[3],
  14007. port: match[4] || '',
  14008. path: match[5] || '/',
  14009. relativePath: false,
  14010. };
  14011. }
  14012. function parseUrl$2(input) {
  14013. if (isSchemeRelativeUrl(input)) {
  14014. const url = parseAbsoluteUrl('http:' + input);
  14015. url.scheme = '';
  14016. return url;
  14017. }
  14018. if (isAbsolutePath(input)) {
  14019. const url = parseAbsoluteUrl('http://foo.com' + input);
  14020. url.scheme = '';
  14021. url.host = '';
  14022. return url;
  14023. }
  14024. if (!isAbsoluteUrl(input)) {
  14025. const url = parseAbsoluteUrl('http://foo.com/' + input);
  14026. url.scheme = '';
  14027. url.host = '';
  14028. url.relativePath = true;
  14029. return url;
  14030. }
  14031. return parseAbsoluteUrl(input);
  14032. }
  14033. function stripPathFilename(path) {
  14034. // If a path ends with a parent directory "..", then it's a relative path with excess parent
  14035. // paths. It's not a file, so we can't strip it.
  14036. if (path.endsWith('/..'))
  14037. return path;
  14038. const index = path.lastIndexOf('/');
  14039. return path.slice(0, index + 1);
  14040. }
  14041. function mergePaths(url, base) {
  14042. // If we're not a relative path, then we're an absolute path, and it doesn't matter what base is.
  14043. if (!url.relativePath)
  14044. return;
  14045. normalizePath$4(base);
  14046. // If the path is just a "/", then it was an empty path to begin with (remember, we're a relative
  14047. // path).
  14048. if (url.path === '/') {
  14049. url.path = base.path;
  14050. }
  14051. else {
  14052. // Resolution happens relative to the base path's directory, not the file.
  14053. url.path = stripPathFilename(base.path) + url.path;
  14054. }
  14055. // If the base path is absolute, then our path is now absolute too.
  14056. url.relativePath = base.relativePath;
  14057. }
  14058. /**
  14059. * The path can have empty directories "//", unneeded parents "foo/..", or current directory
  14060. * "foo/.". We need to normalize to a standard representation.
  14061. */
  14062. function normalizePath$4(url) {
  14063. const { relativePath } = url;
  14064. const pieces = url.path.split('/');
  14065. // We need to preserve the first piece always, so that we output a leading slash. The item at
  14066. // pieces[0] is an empty string.
  14067. let pointer = 1;
  14068. // Positive is the number of real directories we've output, used for popping a parent directory.
  14069. // Eg, "foo/bar/.." will have a positive 2, and we can decrement to be left with just "foo".
  14070. let positive = 0;
  14071. // We need to keep a trailing slash if we encounter an empty directory (eg, splitting "foo/" will
  14072. // generate `["foo", ""]` pieces). And, if we pop a parent directory. But once we encounter a
  14073. // real directory, we won't need to append, unless the other conditions happen again.
  14074. let addTrailingSlash = false;
  14075. for (let i = 1; i < pieces.length; i++) {
  14076. const piece = pieces[i];
  14077. // An empty directory, could be a trailing slash, or just a double "//" in the path.
  14078. if (!piece) {
  14079. addTrailingSlash = true;
  14080. continue;
  14081. }
  14082. // If we encounter a real directory, then we don't need to append anymore.
  14083. addTrailingSlash = false;
  14084. // A current directory, which we can always drop.
  14085. if (piece === '.')
  14086. continue;
  14087. // A parent directory, we need to see if there are any real directories we can pop. Else, we
  14088. // have an excess of parents, and we'll need to keep the "..".
  14089. if (piece === '..') {
  14090. if (positive) {
  14091. addTrailingSlash = true;
  14092. positive--;
  14093. pointer--;
  14094. }
  14095. else if (relativePath) {
  14096. // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute
  14097. // URL, protocol relative URL, or an absolute path, we don't need to keep excess.
  14098. pieces[pointer++] = piece;
  14099. }
  14100. continue;
  14101. }
  14102. // We've encountered a real directory. Move it to the next insertion pointer, which accounts for
  14103. // any popped or dropped directories.
  14104. pieces[pointer++] = piece;
  14105. positive++;
  14106. }
  14107. let path = '';
  14108. for (let i = 1; i < pointer; i++) {
  14109. path += '/' + pieces[i];
  14110. }
  14111. if (!path || (addTrailingSlash && !path.endsWith('/..'))) {
  14112. path += '/';
  14113. }
  14114. url.path = path;
  14115. }
  14116. /**
  14117. * Attempts to resolve `input` URL/path relative to `base`.
  14118. */
  14119. function resolve$3(input, base) {
  14120. if (!input && !base)
  14121. return '';
  14122. const url = parseUrl$2(input);
  14123. // If we have a base, and the input isn't already an absolute URL, then we need to merge.
  14124. if (base && !url.scheme) {
  14125. const baseUrl = parseUrl$2(base);
  14126. url.scheme = baseUrl.scheme;
  14127. // If there's no host, then we were just a path.
  14128. if (!url.host || baseUrl.scheme === 'file:') {
  14129. // The host, user, and port are joined, you can't copy one without the others.
  14130. url.user = baseUrl.user;
  14131. url.host = baseUrl.host;
  14132. url.port = baseUrl.port;
  14133. }
  14134. mergePaths(url, baseUrl);
  14135. }
  14136. normalizePath$4(url);
  14137. // If the input (and base, if there was one) are both relative, then we need to output a relative.
  14138. if (url.relativePath) {
  14139. // The first char is always a "/".
  14140. const path = url.path.slice(1);
  14141. if (!path)
  14142. return '.';
  14143. // If base started with a leading ".", or there is no base and input started with a ".", then we
  14144. // need to ensure that the relative path starts with a ".". We don't know if relative starts
  14145. // with a "..", though, so check before prepending.
  14146. const keepRelative = (base || input).startsWith('.');
  14147. return !keepRelative || path.startsWith('.') ? path : './' + path;
  14148. }
  14149. // If there's no host (and no scheme/user/port), then we need to output an absolute path.
  14150. if (!url.scheme && !url.host)
  14151. return url.path;
  14152. // We're outputting either an absolute URL, or a protocol relative one.
  14153. return `${url.scheme}//${url.user}${url.host}${url.port}${url.path}`;
  14154. }
  14155. function resolve$2(input, base) {
  14156. // The base is always treated as a directory, if it's not empty.
  14157. // https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327
  14158. // https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401
  14159. if (base && !base.endsWith('/'))
  14160. base += '/';
  14161. return resolve$3(input, base);
  14162. }
  14163. /**
  14164. * Removes everything after the last "/", but leaves the slash.
  14165. */
  14166. function stripFilename(path) {
  14167. if (!path)
  14168. return '';
  14169. const index = path.lastIndexOf('/');
  14170. return path.slice(0, index + 1);
  14171. }
  14172. const COLUMN = 0;
  14173. const SOURCES_INDEX = 1;
  14174. const SOURCE_LINE = 2;
  14175. const SOURCE_COLUMN = 3;
  14176. const NAMES_INDEX = 4;
  14177. function maybeSort(mappings, owned) {
  14178. const unsortedIndex = nextUnsortedSegmentLine(mappings, 0);
  14179. if (unsortedIndex === mappings.length)
  14180. return mappings;
  14181. // If we own the array (meaning we parsed it from JSON), then we're free to directly mutate it. If
  14182. // not, we do not want to modify the consumer's input array.
  14183. if (!owned)
  14184. mappings = mappings.slice();
  14185. for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) {
  14186. mappings[i] = sortSegments(mappings[i], owned);
  14187. }
  14188. return mappings;
  14189. }
  14190. function nextUnsortedSegmentLine(mappings, start) {
  14191. for (let i = start; i < mappings.length; i++) {
  14192. if (!isSorted(mappings[i]))
  14193. return i;
  14194. }
  14195. return mappings.length;
  14196. }
  14197. function isSorted(line) {
  14198. for (let j = 1; j < line.length; j++) {
  14199. if (line[j][COLUMN] < line[j - 1][COLUMN]) {
  14200. return false;
  14201. }
  14202. }
  14203. return true;
  14204. }
  14205. function sortSegments(line, owned) {
  14206. if (!owned)
  14207. line = line.slice();
  14208. return line.sort(sortComparator);
  14209. }
  14210. function sortComparator(a, b) {
  14211. return a[COLUMN] - b[COLUMN];
  14212. }
  14213. let found = false;
  14214. /**
  14215. * A binary search implementation that returns the index if a match is found.
  14216. * If no match is found, then the left-index (the index associated with the item that comes just
  14217. * before the desired index) is returned. To maintain proper sort order, a splice would happen at
  14218. * the next index:
  14219. *
  14220. * ```js
  14221. * const array = [1, 3];
  14222. * const needle = 2;
  14223. * const index = binarySearch(array, needle, (item, needle) => item - needle);
  14224. *
  14225. * assert.equal(index, 0);
  14226. * array.splice(index + 1, 0, needle);
  14227. * assert.deepEqual(array, [1, 2, 3]);
  14228. * ```
  14229. */
  14230. function binarySearch(haystack, needle, low, high) {
  14231. while (low <= high) {
  14232. const mid = low + ((high - low) >> 1);
  14233. const cmp = haystack[mid][COLUMN] - needle;
  14234. if (cmp === 0) {
  14235. found = true;
  14236. return mid;
  14237. }
  14238. if (cmp < 0) {
  14239. low = mid + 1;
  14240. }
  14241. else {
  14242. high = mid - 1;
  14243. }
  14244. }
  14245. found = false;
  14246. return low - 1;
  14247. }
  14248. function upperBound(haystack, needle, index) {
  14249. for (let i = index + 1; i < haystack.length; i++, index++) {
  14250. if (haystack[i][COLUMN] !== needle)
  14251. break;
  14252. }
  14253. return index;
  14254. }
  14255. function lowerBound(haystack, needle, index) {
  14256. for (let i = index - 1; i >= 0; i--, index--) {
  14257. if (haystack[i][COLUMN] !== needle)
  14258. break;
  14259. }
  14260. return index;
  14261. }
  14262. function memoizedState() {
  14263. return {
  14264. lastKey: -1,
  14265. lastNeedle: -1,
  14266. lastIndex: -1,
  14267. };
  14268. }
  14269. /**
  14270. * This overly complicated beast is just to record the last tested line/column and the resulting
  14271. * index, allowing us to skip a few tests if mappings are monotonically increasing.
  14272. */
  14273. function memoizedBinarySearch(haystack, needle, state, key) {
  14274. const { lastKey, lastNeedle, lastIndex } = state;
  14275. let low = 0;
  14276. let high = haystack.length - 1;
  14277. if (key === lastKey) {
  14278. if (needle === lastNeedle) {
  14279. found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle;
  14280. return lastIndex;
  14281. }
  14282. if (needle >= lastNeedle) {
  14283. // lastIndex may be -1 if the previous needle was not found.
  14284. low = lastIndex === -1 ? 0 : lastIndex;
  14285. }
  14286. else {
  14287. high = lastIndex;
  14288. }
  14289. }
  14290. state.lastKey = key;
  14291. state.lastNeedle = needle;
  14292. return (state.lastIndex = binarySearch(haystack, needle, low, high));
  14293. }
  14294. const INVALID_ORIGINAL_MAPPING = Object.freeze({
  14295. source: null,
  14296. line: null,
  14297. column: null,
  14298. name: null,
  14299. });
  14300. Object.freeze({
  14301. line: null,
  14302. column: null,
  14303. });
  14304. const LINE_GTR_ZERO = '`line` must be greater than 0 (lines start at line 1)';
  14305. const COL_GTR_EQ_ZERO = '`column` must be greater than or equal to 0 (columns start at column 0)';
  14306. const LEAST_UPPER_BOUND = -1;
  14307. const GREATEST_LOWER_BOUND = 1;
  14308. /**
  14309. * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field.
  14310. */
  14311. let decodedMappings;
  14312. /**
  14313. * A low-level API to find the segment associated with a generated line/column (think, from a
  14314. * stack trace). Line and column here are 0-based, unlike `originalPositionFor`.
  14315. */
  14316. let traceSegment;
  14317. /**
  14318. * A higher-level API to find the source/line/column associated with a generated line/column
  14319. * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in
  14320. * `source-map` library.
  14321. */
  14322. let originalPositionFor$1;
  14323. class TraceMap {
  14324. constructor(map, mapUrl) {
  14325. this._decodedMemo = memoizedState();
  14326. this._bySources = undefined;
  14327. this._bySourceMemos = undefined;
  14328. const isString = typeof map === 'string';
  14329. if (!isString && map.constructor === TraceMap)
  14330. return map;
  14331. const parsed = (isString ? JSON.parse(map) : map);
  14332. const { version, file, names, sourceRoot, sources, sourcesContent } = parsed;
  14333. this.version = version;
  14334. this.file = file;
  14335. this.names = names;
  14336. this.sourceRoot = sourceRoot;
  14337. this.sources = sources;
  14338. this.sourcesContent = sourcesContent;
  14339. if (sourceRoot || mapUrl) {
  14340. const from = resolve$2(sourceRoot || '', stripFilename(mapUrl));
  14341. this.resolvedSources = sources.map((s) => resolve$2(s || '', from));
  14342. }
  14343. else {
  14344. this.resolvedSources = sources.map((s) => s || '');
  14345. }
  14346. const { mappings } = parsed;
  14347. if (typeof mappings === 'string') {
  14348. this._encoded = mappings;
  14349. this._decoded = undefined;
  14350. }
  14351. else {
  14352. this._encoded = undefined;
  14353. this._decoded = maybeSort(mappings, isString);
  14354. }
  14355. }
  14356. }
  14357. (() => {
  14358. decodedMappings = (map) => {
  14359. return (map._decoded || (map._decoded = decode(map._encoded)));
  14360. };
  14361. traceSegment = (map, line, column) => {
  14362. const decoded = decodedMappings(map);
  14363. // It's common for parent source maps to have pointers to lines that have no
  14364. // mapping (like a "//# sourceMappingURL=") at the end of the child file.
  14365. if (line >= decoded.length)
  14366. return null;
  14367. return traceSegmentInternal(decoded[line], map._decodedMemo, line, column, GREATEST_LOWER_BOUND);
  14368. };
  14369. originalPositionFor$1 = (map, { line, column, bias }) => {
  14370. line--;
  14371. if (line < 0)
  14372. throw new Error(LINE_GTR_ZERO);
  14373. if (column < 0)
  14374. throw new Error(COL_GTR_EQ_ZERO);
  14375. const decoded = decodedMappings(map);
  14376. // It's common for parent source maps to have pointers to lines that have no
  14377. // mapping (like a "//# sourceMappingURL=") at the end of the child file.
  14378. if (line >= decoded.length)
  14379. return INVALID_ORIGINAL_MAPPING;
  14380. const segment = traceSegmentInternal(decoded[line], map._decodedMemo, line, column, bias || GREATEST_LOWER_BOUND);
  14381. if (segment == null)
  14382. return INVALID_ORIGINAL_MAPPING;
  14383. if (segment.length == 1)
  14384. return INVALID_ORIGINAL_MAPPING;
  14385. const { names, resolvedSources } = map;
  14386. return {
  14387. source: resolvedSources[segment[SOURCES_INDEX]],
  14388. line: segment[SOURCE_LINE] + 1,
  14389. column: segment[SOURCE_COLUMN],
  14390. name: segment.length === 5 ? names[segment[NAMES_INDEX]] : null,
  14391. };
  14392. };
  14393. })();
  14394. function traceSegmentInternal(segments, memo, line, column, bias) {
  14395. let index = memoizedBinarySearch(segments, column, memo, line);
  14396. if (found) {
  14397. index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index);
  14398. }
  14399. else if (bias === LEAST_UPPER_BOUND)
  14400. index++;
  14401. if (index === -1 || index === segments.length)
  14402. return null;
  14403. return segments[index];
  14404. }
  14405. /**
  14406. * Gets the index associated with `key` in the backing array, if it is already present.
  14407. */
  14408. let get;
  14409. /**
  14410. * Puts `key` into the backing array, if it is not already present. Returns
  14411. * the index of the `key` in the backing array.
  14412. */
  14413. let put;
  14414. /**
  14415. * SetArray acts like a `Set` (allowing only one occurrence of a string `key`), but provides the
  14416. * index of the `key` in the backing array.
  14417. *
  14418. * This is designed to allow synchronizing a second array with the contents of the backing array,
  14419. * like how in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`,
  14420. * and there are never duplicates.
  14421. */
  14422. class SetArray {
  14423. constructor() {
  14424. this._indexes = { __proto__: null };
  14425. this.array = [];
  14426. }
  14427. }
  14428. (() => {
  14429. get = (strarr, key) => strarr._indexes[key];
  14430. put = (strarr, key) => {
  14431. // The key may or may not be present. If it is present, it's a number.
  14432. const index = get(strarr, key);
  14433. if (index !== undefined)
  14434. return index;
  14435. const { array, _indexes: indexes } = strarr;
  14436. return (indexes[key] = array.push(key) - 1);
  14437. };
  14438. })();
  14439. /**
  14440. * A low-level API to associate a generated position with an original source position. Line and
  14441. * column here are 0-based, unlike `addMapping`.
  14442. */
  14443. let addSegment;
  14444. /**
  14445. * Adds/removes the content of the source file to the source map.
  14446. */
  14447. let setSourceContent;
  14448. /**
  14449. * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects
  14450. * a sourcemap, or to JSON.stringify.
  14451. */
  14452. let decodedMap;
  14453. /**
  14454. * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects
  14455. * a sourcemap, or to JSON.stringify.
  14456. */
  14457. let encodedMap;
  14458. /**
  14459. * Provides the state to generate a sourcemap.
  14460. */
  14461. class GenMapping {
  14462. constructor({ file, sourceRoot } = {}) {
  14463. this._names = new SetArray();
  14464. this._sources = new SetArray();
  14465. this._sourcesContent = [];
  14466. this._mappings = [];
  14467. this.file = file;
  14468. this.sourceRoot = sourceRoot;
  14469. }
  14470. }
  14471. (() => {
  14472. addSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name) => {
  14473. const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, } = map;
  14474. const line = getLine$1(mappings, genLine);
  14475. if (source == null) {
  14476. const seg = [genColumn];
  14477. const index = getColumnIndex(line, genColumn, seg);
  14478. return insert(line, index, seg);
  14479. }
  14480. const sourcesIndex = put(sources, source);
  14481. const seg = name
  14482. ? [genColumn, sourcesIndex, sourceLine, sourceColumn, put(names, name)]
  14483. : [genColumn, sourcesIndex, sourceLine, sourceColumn];
  14484. const index = getColumnIndex(line, genColumn, seg);
  14485. if (sourcesIndex === sourcesContent.length)
  14486. sourcesContent[sourcesIndex] = null;
  14487. insert(line, index, seg);
  14488. };
  14489. setSourceContent = (map, source, content) => {
  14490. const { _sources: sources, _sourcesContent: sourcesContent } = map;
  14491. sourcesContent[put(sources, source)] = content;
  14492. };
  14493. decodedMap = (map) => {
  14494. const { file, sourceRoot, _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, } = map;
  14495. return {
  14496. version: 3,
  14497. file,
  14498. names: names.array,
  14499. sourceRoot: sourceRoot || undefined,
  14500. sources: sources.array,
  14501. sourcesContent,
  14502. mappings,
  14503. };
  14504. };
  14505. encodedMap = (map) => {
  14506. const decoded = decodedMap(map);
  14507. return Object.assign(Object.assign({}, decoded), { mappings: encode(decoded.mappings) });
  14508. };
  14509. })();
  14510. function getLine$1(mappings, index) {
  14511. for (let i = mappings.length; i <= index; i++) {
  14512. mappings[i] = [];
  14513. }
  14514. return mappings[index];
  14515. }
  14516. function getColumnIndex(line, column, seg) {
  14517. let index = line.length;
  14518. for (let i = index - 1; i >= 0; i--, index--) {
  14519. const current = line[i];
  14520. const col = current[0];
  14521. if (col > column)
  14522. continue;
  14523. if (col < column)
  14524. break;
  14525. const cmp = compare(current, seg);
  14526. if (cmp === 0)
  14527. return index;
  14528. if (cmp < 0)
  14529. break;
  14530. }
  14531. return index;
  14532. }
  14533. function compare(a, b) {
  14534. let cmp = compareNum(a.length, b.length);
  14535. if (cmp !== 0)
  14536. return cmp;
  14537. // We've already checked genColumn
  14538. if (a.length === 1)
  14539. return 0;
  14540. cmp = compareNum(a[1], b[1]);
  14541. if (cmp !== 0)
  14542. return cmp;
  14543. cmp = compareNum(a[2], b[2]);
  14544. if (cmp !== 0)
  14545. return cmp;
  14546. cmp = compareNum(a[3], b[3]);
  14547. if (cmp !== 0)
  14548. return cmp;
  14549. if (a.length === 4)
  14550. return 0;
  14551. return compareNum(a[4], b[4]);
  14552. }
  14553. function compareNum(a, b) {
  14554. return a - b;
  14555. }
  14556. function insert(array, index, value) {
  14557. if (index === -1)
  14558. return;
  14559. for (let i = array.length; i > index; i--) {
  14560. array[i] = array[i - 1];
  14561. }
  14562. array[index] = value;
  14563. }
  14564. const SOURCELESS_MAPPING = {
  14565. source: null,
  14566. column: null,
  14567. line: null,
  14568. name: null,
  14569. content: null,
  14570. };
  14571. const EMPTY_SOURCES = [];
  14572. function Source(map, sources, source, content) {
  14573. return {
  14574. map,
  14575. sources,
  14576. source,
  14577. content,
  14578. };
  14579. }
  14580. /**
  14581. * MapSource represents a single sourcemap, with the ability to trace mappings into its child nodes
  14582. * (which may themselves be SourceMapTrees).
  14583. */
  14584. function MapSource(map, sources) {
  14585. return Source(map, sources, '', null);
  14586. }
  14587. /**
  14588. * A "leaf" node in the sourcemap tree, representing an original, unmodified source file. Recursive
  14589. * segment tracing ends at the `OriginalSource`.
  14590. */
  14591. function OriginalSource(source, content) {
  14592. return Source(null, EMPTY_SOURCES, source, content);
  14593. }
  14594. /**
  14595. * traceMappings is only called on the root level SourceMapTree, and begins the process of
  14596. * resolving each mapping in terms of the original source files.
  14597. */
  14598. function traceMappings(tree) {
  14599. const gen = new GenMapping({ file: tree.map.file });
  14600. const { sources: rootSources, map } = tree;
  14601. const rootNames = map.names;
  14602. const rootMappings = decodedMappings(map);
  14603. for (let i = 0; i < rootMappings.length; i++) {
  14604. const segments = rootMappings[i];
  14605. let lastSource = null;
  14606. let lastSourceLine = null;
  14607. let lastSourceColumn = null;
  14608. for (let j = 0; j < segments.length; j++) {
  14609. const segment = segments[j];
  14610. const genCol = segment[0];
  14611. let traced = SOURCELESS_MAPPING;
  14612. // 1-length segments only move the current generated column, there's no source information
  14613. // to gather from it.
  14614. if (segment.length !== 1) {
  14615. const source = rootSources[segment[1]];
  14616. traced = originalPositionFor(source, segment[2], segment[3], segment.length === 5 ? rootNames[segment[4]] : '');
  14617. // If the trace is invalid, then the trace ran into a sourcemap that doesn't contain a
  14618. // respective segment into an original source.
  14619. if (traced == null)
  14620. continue;
  14621. }
  14622. // So we traced a segment down into its original source file. Now push a
  14623. // new segment pointing to this location.
  14624. const { column, line, name, content, source } = traced;
  14625. if (line === lastSourceLine && column === lastSourceColumn && source === lastSource) {
  14626. continue;
  14627. }
  14628. lastSourceLine = line;
  14629. lastSourceColumn = column;
  14630. lastSource = source;
  14631. // Sigh, TypeScript can't figure out source/line/column are either all null, or all non-null...
  14632. addSegment(gen, i, genCol, source, line, column, name);
  14633. if (content != null)
  14634. setSourceContent(gen, source, content);
  14635. }
  14636. }
  14637. return gen;
  14638. }
  14639. /**
  14640. * originalPositionFor is only called on children SourceMapTrees. It recurses down into its own
  14641. * child SourceMapTrees, until we find the original source map.
  14642. */
  14643. function originalPositionFor(source, line, column, name) {
  14644. if (!source.map) {
  14645. return { column, line, name, source: source.source, content: source.content };
  14646. }
  14647. const segment = traceSegment(source.map, line, column);
  14648. // If we couldn't find a segment, then this doesn't exist in the sourcemap.
  14649. if (segment == null)
  14650. return null;
  14651. // 1-length segments only move the current generated column, there's no source information
  14652. // to gather from it.
  14653. if (segment.length === 1)
  14654. return SOURCELESS_MAPPING;
  14655. return originalPositionFor(source.sources[segment[1]], segment[2], segment[3], segment.length === 5 ? source.map.names[segment[4]] : name);
  14656. }
  14657. function asArray(value) {
  14658. if (Array.isArray(value))
  14659. return value;
  14660. return [value];
  14661. }
  14662. /**
  14663. * Recursively builds a tree structure out of sourcemap files, with each node
  14664. * being either an `OriginalSource` "leaf" or a `SourceMapTree` composed of
  14665. * `OriginalSource`s and `SourceMapTree`s.
  14666. *
  14667. * Every sourcemap is composed of a collection of source files and mappings
  14668. * into locations of those source files. When we generate a `SourceMapTree` for
  14669. * the sourcemap, we attempt to load each source file's own sourcemap. If it
  14670. * does not have an associated sourcemap, it is considered an original,
  14671. * unmodified source file.
  14672. */
  14673. function buildSourceMapTree(input, loader) {
  14674. const maps = asArray(input).map((m) => new TraceMap(m, ''));
  14675. const map = maps.pop();
  14676. for (let i = 0; i < maps.length; i++) {
  14677. if (maps[i].sources.length > 1) {
  14678. throw new Error(`Transformation map ${i} must have exactly one source file.\n` +
  14679. 'Did you specify these with the most recent transformation maps first?');
  14680. }
  14681. }
  14682. let tree = build$2(map, loader, '', 0);
  14683. for (let i = maps.length - 1; i >= 0; i--) {
  14684. tree = MapSource(maps[i], [tree]);
  14685. }
  14686. return tree;
  14687. }
  14688. function build$2(map, loader, importer, importerDepth) {
  14689. const { resolvedSources, sourcesContent } = map;
  14690. const depth = importerDepth + 1;
  14691. const children = resolvedSources.map((sourceFile, i) => {
  14692. // The loading context gives the loader more information about why this file is being loaded
  14693. // (eg, from which importer). It also allows the loader to override the location of the loaded
  14694. // sourcemap/original source, or to override the content in the sourcesContent field if it's
  14695. // an unmodified source file.
  14696. const ctx = {
  14697. importer,
  14698. depth,
  14699. source: sourceFile || '',
  14700. content: undefined,
  14701. };
  14702. // Use the provided loader callback to retrieve the file's sourcemap.
  14703. // TODO: We should eventually support async loading of sourcemap files.
  14704. const sourceMap = loader(ctx.source, ctx);
  14705. const { source, content } = ctx;
  14706. // If there is a sourcemap, then we need to recurse into it to load its source files.
  14707. if (sourceMap)
  14708. return build$2(new TraceMap(sourceMap, source), loader, source, depth);
  14709. // Else, it's an an unmodified source file.
  14710. // The contents of this unmodified source file can be overridden via the loader context,
  14711. // allowing it to be explicitly null or a string. If it remains undefined, we fall back to
  14712. // the importing sourcemap's `sourcesContent` field.
  14713. const sourceContent = content !== undefined ? content : sourcesContent ? sourcesContent[i] : null;
  14714. return OriginalSource(source, sourceContent);
  14715. });
  14716. return MapSource(map, children);
  14717. }
  14718. /**
  14719. * A SourceMap v3 compatible sourcemap, which only includes fields that were
  14720. * provided to it.
  14721. */
  14722. class SourceMap$1 {
  14723. constructor(map, options) {
  14724. const out = options.decodedMappings ? decodedMap(map) : encodedMap(map);
  14725. this.version = out.version; // SourceMap spec says this should be first.
  14726. this.file = out.file;
  14727. this.mappings = out.mappings;
  14728. this.names = out.names;
  14729. this.sourceRoot = out.sourceRoot;
  14730. this.sources = out.sources;
  14731. if (!options.excludeContent) {
  14732. this.sourcesContent = out.sourcesContent;
  14733. }
  14734. }
  14735. toString() {
  14736. return JSON.stringify(this);
  14737. }
  14738. }
  14739. /**
  14740. * Traces through all the mappings in the root sourcemap, through the sources
  14741. * (and their sourcemaps), all the way back to the original source location.
  14742. *
  14743. * `loader` will be called every time we encounter a source file. If it returns
  14744. * a sourcemap, we will recurse into that sourcemap to continue the trace. If
  14745. * it returns a falsey value, that source file is treated as an original,
  14746. * unmodified source file.
  14747. *
  14748. * Pass `excludeContent` to exclude any self-containing source file content
  14749. * from the output sourcemap.
  14750. *
  14751. * Pass `decodedMappings` to receive a SourceMap with decoded (instead of
  14752. * VLQ encoded) mappings.
  14753. */
  14754. function remapping(input, loader, options) {
  14755. const opts = typeof options === 'object' ? options : { excludeContent: !!options, decodedMappings: false };
  14756. const tree = buildSourceMapTree(input, loader);
  14757. return new SourceMap$1(traceMappings(tree), opts);
  14758. }
  14759. var src$2 = {exports: {}};
  14760. var browser$1 = {exports: {}};
  14761. /**
  14762. * Helpers.
  14763. */
  14764. var s$1 = 1000;
  14765. var m$1 = s$1 * 60;
  14766. var h$1 = m$1 * 60;
  14767. var d$1 = h$1 * 24;
  14768. var w = d$1 * 7;
  14769. var y$1 = d$1 * 365.25;
  14770. /**
  14771. * Parse or format the given `val`.
  14772. *
  14773. * Options:
  14774. *
  14775. * - `long` verbose formatting [false]
  14776. *
  14777. * @param {String|Number} val
  14778. * @param {Object} [options]
  14779. * @throws {Error} throw an error if val is not a non-empty string or a number
  14780. * @return {String|Number}
  14781. * @api public
  14782. */
  14783. var ms$1 = function(val, options) {
  14784. options = options || {};
  14785. var type = typeof val;
  14786. if (type === 'string' && val.length > 0) {
  14787. return parse$g(val);
  14788. } else if (type === 'number' && isFinite(val)) {
  14789. return options.long ? fmtLong$1(val) : fmtShort$1(val);
  14790. }
  14791. throw new Error(
  14792. 'val is not a non-empty string or a valid number. val=' +
  14793. JSON.stringify(val)
  14794. );
  14795. };
  14796. /**
  14797. * Parse the given `str` and return milliseconds.
  14798. *
  14799. * @param {String} str
  14800. * @return {Number}
  14801. * @api private
  14802. */
  14803. function parse$g(str) {
  14804. str = String(str);
  14805. if (str.length > 100) {
  14806. return;
  14807. }
  14808. var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
  14809. str
  14810. );
  14811. if (!match) {
  14812. return;
  14813. }
  14814. var n = parseFloat(match[1]);
  14815. var type = (match[2] || 'ms').toLowerCase();
  14816. switch (type) {
  14817. case 'years':
  14818. case 'year':
  14819. case 'yrs':
  14820. case 'yr':
  14821. case 'y':
  14822. return n * y$1;
  14823. case 'weeks':
  14824. case 'week':
  14825. case 'w':
  14826. return n * w;
  14827. case 'days':
  14828. case 'day':
  14829. case 'd':
  14830. return n * d$1;
  14831. case 'hours':
  14832. case 'hour':
  14833. case 'hrs':
  14834. case 'hr':
  14835. case 'h':
  14836. return n * h$1;
  14837. case 'minutes':
  14838. case 'minute':
  14839. case 'mins':
  14840. case 'min':
  14841. case 'm':
  14842. return n * m$1;
  14843. case 'seconds':
  14844. case 'second':
  14845. case 'secs':
  14846. case 'sec':
  14847. case 's':
  14848. return n * s$1;
  14849. case 'milliseconds':
  14850. case 'millisecond':
  14851. case 'msecs':
  14852. case 'msec':
  14853. case 'ms':
  14854. return n;
  14855. default:
  14856. return undefined;
  14857. }
  14858. }
  14859. /**
  14860. * Short format for `ms`.
  14861. *
  14862. * @param {Number} ms
  14863. * @return {String}
  14864. * @api private
  14865. */
  14866. function fmtShort$1(ms) {
  14867. var msAbs = Math.abs(ms);
  14868. if (msAbs >= d$1) {
  14869. return Math.round(ms / d$1) + 'd';
  14870. }
  14871. if (msAbs >= h$1) {
  14872. return Math.round(ms / h$1) + 'h';
  14873. }
  14874. if (msAbs >= m$1) {
  14875. return Math.round(ms / m$1) + 'm';
  14876. }
  14877. if (msAbs >= s$1) {
  14878. return Math.round(ms / s$1) + 's';
  14879. }
  14880. return ms + 'ms';
  14881. }
  14882. /**
  14883. * Long format for `ms`.
  14884. *
  14885. * @param {Number} ms
  14886. * @return {String}
  14887. * @api private
  14888. */
  14889. function fmtLong$1(ms) {
  14890. var msAbs = Math.abs(ms);
  14891. if (msAbs >= d$1) {
  14892. return plural$1(ms, msAbs, d$1, 'day');
  14893. }
  14894. if (msAbs >= h$1) {
  14895. return plural$1(ms, msAbs, h$1, 'hour');
  14896. }
  14897. if (msAbs >= m$1) {
  14898. return plural$1(ms, msAbs, m$1, 'minute');
  14899. }
  14900. if (msAbs >= s$1) {
  14901. return plural$1(ms, msAbs, s$1, 'second');
  14902. }
  14903. return ms + ' ms';
  14904. }
  14905. /**
  14906. * Pluralization helper.
  14907. */
  14908. function plural$1(ms, msAbs, n, name) {
  14909. var isPlural = msAbs >= n * 1.5;
  14910. return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
  14911. }
  14912. /**
  14913. * This is the common logic for both the Node.js and web browser
  14914. * implementations of `debug()`.
  14915. */
  14916. function setup(env) {
  14917. createDebug.debug = createDebug;
  14918. createDebug.default = createDebug;
  14919. createDebug.coerce = coerce;
  14920. createDebug.disable = disable;
  14921. createDebug.enable = enable;
  14922. createDebug.enabled = enabled;
  14923. createDebug.humanize = ms$1;
  14924. createDebug.destroy = destroy;
  14925. Object.keys(env).forEach(key => {
  14926. createDebug[key] = env[key];
  14927. });
  14928. /**
  14929. * The currently active debug mode names, and names to skip.
  14930. */
  14931. createDebug.names = [];
  14932. createDebug.skips = [];
  14933. /**
  14934. * Map of special "%n" handling functions, for the debug "format" argument.
  14935. *
  14936. * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
  14937. */
  14938. createDebug.formatters = {};
  14939. /**
  14940. * Selects a color for a debug namespace
  14941. * @param {String} namespace The namespace string for the debug instance to be colored
  14942. * @return {Number|String} An ANSI color code for the given namespace
  14943. * @api private
  14944. */
  14945. function selectColor(namespace) {
  14946. let hash = 0;
  14947. for (let i = 0; i < namespace.length; i++) {
  14948. hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
  14949. hash |= 0; // Convert to 32bit integer
  14950. }
  14951. return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
  14952. }
  14953. createDebug.selectColor = selectColor;
  14954. /**
  14955. * Create a debugger with the given `namespace`.
  14956. *
  14957. * @param {String} namespace
  14958. * @return {Function}
  14959. * @api public
  14960. */
  14961. function createDebug(namespace) {
  14962. let prevTime;
  14963. let enableOverride = null;
  14964. let namespacesCache;
  14965. let enabledCache;
  14966. function debug(...args) {
  14967. // Disabled?
  14968. if (!debug.enabled) {
  14969. return;
  14970. }
  14971. const self = debug;
  14972. // Set `diff` timestamp
  14973. const curr = Number(new Date());
  14974. const ms = curr - (prevTime || curr);
  14975. self.diff = ms;
  14976. self.prev = prevTime;
  14977. self.curr = curr;
  14978. prevTime = curr;
  14979. args[0] = createDebug.coerce(args[0]);
  14980. if (typeof args[0] !== 'string') {
  14981. // Anything else let's inspect with %O
  14982. args.unshift('%O');
  14983. }
  14984. // Apply any `formatters` transformations
  14985. let index = 0;
  14986. args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
  14987. // If we encounter an escaped % then don't increase the array index
  14988. if (match === '%%') {
  14989. return '%';
  14990. }
  14991. index++;
  14992. const formatter = createDebug.formatters[format];
  14993. if (typeof formatter === 'function') {
  14994. const val = args[index];
  14995. match = formatter.call(self, val);
  14996. // Now we need to remove `args[index]` since it's inlined in the `format`
  14997. args.splice(index, 1);
  14998. index--;
  14999. }
  15000. return match;
  15001. });
  15002. // Apply env-specific formatting (colors, etc.)
  15003. createDebug.formatArgs.call(self, args);
  15004. const logFn = self.log || createDebug.log;
  15005. logFn.apply(self, args);
  15006. }
  15007. debug.namespace = namespace;
  15008. debug.useColors = createDebug.useColors();
  15009. debug.color = createDebug.selectColor(namespace);
  15010. debug.extend = extend;
  15011. debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
  15012. Object.defineProperty(debug, 'enabled', {
  15013. enumerable: true,
  15014. configurable: false,
  15015. get: () => {
  15016. if (enableOverride !== null) {
  15017. return enableOverride;
  15018. }
  15019. if (namespacesCache !== createDebug.namespaces) {
  15020. namespacesCache = createDebug.namespaces;
  15021. enabledCache = createDebug.enabled(namespace);
  15022. }
  15023. return enabledCache;
  15024. },
  15025. set: v => {
  15026. enableOverride = v;
  15027. }
  15028. });
  15029. // Env-specific initialization logic for debug instances
  15030. if (typeof createDebug.init === 'function') {
  15031. createDebug.init(debug);
  15032. }
  15033. return debug;
  15034. }
  15035. function extend(namespace, delimiter) {
  15036. const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
  15037. newDebug.log = this.log;
  15038. return newDebug;
  15039. }
  15040. /**
  15041. * Enables a debug mode by namespaces. This can include modes
  15042. * separated by a colon and wildcards.
  15043. *
  15044. * @param {String} namespaces
  15045. * @api public
  15046. */
  15047. function enable(namespaces) {
  15048. createDebug.save(namespaces);
  15049. createDebug.namespaces = namespaces;
  15050. createDebug.names = [];
  15051. createDebug.skips = [];
  15052. let i;
  15053. const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
  15054. const len = split.length;
  15055. for (i = 0; i < len; i++) {
  15056. if (!split[i]) {
  15057. // ignore empty strings
  15058. continue;
  15059. }
  15060. namespaces = split[i].replace(/\*/g, '.*?');
  15061. if (namespaces[0] === '-') {
  15062. createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));
  15063. } else {
  15064. createDebug.names.push(new RegExp('^' + namespaces + '$'));
  15065. }
  15066. }
  15067. }
  15068. /**
  15069. * Disable debug output.
  15070. *
  15071. * @return {String} namespaces
  15072. * @api public
  15073. */
  15074. function disable() {
  15075. const namespaces = [
  15076. ...createDebug.names.map(toNamespace),
  15077. ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
  15078. ].join(',');
  15079. createDebug.enable('');
  15080. return namespaces;
  15081. }
  15082. /**
  15083. * Returns true if the given mode name is enabled, false otherwise.
  15084. *
  15085. * @param {String} name
  15086. * @return {Boolean}
  15087. * @api public
  15088. */
  15089. function enabled(name) {
  15090. if (name[name.length - 1] === '*') {
  15091. return true;
  15092. }
  15093. let i;
  15094. let len;
  15095. for (i = 0, len = createDebug.skips.length; i < len; i++) {
  15096. if (createDebug.skips[i].test(name)) {
  15097. return false;
  15098. }
  15099. }
  15100. for (i = 0, len = createDebug.names.length; i < len; i++) {
  15101. if (createDebug.names[i].test(name)) {
  15102. return true;
  15103. }
  15104. }
  15105. return false;
  15106. }
  15107. /**
  15108. * Convert regexp to namespace
  15109. *
  15110. * @param {RegExp} regxep
  15111. * @return {String} namespace
  15112. * @api private
  15113. */
  15114. function toNamespace(regexp) {
  15115. return regexp.toString()
  15116. .substring(2, regexp.toString().length - 2)
  15117. .replace(/\.\*\?$/, '*');
  15118. }
  15119. /**
  15120. * Coerce `val`.
  15121. *
  15122. * @param {Mixed} val
  15123. * @return {Mixed}
  15124. * @api private
  15125. */
  15126. function coerce(val) {
  15127. if (val instanceof Error) {
  15128. return val.stack || val.message;
  15129. }
  15130. return val;
  15131. }
  15132. /**
  15133. * XXX DO NOT USE. This is a temporary stub function.
  15134. * XXX It WILL be removed in the next major release.
  15135. */
  15136. function destroy() {
  15137. console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
  15138. }
  15139. createDebug.enable(createDebug.load());
  15140. return createDebug;
  15141. }
  15142. var common$4 = setup;
  15143. /* eslint-env browser */
  15144. (function (module, exports) {
  15145. /**
  15146. * This is the web browser implementation of `debug()`.
  15147. */
  15148. exports.formatArgs = formatArgs;
  15149. exports.save = save;
  15150. exports.load = load;
  15151. exports.useColors = useColors;
  15152. exports.storage = localstorage();
  15153. exports.destroy = (() => {
  15154. let warned = false;
  15155. return () => {
  15156. if (!warned) {
  15157. warned = true;
  15158. console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
  15159. }
  15160. };
  15161. })();
  15162. /**
  15163. * Colors.
  15164. */
  15165. exports.colors = [
  15166. '#0000CC',
  15167. '#0000FF',
  15168. '#0033CC',
  15169. '#0033FF',
  15170. '#0066CC',
  15171. '#0066FF',
  15172. '#0099CC',
  15173. '#0099FF',
  15174. '#00CC00',
  15175. '#00CC33',
  15176. '#00CC66',
  15177. '#00CC99',
  15178. '#00CCCC',
  15179. '#00CCFF',
  15180. '#3300CC',
  15181. '#3300FF',
  15182. '#3333CC',
  15183. '#3333FF',
  15184. '#3366CC',
  15185. '#3366FF',
  15186. '#3399CC',
  15187. '#3399FF',
  15188. '#33CC00',
  15189. '#33CC33',
  15190. '#33CC66',
  15191. '#33CC99',
  15192. '#33CCCC',
  15193. '#33CCFF',
  15194. '#6600CC',
  15195. '#6600FF',
  15196. '#6633CC',
  15197. '#6633FF',
  15198. '#66CC00',
  15199. '#66CC33',
  15200. '#9900CC',
  15201. '#9900FF',
  15202. '#9933CC',
  15203. '#9933FF',
  15204. '#99CC00',
  15205. '#99CC33',
  15206. '#CC0000',
  15207. '#CC0033',
  15208. '#CC0066',
  15209. '#CC0099',
  15210. '#CC00CC',
  15211. '#CC00FF',
  15212. '#CC3300',
  15213. '#CC3333',
  15214. '#CC3366',
  15215. '#CC3399',
  15216. '#CC33CC',
  15217. '#CC33FF',
  15218. '#CC6600',
  15219. '#CC6633',
  15220. '#CC9900',
  15221. '#CC9933',
  15222. '#CCCC00',
  15223. '#CCCC33',
  15224. '#FF0000',
  15225. '#FF0033',
  15226. '#FF0066',
  15227. '#FF0099',
  15228. '#FF00CC',
  15229. '#FF00FF',
  15230. '#FF3300',
  15231. '#FF3333',
  15232. '#FF3366',
  15233. '#FF3399',
  15234. '#FF33CC',
  15235. '#FF33FF',
  15236. '#FF6600',
  15237. '#FF6633',
  15238. '#FF9900',
  15239. '#FF9933',
  15240. '#FFCC00',
  15241. '#FFCC33'
  15242. ];
  15243. /**
  15244. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  15245. * and the Firebug extension (any Firefox version) are known
  15246. * to support "%c" CSS customizations.
  15247. *
  15248. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  15249. */
  15250. // eslint-disable-next-line complexity
  15251. function useColors() {
  15252. // NB: In an Electron preload script, document will be defined but not fully
  15253. // initialized. Since we know we're in Chrome, we'll just detect this case
  15254. // explicitly
  15255. if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
  15256. return true;
  15257. }
  15258. // Internet Explorer and Edge do not support colors.
  15259. if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
  15260. return false;
  15261. }
  15262. // Is webkit? http://stackoverflow.com/a/16459606/376773
  15263. // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
  15264. return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
  15265. // Is firebug? http://stackoverflow.com/a/398120/376773
  15266. (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
  15267. // Is firefox >= v31?
  15268. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  15269. (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
  15270. // Double check webkit in userAgent just in case we are in a worker
  15271. (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
  15272. }
  15273. /**
  15274. * Colorize log arguments if enabled.
  15275. *
  15276. * @api public
  15277. */
  15278. function formatArgs(args) {
  15279. args[0] = (this.useColors ? '%c' : '') +
  15280. this.namespace +
  15281. (this.useColors ? ' %c' : ' ') +
  15282. args[0] +
  15283. (this.useColors ? '%c ' : ' ') +
  15284. '+' + module.exports.humanize(this.diff);
  15285. if (!this.useColors) {
  15286. return;
  15287. }
  15288. const c = 'color: ' + this.color;
  15289. args.splice(1, 0, c, 'color: inherit');
  15290. // The final "%c" is somewhat tricky, because there could be other
  15291. // arguments passed either before or after the %c, so we need to
  15292. // figure out the correct index to insert the CSS into
  15293. let index = 0;
  15294. let lastC = 0;
  15295. args[0].replace(/%[a-zA-Z%]/g, match => {
  15296. if (match === '%%') {
  15297. return;
  15298. }
  15299. index++;
  15300. if (match === '%c') {
  15301. // We only are interested in the *last* %c
  15302. // (the user may have provided their own)
  15303. lastC = index;
  15304. }
  15305. });
  15306. args.splice(lastC, 0, c);
  15307. }
  15308. /**
  15309. * Invokes `console.debug()` when available.
  15310. * No-op when `console.debug` is not a "function".
  15311. * If `console.debug` is not available, falls back
  15312. * to `console.log`.
  15313. *
  15314. * @api public
  15315. */
  15316. exports.log = console.debug || console.log || (() => {});
  15317. /**
  15318. * Save `namespaces`.
  15319. *
  15320. * @param {String} namespaces
  15321. * @api private
  15322. */
  15323. function save(namespaces) {
  15324. try {
  15325. if (namespaces) {
  15326. exports.storage.setItem('debug', namespaces);
  15327. } else {
  15328. exports.storage.removeItem('debug');
  15329. }
  15330. } catch (error) {
  15331. // Swallow
  15332. // XXX (@Qix-) should we be logging these?
  15333. }
  15334. }
  15335. /**
  15336. * Load `namespaces`.
  15337. *
  15338. * @return {String} returns the previously persisted debug modes
  15339. * @api private
  15340. */
  15341. function load() {
  15342. let r;
  15343. try {
  15344. r = exports.storage.getItem('debug');
  15345. } catch (error) {
  15346. // Swallow
  15347. // XXX (@Qix-) should we be logging these?
  15348. }
  15349. // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
  15350. if (!r && typeof process !== 'undefined' && 'env' in process) {
  15351. r = process.env.DEBUG;
  15352. }
  15353. return r;
  15354. }
  15355. /**
  15356. * Localstorage attempts to return the localstorage.
  15357. *
  15358. * This is necessary because safari throws
  15359. * when a user disables cookies/localstorage
  15360. * and you attempt to access it.
  15361. *
  15362. * @return {LocalStorage}
  15363. * @api private
  15364. */
  15365. function localstorage() {
  15366. try {
  15367. // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
  15368. // The Browser also has localStorage in the global context.
  15369. return localStorage;
  15370. } catch (error) {
  15371. // Swallow
  15372. // XXX (@Qix-) should we be logging these?
  15373. }
  15374. }
  15375. module.exports = common$4(exports);
  15376. const {formatters} = module.exports;
  15377. /**
  15378. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  15379. */
  15380. formatters.j = function (v) {
  15381. try {
  15382. return JSON.stringify(v);
  15383. } catch (error) {
  15384. return '[UnexpectedJSONParseError]: ' + error.message;
  15385. }
  15386. };
  15387. }(browser$1, browser$1.exports));
  15388. var node$1 = {exports: {}};
  15389. /**
  15390. * Module dependencies.
  15391. */
  15392. (function (module, exports) {
  15393. const tty = require$$0__default;
  15394. const util = require$$0__default$2;
  15395. /**
  15396. * This is the Node.js implementation of `debug()`.
  15397. */
  15398. exports.init = init;
  15399. exports.log = log;
  15400. exports.formatArgs = formatArgs;
  15401. exports.save = save;
  15402. exports.load = load;
  15403. exports.useColors = useColors;
  15404. exports.destroy = util.deprecate(
  15405. () => {},
  15406. 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'
  15407. );
  15408. /**
  15409. * Colors.
  15410. */
  15411. exports.colors = [6, 2, 3, 4, 5, 1];
  15412. try {
  15413. // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)
  15414. // eslint-disable-next-line import/no-extraneous-dependencies
  15415. const supportsColor = require('supports-color');
  15416. if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
  15417. exports.colors = [
  15418. 20,
  15419. 21,
  15420. 26,
  15421. 27,
  15422. 32,
  15423. 33,
  15424. 38,
  15425. 39,
  15426. 40,
  15427. 41,
  15428. 42,
  15429. 43,
  15430. 44,
  15431. 45,
  15432. 56,
  15433. 57,
  15434. 62,
  15435. 63,
  15436. 68,
  15437. 69,
  15438. 74,
  15439. 75,
  15440. 76,
  15441. 77,
  15442. 78,
  15443. 79,
  15444. 80,
  15445. 81,
  15446. 92,
  15447. 93,
  15448. 98,
  15449. 99,
  15450. 112,
  15451. 113,
  15452. 128,
  15453. 129,
  15454. 134,
  15455. 135,
  15456. 148,
  15457. 149,
  15458. 160,
  15459. 161,
  15460. 162,
  15461. 163,
  15462. 164,
  15463. 165,
  15464. 166,
  15465. 167,
  15466. 168,
  15467. 169,
  15468. 170,
  15469. 171,
  15470. 172,
  15471. 173,
  15472. 178,
  15473. 179,
  15474. 184,
  15475. 185,
  15476. 196,
  15477. 197,
  15478. 198,
  15479. 199,
  15480. 200,
  15481. 201,
  15482. 202,
  15483. 203,
  15484. 204,
  15485. 205,
  15486. 206,
  15487. 207,
  15488. 208,
  15489. 209,
  15490. 214,
  15491. 215,
  15492. 220,
  15493. 221
  15494. ];
  15495. }
  15496. } catch (error) {
  15497. // Swallow - we only care if `supports-color` is available; it doesn't have to be.
  15498. }
  15499. /**
  15500. * Build up the default `inspectOpts` object from the environment variables.
  15501. *
  15502. * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
  15503. */
  15504. exports.inspectOpts = Object.keys(process.env).filter(key => {
  15505. return /^debug_/i.test(key);
  15506. }).reduce((obj, key) => {
  15507. // Camel-case
  15508. const prop = key
  15509. .substring(6)
  15510. .toLowerCase()
  15511. .replace(/_([a-z])/g, (_, k) => {
  15512. return k.toUpperCase();
  15513. });
  15514. // Coerce string value into JS value
  15515. let val = process.env[key];
  15516. if (/^(yes|on|true|enabled)$/i.test(val)) {
  15517. val = true;
  15518. } else if (/^(no|off|false|disabled)$/i.test(val)) {
  15519. val = false;
  15520. } else if (val === 'null') {
  15521. val = null;
  15522. } else {
  15523. val = Number(val);
  15524. }
  15525. obj[prop] = val;
  15526. return obj;
  15527. }, {});
  15528. /**
  15529. * Is stdout a TTY? Colored output is enabled when `true`.
  15530. */
  15531. function useColors() {
  15532. return 'colors' in exports.inspectOpts ?
  15533. Boolean(exports.inspectOpts.colors) :
  15534. tty.isatty(process.stderr.fd);
  15535. }
  15536. /**
  15537. * Adds ANSI color escape codes if enabled.
  15538. *
  15539. * @api public
  15540. */
  15541. function formatArgs(args) {
  15542. const {namespace: name, useColors} = this;
  15543. if (useColors) {
  15544. const c = this.color;
  15545. const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c);
  15546. const prefix = ` ${colorCode};1m${name} \u001B[0m`;
  15547. args[0] = prefix + args[0].split('\n').join('\n' + prefix);
  15548. args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m');
  15549. } else {
  15550. args[0] = getDate() + name + ' ' + args[0];
  15551. }
  15552. }
  15553. function getDate() {
  15554. if (exports.inspectOpts.hideDate) {
  15555. return '';
  15556. }
  15557. return new Date().toISOString() + ' ';
  15558. }
  15559. /**
  15560. * Invokes `util.format()` with the specified arguments and writes to stderr.
  15561. */
  15562. function log(...args) {
  15563. return process.stderr.write(util.format(...args) + '\n');
  15564. }
  15565. /**
  15566. * Save `namespaces`.
  15567. *
  15568. * @param {String} namespaces
  15569. * @api private
  15570. */
  15571. function save(namespaces) {
  15572. if (namespaces) {
  15573. process.env.DEBUG = namespaces;
  15574. } else {
  15575. // If you set a process.env field to null or undefined, it gets cast to the
  15576. // string 'null' or 'undefined'. Just delete instead.
  15577. delete process.env.DEBUG;
  15578. }
  15579. }
  15580. /**
  15581. * Load `namespaces`.
  15582. *
  15583. * @return {String} returns the previously persisted debug modes
  15584. * @api private
  15585. */
  15586. function load() {
  15587. return process.env.DEBUG;
  15588. }
  15589. /**
  15590. * Init logic for `debug` instances.
  15591. *
  15592. * Create a new `inspectOpts` object in case `useColors` is set
  15593. * differently for a particular `debug` instance.
  15594. */
  15595. function init(debug) {
  15596. debug.inspectOpts = {};
  15597. const keys = Object.keys(exports.inspectOpts);
  15598. for (let i = 0; i < keys.length; i++) {
  15599. debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
  15600. }
  15601. }
  15602. module.exports = common$4(exports);
  15603. const {formatters} = module.exports;
  15604. /**
  15605. * Map %o to `util.inspect()`, all on a single line.
  15606. */
  15607. formatters.o = function (v) {
  15608. this.inspectOpts.colors = this.useColors;
  15609. return util.inspect(v, this.inspectOpts)
  15610. .split('\n')
  15611. .map(str => str.trim())
  15612. .join(' ');
  15613. };
  15614. /**
  15615. * Map %O to `util.inspect()`, allowing multiple lines if needed.
  15616. */
  15617. formatters.O = function (v) {
  15618. this.inspectOpts.colors = this.useColors;
  15619. return util.inspect(v, this.inspectOpts);
  15620. };
  15621. }(node$1, node$1.exports));
  15622. /**
  15623. * Detect Electron renderer / nwjs process, which is node, but we should
  15624. * treat as a browser.
  15625. */
  15626. if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {
  15627. src$2.exports = browser$1.exports;
  15628. } else {
  15629. src$2.exports = node$1.exports;
  15630. }
  15631. var _debug = src$2.exports;
  15632. const DEFAULT_MAIN_FIELDS = [
  15633. 'module',
  15634. 'jsnext:main',
  15635. 'jsnext'
  15636. ];
  15637. const DEFAULT_EXTENSIONS$1 = [
  15638. '.mjs',
  15639. '.js',
  15640. '.ts',
  15641. '.jsx',
  15642. '.tsx',
  15643. '.json'
  15644. ];
  15645. const JS_TYPES_RE = /\.(?:j|t)sx?$|\.mjs$/;
  15646. const OPTIMIZABLE_ENTRY_RE = /\.(?:m?js|ts)$/;
  15647. const SPECIAL_QUERY_RE = /[\?&](?:worker|sharedworker|raw|url)\b/;
  15648. /**
  15649. * Prefix for resolved fs paths, since windows paths may not be valid as URLs.
  15650. */
  15651. const FS_PREFIX = `/@fs/`;
  15652. /**
  15653. * Prefix for resolved Ids that are not valid browser import specifiers
  15654. */
  15655. const VALID_ID_PREFIX = `/@id/`;
  15656. /**
  15657. * Plugins that use 'virtual modules' (e.g. for helper functions), prefix the
  15658. * module ID with `\0`, a convention from the rollup ecosystem.
  15659. * This prevents other plugins from trying to process the id (like node resolution),
  15660. * and core features like sourcemaps can use this info to differentiate between
  15661. * virtual modules and regular files.
  15662. * `\0` is not a permitted char in import URLs so we have to replace them during
  15663. * import analysis. The id will be decoded back before entering the plugins pipeline.
  15664. * These encoded virtual ids are also prefixed by the VALID_ID_PREFIX, so virtual
  15665. * modules in the browser end up encoded as `/@id/__x00__{id}`
  15666. */
  15667. const NULL_BYTE_PLACEHOLDER = `__x00__`;
  15668. const CLIENT_PUBLIC_PATH = `/@vite/client`;
  15669. const ENV_PUBLIC_PATH = `/@vite/env`;
  15670. // eslint-disable-next-line node/no-missing-require
  15671. const CLIENT_ENTRY = require.resolve('vite/dist/client/client.mjs');
  15672. // eslint-disable-next-line node/no-missing-require
  15673. const ENV_ENTRY = require.resolve('vite/dist/client/env.mjs');
  15674. const CLIENT_DIR = path__default.dirname(CLIENT_ENTRY);
  15675. // ** READ THIS ** before editing `KNOWN_ASSET_TYPES`.
  15676. // If you add an asset to `KNOWN_ASSET_TYPES`, make sure to also add it
  15677. // to the TypeScript declaration file `packages/vite/client.d.ts`.
  15678. const KNOWN_ASSET_TYPES = [
  15679. // images
  15680. 'png',
  15681. 'jpe?g',
  15682. 'gif',
  15683. 'svg',
  15684. 'ico',
  15685. 'webp',
  15686. 'avif',
  15687. // media
  15688. 'mp4',
  15689. 'webm',
  15690. 'ogg',
  15691. 'mp3',
  15692. 'wav',
  15693. 'flac',
  15694. 'aac',
  15695. // fonts
  15696. 'woff2?',
  15697. 'eot',
  15698. 'ttf',
  15699. 'otf',
  15700. // other
  15701. 'wasm',
  15702. 'webmanifest',
  15703. 'pdf',
  15704. 'txt'
  15705. ];
  15706. const DEFAULT_ASSETS_RE = new RegExp(`\\.(` + KNOWN_ASSET_TYPES.join('|') + `)(\\?.*)?$`);
  15707. const DEP_VERSION_RE = /[\?&](v=[\w\.-]+)\b/;
  15708. function slash(p) {
  15709. return p.replace(/\\/g, '/');
  15710. }
  15711. // Strip valid id prefix. This is prepended to resolved Ids that are
  15712. // not valid browser import specifiers by the importAnalysis plugin.
  15713. function unwrapId(id) {
  15714. return id.startsWith(VALID_ID_PREFIX) ? id.slice(VALID_ID_PREFIX.length) : id;
  15715. }
  15716. const flattenId = (id) => id.replace(/(\s*>\s*)/g, '__').replace(/[\/\.:]/g, '_');
  15717. const normalizeId = (id) => id.replace(/(\s*>\s*)/g, ' > ');
  15718. //TODO: revisit later to see if the edge case that "compiling using node v12 code to be run in node v16 in the server" is what we intend to support.
  15719. const builtins = new Set([
  15720. ...require$$0$7.builtinModules,
  15721. 'assert/strict',
  15722. 'diagnostics_channel',
  15723. 'dns/promises',
  15724. 'fs/promises',
  15725. 'path/posix',
  15726. 'path/win32',
  15727. 'readline/promises',
  15728. 'stream/consumers',
  15729. 'stream/promises',
  15730. 'stream/web',
  15731. 'timers/promises',
  15732. 'util/types',
  15733. 'wasi'
  15734. ]);
  15735. function isBuiltin(id) {
  15736. return builtins.has(id.replace(/^node:/, ''));
  15737. }
  15738. function moduleListContains(moduleList, id) {
  15739. return moduleList === null || moduleList === void 0 ? void 0 : moduleList.some((m) => m === id || id.startsWith(m + '/'));
  15740. }
  15741. const bareImportRE = /^[\w@](?!.*:\/\/)/;
  15742. let isRunningWithYarnPnp;
  15743. try {
  15744. isRunningWithYarnPnp = Boolean(require('pnpapi'));
  15745. }
  15746. catch { }
  15747. const ssrExtensions = ['.js', '.cjs', '.json', '.node'];
  15748. function resolveFrom(id, basedir, preserveSymlinks = false, ssr = false) {
  15749. return resolve__default.sync(id, {
  15750. basedir,
  15751. paths: [],
  15752. extensions: ssr ? ssrExtensions : DEFAULT_EXTENSIONS$1,
  15753. // necessary to work with pnpm
  15754. preserveSymlinks: preserveSymlinks || isRunningWithYarnPnp || false
  15755. });
  15756. }
  15757. /**
  15758. * like `resolveFrom` but supports resolving `>` path in `id`,
  15759. * for example: `foo > bar > baz`
  15760. */
  15761. function nestedResolveFrom(id, basedir, preserveSymlinks = false) {
  15762. const pkgs = id.split('>').map((pkg) => pkg.trim());
  15763. try {
  15764. for (const pkg of pkgs) {
  15765. basedir = resolveFrom(pkg, basedir, preserveSymlinks);
  15766. }
  15767. }
  15768. catch { }
  15769. return basedir;
  15770. }
  15771. // set in bin/vite.js
  15772. const filter = process.env.VITE_DEBUG_FILTER;
  15773. const DEBUG = process.env.DEBUG;
  15774. function createDebugger(namespace, options = {}) {
  15775. const log = _debug(namespace);
  15776. const { onlyWhenFocused } = options;
  15777. const focus = typeof onlyWhenFocused === 'string' ? onlyWhenFocused : namespace;
  15778. return (msg, ...args) => {
  15779. if (filter && !msg.includes(filter)) {
  15780. return;
  15781. }
  15782. if (onlyWhenFocused && !(DEBUG === null || DEBUG === void 0 ? void 0 : DEBUG.includes(focus))) {
  15783. return;
  15784. }
  15785. log(msg, ...args);
  15786. };
  15787. }
  15788. function testCaseInsensitiveFS() {
  15789. if (!CLIENT_ENTRY.endsWith('client.mjs')) {
  15790. throw new Error(`cannot test case insensitive FS, CLIENT_ENTRY const doesn't contain client.mjs`);
  15791. }
  15792. if (!fs__default.existsSync(CLIENT_ENTRY)) {
  15793. throw new Error('cannot test case insensitive FS, CLIENT_ENTRY does not point to an existing file: ' +
  15794. CLIENT_ENTRY);
  15795. }
  15796. return fs__default.existsSync(CLIENT_ENTRY.replace('client.mjs', 'cLiEnT.mjs'));
  15797. }
  15798. const isCaseInsensitiveFS = testCaseInsensitiveFS();
  15799. const isWindows$3 = require$$2__default.platform() === 'win32';
  15800. const VOLUME_RE = /^[A-Z]:/i;
  15801. function normalizePath$3(id) {
  15802. return path__default.posix.normalize(isWindows$3 ? slash(id) : id);
  15803. }
  15804. function fsPathFromId(id) {
  15805. const fsPath = normalizePath$3(id.startsWith(FS_PREFIX) ? id.slice(FS_PREFIX.length) : id);
  15806. return fsPath.startsWith('/') || fsPath.match(VOLUME_RE)
  15807. ? fsPath
  15808. : `/${fsPath}`;
  15809. }
  15810. function fsPathFromUrl(url) {
  15811. return fsPathFromId(cleanUrl(url));
  15812. }
  15813. /**
  15814. * Check if dir is a parent of file
  15815. *
  15816. * Warning: parameters are not validated, only works with normalized absolute paths
  15817. *
  15818. * @param dir - normalized absolute path
  15819. * @param file - normalized absolute path
  15820. * @returns true if dir is a parent of file
  15821. */
  15822. function isParentDirectory(dir, file) {
  15823. if (!dir.endsWith('/')) {
  15824. dir = `${dir}/`;
  15825. }
  15826. return (file.startsWith(dir) ||
  15827. (isCaseInsensitiveFS && file.toLowerCase().startsWith(dir.toLowerCase())));
  15828. }
  15829. function ensureVolumeInPath(file) {
  15830. return isWindows$3 ? path__default.resolve(file) : file;
  15831. }
  15832. const queryRE = /\?.*$/s;
  15833. const hashRE = /#.*$/s;
  15834. const cleanUrl = (url) => url.replace(hashRE, '').replace(queryRE, '');
  15835. const externalRE = /^(https?:)?\/\//;
  15836. const isExternalUrl = (url) => externalRE.test(url);
  15837. const dataUrlRE = /^\s*data:/i;
  15838. const isDataUrl = (url) => dataUrlRE.test(url);
  15839. const virtualModuleRE = /^virtual-module:.*/;
  15840. const virtualModulePrefix = 'virtual-module:';
  15841. const knownJsSrcRE = /\.((j|t)sx?|mjs|vue|marko|svelte|astro)($|\?)/;
  15842. const isJSRequest = (url) => {
  15843. url = cleanUrl(url);
  15844. if (knownJsSrcRE.test(url)) {
  15845. return true;
  15846. }
  15847. if (!path__default.extname(url) && !url.endsWith('/')) {
  15848. return true;
  15849. }
  15850. return false;
  15851. };
  15852. const knownTsRE = /\.(ts|mts|cts|tsx)$/;
  15853. const knownTsOutputRE = /\.(js|mjs|cjs|jsx)$/;
  15854. const isTsRequest = (url) => knownTsRE.test(url);
  15855. const isPossibleTsOutput = (url) => knownTsOutputRE.test(cleanUrl(url));
  15856. function getPotentialTsSrcPaths(filePath) {
  15857. const [name, type, query = ''] = filePath.split(/(\.(?:[cm]?js|jsx))(\?.*)?$/);
  15858. const paths = [name + type.replace('js', 'ts') + query];
  15859. if (!type.endsWith('x')) {
  15860. paths.push(name + type.replace('js', 'tsx') + query);
  15861. }
  15862. return paths;
  15863. }
  15864. const importQueryRE = /(\?|&)import=?(?:&|$)/;
  15865. const internalPrefixes = [
  15866. FS_PREFIX,
  15867. VALID_ID_PREFIX,
  15868. CLIENT_PUBLIC_PATH,
  15869. ENV_PUBLIC_PATH
  15870. ];
  15871. const InternalPrefixRE = new RegExp(`^(?:${internalPrefixes.join('|')})`);
  15872. const trailingSeparatorRE = /[\?&]$/;
  15873. const isImportRequest = (url) => importQueryRE.test(url);
  15874. const isInternalRequest = (url) => InternalPrefixRE.test(url);
  15875. function removeImportQuery(url) {
  15876. return url.replace(importQueryRE, '$1').replace(trailingSeparatorRE, '');
  15877. }
  15878. function injectQuery(url, queryToInject) {
  15879. // encode percents for consistent behavior with pathToFileURL
  15880. // see #2614 for details
  15881. let resolvedUrl = new require$$0$6.URL(url.replace(/%/g, '%25'), 'relative:///');
  15882. if (resolvedUrl.protocol !== 'relative:') {
  15883. resolvedUrl = require$$0$6.pathToFileURL(url);
  15884. }
  15885. let { protocol, pathname, search, hash } = resolvedUrl;
  15886. if (protocol === 'file:') {
  15887. pathname = pathname.slice(1);
  15888. }
  15889. pathname = decodeURIComponent(pathname);
  15890. return `${pathname}?${queryToInject}${search ? `&` + search.slice(1) : ''}${hash !== null && hash !== void 0 ? hash : ''}`;
  15891. }
  15892. const timestampRE = /\bt=\d{13}&?\b/;
  15893. function removeTimestampQuery(url) {
  15894. return url.replace(timestampRE, '').replace(trailingSeparatorRE, '');
  15895. }
  15896. async function asyncReplace(input, re, replacer) {
  15897. let match;
  15898. let remaining = input;
  15899. let rewritten = '';
  15900. while ((match = re.exec(remaining))) {
  15901. rewritten += remaining.slice(0, match.index);
  15902. rewritten += await replacer(match);
  15903. remaining = remaining.slice(match.index + match[0].length);
  15904. }
  15905. rewritten += remaining;
  15906. return rewritten;
  15907. }
  15908. function timeFrom(start, subtract = 0) {
  15909. const time = perf_hooks.performance.now() - start - subtract;
  15910. const timeString = (time.toFixed(2) + `ms`).padEnd(5, ' ');
  15911. if (time < 10) {
  15912. return colors$1.green(timeString);
  15913. }
  15914. else if (time < 50) {
  15915. return colors$1.yellow(timeString);
  15916. }
  15917. else {
  15918. return colors$1.red(timeString);
  15919. }
  15920. }
  15921. /**
  15922. * pretty url for logging.
  15923. */
  15924. function prettifyUrl(url, root) {
  15925. url = removeTimestampQuery(url);
  15926. const isAbsoluteFile = url.startsWith(root);
  15927. if (isAbsoluteFile || url.startsWith(FS_PREFIX)) {
  15928. let file = path__default.relative(root, isAbsoluteFile ? url : fsPathFromId(url));
  15929. const seg = file.split('/');
  15930. const npmIndex = seg.indexOf(`node_modules`);
  15931. const isSourceMap = file.endsWith('.map');
  15932. if (npmIndex > 0) {
  15933. file = seg[npmIndex + 1];
  15934. if (file.startsWith('@')) {
  15935. file = `${file}/${seg[npmIndex + 2]}`;
  15936. }
  15937. file = `npm: ${colors$1.dim(file)}${isSourceMap ? ` (source map)` : ``}`;
  15938. }
  15939. return colors$1.dim(file);
  15940. }
  15941. else {
  15942. return colors$1.dim(url);
  15943. }
  15944. }
  15945. function isObject$1(value) {
  15946. return Object.prototype.toString.call(value) === '[object Object]';
  15947. }
  15948. function isDefined(value) {
  15949. return value != null;
  15950. }
  15951. function lookupFile(dir, formats, options) {
  15952. for (const format of formats) {
  15953. const fullPath = path__default.join(dir, format);
  15954. if (fs__default.existsSync(fullPath) && fs__default.statSync(fullPath).isFile()) {
  15955. return (options === null || options === void 0 ? void 0 : options.pathOnly) ? fullPath : fs__default.readFileSync(fullPath, 'utf-8');
  15956. }
  15957. }
  15958. const parentDir = path__default.dirname(dir);
  15959. if (parentDir !== dir &&
  15960. (!(options === null || options === void 0 ? void 0 : options.rootDir) || parentDir.startsWith(options === null || options === void 0 ? void 0 : options.rootDir))) {
  15961. return lookupFile(parentDir, formats, options);
  15962. }
  15963. }
  15964. const splitRE = /\r?\n/;
  15965. const range = 2;
  15966. function pad(source, n = 2) {
  15967. const lines = source.split(splitRE);
  15968. return lines.map((l) => ` `.repeat(n) + l).join(`\n`);
  15969. }
  15970. function posToNumber(source, pos) {
  15971. if (typeof pos === 'number')
  15972. return pos;
  15973. const lines = source.split(splitRE);
  15974. const { line, column } = pos;
  15975. let start = 0;
  15976. for (let i = 0; i < line - 1; i++) {
  15977. if (lines[i]) {
  15978. start += lines[i].length + 1;
  15979. }
  15980. }
  15981. return start + column;
  15982. }
  15983. function numberToPos(source, offset) {
  15984. if (typeof offset !== 'number')
  15985. return offset;
  15986. if (offset > source.length) {
  15987. throw new Error(`offset is longer than source length! offset ${offset} > length ${source.length}`);
  15988. }
  15989. const lines = source.split(splitRE);
  15990. let counted = 0;
  15991. let line = 0;
  15992. let column = 0;
  15993. for (; line < lines.length; line++) {
  15994. const lineLength = lines[line].length + 1;
  15995. if (counted + lineLength >= offset) {
  15996. column = offset - counted + 1;
  15997. break;
  15998. }
  15999. counted += lineLength;
  16000. }
  16001. return { line: line + 1, column };
  16002. }
  16003. function generateCodeFrame(source, start = 0, end) {
  16004. start = posToNumber(source, start);
  16005. end = end || start;
  16006. const lines = source.split(splitRE);
  16007. let count = 0;
  16008. const res = [];
  16009. for (let i = 0; i < lines.length; i++) {
  16010. count += lines[i].length + 1;
  16011. if (count >= start) {
  16012. for (let j = i - range; j <= i + range || end > count; j++) {
  16013. if (j < 0 || j >= lines.length)
  16014. continue;
  16015. const line = j + 1;
  16016. res.push(`${line}${' '.repeat(Math.max(3 - String(line).length, 0))}| ${lines[j]}`);
  16017. const lineLength = lines[j].length;
  16018. if (j === i) {
  16019. // push underline
  16020. const pad = start - (count - lineLength) + 1;
  16021. const length = Math.max(1, end > count ? lineLength - pad : end - start);
  16022. res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length));
  16023. }
  16024. else if (j > i) {
  16025. if (end > count) {
  16026. const length = Math.max(Math.min(end - count, lineLength), 1);
  16027. res.push(` | ` + '^'.repeat(length));
  16028. }
  16029. count += lineLength + 1;
  16030. }
  16031. }
  16032. break;
  16033. }
  16034. }
  16035. return res.join('\n');
  16036. }
  16037. function writeFile(filename, content) {
  16038. const dir = path__default.dirname(filename);
  16039. if (!fs__default.existsSync(dir)) {
  16040. fs__default.mkdirSync(dir, { recursive: true });
  16041. }
  16042. fs__default.writeFileSync(filename, content);
  16043. }
  16044. /**
  16045. * Use instead of fs.existsSync(filename)
  16046. * #2051 if we don't have read permission on a directory, existsSync() still
  16047. * works and will result in massively slow subsequent checks (which are
  16048. * unnecessary in the first place)
  16049. */
  16050. function isFileReadable(filename) {
  16051. try {
  16052. const stat = fs__default.statSync(filename, { throwIfNoEntry: false });
  16053. return !!stat;
  16054. }
  16055. catch {
  16056. return false;
  16057. }
  16058. }
  16059. /**
  16060. * Delete every file and subdirectory. **The given directory must exist.**
  16061. * Pass an optional `skip` array to preserve files in the root directory.
  16062. */
  16063. function emptyDir(dir, skip) {
  16064. for (const file of fs__default.readdirSync(dir)) {
  16065. if (skip === null || skip === void 0 ? void 0 : skip.includes(file)) {
  16066. continue;
  16067. }
  16068. const abs = path__default.resolve(dir, file);
  16069. // baseline is Node 12 so can't use rmSync :(
  16070. if (fs__default.lstatSync(abs).isDirectory()) {
  16071. emptyDir(abs);
  16072. fs__default.rmdirSync(abs);
  16073. }
  16074. else {
  16075. fs__default.unlinkSync(abs);
  16076. }
  16077. }
  16078. }
  16079. function copyDir(srcDir, destDir) {
  16080. fs__default.mkdirSync(destDir, { recursive: true });
  16081. for (const file of fs__default.readdirSync(srcDir)) {
  16082. const srcFile = path__default.resolve(srcDir, file);
  16083. if (srcFile === destDir) {
  16084. continue;
  16085. }
  16086. const destFile = path__default.resolve(destDir, file);
  16087. const stat = fs__default.statSync(srcFile);
  16088. if (stat.isDirectory()) {
  16089. copyDir(srcFile, destFile);
  16090. }
  16091. else {
  16092. fs__default.copyFileSync(srcFile, destFile);
  16093. }
  16094. }
  16095. }
  16096. function removeDirSync(dir) {
  16097. var _a;
  16098. if (fs__default.existsSync(dir)) {
  16099. const rmSync = (_a = fs__default.rmSync) !== null && _a !== void 0 ? _a : fs__default.rmdirSync; // TODO: Remove after support for Node 12 is dropped
  16100. rmSync(dir, { recursive: true });
  16101. }
  16102. }
  16103. const removeDir = isWindows$3
  16104. ? require$$0$4.promisify(gracefulRemoveDir)
  16105. : removeDirSync;
  16106. const renameDir = isWindows$3 ? require$$0$4.promisify(gracefulRename) : fs__default.renameSync;
  16107. function ensureWatchedFile(watcher, file, root) {
  16108. if (file &&
  16109. // only need to watch if out of root
  16110. !file.startsWith(root + '/') &&
  16111. // some rollup plugins use null bytes for private resolved Ids
  16112. !file.includes('\0') &&
  16113. fs__default.existsSync(file)) {
  16114. // resolve file to normalized system path
  16115. watcher.add(path__default.resolve(file));
  16116. }
  16117. }
  16118. const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g;
  16119. const imageSetUrlRE = /^(?:[\w\-]+\(.*?\)|'.*?'|".*?"|\S*)/;
  16120. async function processSrcSet(srcs, replacer) {
  16121. const imageCandidates = splitSrcSet(srcs)
  16122. .map((s) => {
  16123. const src = s.replace(escapedSpaceCharacters, ' ').trim();
  16124. const [url] = imageSetUrlRE.exec(src) || [];
  16125. return {
  16126. url,
  16127. descriptor: src === null || src === void 0 ? void 0 : src.slice(url.length).trim()
  16128. };
  16129. })
  16130. .filter(({ url }) => !!url);
  16131. const ret = await Promise.all(imageCandidates.map(async ({ url, descriptor }) => {
  16132. return {
  16133. url: await replacer({ url, descriptor }),
  16134. descriptor
  16135. };
  16136. }));
  16137. return ret.reduce((prev, { url, descriptor }, index) => {
  16138. descriptor !== null && descriptor !== void 0 ? descriptor : (descriptor = '');
  16139. return (prev +=
  16140. url + ` ${descriptor}${index === ret.length - 1 ? '' : ', '}`);
  16141. }, '');
  16142. }
  16143. function splitSrcSet(srcs) {
  16144. const parts = [];
  16145. // There could be a ',' inside of url(data:...), linear-gradient(...) or "data:..."
  16146. const cleanedSrcs = srcs.replace(/(?:url|image|gradient|cross-fade)\([^\)]*\)|"([^"]|(?<=\\)")*"|'([^']|(?<=\\)')*'/g, blankReplacer);
  16147. let startIndex = 0;
  16148. let splitIndex;
  16149. do {
  16150. splitIndex = cleanedSrcs.indexOf(',', startIndex);
  16151. parts.push(srcs.slice(startIndex, splitIndex !== -1 ? splitIndex : undefined));
  16152. startIndex = splitIndex + 1;
  16153. } while (splitIndex !== -1);
  16154. return parts;
  16155. }
  16156. function escapeToLinuxLikePath(path) {
  16157. if (/^[A-Z]:/.test(path)) {
  16158. return path.replace(/^([A-Z]):\//, '/windows/$1/');
  16159. }
  16160. if (/^\/[^/]/.test(path)) {
  16161. return `/linux${path}`;
  16162. }
  16163. return path;
  16164. }
  16165. function unescapeToLinuxLikePath(path) {
  16166. if (path.startsWith('/linux/')) {
  16167. return path.slice('/linux'.length);
  16168. }
  16169. if (path.startsWith('/windows/')) {
  16170. return path.replace(/^\/windows\/([A-Z])\//, '$1:/');
  16171. }
  16172. return path;
  16173. }
  16174. // based on https://github.com/sveltejs/svelte/blob/abf11bb02b2afbd3e4cac509a0f70e318c306364/src/compiler/utils/mapped_code.ts#L221
  16175. const nullSourceMap = {
  16176. names: [],
  16177. sources: [],
  16178. mappings: '',
  16179. version: 3
  16180. };
  16181. function combineSourcemaps(filename, sourcemapList, excludeContent = true) {
  16182. if (sourcemapList.length === 0 ||
  16183. sourcemapList.every((m) => m.sources.length === 0)) {
  16184. return { ...nullSourceMap };
  16185. }
  16186. // hack for parse broken with normalized absolute paths on windows (C:/path/to/something).
  16187. // escape them to linux like paths
  16188. // also avoid mutation here to prevent breaking plugin's using cache to generate sourcemaps like vue (see #7442)
  16189. sourcemapList = sourcemapList.map((sourcemap) => {
  16190. const newSourcemaps = { ...sourcemap };
  16191. newSourcemaps.sources = sourcemap.sources.map((source) => source ? escapeToLinuxLikePath(source) : null);
  16192. if (sourcemap.sourceRoot) {
  16193. newSourcemaps.sourceRoot = escapeToLinuxLikePath(sourcemap.sourceRoot);
  16194. }
  16195. return newSourcemaps;
  16196. });
  16197. const escapedFilename = escapeToLinuxLikePath(filename);
  16198. // We don't declare type here so we can convert/fake/map as RawSourceMap
  16199. let map; //: SourceMap
  16200. let mapIndex = 1;
  16201. const useArrayInterface = sourcemapList.slice(0, -1).find((m) => m.sources.length !== 1) === undefined;
  16202. if (useArrayInterface) {
  16203. map = remapping(sourcemapList, () => null, excludeContent);
  16204. }
  16205. else {
  16206. map = remapping(sourcemapList[0], function loader(sourcefile) {
  16207. if (sourcefile === escapedFilename && sourcemapList[mapIndex]) {
  16208. return sourcemapList[mapIndex++];
  16209. }
  16210. else {
  16211. return null;
  16212. }
  16213. }, excludeContent);
  16214. }
  16215. if (!map.file) {
  16216. delete map.file;
  16217. }
  16218. // unescape the previous hack
  16219. map.sources = map.sources.map((source) => source ? unescapeToLinuxLikePath(source) : source);
  16220. map.file = filename;
  16221. return map;
  16222. }
  16223. function resolveHostname(optionsHost) {
  16224. let host;
  16225. if (optionsHost === undefined || optionsHost === false) {
  16226. // Use a secure default
  16227. host = '127.0.0.1';
  16228. }
  16229. else if (optionsHost === true) {
  16230. // If passed --host in the CLI without arguments
  16231. host = undefined; // undefined typically means 0.0.0.0 or :: (listen on all IPs)
  16232. }
  16233. else {
  16234. host = optionsHost;
  16235. }
  16236. // Set host name to localhost when possible, unless the user explicitly asked for '127.0.0.1'
  16237. const name = (optionsHost !== '127.0.0.1' && host === '127.0.0.1') ||
  16238. host === '0.0.0.0' ||
  16239. host === '::' ||
  16240. host === undefined
  16241. ? 'localhost'
  16242. : host;
  16243. return { host, name };
  16244. }
  16245. function arraify(target) {
  16246. return Array.isArray(target) ? target : [target];
  16247. }
  16248. function toUpperCaseDriveLetter(pathName) {
  16249. return pathName.replace(/^\w:/, (letter) => letter.toUpperCase());
  16250. }
  16251. const multilineCommentsRE = /\/\*(.|[\r\n])*?\*\//gm;
  16252. const singlelineCommentsRE = /\/\/.*/g;
  16253. const usingDynamicImport = typeof jest === 'undefined';
  16254. /**
  16255. * Dynamically import files. It will make sure it's not being compiled away by TS/Rollup.
  16256. *
  16257. * As a temporary workaround for Jest's lack of stable ESM support, we fallback to require
  16258. * if we're in a Jest environment.
  16259. * See https://github.com/vitejs/vite/pull/5197#issuecomment-938054077
  16260. *
  16261. * @param file File path to import.
  16262. */
  16263. const dynamicImport = usingDynamicImport
  16264. ? new Function('file', 'return import(file)')
  16265. : require;
  16266. function parseRequest(id) {
  16267. const { search } = require$$0$6.parse(id);
  16268. if (!search) {
  16269. return null;
  16270. }
  16271. return Object.fromEntries(new require$$0$6.URLSearchParams(search.slice(1)));
  16272. }
  16273. const blankReplacer = (match) => ' '.repeat(match.length);
  16274. // Based on node-graceful-fs
  16275. // The ISC License
  16276. // Copyright (c) 2011-2022 Isaac Z. Schlueter, Ben Noordhuis, and Contributors
  16277. // https://github.com/isaacs/node-graceful-fs/blob/main/LICENSE
  16278. // On Windows, A/V software can lock the directory, causing this
  16279. // to fail with an EACCES or EPERM if the directory contains newly
  16280. // created files. The original tried for up to 60 seconds, we only
  16281. // wait for 5 seconds, as a longer time would be seen as an error
  16282. const GRACEFUL_RENAME_TIMEOUT = 5000;
  16283. function gracefulRename(from, to, cb) {
  16284. const start = Date.now();
  16285. let backoff = 0;
  16286. fs__default.rename(from, to, function CB(er) {
  16287. if (er &&
  16288. (er.code === 'EACCES' || er.code === 'EPERM') &&
  16289. Date.now() - start < GRACEFUL_RENAME_TIMEOUT) {
  16290. setTimeout(function () {
  16291. fs__default.stat(to, function (stater, st) {
  16292. if (stater && stater.code === 'ENOENT')
  16293. fs__default.rename(from, to, CB);
  16294. else
  16295. CB(er);
  16296. });
  16297. }, backoff);
  16298. if (backoff < 100)
  16299. backoff += 10;
  16300. return;
  16301. }
  16302. if (cb)
  16303. cb(er);
  16304. });
  16305. }
  16306. const GRACEFUL_REMOVE_DIR_TIMEOUT = 5000;
  16307. function gracefulRemoveDir(dir, cb) {
  16308. var _a;
  16309. const rmdir = (_a = fs__default.rm) !== null && _a !== void 0 ? _a : fs__default.rmdir; // TODO: Remove after support for Node 12 is dropped
  16310. const start = Date.now();
  16311. let backoff = 0;
  16312. rmdir(dir, { recursive: true }, function CB(er) {
  16313. if (er) {
  16314. if ((er.code === 'ENOTEMPTY' ||
  16315. er.code === 'EACCES' ||
  16316. er.code === 'EPERM') &&
  16317. Date.now() - start < GRACEFUL_REMOVE_DIR_TIMEOUT) {
  16318. setTimeout(function () {
  16319. rmdir(dir, { recursive: true }, CB);
  16320. }, backoff);
  16321. if (backoff < 100)
  16322. backoff += 10;
  16323. return;
  16324. }
  16325. if (er.code === 'ENOENT') {
  16326. er = null;
  16327. }
  16328. }
  16329. if (cb)
  16330. cb(er);
  16331. });
  16332. }
  16333. function emptyCssComments(raw) {
  16334. return raw.replace(multilineCommentsRE, (s) => ' '.repeat(s.length));
  16335. }
  16336. /* eslint no-console: 0 */
  16337. const LogLevels = {
  16338. silent: 0,
  16339. error: 1,
  16340. warn: 2,
  16341. info: 3
  16342. };
  16343. let lastType;
  16344. let lastMsg;
  16345. let sameCount = 0;
  16346. function clearScreen() {
  16347. const repeatCount = process.stdout.rows - 2;
  16348. const blank = repeatCount > 0 ? '\n'.repeat(repeatCount) : '';
  16349. console.log(blank);
  16350. readline__default.cursorTo(process.stdout, 0, 0);
  16351. readline__default.clearScreenDown(process.stdout);
  16352. }
  16353. function createLogger(level = 'info', options = {}) {
  16354. if (options.customLogger) {
  16355. return options.customLogger;
  16356. }
  16357. const loggedErrors = new WeakSet();
  16358. const { prefix = '[vite]', allowClearScreen = true } = options;
  16359. const thresh = LogLevels[level];
  16360. const canClearScreen = allowClearScreen && process.stdout.isTTY && !process.env.CI;
  16361. const clear = canClearScreen ? clearScreen : () => { };
  16362. function output(type, msg, options = {}) {
  16363. if (thresh >= LogLevels[type]) {
  16364. const method = type === 'info' ? 'log' : type;
  16365. const format = () => {
  16366. if (options.timestamp) {
  16367. const tag = type === 'info'
  16368. ? colors$1.cyan(colors$1.bold(prefix))
  16369. : type === 'warn'
  16370. ? colors$1.yellow(colors$1.bold(prefix))
  16371. : colors$1.red(colors$1.bold(prefix));
  16372. return `${colors$1.dim(new Date().toLocaleTimeString())} ${tag} ${msg}`;
  16373. }
  16374. else {
  16375. return msg;
  16376. }
  16377. };
  16378. if (options.error) {
  16379. loggedErrors.add(options.error);
  16380. }
  16381. if (canClearScreen) {
  16382. if (type === lastType && msg === lastMsg) {
  16383. sameCount++;
  16384. clear();
  16385. console[method](format(), colors$1.yellow(`(x${sameCount + 1})`));
  16386. }
  16387. else {
  16388. sameCount = 0;
  16389. lastMsg = msg;
  16390. lastType = type;
  16391. if (options.clear) {
  16392. clear();
  16393. }
  16394. console[method](format());
  16395. }
  16396. }
  16397. else {
  16398. console[method](format());
  16399. }
  16400. }
  16401. }
  16402. const warnedMessages = new Set();
  16403. const logger = {
  16404. hasWarned: false,
  16405. info(msg, opts) {
  16406. output('info', msg, opts);
  16407. },
  16408. warn(msg, opts) {
  16409. logger.hasWarned = true;
  16410. output('warn', msg, opts);
  16411. },
  16412. warnOnce(msg, opts) {
  16413. if (warnedMessages.has(msg))
  16414. return;
  16415. logger.hasWarned = true;
  16416. output('warn', msg, opts);
  16417. warnedMessages.add(msg);
  16418. },
  16419. error(msg, opts) {
  16420. logger.hasWarned = true;
  16421. output('error', msg, opts);
  16422. },
  16423. clearScreen(type) {
  16424. if (thresh >= LogLevels[type]) {
  16425. clear();
  16426. }
  16427. },
  16428. hasErrorLogged(error) {
  16429. return loggedErrors.has(error);
  16430. }
  16431. };
  16432. return logger;
  16433. }
  16434. /**
  16435. * @deprecated Use `server.printUrls()` instead
  16436. */
  16437. function printHttpServerUrls(server, config) {
  16438. printCommonServerUrls(server, config.server, config);
  16439. }
  16440. function printCommonServerUrls(server, options, config) {
  16441. const address = server.address();
  16442. const isAddressInfo = (x) => x === null || x === void 0 ? void 0 : x.address;
  16443. if (isAddressInfo(address)) {
  16444. const hostname = resolveHostname(options.host);
  16445. const protocol = options.https ? 'https' : 'http';
  16446. printServerUrls(hostname, protocol, address.port, config.base, config.logger.info);
  16447. }
  16448. }
  16449. function printServerUrls(hostname, protocol, port, base, info) {
  16450. if (hostname.host === '127.0.0.1') {
  16451. const url = `${protocol}://${hostname.name}:${colors$1.bold(port)}${base}`;
  16452. info(` > Local: ${colors$1.cyan(url)}`);
  16453. if (hostname.name !== '127.0.0.1') {
  16454. info(` > Network: ${colors$1.dim('use `--host` to expose')}`);
  16455. }
  16456. }
  16457. else {
  16458. Object.values(require$$2__default.networkInterfaces())
  16459. .flatMap((nInterface) => nInterface !== null && nInterface !== void 0 ? nInterface : [])
  16460. .filter((detail) => detail &&
  16461. detail.address &&
  16462. // Node < v18
  16463. ((typeof detail.family === 'string' && detail.family === 'IPv4') ||
  16464. // Node >= v18
  16465. (typeof detail.family === 'number' && detail.family === 4)))
  16466. .map((detail) => {
  16467. const type = detail.address.includes('127.0.0.1')
  16468. ? 'Local: '
  16469. : 'Network: ';
  16470. const host = detail.address.replace('127.0.0.1', hostname.name);
  16471. const url = `${protocol}://${host}:${colors$1.bold(port)}${base}`;
  16472. return ` > ${type} ${colors$1.cyan(url)}`;
  16473. })
  16474. .forEach((msg) => info(msg));
  16475. }
  16476. }
  16477. const writeColors = {
  16478. [0 /* JS */]: colors$1.cyan,
  16479. [1 /* CSS */]: colors$1.magenta,
  16480. [2 /* ASSET */]: colors$1.green,
  16481. [3 /* HTML */]: colors$1.blue,
  16482. [4 /* SOURCE_MAP */]: colors$1.gray
  16483. };
  16484. function buildReporterPlugin(config) {
  16485. const compress = require$$0$4.promisify(zlib$1.gzip);
  16486. const chunkLimit = config.build.chunkSizeWarningLimit;
  16487. function isLarge(code) {
  16488. // bail out on particularly large chunks
  16489. return code.length / 1024 > chunkLimit;
  16490. }
  16491. async function getCompressedSize(code) {
  16492. if (config.build.ssr ||
  16493. !config.build.reportCompressedSize ||
  16494. config.build.brotliSize === false) {
  16495. return '';
  16496. }
  16497. return ` / gzip: ${((await compress(typeof code === 'string' ? code : Buffer.from(code)))
  16498. .length / 1024).toFixed(2)} KiB`;
  16499. }
  16500. function printFileInfo(filePath, content, type, maxLength, compressedSize = '') {
  16501. const outDir = normalizePath$3(path__default.relative(config.root, path__default.resolve(config.root, config.build.outDir))) + '/';
  16502. const kibs = content.length / 1024;
  16503. const sizeColor = kibs > chunkLimit ? colors$1.yellow : colors$1.dim;
  16504. config.logger.info(`${colors$1.gray(colors$1.white(colors$1.dim(outDir)))}${writeColors[type](filePath.padEnd(maxLength + 2))} ${sizeColor(`${kibs.toFixed(2)} KiB${compressedSize}`)}`);
  16505. }
  16506. const tty = process.stdout.isTTY && !process.env.CI;
  16507. const shouldLogInfo = LogLevels[config.logLevel || 'info'] >= LogLevels.info;
  16508. let hasTransformed = false;
  16509. let hasRenderedChunk = false;
  16510. let transformedCount = 0;
  16511. let chunkCount = 0;
  16512. const logTransform = throttle((id) => {
  16513. writeLine(`transforming (${transformedCount}) ${colors$1.dim(path__default.relative(config.root, id))}`);
  16514. });
  16515. return {
  16516. name: 'vite:reporter',
  16517. transform(_, id) {
  16518. transformedCount++;
  16519. if (shouldLogInfo) {
  16520. if (!tty) {
  16521. if (!hasTransformed) {
  16522. config.logger.info(`transforming...`);
  16523. }
  16524. }
  16525. else {
  16526. if (id.includes(`?`))
  16527. return;
  16528. logTransform(id);
  16529. }
  16530. hasTransformed = true;
  16531. }
  16532. return null;
  16533. },
  16534. buildEnd() {
  16535. if (shouldLogInfo) {
  16536. if (tty) {
  16537. process.stdout.clearLine(0);
  16538. process.stdout.cursorTo(0);
  16539. }
  16540. config.logger.info(`${colors$1.green(`✓`)} ${transformedCount} modules transformed.`);
  16541. }
  16542. },
  16543. renderStart() {
  16544. chunkCount = 0;
  16545. },
  16546. renderChunk() {
  16547. chunkCount++;
  16548. if (shouldLogInfo) {
  16549. if (!tty) {
  16550. if (!hasRenderedChunk) {
  16551. config.logger.info('rendering chunks...');
  16552. }
  16553. }
  16554. else {
  16555. writeLine(`rendering chunks (${chunkCount})...`);
  16556. }
  16557. hasRenderedChunk = true;
  16558. }
  16559. return null;
  16560. },
  16561. generateBundle() {
  16562. if (shouldLogInfo && tty) {
  16563. process.stdout.clearLine(0);
  16564. process.stdout.cursorTo(0);
  16565. }
  16566. },
  16567. async writeBundle(_, output) {
  16568. let hasLargeChunks = false;
  16569. if (shouldLogInfo) {
  16570. let longest = 0;
  16571. for (const file in output) {
  16572. const l = output[file].fileName.length;
  16573. if (l > longest)
  16574. longest = l;
  16575. }
  16576. // large chunks are deferred to be logged at the end so they are more
  16577. // visible.
  16578. const deferredLogs = [];
  16579. await Promise.all(Object.keys(output).map(async (file) => {
  16580. const chunk = output[file];
  16581. if (chunk.type === 'chunk') {
  16582. const log = async () => {
  16583. printFileInfo(chunk.fileName, chunk.code, 0 /* JS */, longest, await getCompressedSize(chunk.code));
  16584. if (chunk.map) {
  16585. printFileInfo(chunk.fileName + '.map', chunk.map.toString(), 4 /* SOURCE_MAP */, longest);
  16586. }
  16587. };
  16588. if (isLarge(chunk.code)) {
  16589. hasLargeChunks = true;
  16590. deferredLogs.push(log);
  16591. }
  16592. else {
  16593. await log();
  16594. }
  16595. }
  16596. else if (chunk.source) {
  16597. const isCSS = chunk.fileName.endsWith('.css');
  16598. const isMap = chunk.fileName.endsWith('.js.map');
  16599. printFileInfo(chunk.fileName, chunk.source, isCSS
  16600. ? 1 /* CSS */
  16601. : isMap
  16602. ? 4 /* SOURCE_MAP */
  16603. : 2 /* ASSET */, longest, isCSS ? await getCompressedSize(chunk.source) : undefined);
  16604. }
  16605. }));
  16606. await Promise.all(deferredLogs.map((l) => l()));
  16607. }
  16608. else {
  16609. hasLargeChunks = Object.keys(output).some((file) => {
  16610. const chunk = output[file];
  16611. return chunk.type === 'chunk' && chunk.code.length / 1024 > chunkLimit;
  16612. });
  16613. }
  16614. if (hasLargeChunks &&
  16615. config.build.minify &&
  16616. !config.build.lib &&
  16617. !config.build.ssr) {
  16618. config.logger.warn(colors$1.yellow(`\n(!) Some chunks are larger than ${chunkLimit} KiB after minification. Consider:\n` +
  16619. `- Using dynamic import() to code-split the application\n` +
  16620. `- Use build.rollupOptions.output.manualChunks to improve chunking: https://rollupjs.org/guide/en/#outputmanualchunks\n` +
  16621. `- Adjust chunk size limit for this warning via build.chunkSizeWarningLimit.`));
  16622. }
  16623. }
  16624. };
  16625. }
  16626. function writeLine(output) {
  16627. process.stdout.clearLine(0);
  16628. process.stdout.cursorTo(0);
  16629. if (output.length < process.stdout.columns) {
  16630. process.stdout.write(output);
  16631. }
  16632. else {
  16633. process.stdout.write(output.substring(0, process.stdout.columns - 1));
  16634. }
  16635. }
  16636. function throttle(fn) {
  16637. let timerHandle = null;
  16638. return (...args) => {
  16639. if (timerHandle)
  16640. return;
  16641. fn(...args);
  16642. timerHandle = setTimeout(() => {
  16643. timerHandle = null;
  16644. }, 100);
  16645. };
  16646. }
  16647. var __defProp = Object.defineProperty;
  16648. var __defProps = Object.defineProperties;
  16649. var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
  16650. var __getOwnPropSymbols = Object.getOwnPropertySymbols;
  16651. var __hasOwnProp = Object.prototype.hasOwnProperty;
  16652. var __propIsEnum = Object.prototype.propertyIsEnumerable;
  16653. var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  16654. var __spreadValues = (a, b) => {
  16655. for (var prop in b || (b = {}))
  16656. if (__hasOwnProp.call(b, prop))
  16657. __defNormalProp(a, prop, b[prop]);
  16658. if (__getOwnPropSymbols)
  16659. for (var prop of __getOwnPropSymbols(b)) {
  16660. if (__propIsEnum.call(b, prop))
  16661. __defNormalProp(a, prop, b[prop]);
  16662. }
  16663. return a;
  16664. };
  16665. var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
  16666. async function find(filename, options) {
  16667. let dir = path__default.dirname(path__default.resolve(filename));
  16668. const root = (options == null ? void 0 : options.root) ? path__default.resolve(options.root) : null;
  16669. while (dir) {
  16670. const tsconfig = await tsconfigInDir(dir, options);
  16671. if (tsconfig) {
  16672. return tsconfig;
  16673. } else {
  16674. if (root === dir) {
  16675. break;
  16676. }
  16677. const parent = path__default.dirname(dir);
  16678. if (parent === dir) {
  16679. break;
  16680. } else {
  16681. dir = parent;
  16682. }
  16683. }
  16684. }
  16685. throw new Error(`no tsconfig file found for ${filename}`);
  16686. }
  16687. async function tsconfigInDir(dir, options) {
  16688. const tsconfig = path__default.join(dir, "tsconfig.json");
  16689. if (options == null ? void 0 : options.tsConfigPaths) {
  16690. return options.tsConfigPaths.has(tsconfig) ? tsconfig : void 0;
  16691. }
  16692. try {
  16693. const stat = await fs$n.promises.stat(tsconfig);
  16694. if (stat.isFile() || stat.isFIFO()) {
  16695. return tsconfig;
  16696. }
  16697. } catch (e) {
  16698. if (e.code !== "ENOENT") {
  16699. throw e;
  16700. }
  16701. }
  16702. }
  16703. async function findAll(dir, options) {
  16704. const files = [];
  16705. for await (const tsconfigFile of findTSConfig(path__default.resolve(dir), options)) {
  16706. files.push(tsconfigFile);
  16707. }
  16708. return files;
  16709. }
  16710. async function* findTSConfig(dir, options, visited = /* @__PURE__ */ new Set()) {
  16711. if (!visited.has(dir)) {
  16712. visited.add(dir);
  16713. try {
  16714. const dirents = await fs$n.promises.readdir(dir, { withFileTypes: true });
  16715. for (const dirent of dirents) {
  16716. if (dirent.isDirectory() && (!(options == null ? void 0 : options.skip) || !options.skip(dirent.name))) {
  16717. yield* findTSConfig(path__default.resolve(dir, dirent.name), options, visited);
  16718. } else if (dirent.isFile() && dirent.name === "tsconfig.json") {
  16719. yield path__default.resolve(dir, dirent.name);
  16720. }
  16721. }
  16722. } catch (e) {
  16723. if (e.code === "EACCES" || e.code === "ENOENT") {
  16724. return;
  16725. }
  16726. throw e;
  16727. }
  16728. }
  16729. }
  16730. // src/to-json.ts
  16731. function toJson(tsconfigJson) {
  16732. const stripped = stripDanglingComma(stripJsonComments(stripBom(tsconfigJson)));
  16733. if (stripped.trim() === "") {
  16734. return "{}";
  16735. } else {
  16736. return stripped;
  16737. }
  16738. }
  16739. function stripDanglingComma(pseudoJson) {
  16740. let insideString = false;
  16741. let offset = 0;
  16742. let result = "";
  16743. let danglingCommaPos = null;
  16744. for (let i = 0; i < pseudoJson.length; i++) {
  16745. const currentCharacter = pseudoJson[i];
  16746. if (currentCharacter === '"') {
  16747. const escaped = isEscaped(pseudoJson, i);
  16748. if (!escaped) {
  16749. insideString = !insideString;
  16750. }
  16751. }
  16752. if (insideString) {
  16753. danglingCommaPos = null;
  16754. continue;
  16755. }
  16756. if (currentCharacter === ",") {
  16757. danglingCommaPos = i;
  16758. continue;
  16759. }
  16760. if (danglingCommaPos) {
  16761. if (currentCharacter === "}" || currentCharacter === "]") {
  16762. result += pseudoJson.slice(offset, danglingCommaPos) + " ";
  16763. offset = danglingCommaPos + 1;
  16764. danglingCommaPos = null;
  16765. } else if (!currentCharacter.match(/\s/)) {
  16766. danglingCommaPos = null;
  16767. }
  16768. }
  16769. }
  16770. return result + pseudoJson.substring(offset);
  16771. }
  16772. function isEscaped(jsonString, quotePosition) {
  16773. let index = quotePosition - 1;
  16774. let backslashCount = 0;
  16775. while (jsonString[index] === "\\") {
  16776. index -= 1;
  16777. backslashCount += 1;
  16778. }
  16779. return Boolean(backslashCount % 2);
  16780. }
  16781. function strip(string, start, end) {
  16782. return string.slice(start, end).replace(/\S/g, " ");
  16783. }
  16784. var singleComment = Symbol("singleComment");
  16785. var multiComment = Symbol("multiComment");
  16786. function stripJsonComments(jsonString) {
  16787. let isInsideString = false;
  16788. let isInsideComment = false;
  16789. let offset = 0;
  16790. let result = "";
  16791. for (let index = 0; index < jsonString.length; index++) {
  16792. const currentCharacter = jsonString[index];
  16793. const nextCharacter = jsonString[index + 1];
  16794. if (!isInsideComment && currentCharacter === '"') {
  16795. const escaped = isEscaped(jsonString, index);
  16796. if (!escaped) {
  16797. isInsideString = !isInsideString;
  16798. }
  16799. }
  16800. if (isInsideString) {
  16801. continue;
  16802. }
  16803. if (!isInsideComment && currentCharacter + nextCharacter === "//") {
  16804. result += jsonString.slice(offset, index);
  16805. offset = index;
  16806. isInsideComment = singleComment;
  16807. index++;
  16808. } else if (isInsideComment === singleComment && currentCharacter + nextCharacter === "\r\n") {
  16809. index++;
  16810. isInsideComment = false;
  16811. result += strip(jsonString, offset, index);
  16812. offset = index;
  16813. } else if (isInsideComment === singleComment && currentCharacter === "\n") {
  16814. isInsideComment = false;
  16815. result += strip(jsonString, offset, index);
  16816. offset = index;
  16817. } else if (!isInsideComment && currentCharacter + nextCharacter === "/*") {
  16818. result += jsonString.slice(offset, index);
  16819. offset = index;
  16820. isInsideComment = multiComment;
  16821. index++;
  16822. } else if (isInsideComment === multiComment && currentCharacter + nextCharacter === "*/") {
  16823. index++;
  16824. isInsideComment = false;
  16825. result += strip(jsonString, offset, index + 1);
  16826. offset = index + 1;
  16827. }
  16828. }
  16829. return result + (isInsideComment ? strip(jsonString.slice(offset)) : jsonString.slice(offset));
  16830. }
  16831. function stripBom(string) {
  16832. if (string.charCodeAt(0) === 65279) {
  16833. return string.slice(1);
  16834. }
  16835. return string;
  16836. }
  16837. var POSIX_SEP_RE = new RegExp("\\" + path__default.posix.sep, "g");
  16838. var NATIVE_SEP_RE = new RegExp("\\" + path__default.sep, "g");
  16839. var PATTERN_REGEX_CACHE = /* @__PURE__ */ new Map();
  16840. var GLOB_ALL_PATTERN = `**/*`;
  16841. var DEFAULT_EXTENSIONS = [".ts", ".tsx", ".mts", ".cts"];
  16842. var DEFAULT_EXTENSIONS_RE_GROUP = `\\.(?:${DEFAULT_EXTENSIONS.map((ext) => ext.substring(1)).join("|")})`;
  16843. new Function("path", "return import(path).then(m => m.default)");
  16844. async function resolveTSConfig(filename) {
  16845. if (path__default.extname(filename) !== ".json") {
  16846. return;
  16847. }
  16848. const tsconfig = path__default.resolve(filename);
  16849. try {
  16850. const stat = await fs$n.promises.stat(tsconfig);
  16851. if (stat.isFile() || stat.isFIFO()) {
  16852. return tsconfig;
  16853. }
  16854. } catch (e) {
  16855. if (e.code !== "ENOENT") {
  16856. throw e;
  16857. }
  16858. }
  16859. throw new Error(`no tsconfig file found for ${filename}`);
  16860. }
  16861. function posix2native(filename) {
  16862. return path__default.posix.sep !== path__default.sep && filename.includes(path__default.posix.sep) ? filename.replace(POSIX_SEP_RE, path__default.sep) : filename;
  16863. }
  16864. function native2posix(filename) {
  16865. return path__default.posix.sep !== path__default.sep && filename.includes(path__default.sep) ? filename.replace(NATIVE_SEP_RE, path__default.posix.sep) : filename;
  16866. }
  16867. function resolve2posix(dir, filename) {
  16868. if (path__default.sep === path__default.posix.sep) {
  16869. return dir ? path__default.resolve(dir, filename) : path__default.resolve(filename);
  16870. }
  16871. return native2posix(dir ? path__default.resolve(posix2native(dir), posix2native(filename)) : path__default.resolve(posix2native(filename)));
  16872. }
  16873. function resolveReferencedTSConfigFiles(result) {
  16874. const dir = path__default.dirname(result.tsconfigFile);
  16875. return result.tsconfig.references.map((ref) => {
  16876. const refPath = ref.path.endsWith(".json") ? ref.path : path__default.join(ref.path, "tsconfig.json");
  16877. return resolve2posix(dir, refPath);
  16878. });
  16879. }
  16880. function resolveSolutionTSConfig(filename, result) {
  16881. if (result.referenced && DEFAULT_EXTENSIONS.some((ext) => filename.endsWith(ext)) && !isIncluded(filename, result)) {
  16882. const solutionTSConfig = result.referenced.find((referenced) => isIncluded(filename, referenced));
  16883. if (solutionTSConfig) {
  16884. return __spreadProps(__spreadValues({}, solutionTSConfig), {
  16885. solution: result
  16886. });
  16887. }
  16888. }
  16889. return result;
  16890. }
  16891. function isIncluded(filename, result) {
  16892. const dir = native2posix(path__default.dirname(result.tsconfigFile));
  16893. const files = (result.tsconfig.files || []).map((file) => resolve2posix(dir, file));
  16894. const absoluteFilename = resolve2posix(null, filename);
  16895. if (files.includes(filename)) {
  16896. return true;
  16897. }
  16898. const isIncluded2 = isGlobMatch(absoluteFilename, dir, result.tsconfig.include || (result.tsconfig.files ? [] : [GLOB_ALL_PATTERN]));
  16899. if (isIncluded2) {
  16900. const isExcluded = isGlobMatch(absoluteFilename, dir, result.tsconfig.exclude || []);
  16901. return !isExcluded;
  16902. }
  16903. return false;
  16904. }
  16905. function isGlobMatch(filename, dir, patterns) {
  16906. return patterns.some((pattern) => {
  16907. let lastWildcardIndex = pattern.length;
  16908. let hasWildcard = false;
  16909. for (let i = pattern.length - 1; i > -1; i--) {
  16910. if (pattern[i] === "*" || pattern[i] === "?") {
  16911. lastWildcardIndex = i;
  16912. hasWildcard = true;
  16913. break;
  16914. }
  16915. }
  16916. if (lastWildcardIndex < pattern.length - 1 && !filename.endsWith(pattern.slice(lastWildcardIndex + 1))) {
  16917. return false;
  16918. }
  16919. if (pattern.endsWith("*") && !DEFAULT_EXTENSIONS.some((ext) => filename.endsWith(ext))) {
  16920. return false;
  16921. }
  16922. if (pattern === GLOB_ALL_PATTERN) {
  16923. return filename.startsWith(`${dir}/`);
  16924. }
  16925. const resolvedPattern = resolve2posix(dir, pattern);
  16926. let firstWildcardIndex = -1;
  16927. for (let i = 0; i < resolvedPattern.length; i++) {
  16928. if (resolvedPattern[i] === "*" || resolvedPattern[i] === "?") {
  16929. firstWildcardIndex = i;
  16930. hasWildcard = true;
  16931. break;
  16932. }
  16933. }
  16934. if (firstWildcardIndex > 1 && !filename.startsWith(resolvedPattern.slice(0, firstWildcardIndex - 1))) {
  16935. return false;
  16936. }
  16937. if (!hasWildcard) {
  16938. return filename === resolvedPattern;
  16939. }
  16940. if (PATTERN_REGEX_CACHE.has(resolvedPattern)) {
  16941. return PATTERN_REGEX_CACHE.get(resolvedPattern).test(filename);
  16942. }
  16943. const regex = pattern2regex(resolvedPattern);
  16944. PATTERN_REGEX_CACHE.set(resolvedPattern, regex);
  16945. return regex.test(filename);
  16946. });
  16947. }
  16948. function pattern2regex(resolvedPattern) {
  16949. let regexStr = "^";
  16950. for (let i = 0; i < resolvedPattern.length; i++) {
  16951. const char = resolvedPattern[i];
  16952. if (char === "?") {
  16953. regexStr += "[^\\/]";
  16954. continue;
  16955. }
  16956. if (char === "*") {
  16957. if (resolvedPattern[i + 1] === "*" && resolvedPattern[i + 2] === "/") {
  16958. i += 2;
  16959. regexStr += "(?:[^\\/]*\\/)*";
  16960. continue;
  16961. }
  16962. regexStr += "[^\\/]*";
  16963. continue;
  16964. }
  16965. if ("/.+^${}()|[]\\".includes(char)) {
  16966. regexStr += `\\`;
  16967. }
  16968. regexStr += char;
  16969. }
  16970. if (resolvedPattern.endsWith("*")) {
  16971. regexStr += DEFAULT_EXTENSIONS_RE_GROUP;
  16972. }
  16973. regexStr += "$";
  16974. return new RegExp(regexStr);
  16975. }
  16976. // src/parse.ts
  16977. async function parse$f(filename, options) {
  16978. const cache = options == null ? void 0 : options.cache;
  16979. if (cache == null ? void 0 : cache.has(filename)) {
  16980. return cache.get(filename);
  16981. }
  16982. let tsconfigFile;
  16983. if (options == null ? void 0 : options.resolveWithEmptyIfConfigNotFound) {
  16984. try {
  16985. tsconfigFile = await resolveTSConfig(filename) || await find(filename, options);
  16986. } catch (e) {
  16987. const notFoundResult = {
  16988. tsconfigFile: "no_tsconfig_file_found",
  16989. tsconfig: {}
  16990. };
  16991. cache == null ? void 0 : cache.set(filename, notFoundResult);
  16992. return notFoundResult;
  16993. }
  16994. } else {
  16995. tsconfigFile = await resolveTSConfig(filename) || await find(filename, options);
  16996. }
  16997. let result;
  16998. if (cache == null ? void 0 : cache.has(tsconfigFile)) {
  16999. result = cache.get(tsconfigFile);
  17000. } else {
  17001. result = await parseFile$1(tsconfigFile, cache);
  17002. await Promise.all([parseExtends(result, cache), parseReferences(result, cache)]);
  17003. cache == null ? void 0 : cache.set(tsconfigFile, result);
  17004. }
  17005. result = resolveSolutionTSConfig(filename, result);
  17006. cache == null ? void 0 : cache.set(filename, result);
  17007. return result;
  17008. }
  17009. async function parseFile$1(tsconfigFile, cache) {
  17010. if (cache == null ? void 0 : cache.has(tsconfigFile)) {
  17011. return cache.get(tsconfigFile);
  17012. }
  17013. try {
  17014. const tsconfigJson = await fs$n.promises.readFile(tsconfigFile, "utf-8");
  17015. const json = toJson(tsconfigJson);
  17016. const result = {
  17017. tsconfigFile,
  17018. tsconfig: normalizeTSConfig(JSON.parse(json), path__default.dirname(tsconfigFile))
  17019. };
  17020. cache == null ? void 0 : cache.set(tsconfigFile, result);
  17021. return result;
  17022. } catch (e) {
  17023. throw new TSConfckParseError(`parsing ${tsconfigFile} failed: ${e}`, "PARSE_FILE", tsconfigFile, e);
  17024. }
  17025. }
  17026. function normalizeTSConfig(tsconfig, dir) {
  17027. var _a;
  17028. if (((_a = tsconfig.compilerOptions) == null ? void 0 : _a.baseUrl) && !path__default.isAbsolute(tsconfig.compilerOptions.baseUrl)) {
  17029. tsconfig.compilerOptions.baseUrl = resolve2posix(dir, tsconfig.compilerOptions.baseUrl);
  17030. }
  17031. return tsconfig;
  17032. }
  17033. async function parseReferences(result, cache) {
  17034. if (!result.tsconfig.references) {
  17035. return;
  17036. }
  17037. const referencedFiles = resolveReferencedTSConfigFiles(result);
  17038. const referenced = await Promise.all(referencedFiles.map((file) => parseFile$1(file, cache)));
  17039. await Promise.all(referenced.map((ref) => parseExtends(ref, cache)));
  17040. result.referenced = referenced;
  17041. }
  17042. async function parseExtends(result, cache) {
  17043. if (!result.tsconfig.extends) {
  17044. return;
  17045. }
  17046. const extended = [
  17047. { tsconfigFile: result.tsconfigFile, tsconfig: JSON.parse(JSON.stringify(result.tsconfig)) }
  17048. ];
  17049. while (extended[extended.length - 1].tsconfig.extends) {
  17050. const extending = extended[extended.length - 1];
  17051. const extendedTSConfigFile = resolveExtends(extending.tsconfig.extends, extending.tsconfigFile);
  17052. if (extended.some((x) => x.tsconfigFile === extendedTSConfigFile)) {
  17053. const circle = extended.concat({ tsconfigFile: extendedTSConfigFile, tsconfig: null }).map((e) => e.tsconfigFile).join(" -> ");
  17054. throw new TSConfckParseError(`Circular dependency in "extends": ${circle}`, "EXTENDS_CIRCULAR", result.tsconfigFile);
  17055. }
  17056. extended.push(await parseFile$1(extendedTSConfigFile, cache));
  17057. }
  17058. result.extended = extended;
  17059. for (const ext of result.extended.slice(1)) {
  17060. extendTSConfig(result, ext);
  17061. }
  17062. }
  17063. function resolveExtends(extended, from) {
  17064. let error;
  17065. try {
  17066. return require$$0$7.createRequire(from).resolve(extended);
  17067. } catch (e) {
  17068. error = e;
  17069. }
  17070. if (!path__default.isAbsolute(extended) && !extended.startsWith("./") && !extended.startsWith("../")) {
  17071. try {
  17072. const fallbackExtended = path__default.join(extended, "tsconfig.json");
  17073. return require$$0$7.createRequire(from).resolve(fallbackExtended);
  17074. } catch (e) {
  17075. error = e;
  17076. }
  17077. }
  17078. throw new TSConfckParseError(`failed to resolve "extends":"${extended}" in ${from}`, "EXTENDS_RESOLVE", from, error);
  17079. }
  17080. var EXTENDABLE_KEYS = [
  17081. "compilerOptions",
  17082. "files",
  17083. "include",
  17084. "exclude",
  17085. "watchOptions",
  17086. "compileOnSave",
  17087. "typeAcquisition",
  17088. "buildOptions"
  17089. ];
  17090. function extendTSConfig(extending, extended) {
  17091. const extendingConfig = extending.tsconfig;
  17092. const extendedConfig = extended.tsconfig;
  17093. const relativePath = native2posix(path__default.relative(path__default.dirname(extending.tsconfigFile), path__default.dirname(extended.tsconfigFile)));
  17094. for (const key of Object.keys(extendedConfig).filter((key2) => EXTENDABLE_KEYS.includes(key2))) {
  17095. if (key === "compilerOptions") {
  17096. if (!extendingConfig.compilerOptions) {
  17097. extendingConfig.compilerOptions = {};
  17098. }
  17099. for (const option of Object.keys(extendedConfig.compilerOptions)) {
  17100. if (Object.prototype.hasOwnProperty.call(extendingConfig.compilerOptions, option)) {
  17101. continue;
  17102. }
  17103. extendingConfig.compilerOptions[option] = rebaseRelative(option, extendedConfig.compilerOptions[option], relativePath);
  17104. }
  17105. } else if (extendingConfig[key] === void 0) {
  17106. if (key === "watchOptions") {
  17107. extendingConfig.watchOptions = {};
  17108. for (const option of Object.keys(extendedConfig.watchOptions)) {
  17109. extendingConfig.watchOptions[option] = rebaseRelative(option, extendedConfig.watchOptions[option], relativePath);
  17110. }
  17111. } else {
  17112. extendingConfig[key] = rebaseRelative(key, extendedConfig[key], relativePath);
  17113. }
  17114. }
  17115. }
  17116. }
  17117. var REBASE_KEYS = [
  17118. "files",
  17119. "include",
  17120. "exclude",
  17121. "baseUrl",
  17122. "rootDir",
  17123. "rootDirs",
  17124. "typeRoots",
  17125. "outDir",
  17126. "outFile",
  17127. "declarationDir",
  17128. "excludeDirectories",
  17129. "excludeFiles"
  17130. ];
  17131. function rebaseRelative(key, value, prependPath) {
  17132. if (!REBASE_KEYS.includes(key)) {
  17133. return value;
  17134. }
  17135. if (Array.isArray(value)) {
  17136. return value.map((x) => rebasePath(x, prependPath));
  17137. } else {
  17138. return rebasePath(value, prependPath);
  17139. }
  17140. }
  17141. function rebasePath(value, prependPath) {
  17142. if (path__default.isAbsolute(value)) {
  17143. return value;
  17144. } else {
  17145. return path__default.posix.normalize(path__default.posix.join(prependPath, value));
  17146. }
  17147. }
  17148. var TSConfckParseError = class extends Error {
  17149. constructor(message, code, tsconfigFile, cause) {
  17150. super(message);
  17151. Object.setPrototypeOf(this, TSConfckParseError.prototype);
  17152. this.name = TSConfckParseError.name;
  17153. this.code = code;
  17154. this.cause = cause;
  17155. this.tsconfigFile = tsconfigFile;
  17156. }
  17157. };
  17158. const debug$f = createDebugger('vite:esbuild');
  17159. const INJECT_HELPERS_IIFE_RE = /(.*)(var [^\s]+=function\([^)]*?\){"use strict";)(.*)/;
  17160. const INJECT_HELPERS_UMD_RE = /(.*)(\(function\([^)]*?\){.+amd.+function\([^)]*?\){"use strict";)(.*)/;
  17161. let server;
  17162. async function transformWithEsbuild(code, filename, options, inMap) {
  17163. var _a;
  17164. let loader = options === null || options === void 0 ? void 0 : options.loader;
  17165. if (!loader) {
  17166. // if the id ends with a valid ext, use it (e.g. vue blocks)
  17167. // otherwise, cleanup the query before checking the ext
  17168. const ext = path__default
  17169. .extname(/\.\w+$/.test(filename) ? filename : cleanUrl(filename))
  17170. .slice(1);
  17171. if (ext === 'cjs' || ext === 'mjs') {
  17172. loader = 'js';
  17173. }
  17174. else {
  17175. loader = ext;
  17176. }
  17177. }
  17178. let tsconfigRaw = options === null || options === void 0 ? void 0 : options.tsconfigRaw;
  17179. // if options provide tsconfigraw in string, it takes highest precedence
  17180. if (typeof tsconfigRaw !== 'string') {
  17181. // these fields would affect the compilation result
  17182. // https://esbuild.github.io/content-types/#tsconfig-json
  17183. const meaningfulFields = [
  17184. 'target',
  17185. 'jsxFactory',
  17186. 'jsxFragmentFactory',
  17187. 'useDefineForClassFields',
  17188. 'importsNotUsedAsValues',
  17189. 'preserveValueImports'
  17190. ];
  17191. const compilerOptionsForFile = {};
  17192. if (loader === 'ts' || loader === 'tsx') {
  17193. const loadedTsconfig = await loadTsconfigJsonForFile(filename);
  17194. const loadedCompilerOptions = (_a = loadedTsconfig.compilerOptions) !== null && _a !== void 0 ? _a : {};
  17195. for (const field of meaningfulFields) {
  17196. if (field in loadedCompilerOptions) {
  17197. // @ts-ignore TypeScript can't tell they are of the same type
  17198. compilerOptionsForFile[field] = loadedCompilerOptions[field];
  17199. }
  17200. }
  17201. }
  17202. tsconfigRaw = {
  17203. ...tsconfigRaw,
  17204. compilerOptions: {
  17205. ...compilerOptionsForFile,
  17206. ...tsconfigRaw === null || tsconfigRaw === void 0 ? void 0 : tsconfigRaw.compilerOptions
  17207. }
  17208. };
  17209. }
  17210. const resolvedOptions = {
  17211. sourcemap: true,
  17212. // ensure source file name contains full query
  17213. sourcefile: filename,
  17214. ...options,
  17215. loader,
  17216. tsconfigRaw
  17217. };
  17218. delete resolvedOptions.include;
  17219. delete resolvedOptions.exclude;
  17220. delete resolvedOptions.jsxInject;
  17221. try {
  17222. const result = await esbuild.transform(code, resolvedOptions);
  17223. let map;
  17224. if (inMap && resolvedOptions.sourcemap) {
  17225. const nextMap = JSON.parse(result.map);
  17226. nextMap.sourcesContent = [];
  17227. map = combineSourcemaps(filename, [
  17228. nextMap,
  17229. inMap
  17230. ]);
  17231. }
  17232. else {
  17233. map = resolvedOptions.sourcemap
  17234. ? JSON.parse(result.map)
  17235. : { mappings: '' };
  17236. }
  17237. if (Array.isArray(map.sources)) {
  17238. map.sources = map.sources.map((it) => toUpperCaseDriveLetter(it));
  17239. }
  17240. return {
  17241. ...result,
  17242. map
  17243. };
  17244. }
  17245. catch (e) {
  17246. debug$f(`esbuild error with options used: `, resolvedOptions);
  17247. // patch error information
  17248. if (e.errors) {
  17249. e.frame = '';
  17250. e.errors.forEach((m) => {
  17251. e.frame += `\n` + prettifyMessage(m, code);
  17252. });
  17253. e.loc = e.errors[0].location;
  17254. }
  17255. throw e;
  17256. }
  17257. }
  17258. function esbuildPlugin(options = {}) {
  17259. const filter = createFilter$1(options.include || /\.(tsx?|jsx)$/, options.exclude || /\.js$/);
  17260. return {
  17261. name: 'vite:esbuild',
  17262. configureServer(_server) {
  17263. server = _server;
  17264. server.watcher
  17265. .on('add', reloadOnTsconfigChange)
  17266. .on('change', reloadOnTsconfigChange)
  17267. .on('unlink', reloadOnTsconfigChange);
  17268. },
  17269. async configResolved(config) {
  17270. await initTSConfck(config);
  17271. },
  17272. buildEnd() {
  17273. // recycle serve to avoid preventing Node self-exit (#6815)
  17274. server = null;
  17275. },
  17276. async transform(code, id) {
  17277. if (filter(id) || filter(cleanUrl(id))) {
  17278. const result = await transformWithEsbuild(code, id, options);
  17279. if (result.warnings.length) {
  17280. result.warnings.forEach((m) => {
  17281. this.warn(prettifyMessage(m, code));
  17282. });
  17283. }
  17284. if (options.jsxInject && /\.(?:j|t)sx\b/.test(id)) {
  17285. result.code = options.jsxInject + ';' + result.code;
  17286. }
  17287. return {
  17288. code: result.code,
  17289. map: result.map
  17290. };
  17291. }
  17292. }
  17293. };
  17294. }
  17295. const rollupToEsbuildFormatMap = {
  17296. es: 'esm',
  17297. cjs: 'cjs',
  17298. // passing `var Lib = (() => {})()` to esbuild with format = "iife"
  17299. // will turn it to `(() => { var Lib = (() => {})() })()`,
  17300. // so we remove the format config to tell esbuild not doing this
  17301. //
  17302. // although esbuild doesn't change format, there is still possibility
  17303. // that `{ treeShaking: true }` removes a top-level no-side-effect variable
  17304. // like: `var Lib = 1`, which becomes `` after esbuild transforming,
  17305. // but thankfully rollup does not do this optimization now
  17306. iife: undefined
  17307. };
  17308. const buildEsbuildPlugin = (config) => {
  17309. return {
  17310. name: 'vite:esbuild-transpile',
  17311. async configResolved(config) {
  17312. await initTSConfck(config);
  17313. },
  17314. async renderChunk(code, chunk, opts) {
  17315. // @ts-ignore injected by @vitejs/plugin-legacy
  17316. if (opts.__vite_skip_esbuild__) {
  17317. return null;
  17318. }
  17319. const target = config.build.target;
  17320. const minify = config.build.minify === 'esbuild' &&
  17321. // Do not minify ES lib output since that would remove pure annotations
  17322. // and break tree-shaking
  17323. // https://github.com/vuejs/core/issues/2860#issuecomment-926882793
  17324. !(config.build.lib && opts.format === 'es');
  17325. if ((!target || target === 'esnext') && !minify) {
  17326. return null;
  17327. }
  17328. const res = await transformWithEsbuild(code, chunk.fileName, {
  17329. ...config.esbuild,
  17330. target: target || undefined,
  17331. ...(minify
  17332. ? {
  17333. minify,
  17334. treeShaking: true,
  17335. format: rollupToEsbuildFormatMap[opts.format]
  17336. }
  17337. : undefined)
  17338. });
  17339. if (config.build.lib) {
  17340. // #7188, esbuild adds helpers out of the UMD and IIFE wrappers, and the
  17341. // names are minified potentially causing collision with other globals.
  17342. // We use a regex to inject the helpers inside the wrappers.
  17343. // We don't need to create a MagicString here because both the helpers and
  17344. // the headers don't modify the sourcemap
  17345. const injectHelpers = opts.format === 'umd'
  17346. ? INJECT_HELPERS_UMD_RE
  17347. : opts.format === 'iife'
  17348. ? INJECT_HELPERS_IIFE_RE
  17349. : undefined;
  17350. if (injectHelpers) {
  17351. res.code = res.code.replace(injectHelpers, (_, helpers, header, rest) => header + helpers + rest);
  17352. }
  17353. }
  17354. return res;
  17355. }
  17356. };
  17357. };
  17358. function prettifyMessage(m, code) {
  17359. let res = colors$1.yellow(m.text);
  17360. if (m.location) {
  17361. const lines = code.split(/\r?\n/g);
  17362. const line = Number(m.location.line);
  17363. const column = Number(m.location.column);
  17364. const offset = lines
  17365. .slice(0, line - 1)
  17366. .map((l) => l.length)
  17367. .reduce((total, l) => total + l + 1, 0) + column;
  17368. res += `\n` + generateCodeFrame(code, offset, offset + 1);
  17369. }
  17370. return res + `\n`;
  17371. }
  17372. const tsconfckParseOptions = {
  17373. cache: new Map(),
  17374. tsConfigPaths: undefined,
  17375. root: undefined,
  17376. resolveWithEmptyIfConfigNotFound: true
  17377. };
  17378. async function initTSConfck(config) {
  17379. tsconfckParseOptions.cache.clear();
  17380. const workspaceRoot = searchForWorkspaceRoot(config.root);
  17381. tsconfckParseOptions.root = workspaceRoot;
  17382. tsconfckParseOptions.tsConfigPaths = new Set([
  17383. ...(await findAll(workspaceRoot, {
  17384. skip: (dir) => dir === 'node_modules' || dir === '.git'
  17385. }))
  17386. ]);
  17387. }
  17388. async function loadTsconfigJsonForFile(filename) {
  17389. try {
  17390. const result = await parse$f(filename, tsconfckParseOptions);
  17391. // tsconfig could be out of root, make sure it is watched on dev
  17392. if (server && result.tsconfigFile !== 'no_tsconfig_file_found') {
  17393. ensureWatchedFile(server.watcher, result.tsconfigFile, server.config.root);
  17394. }
  17395. return result.tsconfig;
  17396. }
  17397. catch (e) {
  17398. if (e instanceof TSConfckParseError) {
  17399. // tsconfig could be out of root, make sure it is watched on dev
  17400. if (server && e.tsconfigFile) {
  17401. ensureWatchedFile(server.watcher, e.tsconfigFile, server.config.root);
  17402. }
  17403. }
  17404. throw e;
  17405. }
  17406. }
  17407. function reloadOnTsconfigChange(changedFile) {
  17408. var _a;
  17409. // any tsconfig.json that's added in the workspace could be closer to a code file than a previously cached one
  17410. // any json file in the tsconfig cache could have been used to compile ts
  17411. if (path__default.basename(changedFile) === 'tsconfig.json' ||
  17412. (changedFile.endsWith('.json') &&
  17413. ((_a = tsconfckParseOptions === null || tsconfckParseOptions === void 0 ? void 0 : tsconfckParseOptions.cache) === null || _a === void 0 ? void 0 : _a.has(changedFile)))) {
  17414. server.config.logger.info(`changed tsconfig file detected: ${changedFile} - Clearing cache and forcing full-reload to ensure typescript is compiled with updated config values.`, { clear: server.config.clearScreen, timestamp: true });
  17415. // clear module graph to remove code compiled with outdated config
  17416. server.moduleGraph.invalidateAll();
  17417. // reset tsconfck so that recompile works with up2date configs
  17418. initTSConfck(server.config).finally(() => {
  17419. // force full reload
  17420. server.ws.send({
  17421. type: 'full-reload',
  17422. path: '*'
  17423. });
  17424. });
  17425. }
  17426. }
  17427. var dist$2 = {};
  17428. var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
  17429. return (mod && mod.__esModule) ? mod : { "default": mod };
  17430. };
  17431. Object.defineProperty(dist$2, "__esModule", { value: true });
  17432. var Worker_1 = dist$2.Worker = void 0;
  17433. const os_1 = __importDefault(require$$2__default);
  17434. const worker_threads_1 = require$$1__default;
  17435. class Worker {
  17436. constructor(fn, options = {}) {
  17437. this.code = genWorkerCode(fn);
  17438. this.max = options.max || Math.max(1, os_1.default.cpus().length - 1);
  17439. this.pool = [];
  17440. this.idlePool = [];
  17441. this.queue = [];
  17442. }
  17443. async run(...args) {
  17444. const worker = await this._getAvailableWorker();
  17445. return new Promise((resolve, reject) => {
  17446. worker.currentResolve = resolve;
  17447. worker.currentReject = reject;
  17448. worker.postMessage(args);
  17449. });
  17450. }
  17451. stop() {
  17452. this.pool.forEach((w) => w.unref());
  17453. this.queue.forEach(([_, reject]) => reject(new Error('Main worker pool stopped before a worker was available.')));
  17454. this.pool = [];
  17455. this.idlePool = [];
  17456. this.queue = [];
  17457. }
  17458. async _getAvailableWorker() {
  17459. // has idle one?
  17460. if (this.idlePool.length) {
  17461. return this.idlePool.shift();
  17462. }
  17463. // can spawn more?
  17464. if (this.pool.length < this.max) {
  17465. const worker = new worker_threads_1.Worker(this.code, { eval: true });
  17466. worker.on('message', (res) => {
  17467. worker.currentResolve && worker.currentResolve(res);
  17468. worker.currentResolve = null;
  17469. this._assignDoneWorker(worker);
  17470. });
  17471. worker.on('error', (err) => {
  17472. worker.currentReject && worker.currentReject(err);
  17473. worker.currentReject = null;
  17474. });
  17475. worker.on('exit', (code) => {
  17476. const i = this.pool.indexOf(worker);
  17477. if (i > -1)
  17478. this.pool.splice(i, 1);
  17479. if (code !== 0 && worker.currentReject) {
  17480. worker.currentReject(new Error(`Wroker stopped with non-0 exit code ${code}`));
  17481. worker.currentReject = null;
  17482. }
  17483. });
  17484. this.pool.push(worker);
  17485. return worker;
  17486. }
  17487. // no one is available, we have to wait
  17488. let resolve;
  17489. let reject;
  17490. const onWorkerAvailablePromise = new Promise((r, rj) => {
  17491. resolve = r;
  17492. reject = rj;
  17493. });
  17494. this.queue.push([resolve, reject]);
  17495. return onWorkerAvailablePromise;
  17496. }
  17497. _assignDoneWorker(worker) {
  17498. // someone's waiting already?
  17499. if (this.queue.length) {
  17500. const [resolve] = this.queue.shift();
  17501. resolve(worker);
  17502. return;
  17503. }
  17504. // take a rest.
  17505. this.idlePool.push(worker);
  17506. }
  17507. }
  17508. Worker_1 = dist$2.Worker = Worker;
  17509. function genWorkerCode(fn) {
  17510. return `
  17511. const doWork = ${fn.toString()}
  17512. const { parentPort } = require('worker_threads')
  17513. parentPort.on('message', async (args) => {
  17514. const res = await doWork(...args)
  17515. parentPort.postMessage(res)
  17516. })
  17517. `;
  17518. }
  17519. function terserPlugin(config) {
  17520. const makeWorker = () => new Worker_1((basedir, code, options) => {
  17521. // when vite is linked, the worker thread won't share the same resolve
  17522. // root with vite itself, so we have to pass in the basedir and resolve
  17523. // terser first.
  17524. // eslint-disable-next-line node/no-restricted-require
  17525. const terserPath = require.resolve('vite/dist/node/terser', {
  17526. paths: [basedir]
  17527. });
  17528. return require(terserPath).minify(code, options);
  17529. });
  17530. let worker;
  17531. return {
  17532. name: 'vite:terser',
  17533. async renderChunk(code, _chunk, outputOptions) {
  17534. // This plugin is included for any non-false value of config.build.minify,
  17535. // so that normal chunks can use the preferred minifier, and legacy chunks
  17536. // can use terser.
  17537. if (config.build.minify !== 'terser' &&
  17538. // @ts-ignore injected by @vitejs/plugin-legacy
  17539. !outputOptions.__vite_force_terser__) {
  17540. return null;
  17541. }
  17542. // Do not minify ES lib output since that would remove pure annotations
  17543. // and break tree-shaking.
  17544. if (config.build.lib && outputOptions.format === 'es') {
  17545. return null;
  17546. }
  17547. // Lazy load worker.
  17548. worker || (worker = makeWorker());
  17549. const res = await worker.run(__dirname, code, {
  17550. safari10: true,
  17551. ...config.build.terserOptions,
  17552. sourceMap: !!outputOptions.sourcemap,
  17553. module: outputOptions.format.startsWith('es'),
  17554. toplevel: outputOptions.format === 'cjs'
  17555. });
  17556. return {
  17557. code: res.code,
  17558. map: res.map
  17559. };
  17560. },
  17561. closeBundle() {
  17562. worker === null || worker === void 0 ? void 0 : worker.stop();
  17563. }
  17564. };
  17565. }
  17566. function manifestPlugin(config) {
  17567. const manifest = {};
  17568. let outputCount;
  17569. return {
  17570. name: 'vite:manifest',
  17571. buildStart() {
  17572. outputCount = 0;
  17573. },
  17574. generateBundle({ format }, bundle) {
  17575. var _a;
  17576. function getChunkName(chunk) {
  17577. if (chunk.facadeModuleId) {
  17578. let name = normalizePath$3(path__default.relative(config.root, chunk.facadeModuleId));
  17579. if (format === 'system' && !chunk.name.includes('-legacy')) {
  17580. const ext = path__default.extname(name);
  17581. name = name.slice(0, -ext.length) + `-legacy` + ext;
  17582. }
  17583. return name.replace(/\0/g, '');
  17584. }
  17585. else {
  17586. return `_` + path__default.basename(chunk.fileName);
  17587. }
  17588. }
  17589. function getInternalImports(imports) {
  17590. const filteredImports = [];
  17591. for (const file of imports) {
  17592. if (bundle[file] === undefined) {
  17593. continue;
  17594. }
  17595. filteredImports.push(getChunkName(bundle[file]));
  17596. }
  17597. return filteredImports;
  17598. }
  17599. function createChunk(chunk) {
  17600. const manifestChunk = {
  17601. file: chunk.fileName
  17602. };
  17603. if (chunk.facadeModuleId) {
  17604. manifestChunk.src = getChunkName(chunk);
  17605. }
  17606. if (chunk.isEntry) {
  17607. manifestChunk.isEntry = true;
  17608. }
  17609. if (chunk.isDynamicEntry) {
  17610. manifestChunk.isDynamicEntry = true;
  17611. }
  17612. if (chunk.imports.length) {
  17613. const internalImports = getInternalImports(chunk.imports);
  17614. if (internalImports.length > 0) {
  17615. manifestChunk.imports = internalImports;
  17616. }
  17617. }
  17618. if (chunk.dynamicImports.length) {
  17619. const internalImports = getInternalImports(chunk.dynamicImports);
  17620. if (internalImports.length > 0) {
  17621. manifestChunk.dynamicImports = internalImports;
  17622. }
  17623. }
  17624. if (chunk.viteMetadata.importedCss.size) {
  17625. manifestChunk.css = [...chunk.viteMetadata.importedCss];
  17626. }
  17627. if (chunk.viteMetadata.importedAssets.size) {
  17628. manifestChunk.assets = [...chunk.viteMetadata.importedAssets];
  17629. }
  17630. return manifestChunk;
  17631. }
  17632. for (const file in bundle) {
  17633. const chunk = bundle[file];
  17634. if (chunk.type === 'chunk') {
  17635. manifest[getChunkName(chunk)] = createChunk(chunk);
  17636. }
  17637. }
  17638. outputCount++;
  17639. const output = (_a = config.build.rollupOptions) === null || _a === void 0 ? void 0 : _a.output;
  17640. const outputLength = Array.isArray(output) ? output.length : 1;
  17641. if (outputCount >= outputLength) {
  17642. this.emitFile({
  17643. fileName: typeof config.build.manifest === 'string'
  17644. ? config.build.manifest
  17645. : 'manifest.json',
  17646. type: 'asset',
  17647. source: JSON.stringify(manifest, null, 2)
  17648. });
  17649. }
  17650. }
  17651. };
  17652. }
  17653. // This is based on @rollup/plugin-data-uri
  17654. const dataUriRE = /^([^/]+\/[^;,]+)(;base64)?,([\s\S]*)$/;
  17655. const dataUriPrefix = `/@data-uri/`;
  17656. /**
  17657. * Build only, since importing from a data URI works natively.
  17658. */
  17659. function dataURIPlugin() {
  17660. let resolved;
  17661. return {
  17662. name: 'vite:data-uri',
  17663. buildStart() {
  17664. resolved = {};
  17665. },
  17666. resolveId(id) {
  17667. if (!dataUriRE.test(id)) {
  17668. return null;
  17669. }
  17670. const uri = new require$$0$6.URL(id);
  17671. if (uri.protocol !== 'data:') {
  17672. return null;
  17673. }
  17674. const match = uri.pathname.match(dataUriRE);
  17675. if (!match) {
  17676. return null;
  17677. }
  17678. const [, mime, format, data] = match;
  17679. if (mime !== 'text/javascript') {
  17680. throw new Error(`data URI with non-JavaScript mime type is not supported.`);
  17681. }
  17682. // decode data
  17683. const base64 = format && /base64/i.test(format.substring(1));
  17684. const content = base64
  17685. ? Buffer.from(data, 'base64').toString('utf-8')
  17686. : data;
  17687. resolved[id] = content;
  17688. return dataUriPrefix + id;
  17689. },
  17690. load(id) {
  17691. if (id.startsWith(dataUriPrefix)) {
  17692. id = id.slice(dataUriPrefix.length);
  17693. return resolved[id] || null;
  17694. }
  17695. }
  17696. };
  17697. }
  17698. class BitSet {
  17699. constructor(arg) {
  17700. this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
  17701. }
  17702. add(n) {
  17703. this.bits[n >> 5] |= 1 << (n & 31);
  17704. }
  17705. has(n) {
  17706. return !!(this.bits[n >> 5] & (1 << (n & 31)));
  17707. }
  17708. }
  17709. class Chunk {
  17710. constructor(start, end, content) {
  17711. this.start = start;
  17712. this.end = end;
  17713. this.original = content;
  17714. this.intro = '';
  17715. this.outro = '';
  17716. this.content = content;
  17717. this.storeName = false;
  17718. this.edited = false;
  17719. // we make these non-enumerable, for sanity while debugging
  17720. Object.defineProperties(this, {
  17721. previous: { writable: true, value: null },
  17722. next: { writable: true, value: null },
  17723. });
  17724. }
  17725. appendLeft(content) {
  17726. this.outro += content;
  17727. }
  17728. appendRight(content) {
  17729. this.intro = this.intro + content;
  17730. }
  17731. clone() {
  17732. const chunk = new Chunk(this.start, this.end, this.original);
  17733. chunk.intro = this.intro;
  17734. chunk.outro = this.outro;
  17735. chunk.content = this.content;
  17736. chunk.storeName = this.storeName;
  17737. chunk.edited = this.edited;
  17738. return chunk;
  17739. }
  17740. contains(index) {
  17741. return this.start < index && index < this.end;
  17742. }
  17743. eachNext(fn) {
  17744. let chunk = this;
  17745. while (chunk) {
  17746. fn(chunk);
  17747. chunk = chunk.next;
  17748. }
  17749. }
  17750. eachPrevious(fn) {
  17751. let chunk = this;
  17752. while (chunk) {
  17753. fn(chunk);
  17754. chunk = chunk.previous;
  17755. }
  17756. }
  17757. edit(content, storeName, contentOnly) {
  17758. this.content = content;
  17759. if (!contentOnly) {
  17760. this.intro = '';
  17761. this.outro = '';
  17762. }
  17763. this.storeName = storeName;
  17764. this.edited = true;
  17765. return this;
  17766. }
  17767. prependLeft(content) {
  17768. this.outro = content + this.outro;
  17769. }
  17770. prependRight(content) {
  17771. this.intro = content + this.intro;
  17772. }
  17773. split(index) {
  17774. const sliceIndex = index - this.start;
  17775. const originalBefore = this.original.slice(0, sliceIndex);
  17776. const originalAfter = this.original.slice(sliceIndex);
  17777. this.original = originalBefore;
  17778. const newChunk = new Chunk(index, this.end, originalAfter);
  17779. newChunk.outro = this.outro;
  17780. this.outro = '';
  17781. this.end = index;
  17782. if (this.edited) {
  17783. // TODO is this block necessary?...
  17784. newChunk.edit('', false);
  17785. this.content = '';
  17786. } else {
  17787. this.content = originalBefore;
  17788. }
  17789. newChunk.next = this.next;
  17790. if (newChunk.next) newChunk.next.previous = newChunk;
  17791. newChunk.previous = this;
  17792. this.next = newChunk;
  17793. return newChunk;
  17794. }
  17795. toString() {
  17796. return this.intro + this.content + this.outro;
  17797. }
  17798. trimEnd(rx) {
  17799. this.outro = this.outro.replace(rx, '');
  17800. if (this.outro.length) return true;
  17801. const trimmed = this.content.replace(rx, '');
  17802. if (trimmed.length) {
  17803. if (trimmed !== this.content) {
  17804. this.split(this.start + trimmed.length).edit('', undefined, true);
  17805. }
  17806. return true;
  17807. } else {
  17808. this.edit('', undefined, true);
  17809. this.intro = this.intro.replace(rx, '');
  17810. if (this.intro.length) return true;
  17811. }
  17812. }
  17813. trimStart(rx) {
  17814. this.intro = this.intro.replace(rx, '');
  17815. if (this.intro.length) return true;
  17816. const trimmed = this.content.replace(rx, '');
  17817. if (trimmed.length) {
  17818. if (trimmed !== this.content) {
  17819. this.split(this.end - trimmed.length);
  17820. this.edit('', undefined, true);
  17821. }
  17822. return true;
  17823. } else {
  17824. this.edit('', undefined, true);
  17825. this.outro = this.outro.replace(rx, '');
  17826. if (this.outro.length) return true;
  17827. }
  17828. }
  17829. }
  17830. let btoa$1 = () => {
  17831. throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
  17832. };
  17833. if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
  17834. btoa$1 = (str) => window.btoa(unescape(encodeURIComponent(str)));
  17835. } else if (typeof Buffer === 'function') {
  17836. btoa$1 = (str) => Buffer.from(str, 'utf-8').toString('base64');
  17837. }
  17838. class SourceMap {
  17839. constructor(properties) {
  17840. this.version = 3;
  17841. this.file = properties.file;
  17842. this.sources = properties.sources;
  17843. this.sourcesContent = properties.sourcesContent;
  17844. this.names = properties.names;
  17845. this.mappings = encode$1(properties.mappings);
  17846. }
  17847. toString() {
  17848. return JSON.stringify(this);
  17849. }
  17850. toUrl() {
  17851. return 'data:application/json;charset=utf-8;base64,' + btoa$1(this.toString());
  17852. }
  17853. }
  17854. function guessIndent(code) {
  17855. const lines = code.split('\n');
  17856. const tabbed = lines.filter((line) => /^\t+/.test(line));
  17857. const spaced = lines.filter((line) => /^ {2,}/.test(line));
  17858. if (tabbed.length === 0 && spaced.length === 0) {
  17859. return null;
  17860. }
  17861. // More lines tabbed than spaced? Assume tabs, and
  17862. // default to tabs in the case of a tie (or nothing
  17863. // to go on)
  17864. if (tabbed.length >= spaced.length) {
  17865. return '\t';
  17866. }
  17867. // Otherwise, we need to guess the multiple
  17868. const min = spaced.reduce((previous, current) => {
  17869. const numSpaces = /^ +/.exec(current)[0].length;
  17870. return Math.min(numSpaces, previous);
  17871. }, Infinity);
  17872. return new Array(min + 1).join(' ');
  17873. }
  17874. function getRelativePath(from, to) {
  17875. const fromParts = from.split(/[/\\]/);
  17876. const toParts = to.split(/[/\\]/);
  17877. fromParts.pop(); // get dirname
  17878. while (fromParts[0] === toParts[0]) {
  17879. fromParts.shift();
  17880. toParts.shift();
  17881. }
  17882. if (fromParts.length) {
  17883. let i = fromParts.length;
  17884. while (i--) fromParts[i] = '..';
  17885. }
  17886. return fromParts.concat(toParts).join('/');
  17887. }
  17888. const toString$2 = Object.prototype.toString;
  17889. function isObject(thing) {
  17890. return toString$2.call(thing) === '[object Object]';
  17891. }
  17892. function getLocator(source) {
  17893. const originalLines = source.split('\n');
  17894. const lineOffsets = [];
  17895. for (let i = 0, pos = 0; i < originalLines.length; i++) {
  17896. lineOffsets.push(pos);
  17897. pos += originalLines[i].length + 1;
  17898. }
  17899. return function locate(index) {
  17900. let i = 0;
  17901. let j = lineOffsets.length;
  17902. while (i < j) {
  17903. const m = (i + j) >> 1;
  17904. if (index < lineOffsets[m]) {
  17905. j = m;
  17906. } else {
  17907. i = m + 1;
  17908. }
  17909. }
  17910. const line = i - 1;
  17911. const column = index - lineOffsets[line];
  17912. return { line, column };
  17913. };
  17914. }
  17915. class Mappings {
  17916. constructor(hires) {
  17917. this.hires = hires;
  17918. this.generatedCodeLine = 0;
  17919. this.generatedCodeColumn = 0;
  17920. this.raw = [];
  17921. this.rawSegments = this.raw[this.generatedCodeLine] = [];
  17922. this.pending = null;
  17923. }
  17924. addEdit(sourceIndex, content, loc, nameIndex) {
  17925. if (content.length) {
  17926. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  17927. if (nameIndex >= 0) {
  17928. segment.push(nameIndex);
  17929. }
  17930. this.rawSegments.push(segment);
  17931. } else if (this.pending) {
  17932. this.rawSegments.push(this.pending);
  17933. }
  17934. this.advance(content);
  17935. this.pending = null;
  17936. }
  17937. addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
  17938. let originalCharIndex = chunk.start;
  17939. let first = true;
  17940. while (originalCharIndex < chunk.end) {
  17941. if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
  17942. this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]);
  17943. }
  17944. if (original[originalCharIndex] === '\n') {
  17945. loc.line += 1;
  17946. loc.column = 0;
  17947. this.generatedCodeLine += 1;
  17948. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  17949. this.generatedCodeColumn = 0;
  17950. first = true;
  17951. } else {
  17952. loc.column += 1;
  17953. this.generatedCodeColumn += 1;
  17954. first = false;
  17955. }
  17956. originalCharIndex += 1;
  17957. }
  17958. this.pending = null;
  17959. }
  17960. advance(str) {
  17961. if (!str) return;
  17962. const lines = str.split('\n');
  17963. if (lines.length > 1) {
  17964. for (let i = 0; i < lines.length - 1; i++) {
  17965. this.generatedCodeLine++;
  17966. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  17967. }
  17968. this.generatedCodeColumn = 0;
  17969. }
  17970. this.generatedCodeColumn += lines[lines.length - 1].length;
  17971. }
  17972. }
  17973. const n = '\n';
  17974. const warned$1 = {
  17975. insertLeft: false,
  17976. insertRight: false,
  17977. storeName: false,
  17978. };
  17979. class MagicString {
  17980. constructor(string, options = {}) {
  17981. const chunk = new Chunk(0, string.length, string);
  17982. Object.defineProperties(this, {
  17983. original: { writable: true, value: string },
  17984. outro: { writable: true, value: '' },
  17985. intro: { writable: true, value: '' },
  17986. firstChunk: { writable: true, value: chunk },
  17987. lastChunk: { writable: true, value: chunk },
  17988. lastSearchedChunk: { writable: true, value: chunk },
  17989. byStart: { writable: true, value: {} },
  17990. byEnd: { writable: true, value: {} },
  17991. filename: { writable: true, value: options.filename },
  17992. indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
  17993. sourcemapLocations: { writable: true, value: new BitSet() },
  17994. storedNames: { writable: true, value: {} },
  17995. indentStr: { writable: true, value: guessIndent(string) },
  17996. });
  17997. this.byStart[0] = chunk;
  17998. this.byEnd[string.length] = chunk;
  17999. }
  18000. addSourcemapLocation(char) {
  18001. this.sourcemapLocations.add(char);
  18002. }
  18003. append(content) {
  18004. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  18005. this.outro += content;
  18006. return this;
  18007. }
  18008. appendLeft(index, content) {
  18009. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  18010. this._split(index);
  18011. const chunk = this.byEnd[index];
  18012. if (chunk) {
  18013. chunk.appendLeft(content);
  18014. } else {
  18015. this.intro += content;
  18016. }
  18017. return this;
  18018. }
  18019. appendRight(index, content) {
  18020. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  18021. this._split(index);
  18022. const chunk = this.byStart[index];
  18023. if (chunk) {
  18024. chunk.appendRight(content);
  18025. } else {
  18026. this.outro += content;
  18027. }
  18028. return this;
  18029. }
  18030. clone() {
  18031. const cloned = new MagicString(this.original, { filename: this.filename });
  18032. let originalChunk = this.firstChunk;
  18033. let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
  18034. while (originalChunk) {
  18035. cloned.byStart[clonedChunk.start] = clonedChunk;
  18036. cloned.byEnd[clonedChunk.end] = clonedChunk;
  18037. const nextOriginalChunk = originalChunk.next;
  18038. const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
  18039. if (nextClonedChunk) {
  18040. clonedChunk.next = nextClonedChunk;
  18041. nextClonedChunk.previous = clonedChunk;
  18042. clonedChunk = nextClonedChunk;
  18043. }
  18044. originalChunk = nextOriginalChunk;
  18045. }
  18046. cloned.lastChunk = clonedChunk;
  18047. if (this.indentExclusionRanges) {
  18048. cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
  18049. }
  18050. cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
  18051. cloned.intro = this.intro;
  18052. cloned.outro = this.outro;
  18053. return cloned;
  18054. }
  18055. generateDecodedMap(options) {
  18056. options = options || {};
  18057. const sourceIndex = 0;
  18058. const names = Object.keys(this.storedNames);
  18059. const mappings = new Mappings(options.hires);
  18060. const locate = getLocator(this.original);
  18061. if (this.intro) {
  18062. mappings.advance(this.intro);
  18063. }
  18064. this.firstChunk.eachNext((chunk) => {
  18065. const loc = locate(chunk.start);
  18066. if (chunk.intro.length) mappings.advance(chunk.intro);
  18067. if (chunk.edited) {
  18068. mappings.addEdit(
  18069. sourceIndex,
  18070. chunk.content,
  18071. loc,
  18072. chunk.storeName ? names.indexOf(chunk.original) : -1
  18073. );
  18074. } else {
  18075. mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
  18076. }
  18077. if (chunk.outro.length) mappings.advance(chunk.outro);
  18078. });
  18079. return {
  18080. file: options.file ? options.file.split(/[/\\]/).pop() : null,
  18081. sources: [options.source ? getRelativePath(options.file || '', options.source) : null],
  18082. sourcesContent: options.includeContent ? [this.original] : [null],
  18083. names,
  18084. mappings: mappings.raw,
  18085. };
  18086. }
  18087. generateMap(options) {
  18088. return new SourceMap(this.generateDecodedMap(options));
  18089. }
  18090. getIndentString() {
  18091. return this.indentStr === null ? '\t' : this.indentStr;
  18092. }
  18093. indent(indentStr, options) {
  18094. const pattern = /^[^\r\n]/gm;
  18095. if (isObject(indentStr)) {
  18096. options = indentStr;
  18097. indentStr = undefined;
  18098. }
  18099. indentStr = indentStr !== undefined ? indentStr : this.indentStr || '\t';
  18100. if (indentStr === '') return this; // noop
  18101. options = options || {};
  18102. // Process exclusion ranges
  18103. const isExcluded = {};
  18104. if (options.exclude) {
  18105. const exclusions =
  18106. typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
  18107. exclusions.forEach((exclusion) => {
  18108. for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
  18109. isExcluded[i] = true;
  18110. }
  18111. });
  18112. }
  18113. let shouldIndentNextCharacter = options.indentStart !== false;
  18114. const replacer = (match) => {
  18115. if (shouldIndentNextCharacter) return `${indentStr}${match}`;
  18116. shouldIndentNextCharacter = true;
  18117. return match;
  18118. };
  18119. this.intro = this.intro.replace(pattern, replacer);
  18120. let charIndex = 0;
  18121. let chunk = this.firstChunk;
  18122. while (chunk) {
  18123. const end = chunk.end;
  18124. if (chunk.edited) {
  18125. if (!isExcluded[charIndex]) {
  18126. chunk.content = chunk.content.replace(pattern, replacer);
  18127. if (chunk.content.length) {
  18128. shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
  18129. }
  18130. }
  18131. } else {
  18132. charIndex = chunk.start;
  18133. while (charIndex < end) {
  18134. if (!isExcluded[charIndex]) {
  18135. const char = this.original[charIndex];
  18136. if (char === '\n') {
  18137. shouldIndentNextCharacter = true;
  18138. } else if (char !== '\r' && shouldIndentNextCharacter) {
  18139. shouldIndentNextCharacter = false;
  18140. if (charIndex === chunk.start) {
  18141. chunk.prependRight(indentStr);
  18142. } else {
  18143. this._splitChunk(chunk, charIndex);
  18144. chunk = chunk.next;
  18145. chunk.prependRight(indentStr);
  18146. }
  18147. }
  18148. }
  18149. charIndex += 1;
  18150. }
  18151. }
  18152. charIndex = chunk.end;
  18153. chunk = chunk.next;
  18154. }
  18155. this.outro = this.outro.replace(pattern, replacer);
  18156. return this;
  18157. }
  18158. insert() {
  18159. throw new Error(
  18160. 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)'
  18161. );
  18162. }
  18163. insertLeft(index, content) {
  18164. if (!warned$1.insertLeft) {
  18165. console.warn(
  18166. 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead'
  18167. ); // eslint-disable-line no-console
  18168. warned$1.insertLeft = true;
  18169. }
  18170. return this.appendLeft(index, content);
  18171. }
  18172. insertRight(index, content) {
  18173. if (!warned$1.insertRight) {
  18174. console.warn(
  18175. 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead'
  18176. ); // eslint-disable-line no-console
  18177. warned$1.insertRight = true;
  18178. }
  18179. return this.prependRight(index, content);
  18180. }
  18181. move(start, end, index) {
  18182. if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself');
  18183. this._split(start);
  18184. this._split(end);
  18185. this._split(index);
  18186. const first = this.byStart[start];
  18187. const last = this.byEnd[end];
  18188. const oldLeft = first.previous;
  18189. const oldRight = last.next;
  18190. const newRight = this.byStart[index];
  18191. if (!newRight && last === this.lastChunk) return this;
  18192. const newLeft = newRight ? newRight.previous : this.lastChunk;
  18193. if (oldLeft) oldLeft.next = oldRight;
  18194. if (oldRight) oldRight.previous = oldLeft;
  18195. if (newLeft) newLeft.next = first;
  18196. if (newRight) newRight.previous = last;
  18197. if (!first.previous) this.firstChunk = last.next;
  18198. if (!last.next) {
  18199. this.lastChunk = first.previous;
  18200. this.lastChunk.next = null;
  18201. }
  18202. first.previous = newLeft;
  18203. last.next = newRight || null;
  18204. if (!newLeft) this.firstChunk = first;
  18205. if (!newRight) this.lastChunk = last;
  18206. return this;
  18207. }
  18208. overwrite(start, end, content, options) {
  18209. if (typeof content !== 'string') throw new TypeError('replacement content must be a string');
  18210. while (start < 0) start += this.original.length;
  18211. while (end < 0) end += this.original.length;
  18212. if (end > this.original.length) throw new Error('end is out of bounds');
  18213. if (start === end)
  18214. throw new Error(
  18215. 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead'
  18216. );
  18217. this._split(start);
  18218. this._split(end);
  18219. if (options === true) {
  18220. if (!warned$1.storeName) {
  18221. console.warn(
  18222. 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string'
  18223. ); // eslint-disable-line no-console
  18224. warned$1.storeName = true;
  18225. }
  18226. options = { storeName: true };
  18227. }
  18228. const storeName = options !== undefined ? options.storeName : false;
  18229. const contentOnly = options !== undefined ? options.contentOnly : false;
  18230. if (storeName) {
  18231. const original = this.original.slice(start, end);
  18232. Object.defineProperty(this.storedNames, original, {
  18233. writable: true,
  18234. value: true,
  18235. enumerable: true,
  18236. });
  18237. }
  18238. const first = this.byStart[start];
  18239. const last = this.byEnd[end];
  18240. if (first) {
  18241. let chunk = first;
  18242. while (chunk !== last) {
  18243. if (chunk.next !== this.byStart[chunk.end]) {
  18244. throw new Error('Cannot overwrite across a split point');
  18245. }
  18246. chunk = chunk.next;
  18247. chunk.edit('', false);
  18248. }
  18249. first.edit(content, storeName, contentOnly);
  18250. } else {
  18251. // must be inserting at the end
  18252. const newChunk = new Chunk(start, end, '').edit(content, storeName);
  18253. // TODO last chunk in the array may not be the last chunk, if it's moved...
  18254. last.next = newChunk;
  18255. newChunk.previous = last;
  18256. }
  18257. return this;
  18258. }
  18259. prepend(content) {
  18260. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  18261. this.intro = content + this.intro;
  18262. return this;
  18263. }
  18264. prependLeft(index, content) {
  18265. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  18266. this._split(index);
  18267. const chunk = this.byEnd[index];
  18268. if (chunk) {
  18269. chunk.prependLeft(content);
  18270. } else {
  18271. this.intro = content + this.intro;
  18272. }
  18273. return this;
  18274. }
  18275. prependRight(index, content) {
  18276. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  18277. this._split(index);
  18278. const chunk = this.byStart[index];
  18279. if (chunk) {
  18280. chunk.prependRight(content);
  18281. } else {
  18282. this.outro = content + this.outro;
  18283. }
  18284. return this;
  18285. }
  18286. remove(start, end) {
  18287. while (start < 0) start += this.original.length;
  18288. while (end < 0) end += this.original.length;
  18289. if (start === end) return this;
  18290. if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
  18291. if (start > end) throw new Error('end must be greater than start');
  18292. this._split(start);
  18293. this._split(end);
  18294. let chunk = this.byStart[start];
  18295. while (chunk) {
  18296. chunk.intro = '';
  18297. chunk.outro = '';
  18298. chunk.edit('');
  18299. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  18300. }
  18301. return this;
  18302. }
  18303. lastChar() {
  18304. if (this.outro.length) return this.outro[this.outro.length - 1];
  18305. let chunk = this.lastChunk;
  18306. do {
  18307. if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
  18308. if (chunk.content.length) return chunk.content[chunk.content.length - 1];
  18309. if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
  18310. } while ((chunk = chunk.previous));
  18311. if (this.intro.length) return this.intro[this.intro.length - 1];
  18312. return '';
  18313. }
  18314. lastLine() {
  18315. let lineIndex = this.outro.lastIndexOf(n);
  18316. if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
  18317. let lineStr = this.outro;
  18318. let chunk = this.lastChunk;
  18319. do {
  18320. if (chunk.outro.length > 0) {
  18321. lineIndex = chunk.outro.lastIndexOf(n);
  18322. if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
  18323. lineStr = chunk.outro + lineStr;
  18324. }
  18325. if (chunk.content.length > 0) {
  18326. lineIndex = chunk.content.lastIndexOf(n);
  18327. if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
  18328. lineStr = chunk.content + lineStr;
  18329. }
  18330. if (chunk.intro.length > 0) {
  18331. lineIndex = chunk.intro.lastIndexOf(n);
  18332. if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
  18333. lineStr = chunk.intro + lineStr;
  18334. }
  18335. } while ((chunk = chunk.previous));
  18336. lineIndex = this.intro.lastIndexOf(n);
  18337. if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
  18338. return this.intro + lineStr;
  18339. }
  18340. slice(start = 0, end = this.original.length) {
  18341. while (start < 0) start += this.original.length;
  18342. while (end < 0) end += this.original.length;
  18343. let result = '';
  18344. // find start chunk
  18345. let chunk = this.firstChunk;
  18346. while (chunk && (chunk.start > start || chunk.end <= start)) {
  18347. // found end chunk before start
  18348. if (chunk.start < end && chunk.end >= end) {
  18349. return result;
  18350. }
  18351. chunk = chunk.next;
  18352. }
  18353. if (chunk && chunk.edited && chunk.start !== start)
  18354. throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
  18355. const startChunk = chunk;
  18356. while (chunk) {
  18357. if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
  18358. result += chunk.intro;
  18359. }
  18360. const containsEnd = chunk.start < end && chunk.end >= end;
  18361. if (containsEnd && chunk.edited && chunk.end !== end)
  18362. throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
  18363. const sliceStart = startChunk === chunk ? start - chunk.start : 0;
  18364. const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
  18365. result += chunk.content.slice(sliceStart, sliceEnd);
  18366. if (chunk.outro && (!containsEnd || chunk.end === end)) {
  18367. result += chunk.outro;
  18368. }
  18369. if (containsEnd) {
  18370. break;
  18371. }
  18372. chunk = chunk.next;
  18373. }
  18374. return result;
  18375. }
  18376. // TODO deprecate this? not really very useful
  18377. snip(start, end) {
  18378. const clone = this.clone();
  18379. clone.remove(0, start);
  18380. clone.remove(end, clone.original.length);
  18381. return clone;
  18382. }
  18383. _split(index) {
  18384. if (this.byStart[index] || this.byEnd[index]) return;
  18385. let chunk = this.lastSearchedChunk;
  18386. const searchForward = index > chunk.end;
  18387. while (chunk) {
  18388. if (chunk.contains(index)) return this._splitChunk(chunk, index);
  18389. chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
  18390. }
  18391. }
  18392. _splitChunk(chunk, index) {
  18393. if (chunk.edited && chunk.content.length) {
  18394. // zero-length edited chunks are a special case (overlapping replacements)
  18395. const loc = getLocator(this.original)(index);
  18396. throw new Error(
  18397. `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`
  18398. );
  18399. }
  18400. const newChunk = chunk.split(index);
  18401. this.byEnd[index] = chunk;
  18402. this.byStart[index] = newChunk;
  18403. this.byEnd[newChunk.end] = newChunk;
  18404. if (chunk === this.lastChunk) this.lastChunk = newChunk;
  18405. this.lastSearchedChunk = chunk;
  18406. return true;
  18407. }
  18408. toString() {
  18409. let str = this.intro;
  18410. let chunk = this.firstChunk;
  18411. while (chunk) {
  18412. str += chunk.toString();
  18413. chunk = chunk.next;
  18414. }
  18415. return str + this.outro;
  18416. }
  18417. isEmpty() {
  18418. let chunk = this.firstChunk;
  18419. do {
  18420. if (
  18421. (chunk.intro.length && chunk.intro.trim()) ||
  18422. (chunk.content.length && chunk.content.trim()) ||
  18423. (chunk.outro.length && chunk.outro.trim())
  18424. )
  18425. return false;
  18426. } while ((chunk = chunk.next));
  18427. return true;
  18428. }
  18429. length() {
  18430. let chunk = this.firstChunk;
  18431. let length = 0;
  18432. do {
  18433. length += chunk.intro.length + chunk.content.length + chunk.outro.length;
  18434. } while ((chunk = chunk.next));
  18435. return length;
  18436. }
  18437. trimLines() {
  18438. return this.trim('[\\r\\n]');
  18439. }
  18440. trim(charType) {
  18441. return this.trimStart(charType).trimEnd(charType);
  18442. }
  18443. trimEndAborted(charType) {
  18444. const rx = new RegExp((charType || '\\s') + '+$');
  18445. this.outro = this.outro.replace(rx, '');
  18446. if (this.outro.length) return true;
  18447. let chunk = this.lastChunk;
  18448. do {
  18449. const end = chunk.end;
  18450. const aborted = chunk.trimEnd(rx);
  18451. // if chunk was trimmed, we have a new lastChunk
  18452. if (chunk.end !== end) {
  18453. if (this.lastChunk === chunk) {
  18454. this.lastChunk = chunk.next;
  18455. }
  18456. this.byEnd[chunk.end] = chunk;
  18457. this.byStart[chunk.next.start] = chunk.next;
  18458. this.byEnd[chunk.next.end] = chunk.next;
  18459. }
  18460. if (aborted) return true;
  18461. chunk = chunk.previous;
  18462. } while (chunk);
  18463. return false;
  18464. }
  18465. trimEnd(charType) {
  18466. this.trimEndAborted(charType);
  18467. return this;
  18468. }
  18469. trimStartAborted(charType) {
  18470. const rx = new RegExp('^' + (charType || '\\s') + '+');
  18471. this.intro = this.intro.replace(rx, '');
  18472. if (this.intro.length) return true;
  18473. let chunk = this.firstChunk;
  18474. do {
  18475. const end = chunk.end;
  18476. const aborted = chunk.trimStart(rx);
  18477. if (chunk.end !== end) {
  18478. // special case...
  18479. if (chunk === this.lastChunk) this.lastChunk = chunk.next;
  18480. this.byEnd[chunk.end] = chunk;
  18481. this.byStart[chunk.next.start] = chunk.next;
  18482. this.byEnd[chunk.next.end] = chunk.next;
  18483. }
  18484. if (aborted) return true;
  18485. chunk = chunk.next;
  18486. } while (chunk);
  18487. return false;
  18488. }
  18489. trimStart(charType) {
  18490. this.trimStartAborted(charType);
  18491. return this;
  18492. }
  18493. hasChanged() {
  18494. return this.original !== this.toString();
  18495. }
  18496. replace(searchValue, replacement) {
  18497. function getReplacement(match, str) {
  18498. if (typeof replacement === 'string') {
  18499. return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
  18500. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
  18501. if (i === '$') return '$';
  18502. if (i === '&') return match[0];
  18503. const num = +i;
  18504. if (num < match.length) return match[+i];
  18505. return `$${i}`;
  18506. });
  18507. } else {
  18508. return replacement(...match, match.index, str, match.groups);
  18509. }
  18510. }
  18511. function matchAll(re, str) {
  18512. let match;
  18513. const matches = [];
  18514. while ((match = re.exec(str))) {
  18515. matches.push(match);
  18516. }
  18517. return matches;
  18518. }
  18519. if (typeof searchValue !== 'string' && searchValue.global) {
  18520. const matches = matchAll(searchValue, this.original);
  18521. matches.forEach((match) => {
  18522. if (match.index != null)
  18523. this.overwrite(
  18524. match.index,
  18525. match.index + match[0].length,
  18526. getReplacement(match, this.original)
  18527. );
  18528. });
  18529. } else {
  18530. const match = this.original.match(searchValue);
  18531. if (match && match.index != null)
  18532. this.overwrite(
  18533. match.index,
  18534. match.index + match[0].length,
  18535. getReplacement(match, this.original)
  18536. );
  18537. }
  18538. return this;
  18539. }
  18540. }
  18541. /* es-module-lexer 0.10.5 */
  18542. const A=1===new Uint8Array(new Uint16Array([1]).buffer)[0];function parse$e(E,g="@"){if(!C)return init.then((()=>parse$e(E)));const I=E.length+1,o=(C.__heap_base.value||C.__heap_base)+4*I-C.memory.buffer.byteLength;o>0&&C.memory.grow(Math.ceil(o/65536));const k=C.sa(I-1);if((A?B:Q)(E,new Uint16Array(C.memory.buffer,k,I)),!C.parse())throw Object.assign(new Error(`Parse error ${g}:${E.slice(0,C.e()).split("\n").length}:${C.e()-E.lastIndexOf("\n",C.e()-1)}`),{idx:C.e()});const J=[],i=[];for(;C.ri();){const A=C.is(),Q=C.ie(),B=C.ai(),g=C.id(),I=C.ss(),o=C.se();let k;C.ip()&&(k=w(E.slice(-1===g?A-1:A,-1===g?Q+1:Q))),J.push({n:k,s:A,e:Q,ss:I,se:o,d:g,a:B});}for(;C.re();){const A=E.slice(C.es(),C.ee()),Q=A[0];i.push('"'===Q||"'"===Q?w(A):A);}function w(A){try{return (0, eval)(A)}catch(A){}}return [J,i,!!C.f()]}function Q(A,Q){const B=A.length;let C=0;for(;C<B;){const B=A.charCodeAt(C);Q[C++]=(255&B)<<8|B>>>8;}}function B(A,Q){const B=A.length;let C=0;for(;C<B;)Q[C]=A.charCodeAt(C++);}let C;const init=WebAssembly.compile((E="AGFzbQEAAAABKghgAX8Bf2AEf39/fwBgAn9/AGAAAX9gAABgAX8AYAN/f38Bf2ACf38BfwMqKQABAgMDAwMDAwMDAwMDAwMAAAQEBAUEBQAAAAAEBAAGBwACAAAABwMGBAUBcAEBAQUDAQABBg8CfwFBkPIAC38AQZDyAAsHZBEGbWVtb3J5AgACc2EAAAFlAAMCaXMABAJpZQAFAnNzAAYCc2UABwJhaQAIAmlkAAkCaXAACgJlcwALAmVlAAwCcmkADQJyZQAOAWYADwVwYXJzZQAQC19faGVhcF9iYXNlAwEKhjQpaAEBf0EAIAA2AtQJQQAoArAJIgEgAEEBdGoiAEEAOwEAQQAgAEECaiIANgLYCUEAIAA2AtwJQQBBADYCtAlBAEEANgLECUEAQQA2ArwJQQBBADYCuAlBAEEANgLMCUEAQQA2AsAJIAELnwEBA39BACgCxAkhBEEAQQAoAtwJIgU2AsQJQQAgBDYCyAlBACAFQSBqNgLcCSAEQRxqQbQJIAQbIAU2AgBBACgCqAkhBEEAKAKkCSEGIAUgATYCACAFIAA2AgggBSACIAJBAmpBACAGIANGGyAEIANGGzYCDCAFIAM2AhQgBUEANgIQIAUgAjYCBCAFQQA2AhwgBUEAKAKkCSADRjoAGAtIAQF/QQAoAswJIgJBCGpBuAkgAhtBACgC3AkiAjYCAEEAIAI2AswJQQAgAkEMajYC3AkgAkEANgIIIAIgATYCBCACIAA2AgALCABBACgC4AkLFQBBACgCvAkoAgBBACgCsAlrQQF1Cx4BAX9BACgCvAkoAgQiAEEAKAKwCWtBAXVBfyAAGwsVAEEAKAK8CSgCCEEAKAKwCWtBAXULHgEBf0EAKAK8CSgCDCIAQQAoArAJa0EBdUF/IAAbCx4BAX9BACgCvAkoAhAiAEEAKAKwCWtBAXVBfyAAGws7AQF/AkBBACgCvAkoAhQiAEEAKAKkCUcNAEF/DwsCQCAAQQAoAqgJRw0AQX4PCyAAQQAoArAJa0EBdQsLAEEAKAK8CS0AGAsVAEEAKALACSgCAEEAKAKwCWtBAXULFQBBACgCwAkoAgRBACgCsAlrQQF1CyUBAX9BAEEAKAK8CSIAQRxqQbQJIAAbKAIAIgA2ArwJIABBAEcLJQEBf0EAQQAoAsAJIgBBCGpBuAkgABsoAgAiADYCwAkgAEEARwsIAEEALQDkCQvnCwEGfyMAQYDaAGsiASQAQQBBAToA5AlBAEH//wM7AewJQQBBACgCrAk2AvAJQQBBACgCsAlBfmoiAjYCiApBACACQQAoAtQJQQF0aiIDNgKMCkEAQQA7AeYJQQBBADsB6AlBAEEAOwHqCUEAQQA6APQJQQBBADYC4AlBAEEAOgDQCUEAIAFBgNIAajYC+AlBACABQYASajYC/AlBACABNgKACkEAQQA6AIQKAkACQAJAAkADQEEAIAJBAmoiBDYCiAogAiADTw0BAkAgBC8BACIDQXdqQQVJDQACQAJAAkACQAJAIANBm39qDgUBCAgIAgALIANBIEYNBCADQS9GDQMgA0E7Rg0CDAcLQQAvAeoJDQEgBBARRQ0BIAJBBGpBgghBChAoDQEQEkEALQDkCQ0BQQBBACgCiAoiAjYC8AkMBwsgBBARRQ0AIAJBBGpBjAhBChAoDQAQEwtBAEEAKAKICjYC8AkMAQsCQCACLwEEIgRBKkYNACAEQS9HDQQQFAwBC0EBEBULQQAoAowKIQNBACgCiAohAgwACwtBACEDIAQhAkEALQDQCQ0CDAELQQAgAjYCiApBAEEAOgDkCQsDQEEAIAJBAmoiBDYCiAoCQAJAAkACQAJAAkAgAkEAKAKMCk8NACAELwEAIgNBd2pBBUkNBQJAAkACQAJAAkACQAJAAkACQAJAIANBYGoOCg8OCA4ODg4HAQIACwJAAkACQAJAIANBoH9qDgoIEREDEQERERECAAsgA0GFf2oOAwUQBgsLQQAvAeoJDQ8gBBARRQ0PIAJBBGpBgghBChAoDQ8QEgwPCyAEEBFFDQ4gAkEEakGMCEEKECgNDhATDA4LIAQQEUUNDSACKQAEQuyAhIOwjsA5Ug0NIAIvAQwiBEF3aiICQRdLDQtBASACdEGfgIAEcUUNCwwMC0EAQQAvAeoJIgJBAWo7AeoJQQAoAvwJIAJBAnRqQQAoAvAJNgIADAwLQQAvAeoJIgNFDQhBACADQX9qIgU7AeoJQQAvAegJIgNFDQsgA0ECdEEAKAKACmpBfGooAgAiBigCFEEAKAL8CSAFQf//A3FBAnRqKAIARw0LAkAgBigCBA0AIAYgBDYCBAtBACADQX9qOwHoCSAGIAJBBGo2AgwMCwsCQEEAKALwCSIELwEAQSlHDQBBACgCxAkiAkUNACACKAIEIARHDQBBAEEAKALICSICNgLECQJAIAJFDQAgAkEANgIcDAELQQBBADYCtAkLIAFBgBBqQQAvAeoJIgJqQQAtAIQKOgAAQQAgAkEBajsB6glBACgC/AkgAkECdGogBDYCAEEAQQA6AIQKDAoLQQAvAeoJIgJFDQZBACACQX9qIgM7AeoJIAJBAC8B7AkiBEcNAUEAQQAvAeYJQX9qIgI7AeYJQQBBACgC+AkgAkH//wNxQQF0ai8BADsB7AkLEBYMCAsgBEH//wNGDQcgA0H//wNxIARJDQQMBwtBJxAXDAYLQSIQFwwFCyADQS9HDQQCQAJAIAIvAQQiAkEqRg0AIAJBL0cNARAUDAcLQQEQFQwGCwJAAkACQAJAQQAoAvAJIgQvAQAiAhAYRQ0AAkACQAJAIAJBVWoOBAEFAgAFCyAEQX5qLwEAQVBqQf//A3FBCkkNAwwECyAEQX5qLwEAQStGDQIMAwsgBEF+ai8BAEEtRg0BDAILAkAgAkH9AEYNACACQSlHDQFBACgC/AlBAC8B6glBAnRqKAIAEBlFDQEMAgtBACgC/AlBAC8B6gkiA0ECdGooAgAQGg0BIAFBgBBqIANqLQAADQELIAQQGw0AIAJFDQBBASEEIAJBL0ZBAC0A9AlBAEdxRQ0BCxAcQQAhBAtBACAEOgD0CQwEC0EALwHsCUH//wNGQQAvAeoJRXFBAC0A0AlFcUEALwHoCUVxIQMMBgsQHUEAIQMMBQsgBEGgAUcNAQtBAEEBOgCECgtBAEEAKAKICjYC8AkLQQAoAogKIQIMAAsLIAFBgNoAaiQAIAMLHQACQEEAKAKwCSAARw0AQQEPCyAAQX5qLwEAEB4LpgYBBH9BAEEAKAKICiIAQQxqIgE2AogKQQEQISECAkACQAJAAkACQEEAKAKICiIDIAFHDQAgAhAlRQ0BCwJAAkACQAJAAkAgAkGff2oODAYBAwgBBwEBAQEBBAALAkACQCACQSpGDQAgAkH2AEYNBSACQfsARw0CQQAgA0ECajYCiApBARAhIQNBACgCiAohAQNAAkACQCADQf//A3EiAkEiRg0AIAJBJ0YNACACECQaQQAoAogKIQIMAQsgAhAXQQBBACgCiApBAmoiAjYCiAoLQQEQIRoCQCABIAIQJiIDQSxHDQBBAEEAKAKICkECajYCiApBARAhIQMLQQAoAogKIQICQCADQf0ARg0AIAIgAUYNBSACIQEgAkEAKAKMCk0NAQwFCwtBACACQQJqNgKICgwBC0EAIANBAmo2AogKQQEQIRpBACgCiAoiAiACECYaC0EBECEhAgtBACgCiAohAwJAIAJB5gBHDQAgA0ECakGeCEEGECgNAEEAIANBCGo2AogKIABBARAhECIPC0EAIANBfmo2AogKDAMLEB0PCwJAIAMpAAJC7ICEg7COwDlSDQAgAy8BChAeRQ0AQQAgA0EKajYCiApBARAhIQJBACgCiAohAyACECQaIANBACgCiAoQAkEAQQAoAogKQX5qNgKICg8LQQAgA0EEaiIDNgKICgtBACADQQRqIgI2AogKQQBBADoA5AkDQEEAIAJBAmo2AogKQQEQISEDQQAoAogKIQICQCADECRBIHJB+wBHDQBBAEEAKAKICkF+ajYCiAoPC0EAKAKICiIDIAJGDQEgAiADEAICQEEBECEiAkEsRg0AAkAgAkE9Rw0AQQBBACgCiApBfmo2AogKDwtBAEEAKAKICkF+ajYCiAoPC0EAKAKICiECDAALCw8LQQAgA0EKajYCiApBARAhGkEAKAKICiEDC0EAIANBEGo2AogKAkBBARAhIgJBKkcNAEEAQQAoAogKQQJqNgKICkEBECEhAgtBACgCiAohAyACECQaIANBACgCiAoQAkEAQQAoAogKQX5qNgKICg8LIAMgA0EOahACC6sGAQR/QQBBACgCiAoiAEEMaiIBNgKICgJAAkACQAJAAkACQAJAAkACQAJAQQEQISICQVlqDggCCAECAQEBBwALIAJBIkYNASACQfsARg0CC0EAKAKICiABRg0HC0EALwHqCQ0BQQAoAogKIQJBACgCjAohAwNAIAIgA08NBAJAAkAgAi8BACIBQSdGDQAgAUEiRw0BCyAAIAEQIg8LQQAgAkECaiICNgKICgwACwtBACgCiAohAkEALwHqCQ0BAkADQAJAAkACQCACQQAoAowKTw0AQQEQISICQSJGDQEgAkEnRg0BIAJB/QBHDQJBAEEAKAKICkECajYCiAoLQQEQIRpBACgCiAoiAikAAELmgMiD8I3ANlINBkEAIAJBCGo2AogKQQEQISICQSJGDQMgAkEnRg0DDAYLIAIQFwtBAEEAKAKICkECaiICNgKICgwACwsgACACECIMBQtBAEEAKAKICkF+ajYCiAoPC0EAIAJBfmo2AogKDwsQHQ8LQQBBACgCiApBAmo2AogKQQEQIUHtAEcNAUEAKAKICiICQQJqQZYIQQYQKA0BQQAoAvAJLwEAQS5GDQEgACAAIAJBCGpBACgCqAkQAQ8LQQAoAvwJQQAvAeoJIgJBAnRqQQAoAogKNgIAQQAgAkEBajsB6glBACgC8AkvAQBBLkYNAEEAQQAoAogKIgFBAmo2AogKQQEQISECIABBACgCiApBACABEAFBAEEALwHoCSIBQQFqOwHoCUEAKAKACiABQQJ0akEAKALECTYCAAJAIAJBIkYNACACQSdGDQBBAEEAKAKICkF+ajYCiAoPCyACEBdBAEEAKAKICkECaiICNgKICgJAAkACQEEBECFBV2oOBAECAgACC0EAQQAoAogKQQJqNgKICkEBECEaQQAoAsQJIgEgAjYCBCABQQE6ABggAUEAKAKICiICNgIQQQAgAkF+ajYCiAoPC0EAKALECSIBIAI2AgQgAUEBOgAYQQBBAC8B6glBf2o7AeoJIAFBACgCiApBAmo2AgxBAEEALwHoCUF/ajsB6AkPC0EAQQAoAogKQX5qNgKICg8LC0cBA39BACgCiApBAmohAEEAKAKMCiEBAkADQCAAIgJBfmogAU8NASACQQJqIQAgAi8BAEF2ag4EAQAAAQALC0EAIAI2AogKC5gBAQN/QQBBACgCiAoiAUECajYCiAogAUEGaiEBQQAoAowKIQIDQAJAAkACQCABQXxqIAJPDQAgAUF+ai8BACEDAkACQCAADQAgA0EqRg0BIANBdmoOBAIEBAIECyADQSpHDQMLIAEvAQBBL0cNAkEAIAFBfmo2AogKDAELIAFBfmohAQtBACABNgKICg8LIAFBAmohAQwACwu/AQEEf0EAKAKICiEAQQAoAowKIQECQAJAA0AgACICQQJqIQAgAiABTw0BAkACQCAALwEAIgNBpH9qDgUBAgICBAALIANBJEcNASACLwEEQfsARw0BQQBBAC8B5gkiAEEBajsB5glBACgC+AkgAEEBdGpBAC8B7Ak7AQBBACACQQRqNgKICkEAQQAvAeoJQQFqIgA7AewJQQAgADsB6gkPCyACQQRqIQAMAAsLQQAgADYCiAoQHQ8LQQAgADYCiAoLiAEBBH9BACgCiAohAUEAKAKMCiECAkACQANAIAEiA0ECaiEBIAMgAk8NASABLwEAIgQgAEYNAgJAIARB3ABGDQAgBEF2ag4EAgEBAgELIANBBGohASADLwEEQQ1HDQAgA0EGaiABIAMvAQZBCkYbIQEMAAsLQQAgATYCiAoQHQ8LQQAgATYCiAoLbAEBfwJAAkAgAEFfaiIBQQVLDQBBASABdEExcQ0BCyAAQUZqQf//A3FBBkkNACAAQSlHIABBWGpB//8DcUEHSXENAAJAIABBpX9qDgQBAAABAAsgAEH9AEcgAEGFf2pB//8DcUEESXEPC0EBCy4BAX9BASEBAkAgAEH2CEEFEB8NACAAQYAJQQMQHw0AIABBhglBAhAfIQELIAELgwEBAn9BASEBAkACQAJAAkACQAJAIAAvAQAiAkFFag4EBQQEAQALAkAgAkGbf2oOBAMEBAIACyACQSlGDQQgAkH5AEcNAyAAQX5qQZIJQQYQHw8LIABBfmovAQBBPUYPCyAAQX5qQYoJQQQQHw8LIABBfmpBnglBAxAfDwtBACEBCyABC5MDAQJ/QQAhAQJAAkACQAJAAkACQAJAAkACQCAALwEAQZx/ag4UAAECCAgICAgICAMECAgFCAYICAcICwJAAkAgAEF+ai8BAEGXf2oOBAAJCQEJCyAAQXxqQa4IQQIQHw8LIABBfGpBsghBAxAfDwsCQAJAIABBfmovAQBBjX9qDgIAAQgLAkAgAEF8ai8BACICQeEARg0AIAJB7ABHDQggAEF6akHlABAgDwsgAEF6akHjABAgDwsgAEF8akG4CEEEEB8PCyAAQX5qLwEAQe8ARw0FIABBfGovAQBB5QBHDQUCQCAAQXpqLwEAIgJB8ABGDQAgAkHjAEcNBiAAQXhqQcAIQQYQHw8LIABBeGpBzAhBAhAfDwtBASEBIABBfmoiAEHpABAgDQQgAEHQCEEFEB8PCyAAQX5qQeQAECAPCyAAQX5qQdoIQQcQHw8LIABBfmpB6AhBBBAfDwsCQCAAQX5qLwEAIgJB7wBGDQAgAkHlAEcNASAAQXxqQe4AECAPCyAAQXxqQfAIQQMQHyEBCyABC3ABAn8CQAJAA0BBAEEAKAKICiIAQQJqIgE2AogKIABBACgCjApPDQECQAJAAkAgAS8BACIBQaV/ag4CAQIACwJAIAFBdmoOBAQDAwQACyABQS9HDQIMBAsQJxoMAQtBACAAQQRqNgKICgwACwsQHQsLNQEBf0EAQQE6ANAJQQAoAogKIQBBAEEAKAKMCkECajYCiApBACAAQQAoArAJa0EBdTYC4AkLNAEBf0EBIQECQCAAQXdqQf//A3FBBUkNACAAQYABckGgAUYNACAAQS5HIAAQJXEhAQsgAQtJAQN/QQAhAwJAIAAgAkEBdCICayIEQQJqIgBBACgCsAkiBUkNACAAIAEgAhAoDQACQCAAIAVHDQBBAQ8LIAQvAQAQHiEDCyADCz0BAn9BACECAkBBACgCsAkiAyAASw0AIAAvAQAgAUcNAAJAIAMgAEcNAEEBDwsgAEF+ai8BABAeIQILIAILnAEBA39BACgCiAohAQJAA0ACQAJAIAEvAQAiAkEvRw0AAkAgAS8BAiIBQSpGDQAgAUEvRw0EEBQMAgsgABAVDAELAkACQCAARQ0AIAJBd2oiAUEXSw0BQQEgAXRBn4CABHFFDQEMAgsgAhAjRQ0DDAELIAJBoAFHDQILQQBBACgCiAoiA0ECaiIBNgKICiADQQAoAowKSQ0ACwsgAgvCAwEBfwJAIAFBIkYNACABQSdGDQAQHQ8LQQAoAogKIQIgARAXIAAgAkECakEAKAKICkEAKAKkCRABQQBBACgCiApBAmo2AogKQQAQISEAQQAoAogKIQECQAJAIABB4QBHDQAgAUECakGkCEEKEChFDQELQQAgAUF+ajYCiAoPC0EAIAFBDGo2AogKAkBBARAhQfsARg0AQQAgATYCiAoPC0EAKAKICiICIQADQEEAIABBAmo2AogKAkACQAJAQQEQISIAQSJGDQAgAEEnRw0BQScQF0EAQQAoAogKQQJqNgKICkEBECEhAAwCC0EiEBdBAEEAKAKICkECajYCiApBARAhIQAMAQsgABAkIQALAkAgAEE6Rg0AQQAgATYCiAoPC0EAQQAoAogKQQJqNgKICgJAQQEQISIAQSJGDQAgAEEnRg0AQQAgATYCiAoPCyAAEBdBAEEAKAKICkECajYCiAoCQAJAQQEQISIAQSxGDQAgAEH9AEYNAUEAIAE2AogKDwtBAEEAKAKICkECajYCiApBARAhQf0ARg0AQQAoAogKIQAMAQsLQQAoAsQJIgEgAjYCECABQQAoAogKQQJqNgIMCzABAX8CQAJAIABBd2oiAUEXSw0AQQEgAXRBjYCABHENAQsgAEGgAUYNAEEADwtBAQttAQJ/AkACQANAAkAgAEH//wNxIgFBd2oiAkEXSw0AQQEgAnRBn4CABHENAgsgAUGgAUYNASAAIQIgARAlDQJBACECQQBBACgCiAoiAEECajYCiAogAC8BAiIADQAMAgsLIAAhAgsgAkH//wNxC2gBAn9BASEBAkACQCAAQV9qIgJBBUsNAEEBIAJ0QTFxDQELIABB+P8DcUEoRg0AIABBRmpB//8DcUEGSQ0AAkAgAEGlf2oiAkEDSw0AIAJBAUcNAQsgAEGFf2pB//8DcUEESSEBCyABC4sBAQJ/AkBBACgCiAoiAi8BACIDQeEARw0AQQAgAkEEajYCiApBARAhIQJBACgCiAohAAJAAkAgAkEiRg0AIAJBJ0YNACACECQaQQAoAogKIQEMAQsgAhAXQQBBACgCiApBAmoiATYCiAoLQQEQISEDQQAoAogKIQILAkAgAiAARg0AIAAgARACCyADC3IBBH9BACgCiAohAEEAKAKMCiEBAkACQANAIABBAmohAiAAIAFPDQECQAJAIAIvAQAiA0Gkf2oOAgEEAAsgAiEAIANBdmoOBAIBAQIBCyAAQQRqIQAMAAsLQQAgAjYCiAoQHUEADwtBACACNgKICkHdAAtJAQN/QQAhAwJAIAJFDQACQANAIAAtAAAiBCABLQAAIgVHDQEgAUEBaiEBIABBAWohACACQX9qIgINAAwCCwsgBCAFayEDCyADCwvCAQIAQYAIC6QBAAB4AHAAbwByAHQAbQBwAG8AcgB0AGUAdABhAGYAcgBvAG0AcwBzAGUAcgB0AHYAbwB5AGkAZQBkAGUAbABlAGkAbgBzAHQAYQBuAHQAeQByAGUAdAB1AHIAZABlAGIAdQBnAGcAZQBhAHcAYQBpAHQAaAByAHcAaABpAGwAZQBmAG8AcgBpAGYAYwBhAHQAYwBmAGkAbgBhAGwAbABlAGwAcwAAQaQJCxABAAAAAgAAAAAEAAAQOQAA","undefined"!=typeof Buffer?Buffer.from(E,"base64"):Uint8Array.from(atob(E),(A=>A.charCodeAt(0))))).then(WebAssembly.instantiate).then((({exports:A})=>{C=A;}));var E;
  18543. // This is a generated file. Do not edit.
  18544. var Space_Separator = /[\u1680\u2000-\u200A\u202F\u205F\u3000]/;
  18545. var ID_Start = /[\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\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\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\u09FC\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\u0AF9\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-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\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-\u13F5\u13F8-\u13FD\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-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\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-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\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-\uAB65\uAB70-\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\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\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\uDCE0-\uDCF2\uDCF4\uDCF5\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\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\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\uDD00-\uDD43]|\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\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/;
  18546. var ID_Continue = /[\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\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\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\u09FC\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\u0AF9-\u0AFF\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-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\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\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\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-\u13F5\u13F8-\u13FD\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\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\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\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-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\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-\uAB65\uAB70-\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-\uFE2F\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\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\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\uDCE0-\uDCF2\uDCF4\uDCF5\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\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\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\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\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]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\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\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/;
  18547. var unicode = {
  18548. Space_Separator: Space_Separator,
  18549. ID_Start: ID_Start,
  18550. ID_Continue: ID_Continue
  18551. };
  18552. var util$1 = {
  18553. isSpaceSeparator (c) {
  18554. return typeof c === 'string' && unicode.Space_Separator.test(c)
  18555. },
  18556. isIdStartChar (c) {
  18557. return typeof c === 'string' && (
  18558. (c >= 'a' && c <= 'z') ||
  18559. (c >= 'A' && c <= 'Z') ||
  18560. (c === '$') || (c === '_') ||
  18561. unicode.ID_Start.test(c)
  18562. )
  18563. },
  18564. isIdContinueChar (c) {
  18565. return typeof c === 'string' && (
  18566. (c >= 'a' && c <= 'z') ||
  18567. (c >= 'A' && c <= 'Z') ||
  18568. (c >= '0' && c <= '9') ||
  18569. (c === '$') || (c === '_') ||
  18570. (c === '\u200C') || (c === '\u200D') ||
  18571. unicode.ID_Continue.test(c)
  18572. )
  18573. },
  18574. isDigit (c) {
  18575. return typeof c === 'string' && /[0-9]/.test(c)
  18576. },
  18577. isHexDigit (c) {
  18578. return typeof c === 'string' && /[0-9A-Fa-f]/.test(c)
  18579. },
  18580. };
  18581. let source;
  18582. let parseState;
  18583. let stack;
  18584. let pos;
  18585. let line;
  18586. let column;
  18587. let token;
  18588. let key;
  18589. let root;
  18590. var parse$d = function parse (text, reviver) {
  18591. source = String(text);
  18592. parseState = 'start';
  18593. stack = [];
  18594. pos = 0;
  18595. line = 1;
  18596. column = 0;
  18597. token = undefined;
  18598. key = undefined;
  18599. root = undefined;
  18600. do {
  18601. token = lex();
  18602. // This code is unreachable.
  18603. // if (!parseStates[parseState]) {
  18604. // throw invalidParseState()
  18605. // }
  18606. parseStates[parseState]();
  18607. } while (token.type !== 'eof')
  18608. if (typeof reviver === 'function') {
  18609. return internalize({'': root}, '', reviver)
  18610. }
  18611. return root
  18612. };
  18613. function internalize (holder, name, reviver) {
  18614. const value = holder[name];
  18615. if (value != null && typeof value === 'object') {
  18616. for (const key in value) {
  18617. const replacement = internalize(value, key, reviver);
  18618. if (replacement === undefined) {
  18619. delete value[key];
  18620. } else {
  18621. value[key] = replacement;
  18622. }
  18623. }
  18624. }
  18625. return reviver.call(holder, name, value)
  18626. }
  18627. let lexState;
  18628. let buffer;
  18629. let doubleQuote;
  18630. let sign;
  18631. let c;
  18632. function lex () {
  18633. lexState = 'default';
  18634. buffer = '';
  18635. doubleQuote = false;
  18636. sign = 1;
  18637. for (;;) {
  18638. c = peek();
  18639. // This code is unreachable.
  18640. // if (!lexStates[lexState]) {
  18641. // throw invalidLexState(lexState)
  18642. // }
  18643. const token = lexStates[lexState]();
  18644. if (token) {
  18645. return token
  18646. }
  18647. }
  18648. }
  18649. function peek () {
  18650. if (source[pos]) {
  18651. return String.fromCodePoint(source.codePointAt(pos))
  18652. }
  18653. }
  18654. function read () {
  18655. const c = peek();
  18656. if (c === '\n') {
  18657. line++;
  18658. column = 0;
  18659. } else if (c) {
  18660. column += c.length;
  18661. } else {
  18662. column++;
  18663. }
  18664. if (c) {
  18665. pos += c.length;
  18666. }
  18667. return c
  18668. }
  18669. const lexStates = {
  18670. default () {
  18671. switch (c) {
  18672. case '\t':
  18673. case '\v':
  18674. case '\f':
  18675. case ' ':
  18676. case '\u00A0':
  18677. case '\uFEFF':
  18678. case '\n':
  18679. case '\r':
  18680. case '\u2028':
  18681. case '\u2029':
  18682. read();
  18683. return
  18684. case '/':
  18685. read();
  18686. lexState = 'comment';
  18687. return
  18688. case undefined:
  18689. read();
  18690. return newToken('eof')
  18691. }
  18692. if (util$1.isSpaceSeparator(c)) {
  18693. read();
  18694. return
  18695. }
  18696. // This code is unreachable.
  18697. // if (!lexStates[parseState]) {
  18698. // throw invalidLexState(parseState)
  18699. // }
  18700. return lexStates[parseState]()
  18701. },
  18702. comment () {
  18703. switch (c) {
  18704. case '*':
  18705. read();
  18706. lexState = 'multiLineComment';
  18707. return
  18708. case '/':
  18709. read();
  18710. lexState = 'singleLineComment';
  18711. return
  18712. }
  18713. throw invalidChar(read())
  18714. },
  18715. multiLineComment () {
  18716. switch (c) {
  18717. case '*':
  18718. read();
  18719. lexState = 'multiLineCommentAsterisk';
  18720. return
  18721. case undefined:
  18722. throw invalidChar(read())
  18723. }
  18724. read();
  18725. },
  18726. multiLineCommentAsterisk () {
  18727. switch (c) {
  18728. case '*':
  18729. read();
  18730. return
  18731. case '/':
  18732. read();
  18733. lexState = 'default';
  18734. return
  18735. case undefined:
  18736. throw invalidChar(read())
  18737. }
  18738. read();
  18739. lexState = 'multiLineComment';
  18740. },
  18741. singleLineComment () {
  18742. switch (c) {
  18743. case '\n':
  18744. case '\r':
  18745. case '\u2028':
  18746. case '\u2029':
  18747. read();
  18748. lexState = 'default';
  18749. return
  18750. case undefined:
  18751. read();
  18752. return newToken('eof')
  18753. }
  18754. read();
  18755. },
  18756. value () {
  18757. switch (c) {
  18758. case '{':
  18759. case '[':
  18760. return newToken('punctuator', read())
  18761. case 'n':
  18762. read();
  18763. literal$1('ull');
  18764. return newToken('null', null)
  18765. case 't':
  18766. read();
  18767. literal$1('rue');
  18768. return newToken('boolean', true)
  18769. case 'f':
  18770. read();
  18771. literal$1('alse');
  18772. return newToken('boolean', false)
  18773. case '-':
  18774. case '+':
  18775. if (read() === '-') {
  18776. sign = -1;
  18777. }
  18778. lexState = 'sign';
  18779. return
  18780. case '.':
  18781. buffer = read();
  18782. lexState = 'decimalPointLeading';
  18783. return
  18784. case '0':
  18785. buffer = read();
  18786. lexState = 'zero';
  18787. return
  18788. case '1':
  18789. case '2':
  18790. case '3':
  18791. case '4':
  18792. case '5':
  18793. case '6':
  18794. case '7':
  18795. case '8':
  18796. case '9':
  18797. buffer = read();
  18798. lexState = 'decimalInteger';
  18799. return
  18800. case 'I':
  18801. read();
  18802. literal$1('nfinity');
  18803. return newToken('numeric', Infinity)
  18804. case 'N':
  18805. read();
  18806. literal$1('aN');
  18807. return newToken('numeric', NaN)
  18808. case '"':
  18809. case "'":
  18810. doubleQuote = (read() === '"');
  18811. buffer = '';
  18812. lexState = 'string';
  18813. return
  18814. }
  18815. throw invalidChar(read())
  18816. },
  18817. identifierNameStartEscape () {
  18818. if (c !== 'u') {
  18819. throw invalidChar(read())
  18820. }
  18821. read();
  18822. const u = unicodeEscape();
  18823. switch (u) {
  18824. case '$':
  18825. case '_':
  18826. break
  18827. default:
  18828. if (!util$1.isIdStartChar(u)) {
  18829. throw invalidIdentifier()
  18830. }
  18831. break
  18832. }
  18833. buffer += u;
  18834. lexState = 'identifierName';
  18835. },
  18836. identifierName () {
  18837. switch (c) {
  18838. case '$':
  18839. case '_':
  18840. case '\u200C':
  18841. case '\u200D':
  18842. buffer += read();
  18843. return
  18844. case '\\':
  18845. read();
  18846. lexState = 'identifierNameEscape';
  18847. return
  18848. }
  18849. if (util$1.isIdContinueChar(c)) {
  18850. buffer += read();
  18851. return
  18852. }
  18853. return newToken('identifier', buffer)
  18854. },
  18855. identifierNameEscape () {
  18856. if (c !== 'u') {
  18857. throw invalidChar(read())
  18858. }
  18859. read();
  18860. const u = unicodeEscape();
  18861. switch (u) {
  18862. case '$':
  18863. case '_':
  18864. case '\u200C':
  18865. case '\u200D':
  18866. break
  18867. default:
  18868. if (!util$1.isIdContinueChar(u)) {
  18869. throw invalidIdentifier()
  18870. }
  18871. break
  18872. }
  18873. buffer += u;
  18874. lexState = 'identifierName';
  18875. },
  18876. sign () {
  18877. switch (c) {
  18878. case '.':
  18879. buffer = read();
  18880. lexState = 'decimalPointLeading';
  18881. return
  18882. case '0':
  18883. buffer = read();
  18884. lexState = 'zero';
  18885. return
  18886. case '1':
  18887. case '2':
  18888. case '3':
  18889. case '4':
  18890. case '5':
  18891. case '6':
  18892. case '7':
  18893. case '8':
  18894. case '9':
  18895. buffer = read();
  18896. lexState = 'decimalInteger';
  18897. return
  18898. case 'I':
  18899. read();
  18900. literal$1('nfinity');
  18901. return newToken('numeric', sign * Infinity)
  18902. case 'N':
  18903. read();
  18904. literal$1('aN');
  18905. return newToken('numeric', NaN)
  18906. }
  18907. throw invalidChar(read())
  18908. },
  18909. zero () {
  18910. switch (c) {
  18911. case '.':
  18912. buffer += read();
  18913. lexState = 'decimalPoint';
  18914. return
  18915. case 'e':
  18916. case 'E':
  18917. buffer += read();
  18918. lexState = 'decimalExponent';
  18919. return
  18920. case 'x':
  18921. case 'X':
  18922. buffer += read();
  18923. lexState = 'hexadecimal';
  18924. return
  18925. }
  18926. return newToken('numeric', sign * 0)
  18927. },
  18928. decimalInteger () {
  18929. switch (c) {
  18930. case '.':
  18931. buffer += read();
  18932. lexState = 'decimalPoint';
  18933. return
  18934. case 'e':
  18935. case 'E':
  18936. buffer += read();
  18937. lexState = 'decimalExponent';
  18938. return
  18939. }
  18940. if (util$1.isDigit(c)) {
  18941. buffer += read();
  18942. return
  18943. }
  18944. return newToken('numeric', sign * Number(buffer))
  18945. },
  18946. decimalPointLeading () {
  18947. if (util$1.isDigit(c)) {
  18948. buffer += read();
  18949. lexState = 'decimalFraction';
  18950. return
  18951. }
  18952. throw invalidChar(read())
  18953. },
  18954. decimalPoint () {
  18955. switch (c) {
  18956. case 'e':
  18957. case 'E':
  18958. buffer += read();
  18959. lexState = 'decimalExponent';
  18960. return
  18961. }
  18962. if (util$1.isDigit(c)) {
  18963. buffer += read();
  18964. lexState = 'decimalFraction';
  18965. return
  18966. }
  18967. return newToken('numeric', sign * Number(buffer))
  18968. },
  18969. decimalFraction () {
  18970. switch (c) {
  18971. case 'e':
  18972. case 'E':
  18973. buffer += read();
  18974. lexState = 'decimalExponent';
  18975. return
  18976. }
  18977. if (util$1.isDigit(c)) {
  18978. buffer += read();
  18979. return
  18980. }
  18981. return newToken('numeric', sign * Number(buffer))
  18982. },
  18983. decimalExponent () {
  18984. switch (c) {
  18985. case '+':
  18986. case '-':
  18987. buffer += read();
  18988. lexState = 'decimalExponentSign';
  18989. return
  18990. }
  18991. if (util$1.isDigit(c)) {
  18992. buffer += read();
  18993. lexState = 'decimalExponentInteger';
  18994. return
  18995. }
  18996. throw invalidChar(read())
  18997. },
  18998. decimalExponentSign () {
  18999. if (util$1.isDigit(c)) {
  19000. buffer += read();
  19001. lexState = 'decimalExponentInteger';
  19002. return
  19003. }
  19004. throw invalidChar(read())
  19005. },
  19006. decimalExponentInteger () {
  19007. if (util$1.isDigit(c)) {
  19008. buffer += read();
  19009. return
  19010. }
  19011. return newToken('numeric', sign * Number(buffer))
  19012. },
  19013. hexadecimal () {
  19014. if (util$1.isHexDigit(c)) {
  19015. buffer += read();
  19016. lexState = 'hexadecimalInteger';
  19017. return
  19018. }
  19019. throw invalidChar(read())
  19020. },
  19021. hexadecimalInteger () {
  19022. if (util$1.isHexDigit(c)) {
  19023. buffer += read();
  19024. return
  19025. }
  19026. return newToken('numeric', sign * Number(buffer))
  19027. },
  19028. string () {
  19029. switch (c) {
  19030. case '\\':
  19031. read();
  19032. buffer += escape$1();
  19033. return
  19034. case '"':
  19035. if (doubleQuote) {
  19036. read();
  19037. return newToken('string', buffer)
  19038. }
  19039. buffer += read();
  19040. return
  19041. case "'":
  19042. if (!doubleQuote) {
  19043. read();
  19044. return newToken('string', buffer)
  19045. }
  19046. buffer += read();
  19047. return
  19048. case '\n':
  19049. case '\r':
  19050. throw invalidChar(read())
  19051. case '\u2028':
  19052. case '\u2029':
  19053. separatorChar(c);
  19054. break
  19055. case undefined:
  19056. throw invalidChar(read())
  19057. }
  19058. buffer += read();
  19059. },
  19060. start () {
  19061. switch (c) {
  19062. case '{':
  19063. case '[':
  19064. return newToken('punctuator', read())
  19065. // This code is unreachable since the default lexState handles eof.
  19066. // case undefined:
  19067. // return newToken('eof')
  19068. }
  19069. lexState = 'value';
  19070. },
  19071. beforePropertyName () {
  19072. switch (c) {
  19073. case '$':
  19074. case '_':
  19075. buffer = read();
  19076. lexState = 'identifierName';
  19077. return
  19078. case '\\':
  19079. read();
  19080. lexState = 'identifierNameStartEscape';
  19081. return
  19082. case '}':
  19083. return newToken('punctuator', read())
  19084. case '"':
  19085. case "'":
  19086. doubleQuote = (read() === '"');
  19087. lexState = 'string';
  19088. return
  19089. }
  19090. if (util$1.isIdStartChar(c)) {
  19091. buffer += read();
  19092. lexState = 'identifierName';
  19093. return
  19094. }
  19095. throw invalidChar(read())
  19096. },
  19097. afterPropertyName () {
  19098. if (c === ':') {
  19099. return newToken('punctuator', read())
  19100. }
  19101. throw invalidChar(read())
  19102. },
  19103. beforePropertyValue () {
  19104. lexState = 'value';
  19105. },
  19106. afterPropertyValue () {
  19107. switch (c) {
  19108. case ',':
  19109. case '}':
  19110. return newToken('punctuator', read())
  19111. }
  19112. throw invalidChar(read())
  19113. },
  19114. beforeArrayValue () {
  19115. if (c === ']') {
  19116. return newToken('punctuator', read())
  19117. }
  19118. lexState = 'value';
  19119. },
  19120. afterArrayValue () {
  19121. switch (c) {
  19122. case ',':
  19123. case ']':
  19124. return newToken('punctuator', read())
  19125. }
  19126. throw invalidChar(read())
  19127. },
  19128. end () {
  19129. // This code is unreachable since it's handled by the default lexState.
  19130. // if (c === undefined) {
  19131. // read()
  19132. // return newToken('eof')
  19133. // }
  19134. throw invalidChar(read())
  19135. },
  19136. };
  19137. function newToken (type, value) {
  19138. return {
  19139. type,
  19140. value,
  19141. line,
  19142. column,
  19143. }
  19144. }
  19145. function literal$1 (s) {
  19146. for (const c of s) {
  19147. const p = peek();
  19148. if (p !== c) {
  19149. throw invalidChar(read())
  19150. }
  19151. read();
  19152. }
  19153. }
  19154. function escape$1 () {
  19155. const c = peek();
  19156. switch (c) {
  19157. case 'b':
  19158. read();
  19159. return '\b'
  19160. case 'f':
  19161. read();
  19162. return '\f'
  19163. case 'n':
  19164. read();
  19165. return '\n'
  19166. case 'r':
  19167. read();
  19168. return '\r'
  19169. case 't':
  19170. read();
  19171. return '\t'
  19172. case 'v':
  19173. read();
  19174. return '\v'
  19175. case '0':
  19176. read();
  19177. if (util$1.isDigit(peek())) {
  19178. throw invalidChar(read())
  19179. }
  19180. return '\0'
  19181. case 'x':
  19182. read();
  19183. return hexEscape()
  19184. case 'u':
  19185. read();
  19186. return unicodeEscape()
  19187. case '\n':
  19188. case '\u2028':
  19189. case '\u2029':
  19190. read();
  19191. return ''
  19192. case '\r':
  19193. read();
  19194. if (peek() === '\n') {
  19195. read();
  19196. }
  19197. return ''
  19198. case '1':
  19199. case '2':
  19200. case '3':
  19201. case '4':
  19202. case '5':
  19203. case '6':
  19204. case '7':
  19205. case '8':
  19206. case '9':
  19207. throw invalidChar(read())
  19208. case undefined:
  19209. throw invalidChar(read())
  19210. }
  19211. return read()
  19212. }
  19213. function hexEscape () {
  19214. let buffer = '';
  19215. let c = peek();
  19216. if (!util$1.isHexDigit(c)) {
  19217. throw invalidChar(read())
  19218. }
  19219. buffer += read();
  19220. c = peek();
  19221. if (!util$1.isHexDigit(c)) {
  19222. throw invalidChar(read())
  19223. }
  19224. buffer += read();
  19225. return String.fromCodePoint(parseInt(buffer, 16))
  19226. }
  19227. function unicodeEscape () {
  19228. let buffer = '';
  19229. let count = 4;
  19230. while (count-- > 0) {
  19231. const c = peek();
  19232. if (!util$1.isHexDigit(c)) {
  19233. throw invalidChar(read())
  19234. }
  19235. buffer += read();
  19236. }
  19237. return String.fromCodePoint(parseInt(buffer, 16))
  19238. }
  19239. const parseStates = {
  19240. start () {
  19241. if (token.type === 'eof') {
  19242. throw invalidEOF()
  19243. }
  19244. push$1();
  19245. },
  19246. beforePropertyName () {
  19247. switch (token.type) {
  19248. case 'identifier':
  19249. case 'string':
  19250. key = token.value;
  19251. parseState = 'afterPropertyName';
  19252. return
  19253. case 'punctuator':
  19254. // This code is unreachable since it's handled by the lexState.
  19255. // if (token.value !== '}') {
  19256. // throw invalidToken()
  19257. // }
  19258. pop();
  19259. return
  19260. case 'eof':
  19261. throw invalidEOF()
  19262. }
  19263. // This code is unreachable since it's handled by the lexState.
  19264. // throw invalidToken()
  19265. },
  19266. afterPropertyName () {
  19267. // This code is unreachable since it's handled by the lexState.
  19268. // if (token.type !== 'punctuator' || token.value !== ':') {
  19269. // throw invalidToken()
  19270. // }
  19271. if (token.type === 'eof') {
  19272. throw invalidEOF()
  19273. }
  19274. parseState = 'beforePropertyValue';
  19275. },
  19276. beforePropertyValue () {
  19277. if (token.type === 'eof') {
  19278. throw invalidEOF()
  19279. }
  19280. push$1();
  19281. },
  19282. beforeArrayValue () {
  19283. if (token.type === 'eof') {
  19284. throw invalidEOF()
  19285. }
  19286. if (token.type === 'punctuator' && token.value === ']') {
  19287. pop();
  19288. return
  19289. }
  19290. push$1();
  19291. },
  19292. afterPropertyValue () {
  19293. // This code is unreachable since it's handled by the lexState.
  19294. // if (token.type !== 'punctuator') {
  19295. // throw invalidToken()
  19296. // }
  19297. if (token.type === 'eof') {
  19298. throw invalidEOF()
  19299. }
  19300. switch (token.value) {
  19301. case ',':
  19302. parseState = 'beforePropertyName';
  19303. return
  19304. case '}':
  19305. pop();
  19306. }
  19307. // This code is unreachable since it's handled by the lexState.
  19308. // throw invalidToken()
  19309. },
  19310. afterArrayValue () {
  19311. // This code is unreachable since it's handled by the lexState.
  19312. // if (token.type !== 'punctuator') {
  19313. // throw invalidToken()
  19314. // }
  19315. if (token.type === 'eof') {
  19316. throw invalidEOF()
  19317. }
  19318. switch (token.value) {
  19319. case ',':
  19320. parseState = 'beforeArrayValue';
  19321. return
  19322. case ']':
  19323. pop();
  19324. }
  19325. // This code is unreachable since it's handled by the lexState.
  19326. // throw invalidToken()
  19327. },
  19328. end () {
  19329. // This code is unreachable since it's handled by the lexState.
  19330. // if (token.type !== 'eof') {
  19331. // throw invalidToken()
  19332. // }
  19333. },
  19334. };
  19335. function push$1 () {
  19336. let value;
  19337. switch (token.type) {
  19338. case 'punctuator':
  19339. switch (token.value) {
  19340. case '{':
  19341. value = {};
  19342. break
  19343. case '[':
  19344. value = [];
  19345. break
  19346. }
  19347. break
  19348. case 'null':
  19349. case 'boolean':
  19350. case 'numeric':
  19351. case 'string':
  19352. value = token.value;
  19353. break
  19354. // This code is unreachable.
  19355. // default:
  19356. // throw invalidToken()
  19357. }
  19358. if (root === undefined) {
  19359. root = value;
  19360. } else {
  19361. const parent = stack[stack.length - 1];
  19362. if (Array.isArray(parent)) {
  19363. parent.push(value);
  19364. } else {
  19365. parent[key] = value;
  19366. }
  19367. }
  19368. if (value !== null && typeof value === 'object') {
  19369. stack.push(value);
  19370. if (Array.isArray(value)) {
  19371. parseState = 'beforeArrayValue';
  19372. } else {
  19373. parseState = 'beforePropertyName';
  19374. }
  19375. } else {
  19376. const current = stack[stack.length - 1];
  19377. if (current == null) {
  19378. parseState = 'end';
  19379. } else if (Array.isArray(current)) {
  19380. parseState = 'afterArrayValue';
  19381. } else {
  19382. parseState = 'afterPropertyValue';
  19383. }
  19384. }
  19385. }
  19386. function pop () {
  19387. stack.pop();
  19388. const current = stack[stack.length - 1];
  19389. if (current == null) {
  19390. parseState = 'end';
  19391. } else if (Array.isArray(current)) {
  19392. parseState = 'afterArrayValue';
  19393. } else {
  19394. parseState = 'afterPropertyValue';
  19395. }
  19396. }
  19397. // This code is unreachable.
  19398. // function invalidParseState () {
  19399. // return new Error(`JSON5: invalid parse state '${parseState}'`)
  19400. // }
  19401. // This code is unreachable.
  19402. // function invalidLexState (state) {
  19403. // return new Error(`JSON5: invalid lex state '${state}'`)
  19404. // }
  19405. function invalidChar (c) {
  19406. if (c === undefined) {
  19407. return syntaxError(`JSON5: invalid end of input at ${line}:${column}`)
  19408. }
  19409. return syntaxError(`JSON5: invalid character '${formatChar(c)}' at ${line}:${column}`)
  19410. }
  19411. function invalidEOF () {
  19412. return syntaxError(`JSON5: invalid end of input at ${line}:${column}`)
  19413. }
  19414. // This code is unreachable.
  19415. // function invalidToken () {
  19416. // if (token.type === 'eof') {
  19417. // return syntaxError(`JSON5: invalid end of input at ${line}:${column}`)
  19418. // }
  19419. // const c = String.fromCodePoint(token.value.codePointAt(0))
  19420. // return syntaxError(`JSON5: invalid character '${formatChar(c)}' at ${line}:${column}`)
  19421. // }
  19422. function invalidIdentifier () {
  19423. column -= 5;
  19424. return syntaxError(`JSON5: invalid identifier character at ${line}:${column}`)
  19425. }
  19426. function separatorChar (c) {
  19427. console.warn(`JSON5: '${formatChar(c)}' in strings is not valid ECMAScript; consider escaping`);
  19428. }
  19429. function formatChar (c) {
  19430. const replacements = {
  19431. "'": "\\'",
  19432. '"': '\\"',
  19433. '\\': '\\\\',
  19434. '\b': '\\b',
  19435. '\f': '\\f',
  19436. '\n': '\\n',
  19437. '\r': '\\r',
  19438. '\t': '\\t',
  19439. '\v': '\\v',
  19440. '\0': '\\0',
  19441. '\u2028': '\\u2028',
  19442. '\u2029': '\\u2029',
  19443. };
  19444. if (replacements[c]) {
  19445. return replacements[c]
  19446. }
  19447. if (c < ' ') {
  19448. const hexString = c.charCodeAt(0).toString(16);
  19449. return '\\x' + ('00' + hexString).substring(hexString.length)
  19450. }
  19451. return c
  19452. }
  19453. function syntaxError (message) {
  19454. const err = new SyntaxError(message);
  19455. err.lineNumber = line;
  19456. err.columnNumber = column;
  19457. return err
  19458. }
  19459. var stringify$2 = function stringify (value, replacer, space) {
  19460. const stack = [];
  19461. let indent = '';
  19462. let propertyList;
  19463. let replacerFunc;
  19464. let gap = '';
  19465. let quote;
  19466. if (
  19467. replacer != null &&
  19468. typeof replacer === 'object' &&
  19469. !Array.isArray(replacer)
  19470. ) {
  19471. space = replacer.space;
  19472. quote = replacer.quote;
  19473. replacer = replacer.replacer;
  19474. }
  19475. if (typeof replacer === 'function') {
  19476. replacerFunc = replacer;
  19477. } else if (Array.isArray(replacer)) {
  19478. propertyList = [];
  19479. for (const v of replacer) {
  19480. let item;
  19481. if (typeof v === 'string') {
  19482. item = v;
  19483. } else if (
  19484. typeof v === 'number' ||
  19485. v instanceof String ||
  19486. v instanceof Number
  19487. ) {
  19488. item = String(v);
  19489. }
  19490. if (item !== undefined && propertyList.indexOf(item) < 0) {
  19491. propertyList.push(item);
  19492. }
  19493. }
  19494. }
  19495. if (space instanceof Number) {
  19496. space = Number(space);
  19497. } else if (space instanceof String) {
  19498. space = String(space);
  19499. }
  19500. if (typeof space === 'number') {
  19501. if (space > 0) {
  19502. space = Math.min(10, Math.floor(space));
  19503. gap = ' '.substr(0, space);
  19504. }
  19505. } else if (typeof space === 'string') {
  19506. gap = space.substr(0, 10);
  19507. }
  19508. return serializeProperty('', {'': value})
  19509. function serializeProperty (key, holder) {
  19510. let value = holder[key];
  19511. if (value != null) {
  19512. if (typeof value.toJSON5 === 'function') {
  19513. value = value.toJSON5(key);
  19514. } else if (typeof value.toJSON === 'function') {
  19515. value = value.toJSON(key);
  19516. }
  19517. }
  19518. if (replacerFunc) {
  19519. value = replacerFunc.call(holder, key, value);
  19520. }
  19521. if (value instanceof Number) {
  19522. value = Number(value);
  19523. } else if (value instanceof String) {
  19524. value = String(value);
  19525. } else if (value instanceof Boolean) {
  19526. value = value.valueOf();
  19527. }
  19528. switch (value) {
  19529. case null: return 'null'
  19530. case true: return 'true'
  19531. case false: return 'false'
  19532. }
  19533. if (typeof value === 'string') {
  19534. return quoteString(value)
  19535. }
  19536. if (typeof value === 'number') {
  19537. return String(value)
  19538. }
  19539. if (typeof value === 'object') {
  19540. return Array.isArray(value) ? serializeArray(value) : serializeObject(value)
  19541. }
  19542. return undefined
  19543. }
  19544. function quoteString (value) {
  19545. const quotes = {
  19546. "'": 0.1,
  19547. '"': 0.2,
  19548. };
  19549. const replacements = {
  19550. "'": "\\'",
  19551. '"': '\\"',
  19552. '\\': '\\\\',
  19553. '\b': '\\b',
  19554. '\f': '\\f',
  19555. '\n': '\\n',
  19556. '\r': '\\r',
  19557. '\t': '\\t',
  19558. '\v': '\\v',
  19559. '\0': '\\0',
  19560. '\u2028': '\\u2028',
  19561. '\u2029': '\\u2029',
  19562. };
  19563. let product = '';
  19564. for (let i = 0; i < value.length; i++) {
  19565. const c = value[i];
  19566. switch (c) {
  19567. case "'":
  19568. case '"':
  19569. quotes[c]++;
  19570. product += c;
  19571. continue
  19572. case '\0':
  19573. if (util$1.isDigit(value[i + 1])) {
  19574. product += '\\x00';
  19575. continue
  19576. }
  19577. }
  19578. if (replacements[c]) {
  19579. product += replacements[c];
  19580. continue
  19581. }
  19582. if (c < ' ') {
  19583. let hexString = c.charCodeAt(0).toString(16);
  19584. product += '\\x' + ('00' + hexString).substring(hexString.length);
  19585. continue
  19586. }
  19587. product += c;
  19588. }
  19589. const quoteChar = quote || Object.keys(quotes).reduce((a, b) => (quotes[a] < quotes[b]) ? a : b);
  19590. product = product.replace(new RegExp(quoteChar, 'g'), replacements[quoteChar]);
  19591. return quoteChar + product + quoteChar
  19592. }
  19593. function serializeObject (value) {
  19594. if (stack.indexOf(value) >= 0) {
  19595. throw TypeError('Converting circular structure to JSON5')
  19596. }
  19597. stack.push(value);
  19598. let stepback = indent;
  19599. indent = indent + gap;
  19600. let keys = propertyList || Object.keys(value);
  19601. let partial = [];
  19602. for (const key of keys) {
  19603. const propertyString = serializeProperty(key, value);
  19604. if (propertyString !== undefined) {
  19605. let member = serializeKey(key) + ':';
  19606. if (gap !== '') {
  19607. member += ' ';
  19608. }
  19609. member += propertyString;
  19610. partial.push(member);
  19611. }
  19612. }
  19613. let final;
  19614. if (partial.length === 0) {
  19615. final = '{}';
  19616. } else {
  19617. let properties;
  19618. if (gap === '') {
  19619. properties = partial.join(',');
  19620. final = '{' + properties + '}';
  19621. } else {
  19622. let separator = ',\n' + indent;
  19623. properties = partial.join(separator);
  19624. final = '{\n' + indent + properties + ',\n' + stepback + '}';
  19625. }
  19626. }
  19627. stack.pop();
  19628. indent = stepback;
  19629. return final
  19630. }
  19631. function serializeKey (key) {
  19632. if (key.length === 0) {
  19633. return quoteString(key)
  19634. }
  19635. const firstChar = String.fromCodePoint(key.codePointAt(0));
  19636. if (!util$1.isIdStartChar(firstChar)) {
  19637. return quoteString(key)
  19638. }
  19639. for (let i = firstChar.length; i < key.length; i++) {
  19640. if (!util$1.isIdContinueChar(String.fromCodePoint(key.codePointAt(i)))) {
  19641. return quoteString(key)
  19642. }
  19643. }
  19644. return key
  19645. }
  19646. function serializeArray (value) {
  19647. if (stack.indexOf(value) >= 0) {
  19648. throw TypeError('Converting circular structure to JSON5')
  19649. }
  19650. stack.push(value);
  19651. let stepback = indent;
  19652. indent = indent + gap;
  19653. let partial = [];
  19654. for (let i = 0; i < value.length; i++) {
  19655. const propertyString = serializeProperty(String(i), value);
  19656. partial.push((propertyString !== undefined) ? propertyString : 'null');
  19657. }
  19658. let final;
  19659. if (partial.length === 0) {
  19660. final = '[]';
  19661. } else {
  19662. if (gap === '') {
  19663. let properties = partial.join(',');
  19664. final = '[' + properties + ']';
  19665. } else {
  19666. let separator = ',\n' + indent;
  19667. let properties = partial.join(separator);
  19668. final = '[\n' + indent + properties + ',\n' + stepback + ']';
  19669. }
  19670. }
  19671. stack.pop();
  19672. indent = stepback;
  19673. return final
  19674. }
  19675. };
  19676. const JSON5 = {
  19677. parse: parse$d,
  19678. stringify: stringify$2,
  19679. };
  19680. var lib$2 = JSON5;
  19681. var dist$1 = {};
  19682. (function (exports) {
  19683. Object.defineProperty(exports, "__esModule", { value: true });
  19684. exports.lilconfigSync = exports.lilconfig = exports.defaultLoaders = void 0;
  19685. const path = path__default;
  19686. const fs = fs__default;
  19687. const os = require$$2__default;
  19688. const fsReadFileAsync = fs.promises.readFile;
  19689. function getDefaultSearchPlaces(name) {
  19690. return [
  19691. 'package.json',
  19692. `.${name}rc.json`,
  19693. `.${name}rc.js`,
  19694. `${name}.config.js`,
  19695. `.${name}rc.cjs`,
  19696. `${name}.config.cjs`,
  19697. ];
  19698. }
  19699. function getSearchPaths(startDir, stopDir) {
  19700. return startDir
  19701. .split(path.sep)
  19702. .reduceRight((acc, _, ind, arr) => {
  19703. const currentPath = arr.slice(0, ind + 1).join(path.sep);
  19704. if (!acc.passedStopDir)
  19705. acc.searchPlaces.push(currentPath || path.sep);
  19706. if (currentPath === stopDir)
  19707. acc.passedStopDir = true;
  19708. return acc;
  19709. }, { searchPlaces: [], passedStopDir: false }).searchPlaces;
  19710. }
  19711. exports.defaultLoaders = Object.freeze({
  19712. '.js': eval('require'),
  19713. '.json': eval('require'),
  19714. '.cjs': eval('require'),
  19715. noExt(_, content) {
  19716. return JSON.parse(content);
  19717. },
  19718. });
  19719. function getExtDesc(ext) {
  19720. return ext === 'noExt' ? 'files without extensions' : `extension "${ext}"`;
  19721. }
  19722. function getOptions(name, options = {}) {
  19723. const conf = {
  19724. stopDir: os.homedir(),
  19725. searchPlaces: getDefaultSearchPlaces(name),
  19726. ignoreEmptySearchPlaces: true,
  19727. transform: (x) => x,
  19728. packageProp: [name],
  19729. ...options,
  19730. loaders: { ...exports.defaultLoaders, ...options.loaders },
  19731. };
  19732. conf.searchPlaces.forEach(place => {
  19733. const key = path.extname(place) || 'noExt';
  19734. const loader = conf.loaders[key];
  19735. if (!loader) {
  19736. throw new Error(`No loader specified for ${getExtDesc(key)}, so searchPlaces item "${place}" is invalid`);
  19737. }
  19738. if (typeof loader !== 'function') {
  19739. throw new Error(`loader for ${getExtDesc(key)} is not a function (type provided: "${typeof loader}"), so searchPlaces item "${place}" is invalid`);
  19740. }
  19741. });
  19742. return conf;
  19743. }
  19744. function getPackageProp(props, obj) {
  19745. if (typeof props === 'string' && props in obj)
  19746. return obj[props];
  19747. return ((Array.isArray(props) ? props : props.split('.')).reduce((acc, prop) => (acc === undefined ? acc : acc[prop]), obj) || null);
  19748. }
  19749. function getSearchItems(searchPlaces, searchPaths) {
  19750. return searchPaths.reduce((acc, searchPath) => {
  19751. searchPlaces.forEach(fileName => acc.push({
  19752. fileName,
  19753. filepath: path.join(searchPath, fileName),
  19754. loaderKey: path.extname(fileName) || 'noExt',
  19755. }));
  19756. return acc;
  19757. }, []);
  19758. }
  19759. function validateFilePath(filepath) {
  19760. if (!filepath)
  19761. throw new Error('load must pass a non-empty string');
  19762. }
  19763. function validateLoader(loader, ext) {
  19764. if (!loader)
  19765. throw new Error(`No loader specified for extension "${ext}"`);
  19766. if (typeof loader !== 'function')
  19767. throw new Error('loader is not a function');
  19768. }
  19769. function lilconfig(name, options) {
  19770. const { ignoreEmptySearchPlaces, loaders, packageProp, searchPlaces, stopDir, transform, } = getOptions(name, options);
  19771. return {
  19772. async search(searchFrom = process.cwd()) {
  19773. const searchPaths = getSearchPaths(searchFrom, stopDir);
  19774. const result = {
  19775. config: null,
  19776. filepath: '',
  19777. };
  19778. const searchItems = getSearchItems(searchPlaces, searchPaths);
  19779. for (const { fileName, filepath, loaderKey } of searchItems) {
  19780. try {
  19781. await fs.promises.access(filepath);
  19782. }
  19783. catch (_a) {
  19784. continue;
  19785. }
  19786. const content = String(await fsReadFileAsync(filepath));
  19787. const loader = loaders[loaderKey];
  19788. if (fileName === 'package.json') {
  19789. const pkg = await loader(filepath, content);
  19790. const maybeConfig = getPackageProp(packageProp, pkg);
  19791. if (maybeConfig != null) {
  19792. result.config = maybeConfig;
  19793. result.filepath = filepath;
  19794. break;
  19795. }
  19796. continue;
  19797. }
  19798. const isEmpty = content.trim() === '';
  19799. if (isEmpty && ignoreEmptySearchPlaces)
  19800. continue;
  19801. if (isEmpty) {
  19802. result.isEmpty = true;
  19803. result.config = undefined;
  19804. }
  19805. else {
  19806. validateLoader(loader, loaderKey);
  19807. result.config = await loader(filepath, content);
  19808. }
  19809. result.filepath = filepath;
  19810. break;
  19811. }
  19812. if (result.filepath === '' && result.config === null)
  19813. return transform(null);
  19814. return transform(result);
  19815. },
  19816. async load(filepath) {
  19817. validateFilePath(filepath);
  19818. const absPath = path.resolve(process.cwd(), filepath);
  19819. const { base, ext } = path.parse(absPath);
  19820. const loaderKey = ext || 'noExt';
  19821. const loader = loaders[loaderKey];
  19822. validateLoader(loader, loaderKey);
  19823. const content = String(await fsReadFileAsync(absPath));
  19824. if (base === 'package.json') {
  19825. const pkg = await loader(absPath, content);
  19826. return transform({
  19827. config: getPackageProp(packageProp, pkg),
  19828. filepath: absPath,
  19829. });
  19830. }
  19831. const result = {
  19832. config: null,
  19833. filepath: absPath,
  19834. };
  19835. const isEmpty = content.trim() === '';
  19836. if (isEmpty && ignoreEmptySearchPlaces)
  19837. return transform({
  19838. config: undefined,
  19839. filepath: absPath,
  19840. isEmpty: true,
  19841. });
  19842. result.config = isEmpty
  19843. ? undefined
  19844. : await loader(absPath, content);
  19845. return transform(isEmpty ? { ...result, isEmpty, config: undefined } : result);
  19846. },
  19847. };
  19848. }
  19849. exports.lilconfig = lilconfig;
  19850. function lilconfigSync(name, options) {
  19851. const { ignoreEmptySearchPlaces, loaders, packageProp, searchPlaces, stopDir, transform, } = getOptions(name, options);
  19852. return {
  19853. search(searchFrom = process.cwd()) {
  19854. const searchPaths = getSearchPaths(searchFrom, stopDir);
  19855. const result = {
  19856. config: null,
  19857. filepath: '',
  19858. };
  19859. const searchItems = getSearchItems(searchPlaces, searchPaths);
  19860. for (const { fileName, filepath, loaderKey } of searchItems) {
  19861. try {
  19862. fs.accessSync(filepath);
  19863. }
  19864. catch (_a) {
  19865. continue;
  19866. }
  19867. const loader = loaders[loaderKey];
  19868. const content = String(fs.readFileSync(filepath));
  19869. if (fileName === 'package.json') {
  19870. const pkg = loader(filepath, content);
  19871. const maybeConfig = getPackageProp(packageProp, pkg);
  19872. if (maybeConfig != null) {
  19873. result.config = maybeConfig;
  19874. result.filepath = filepath;
  19875. break;
  19876. }
  19877. continue;
  19878. }
  19879. const isEmpty = content.trim() === '';
  19880. if (isEmpty && ignoreEmptySearchPlaces)
  19881. continue;
  19882. if (isEmpty) {
  19883. result.isEmpty = true;
  19884. result.config = undefined;
  19885. }
  19886. else {
  19887. validateLoader(loader, loaderKey);
  19888. result.config = loader(filepath, content);
  19889. }
  19890. result.filepath = filepath;
  19891. break;
  19892. }
  19893. if (result.filepath === '' && result.config === null)
  19894. return transform(null);
  19895. return transform(result);
  19896. },
  19897. load(filepath) {
  19898. validateFilePath(filepath);
  19899. const absPath = path.resolve(process.cwd(), filepath);
  19900. const { base, ext } = path.parse(absPath);
  19901. const loaderKey = ext || 'noExt';
  19902. const loader = loaders[loaderKey];
  19903. validateLoader(loader, loaderKey);
  19904. const content = String(fs.readFileSync(absPath));
  19905. if (base === 'package.json') {
  19906. const pkg = loader(absPath, content);
  19907. return transform({
  19908. config: getPackageProp(packageProp, pkg),
  19909. filepath: absPath,
  19910. });
  19911. }
  19912. const result = {
  19913. config: null,
  19914. filepath: absPath,
  19915. };
  19916. const isEmpty = content.trim() === '';
  19917. if (isEmpty && ignoreEmptySearchPlaces)
  19918. return transform({
  19919. filepath: absPath,
  19920. config: undefined,
  19921. isEmpty: true,
  19922. });
  19923. result.config = isEmpty ? undefined : loader(absPath, content);
  19924. return transform(isEmpty ? { ...result, isEmpty, config: undefined } : result);
  19925. },
  19926. };
  19927. }
  19928. exports.lilconfigSync = lilconfigSync;
  19929. }(dist$1));
  19930. var dist = {};
  19931. var parseCst$1 = {};
  19932. var PlainValueEc8e588e = {};
  19933. const Char = {
  19934. ANCHOR: '&',
  19935. COMMENT: '#',
  19936. TAG: '!',
  19937. DIRECTIVES_END: '-',
  19938. DOCUMENT_END: '.'
  19939. };
  19940. const Type = {
  19941. ALIAS: 'ALIAS',
  19942. BLANK_LINE: 'BLANK_LINE',
  19943. BLOCK_FOLDED: 'BLOCK_FOLDED',
  19944. BLOCK_LITERAL: 'BLOCK_LITERAL',
  19945. COMMENT: 'COMMENT',
  19946. DIRECTIVE: 'DIRECTIVE',
  19947. DOCUMENT: 'DOCUMENT',
  19948. FLOW_MAP: 'FLOW_MAP',
  19949. FLOW_SEQ: 'FLOW_SEQ',
  19950. MAP: 'MAP',
  19951. MAP_KEY: 'MAP_KEY',
  19952. MAP_VALUE: 'MAP_VALUE',
  19953. PLAIN: 'PLAIN',
  19954. QUOTE_DOUBLE: 'QUOTE_DOUBLE',
  19955. QUOTE_SINGLE: 'QUOTE_SINGLE',
  19956. SEQ: 'SEQ',
  19957. SEQ_ITEM: 'SEQ_ITEM'
  19958. };
  19959. const defaultTagPrefix = 'tag:yaml.org,2002:';
  19960. const defaultTags = {
  19961. MAP: 'tag:yaml.org,2002:map',
  19962. SEQ: 'tag:yaml.org,2002:seq',
  19963. STR: 'tag:yaml.org,2002:str'
  19964. };
  19965. function findLineStarts(src) {
  19966. const ls = [0];
  19967. let offset = src.indexOf('\n');
  19968. while (offset !== -1) {
  19969. offset += 1;
  19970. ls.push(offset);
  19971. offset = src.indexOf('\n', offset);
  19972. }
  19973. return ls;
  19974. }
  19975. function getSrcInfo(cst) {
  19976. let lineStarts, src;
  19977. if (typeof cst === 'string') {
  19978. lineStarts = findLineStarts(cst);
  19979. src = cst;
  19980. } else {
  19981. if (Array.isArray(cst)) cst = cst[0];
  19982. if (cst && cst.context) {
  19983. if (!cst.lineStarts) cst.lineStarts = findLineStarts(cst.context.src);
  19984. lineStarts = cst.lineStarts;
  19985. src = cst.context.src;
  19986. }
  19987. }
  19988. return {
  19989. lineStarts,
  19990. src
  19991. };
  19992. }
  19993. /**
  19994. * @typedef {Object} LinePos - One-indexed position in the source
  19995. * @property {number} line
  19996. * @property {number} col
  19997. */
  19998. /**
  19999. * Determine the line/col position matching a character offset.
  20000. *
  20001. * Accepts a source string or a CST document as the second parameter. With
  20002. * the latter, starting indices for lines are cached in the document as
  20003. * `lineStarts: number[]`.
  20004. *
  20005. * Returns a one-indexed `{ line, col }` location if found, or
  20006. * `undefined` otherwise.
  20007. *
  20008. * @param {number} offset
  20009. * @param {string|Document|Document[]} cst
  20010. * @returns {?LinePos}
  20011. */
  20012. function getLinePos(offset, cst) {
  20013. if (typeof offset !== 'number' || offset < 0) return null;
  20014. const {
  20015. lineStarts,
  20016. src
  20017. } = getSrcInfo(cst);
  20018. if (!lineStarts || !src || offset > src.length) return null;
  20019. for (let i = 0; i < lineStarts.length; ++i) {
  20020. const start = lineStarts[i];
  20021. if (offset < start) {
  20022. return {
  20023. line: i,
  20024. col: offset - lineStarts[i - 1] + 1
  20025. };
  20026. }
  20027. if (offset === start) return {
  20028. line: i + 1,
  20029. col: 1
  20030. };
  20031. }
  20032. const line = lineStarts.length;
  20033. return {
  20034. line,
  20035. col: offset - lineStarts[line - 1] + 1
  20036. };
  20037. }
  20038. /**
  20039. * Get a specified line from the source.
  20040. *
  20041. * Accepts a source string or a CST document as the second parameter. With
  20042. * the latter, starting indices for lines are cached in the document as
  20043. * `lineStarts: number[]`.
  20044. *
  20045. * Returns the line as a string if found, or `null` otherwise.
  20046. *
  20047. * @param {number} line One-indexed line number
  20048. * @param {string|Document|Document[]} cst
  20049. * @returns {?string}
  20050. */
  20051. function getLine(line, cst) {
  20052. const {
  20053. lineStarts,
  20054. src
  20055. } = getSrcInfo(cst);
  20056. if (!lineStarts || !(line >= 1) || line > lineStarts.length) return null;
  20057. const start = lineStarts[line - 1];
  20058. let end = lineStarts[line]; // undefined for last line; that's ok for slice()
  20059. while (end && end > start && src[end - 1] === '\n') --end;
  20060. return src.slice(start, end);
  20061. }
  20062. /**
  20063. * Pretty-print the starting line from the source indicated by the range `pos`
  20064. *
  20065. * Trims output to `maxWidth` chars while keeping the starting column visible,
  20066. * using `…` at either end to indicate dropped characters.
  20067. *
  20068. * Returns a two-line string (or `null`) with `\n` as separator; the second line
  20069. * will hold appropriately indented `^` marks indicating the column range.
  20070. *
  20071. * @param {Object} pos
  20072. * @param {LinePos} pos.start
  20073. * @param {LinePos} [pos.end]
  20074. * @param {string|Document|Document[]*} cst
  20075. * @param {number} [maxWidth=80]
  20076. * @returns {?string}
  20077. */
  20078. function getPrettyContext({
  20079. start,
  20080. end
  20081. }, cst, maxWidth = 80) {
  20082. let src = getLine(start.line, cst);
  20083. if (!src) return null;
  20084. let {
  20085. col
  20086. } = start;
  20087. if (src.length > maxWidth) {
  20088. if (col <= maxWidth - 10) {
  20089. src = src.substr(0, maxWidth - 1) + '…';
  20090. } else {
  20091. const halfWidth = Math.round(maxWidth / 2);
  20092. if (src.length > col + halfWidth) src = src.substr(0, col + halfWidth - 1) + '…';
  20093. col -= src.length - maxWidth;
  20094. src = '…' + src.substr(1 - maxWidth);
  20095. }
  20096. }
  20097. let errLen = 1;
  20098. let errEnd = '';
  20099. if (end) {
  20100. if (end.line === start.line && col + (end.col - start.col) <= maxWidth + 1) {
  20101. errLen = end.col - start.col;
  20102. } else {
  20103. errLen = Math.min(src.length + 1, maxWidth) - col;
  20104. errEnd = '…';
  20105. }
  20106. }
  20107. const offset = col > 1 ? ' '.repeat(col - 1) : '';
  20108. const err = '^'.repeat(errLen);
  20109. return `${src}\n${offset}${err}${errEnd}`;
  20110. }
  20111. class Range {
  20112. static copy(orig) {
  20113. return new Range(orig.start, orig.end);
  20114. }
  20115. constructor(start, end) {
  20116. this.start = start;
  20117. this.end = end || start;
  20118. }
  20119. isEmpty() {
  20120. return typeof this.start !== 'number' || !this.end || this.end <= this.start;
  20121. }
  20122. /**
  20123. * Set `origStart` and `origEnd` to point to the original source range for
  20124. * this node, which may differ due to dropped CR characters.
  20125. *
  20126. * @param {number[]} cr - Positions of dropped CR characters
  20127. * @param {number} offset - Starting index of `cr` from the last call
  20128. * @returns {number} - The next offset, matching the one found for `origStart`
  20129. */
  20130. setOrigRange(cr, offset) {
  20131. const {
  20132. start,
  20133. end
  20134. } = this;
  20135. if (cr.length === 0 || end <= cr[0]) {
  20136. this.origStart = start;
  20137. this.origEnd = end;
  20138. return offset;
  20139. }
  20140. let i = offset;
  20141. while (i < cr.length) {
  20142. if (cr[i] > start) break;else ++i;
  20143. }
  20144. this.origStart = start + i;
  20145. const nextOffset = i;
  20146. while (i < cr.length) {
  20147. // if end was at \n, it should now be at \r
  20148. if (cr[i] >= end) break;else ++i;
  20149. }
  20150. this.origEnd = end + i;
  20151. return nextOffset;
  20152. }
  20153. }
  20154. /** Root class of all nodes */
  20155. class Node$2 {
  20156. static addStringTerminator(src, offset, str) {
  20157. if (str[str.length - 1] === '\n') return str;
  20158. const next = Node$2.endOfWhiteSpace(src, offset);
  20159. return next >= src.length || src[next] === '\n' ? str + '\n' : str;
  20160. } // ^(---|...)
  20161. static atDocumentBoundary(src, offset, sep) {
  20162. const ch0 = src[offset];
  20163. if (!ch0) return true;
  20164. const prev = src[offset - 1];
  20165. if (prev && prev !== '\n') return false;
  20166. if (sep) {
  20167. if (ch0 !== sep) return false;
  20168. } else {
  20169. if (ch0 !== Char.DIRECTIVES_END && ch0 !== Char.DOCUMENT_END) return false;
  20170. }
  20171. const ch1 = src[offset + 1];
  20172. const ch2 = src[offset + 2];
  20173. if (ch1 !== ch0 || ch2 !== ch0) return false;
  20174. const ch3 = src[offset + 3];
  20175. return !ch3 || ch3 === '\n' || ch3 === '\t' || ch3 === ' ';
  20176. }
  20177. static endOfIdentifier(src, offset) {
  20178. let ch = src[offset];
  20179. const isVerbatim = ch === '<';
  20180. const notOk = isVerbatim ? ['\n', '\t', ' ', '>'] : ['\n', '\t', ' ', '[', ']', '{', '}', ','];
  20181. while (ch && notOk.indexOf(ch) === -1) ch = src[offset += 1];
  20182. if (isVerbatim && ch === '>') offset += 1;
  20183. return offset;
  20184. }
  20185. static endOfIndent(src, offset) {
  20186. let ch = src[offset];
  20187. while (ch === ' ') ch = src[offset += 1];
  20188. return offset;
  20189. }
  20190. static endOfLine(src, offset) {
  20191. let ch = src[offset];
  20192. while (ch && ch !== '\n') ch = src[offset += 1];
  20193. return offset;
  20194. }
  20195. static endOfWhiteSpace(src, offset) {
  20196. let ch = src[offset];
  20197. while (ch === '\t' || ch === ' ') ch = src[offset += 1];
  20198. return offset;
  20199. }
  20200. static startOfLine(src, offset) {
  20201. let ch = src[offset - 1];
  20202. if (ch === '\n') return offset;
  20203. while (ch && ch !== '\n') ch = src[offset -= 1];
  20204. return offset + 1;
  20205. }
  20206. /**
  20207. * End of indentation, or null if the line's indent level is not more
  20208. * than `indent`
  20209. *
  20210. * @param {string} src
  20211. * @param {number} indent
  20212. * @param {number} lineStart
  20213. * @returns {?number}
  20214. */
  20215. static endOfBlockIndent(src, indent, lineStart) {
  20216. const inEnd = Node$2.endOfIndent(src, lineStart);
  20217. if (inEnd > lineStart + indent) {
  20218. return inEnd;
  20219. } else {
  20220. const wsEnd = Node$2.endOfWhiteSpace(src, inEnd);
  20221. const ch = src[wsEnd];
  20222. if (!ch || ch === '\n') return wsEnd;
  20223. }
  20224. return null;
  20225. }
  20226. static atBlank(src, offset, endAsBlank) {
  20227. const ch = src[offset];
  20228. return ch === '\n' || ch === '\t' || ch === ' ' || endAsBlank && !ch;
  20229. }
  20230. static nextNodeIsIndented(ch, indentDiff, indicatorAsIndent) {
  20231. if (!ch || indentDiff < 0) return false;
  20232. if (indentDiff > 0) return true;
  20233. return indicatorAsIndent && ch === '-';
  20234. } // should be at line or string end, or at next non-whitespace char
  20235. static normalizeOffset(src, offset) {
  20236. const ch = src[offset];
  20237. return !ch ? offset : ch !== '\n' && src[offset - 1] === '\n' ? offset - 1 : Node$2.endOfWhiteSpace(src, offset);
  20238. } // fold single newline into space, multiple newlines to N - 1 newlines
  20239. // presumes src[offset] === '\n'
  20240. static foldNewline(src, offset, indent) {
  20241. let inCount = 0;
  20242. let error = false;
  20243. let fold = '';
  20244. let ch = src[offset + 1];
  20245. while (ch === ' ' || ch === '\t' || ch === '\n') {
  20246. switch (ch) {
  20247. case '\n':
  20248. inCount = 0;
  20249. offset += 1;
  20250. fold += '\n';
  20251. break;
  20252. case '\t':
  20253. if (inCount <= indent) error = true;
  20254. offset = Node$2.endOfWhiteSpace(src, offset + 2) - 1;
  20255. break;
  20256. case ' ':
  20257. inCount += 1;
  20258. offset += 1;
  20259. break;
  20260. }
  20261. ch = src[offset + 1];
  20262. }
  20263. if (!fold) fold = ' ';
  20264. if (ch && inCount <= indent) error = true;
  20265. return {
  20266. fold,
  20267. offset,
  20268. error
  20269. };
  20270. }
  20271. constructor(type, props, context) {
  20272. Object.defineProperty(this, 'context', {
  20273. value: context || null,
  20274. writable: true
  20275. });
  20276. this.error = null;
  20277. this.range = null;
  20278. this.valueRange = null;
  20279. this.props = props || [];
  20280. this.type = type;
  20281. this.value = null;
  20282. }
  20283. getPropValue(idx, key, skipKey) {
  20284. if (!this.context) return null;
  20285. const {
  20286. src
  20287. } = this.context;
  20288. const prop = this.props[idx];
  20289. return prop && src[prop.start] === key ? src.slice(prop.start + (skipKey ? 1 : 0), prop.end) : null;
  20290. }
  20291. get anchor() {
  20292. for (let i = 0; i < this.props.length; ++i) {
  20293. const anchor = this.getPropValue(i, Char.ANCHOR, true);
  20294. if (anchor != null) return anchor;
  20295. }
  20296. return null;
  20297. }
  20298. get comment() {
  20299. const comments = [];
  20300. for (let i = 0; i < this.props.length; ++i) {
  20301. const comment = this.getPropValue(i, Char.COMMENT, true);
  20302. if (comment != null) comments.push(comment);
  20303. }
  20304. return comments.length > 0 ? comments.join('\n') : null;
  20305. }
  20306. commentHasRequiredWhitespace(start) {
  20307. const {
  20308. src
  20309. } = this.context;
  20310. if (this.header && start === this.header.end) return false;
  20311. if (!this.valueRange) return false;
  20312. const {
  20313. end
  20314. } = this.valueRange;
  20315. return start !== end || Node$2.atBlank(src, end - 1);
  20316. }
  20317. get hasComment() {
  20318. if (this.context) {
  20319. const {
  20320. src
  20321. } = this.context;
  20322. for (let i = 0; i < this.props.length; ++i) {
  20323. if (src[this.props[i].start] === Char.COMMENT) return true;
  20324. }
  20325. }
  20326. return false;
  20327. }
  20328. get hasProps() {
  20329. if (this.context) {
  20330. const {
  20331. src
  20332. } = this.context;
  20333. for (let i = 0; i < this.props.length; ++i) {
  20334. if (src[this.props[i].start] !== Char.COMMENT) return true;
  20335. }
  20336. }
  20337. return false;
  20338. }
  20339. get includesTrailingLines() {
  20340. return false;
  20341. }
  20342. get jsonLike() {
  20343. const jsonLikeTypes = [Type.FLOW_MAP, Type.FLOW_SEQ, Type.QUOTE_DOUBLE, Type.QUOTE_SINGLE];
  20344. return jsonLikeTypes.indexOf(this.type) !== -1;
  20345. }
  20346. get rangeAsLinePos() {
  20347. if (!this.range || !this.context) return undefined;
  20348. const start = getLinePos(this.range.start, this.context.root);
  20349. if (!start) return undefined;
  20350. const end = getLinePos(this.range.end, this.context.root);
  20351. return {
  20352. start,
  20353. end
  20354. };
  20355. }
  20356. get rawValue() {
  20357. if (!this.valueRange || !this.context) return null;
  20358. const {
  20359. start,
  20360. end
  20361. } = this.valueRange;
  20362. return this.context.src.slice(start, end);
  20363. }
  20364. get tag() {
  20365. for (let i = 0; i < this.props.length; ++i) {
  20366. const tag = this.getPropValue(i, Char.TAG, false);
  20367. if (tag != null) {
  20368. if (tag[1] === '<') {
  20369. return {
  20370. verbatim: tag.slice(2, -1)
  20371. };
  20372. } else {
  20373. // eslint-disable-next-line no-unused-vars
  20374. const [_, handle, suffix] = tag.match(/^(.*!)([^!]*)$/);
  20375. return {
  20376. handle,
  20377. suffix
  20378. };
  20379. }
  20380. }
  20381. }
  20382. return null;
  20383. }
  20384. get valueRangeContainsNewline() {
  20385. if (!this.valueRange || !this.context) return false;
  20386. const {
  20387. start,
  20388. end
  20389. } = this.valueRange;
  20390. const {
  20391. src
  20392. } = this.context;
  20393. for (let i = start; i < end; ++i) {
  20394. if (src[i] === '\n') return true;
  20395. }
  20396. return false;
  20397. }
  20398. parseComment(start) {
  20399. const {
  20400. src
  20401. } = this.context;
  20402. if (src[start] === Char.COMMENT) {
  20403. const end = Node$2.endOfLine(src, start + 1);
  20404. const commentRange = new Range(start, end);
  20405. this.props.push(commentRange);
  20406. return end;
  20407. }
  20408. return start;
  20409. }
  20410. /**
  20411. * Populates the `origStart` and `origEnd` values of all ranges for this
  20412. * node. Extended by child classes to handle descendant nodes.
  20413. *
  20414. * @param {number[]} cr - Positions of dropped CR characters
  20415. * @param {number} offset - Starting index of `cr` from the last call
  20416. * @returns {number} - The next offset, matching the one found for `origStart`
  20417. */
  20418. setOrigRanges(cr, offset) {
  20419. if (this.range) offset = this.range.setOrigRange(cr, offset);
  20420. if (this.valueRange) this.valueRange.setOrigRange(cr, offset);
  20421. this.props.forEach(prop => prop.setOrigRange(cr, offset));
  20422. return offset;
  20423. }
  20424. toString() {
  20425. const {
  20426. context: {
  20427. src
  20428. },
  20429. range,
  20430. value
  20431. } = this;
  20432. if (value != null) return value;
  20433. const str = src.slice(range.start, range.end);
  20434. return Node$2.addStringTerminator(src, range.end, str);
  20435. }
  20436. }
  20437. class YAMLError extends Error {
  20438. constructor(name, source, message) {
  20439. if (!message || !(source instanceof Node$2)) throw new Error(`Invalid arguments for new ${name}`);
  20440. super();
  20441. this.name = name;
  20442. this.message = message;
  20443. this.source = source;
  20444. }
  20445. makePretty() {
  20446. if (!this.source) return;
  20447. this.nodeType = this.source.type;
  20448. const cst = this.source.context && this.source.context.root;
  20449. if (typeof this.offset === 'number') {
  20450. this.range = new Range(this.offset, this.offset + 1);
  20451. const start = cst && getLinePos(this.offset, cst);
  20452. if (start) {
  20453. const end = {
  20454. line: start.line,
  20455. col: start.col + 1
  20456. };
  20457. this.linePos = {
  20458. start,
  20459. end
  20460. };
  20461. }
  20462. delete this.offset;
  20463. } else {
  20464. this.range = this.source.range;
  20465. this.linePos = this.source.rangeAsLinePos;
  20466. }
  20467. if (this.linePos) {
  20468. const {
  20469. line,
  20470. col
  20471. } = this.linePos.start;
  20472. this.message += ` at line ${line}, column ${col}`;
  20473. const ctx = cst && getPrettyContext(this.linePos, cst);
  20474. if (ctx) this.message += `:\n\n${ctx}\n`;
  20475. }
  20476. delete this.source;
  20477. }
  20478. }
  20479. class YAMLReferenceError extends YAMLError {
  20480. constructor(source, message) {
  20481. super('YAMLReferenceError', source, message);
  20482. }
  20483. }
  20484. class YAMLSemanticError extends YAMLError {
  20485. constructor(source, message) {
  20486. super('YAMLSemanticError', source, message);
  20487. }
  20488. }
  20489. class YAMLSyntaxError extends YAMLError {
  20490. constructor(source, message) {
  20491. super('YAMLSyntaxError', source, message);
  20492. }
  20493. }
  20494. class YAMLWarning extends YAMLError {
  20495. constructor(source, message) {
  20496. super('YAMLWarning', source, message);
  20497. }
  20498. }
  20499. function _defineProperty(obj, key, value) {
  20500. if (key in obj) {
  20501. Object.defineProperty(obj, key, {
  20502. value: value,
  20503. enumerable: true,
  20504. configurable: true,
  20505. writable: true
  20506. });
  20507. } else {
  20508. obj[key] = value;
  20509. }
  20510. return obj;
  20511. }
  20512. class PlainValue$6 extends Node$2 {
  20513. static endOfLine(src, start, inFlow) {
  20514. let ch = src[start];
  20515. let offset = start;
  20516. while (ch && ch !== '\n') {
  20517. if (inFlow && (ch === '[' || ch === ']' || ch === '{' || ch === '}' || ch === ',')) break;
  20518. const next = src[offset + 1];
  20519. if (ch === ':' && (!next || next === '\n' || next === '\t' || next === ' ' || inFlow && next === ',')) break;
  20520. if ((ch === ' ' || ch === '\t') && next === '#') break;
  20521. offset += 1;
  20522. ch = next;
  20523. }
  20524. return offset;
  20525. }
  20526. get strValue() {
  20527. if (!this.valueRange || !this.context) return null;
  20528. let {
  20529. start,
  20530. end
  20531. } = this.valueRange;
  20532. const {
  20533. src
  20534. } = this.context;
  20535. let ch = src[end - 1];
  20536. while (start < end && (ch === '\n' || ch === '\t' || ch === ' ')) ch = src[--end - 1];
  20537. let str = '';
  20538. for (let i = start; i < end; ++i) {
  20539. const ch = src[i];
  20540. if (ch === '\n') {
  20541. const {
  20542. fold,
  20543. offset
  20544. } = Node$2.foldNewline(src, i, -1);
  20545. str += fold;
  20546. i = offset;
  20547. } else if (ch === ' ' || ch === '\t') {
  20548. // trim trailing whitespace
  20549. const wsStart = i;
  20550. let next = src[i + 1];
  20551. while (i < end && (next === ' ' || next === '\t')) {
  20552. i += 1;
  20553. next = src[i + 1];
  20554. }
  20555. if (next !== '\n') str += i > wsStart ? src.slice(wsStart, i + 1) : ch;
  20556. } else {
  20557. str += ch;
  20558. }
  20559. }
  20560. const ch0 = src[start];
  20561. switch (ch0) {
  20562. case '\t':
  20563. {
  20564. const msg = 'Plain value cannot start with a tab character';
  20565. const errors = [new YAMLSemanticError(this, msg)];
  20566. return {
  20567. errors,
  20568. str
  20569. };
  20570. }
  20571. case '@':
  20572. case '`':
  20573. {
  20574. const msg = `Plain value cannot start with reserved character ${ch0}`;
  20575. const errors = [new YAMLSemanticError(this, msg)];
  20576. return {
  20577. errors,
  20578. str
  20579. };
  20580. }
  20581. default:
  20582. return str;
  20583. }
  20584. }
  20585. parseBlockValue(start) {
  20586. const {
  20587. indent,
  20588. inFlow,
  20589. src
  20590. } = this.context;
  20591. let offset = start;
  20592. let valueEnd = start;
  20593. for (let ch = src[offset]; ch === '\n'; ch = src[offset]) {
  20594. if (Node$2.atDocumentBoundary(src, offset + 1)) break;
  20595. const end = Node$2.endOfBlockIndent(src, indent, offset + 1);
  20596. if (end === null || src[end] === '#') break;
  20597. if (src[end] === '\n') {
  20598. offset = end;
  20599. } else {
  20600. valueEnd = PlainValue$6.endOfLine(src, end, inFlow);
  20601. offset = valueEnd;
  20602. }
  20603. }
  20604. if (this.valueRange.isEmpty()) this.valueRange.start = start;
  20605. this.valueRange.end = valueEnd;
  20606. return valueEnd;
  20607. }
  20608. /**
  20609. * Parses a plain value from the source
  20610. *
  20611. * Accepted forms are:
  20612. * ```
  20613. * #comment
  20614. *
  20615. * first line
  20616. *
  20617. * first line #comment
  20618. *
  20619. * first line
  20620. * block
  20621. * lines
  20622. *
  20623. * #comment
  20624. * block
  20625. * lines
  20626. * ```
  20627. * where block lines are empty or have an indent level greater than `indent`.
  20628. *
  20629. * @param {ParseContext} context
  20630. * @param {number} start - Index of first character
  20631. * @returns {number} - Index of the character after this scalar, may be `\n`
  20632. */
  20633. parse(context, start) {
  20634. this.context = context;
  20635. const {
  20636. inFlow,
  20637. src
  20638. } = context;
  20639. let offset = start;
  20640. const ch = src[offset];
  20641. if (ch && ch !== '#' && ch !== '\n') {
  20642. offset = PlainValue$6.endOfLine(src, start, inFlow);
  20643. }
  20644. this.valueRange = new Range(start, offset);
  20645. offset = Node$2.endOfWhiteSpace(src, offset);
  20646. offset = this.parseComment(offset);
  20647. if (!this.hasComment || this.valueRange.isEmpty()) {
  20648. offset = this.parseBlockValue(offset);
  20649. }
  20650. return offset;
  20651. }
  20652. }
  20653. PlainValueEc8e588e.Char = Char;
  20654. PlainValueEc8e588e.Node = Node$2;
  20655. PlainValueEc8e588e.PlainValue = PlainValue$6;
  20656. PlainValueEc8e588e.Range = Range;
  20657. PlainValueEc8e588e.Type = Type;
  20658. PlainValueEc8e588e.YAMLError = YAMLError;
  20659. PlainValueEc8e588e.YAMLReferenceError = YAMLReferenceError;
  20660. PlainValueEc8e588e.YAMLSemanticError = YAMLSemanticError;
  20661. PlainValueEc8e588e.YAMLSyntaxError = YAMLSyntaxError;
  20662. PlainValueEc8e588e.YAMLWarning = YAMLWarning;
  20663. PlainValueEc8e588e._defineProperty = _defineProperty;
  20664. PlainValueEc8e588e.defaultTagPrefix = defaultTagPrefix;
  20665. PlainValueEc8e588e.defaultTags = defaultTags;
  20666. var PlainValue$5 = PlainValueEc8e588e;
  20667. class BlankLine extends PlainValue$5.Node {
  20668. constructor() {
  20669. super(PlainValue$5.Type.BLANK_LINE);
  20670. }
  20671. /* istanbul ignore next */
  20672. get includesTrailingLines() {
  20673. // This is never called from anywhere, but if it were,
  20674. // this is the value it should return.
  20675. return true;
  20676. }
  20677. /**
  20678. * Parses a blank line from the source
  20679. *
  20680. * @param {ParseContext} context
  20681. * @param {number} start - Index of first \n character
  20682. * @returns {number} - Index of the character after this
  20683. */
  20684. parse(context, start) {
  20685. this.context = context;
  20686. this.range = new PlainValue$5.Range(start, start + 1);
  20687. return start + 1;
  20688. }
  20689. }
  20690. class CollectionItem extends PlainValue$5.Node {
  20691. constructor(type, props) {
  20692. super(type, props);
  20693. this.node = null;
  20694. }
  20695. get includesTrailingLines() {
  20696. return !!this.node && this.node.includesTrailingLines;
  20697. }
  20698. /**
  20699. * @param {ParseContext} context
  20700. * @param {number} start - Index of first character
  20701. * @returns {number} - Index of the character after this
  20702. */
  20703. parse(context, start) {
  20704. this.context = context;
  20705. const {
  20706. parseNode,
  20707. src
  20708. } = context;
  20709. let {
  20710. atLineStart,
  20711. lineStart
  20712. } = context;
  20713. if (!atLineStart && this.type === PlainValue$5.Type.SEQ_ITEM) this.error = new PlainValue$5.YAMLSemanticError(this, 'Sequence items must not have preceding content on the same line');
  20714. const indent = atLineStart ? start - lineStart : context.indent;
  20715. let offset = PlainValue$5.Node.endOfWhiteSpace(src, start + 1);
  20716. let ch = src[offset];
  20717. const inlineComment = ch === '#';
  20718. const comments = [];
  20719. let blankLine = null;
  20720. while (ch === '\n' || ch === '#') {
  20721. if (ch === '#') {
  20722. const end = PlainValue$5.Node.endOfLine(src, offset + 1);
  20723. comments.push(new PlainValue$5.Range(offset, end));
  20724. offset = end;
  20725. } else {
  20726. atLineStart = true;
  20727. lineStart = offset + 1;
  20728. const wsEnd = PlainValue$5.Node.endOfWhiteSpace(src, lineStart);
  20729. if (src[wsEnd] === '\n' && comments.length === 0) {
  20730. blankLine = new BlankLine();
  20731. lineStart = blankLine.parse({
  20732. src
  20733. }, lineStart);
  20734. }
  20735. offset = PlainValue$5.Node.endOfIndent(src, lineStart);
  20736. }
  20737. ch = src[offset];
  20738. }
  20739. if (PlainValue$5.Node.nextNodeIsIndented(ch, offset - (lineStart + indent), this.type !== PlainValue$5.Type.SEQ_ITEM)) {
  20740. this.node = parseNode({
  20741. atLineStart,
  20742. inCollection: false,
  20743. indent,
  20744. lineStart,
  20745. parent: this
  20746. }, offset);
  20747. } else if (ch && lineStart > start + 1) {
  20748. offset = lineStart - 1;
  20749. }
  20750. if (this.node) {
  20751. if (blankLine) {
  20752. // Only blank lines preceding non-empty nodes are captured. Note that
  20753. // this means that collection item range start indices do not always
  20754. // increase monotonically. -- eemeli/yaml#126
  20755. const items = context.parent.items || context.parent.contents;
  20756. if (items) items.push(blankLine);
  20757. }
  20758. if (comments.length) Array.prototype.push.apply(this.props, comments);
  20759. offset = this.node.range.end;
  20760. } else {
  20761. if (inlineComment) {
  20762. const c = comments[0];
  20763. this.props.push(c);
  20764. offset = c.end;
  20765. } else {
  20766. offset = PlainValue$5.Node.endOfLine(src, start + 1);
  20767. }
  20768. }
  20769. const end = this.node ? this.node.valueRange.end : offset;
  20770. this.valueRange = new PlainValue$5.Range(start, end);
  20771. return offset;
  20772. }
  20773. setOrigRanges(cr, offset) {
  20774. offset = super.setOrigRanges(cr, offset);
  20775. return this.node ? this.node.setOrigRanges(cr, offset) : offset;
  20776. }
  20777. toString() {
  20778. const {
  20779. context: {
  20780. src
  20781. },
  20782. node,
  20783. range,
  20784. value
  20785. } = this;
  20786. if (value != null) return value;
  20787. const str = node ? src.slice(range.start, node.range.start) + String(node) : src.slice(range.start, range.end);
  20788. return PlainValue$5.Node.addStringTerminator(src, range.end, str);
  20789. }
  20790. }
  20791. class Comment extends PlainValue$5.Node {
  20792. constructor() {
  20793. super(PlainValue$5.Type.COMMENT);
  20794. }
  20795. /**
  20796. * Parses a comment line from the source
  20797. *
  20798. * @param {ParseContext} context
  20799. * @param {number} start - Index of first character
  20800. * @returns {number} - Index of the character after this scalar
  20801. */
  20802. parse(context, start) {
  20803. this.context = context;
  20804. const offset = this.parseComment(start);
  20805. this.range = new PlainValue$5.Range(start, offset);
  20806. return offset;
  20807. }
  20808. }
  20809. function grabCollectionEndComments(node) {
  20810. let cnode = node;
  20811. while (cnode instanceof CollectionItem) cnode = cnode.node;
  20812. if (!(cnode instanceof Collection$1)) return null;
  20813. const len = cnode.items.length;
  20814. let ci = -1;
  20815. for (let i = len - 1; i >= 0; --i) {
  20816. const n = cnode.items[i];
  20817. if (n.type === PlainValue$5.Type.COMMENT) {
  20818. // Keep sufficiently indented comments with preceding node
  20819. const {
  20820. indent,
  20821. lineStart
  20822. } = n.context;
  20823. if (indent > 0 && n.range.start >= lineStart + indent) break;
  20824. ci = i;
  20825. } else if (n.type === PlainValue$5.Type.BLANK_LINE) ci = i;else break;
  20826. }
  20827. if (ci === -1) return null;
  20828. const ca = cnode.items.splice(ci, len - ci);
  20829. const prevEnd = ca[0].range.start;
  20830. while (true) {
  20831. cnode.range.end = prevEnd;
  20832. if (cnode.valueRange && cnode.valueRange.end > prevEnd) cnode.valueRange.end = prevEnd;
  20833. if (cnode === node) break;
  20834. cnode = cnode.context.parent;
  20835. }
  20836. return ca;
  20837. }
  20838. class Collection$1 extends PlainValue$5.Node {
  20839. static nextContentHasIndent(src, offset, indent) {
  20840. const lineStart = PlainValue$5.Node.endOfLine(src, offset) + 1;
  20841. offset = PlainValue$5.Node.endOfWhiteSpace(src, lineStart);
  20842. const ch = src[offset];
  20843. if (!ch) return false;
  20844. if (offset >= lineStart + indent) return true;
  20845. if (ch !== '#' && ch !== '\n') return false;
  20846. return Collection$1.nextContentHasIndent(src, offset, indent);
  20847. }
  20848. constructor(firstItem) {
  20849. super(firstItem.type === PlainValue$5.Type.SEQ_ITEM ? PlainValue$5.Type.SEQ : PlainValue$5.Type.MAP);
  20850. for (let i = firstItem.props.length - 1; i >= 0; --i) {
  20851. if (firstItem.props[i].start < firstItem.context.lineStart) {
  20852. // props on previous line are assumed by the collection
  20853. this.props = firstItem.props.slice(0, i + 1);
  20854. firstItem.props = firstItem.props.slice(i + 1);
  20855. const itemRange = firstItem.props[0] || firstItem.valueRange;
  20856. firstItem.range.start = itemRange.start;
  20857. break;
  20858. }
  20859. }
  20860. this.items = [firstItem];
  20861. const ec = grabCollectionEndComments(firstItem);
  20862. if (ec) Array.prototype.push.apply(this.items, ec);
  20863. }
  20864. get includesTrailingLines() {
  20865. return this.items.length > 0;
  20866. }
  20867. /**
  20868. * @param {ParseContext} context
  20869. * @param {number} start - Index of first character
  20870. * @returns {number} - Index of the character after this
  20871. */
  20872. parse(context, start) {
  20873. this.context = context;
  20874. const {
  20875. parseNode,
  20876. src
  20877. } = context; // It's easier to recalculate lineStart here rather than tracking down the
  20878. // last context from which to read it -- eemeli/yaml#2
  20879. let lineStart = PlainValue$5.Node.startOfLine(src, start);
  20880. const firstItem = this.items[0]; // First-item context needs to be correct for later comment handling
  20881. // -- eemeli/yaml#17
  20882. firstItem.context.parent = this;
  20883. this.valueRange = PlainValue$5.Range.copy(firstItem.valueRange);
  20884. const indent = firstItem.range.start - firstItem.context.lineStart;
  20885. let offset = start;
  20886. offset = PlainValue$5.Node.normalizeOffset(src, offset);
  20887. let ch = src[offset];
  20888. let atLineStart = PlainValue$5.Node.endOfWhiteSpace(src, lineStart) === offset;
  20889. let prevIncludesTrailingLines = false;
  20890. while (ch) {
  20891. while (ch === '\n' || ch === '#') {
  20892. if (atLineStart && ch === '\n' && !prevIncludesTrailingLines) {
  20893. const blankLine = new BlankLine();
  20894. offset = blankLine.parse({
  20895. src
  20896. }, offset);
  20897. this.valueRange.end = offset;
  20898. if (offset >= src.length) {
  20899. ch = null;
  20900. break;
  20901. }
  20902. this.items.push(blankLine);
  20903. offset -= 1; // blankLine.parse() consumes terminal newline
  20904. } else if (ch === '#') {
  20905. if (offset < lineStart + indent && !Collection$1.nextContentHasIndent(src, offset, indent)) {
  20906. return offset;
  20907. }
  20908. const comment = new Comment();
  20909. offset = comment.parse({
  20910. indent,
  20911. lineStart,
  20912. src
  20913. }, offset);
  20914. this.items.push(comment);
  20915. this.valueRange.end = offset;
  20916. if (offset >= src.length) {
  20917. ch = null;
  20918. break;
  20919. }
  20920. }
  20921. lineStart = offset + 1;
  20922. offset = PlainValue$5.Node.endOfIndent(src, lineStart);
  20923. if (PlainValue$5.Node.atBlank(src, offset)) {
  20924. const wsEnd = PlainValue$5.Node.endOfWhiteSpace(src, offset);
  20925. const next = src[wsEnd];
  20926. if (!next || next === '\n' || next === '#') {
  20927. offset = wsEnd;
  20928. }
  20929. }
  20930. ch = src[offset];
  20931. atLineStart = true;
  20932. }
  20933. if (!ch) {
  20934. break;
  20935. }
  20936. if (offset !== lineStart + indent && (atLineStart || ch !== ':')) {
  20937. if (offset < lineStart + indent) {
  20938. if (lineStart > start) offset = lineStart;
  20939. break;
  20940. } else if (!this.error) {
  20941. const msg = 'All collection items must start at the same column';
  20942. this.error = new PlainValue$5.YAMLSyntaxError(this, msg);
  20943. }
  20944. }
  20945. if (firstItem.type === PlainValue$5.Type.SEQ_ITEM) {
  20946. if (ch !== '-') {
  20947. if (lineStart > start) offset = lineStart;
  20948. break;
  20949. }
  20950. } else if (ch === '-' && !this.error) {
  20951. // map key may start with -, as long as it's followed by a non-whitespace char
  20952. const next = src[offset + 1];
  20953. if (!next || next === '\n' || next === '\t' || next === ' ') {
  20954. const msg = 'A collection cannot be both a mapping and a sequence';
  20955. this.error = new PlainValue$5.YAMLSyntaxError(this, msg);
  20956. }
  20957. }
  20958. const node = parseNode({
  20959. atLineStart,
  20960. inCollection: true,
  20961. indent,
  20962. lineStart,
  20963. parent: this
  20964. }, offset);
  20965. if (!node) return offset; // at next document start
  20966. this.items.push(node);
  20967. this.valueRange.end = node.valueRange.end;
  20968. offset = PlainValue$5.Node.normalizeOffset(src, node.range.end);
  20969. ch = src[offset];
  20970. atLineStart = false;
  20971. prevIncludesTrailingLines = node.includesTrailingLines; // Need to reset lineStart and atLineStart here if preceding node's range
  20972. // has advanced to check the current line's indentation level
  20973. // -- eemeli/yaml#10 & eemeli/yaml#38
  20974. if (ch) {
  20975. let ls = offset - 1;
  20976. let prev = src[ls];
  20977. while (prev === ' ' || prev === '\t') prev = src[--ls];
  20978. if (prev === '\n') {
  20979. lineStart = ls + 1;
  20980. atLineStart = true;
  20981. }
  20982. }
  20983. const ec = grabCollectionEndComments(node);
  20984. if (ec) Array.prototype.push.apply(this.items, ec);
  20985. }
  20986. return offset;
  20987. }
  20988. setOrigRanges(cr, offset) {
  20989. offset = super.setOrigRanges(cr, offset);
  20990. this.items.forEach(node => {
  20991. offset = node.setOrigRanges(cr, offset);
  20992. });
  20993. return offset;
  20994. }
  20995. toString() {
  20996. const {
  20997. context: {
  20998. src
  20999. },
  21000. items,
  21001. range,
  21002. value
  21003. } = this;
  21004. if (value != null) return value;
  21005. let str = src.slice(range.start, items[0].range.start) + String(items[0]);
  21006. for (let i = 1; i < items.length; ++i) {
  21007. const item = items[i];
  21008. const {
  21009. atLineStart,
  21010. indent
  21011. } = item.context;
  21012. if (atLineStart) for (let i = 0; i < indent; ++i) str += ' ';
  21013. str += String(item);
  21014. }
  21015. return PlainValue$5.Node.addStringTerminator(src, range.end, str);
  21016. }
  21017. }
  21018. class Directive extends PlainValue$5.Node {
  21019. constructor() {
  21020. super(PlainValue$5.Type.DIRECTIVE);
  21021. this.name = null;
  21022. }
  21023. get parameters() {
  21024. const raw = this.rawValue;
  21025. return raw ? raw.trim().split(/[ \t]+/) : [];
  21026. }
  21027. parseName(start) {
  21028. const {
  21029. src
  21030. } = this.context;
  21031. let offset = start;
  21032. let ch = src[offset];
  21033. while (ch && ch !== '\n' && ch !== '\t' && ch !== ' ') ch = src[offset += 1];
  21034. this.name = src.slice(start, offset);
  21035. return offset;
  21036. }
  21037. parseParameters(start) {
  21038. const {
  21039. src
  21040. } = this.context;
  21041. let offset = start;
  21042. let ch = src[offset];
  21043. while (ch && ch !== '\n' && ch !== '#') ch = src[offset += 1];
  21044. this.valueRange = new PlainValue$5.Range(start, offset);
  21045. return offset;
  21046. }
  21047. parse(context, start) {
  21048. this.context = context;
  21049. let offset = this.parseName(start + 1);
  21050. offset = this.parseParameters(offset);
  21051. offset = this.parseComment(offset);
  21052. this.range = new PlainValue$5.Range(start, offset);
  21053. return offset;
  21054. }
  21055. }
  21056. class Document$3 extends PlainValue$5.Node {
  21057. static startCommentOrEndBlankLine(src, start) {
  21058. const offset = PlainValue$5.Node.endOfWhiteSpace(src, start);
  21059. const ch = src[offset];
  21060. return ch === '#' || ch === '\n' ? offset : start;
  21061. }
  21062. constructor() {
  21063. super(PlainValue$5.Type.DOCUMENT);
  21064. this.directives = null;
  21065. this.contents = null;
  21066. this.directivesEndMarker = null;
  21067. this.documentEndMarker = null;
  21068. }
  21069. parseDirectives(start) {
  21070. const {
  21071. src
  21072. } = this.context;
  21073. this.directives = [];
  21074. let atLineStart = true;
  21075. let hasDirectives = false;
  21076. let offset = start;
  21077. while (!PlainValue$5.Node.atDocumentBoundary(src, offset, PlainValue$5.Char.DIRECTIVES_END)) {
  21078. offset = Document$3.startCommentOrEndBlankLine(src, offset);
  21079. switch (src[offset]) {
  21080. case '\n':
  21081. if (atLineStart) {
  21082. const blankLine = new BlankLine();
  21083. offset = blankLine.parse({
  21084. src
  21085. }, offset);
  21086. if (offset < src.length) {
  21087. this.directives.push(blankLine);
  21088. }
  21089. } else {
  21090. offset += 1;
  21091. atLineStart = true;
  21092. }
  21093. break;
  21094. case '#':
  21095. {
  21096. const comment = new Comment();
  21097. offset = comment.parse({
  21098. src
  21099. }, offset);
  21100. this.directives.push(comment);
  21101. atLineStart = false;
  21102. }
  21103. break;
  21104. case '%':
  21105. {
  21106. const directive = new Directive();
  21107. offset = directive.parse({
  21108. parent: this,
  21109. src
  21110. }, offset);
  21111. this.directives.push(directive);
  21112. hasDirectives = true;
  21113. atLineStart = false;
  21114. }
  21115. break;
  21116. default:
  21117. if (hasDirectives) {
  21118. this.error = new PlainValue$5.YAMLSemanticError(this, 'Missing directives-end indicator line');
  21119. } else if (this.directives.length > 0) {
  21120. this.contents = this.directives;
  21121. this.directives = [];
  21122. }
  21123. return offset;
  21124. }
  21125. }
  21126. if (src[offset]) {
  21127. this.directivesEndMarker = new PlainValue$5.Range(offset, offset + 3);
  21128. return offset + 3;
  21129. }
  21130. if (hasDirectives) {
  21131. this.error = new PlainValue$5.YAMLSemanticError(this, 'Missing directives-end indicator line');
  21132. } else if (this.directives.length > 0) {
  21133. this.contents = this.directives;
  21134. this.directives = [];
  21135. }
  21136. return offset;
  21137. }
  21138. parseContents(start) {
  21139. const {
  21140. parseNode,
  21141. src
  21142. } = this.context;
  21143. if (!this.contents) this.contents = [];
  21144. let lineStart = start;
  21145. while (src[lineStart - 1] === '-') lineStart -= 1;
  21146. let offset = PlainValue$5.Node.endOfWhiteSpace(src, start);
  21147. let atLineStart = lineStart === start;
  21148. this.valueRange = new PlainValue$5.Range(offset);
  21149. while (!PlainValue$5.Node.atDocumentBoundary(src, offset, PlainValue$5.Char.DOCUMENT_END)) {
  21150. switch (src[offset]) {
  21151. case '\n':
  21152. if (atLineStart) {
  21153. const blankLine = new BlankLine();
  21154. offset = blankLine.parse({
  21155. src
  21156. }, offset);
  21157. if (offset < src.length) {
  21158. this.contents.push(blankLine);
  21159. }
  21160. } else {
  21161. offset += 1;
  21162. atLineStart = true;
  21163. }
  21164. lineStart = offset;
  21165. break;
  21166. case '#':
  21167. {
  21168. const comment = new Comment();
  21169. offset = comment.parse({
  21170. src
  21171. }, offset);
  21172. this.contents.push(comment);
  21173. atLineStart = false;
  21174. }
  21175. break;
  21176. default:
  21177. {
  21178. const iEnd = PlainValue$5.Node.endOfIndent(src, offset);
  21179. const context = {
  21180. atLineStart,
  21181. indent: -1,
  21182. inFlow: false,
  21183. inCollection: false,
  21184. lineStart,
  21185. parent: this
  21186. };
  21187. const node = parseNode(context, iEnd);
  21188. if (!node) return this.valueRange.end = iEnd; // at next document start
  21189. this.contents.push(node);
  21190. offset = node.range.end;
  21191. atLineStart = false;
  21192. const ec = grabCollectionEndComments(node);
  21193. if (ec) Array.prototype.push.apply(this.contents, ec);
  21194. }
  21195. }
  21196. offset = Document$3.startCommentOrEndBlankLine(src, offset);
  21197. }
  21198. this.valueRange.end = offset;
  21199. if (src[offset]) {
  21200. this.documentEndMarker = new PlainValue$5.Range(offset, offset + 3);
  21201. offset += 3;
  21202. if (src[offset]) {
  21203. offset = PlainValue$5.Node.endOfWhiteSpace(src, offset);
  21204. if (src[offset] === '#') {
  21205. const comment = new Comment();
  21206. offset = comment.parse({
  21207. src
  21208. }, offset);
  21209. this.contents.push(comment);
  21210. }
  21211. switch (src[offset]) {
  21212. case '\n':
  21213. offset += 1;
  21214. break;
  21215. case undefined:
  21216. break;
  21217. default:
  21218. this.error = new PlainValue$5.YAMLSyntaxError(this, 'Document end marker line cannot have a non-comment suffix');
  21219. }
  21220. }
  21221. }
  21222. return offset;
  21223. }
  21224. /**
  21225. * @param {ParseContext} context
  21226. * @param {number} start - Index of first character
  21227. * @returns {number} - Index of the character after this
  21228. */
  21229. parse(context, start) {
  21230. context.root = this;
  21231. this.context = context;
  21232. const {
  21233. src
  21234. } = context;
  21235. let offset = src.charCodeAt(start) === 0xfeff ? start + 1 : start; // skip BOM
  21236. offset = this.parseDirectives(offset);
  21237. offset = this.parseContents(offset);
  21238. return offset;
  21239. }
  21240. setOrigRanges(cr, offset) {
  21241. offset = super.setOrigRanges(cr, offset);
  21242. this.directives.forEach(node => {
  21243. offset = node.setOrigRanges(cr, offset);
  21244. });
  21245. if (this.directivesEndMarker) offset = this.directivesEndMarker.setOrigRange(cr, offset);
  21246. this.contents.forEach(node => {
  21247. offset = node.setOrigRanges(cr, offset);
  21248. });
  21249. if (this.documentEndMarker) offset = this.documentEndMarker.setOrigRange(cr, offset);
  21250. return offset;
  21251. }
  21252. toString() {
  21253. const {
  21254. contents,
  21255. directives,
  21256. value
  21257. } = this;
  21258. if (value != null) return value;
  21259. let str = directives.join('');
  21260. if (contents.length > 0) {
  21261. if (directives.length > 0 || contents[0].type === PlainValue$5.Type.COMMENT) str += '---\n';
  21262. str += contents.join('');
  21263. }
  21264. if (str[str.length - 1] !== '\n') str += '\n';
  21265. return str;
  21266. }
  21267. }
  21268. class Alias$1 extends PlainValue$5.Node {
  21269. /**
  21270. * Parses an *alias from the source
  21271. *
  21272. * @param {ParseContext} context
  21273. * @param {number} start - Index of first character
  21274. * @returns {number} - Index of the character after this scalar
  21275. */
  21276. parse(context, start) {
  21277. this.context = context;
  21278. const {
  21279. src
  21280. } = context;
  21281. let offset = PlainValue$5.Node.endOfIdentifier(src, start + 1);
  21282. this.valueRange = new PlainValue$5.Range(start + 1, offset);
  21283. offset = PlainValue$5.Node.endOfWhiteSpace(src, offset);
  21284. offset = this.parseComment(offset);
  21285. return offset;
  21286. }
  21287. }
  21288. const Chomp = {
  21289. CLIP: 'CLIP',
  21290. KEEP: 'KEEP',
  21291. STRIP: 'STRIP'
  21292. };
  21293. class BlockValue extends PlainValue$5.Node {
  21294. constructor(type, props) {
  21295. super(type, props);
  21296. this.blockIndent = null;
  21297. this.chomping = Chomp.CLIP;
  21298. this.header = null;
  21299. }
  21300. get includesTrailingLines() {
  21301. return this.chomping === Chomp.KEEP;
  21302. }
  21303. get strValue() {
  21304. if (!this.valueRange || !this.context) return null;
  21305. let {
  21306. start,
  21307. end
  21308. } = this.valueRange;
  21309. const {
  21310. indent,
  21311. src
  21312. } = this.context;
  21313. if (this.valueRange.isEmpty()) return '';
  21314. let lastNewLine = null;
  21315. let ch = src[end - 1];
  21316. while (ch === '\n' || ch === '\t' || ch === ' ') {
  21317. end -= 1;
  21318. if (end <= start) {
  21319. if (this.chomping === Chomp.KEEP) break;else return ''; // probably never happens
  21320. }
  21321. if (ch === '\n') lastNewLine = end;
  21322. ch = src[end - 1];
  21323. }
  21324. let keepStart = end + 1;
  21325. if (lastNewLine) {
  21326. if (this.chomping === Chomp.KEEP) {
  21327. keepStart = lastNewLine;
  21328. end = this.valueRange.end;
  21329. } else {
  21330. end = lastNewLine;
  21331. }
  21332. }
  21333. const bi = indent + this.blockIndent;
  21334. const folded = this.type === PlainValue$5.Type.BLOCK_FOLDED;
  21335. let atStart = true;
  21336. let str = '';
  21337. let sep = '';
  21338. let prevMoreIndented = false;
  21339. for (let i = start; i < end; ++i) {
  21340. for (let j = 0; j < bi; ++j) {
  21341. if (src[i] !== ' ') break;
  21342. i += 1;
  21343. }
  21344. const ch = src[i];
  21345. if (ch === '\n') {
  21346. if (sep === '\n') str += '\n';else sep = '\n';
  21347. } else {
  21348. const lineEnd = PlainValue$5.Node.endOfLine(src, i);
  21349. const line = src.slice(i, lineEnd);
  21350. i = lineEnd;
  21351. if (folded && (ch === ' ' || ch === '\t') && i < keepStart) {
  21352. if (sep === ' ') sep = '\n';else if (!prevMoreIndented && !atStart && sep === '\n') sep = '\n\n';
  21353. str += sep + line; //+ ((lineEnd < end && src[lineEnd]) || '')
  21354. sep = lineEnd < end && src[lineEnd] || '';
  21355. prevMoreIndented = true;
  21356. } else {
  21357. str += sep + line;
  21358. sep = folded && i < keepStart ? ' ' : '\n';
  21359. prevMoreIndented = false;
  21360. }
  21361. if (atStart && line !== '') atStart = false;
  21362. }
  21363. }
  21364. return this.chomping === Chomp.STRIP ? str : str + '\n';
  21365. }
  21366. parseBlockHeader(start) {
  21367. const {
  21368. src
  21369. } = this.context;
  21370. let offset = start + 1;
  21371. let bi = '';
  21372. while (true) {
  21373. const ch = src[offset];
  21374. switch (ch) {
  21375. case '-':
  21376. this.chomping = Chomp.STRIP;
  21377. break;
  21378. case '+':
  21379. this.chomping = Chomp.KEEP;
  21380. break;
  21381. case '0':
  21382. case '1':
  21383. case '2':
  21384. case '3':
  21385. case '4':
  21386. case '5':
  21387. case '6':
  21388. case '7':
  21389. case '8':
  21390. case '9':
  21391. bi += ch;
  21392. break;
  21393. default:
  21394. this.blockIndent = Number(bi) || null;
  21395. this.header = new PlainValue$5.Range(start, offset);
  21396. return offset;
  21397. }
  21398. offset += 1;
  21399. }
  21400. }
  21401. parseBlockValue(start) {
  21402. const {
  21403. indent,
  21404. src
  21405. } = this.context;
  21406. const explicit = !!this.blockIndent;
  21407. let offset = start;
  21408. let valueEnd = start;
  21409. let minBlockIndent = 1;
  21410. for (let ch = src[offset]; ch === '\n'; ch = src[offset]) {
  21411. offset += 1;
  21412. if (PlainValue$5.Node.atDocumentBoundary(src, offset)) break;
  21413. const end = PlainValue$5.Node.endOfBlockIndent(src, indent, offset); // should not include tab?
  21414. if (end === null) break;
  21415. const ch = src[end];
  21416. const lineIndent = end - (offset + indent);
  21417. if (!this.blockIndent) {
  21418. // no explicit block indent, none yet detected
  21419. if (src[end] !== '\n') {
  21420. // first line with non-whitespace content
  21421. if (lineIndent < minBlockIndent) {
  21422. const msg = 'Block scalars with more-indented leading empty lines must use an explicit indentation indicator';
  21423. this.error = new PlainValue$5.YAMLSemanticError(this, msg);
  21424. }
  21425. this.blockIndent = lineIndent;
  21426. } else if (lineIndent > minBlockIndent) {
  21427. // empty line with more whitespace
  21428. minBlockIndent = lineIndent;
  21429. }
  21430. } else if (ch && ch !== '\n' && lineIndent < this.blockIndent) {
  21431. if (src[end] === '#') break;
  21432. if (!this.error) {
  21433. const src = explicit ? 'explicit indentation indicator' : 'first line';
  21434. const msg = `Block scalars must not be less indented than their ${src}`;
  21435. this.error = new PlainValue$5.YAMLSemanticError(this, msg);
  21436. }
  21437. }
  21438. if (src[end] === '\n') {
  21439. offset = end;
  21440. } else {
  21441. offset = valueEnd = PlainValue$5.Node.endOfLine(src, end);
  21442. }
  21443. }
  21444. if (this.chomping !== Chomp.KEEP) {
  21445. offset = src[valueEnd] ? valueEnd + 1 : valueEnd;
  21446. }
  21447. this.valueRange = new PlainValue$5.Range(start + 1, offset);
  21448. return offset;
  21449. }
  21450. /**
  21451. * Parses a block value from the source
  21452. *
  21453. * Accepted forms are:
  21454. * ```
  21455. * BS
  21456. * block
  21457. * lines
  21458. *
  21459. * BS #comment
  21460. * block
  21461. * lines
  21462. * ```
  21463. * where the block style BS matches the regexp `[|>][-+1-9]*` and block lines
  21464. * are empty or have an indent level greater than `indent`.
  21465. *
  21466. * @param {ParseContext} context
  21467. * @param {number} start - Index of first character
  21468. * @returns {number} - Index of the character after this block
  21469. */
  21470. parse(context, start) {
  21471. this.context = context;
  21472. const {
  21473. src
  21474. } = context;
  21475. let offset = this.parseBlockHeader(start);
  21476. offset = PlainValue$5.Node.endOfWhiteSpace(src, offset);
  21477. offset = this.parseComment(offset);
  21478. offset = this.parseBlockValue(offset);
  21479. return offset;
  21480. }
  21481. setOrigRanges(cr, offset) {
  21482. offset = super.setOrigRanges(cr, offset);
  21483. return this.header ? this.header.setOrigRange(cr, offset) : offset;
  21484. }
  21485. }
  21486. class FlowCollection extends PlainValue$5.Node {
  21487. constructor(type, props) {
  21488. super(type, props);
  21489. this.items = null;
  21490. }
  21491. prevNodeIsJsonLike(idx = this.items.length) {
  21492. const node = this.items[idx - 1];
  21493. return !!node && (node.jsonLike || node.type === PlainValue$5.Type.COMMENT && this.prevNodeIsJsonLike(idx - 1));
  21494. }
  21495. /**
  21496. * @param {ParseContext} context
  21497. * @param {number} start - Index of first character
  21498. * @returns {number} - Index of the character after this
  21499. */
  21500. parse(context, start) {
  21501. this.context = context;
  21502. const {
  21503. parseNode,
  21504. src
  21505. } = context;
  21506. let {
  21507. indent,
  21508. lineStart
  21509. } = context;
  21510. let char = src[start]; // { or [
  21511. this.items = [{
  21512. char,
  21513. offset: start
  21514. }];
  21515. let offset = PlainValue$5.Node.endOfWhiteSpace(src, start + 1);
  21516. char = src[offset];
  21517. while (char && char !== ']' && char !== '}') {
  21518. switch (char) {
  21519. case '\n':
  21520. {
  21521. lineStart = offset + 1;
  21522. const wsEnd = PlainValue$5.Node.endOfWhiteSpace(src, lineStart);
  21523. if (src[wsEnd] === '\n') {
  21524. const blankLine = new BlankLine();
  21525. lineStart = blankLine.parse({
  21526. src
  21527. }, lineStart);
  21528. this.items.push(blankLine);
  21529. }
  21530. offset = PlainValue$5.Node.endOfIndent(src, lineStart);
  21531. if (offset <= lineStart + indent) {
  21532. char = src[offset];
  21533. if (offset < lineStart + indent || char !== ']' && char !== '}') {
  21534. const msg = 'Insufficient indentation in flow collection';
  21535. this.error = new PlainValue$5.YAMLSemanticError(this, msg);
  21536. }
  21537. }
  21538. }
  21539. break;
  21540. case ',':
  21541. {
  21542. this.items.push({
  21543. char,
  21544. offset
  21545. });
  21546. offset += 1;
  21547. }
  21548. break;
  21549. case '#':
  21550. {
  21551. const comment = new Comment();
  21552. offset = comment.parse({
  21553. src
  21554. }, offset);
  21555. this.items.push(comment);
  21556. }
  21557. break;
  21558. case '?':
  21559. case ':':
  21560. {
  21561. const next = src[offset + 1];
  21562. if (next === '\n' || next === '\t' || next === ' ' || next === ',' || // in-flow : after JSON-like key does not need to be followed by whitespace
  21563. char === ':' && this.prevNodeIsJsonLike()) {
  21564. this.items.push({
  21565. char,
  21566. offset
  21567. });
  21568. offset += 1;
  21569. break;
  21570. }
  21571. }
  21572. // fallthrough
  21573. default:
  21574. {
  21575. const node = parseNode({
  21576. atLineStart: false,
  21577. inCollection: false,
  21578. inFlow: true,
  21579. indent: -1,
  21580. lineStart,
  21581. parent: this
  21582. }, offset);
  21583. if (!node) {
  21584. // at next document start
  21585. this.valueRange = new PlainValue$5.Range(start, offset);
  21586. return offset;
  21587. }
  21588. this.items.push(node);
  21589. offset = PlainValue$5.Node.normalizeOffset(src, node.range.end);
  21590. }
  21591. }
  21592. offset = PlainValue$5.Node.endOfWhiteSpace(src, offset);
  21593. char = src[offset];
  21594. }
  21595. this.valueRange = new PlainValue$5.Range(start, offset + 1);
  21596. if (char) {
  21597. this.items.push({
  21598. char,
  21599. offset
  21600. });
  21601. offset = PlainValue$5.Node.endOfWhiteSpace(src, offset + 1);
  21602. offset = this.parseComment(offset);
  21603. }
  21604. return offset;
  21605. }
  21606. setOrigRanges(cr, offset) {
  21607. offset = super.setOrigRanges(cr, offset);
  21608. this.items.forEach(node => {
  21609. if (node instanceof PlainValue$5.Node) {
  21610. offset = node.setOrigRanges(cr, offset);
  21611. } else if (cr.length === 0) {
  21612. node.origOffset = node.offset;
  21613. } else {
  21614. let i = offset;
  21615. while (i < cr.length) {
  21616. if (cr[i] > node.offset) break;else ++i;
  21617. }
  21618. node.origOffset = node.offset + i;
  21619. offset = i;
  21620. }
  21621. });
  21622. return offset;
  21623. }
  21624. toString() {
  21625. const {
  21626. context: {
  21627. src
  21628. },
  21629. items,
  21630. range,
  21631. value
  21632. } = this;
  21633. if (value != null) return value;
  21634. const nodes = items.filter(item => item instanceof PlainValue$5.Node);
  21635. let str = '';
  21636. let prevEnd = range.start;
  21637. nodes.forEach(node => {
  21638. const prefix = src.slice(prevEnd, node.range.start);
  21639. prevEnd = node.range.end;
  21640. str += prefix + String(node);
  21641. if (str[str.length - 1] === '\n' && src[prevEnd - 1] !== '\n' && src[prevEnd] === '\n') {
  21642. // Comment range does not include the terminal newline, but its
  21643. // stringified value does. Without this fix, newlines at comment ends
  21644. // get duplicated.
  21645. prevEnd += 1;
  21646. }
  21647. });
  21648. str += src.slice(prevEnd, range.end);
  21649. return PlainValue$5.Node.addStringTerminator(src, range.end, str);
  21650. }
  21651. }
  21652. class QuoteDouble extends PlainValue$5.Node {
  21653. static endOfQuote(src, offset) {
  21654. let ch = src[offset];
  21655. while (ch && ch !== '"') {
  21656. offset += ch === '\\' ? 2 : 1;
  21657. ch = src[offset];
  21658. }
  21659. return offset + 1;
  21660. }
  21661. /**
  21662. * @returns {string | { str: string, errors: YAMLSyntaxError[] }}
  21663. */
  21664. get strValue() {
  21665. if (!this.valueRange || !this.context) return null;
  21666. const errors = [];
  21667. const {
  21668. start,
  21669. end
  21670. } = this.valueRange;
  21671. const {
  21672. indent,
  21673. src
  21674. } = this.context;
  21675. if (src[end - 1] !== '"') errors.push(new PlainValue$5.YAMLSyntaxError(this, 'Missing closing "quote')); // Using String#replace is too painful with escaped newlines preceded by
  21676. // escaped backslashes; also, this should be faster.
  21677. let str = '';
  21678. for (let i = start + 1; i < end - 1; ++i) {
  21679. const ch = src[i];
  21680. if (ch === '\n') {
  21681. if (PlainValue$5.Node.atDocumentBoundary(src, i + 1)) errors.push(new PlainValue$5.YAMLSemanticError(this, 'Document boundary indicators are not allowed within string values'));
  21682. const {
  21683. fold,
  21684. offset,
  21685. error
  21686. } = PlainValue$5.Node.foldNewline(src, i, indent);
  21687. str += fold;
  21688. i = offset;
  21689. if (error) errors.push(new PlainValue$5.YAMLSemanticError(this, 'Multi-line double-quoted string needs to be sufficiently indented'));
  21690. } else if (ch === '\\') {
  21691. i += 1;
  21692. switch (src[i]) {
  21693. case '0':
  21694. str += '\0';
  21695. break;
  21696. // null character
  21697. case 'a':
  21698. str += '\x07';
  21699. break;
  21700. // bell character
  21701. case 'b':
  21702. str += '\b';
  21703. break;
  21704. // backspace
  21705. case 'e':
  21706. str += '\x1b';
  21707. break;
  21708. // escape character
  21709. case 'f':
  21710. str += '\f';
  21711. break;
  21712. // form feed
  21713. case 'n':
  21714. str += '\n';
  21715. break;
  21716. // line feed
  21717. case 'r':
  21718. str += '\r';
  21719. break;
  21720. // carriage return
  21721. case 't':
  21722. str += '\t';
  21723. break;
  21724. // horizontal tab
  21725. case 'v':
  21726. str += '\v';
  21727. break;
  21728. // vertical tab
  21729. case 'N':
  21730. str += '\u0085';
  21731. break;
  21732. // Unicode next line
  21733. case '_':
  21734. str += '\u00a0';
  21735. break;
  21736. // Unicode non-breaking space
  21737. case 'L':
  21738. str += '\u2028';
  21739. break;
  21740. // Unicode line separator
  21741. case 'P':
  21742. str += '\u2029';
  21743. break;
  21744. // Unicode paragraph separator
  21745. case ' ':
  21746. str += ' ';
  21747. break;
  21748. case '"':
  21749. str += '"';
  21750. break;
  21751. case '/':
  21752. str += '/';
  21753. break;
  21754. case '\\':
  21755. str += '\\';
  21756. break;
  21757. case '\t':
  21758. str += '\t';
  21759. break;
  21760. case 'x':
  21761. str += this.parseCharCode(i + 1, 2, errors);
  21762. i += 2;
  21763. break;
  21764. case 'u':
  21765. str += this.parseCharCode(i + 1, 4, errors);
  21766. i += 4;
  21767. break;
  21768. case 'U':
  21769. str += this.parseCharCode(i + 1, 8, errors);
  21770. i += 8;
  21771. break;
  21772. case '\n':
  21773. // skip escaped newlines, but still trim the following line
  21774. while (src[i + 1] === ' ' || src[i + 1] === '\t') i += 1;
  21775. break;
  21776. default:
  21777. errors.push(new PlainValue$5.YAMLSyntaxError(this, `Invalid escape sequence ${src.substr(i - 1, 2)}`));
  21778. str += '\\' + src[i];
  21779. }
  21780. } else if (ch === ' ' || ch === '\t') {
  21781. // trim trailing whitespace
  21782. const wsStart = i;
  21783. let next = src[i + 1];
  21784. while (next === ' ' || next === '\t') {
  21785. i += 1;
  21786. next = src[i + 1];
  21787. }
  21788. if (next !== '\n') str += i > wsStart ? src.slice(wsStart, i + 1) : ch;
  21789. } else {
  21790. str += ch;
  21791. }
  21792. }
  21793. return errors.length > 0 ? {
  21794. errors,
  21795. str
  21796. } : str;
  21797. }
  21798. parseCharCode(offset, length, errors) {
  21799. const {
  21800. src
  21801. } = this.context;
  21802. const cc = src.substr(offset, length);
  21803. const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc);
  21804. const code = ok ? parseInt(cc, 16) : NaN;
  21805. if (isNaN(code)) {
  21806. errors.push(new PlainValue$5.YAMLSyntaxError(this, `Invalid escape sequence ${src.substr(offset - 2, length + 2)}`));
  21807. return src.substr(offset - 2, length + 2);
  21808. }
  21809. return String.fromCodePoint(code);
  21810. }
  21811. /**
  21812. * Parses a "double quoted" value from the source
  21813. *
  21814. * @param {ParseContext} context
  21815. * @param {number} start - Index of first character
  21816. * @returns {number} - Index of the character after this scalar
  21817. */
  21818. parse(context, start) {
  21819. this.context = context;
  21820. const {
  21821. src
  21822. } = context;
  21823. let offset = QuoteDouble.endOfQuote(src, start + 1);
  21824. this.valueRange = new PlainValue$5.Range(start, offset);
  21825. offset = PlainValue$5.Node.endOfWhiteSpace(src, offset);
  21826. offset = this.parseComment(offset);
  21827. return offset;
  21828. }
  21829. }
  21830. class QuoteSingle extends PlainValue$5.Node {
  21831. static endOfQuote(src, offset) {
  21832. let ch = src[offset];
  21833. while (ch) {
  21834. if (ch === "'") {
  21835. if (src[offset + 1] !== "'") break;
  21836. ch = src[offset += 2];
  21837. } else {
  21838. ch = src[offset += 1];
  21839. }
  21840. }
  21841. return offset + 1;
  21842. }
  21843. /**
  21844. * @returns {string | { str: string, errors: YAMLSyntaxError[] }}
  21845. */
  21846. get strValue() {
  21847. if (!this.valueRange || !this.context) return null;
  21848. const errors = [];
  21849. const {
  21850. start,
  21851. end
  21852. } = this.valueRange;
  21853. const {
  21854. indent,
  21855. src
  21856. } = this.context;
  21857. if (src[end - 1] !== "'") errors.push(new PlainValue$5.YAMLSyntaxError(this, "Missing closing 'quote"));
  21858. let str = '';
  21859. for (let i = start + 1; i < end - 1; ++i) {
  21860. const ch = src[i];
  21861. if (ch === '\n') {
  21862. if (PlainValue$5.Node.atDocumentBoundary(src, i + 1)) errors.push(new PlainValue$5.YAMLSemanticError(this, 'Document boundary indicators are not allowed within string values'));
  21863. const {
  21864. fold,
  21865. offset,
  21866. error
  21867. } = PlainValue$5.Node.foldNewline(src, i, indent);
  21868. str += fold;
  21869. i = offset;
  21870. if (error) errors.push(new PlainValue$5.YAMLSemanticError(this, 'Multi-line single-quoted string needs to be sufficiently indented'));
  21871. } else if (ch === "'") {
  21872. str += ch;
  21873. i += 1;
  21874. if (src[i] !== "'") errors.push(new PlainValue$5.YAMLSyntaxError(this, 'Unescaped single quote? This should not happen.'));
  21875. } else if (ch === ' ' || ch === '\t') {
  21876. // trim trailing whitespace
  21877. const wsStart = i;
  21878. let next = src[i + 1];
  21879. while (next === ' ' || next === '\t') {
  21880. i += 1;
  21881. next = src[i + 1];
  21882. }
  21883. if (next !== '\n') str += i > wsStart ? src.slice(wsStart, i + 1) : ch;
  21884. } else {
  21885. str += ch;
  21886. }
  21887. }
  21888. return errors.length > 0 ? {
  21889. errors,
  21890. str
  21891. } : str;
  21892. }
  21893. /**
  21894. * Parses a 'single quoted' value from the source
  21895. *
  21896. * @param {ParseContext} context
  21897. * @param {number} start - Index of first character
  21898. * @returns {number} - Index of the character after this scalar
  21899. */
  21900. parse(context, start) {
  21901. this.context = context;
  21902. const {
  21903. src
  21904. } = context;
  21905. let offset = QuoteSingle.endOfQuote(src, start + 1);
  21906. this.valueRange = new PlainValue$5.Range(start, offset);
  21907. offset = PlainValue$5.Node.endOfWhiteSpace(src, offset);
  21908. offset = this.parseComment(offset);
  21909. return offset;
  21910. }
  21911. }
  21912. function createNewNode(type, props) {
  21913. switch (type) {
  21914. case PlainValue$5.Type.ALIAS:
  21915. return new Alias$1(type, props);
  21916. case PlainValue$5.Type.BLOCK_FOLDED:
  21917. case PlainValue$5.Type.BLOCK_LITERAL:
  21918. return new BlockValue(type, props);
  21919. case PlainValue$5.Type.FLOW_MAP:
  21920. case PlainValue$5.Type.FLOW_SEQ:
  21921. return new FlowCollection(type, props);
  21922. case PlainValue$5.Type.MAP_KEY:
  21923. case PlainValue$5.Type.MAP_VALUE:
  21924. case PlainValue$5.Type.SEQ_ITEM:
  21925. return new CollectionItem(type, props);
  21926. case PlainValue$5.Type.COMMENT:
  21927. case PlainValue$5.Type.PLAIN:
  21928. return new PlainValue$5.PlainValue(type, props);
  21929. case PlainValue$5.Type.QUOTE_DOUBLE:
  21930. return new QuoteDouble(type, props);
  21931. case PlainValue$5.Type.QUOTE_SINGLE:
  21932. return new QuoteSingle(type, props);
  21933. /* istanbul ignore next */
  21934. default:
  21935. return null;
  21936. // should never happen
  21937. }
  21938. }
  21939. /**
  21940. * @param {boolean} atLineStart - Node starts at beginning of line
  21941. * @param {boolean} inFlow - true if currently in a flow context
  21942. * @param {boolean} inCollection - true if currently in a collection context
  21943. * @param {number} indent - Current level of indentation
  21944. * @param {number} lineStart - Start of the current line
  21945. * @param {Node} parent - The parent of the node
  21946. * @param {string} src - Source of the YAML document
  21947. */
  21948. class ParseContext {
  21949. static parseType(src, offset, inFlow) {
  21950. switch (src[offset]) {
  21951. case '*':
  21952. return PlainValue$5.Type.ALIAS;
  21953. case '>':
  21954. return PlainValue$5.Type.BLOCK_FOLDED;
  21955. case '|':
  21956. return PlainValue$5.Type.BLOCK_LITERAL;
  21957. case '{':
  21958. return PlainValue$5.Type.FLOW_MAP;
  21959. case '[':
  21960. return PlainValue$5.Type.FLOW_SEQ;
  21961. case '?':
  21962. return !inFlow && PlainValue$5.Node.atBlank(src, offset + 1, true) ? PlainValue$5.Type.MAP_KEY : PlainValue$5.Type.PLAIN;
  21963. case ':':
  21964. return !inFlow && PlainValue$5.Node.atBlank(src, offset + 1, true) ? PlainValue$5.Type.MAP_VALUE : PlainValue$5.Type.PLAIN;
  21965. case '-':
  21966. return !inFlow && PlainValue$5.Node.atBlank(src, offset + 1, true) ? PlainValue$5.Type.SEQ_ITEM : PlainValue$5.Type.PLAIN;
  21967. case '"':
  21968. return PlainValue$5.Type.QUOTE_DOUBLE;
  21969. case "'":
  21970. return PlainValue$5.Type.QUOTE_SINGLE;
  21971. default:
  21972. return PlainValue$5.Type.PLAIN;
  21973. }
  21974. }
  21975. constructor(orig = {}, {
  21976. atLineStart,
  21977. inCollection,
  21978. inFlow,
  21979. indent,
  21980. lineStart,
  21981. parent
  21982. } = {}) {
  21983. PlainValue$5._defineProperty(this, "parseNode", (overlay, start) => {
  21984. if (PlainValue$5.Node.atDocumentBoundary(this.src, start)) return null;
  21985. const context = new ParseContext(this, overlay);
  21986. const {
  21987. props,
  21988. type,
  21989. valueStart
  21990. } = context.parseProps(start);
  21991. const node = createNewNode(type, props);
  21992. let offset = node.parse(context, valueStart);
  21993. node.range = new PlainValue$5.Range(start, offset);
  21994. /* istanbul ignore if */
  21995. if (offset <= start) {
  21996. // This should never happen, but if it does, let's make sure to at least
  21997. // step one character forward to avoid a busy loop.
  21998. node.error = new Error(`Node#parse consumed no characters`);
  21999. node.error.parseEnd = offset;
  22000. node.error.source = node;
  22001. node.range.end = start + 1;
  22002. }
  22003. if (context.nodeStartsCollection(node)) {
  22004. if (!node.error && !context.atLineStart && context.parent.type === PlainValue$5.Type.DOCUMENT) {
  22005. node.error = new PlainValue$5.YAMLSyntaxError(node, 'Block collection must not have preceding content here (e.g. directives-end indicator)');
  22006. }
  22007. const collection = new Collection$1(node);
  22008. offset = collection.parse(new ParseContext(context), offset);
  22009. collection.range = new PlainValue$5.Range(start, offset);
  22010. return collection;
  22011. }
  22012. return node;
  22013. });
  22014. this.atLineStart = atLineStart != null ? atLineStart : orig.atLineStart || false;
  22015. this.inCollection = inCollection != null ? inCollection : orig.inCollection || false;
  22016. this.inFlow = inFlow != null ? inFlow : orig.inFlow || false;
  22017. this.indent = indent != null ? indent : orig.indent;
  22018. this.lineStart = lineStart != null ? lineStart : orig.lineStart;
  22019. this.parent = parent != null ? parent : orig.parent || {};
  22020. this.root = orig.root;
  22021. this.src = orig.src;
  22022. }
  22023. nodeStartsCollection(node) {
  22024. const {
  22025. inCollection,
  22026. inFlow,
  22027. src
  22028. } = this;
  22029. if (inCollection || inFlow) return false;
  22030. if (node instanceof CollectionItem) return true; // check for implicit key
  22031. let offset = node.range.end;
  22032. if (src[offset] === '\n' || src[offset - 1] === '\n') return false;
  22033. offset = PlainValue$5.Node.endOfWhiteSpace(src, offset);
  22034. return src[offset] === ':';
  22035. } // Anchor and tag are before type, which determines the node implementation
  22036. // class; hence this intermediate step.
  22037. parseProps(offset) {
  22038. const {
  22039. inFlow,
  22040. parent,
  22041. src
  22042. } = this;
  22043. const props = [];
  22044. let lineHasProps = false;
  22045. offset = this.atLineStart ? PlainValue$5.Node.endOfIndent(src, offset) : PlainValue$5.Node.endOfWhiteSpace(src, offset);
  22046. let ch = src[offset];
  22047. while (ch === PlainValue$5.Char.ANCHOR || ch === PlainValue$5.Char.COMMENT || ch === PlainValue$5.Char.TAG || ch === '\n') {
  22048. if (ch === '\n') {
  22049. let inEnd = offset;
  22050. let lineStart;
  22051. do {
  22052. lineStart = inEnd + 1;
  22053. inEnd = PlainValue$5.Node.endOfIndent(src, lineStart);
  22054. } while (src[inEnd] === '\n');
  22055. const indentDiff = inEnd - (lineStart + this.indent);
  22056. const noIndicatorAsIndent = parent.type === PlainValue$5.Type.SEQ_ITEM && parent.context.atLineStart;
  22057. if (src[inEnd] !== '#' && !PlainValue$5.Node.nextNodeIsIndented(src[inEnd], indentDiff, !noIndicatorAsIndent)) break;
  22058. this.atLineStart = true;
  22059. this.lineStart = lineStart;
  22060. lineHasProps = false;
  22061. offset = inEnd;
  22062. } else if (ch === PlainValue$5.Char.COMMENT) {
  22063. const end = PlainValue$5.Node.endOfLine(src, offset + 1);
  22064. props.push(new PlainValue$5.Range(offset, end));
  22065. offset = end;
  22066. } else {
  22067. let end = PlainValue$5.Node.endOfIdentifier(src, offset + 1);
  22068. if (ch === PlainValue$5.Char.TAG && src[end] === ',' && /^[a-zA-Z0-9-]+\.[a-zA-Z0-9-]+,\d\d\d\d(-\d\d){0,2}\/\S/.test(src.slice(offset + 1, end + 13))) {
  22069. // Let's presume we're dealing with a YAML 1.0 domain tag here, rather
  22070. // than an empty but 'foo.bar' private-tagged node in a flow collection
  22071. // followed without whitespace by a plain string starting with a year
  22072. // or date divided by something.
  22073. end = PlainValue$5.Node.endOfIdentifier(src, end + 5);
  22074. }
  22075. props.push(new PlainValue$5.Range(offset, end));
  22076. lineHasProps = true;
  22077. offset = PlainValue$5.Node.endOfWhiteSpace(src, end);
  22078. }
  22079. ch = src[offset];
  22080. } // '- &a : b' has an anchor on an empty node
  22081. if (lineHasProps && ch === ':' && PlainValue$5.Node.atBlank(src, offset + 1, true)) offset -= 1;
  22082. const type = ParseContext.parseType(src, offset, inFlow);
  22083. return {
  22084. props,
  22085. type,
  22086. valueStart: offset
  22087. };
  22088. }
  22089. /**
  22090. * Parses a node from the source
  22091. * @param {ParseContext} overlay
  22092. * @param {number} start - Index of first non-whitespace character for the node
  22093. * @returns {?Node} - null if at a document boundary
  22094. */
  22095. }
  22096. // Published as 'yaml/parse-cst'
  22097. function parse$c(src) {
  22098. const cr = [];
  22099. if (src.indexOf('\r') !== -1) {
  22100. src = src.replace(/\r\n?/g, (match, offset) => {
  22101. if (match.length > 1) cr.push(offset);
  22102. return '\n';
  22103. });
  22104. }
  22105. const documents = [];
  22106. let offset = 0;
  22107. do {
  22108. const doc = new Document$3();
  22109. const context = new ParseContext({
  22110. src
  22111. });
  22112. offset = doc.parse(context, offset);
  22113. documents.push(doc);
  22114. } while (offset < src.length);
  22115. documents.setOrigRanges = () => {
  22116. if (cr.length === 0) return false;
  22117. for (let i = 1; i < cr.length; ++i) cr[i] -= i;
  22118. let crOffset = 0;
  22119. for (let i = 0; i < documents.length; ++i) {
  22120. crOffset = documents[i].setOrigRanges(cr, crOffset);
  22121. }
  22122. cr.splice(0, cr.length);
  22123. return true;
  22124. };
  22125. documents.toString = () => documents.join('...\n');
  22126. return documents;
  22127. }
  22128. parseCst$1.parse = parse$c;
  22129. var Document9b4560a1 = {};
  22130. var resolveSeqD03cb037 = {};
  22131. var PlainValue$4 = PlainValueEc8e588e;
  22132. function addCommentBefore(str, indent, comment) {
  22133. if (!comment) return str;
  22134. const cc = comment.replace(/[\s\S]^/gm, `$&${indent}#`);
  22135. return `#${cc}\n${indent}${str}`;
  22136. }
  22137. function addComment(str, indent, comment) {
  22138. return !comment ? str : comment.indexOf('\n') === -1 ? `${str} #${comment}` : `${str}\n` + comment.replace(/^/gm, `${indent || ''}#`);
  22139. }
  22140. class Node$1 {}
  22141. function toJSON(value, arg, ctx) {
  22142. if (Array.isArray(value)) return value.map((v, i) => toJSON(v, String(i), ctx));
  22143. if (value && typeof value.toJSON === 'function') {
  22144. const anchor = ctx && ctx.anchors && ctx.anchors.get(value);
  22145. if (anchor) ctx.onCreate = res => {
  22146. anchor.res = res;
  22147. delete ctx.onCreate;
  22148. };
  22149. const res = value.toJSON(arg, ctx);
  22150. if (anchor && ctx.onCreate) ctx.onCreate(res);
  22151. return res;
  22152. }
  22153. if ((!ctx || !ctx.keep) && typeof value === 'bigint') return Number(value);
  22154. return value;
  22155. }
  22156. class Scalar extends Node$1 {
  22157. constructor(value) {
  22158. super();
  22159. this.value = value;
  22160. }
  22161. toJSON(arg, ctx) {
  22162. return ctx && ctx.keep ? this.value : toJSON(this.value, arg, ctx);
  22163. }
  22164. toString() {
  22165. return String(this.value);
  22166. }
  22167. }
  22168. function collectionFromPath(schema, path, value) {
  22169. let v = value;
  22170. for (let i = path.length - 1; i >= 0; --i) {
  22171. const k = path[i];
  22172. if (Number.isInteger(k) && k >= 0) {
  22173. const a = [];
  22174. a[k] = v;
  22175. v = a;
  22176. } else {
  22177. const o = {};
  22178. Object.defineProperty(o, k, {
  22179. value: v,
  22180. writable: true,
  22181. enumerable: true,
  22182. configurable: true
  22183. });
  22184. v = o;
  22185. }
  22186. }
  22187. return schema.createNode(v, false);
  22188. } // null, undefined, or an empty non-string iterable (e.g. [])
  22189. const isEmptyPath = path => path == null || typeof path === 'object' && path[Symbol.iterator]().next().done;
  22190. class Collection extends Node$1 {
  22191. constructor(schema) {
  22192. super();
  22193. PlainValue$4._defineProperty(this, "items", []);
  22194. this.schema = schema;
  22195. }
  22196. addIn(path, value) {
  22197. if (isEmptyPath(path)) this.add(value);else {
  22198. const [key, ...rest] = path;
  22199. const node = this.get(key, true);
  22200. if (node instanceof Collection) node.addIn(rest, value);else if (node === undefined && this.schema) this.set(key, collectionFromPath(this.schema, rest, value));else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
  22201. }
  22202. }
  22203. deleteIn([key, ...rest]) {
  22204. if (rest.length === 0) return this.delete(key);
  22205. const node = this.get(key, true);
  22206. if (node instanceof Collection) return node.deleteIn(rest);else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
  22207. }
  22208. getIn([key, ...rest], keepScalar) {
  22209. const node = this.get(key, true);
  22210. if (rest.length === 0) return !keepScalar && node instanceof Scalar ? node.value : node;else return node instanceof Collection ? node.getIn(rest, keepScalar) : undefined;
  22211. }
  22212. hasAllNullValues() {
  22213. return this.items.every(node => {
  22214. if (!node || node.type !== 'PAIR') return false;
  22215. const n = node.value;
  22216. return n == null || n instanceof Scalar && n.value == null && !n.commentBefore && !n.comment && !n.tag;
  22217. });
  22218. }
  22219. hasIn([key, ...rest]) {
  22220. if (rest.length === 0) return this.has(key);
  22221. const node = this.get(key, true);
  22222. return node instanceof Collection ? node.hasIn(rest) : false;
  22223. }
  22224. setIn([key, ...rest], value) {
  22225. if (rest.length === 0) {
  22226. this.set(key, value);
  22227. } else {
  22228. const node = this.get(key, true);
  22229. if (node instanceof Collection) node.setIn(rest, value);else if (node === undefined && this.schema) this.set(key, collectionFromPath(this.schema, rest, value));else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
  22230. }
  22231. } // overridden in implementations
  22232. /* istanbul ignore next */
  22233. toJSON() {
  22234. return null;
  22235. }
  22236. toString(ctx, {
  22237. blockItem,
  22238. flowChars,
  22239. isMap,
  22240. itemIndent
  22241. }, onComment, onChompKeep) {
  22242. const {
  22243. indent,
  22244. indentStep,
  22245. stringify
  22246. } = ctx;
  22247. const inFlow = this.type === PlainValue$4.Type.FLOW_MAP || this.type === PlainValue$4.Type.FLOW_SEQ || ctx.inFlow;
  22248. if (inFlow) itemIndent += indentStep;
  22249. const allNullValues = isMap && this.hasAllNullValues();
  22250. ctx = Object.assign({}, ctx, {
  22251. allNullValues,
  22252. indent: itemIndent,
  22253. inFlow,
  22254. type: null
  22255. });
  22256. let chompKeep = false;
  22257. let hasItemWithNewLine = false;
  22258. const nodes = this.items.reduce((nodes, item, i) => {
  22259. let comment;
  22260. if (item) {
  22261. if (!chompKeep && item.spaceBefore) nodes.push({
  22262. type: 'comment',
  22263. str: ''
  22264. });
  22265. if (item.commentBefore) item.commentBefore.match(/^.*$/gm).forEach(line => {
  22266. nodes.push({
  22267. type: 'comment',
  22268. str: `#${line}`
  22269. });
  22270. });
  22271. if (item.comment) comment = item.comment;
  22272. if (inFlow && (!chompKeep && item.spaceBefore || item.commentBefore || item.comment || item.key && (item.key.commentBefore || item.key.comment) || item.value && (item.value.commentBefore || item.value.comment))) hasItemWithNewLine = true;
  22273. }
  22274. chompKeep = false;
  22275. let str = stringify(item, ctx, () => comment = null, () => chompKeep = true);
  22276. if (inFlow && !hasItemWithNewLine && str.includes('\n')) hasItemWithNewLine = true;
  22277. if (inFlow && i < this.items.length - 1) str += ',';
  22278. str = addComment(str, itemIndent, comment);
  22279. if (chompKeep && (comment || inFlow)) chompKeep = false;
  22280. nodes.push({
  22281. type: 'item',
  22282. str
  22283. });
  22284. return nodes;
  22285. }, []);
  22286. let str;
  22287. if (nodes.length === 0) {
  22288. str = flowChars.start + flowChars.end;
  22289. } else if (inFlow) {
  22290. const {
  22291. start,
  22292. end
  22293. } = flowChars;
  22294. const strings = nodes.map(n => n.str);
  22295. if (hasItemWithNewLine || strings.reduce((sum, str) => sum + str.length + 2, 2) > Collection.maxFlowStringSingleLineLength) {
  22296. str = start;
  22297. for (const s of strings) {
  22298. str += s ? `\n${indentStep}${indent}${s}` : '\n';
  22299. }
  22300. str += `\n${indent}${end}`;
  22301. } else {
  22302. str = `${start} ${strings.join(' ')} ${end}`;
  22303. }
  22304. } else {
  22305. const strings = nodes.map(blockItem);
  22306. str = strings.shift();
  22307. for (const s of strings) str += s ? `\n${indent}${s}` : '\n';
  22308. }
  22309. if (this.comment) {
  22310. str += '\n' + this.comment.replace(/^/gm, `${indent}#`);
  22311. if (onComment) onComment();
  22312. } else if (chompKeep && onChompKeep) onChompKeep();
  22313. return str;
  22314. }
  22315. }
  22316. PlainValue$4._defineProperty(Collection, "maxFlowStringSingleLineLength", 60);
  22317. function asItemIndex(key) {
  22318. let idx = key instanceof Scalar ? key.value : key;
  22319. if (idx && typeof idx === 'string') idx = Number(idx);
  22320. return Number.isInteger(idx) && idx >= 0 ? idx : null;
  22321. }
  22322. class YAMLSeq extends Collection {
  22323. add(value) {
  22324. this.items.push(value);
  22325. }
  22326. delete(key) {
  22327. const idx = asItemIndex(key);
  22328. if (typeof idx !== 'number') return false;
  22329. const del = this.items.splice(idx, 1);
  22330. return del.length > 0;
  22331. }
  22332. get(key, keepScalar) {
  22333. const idx = asItemIndex(key);
  22334. if (typeof idx !== 'number') return undefined;
  22335. const it = this.items[idx];
  22336. return !keepScalar && it instanceof Scalar ? it.value : it;
  22337. }
  22338. has(key) {
  22339. const idx = asItemIndex(key);
  22340. return typeof idx === 'number' && idx < this.items.length;
  22341. }
  22342. set(key, value) {
  22343. const idx = asItemIndex(key);
  22344. if (typeof idx !== 'number') throw new Error(`Expected a valid index, not ${key}.`);
  22345. this.items[idx] = value;
  22346. }
  22347. toJSON(_, ctx) {
  22348. const seq = [];
  22349. if (ctx && ctx.onCreate) ctx.onCreate(seq);
  22350. let i = 0;
  22351. for (const item of this.items) seq.push(toJSON(item, String(i++), ctx));
  22352. return seq;
  22353. }
  22354. toString(ctx, onComment, onChompKeep) {
  22355. if (!ctx) return JSON.stringify(this);
  22356. return super.toString(ctx, {
  22357. blockItem: n => n.type === 'comment' ? n.str : `- ${n.str}`,
  22358. flowChars: {
  22359. start: '[',
  22360. end: ']'
  22361. },
  22362. isMap: false,
  22363. itemIndent: (ctx.indent || '') + ' '
  22364. }, onComment, onChompKeep);
  22365. }
  22366. }
  22367. const stringifyKey = (key, jsKey, ctx) => {
  22368. if (jsKey === null) return '';
  22369. if (typeof jsKey !== 'object') return String(jsKey);
  22370. if (key instanceof Node$1 && ctx && ctx.doc) return key.toString({
  22371. anchors: Object.create(null),
  22372. doc: ctx.doc,
  22373. indent: '',
  22374. indentStep: ctx.indentStep,
  22375. inFlow: true,
  22376. inStringifyKey: true,
  22377. stringify: ctx.stringify
  22378. });
  22379. return JSON.stringify(jsKey);
  22380. };
  22381. class Pair extends Node$1 {
  22382. constructor(key, value = null) {
  22383. super();
  22384. this.key = key;
  22385. this.value = value;
  22386. this.type = Pair.Type.PAIR;
  22387. }
  22388. get commentBefore() {
  22389. return this.key instanceof Node$1 ? this.key.commentBefore : undefined;
  22390. }
  22391. set commentBefore(cb) {
  22392. if (this.key == null) this.key = new Scalar(null);
  22393. if (this.key instanceof Node$1) this.key.commentBefore = cb;else {
  22394. const msg = 'Pair.commentBefore is an alias for Pair.key.commentBefore. To set it, the key must be a Node.';
  22395. throw new Error(msg);
  22396. }
  22397. }
  22398. addToJSMap(ctx, map) {
  22399. const key = toJSON(this.key, '', ctx);
  22400. if (map instanceof Map) {
  22401. const value = toJSON(this.value, key, ctx);
  22402. map.set(key, value);
  22403. } else if (map instanceof Set) {
  22404. map.add(key);
  22405. } else {
  22406. const stringKey = stringifyKey(this.key, key, ctx);
  22407. const value = toJSON(this.value, stringKey, ctx);
  22408. if (stringKey in map) Object.defineProperty(map, stringKey, {
  22409. value,
  22410. writable: true,
  22411. enumerable: true,
  22412. configurable: true
  22413. });else map[stringKey] = value;
  22414. }
  22415. return map;
  22416. }
  22417. toJSON(_, ctx) {
  22418. const pair = ctx && ctx.mapAsMap ? new Map() : {};
  22419. return this.addToJSMap(ctx, pair);
  22420. }
  22421. toString(ctx, onComment, onChompKeep) {
  22422. if (!ctx || !ctx.doc) return JSON.stringify(this);
  22423. const {
  22424. indent: indentSize,
  22425. indentSeq,
  22426. simpleKeys
  22427. } = ctx.doc.options;
  22428. let {
  22429. key,
  22430. value
  22431. } = this;
  22432. let keyComment = key instanceof Node$1 && key.comment;
  22433. if (simpleKeys) {
  22434. if (keyComment) {
  22435. throw new Error('With simple keys, key nodes cannot have comments');
  22436. }
  22437. if (key instanceof Collection) {
  22438. const msg = 'With simple keys, collection cannot be used as a key value';
  22439. throw new Error(msg);
  22440. }
  22441. }
  22442. let explicitKey = !simpleKeys && (!key || keyComment || (key instanceof Node$1 ? key instanceof Collection || key.type === PlainValue$4.Type.BLOCK_FOLDED || key.type === PlainValue$4.Type.BLOCK_LITERAL : typeof key === 'object'));
  22443. const {
  22444. doc,
  22445. indent,
  22446. indentStep,
  22447. stringify
  22448. } = ctx;
  22449. ctx = Object.assign({}, ctx, {
  22450. implicitKey: !explicitKey,
  22451. indent: indent + indentStep
  22452. });
  22453. let chompKeep = false;
  22454. let str = stringify(key, ctx, () => keyComment = null, () => chompKeep = true);
  22455. str = addComment(str, ctx.indent, keyComment);
  22456. if (!explicitKey && str.length > 1024) {
  22457. if (simpleKeys) throw new Error('With simple keys, single line scalar must not span more than 1024 characters');
  22458. explicitKey = true;
  22459. }
  22460. if (ctx.allNullValues && !simpleKeys) {
  22461. if (this.comment) {
  22462. str = addComment(str, ctx.indent, this.comment);
  22463. if (onComment) onComment();
  22464. } else if (chompKeep && !keyComment && onChompKeep) onChompKeep();
  22465. return ctx.inFlow && !explicitKey ? str : `? ${str}`;
  22466. }
  22467. str = explicitKey ? `? ${str}\n${indent}:` : `${str}:`;
  22468. if (this.comment) {
  22469. // expected (but not strictly required) to be a single-line comment
  22470. str = addComment(str, ctx.indent, this.comment);
  22471. if (onComment) onComment();
  22472. }
  22473. let vcb = '';
  22474. let valueComment = null;
  22475. if (value instanceof Node$1) {
  22476. if (value.spaceBefore) vcb = '\n';
  22477. if (value.commentBefore) {
  22478. const cs = value.commentBefore.replace(/^/gm, `${ctx.indent}#`);
  22479. vcb += `\n${cs}`;
  22480. }
  22481. valueComment = value.comment;
  22482. } else if (value && typeof value === 'object') {
  22483. value = doc.schema.createNode(value, true);
  22484. }
  22485. ctx.implicitKey = false;
  22486. if (!explicitKey && !this.comment && value instanceof Scalar) ctx.indentAtStart = str.length + 1;
  22487. chompKeep = false;
  22488. if (!indentSeq && indentSize >= 2 && !ctx.inFlow && !explicitKey && value instanceof YAMLSeq && value.type !== PlainValue$4.Type.FLOW_SEQ && !value.tag && !doc.anchors.getName(value)) {
  22489. // If indentSeq === false, consider '- ' as part of indentation where possible
  22490. ctx.indent = ctx.indent.substr(2);
  22491. }
  22492. const valueStr = stringify(value, ctx, () => valueComment = null, () => chompKeep = true);
  22493. let ws = ' ';
  22494. if (vcb || this.comment) {
  22495. ws = `${vcb}\n${ctx.indent}`;
  22496. } else if (!explicitKey && value instanceof Collection) {
  22497. const flow = valueStr[0] === '[' || valueStr[0] === '{';
  22498. if (!flow || valueStr.includes('\n')) ws = `\n${ctx.indent}`;
  22499. } else if (valueStr[0] === '\n') ws = '';
  22500. if (chompKeep && !valueComment && onChompKeep) onChompKeep();
  22501. return addComment(str + ws + valueStr, ctx.indent, valueComment);
  22502. }
  22503. }
  22504. PlainValue$4._defineProperty(Pair, "Type", {
  22505. PAIR: 'PAIR',
  22506. MERGE_PAIR: 'MERGE_PAIR'
  22507. });
  22508. const getAliasCount = (node, anchors) => {
  22509. if (node instanceof Alias) {
  22510. const anchor = anchors.get(node.source);
  22511. return anchor.count * anchor.aliasCount;
  22512. } else if (node instanceof Collection) {
  22513. let count = 0;
  22514. for (const item of node.items) {
  22515. const c = getAliasCount(item, anchors);
  22516. if (c > count) count = c;
  22517. }
  22518. return count;
  22519. } else if (node instanceof Pair) {
  22520. const kc = getAliasCount(node.key, anchors);
  22521. const vc = getAliasCount(node.value, anchors);
  22522. return Math.max(kc, vc);
  22523. }
  22524. return 1;
  22525. };
  22526. class Alias extends Node$1 {
  22527. static stringify({
  22528. range,
  22529. source
  22530. }, {
  22531. anchors,
  22532. doc,
  22533. implicitKey,
  22534. inStringifyKey
  22535. }) {
  22536. let anchor = Object.keys(anchors).find(a => anchors[a] === source);
  22537. if (!anchor && inStringifyKey) anchor = doc.anchors.getName(source) || doc.anchors.newName();
  22538. if (anchor) return `*${anchor}${implicitKey ? ' ' : ''}`;
  22539. const msg = doc.anchors.getName(source) ? 'Alias node must be after source node' : 'Source node not found for alias node';
  22540. throw new Error(`${msg} [${range}]`);
  22541. }
  22542. constructor(source) {
  22543. super();
  22544. this.source = source;
  22545. this.type = PlainValue$4.Type.ALIAS;
  22546. }
  22547. set tag(t) {
  22548. throw new Error('Alias nodes cannot have tags');
  22549. }
  22550. toJSON(arg, ctx) {
  22551. if (!ctx) return toJSON(this.source, arg, ctx);
  22552. const {
  22553. anchors,
  22554. maxAliasCount
  22555. } = ctx;
  22556. const anchor = anchors.get(this.source);
  22557. /* istanbul ignore if */
  22558. if (!anchor || anchor.res === undefined) {
  22559. const msg = 'This should not happen: Alias anchor was not resolved?';
  22560. if (this.cstNode) throw new PlainValue$4.YAMLReferenceError(this.cstNode, msg);else throw new ReferenceError(msg);
  22561. }
  22562. if (maxAliasCount >= 0) {
  22563. anchor.count += 1;
  22564. if (anchor.aliasCount === 0) anchor.aliasCount = getAliasCount(this.source, anchors);
  22565. if (anchor.count * anchor.aliasCount > maxAliasCount) {
  22566. const msg = 'Excessive alias count indicates a resource exhaustion attack';
  22567. if (this.cstNode) throw new PlainValue$4.YAMLReferenceError(this.cstNode, msg);else throw new ReferenceError(msg);
  22568. }
  22569. }
  22570. return anchor.res;
  22571. } // Only called when stringifying an alias mapping key while constructing
  22572. // Object output.
  22573. toString(ctx) {
  22574. return Alias.stringify(this, ctx);
  22575. }
  22576. }
  22577. PlainValue$4._defineProperty(Alias, "default", true);
  22578. function findPair(items, key) {
  22579. const k = key instanceof Scalar ? key.value : key;
  22580. for (const it of items) {
  22581. if (it instanceof Pair) {
  22582. if (it.key === key || it.key === k) return it;
  22583. if (it.key && it.key.value === k) return it;
  22584. }
  22585. }
  22586. return undefined;
  22587. }
  22588. class YAMLMap extends Collection {
  22589. add(pair, overwrite) {
  22590. if (!pair) pair = new Pair(pair);else if (!(pair instanceof Pair)) pair = new Pair(pair.key || pair, pair.value);
  22591. const prev = findPair(this.items, pair.key);
  22592. const sortEntries = this.schema && this.schema.sortMapEntries;
  22593. if (prev) {
  22594. if (overwrite) prev.value = pair.value;else throw new Error(`Key ${pair.key} already set`);
  22595. } else if (sortEntries) {
  22596. const i = this.items.findIndex(item => sortEntries(pair, item) < 0);
  22597. if (i === -1) this.items.push(pair);else this.items.splice(i, 0, pair);
  22598. } else {
  22599. this.items.push(pair);
  22600. }
  22601. }
  22602. delete(key) {
  22603. const it = findPair(this.items, key);
  22604. if (!it) return false;
  22605. const del = this.items.splice(this.items.indexOf(it), 1);
  22606. return del.length > 0;
  22607. }
  22608. get(key, keepScalar) {
  22609. const it = findPair(this.items, key);
  22610. const node = it && it.value;
  22611. return !keepScalar && node instanceof Scalar ? node.value : node;
  22612. }
  22613. has(key) {
  22614. return !!findPair(this.items, key);
  22615. }
  22616. set(key, value) {
  22617. this.add(new Pair(key, value), true);
  22618. }
  22619. /**
  22620. * @param {*} arg ignored
  22621. * @param {*} ctx Conversion context, originally set in Document#toJSON()
  22622. * @param {Class} Type If set, forces the returned collection type
  22623. * @returns {*} Instance of Type, Map, or Object
  22624. */
  22625. toJSON(_, ctx, Type) {
  22626. const map = Type ? new Type() : ctx && ctx.mapAsMap ? new Map() : {};
  22627. if (ctx && ctx.onCreate) ctx.onCreate(map);
  22628. for (const item of this.items) item.addToJSMap(ctx, map);
  22629. return map;
  22630. }
  22631. toString(ctx, onComment, onChompKeep) {
  22632. if (!ctx) return JSON.stringify(this);
  22633. for (const item of this.items) {
  22634. if (!(item instanceof Pair)) throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`);
  22635. }
  22636. return super.toString(ctx, {
  22637. blockItem: n => n.str,
  22638. flowChars: {
  22639. start: '{',
  22640. end: '}'
  22641. },
  22642. isMap: true,
  22643. itemIndent: ctx.indent || ''
  22644. }, onComment, onChompKeep);
  22645. }
  22646. }
  22647. const MERGE_KEY = '<<';
  22648. class Merge extends Pair {
  22649. constructor(pair) {
  22650. if (pair instanceof Pair) {
  22651. let seq = pair.value;
  22652. if (!(seq instanceof YAMLSeq)) {
  22653. seq = new YAMLSeq();
  22654. seq.items.push(pair.value);
  22655. seq.range = pair.value.range;
  22656. }
  22657. super(pair.key, seq);
  22658. this.range = pair.range;
  22659. } else {
  22660. super(new Scalar(MERGE_KEY), new YAMLSeq());
  22661. }
  22662. this.type = Pair.Type.MERGE_PAIR;
  22663. } // If the value associated with a merge key is a single mapping node, each of
  22664. // its key/value pairs is inserted into the current mapping, unless the key
  22665. // already exists in it. If the value associated with the merge key is a
  22666. // sequence, then this sequence is expected to contain mapping nodes and each
  22667. // of these nodes is merged in turn according to its order in the sequence.
  22668. // Keys in mapping nodes earlier in the sequence override keys specified in
  22669. // later mapping nodes. -- http://yaml.org/type/merge.html
  22670. addToJSMap(ctx, map) {
  22671. for (const {
  22672. source
  22673. } of this.value.items) {
  22674. if (!(source instanceof YAMLMap)) throw new Error('Merge sources must be maps');
  22675. const srcMap = source.toJSON(null, ctx, Map);
  22676. for (const [key, value] of srcMap) {
  22677. if (map instanceof Map) {
  22678. if (!map.has(key)) map.set(key, value);
  22679. } else if (map instanceof Set) {
  22680. map.add(key);
  22681. } else if (!Object.prototype.hasOwnProperty.call(map, key)) {
  22682. Object.defineProperty(map, key, {
  22683. value,
  22684. writable: true,
  22685. enumerable: true,
  22686. configurable: true
  22687. });
  22688. }
  22689. }
  22690. }
  22691. return map;
  22692. }
  22693. toString(ctx, onComment) {
  22694. const seq = this.value;
  22695. if (seq.items.length > 1) return super.toString(ctx, onComment);
  22696. this.value = seq.items[0];
  22697. const str = super.toString(ctx, onComment);
  22698. this.value = seq;
  22699. return str;
  22700. }
  22701. }
  22702. const binaryOptions = {
  22703. defaultType: PlainValue$4.Type.BLOCK_LITERAL,
  22704. lineWidth: 76
  22705. };
  22706. const boolOptions = {
  22707. trueStr: 'true',
  22708. falseStr: 'false'
  22709. };
  22710. const intOptions = {
  22711. asBigInt: false
  22712. };
  22713. const nullOptions = {
  22714. nullStr: 'null'
  22715. };
  22716. const strOptions = {
  22717. defaultType: PlainValue$4.Type.PLAIN,
  22718. doubleQuoted: {
  22719. jsonEncoding: false,
  22720. minMultiLineLength: 40
  22721. },
  22722. fold: {
  22723. lineWidth: 80,
  22724. minContentWidth: 20
  22725. }
  22726. };
  22727. function resolveScalar(str, tags, scalarFallback) {
  22728. for (const {
  22729. format,
  22730. test,
  22731. resolve
  22732. } of tags) {
  22733. if (test) {
  22734. const match = str.match(test);
  22735. if (match) {
  22736. let res = resolve.apply(null, match);
  22737. if (!(res instanceof Scalar)) res = new Scalar(res);
  22738. if (format) res.format = format;
  22739. return res;
  22740. }
  22741. }
  22742. }
  22743. if (scalarFallback) str = scalarFallback(str);
  22744. return new Scalar(str);
  22745. }
  22746. const FOLD_FLOW = 'flow';
  22747. const FOLD_BLOCK = 'block';
  22748. const FOLD_QUOTED = 'quoted'; // presumes i+1 is at the start of a line
  22749. // returns index of last newline in more-indented block
  22750. const consumeMoreIndentedLines = (text, i) => {
  22751. let ch = text[i + 1];
  22752. while (ch === ' ' || ch === '\t') {
  22753. do {
  22754. ch = text[i += 1];
  22755. } while (ch && ch !== '\n');
  22756. ch = text[i + 1];
  22757. }
  22758. return i;
  22759. };
  22760. /**
  22761. * Tries to keep input at up to `lineWidth` characters, splitting only on spaces
  22762. * not followed by newlines or spaces unless `mode` is `'quoted'`. Lines are
  22763. * terminated with `\n` and started with `indent`.
  22764. *
  22765. * @param {string} text
  22766. * @param {string} indent
  22767. * @param {string} [mode='flow'] `'block'` prevents more-indented lines
  22768. * from being folded; `'quoted'` allows for `\` escapes, including escaped
  22769. * newlines
  22770. * @param {Object} options
  22771. * @param {number} [options.indentAtStart] Accounts for leading contents on
  22772. * the first line, defaulting to `indent.length`
  22773. * @param {number} [options.lineWidth=80]
  22774. * @param {number} [options.minContentWidth=20] Allow highly indented lines to
  22775. * stretch the line width or indent content from the start
  22776. * @param {function} options.onFold Called once if the text is folded
  22777. * @param {function} options.onFold Called once if any line of text exceeds
  22778. * lineWidth characters
  22779. */
  22780. function foldFlowLines(text, indent, mode, {
  22781. indentAtStart,
  22782. lineWidth = 80,
  22783. minContentWidth = 20,
  22784. onFold,
  22785. onOverflow
  22786. }) {
  22787. if (!lineWidth || lineWidth < 0) return text;
  22788. const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length);
  22789. if (text.length <= endStep) return text;
  22790. const folds = [];
  22791. const escapedFolds = {};
  22792. let end = lineWidth - indent.length;
  22793. if (typeof indentAtStart === 'number') {
  22794. if (indentAtStart > lineWidth - Math.max(2, minContentWidth)) folds.push(0);else end = lineWidth - indentAtStart;
  22795. }
  22796. let split = undefined;
  22797. let prev = undefined;
  22798. let overflow = false;
  22799. let i = -1;
  22800. let escStart = -1;
  22801. let escEnd = -1;
  22802. if (mode === FOLD_BLOCK) {
  22803. i = consumeMoreIndentedLines(text, i);
  22804. if (i !== -1) end = i + endStep;
  22805. }
  22806. for (let ch; ch = text[i += 1];) {
  22807. if (mode === FOLD_QUOTED && ch === '\\') {
  22808. escStart = i;
  22809. switch (text[i + 1]) {
  22810. case 'x':
  22811. i += 3;
  22812. break;
  22813. case 'u':
  22814. i += 5;
  22815. break;
  22816. case 'U':
  22817. i += 9;
  22818. break;
  22819. default:
  22820. i += 1;
  22821. }
  22822. escEnd = i;
  22823. }
  22824. if (ch === '\n') {
  22825. if (mode === FOLD_BLOCK) i = consumeMoreIndentedLines(text, i);
  22826. end = i + endStep;
  22827. split = undefined;
  22828. } else {
  22829. if (ch === ' ' && prev && prev !== ' ' && prev !== '\n' && prev !== '\t') {
  22830. // space surrounded by non-space can be replaced with newline + indent
  22831. const next = text[i + 1];
  22832. if (next && next !== ' ' && next !== '\n' && next !== '\t') split = i;
  22833. }
  22834. if (i >= end) {
  22835. if (split) {
  22836. folds.push(split);
  22837. end = split + endStep;
  22838. split = undefined;
  22839. } else if (mode === FOLD_QUOTED) {
  22840. // white-space collected at end may stretch past lineWidth
  22841. while (prev === ' ' || prev === '\t') {
  22842. prev = ch;
  22843. ch = text[i += 1];
  22844. overflow = true;
  22845. } // Account for newline escape, but don't break preceding escape
  22846. const j = i > escEnd + 1 ? i - 2 : escStart - 1; // Bail out if lineWidth & minContentWidth are shorter than an escape string
  22847. if (escapedFolds[j]) return text;
  22848. folds.push(j);
  22849. escapedFolds[j] = true;
  22850. end = j + endStep;
  22851. split = undefined;
  22852. } else {
  22853. overflow = true;
  22854. }
  22855. }
  22856. }
  22857. prev = ch;
  22858. }
  22859. if (overflow && onOverflow) onOverflow();
  22860. if (folds.length === 0) return text;
  22861. if (onFold) onFold();
  22862. let res = text.slice(0, folds[0]);
  22863. for (let i = 0; i < folds.length; ++i) {
  22864. const fold = folds[i];
  22865. const end = folds[i + 1] || text.length;
  22866. if (fold === 0) res = `\n${indent}${text.slice(0, end)}`;else {
  22867. if (mode === FOLD_QUOTED && escapedFolds[fold]) res += `${text[fold]}\\`;
  22868. res += `\n${indent}${text.slice(fold + 1, end)}`;
  22869. }
  22870. }
  22871. return res;
  22872. }
  22873. const getFoldOptions = ({
  22874. indentAtStart
  22875. }) => indentAtStart ? Object.assign({
  22876. indentAtStart
  22877. }, strOptions.fold) : strOptions.fold; // Also checks for lines starting with %, as parsing the output as YAML 1.1 will
  22878. // presume that's starting a new document.
  22879. const containsDocumentMarker = str => /^(%|---|\.\.\.)/m.test(str);
  22880. function lineLengthOverLimit(str, lineWidth, indentLength) {
  22881. if (!lineWidth || lineWidth < 0) return false;
  22882. const limit = lineWidth - indentLength;
  22883. const strLen = str.length;
  22884. if (strLen <= limit) return false;
  22885. for (let i = 0, start = 0; i < strLen; ++i) {
  22886. if (str[i] === '\n') {
  22887. if (i - start > limit) return true;
  22888. start = i + 1;
  22889. if (strLen - start <= limit) return false;
  22890. }
  22891. }
  22892. return true;
  22893. }
  22894. function doubleQuotedString(value, ctx) {
  22895. const {
  22896. implicitKey
  22897. } = ctx;
  22898. const {
  22899. jsonEncoding,
  22900. minMultiLineLength
  22901. } = strOptions.doubleQuoted;
  22902. const json = JSON.stringify(value);
  22903. if (jsonEncoding) return json;
  22904. const indent = ctx.indent || (containsDocumentMarker(value) ? ' ' : '');
  22905. let str = '';
  22906. let start = 0;
  22907. for (let i = 0, ch = json[i]; ch; ch = json[++i]) {
  22908. if (ch === ' ' && json[i + 1] === '\\' && json[i + 2] === 'n') {
  22909. // space before newline needs to be escaped to not be folded
  22910. str += json.slice(start, i) + '\\ ';
  22911. i += 1;
  22912. start = i;
  22913. ch = '\\';
  22914. }
  22915. if (ch === '\\') switch (json[i + 1]) {
  22916. case 'u':
  22917. {
  22918. str += json.slice(start, i);
  22919. const code = json.substr(i + 2, 4);
  22920. switch (code) {
  22921. case '0000':
  22922. str += '\\0';
  22923. break;
  22924. case '0007':
  22925. str += '\\a';
  22926. break;
  22927. case '000b':
  22928. str += '\\v';
  22929. break;
  22930. case '001b':
  22931. str += '\\e';
  22932. break;
  22933. case '0085':
  22934. str += '\\N';
  22935. break;
  22936. case '00a0':
  22937. str += '\\_';
  22938. break;
  22939. case '2028':
  22940. str += '\\L';
  22941. break;
  22942. case '2029':
  22943. str += '\\P';
  22944. break;
  22945. default:
  22946. if (code.substr(0, 2) === '00') str += '\\x' + code.substr(2);else str += json.substr(i, 6);
  22947. }
  22948. i += 5;
  22949. start = i + 1;
  22950. }
  22951. break;
  22952. case 'n':
  22953. if (implicitKey || json[i + 2] === '"' || json.length < minMultiLineLength) {
  22954. i += 1;
  22955. } else {
  22956. // folding will eat first newline
  22957. str += json.slice(start, i) + '\n\n';
  22958. while (json[i + 2] === '\\' && json[i + 3] === 'n' && json[i + 4] !== '"') {
  22959. str += '\n';
  22960. i += 2;
  22961. }
  22962. str += indent; // space after newline needs to be escaped to not be folded
  22963. if (json[i + 2] === ' ') str += '\\';
  22964. i += 1;
  22965. start = i + 1;
  22966. }
  22967. break;
  22968. default:
  22969. i += 1;
  22970. }
  22971. }
  22972. str = start ? str + json.slice(start) : json;
  22973. return implicitKey ? str : foldFlowLines(str, indent, FOLD_QUOTED, getFoldOptions(ctx));
  22974. }
  22975. function singleQuotedString(value, ctx) {
  22976. if (ctx.implicitKey) {
  22977. if (/\n/.test(value)) return doubleQuotedString(value, ctx);
  22978. } else {
  22979. // single quoted string can't have leading or trailing whitespace around newline
  22980. if (/[ \t]\n|\n[ \t]/.test(value)) return doubleQuotedString(value, ctx);
  22981. }
  22982. const indent = ctx.indent || (containsDocumentMarker(value) ? ' ' : '');
  22983. const res = "'" + value.replace(/'/g, "''").replace(/\n+/g, `$&\n${indent}`) + "'";
  22984. return ctx.implicitKey ? res : foldFlowLines(res, indent, FOLD_FLOW, getFoldOptions(ctx));
  22985. }
  22986. function blockString({
  22987. comment,
  22988. type,
  22989. value
  22990. }, ctx, onComment, onChompKeep) {
  22991. // 1. Block can't end in whitespace unless the last line is non-empty.
  22992. // 2. Strings consisting of only whitespace are best rendered explicitly.
  22993. if (/\n[\t ]+$/.test(value) || /^\s*$/.test(value)) {
  22994. return doubleQuotedString(value, ctx);
  22995. }
  22996. const indent = ctx.indent || (ctx.forceBlockIndent || containsDocumentMarker(value) ? ' ' : '');
  22997. const indentSize = indent ? '2' : '1'; // root is at -1
  22998. const literal = type === PlainValue$4.Type.BLOCK_FOLDED ? false : type === PlainValue$4.Type.BLOCK_LITERAL ? true : !lineLengthOverLimit(value, strOptions.fold.lineWidth, indent.length);
  22999. let header = literal ? '|' : '>';
  23000. if (!value) return header + '\n';
  23001. let wsStart = '';
  23002. let wsEnd = '';
  23003. value = value.replace(/[\n\t ]*$/, ws => {
  23004. const n = ws.indexOf('\n');
  23005. if (n === -1) {
  23006. header += '-'; // strip
  23007. } else if (value === ws || n !== ws.length - 1) {
  23008. header += '+'; // keep
  23009. if (onChompKeep) onChompKeep();
  23010. }
  23011. wsEnd = ws.replace(/\n$/, '');
  23012. return '';
  23013. }).replace(/^[\n ]*/, ws => {
  23014. if (ws.indexOf(' ') !== -1) header += indentSize;
  23015. const m = ws.match(/ +$/);
  23016. if (m) {
  23017. wsStart = ws.slice(0, -m[0].length);
  23018. return m[0];
  23019. } else {
  23020. wsStart = ws;
  23021. return '';
  23022. }
  23023. });
  23024. if (wsEnd) wsEnd = wsEnd.replace(/\n+(?!\n|$)/g, `$&${indent}`);
  23025. if (wsStart) wsStart = wsStart.replace(/\n+/g, `$&${indent}`);
  23026. if (comment) {
  23027. header += ' #' + comment.replace(/ ?[\r\n]+/g, ' ');
  23028. if (onComment) onComment();
  23029. }
  23030. if (!value) return `${header}${indentSize}\n${indent}${wsEnd}`;
  23031. if (literal) {
  23032. value = value.replace(/\n+/g, `$&${indent}`);
  23033. return `${header}\n${indent}${wsStart}${value}${wsEnd}`;
  23034. }
  23035. value = value.replace(/\n+/g, '\n$&').replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, '$1$2') // more-indented lines aren't folded
  23036. // ^ ind.line ^ empty ^ capture next empty lines only at end of indent
  23037. .replace(/\n+/g, `$&${indent}`);
  23038. const body = foldFlowLines(`${wsStart}${value}${wsEnd}`, indent, FOLD_BLOCK, strOptions.fold);
  23039. return `${header}\n${indent}${body}`;
  23040. }
  23041. function plainString(item, ctx, onComment, onChompKeep) {
  23042. const {
  23043. comment,
  23044. type,
  23045. value
  23046. } = item;
  23047. const {
  23048. actualString,
  23049. implicitKey,
  23050. indent,
  23051. inFlow
  23052. } = ctx;
  23053. if (implicitKey && /[\n[\]{},]/.test(value) || inFlow && /[[\]{},]/.test(value)) {
  23054. return doubleQuotedString(value, ctx);
  23055. }
  23056. if (!value || /^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value)) {
  23057. // not allowed:
  23058. // - empty string, '-' or '?'
  23059. // - start with an indicator character (except [?:-]) or /[?-] /
  23060. // - '\n ', ': ' or ' \n' anywhere
  23061. // - '#' not preceded by a non-space char
  23062. // - end with ' ' or ':'
  23063. return implicitKey || inFlow || value.indexOf('\n') === -1 ? value.indexOf('"') !== -1 && value.indexOf("'") === -1 ? singleQuotedString(value, ctx) : doubleQuotedString(value, ctx) : blockString(item, ctx, onComment, onChompKeep);
  23064. }
  23065. if (!implicitKey && !inFlow && type !== PlainValue$4.Type.PLAIN && value.indexOf('\n') !== -1) {
  23066. // Where allowed & type not set explicitly, prefer block style for multiline strings
  23067. return blockString(item, ctx, onComment, onChompKeep);
  23068. }
  23069. if (indent === '' && containsDocumentMarker(value)) {
  23070. ctx.forceBlockIndent = true;
  23071. return blockString(item, ctx, onComment, onChompKeep);
  23072. }
  23073. const str = value.replace(/\n+/g, `$&\n${indent}`); // Verify that output will be parsed as a string, as e.g. plain numbers and
  23074. // booleans get parsed with those types in v1.2 (e.g. '42', 'true' & '0.9e-3'),
  23075. // and others in v1.1.
  23076. if (actualString) {
  23077. const {
  23078. tags
  23079. } = ctx.doc.schema;
  23080. const resolved = resolveScalar(str, tags, tags.scalarFallback).value;
  23081. if (typeof resolved !== 'string') return doubleQuotedString(value, ctx);
  23082. }
  23083. const body = implicitKey ? str : foldFlowLines(str, indent, FOLD_FLOW, getFoldOptions(ctx));
  23084. if (comment && !inFlow && (body.indexOf('\n') !== -1 || comment.indexOf('\n') !== -1)) {
  23085. if (onComment) onComment();
  23086. return addCommentBefore(body, indent, comment);
  23087. }
  23088. return body;
  23089. }
  23090. function stringifyString(item, ctx, onComment, onChompKeep) {
  23091. const {
  23092. defaultType
  23093. } = strOptions;
  23094. const {
  23095. implicitKey,
  23096. inFlow
  23097. } = ctx;
  23098. let {
  23099. type,
  23100. value
  23101. } = item;
  23102. if (typeof value !== 'string') {
  23103. value = String(value);
  23104. item = Object.assign({}, item, {
  23105. value
  23106. });
  23107. }
  23108. const _stringify = _type => {
  23109. switch (_type) {
  23110. case PlainValue$4.Type.BLOCK_FOLDED:
  23111. case PlainValue$4.Type.BLOCK_LITERAL:
  23112. return blockString(item, ctx, onComment, onChompKeep);
  23113. case PlainValue$4.Type.QUOTE_DOUBLE:
  23114. return doubleQuotedString(value, ctx);
  23115. case PlainValue$4.Type.QUOTE_SINGLE:
  23116. return singleQuotedString(value, ctx);
  23117. case PlainValue$4.Type.PLAIN:
  23118. return plainString(item, ctx, onComment, onChompKeep);
  23119. default:
  23120. return null;
  23121. }
  23122. };
  23123. if (type !== PlainValue$4.Type.QUOTE_DOUBLE && /[\x00-\x08\x0b-\x1f\x7f-\x9f]/.test(value)) {
  23124. // force double quotes on control characters
  23125. type = PlainValue$4.Type.QUOTE_DOUBLE;
  23126. } else if ((implicitKey || inFlow) && (type === PlainValue$4.Type.BLOCK_FOLDED || type === PlainValue$4.Type.BLOCK_LITERAL)) {
  23127. // should not happen; blocks are not valid inside flow containers
  23128. type = PlainValue$4.Type.QUOTE_DOUBLE;
  23129. }
  23130. let res = _stringify(type);
  23131. if (res === null) {
  23132. res = _stringify(defaultType);
  23133. if (res === null) throw new Error(`Unsupported default string type ${defaultType}`);
  23134. }
  23135. return res;
  23136. }
  23137. function stringifyNumber({
  23138. format,
  23139. minFractionDigits,
  23140. tag,
  23141. value
  23142. }) {
  23143. if (typeof value === 'bigint') return String(value);
  23144. if (!isFinite(value)) return isNaN(value) ? '.nan' : value < 0 ? '-.inf' : '.inf';
  23145. let n = JSON.stringify(value);
  23146. if (!format && minFractionDigits && (!tag || tag === 'tag:yaml.org,2002:float') && /^\d/.test(n)) {
  23147. let i = n.indexOf('.');
  23148. if (i < 0) {
  23149. i = n.length;
  23150. n += '.';
  23151. }
  23152. let d = minFractionDigits - (n.length - i - 1);
  23153. while (d-- > 0) n += '0';
  23154. }
  23155. return n;
  23156. }
  23157. function checkFlowCollectionEnd(errors, cst) {
  23158. let char, name;
  23159. switch (cst.type) {
  23160. case PlainValue$4.Type.FLOW_MAP:
  23161. char = '}';
  23162. name = 'flow map';
  23163. break;
  23164. case PlainValue$4.Type.FLOW_SEQ:
  23165. char = ']';
  23166. name = 'flow sequence';
  23167. break;
  23168. default:
  23169. errors.push(new PlainValue$4.YAMLSemanticError(cst, 'Not a flow collection!?'));
  23170. return;
  23171. }
  23172. let lastItem;
  23173. for (let i = cst.items.length - 1; i >= 0; --i) {
  23174. const item = cst.items[i];
  23175. if (!item || item.type !== PlainValue$4.Type.COMMENT) {
  23176. lastItem = item;
  23177. break;
  23178. }
  23179. }
  23180. if (lastItem && lastItem.char !== char) {
  23181. const msg = `Expected ${name} to end with ${char}`;
  23182. let err;
  23183. if (typeof lastItem.offset === 'number') {
  23184. err = new PlainValue$4.YAMLSemanticError(cst, msg);
  23185. err.offset = lastItem.offset + 1;
  23186. } else {
  23187. err = new PlainValue$4.YAMLSemanticError(lastItem, msg);
  23188. if (lastItem.range && lastItem.range.end) err.offset = lastItem.range.end - lastItem.range.start;
  23189. }
  23190. errors.push(err);
  23191. }
  23192. }
  23193. function checkFlowCommentSpace(errors, comment) {
  23194. const prev = comment.context.src[comment.range.start - 1];
  23195. if (prev !== '\n' && prev !== '\t' && prev !== ' ') {
  23196. const msg = 'Comments must be separated from other tokens by white space characters';
  23197. errors.push(new PlainValue$4.YAMLSemanticError(comment, msg));
  23198. }
  23199. }
  23200. function getLongKeyError(source, key) {
  23201. const sk = String(key);
  23202. const k = sk.substr(0, 8) + '...' + sk.substr(-8);
  23203. return new PlainValue$4.YAMLSemanticError(source, `The "${k}" key is too long`);
  23204. }
  23205. function resolveComments(collection, comments) {
  23206. for (const {
  23207. afterKey,
  23208. before,
  23209. comment
  23210. } of comments) {
  23211. let item = collection.items[before];
  23212. if (!item) {
  23213. if (comment !== undefined) {
  23214. if (collection.comment) collection.comment += '\n' + comment;else collection.comment = comment;
  23215. }
  23216. } else {
  23217. if (afterKey && item.value) item = item.value;
  23218. if (comment === undefined) {
  23219. if (afterKey || !item.commentBefore) item.spaceBefore = true;
  23220. } else {
  23221. if (item.commentBefore) item.commentBefore += '\n' + comment;else item.commentBefore = comment;
  23222. }
  23223. }
  23224. }
  23225. }
  23226. // on error, will return { str: string, errors: Error[] }
  23227. function resolveString(doc, node) {
  23228. const res = node.strValue;
  23229. if (!res) return '';
  23230. if (typeof res === 'string') return res;
  23231. res.errors.forEach(error => {
  23232. if (!error.source) error.source = node;
  23233. doc.errors.push(error);
  23234. });
  23235. return res.str;
  23236. }
  23237. function resolveTagHandle(doc, node) {
  23238. const {
  23239. handle,
  23240. suffix
  23241. } = node.tag;
  23242. let prefix = doc.tagPrefixes.find(p => p.handle === handle);
  23243. if (!prefix) {
  23244. const dtp = doc.getDefaults().tagPrefixes;
  23245. if (dtp) prefix = dtp.find(p => p.handle === handle);
  23246. if (!prefix) throw new PlainValue$4.YAMLSemanticError(node, `The ${handle} tag handle is non-default and was not declared.`);
  23247. }
  23248. if (!suffix) throw new PlainValue$4.YAMLSemanticError(node, `The ${handle} tag has no suffix.`);
  23249. if (handle === '!' && (doc.version || doc.options.version) === '1.0') {
  23250. if (suffix[0] === '^') {
  23251. doc.warnings.push(new PlainValue$4.YAMLWarning(node, 'YAML 1.0 ^ tag expansion is not supported'));
  23252. return suffix;
  23253. }
  23254. if (/[:/]/.test(suffix)) {
  23255. // word/foo -> tag:word.yaml.org,2002:foo
  23256. const vocab = suffix.match(/^([a-z0-9-]+)\/(.*)/i);
  23257. return vocab ? `tag:${vocab[1]}.yaml.org,2002:${vocab[2]}` : `tag:${suffix}`;
  23258. }
  23259. }
  23260. return prefix.prefix + decodeURIComponent(suffix);
  23261. }
  23262. function resolveTagName(doc, node) {
  23263. const {
  23264. tag,
  23265. type
  23266. } = node;
  23267. let nonSpecific = false;
  23268. if (tag) {
  23269. const {
  23270. handle,
  23271. suffix,
  23272. verbatim
  23273. } = tag;
  23274. if (verbatim) {
  23275. if (verbatim !== '!' && verbatim !== '!!') return verbatim;
  23276. const msg = `Verbatim tags aren't resolved, so ${verbatim} is invalid.`;
  23277. doc.errors.push(new PlainValue$4.YAMLSemanticError(node, msg));
  23278. } else if (handle === '!' && !suffix) {
  23279. nonSpecific = true;
  23280. } else {
  23281. try {
  23282. return resolveTagHandle(doc, node);
  23283. } catch (error) {
  23284. doc.errors.push(error);
  23285. }
  23286. }
  23287. }
  23288. switch (type) {
  23289. case PlainValue$4.Type.BLOCK_FOLDED:
  23290. case PlainValue$4.Type.BLOCK_LITERAL:
  23291. case PlainValue$4.Type.QUOTE_DOUBLE:
  23292. case PlainValue$4.Type.QUOTE_SINGLE:
  23293. return PlainValue$4.defaultTags.STR;
  23294. case PlainValue$4.Type.FLOW_MAP:
  23295. case PlainValue$4.Type.MAP:
  23296. return PlainValue$4.defaultTags.MAP;
  23297. case PlainValue$4.Type.FLOW_SEQ:
  23298. case PlainValue$4.Type.SEQ:
  23299. return PlainValue$4.defaultTags.SEQ;
  23300. case PlainValue$4.Type.PLAIN:
  23301. return nonSpecific ? PlainValue$4.defaultTags.STR : null;
  23302. default:
  23303. return null;
  23304. }
  23305. }
  23306. function resolveByTagName(doc, node, tagName) {
  23307. const {
  23308. tags
  23309. } = doc.schema;
  23310. const matchWithTest = [];
  23311. for (const tag of tags) {
  23312. if (tag.tag === tagName) {
  23313. if (tag.test) matchWithTest.push(tag);else {
  23314. const res = tag.resolve(doc, node);
  23315. return res instanceof Collection ? res : new Scalar(res);
  23316. }
  23317. }
  23318. }
  23319. const str = resolveString(doc, node);
  23320. if (typeof str === 'string' && matchWithTest.length > 0) return resolveScalar(str, matchWithTest, tags.scalarFallback);
  23321. return null;
  23322. }
  23323. function getFallbackTagName({
  23324. type
  23325. }) {
  23326. switch (type) {
  23327. case PlainValue$4.Type.FLOW_MAP:
  23328. case PlainValue$4.Type.MAP:
  23329. return PlainValue$4.defaultTags.MAP;
  23330. case PlainValue$4.Type.FLOW_SEQ:
  23331. case PlainValue$4.Type.SEQ:
  23332. return PlainValue$4.defaultTags.SEQ;
  23333. default:
  23334. return PlainValue$4.defaultTags.STR;
  23335. }
  23336. }
  23337. function resolveTag(doc, node, tagName) {
  23338. try {
  23339. const res = resolveByTagName(doc, node, tagName);
  23340. if (res) {
  23341. if (tagName && node.tag) res.tag = tagName;
  23342. return res;
  23343. }
  23344. } catch (error) {
  23345. /* istanbul ignore if */
  23346. if (!error.source) error.source = node;
  23347. doc.errors.push(error);
  23348. return null;
  23349. }
  23350. try {
  23351. const fallback = getFallbackTagName(node);
  23352. if (!fallback) throw new Error(`The tag ${tagName} is unavailable`);
  23353. const msg = `The tag ${tagName} is unavailable, falling back to ${fallback}`;
  23354. doc.warnings.push(new PlainValue$4.YAMLWarning(node, msg));
  23355. const res = resolveByTagName(doc, node, fallback);
  23356. res.tag = tagName;
  23357. return res;
  23358. } catch (error) {
  23359. const refError = new PlainValue$4.YAMLReferenceError(node, error.message);
  23360. refError.stack = error.stack;
  23361. doc.errors.push(refError);
  23362. return null;
  23363. }
  23364. }
  23365. const isCollectionItem = node => {
  23366. if (!node) return false;
  23367. const {
  23368. type
  23369. } = node;
  23370. return type === PlainValue$4.Type.MAP_KEY || type === PlainValue$4.Type.MAP_VALUE || type === PlainValue$4.Type.SEQ_ITEM;
  23371. };
  23372. function resolveNodeProps(errors, node) {
  23373. const comments = {
  23374. before: [],
  23375. after: []
  23376. };
  23377. let hasAnchor = false;
  23378. let hasTag = false;
  23379. const props = isCollectionItem(node.context.parent) ? node.context.parent.props.concat(node.props) : node.props;
  23380. for (const {
  23381. start,
  23382. end
  23383. } of props) {
  23384. switch (node.context.src[start]) {
  23385. case PlainValue$4.Char.COMMENT:
  23386. {
  23387. if (!node.commentHasRequiredWhitespace(start)) {
  23388. const msg = 'Comments must be separated from other tokens by white space characters';
  23389. errors.push(new PlainValue$4.YAMLSemanticError(node, msg));
  23390. }
  23391. const {
  23392. header,
  23393. valueRange
  23394. } = node;
  23395. const cc = valueRange && (start > valueRange.start || header && start > header.start) ? comments.after : comments.before;
  23396. cc.push(node.context.src.slice(start + 1, end));
  23397. break;
  23398. }
  23399. // Actual anchor & tag resolution is handled by schema, here we just complain
  23400. case PlainValue$4.Char.ANCHOR:
  23401. if (hasAnchor) {
  23402. const msg = 'A node can have at most one anchor';
  23403. errors.push(new PlainValue$4.YAMLSemanticError(node, msg));
  23404. }
  23405. hasAnchor = true;
  23406. break;
  23407. case PlainValue$4.Char.TAG:
  23408. if (hasTag) {
  23409. const msg = 'A node can have at most one tag';
  23410. errors.push(new PlainValue$4.YAMLSemanticError(node, msg));
  23411. }
  23412. hasTag = true;
  23413. break;
  23414. }
  23415. }
  23416. return {
  23417. comments,
  23418. hasAnchor,
  23419. hasTag
  23420. };
  23421. }
  23422. function resolveNodeValue(doc, node) {
  23423. const {
  23424. anchors,
  23425. errors,
  23426. schema
  23427. } = doc;
  23428. if (node.type === PlainValue$4.Type.ALIAS) {
  23429. const name = node.rawValue;
  23430. const src = anchors.getNode(name);
  23431. if (!src) {
  23432. const msg = `Aliased anchor not found: ${name}`;
  23433. errors.push(new PlainValue$4.YAMLReferenceError(node, msg));
  23434. return null;
  23435. } // Lazy resolution for circular references
  23436. const res = new Alias(src);
  23437. anchors._cstAliases.push(res);
  23438. return res;
  23439. }
  23440. const tagName = resolveTagName(doc, node);
  23441. if (tagName) return resolveTag(doc, node, tagName);
  23442. if (node.type !== PlainValue$4.Type.PLAIN) {
  23443. const msg = `Failed to resolve ${node.type} node here`;
  23444. errors.push(new PlainValue$4.YAMLSyntaxError(node, msg));
  23445. return null;
  23446. }
  23447. try {
  23448. const str = resolveString(doc, node);
  23449. return resolveScalar(str, schema.tags, schema.tags.scalarFallback);
  23450. } catch (error) {
  23451. if (!error.source) error.source = node;
  23452. errors.push(error);
  23453. return null;
  23454. }
  23455. } // sets node.resolved on success
  23456. function resolveNode(doc, node) {
  23457. if (!node) return null;
  23458. if (node.error) doc.errors.push(node.error);
  23459. const {
  23460. comments,
  23461. hasAnchor,
  23462. hasTag
  23463. } = resolveNodeProps(doc.errors, node);
  23464. if (hasAnchor) {
  23465. const {
  23466. anchors
  23467. } = doc;
  23468. const name = node.anchor;
  23469. const prev = anchors.getNode(name); // At this point, aliases for any preceding node with the same anchor
  23470. // name have already been resolved, so it may safely be renamed.
  23471. if (prev) anchors.map[anchors.newName(name)] = prev; // During parsing, we need to store the CST node in anchors.map as
  23472. // anchors need to be available during resolution to allow for
  23473. // circular references.
  23474. anchors.map[name] = node;
  23475. }
  23476. if (node.type === PlainValue$4.Type.ALIAS && (hasAnchor || hasTag)) {
  23477. const msg = 'An alias node must not specify any properties';
  23478. doc.errors.push(new PlainValue$4.YAMLSemanticError(node, msg));
  23479. }
  23480. const res = resolveNodeValue(doc, node);
  23481. if (res) {
  23482. res.range = [node.range.start, node.range.end];
  23483. if (doc.options.keepCstNodes) res.cstNode = node;
  23484. if (doc.options.keepNodeTypes) res.type = node.type;
  23485. const cb = comments.before.join('\n');
  23486. if (cb) {
  23487. res.commentBefore = res.commentBefore ? `${res.commentBefore}\n${cb}` : cb;
  23488. }
  23489. const ca = comments.after.join('\n');
  23490. if (ca) res.comment = res.comment ? `${res.comment}\n${ca}` : ca;
  23491. }
  23492. return node.resolved = res;
  23493. }
  23494. function resolveMap(doc, cst) {
  23495. if (cst.type !== PlainValue$4.Type.MAP && cst.type !== PlainValue$4.Type.FLOW_MAP) {
  23496. const msg = `A ${cst.type} node cannot be resolved as a mapping`;
  23497. doc.errors.push(new PlainValue$4.YAMLSyntaxError(cst, msg));
  23498. return null;
  23499. }
  23500. const {
  23501. comments,
  23502. items
  23503. } = cst.type === PlainValue$4.Type.FLOW_MAP ? resolveFlowMapItems(doc, cst) : resolveBlockMapItems(doc, cst);
  23504. const map = new YAMLMap();
  23505. map.items = items;
  23506. resolveComments(map, comments);
  23507. let hasCollectionKey = false;
  23508. for (let i = 0; i < items.length; ++i) {
  23509. const {
  23510. key: iKey
  23511. } = items[i];
  23512. if (iKey instanceof Collection) hasCollectionKey = true;
  23513. if (doc.schema.merge && iKey && iKey.value === MERGE_KEY) {
  23514. items[i] = new Merge(items[i]);
  23515. const sources = items[i].value.items;
  23516. let error = null;
  23517. sources.some(node => {
  23518. if (node instanceof Alias) {
  23519. // During parsing, alias sources are CST nodes; to account for
  23520. // circular references their resolved values can't be used here.
  23521. const {
  23522. type
  23523. } = node.source;
  23524. if (type === PlainValue$4.Type.MAP || type === PlainValue$4.Type.FLOW_MAP) return false;
  23525. return error = 'Merge nodes aliases can only point to maps';
  23526. }
  23527. return error = 'Merge nodes can only have Alias nodes as values';
  23528. });
  23529. if (error) doc.errors.push(new PlainValue$4.YAMLSemanticError(cst, error));
  23530. } else {
  23531. for (let j = i + 1; j < items.length; ++j) {
  23532. const {
  23533. key: jKey
  23534. } = items[j];
  23535. if (iKey === jKey || iKey && jKey && Object.prototype.hasOwnProperty.call(iKey, 'value') && iKey.value === jKey.value) {
  23536. const msg = `Map keys must be unique; "${iKey}" is repeated`;
  23537. doc.errors.push(new PlainValue$4.YAMLSemanticError(cst, msg));
  23538. break;
  23539. }
  23540. }
  23541. }
  23542. }
  23543. if (hasCollectionKey && !doc.options.mapAsMap) {
  23544. const warn = 'Keys with collection values will be stringified as YAML due to JS Object restrictions. Use mapAsMap: true to avoid this.';
  23545. doc.warnings.push(new PlainValue$4.YAMLWarning(cst, warn));
  23546. }
  23547. cst.resolved = map;
  23548. return map;
  23549. }
  23550. const valueHasPairComment = ({
  23551. context: {
  23552. lineStart,
  23553. node,
  23554. src
  23555. },
  23556. props
  23557. }) => {
  23558. if (props.length === 0) return false;
  23559. const {
  23560. start
  23561. } = props[0];
  23562. if (node && start > node.valueRange.start) return false;
  23563. if (src[start] !== PlainValue$4.Char.COMMENT) return false;
  23564. for (let i = lineStart; i < start; ++i) if (src[i] === '\n') return false;
  23565. return true;
  23566. };
  23567. function resolvePairComment(item, pair) {
  23568. if (!valueHasPairComment(item)) return;
  23569. const comment = item.getPropValue(0, PlainValue$4.Char.COMMENT, true);
  23570. let found = false;
  23571. const cb = pair.value.commentBefore;
  23572. if (cb && cb.startsWith(comment)) {
  23573. pair.value.commentBefore = cb.substr(comment.length + 1);
  23574. found = true;
  23575. } else {
  23576. const cc = pair.value.comment;
  23577. if (!item.node && cc && cc.startsWith(comment)) {
  23578. pair.value.comment = cc.substr(comment.length + 1);
  23579. found = true;
  23580. }
  23581. }
  23582. if (found) pair.comment = comment;
  23583. }
  23584. function resolveBlockMapItems(doc, cst) {
  23585. const comments = [];
  23586. const items = [];
  23587. let key = undefined;
  23588. let keyStart = null;
  23589. for (let i = 0; i < cst.items.length; ++i) {
  23590. const item = cst.items[i];
  23591. switch (item.type) {
  23592. case PlainValue$4.Type.BLANK_LINE:
  23593. comments.push({
  23594. afterKey: !!key,
  23595. before: items.length
  23596. });
  23597. break;
  23598. case PlainValue$4.Type.COMMENT:
  23599. comments.push({
  23600. afterKey: !!key,
  23601. before: items.length,
  23602. comment: item.comment
  23603. });
  23604. break;
  23605. case PlainValue$4.Type.MAP_KEY:
  23606. if (key !== undefined) items.push(new Pair(key));
  23607. if (item.error) doc.errors.push(item.error);
  23608. key = resolveNode(doc, item.node);
  23609. keyStart = null;
  23610. break;
  23611. case PlainValue$4.Type.MAP_VALUE:
  23612. {
  23613. if (key === undefined) key = null;
  23614. if (item.error) doc.errors.push(item.error);
  23615. if (!item.context.atLineStart && item.node && item.node.type === PlainValue$4.Type.MAP && !item.node.context.atLineStart) {
  23616. const msg = 'Nested mappings are not allowed in compact mappings';
  23617. doc.errors.push(new PlainValue$4.YAMLSemanticError(item.node, msg));
  23618. }
  23619. let valueNode = item.node;
  23620. if (!valueNode && item.props.length > 0) {
  23621. // Comments on an empty mapping value need to be preserved, so we
  23622. // need to construct a minimal empty node here to use instead of the
  23623. // missing `item.node`. -- eemeli/yaml#19
  23624. valueNode = new PlainValue$4.PlainValue(PlainValue$4.Type.PLAIN, []);
  23625. valueNode.context = {
  23626. parent: item,
  23627. src: item.context.src
  23628. };
  23629. const pos = item.range.start + 1;
  23630. valueNode.range = {
  23631. start: pos,
  23632. end: pos
  23633. };
  23634. valueNode.valueRange = {
  23635. start: pos,
  23636. end: pos
  23637. };
  23638. if (typeof item.range.origStart === 'number') {
  23639. const origPos = item.range.origStart + 1;
  23640. valueNode.range.origStart = valueNode.range.origEnd = origPos;
  23641. valueNode.valueRange.origStart = valueNode.valueRange.origEnd = origPos;
  23642. }
  23643. }
  23644. const pair = new Pair(key, resolveNode(doc, valueNode));
  23645. resolvePairComment(item, pair);
  23646. items.push(pair);
  23647. if (key && typeof keyStart === 'number') {
  23648. if (item.range.start > keyStart + 1024) doc.errors.push(getLongKeyError(cst, key));
  23649. }
  23650. key = undefined;
  23651. keyStart = null;
  23652. }
  23653. break;
  23654. default:
  23655. if (key !== undefined) items.push(new Pair(key));
  23656. key = resolveNode(doc, item);
  23657. keyStart = item.range.start;
  23658. if (item.error) doc.errors.push(item.error);
  23659. next: for (let j = i + 1;; ++j) {
  23660. const nextItem = cst.items[j];
  23661. switch (nextItem && nextItem.type) {
  23662. case PlainValue$4.Type.BLANK_LINE:
  23663. case PlainValue$4.Type.COMMENT:
  23664. continue next;
  23665. case PlainValue$4.Type.MAP_VALUE:
  23666. break next;
  23667. default:
  23668. {
  23669. const msg = 'Implicit map keys need to be followed by map values';
  23670. doc.errors.push(new PlainValue$4.YAMLSemanticError(item, msg));
  23671. break next;
  23672. }
  23673. }
  23674. }
  23675. if (item.valueRangeContainsNewline) {
  23676. const msg = 'Implicit map keys need to be on a single line';
  23677. doc.errors.push(new PlainValue$4.YAMLSemanticError(item, msg));
  23678. }
  23679. }
  23680. }
  23681. if (key !== undefined) items.push(new Pair(key));
  23682. return {
  23683. comments,
  23684. items
  23685. };
  23686. }
  23687. function resolveFlowMapItems(doc, cst) {
  23688. const comments = [];
  23689. const items = [];
  23690. let key = undefined;
  23691. let explicitKey = false;
  23692. let next = '{';
  23693. for (let i = 0; i < cst.items.length; ++i) {
  23694. const item = cst.items[i];
  23695. if (typeof item.char === 'string') {
  23696. const {
  23697. char,
  23698. offset
  23699. } = item;
  23700. if (char === '?' && key === undefined && !explicitKey) {
  23701. explicitKey = true;
  23702. next = ':';
  23703. continue;
  23704. }
  23705. if (char === ':') {
  23706. if (key === undefined) key = null;
  23707. if (next === ':') {
  23708. next = ',';
  23709. continue;
  23710. }
  23711. } else {
  23712. if (explicitKey) {
  23713. if (key === undefined && char !== ',') key = null;
  23714. explicitKey = false;
  23715. }
  23716. if (key !== undefined) {
  23717. items.push(new Pair(key));
  23718. key = undefined;
  23719. if (char === ',') {
  23720. next = ':';
  23721. continue;
  23722. }
  23723. }
  23724. }
  23725. if (char === '}') {
  23726. if (i === cst.items.length - 1) continue;
  23727. } else if (char === next) {
  23728. next = ':';
  23729. continue;
  23730. }
  23731. const msg = `Flow map contains an unexpected ${char}`;
  23732. const err = new PlainValue$4.YAMLSyntaxError(cst, msg);
  23733. err.offset = offset;
  23734. doc.errors.push(err);
  23735. } else if (item.type === PlainValue$4.Type.BLANK_LINE) {
  23736. comments.push({
  23737. afterKey: !!key,
  23738. before: items.length
  23739. });
  23740. } else if (item.type === PlainValue$4.Type.COMMENT) {
  23741. checkFlowCommentSpace(doc.errors, item);
  23742. comments.push({
  23743. afterKey: !!key,
  23744. before: items.length,
  23745. comment: item.comment
  23746. });
  23747. } else if (key === undefined) {
  23748. if (next === ',') doc.errors.push(new PlainValue$4.YAMLSemanticError(item, 'Separator , missing in flow map'));
  23749. key = resolveNode(doc, item);
  23750. } else {
  23751. if (next !== ',') doc.errors.push(new PlainValue$4.YAMLSemanticError(item, 'Indicator : missing in flow map entry'));
  23752. items.push(new Pair(key, resolveNode(doc, item)));
  23753. key = undefined;
  23754. explicitKey = false;
  23755. }
  23756. }
  23757. checkFlowCollectionEnd(doc.errors, cst);
  23758. if (key !== undefined) items.push(new Pair(key));
  23759. return {
  23760. comments,
  23761. items
  23762. };
  23763. }
  23764. function resolveSeq$3(doc, cst) {
  23765. if (cst.type !== PlainValue$4.Type.SEQ && cst.type !== PlainValue$4.Type.FLOW_SEQ) {
  23766. const msg = `A ${cst.type} node cannot be resolved as a sequence`;
  23767. doc.errors.push(new PlainValue$4.YAMLSyntaxError(cst, msg));
  23768. return null;
  23769. }
  23770. const {
  23771. comments,
  23772. items
  23773. } = cst.type === PlainValue$4.Type.FLOW_SEQ ? resolveFlowSeqItems(doc, cst) : resolveBlockSeqItems(doc, cst);
  23774. const seq = new YAMLSeq();
  23775. seq.items = items;
  23776. resolveComments(seq, comments);
  23777. if (!doc.options.mapAsMap && items.some(it => it instanceof Pair && it.key instanceof Collection)) {
  23778. const warn = 'Keys with collection values will be stringified as YAML due to JS Object restrictions. Use mapAsMap: true to avoid this.';
  23779. doc.warnings.push(new PlainValue$4.YAMLWarning(cst, warn));
  23780. }
  23781. cst.resolved = seq;
  23782. return seq;
  23783. }
  23784. function resolveBlockSeqItems(doc, cst) {
  23785. const comments = [];
  23786. const items = [];
  23787. for (let i = 0; i < cst.items.length; ++i) {
  23788. const item = cst.items[i];
  23789. switch (item.type) {
  23790. case PlainValue$4.Type.BLANK_LINE:
  23791. comments.push({
  23792. before: items.length
  23793. });
  23794. break;
  23795. case PlainValue$4.Type.COMMENT:
  23796. comments.push({
  23797. comment: item.comment,
  23798. before: items.length
  23799. });
  23800. break;
  23801. case PlainValue$4.Type.SEQ_ITEM:
  23802. if (item.error) doc.errors.push(item.error);
  23803. items.push(resolveNode(doc, item.node));
  23804. if (item.hasProps) {
  23805. const msg = 'Sequence items cannot have tags or anchors before the - indicator';
  23806. doc.errors.push(new PlainValue$4.YAMLSemanticError(item, msg));
  23807. }
  23808. break;
  23809. default:
  23810. if (item.error) doc.errors.push(item.error);
  23811. doc.errors.push(new PlainValue$4.YAMLSyntaxError(item, `Unexpected ${item.type} node in sequence`));
  23812. }
  23813. }
  23814. return {
  23815. comments,
  23816. items
  23817. };
  23818. }
  23819. function resolveFlowSeqItems(doc, cst) {
  23820. const comments = [];
  23821. const items = [];
  23822. let explicitKey = false;
  23823. let key = undefined;
  23824. let keyStart = null;
  23825. let next = '[';
  23826. let prevItem = null;
  23827. for (let i = 0; i < cst.items.length; ++i) {
  23828. const item = cst.items[i];
  23829. if (typeof item.char === 'string') {
  23830. const {
  23831. char,
  23832. offset
  23833. } = item;
  23834. if (char !== ':' && (explicitKey || key !== undefined)) {
  23835. if (explicitKey && key === undefined) key = next ? items.pop() : null;
  23836. items.push(new Pair(key));
  23837. explicitKey = false;
  23838. key = undefined;
  23839. keyStart = null;
  23840. }
  23841. if (char === next) {
  23842. next = null;
  23843. } else if (!next && char === '?') {
  23844. explicitKey = true;
  23845. } else if (next !== '[' && char === ':' && key === undefined) {
  23846. if (next === ',') {
  23847. key = items.pop();
  23848. if (key instanceof Pair) {
  23849. const msg = 'Chaining flow sequence pairs is invalid';
  23850. const err = new PlainValue$4.YAMLSemanticError(cst, msg);
  23851. err.offset = offset;
  23852. doc.errors.push(err);
  23853. }
  23854. if (!explicitKey && typeof keyStart === 'number') {
  23855. const keyEnd = item.range ? item.range.start : item.offset;
  23856. if (keyEnd > keyStart + 1024) doc.errors.push(getLongKeyError(cst, key));
  23857. const {
  23858. src
  23859. } = prevItem.context;
  23860. for (let i = keyStart; i < keyEnd; ++i) if (src[i] === '\n') {
  23861. const msg = 'Implicit keys of flow sequence pairs need to be on a single line';
  23862. doc.errors.push(new PlainValue$4.YAMLSemanticError(prevItem, msg));
  23863. break;
  23864. }
  23865. }
  23866. } else {
  23867. key = null;
  23868. }
  23869. keyStart = null;
  23870. explicitKey = false;
  23871. next = null;
  23872. } else if (next === '[' || char !== ']' || i < cst.items.length - 1) {
  23873. const msg = `Flow sequence contains an unexpected ${char}`;
  23874. const err = new PlainValue$4.YAMLSyntaxError(cst, msg);
  23875. err.offset = offset;
  23876. doc.errors.push(err);
  23877. }
  23878. } else if (item.type === PlainValue$4.Type.BLANK_LINE) {
  23879. comments.push({
  23880. before: items.length
  23881. });
  23882. } else if (item.type === PlainValue$4.Type.COMMENT) {
  23883. checkFlowCommentSpace(doc.errors, item);
  23884. comments.push({
  23885. comment: item.comment,
  23886. before: items.length
  23887. });
  23888. } else {
  23889. if (next) {
  23890. const msg = `Expected a ${next} in flow sequence`;
  23891. doc.errors.push(new PlainValue$4.YAMLSemanticError(item, msg));
  23892. }
  23893. const value = resolveNode(doc, item);
  23894. if (key === undefined) {
  23895. items.push(value);
  23896. prevItem = item;
  23897. } else {
  23898. items.push(new Pair(key, value));
  23899. key = undefined;
  23900. }
  23901. keyStart = item.range.start;
  23902. next = ',';
  23903. }
  23904. }
  23905. checkFlowCollectionEnd(doc.errors, cst);
  23906. if (key !== undefined) items.push(new Pair(key));
  23907. return {
  23908. comments,
  23909. items
  23910. };
  23911. }
  23912. resolveSeqD03cb037.Alias = Alias;
  23913. resolveSeqD03cb037.Collection = Collection;
  23914. resolveSeqD03cb037.Merge = Merge;
  23915. resolveSeqD03cb037.Node = Node$1;
  23916. resolveSeqD03cb037.Pair = Pair;
  23917. resolveSeqD03cb037.Scalar = Scalar;
  23918. resolveSeqD03cb037.YAMLMap = YAMLMap;
  23919. resolveSeqD03cb037.YAMLSeq = YAMLSeq;
  23920. resolveSeqD03cb037.addComment = addComment;
  23921. resolveSeqD03cb037.binaryOptions = binaryOptions;
  23922. resolveSeqD03cb037.boolOptions = boolOptions;
  23923. resolveSeqD03cb037.findPair = findPair;
  23924. resolveSeqD03cb037.intOptions = intOptions;
  23925. resolveSeqD03cb037.isEmptyPath = isEmptyPath;
  23926. resolveSeqD03cb037.nullOptions = nullOptions;
  23927. resolveSeqD03cb037.resolveMap = resolveMap;
  23928. resolveSeqD03cb037.resolveNode = resolveNode;
  23929. resolveSeqD03cb037.resolveSeq = resolveSeq$3;
  23930. resolveSeqD03cb037.resolveString = resolveString;
  23931. resolveSeqD03cb037.strOptions = strOptions;
  23932. resolveSeqD03cb037.stringifyNumber = stringifyNumber;
  23933. resolveSeqD03cb037.stringifyString = stringifyString;
  23934. resolveSeqD03cb037.toJSON = toJSON;
  23935. var Schema88e323a7 = {};
  23936. var warnings1000a372 = {};
  23937. var PlainValue$3 = PlainValueEc8e588e;
  23938. var resolveSeq$2 = resolveSeqD03cb037;
  23939. /* global atob, btoa, Buffer */
  23940. const binary = {
  23941. identify: value => value instanceof Uint8Array,
  23942. // Buffer inherits from Uint8Array
  23943. default: false,
  23944. tag: 'tag:yaml.org,2002:binary',
  23945. /**
  23946. * Returns a Buffer in node and an Uint8Array in browsers
  23947. *
  23948. * To use the resulting buffer as an image, you'll want to do something like:
  23949. *
  23950. * const blob = new Blob([buffer], { type: 'image/jpeg' })
  23951. * document.querySelector('#photo').src = URL.createObjectURL(blob)
  23952. */
  23953. resolve: (doc, node) => {
  23954. const src = resolveSeq$2.resolveString(doc, node);
  23955. if (typeof Buffer === 'function') {
  23956. return Buffer.from(src, 'base64');
  23957. } else if (typeof atob === 'function') {
  23958. // On IE 11, atob() can't handle newlines
  23959. const str = atob(src.replace(/[\n\r]/g, ''));
  23960. const buffer = new Uint8Array(str.length);
  23961. for (let i = 0; i < str.length; ++i) buffer[i] = str.charCodeAt(i);
  23962. return buffer;
  23963. } else {
  23964. const msg = 'This environment does not support reading binary tags; either Buffer or atob is required';
  23965. doc.errors.push(new PlainValue$3.YAMLReferenceError(node, msg));
  23966. return null;
  23967. }
  23968. },
  23969. options: resolveSeq$2.binaryOptions,
  23970. stringify: ({
  23971. comment,
  23972. type,
  23973. value
  23974. }, ctx, onComment, onChompKeep) => {
  23975. let src;
  23976. if (typeof Buffer === 'function') {
  23977. src = value instanceof Buffer ? value.toString('base64') : Buffer.from(value.buffer).toString('base64');
  23978. } else if (typeof btoa === 'function') {
  23979. let s = '';
  23980. for (let i = 0; i < value.length; ++i) s += String.fromCharCode(value[i]);
  23981. src = btoa(s);
  23982. } else {
  23983. throw new Error('This environment does not support writing binary tags; either Buffer or btoa is required');
  23984. }
  23985. if (!type) type = resolveSeq$2.binaryOptions.defaultType;
  23986. if (type === PlainValue$3.Type.QUOTE_DOUBLE) {
  23987. value = src;
  23988. } else {
  23989. const {
  23990. lineWidth
  23991. } = resolveSeq$2.binaryOptions;
  23992. const n = Math.ceil(src.length / lineWidth);
  23993. const lines = new Array(n);
  23994. for (let i = 0, o = 0; i < n; ++i, o += lineWidth) {
  23995. lines[i] = src.substr(o, lineWidth);
  23996. }
  23997. value = lines.join(type === PlainValue$3.Type.BLOCK_LITERAL ? '\n' : ' ');
  23998. }
  23999. return resolveSeq$2.stringifyString({
  24000. comment,
  24001. type,
  24002. value
  24003. }, ctx, onComment, onChompKeep);
  24004. }
  24005. };
  24006. function parsePairs(doc, cst) {
  24007. const seq = resolveSeq$2.resolveSeq(doc, cst);
  24008. for (let i = 0; i < seq.items.length; ++i) {
  24009. let item = seq.items[i];
  24010. if (item instanceof resolveSeq$2.Pair) continue;else if (item instanceof resolveSeq$2.YAMLMap) {
  24011. if (item.items.length > 1) {
  24012. const msg = 'Each pair must have its own sequence indicator';
  24013. throw new PlainValue$3.YAMLSemanticError(cst, msg);
  24014. }
  24015. const pair = item.items[0] || new resolveSeq$2.Pair();
  24016. if (item.commentBefore) pair.commentBefore = pair.commentBefore ? `${item.commentBefore}\n${pair.commentBefore}` : item.commentBefore;
  24017. if (item.comment) pair.comment = pair.comment ? `${item.comment}\n${pair.comment}` : item.comment;
  24018. item = pair;
  24019. }
  24020. seq.items[i] = item instanceof resolveSeq$2.Pair ? item : new resolveSeq$2.Pair(item);
  24021. }
  24022. return seq;
  24023. }
  24024. function createPairs(schema, iterable, ctx) {
  24025. const pairs = new resolveSeq$2.YAMLSeq(schema);
  24026. pairs.tag = 'tag:yaml.org,2002:pairs';
  24027. for (const it of iterable) {
  24028. let key, value;
  24029. if (Array.isArray(it)) {
  24030. if (it.length === 2) {
  24031. key = it[0];
  24032. value = it[1];
  24033. } else throw new TypeError(`Expected [key, value] tuple: ${it}`);
  24034. } else if (it && it instanceof Object) {
  24035. const keys = Object.keys(it);
  24036. if (keys.length === 1) {
  24037. key = keys[0];
  24038. value = it[key];
  24039. } else throw new TypeError(`Expected { key: value } tuple: ${it}`);
  24040. } else {
  24041. key = it;
  24042. }
  24043. const pair = schema.createPair(key, value, ctx);
  24044. pairs.items.push(pair);
  24045. }
  24046. return pairs;
  24047. }
  24048. const pairs = {
  24049. default: false,
  24050. tag: 'tag:yaml.org,2002:pairs',
  24051. resolve: parsePairs,
  24052. createNode: createPairs
  24053. };
  24054. class YAMLOMap extends resolveSeq$2.YAMLSeq {
  24055. constructor() {
  24056. super();
  24057. PlainValue$3._defineProperty(this, "add", resolveSeq$2.YAMLMap.prototype.add.bind(this));
  24058. PlainValue$3._defineProperty(this, "delete", resolveSeq$2.YAMLMap.prototype.delete.bind(this));
  24059. PlainValue$3._defineProperty(this, "get", resolveSeq$2.YAMLMap.prototype.get.bind(this));
  24060. PlainValue$3._defineProperty(this, "has", resolveSeq$2.YAMLMap.prototype.has.bind(this));
  24061. PlainValue$3._defineProperty(this, "set", resolveSeq$2.YAMLMap.prototype.set.bind(this));
  24062. this.tag = YAMLOMap.tag;
  24063. }
  24064. toJSON(_, ctx) {
  24065. const map = new Map();
  24066. if (ctx && ctx.onCreate) ctx.onCreate(map);
  24067. for (const pair of this.items) {
  24068. let key, value;
  24069. if (pair instanceof resolveSeq$2.Pair) {
  24070. key = resolveSeq$2.toJSON(pair.key, '', ctx);
  24071. value = resolveSeq$2.toJSON(pair.value, key, ctx);
  24072. } else {
  24073. key = resolveSeq$2.toJSON(pair, '', ctx);
  24074. }
  24075. if (map.has(key)) throw new Error('Ordered maps must not include duplicate keys');
  24076. map.set(key, value);
  24077. }
  24078. return map;
  24079. }
  24080. }
  24081. PlainValue$3._defineProperty(YAMLOMap, "tag", 'tag:yaml.org,2002:omap');
  24082. function parseOMap(doc, cst) {
  24083. const pairs = parsePairs(doc, cst);
  24084. const seenKeys = [];
  24085. for (const {
  24086. key
  24087. } of pairs.items) {
  24088. if (key instanceof resolveSeq$2.Scalar) {
  24089. if (seenKeys.includes(key.value)) {
  24090. const msg = 'Ordered maps must not include duplicate keys';
  24091. throw new PlainValue$3.YAMLSemanticError(cst, msg);
  24092. } else {
  24093. seenKeys.push(key.value);
  24094. }
  24095. }
  24096. }
  24097. return Object.assign(new YAMLOMap(), pairs);
  24098. }
  24099. function createOMap(schema, iterable, ctx) {
  24100. const pairs = createPairs(schema, iterable, ctx);
  24101. const omap = new YAMLOMap();
  24102. omap.items = pairs.items;
  24103. return omap;
  24104. }
  24105. const omap = {
  24106. identify: value => value instanceof Map,
  24107. nodeClass: YAMLOMap,
  24108. default: false,
  24109. tag: 'tag:yaml.org,2002:omap',
  24110. resolve: parseOMap,
  24111. createNode: createOMap
  24112. };
  24113. class YAMLSet extends resolveSeq$2.YAMLMap {
  24114. constructor() {
  24115. super();
  24116. this.tag = YAMLSet.tag;
  24117. }
  24118. add(key) {
  24119. const pair = key instanceof resolveSeq$2.Pair ? key : new resolveSeq$2.Pair(key);
  24120. const prev = resolveSeq$2.findPair(this.items, pair.key);
  24121. if (!prev) this.items.push(pair);
  24122. }
  24123. get(key, keepPair) {
  24124. const pair = resolveSeq$2.findPair(this.items, key);
  24125. return !keepPair && pair instanceof resolveSeq$2.Pair ? pair.key instanceof resolveSeq$2.Scalar ? pair.key.value : pair.key : pair;
  24126. }
  24127. set(key, value) {
  24128. if (typeof value !== 'boolean') throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`);
  24129. const prev = resolveSeq$2.findPair(this.items, key);
  24130. if (prev && !value) {
  24131. this.items.splice(this.items.indexOf(prev), 1);
  24132. } else if (!prev && value) {
  24133. this.items.push(new resolveSeq$2.Pair(key));
  24134. }
  24135. }
  24136. toJSON(_, ctx) {
  24137. return super.toJSON(_, ctx, Set);
  24138. }
  24139. toString(ctx, onComment, onChompKeep) {
  24140. if (!ctx) return JSON.stringify(this);
  24141. if (this.hasAllNullValues()) return super.toString(ctx, onComment, onChompKeep);else throw new Error('Set items must all have null values');
  24142. }
  24143. }
  24144. PlainValue$3._defineProperty(YAMLSet, "tag", 'tag:yaml.org,2002:set');
  24145. function parseSet(doc, cst) {
  24146. const map = resolveSeq$2.resolveMap(doc, cst);
  24147. if (!map.hasAllNullValues()) throw new PlainValue$3.YAMLSemanticError(cst, 'Set items must all have null values');
  24148. return Object.assign(new YAMLSet(), map);
  24149. }
  24150. function createSet(schema, iterable, ctx) {
  24151. const set = new YAMLSet();
  24152. for (const value of iterable) set.items.push(schema.createPair(value, null, ctx));
  24153. return set;
  24154. }
  24155. const set = {
  24156. identify: value => value instanceof Set,
  24157. nodeClass: YAMLSet,
  24158. default: false,
  24159. tag: 'tag:yaml.org,2002:set',
  24160. resolve: parseSet,
  24161. createNode: createSet
  24162. };
  24163. const parseSexagesimal = (sign, parts) => {
  24164. const n = parts.split(':').reduce((n, p) => n * 60 + Number(p), 0);
  24165. return sign === '-' ? -n : n;
  24166. }; // hhhh:mm:ss.sss
  24167. const stringifySexagesimal = ({
  24168. value
  24169. }) => {
  24170. if (isNaN(value) || !isFinite(value)) return resolveSeq$2.stringifyNumber(value);
  24171. let sign = '';
  24172. if (value < 0) {
  24173. sign = '-';
  24174. value = Math.abs(value);
  24175. }
  24176. const parts = [value % 60]; // seconds, including ms
  24177. if (value < 60) {
  24178. parts.unshift(0); // at least one : is required
  24179. } else {
  24180. value = Math.round((value - parts[0]) / 60);
  24181. parts.unshift(value % 60); // minutes
  24182. if (value >= 60) {
  24183. value = Math.round((value - parts[0]) / 60);
  24184. parts.unshift(value); // hours
  24185. }
  24186. }
  24187. return sign + parts.map(n => n < 10 ? '0' + String(n) : String(n)).join(':').replace(/000000\d*$/, '') // % 60 may introduce error
  24188. ;
  24189. };
  24190. const intTime = {
  24191. identify: value => typeof value === 'number',
  24192. default: true,
  24193. tag: 'tag:yaml.org,2002:int',
  24194. format: 'TIME',
  24195. test: /^([-+]?)([0-9][0-9_]*(?::[0-5]?[0-9])+)$/,
  24196. resolve: (str, sign, parts) => parseSexagesimal(sign, parts.replace(/_/g, '')),
  24197. stringify: stringifySexagesimal
  24198. };
  24199. const floatTime = {
  24200. identify: value => typeof value === 'number',
  24201. default: true,
  24202. tag: 'tag:yaml.org,2002:float',
  24203. format: 'TIME',
  24204. test: /^([-+]?)([0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*)$/,
  24205. resolve: (str, sign, parts) => parseSexagesimal(sign, parts.replace(/_/g, '')),
  24206. stringify: stringifySexagesimal
  24207. };
  24208. const timestamp = {
  24209. identify: value => value instanceof Date,
  24210. default: true,
  24211. tag: 'tag:yaml.org,2002:timestamp',
  24212. // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part
  24213. // may be omitted altogether, resulting in a date format. In such a case, the time part is
  24214. // assumed to be 00:00:00Z (start of day, UTC).
  24215. test: RegExp('^(?:' + '([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})' + // YYYY-Mm-Dd
  24216. '(?:(?:t|T|[ \\t]+)' + // t | T | whitespace
  24217. '([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)' + // Hh:Mm:Ss(.ss)?
  24218. '(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?' + // Z | +5 | -03:30
  24219. ')?' + ')$'),
  24220. resolve: (str, year, month, day, hour, minute, second, millisec, tz) => {
  24221. if (millisec) millisec = (millisec + '00').substr(1, 3);
  24222. let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec || 0);
  24223. if (tz && tz !== 'Z') {
  24224. let d = parseSexagesimal(tz[0], tz.slice(1));
  24225. if (Math.abs(d) < 30) d *= 60;
  24226. date -= 60000 * d;
  24227. }
  24228. return new Date(date);
  24229. },
  24230. stringify: ({
  24231. value
  24232. }) => value.toISOString().replace(/((T00:00)?:00)?\.000Z$/, '')
  24233. };
  24234. /* global console, process, YAML_SILENCE_DEPRECATION_WARNINGS, YAML_SILENCE_WARNINGS */
  24235. function shouldWarn(deprecation) {
  24236. const env = typeof process !== 'undefined' && process.env || {};
  24237. if (deprecation) {
  24238. if (typeof YAML_SILENCE_DEPRECATION_WARNINGS !== 'undefined') return !YAML_SILENCE_DEPRECATION_WARNINGS;
  24239. return !env.YAML_SILENCE_DEPRECATION_WARNINGS;
  24240. }
  24241. if (typeof YAML_SILENCE_WARNINGS !== 'undefined') return !YAML_SILENCE_WARNINGS;
  24242. return !env.YAML_SILENCE_WARNINGS;
  24243. }
  24244. function warn(warning, type) {
  24245. if (shouldWarn(false)) {
  24246. const emit = typeof process !== 'undefined' && process.emitWarning; // This will throw in Jest if `warning` is an Error instance due to
  24247. // https://github.com/facebook/jest/issues/2549
  24248. if (emit) emit(warning, type);else {
  24249. // eslint-disable-next-line no-console
  24250. console.warn(type ? `${type}: ${warning}` : warning);
  24251. }
  24252. }
  24253. }
  24254. function warnFileDeprecation(filename) {
  24255. if (shouldWarn(true)) {
  24256. const path = filename.replace(/.*yaml[/\\]/i, '').replace(/\.js$/, '').replace(/\\/g, '/');
  24257. warn(`The endpoint 'yaml/${path}' will be removed in a future release.`, 'DeprecationWarning');
  24258. }
  24259. }
  24260. const warned = {};
  24261. function warnOptionDeprecation(name, alternative) {
  24262. if (!warned[name] && shouldWarn(true)) {
  24263. warned[name] = true;
  24264. let msg = `The option '${name}' will be removed in a future release`;
  24265. msg += alternative ? `, use '${alternative}' instead.` : '.';
  24266. warn(msg, 'DeprecationWarning');
  24267. }
  24268. }
  24269. warnings1000a372.binary = binary;
  24270. warnings1000a372.floatTime = floatTime;
  24271. warnings1000a372.intTime = intTime;
  24272. warnings1000a372.omap = omap;
  24273. warnings1000a372.pairs = pairs;
  24274. warnings1000a372.set = set;
  24275. warnings1000a372.timestamp = timestamp;
  24276. warnings1000a372.warn = warn;
  24277. warnings1000a372.warnFileDeprecation = warnFileDeprecation;
  24278. warnings1000a372.warnOptionDeprecation = warnOptionDeprecation;
  24279. var PlainValue$2 = PlainValueEc8e588e;
  24280. var resolveSeq$1 = resolveSeqD03cb037;
  24281. var warnings$1 = warnings1000a372;
  24282. function createMap(schema, obj, ctx) {
  24283. const map = new resolveSeq$1.YAMLMap(schema);
  24284. if (obj instanceof Map) {
  24285. for (const [key, value] of obj) map.items.push(schema.createPair(key, value, ctx));
  24286. } else if (obj && typeof obj === 'object') {
  24287. for (const key of Object.keys(obj)) map.items.push(schema.createPair(key, obj[key], ctx));
  24288. }
  24289. if (typeof schema.sortMapEntries === 'function') {
  24290. map.items.sort(schema.sortMapEntries);
  24291. }
  24292. return map;
  24293. }
  24294. const map = {
  24295. createNode: createMap,
  24296. default: true,
  24297. nodeClass: resolveSeq$1.YAMLMap,
  24298. tag: 'tag:yaml.org,2002:map',
  24299. resolve: resolveSeq$1.resolveMap
  24300. };
  24301. function createSeq(schema, obj, ctx) {
  24302. const seq = new resolveSeq$1.YAMLSeq(schema);
  24303. if (obj && obj[Symbol.iterator]) {
  24304. for (const it of obj) {
  24305. const v = schema.createNode(it, ctx.wrapScalars, null, ctx);
  24306. seq.items.push(v);
  24307. }
  24308. }
  24309. return seq;
  24310. }
  24311. const seq = {
  24312. createNode: createSeq,
  24313. default: true,
  24314. nodeClass: resolveSeq$1.YAMLSeq,
  24315. tag: 'tag:yaml.org,2002:seq',
  24316. resolve: resolveSeq$1.resolveSeq
  24317. };
  24318. const string = {
  24319. identify: value => typeof value === 'string',
  24320. default: true,
  24321. tag: 'tag:yaml.org,2002:str',
  24322. resolve: resolveSeq$1.resolveString,
  24323. stringify(item, ctx, onComment, onChompKeep) {
  24324. ctx = Object.assign({
  24325. actualString: true
  24326. }, ctx);
  24327. return resolveSeq$1.stringifyString(item, ctx, onComment, onChompKeep);
  24328. },
  24329. options: resolveSeq$1.strOptions
  24330. };
  24331. const failsafe = [map, seq, string];
  24332. /* global BigInt */
  24333. const intIdentify$2 = value => typeof value === 'bigint' || Number.isInteger(value);
  24334. const intResolve$1 = (src, part, radix) => resolveSeq$1.intOptions.asBigInt ? BigInt(src) : parseInt(part, radix);
  24335. function intStringify$1(node, radix, prefix) {
  24336. const {
  24337. value
  24338. } = node;
  24339. if (intIdentify$2(value) && value >= 0) return prefix + value.toString(radix);
  24340. return resolveSeq$1.stringifyNumber(node);
  24341. }
  24342. const nullObj = {
  24343. identify: value => value == null,
  24344. createNode: (schema, value, ctx) => ctx.wrapScalars ? new resolveSeq$1.Scalar(null) : null,
  24345. default: true,
  24346. tag: 'tag:yaml.org,2002:null',
  24347. test: /^(?:~|[Nn]ull|NULL)?$/,
  24348. resolve: () => null,
  24349. options: resolveSeq$1.nullOptions,
  24350. stringify: () => resolveSeq$1.nullOptions.nullStr
  24351. };
  24352. const boolObj = {
  24353. identify: value => typeof value === 'boolean',
  24354. default: true,
  24355. tag: 'tag:yaml.org,2002:bool',
  24356. test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,
  24357. resolve: str => str[0] === 't' || str[0] === 'T',
  24358. options: resolveSeq$1.boolOptions,
  24359. stringify: ({
  24360. value
  24361. }) => value ? resolveSeq$1.boolOptions.trueStr : resolveSeq$1.boolOptions.falseStr
  24362. };
  24363. const octObj = {
  24364. identify: value => intIdentify$2(value) && value >= 0,
  24365. default: true,
  24366. tag: 'tag:yaml.org,2002:int',
  24367. format: 'OCT',
  24368. test: /^0o([0-7]+)$/,
  24369. resolve: (str, oct) => intResolve$1(str, oct, 8),
  24370. options: resolveSeq$1.intOptions,
  24371. stringify: node => intStringify$1(node, 8, '0o')
  24372. };
  24373. const intObj = {
  24374. identify: intIdentify$2,
  24375. default: true,
  24376. tag: 'tag:yaml.org,2002:int',
  24377. test: /^[-+]?[0-9]+$/,
  24378. resolve: str => intResolve$1(str, str, 10),
  24379. options: resolveSeq$1.intOptions,
  24380. stringify: resolveSeq$1.stringifyNumber
  24381. };
  24382. const hexObj = {
  24383. identify: value => intIdentify$2(value) && value >= 0,
  24384. default: true,
  24385. tag: 'tag:yaml.org,2002:int',
  24386. format: 'HEX',
  24387. test: /^0x([0-9a-fA-F]+)$/,
  24388. resolve: (str, hex) => intResolve$1(str, hex, 16),
  24389. options: resolveSeq$1.intOptions,
  24390. stringify: node => intStringify$1(node, 16, '0x')
  24391. };
  24392. const nanObj = {
  24393. identify: value => typeof value === 'number',
  24394. default: true,
  24395. tag: 'tag:yaml.org,2002:float',
  24396. test: /^(?:[-+]?\.inf|(\.nan))$/i,
  24397. resolve: (str, nan) => nan ? NaN : str[0] === '-' ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
  24398. stringify: resolveSeq$1.stringifyNumber
  24399. };
  24400. const expObj = {
  24401. identify: value => typeof value === 'number',
  24402. default: true,
  24403. tag: 'tag:yaml.org,2002:float',
  24404. format: 'EXP',
  24405. test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,
  24406. resolve: str => parseFloat(str),
  24407. stringify: ({
  24408. value
  24409. }) => Number(value).toExponential()
  24410. };
  24411. const floatObj = {
  24412. identify: value => typeof value === 'number',
  24413. default: true,
  24414. tag: 'tag:yaml.org,2002:float',
  24415. test: /^[-+]?(?:\.([0-9]+)|[0-9]+\.([0-9]*))$/,
  24416. resolve(str, frac1, frac2) {
  24417. const frac = frac1 || frac2;
  24418. const node = new resolveSeq$1.Scalar(parseFloat(str));
  24419. if (frac && frac[frac.length - 1] === '0') node.minFractionDigits = frac.length;
  24420. return node;
  24421. },
  24422. stringify: resolveSeq$1.stringifyNumber
  24423. };
  24424. const core$1 = failsafe.concat([nullObj, boolObj, octObj, intObj, hexObj, nanObj, expObj, floatObj]);
  24425. /* global BigInt */
  24426. const intIdentify$1 = value => typeof value === 'bigint' || Number.isInteger(value);
  24427. const stringifyJSON = ({
  24428. value
  24429. }) => JSON.stringify(value);
  24430. const json = [map, seq, {
  24431. identify: value => typeof value === 'string',
  24432. default: true,
  24433. tag: 'tag:yaml.org,2002:str',
  24434. resolve: resolveSeq$1.resolveString,
  24435. stringify: stringifyJSON
  24436. }, {
  24437. identify: value => value == null,
  24438. createNode: (schema, value, ctx) => ctx.wrapScalars ? new resolveSeq$1.Scalar(null) : null,
  24439. default: true,
  24440. tag: 'tag:yaml.org,2002:null',
  24441. test: /^null$/,
  24442. resolve: () => null,
  24443. stringify: stringifyJSON
  24444. }, {
  24445. identify: value => typeof value === 'boolean',
  24446. default: true,
  24447. tag: 'tag:yaml.org,2002:bool',
  24448. test: /^true|false$/,
  24449. resolve: str => str === 'true',
  24450. stringify: stringifyJSON
  24451. }, {
  24452. identify: intIdentify$1,
  24453. default: true,
  24454. tag: 'tag:yaml.org,2002:int',
  24455. test: /^-?(?:0|[1-9][0-9]*)$/,
  24456. resolve: str => resolveSeq$1.intOptions.asBigInt ? BigInt(str) : parseInt(str, 10),
  24457. stringify: ({
  24458. value
  24459. }) => intIdentify$1(value) ? value.toString() : JSON.stringify(value)
  24460. }, {
  24461. identify: value => typeof value === 'number',
  24462. default: true,
  24463. tag: 'tag:yaml.org,2002:float',
  24464. test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,
  24465. resolve: str => parseFloat(str),
  24466. stringify: stringifyJSON
  24467. }];
  24468. json.scalarFallback = str => {
  24469. throw new SyntaxError(`Unresolved plain scalar ${JSON.stringify(str)}`);
  24470. };
  24471. /* global BigInt */
  24472. const boolStringify = ({
  24473. value
  24474. }) => value ? resolveSeq$1.boolOptions.trueStr : resolveSeq$1.boolOptions.falseStr;
  24475. const intIdentify = value => typeof value === 'bigint' || Number.isInteger(value);
  24476. function intResolve(sign, src, radix) {
  24477. let str = src.replace(/_/g, '');
  24478. if (resolveSeq$1.intOptions.asBigInt) {
  24479. switch (radix) {
  24480. case 2:
  24481. str = `0b${str}`;
  24482. break;
  24483. case 8:
  24484. str = `0o${str}`;
  24485. break;
  24486. case 16:
  24487. str = `0x${str}`;
  24488. break;
  24489. }
  24490. const n = BigInt(str);
  24491. return sign === '-' ? BigInt(-1) * n : n;
  24492. }
  24493. const n = parseInt(str, radix);
  24494. return sign === '-' ? -1 * n : n;
  24495. }
  24496. function intStringify(node, radix, prefix) {
  24497. const {
  24498. value
  24499. } = node;
  24500. if (intIdentify(value)) {
  24501. const str = value.toString(radix);
  24502. return value < 0 ? '-' + prefix + str.substr(1) : prefix + str;
  24503. }
  24504. return resolveSeq$1.stringifyNumber(node);
  24505. }
  24506. const yaml11 = failsafe.concat([{
  24507. identify: value => value == null,
  24508. createNode: (schema, value, ctx) => ctx.wrapScalars ? new resolveSeq$1.Scalar(null) : null,
  24509. default: true,
  24510. tag: 'tag:yaml.org,2002:null',
  24511. test: /^(?:~|[Nn]ull|NULL)?$/,
  24512. resolve: () => null,
  24513. options: resolveSeq$1.nullOptions,
  24514. stringify: () => resolveSeq$1.nullOptions.nullStr
  24515. }, {
  24516. identify: value => typeof value === 'boolean',
  24517. default: true,
  24518. tag: 'tag:yaml.org,2002:bool',
  24519. test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,
  24520. resolve: () => true,
  24521. options: resolveSeq$1.boolOptions,
  24522. stringify: boolStringify
  24523. }, {
  24524. identify: value => typeof value === 'boolean',
  24525. default: true,
  24526. tag: 'tag:yaml.org,2002:bool',
  24527. test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/i,
  24528. resolve: () => false,
  24529. options: resolveSeq$1.boolOptions,
  24530. stringify: boolStringify
  24531. }, {
  24532. identify: intIdentify,
  24533. default: true,
  24534. tag: 'tag:yaml.org,2002:int',
  24535. format: 'BIN',
  24536. test: /^([-+]?)0b([0-1_]+)$/,
  24537. resolve: (str, sign, bin) => intResolve(sign, bin, 2),
  24538. stringify: node => intStringify(node, 2, '0b')
  24539. }, {
  24540. identify: intIdentify,
  24541. default: true,
  24542. tag: 'tag:yaml.org,2002:int',
  24543. format: 'OCT',
  24544. test: /^([-+]?)0([0-7_]+)$/,
  24545. resolve: (str, sign, oct) => intResolve(sign, oct, 8),
  24546. stringify: node => intStringify(node, 8, '0')
  24547. }, {
  24548. identify: intIdentify,
  24549. default: true,
  24550. tag: 'tag:yaml.org,2002:int',
  24551. test: /^([-+]?)([0-9][0-9_]*)$/,
  24552. resolve: (str, sign, abs) => intResolve(sign, abs, 10),
  24553. stringify: resolveSeq$1.stringifyNumber
  24554. }, {
  24555. identify: intIdentify,
  24556. default: true,
  24557. tag: 'tag:yaml.org,2002:int',
  24558. format: 'HEX',
  24559. test: /^([-+]?)0x([0-9a-fA-F_]+)$/,
  24560. resolve: (str, sign, hex) => intResolve(sign, hex, 16),
  24561. stringify: node => intStringify(node, 16, '0x')
  24562. }, {
  24563. identify: value => typeof value === 'number',
  24564. default: true,
  24565. tag: 'tag:yaml.org,2002:float',
  24566. test: /^(?:[-+]?\.inf|(\.nan))$/i,
  24567. resolve: (str, nan) => nan ? NaN : str[0] === '-' ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
  24568. stringify: resolveSeq$1.stringifyNumber
  24569. }, {
  24570. identify: value => typeof value === 'number',
  24571. default: true,
  24572. tag: 'tag:yaml.org,2002:float',
  24573. format: 'EXP',
  24574. test: /^[-+]?([0-9][0-9_]*)?(\.[0-9_]*)?[eE][-+]?[0-9]+$/,
  24575. resolve: str => parseFloat(str.replace(/_/g, '')),
  24576. stringify: ({
  24577. value
  24578. }) => Number(value).toExponential()
  24579. }, {
  24580. identify: value => typeof value === 'number',
  24581. default: true,
  24582. tag: 'tag:yaml.org,2002:float',
  24583. test: /^[-+]?(?:[0-9][0-9_]*)?\.([0-9_]*)$/,
  24584. resolve(str, frac) {
  24585. const node = new resolveSeq$1.Scalar(parseFloat(str.replace(/_/g, '')));
  24586. if (frac) {
  24587. const f = frac.replace(/_/g, '');
  24588. if (f[f.length - 1] === '0') node.minFractionDigits = f.length;
  24589. }
  24590. return node;
  24591. },
  24592. stringify: resolveSeq$1.stringifyNumber
  24593. }], warnings$1.binary, warnings$1.omap, warnings$1.pairs, warnings$1.set, warnings$1.intTime, warnings$1.floatTime, warnings$1.timestamp);
  24594. const schemas = {
  24595. core: core$1,
  24596. failsafe,
  24597. json,
  24598. yaml11
  24599. };
  24600. const tags = {
  24601. binary: warnings$1.binary,
  24602. bool: boolObj,
  24603. float: floatObj,
  24604. floatExp: expObj,
  24605. floatNaN: nanObj,
  24606. floatTime: warnings$1.floatTime,
  24607. int: intObj,
  24608. intHex: hexObj,
  24609. intOct: octObj,
  24610. intTime: warnings$1.intTime,
  24611. map,
  24612. null: nullObj,
  24613. omap: warnings$1.omap,
  24614. pairs: warnings$1.pairs,
  24615. seq,
  24616. set: warnings$1.set,
  24617. timestamp: warnings$1.timestamp
  24618. };
  24619. function findTagObject(value, tagName, tags) {
  24620. if (tagName) {
  24621. const match = tags.filter(t => t.tag === tagName);
  24622. const tagObj = match.find(t => !t.format) || match[0];
  24623. if (!tagObj) throw new Error(`Tag ${tagName} not found`);
  24624. return tagObj;
  24625. } // TODO: deprecate/remove class check
  24626. return tags.find(t => (t.identify && t.identify(value) || t.class && value instanceof t.class) && !t.format);
  24627. }
  24628. function createNode$1(value, tagName, ctx) {
  24629. if (value instanceof resolveSeq$1.Node) return value;
  24630. const {
  24631. defaultPrefix,
  24632. onTagObj,
  24633. prevObjects,
  24634. schema,
  24635. wrapScalars
  24636. } = ctx;
  24637. if (tagName && tagName.startsWith('!!')) tagName = defaultPrefix + tagName.slice(2);
  24638. let tagObj = findTagObject(value, tagName, schema.tags);
  24639. if (!tagObj) {
  24640. if (typeof value.toJSON === 'function') value = value.toJSON();
  24641. if (!value || typeof value !== 'object') return wrapScalars ? new resolveSeq$1.Scalar(value) : value;
  24642. tagObj = value instanceof Map ? map : value[Symbol.iterator] ? seq : map;
  24643. }
  24644. if (onTagObj) {
  24645. onTagObj(tagObj);
  24646. delete ctx.onTagObj;
  24647. } // Detect duplicate references to the same object & use Alias nodes for all
  24648. // after first. The `obj` wrapper allows for circular references to resolve.
  24649. const obj = {
  24650. value: undefined,
  24651. node: undefined
  24652. };
  24653. if (value && typeof value === 'object' && prevObjects) {
  24654. const prev = prevObjects.get(value);
  24655. if (prev) {
  24656. const alias = new resolveSeq$1.Alias(prev); // leaves source dirty; must be cleaned by caller
  24657. ctx.aliasNodes.push(alias); // defined along with prevObjects
  24658. return alias;
  24659. }
  24660. obj.value = value;
  24661. prevObjects.set(value, obj);
  24662. }
  24663. obj.node = tagObj.createNode ? tagObj.createNode(ctx.schema, value, ctx) : wrapScalars ? new resolveSeq$1.Scalar(value) : value;
  24664. if (tagName && obj.node instanceof resolveSeq$1.Node) obj.node.tag = tagName;
  24665. return obj.node;
  24666. }
  24667. function getSchemaTags(schemas, knownTags, customTags, schemaId) {
  24668. let tags = schemas[schemaId.replace(/\W/g, '')]; // 'yaml-1.1' -> 'yaml11'
  24669. if (!tags) {
  24670. const keys = Object.keys(schemas).map(key => JSON.stringify(key)).join(', ');
  24671. throw new Error(`Unknown schema "${schemaId}"; use one of ${keys}`);
  24672. }
  24673. if (Array.isArray(customTags)) {
  24674. for (const tag of customTags) tags = tags.concat(tag);
  24675. } else if (typeof customTags === 'function') {
  24676. tags = customTags(tags.slice());
  24677. }
  24678. for (let i = 0; i < tags.length; ++i) {
  24679. const tag = tags[i];
  24680. if (typeof tag === 'string') {
  24681. const tagObj = knownTags[tag];
  24682. if (!tagObj) {
  24683. const keys = Object.keys(knownTags).map(key => JSON.stringify(key)).join(', ');
  24684. throw new Error(`Unknown custom tag "${tag}"; use one of ${keys}`);
  24685. }
  24686. tags[i] = tagObj;
  24687. }
  24688. }
  24689. return tags;
  24690. }
  24691. const sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0;
  24692. class Schema$2 {
  24693. // TODO: remove in v2
  24694. // TODO: remove in v2
  24695. constructor({
  24696. customTags,
  24697. merge,
  24698. schema,
  24699. sortMapEntries,
  24700. tags: deprecatedCustomTags
  24701. }) {
  24702. this.merge = !!merge;
  24703. this.name = schema;
  24704. this.sortMapEntries = sortMapEntries === true ? sortMapEntriesByKey : sortMapEntries || null;
  24705. if (!customTags && deprecatedCustomTags) warnings$1.warnOptionDeprecation('tags', 'customTags');
  24706. this.tags = getSchemaTags(schemas, tags, customTags || deprecatedCustomTags, schema);
  24707. }
  24708. createNode(value, wrapScalars, tagName, ctx) {
  24709. const baseCtx = {
  24710. defaultPrefix: Schema$2.defaultPrefix,
  24711. schema: this,
  24712. wrapScalars
  24713. };
  24714. const createCtx = ctx ? Object.assign(ctx, baseCtx) : baseCtx;
  24715. return createNode$1(value, tagName, createCtx);
  24716. }
  24717. createPair(key, value, ctx) {
  24718. if (!ctx) ctx = {
  24719. wrapScalars: true
  24720. };
  24721. const k = this.createNode(key, ctx.wrapScalars, null, ctx);
  24722. const v = this.createNode(value, ctx.wrapScalars, null, ctx);
  24723. return new resolveSeq$1.Pair(k, v);
  24724. }
  24725. }
  24726. PlainValue$2._defineProperty(Schema$2, "defaultPrefix", PlainValue$2.defaultTagPrefix);
  24727. PlainValue$2._defineProperty(Schema$2, "defaultTags", PlainValue$2.defaultTags);
  24728. Schema88e323a7.Schema = Schema$2;
  24729. var PlainValue$1 = PlainValueEc8e588e;
  24730. var resolveSeq = resolveSeqD03cb037;
  24731. var Schema$1 = Schema88e323a7;
  24732. const defaultOptions$1 = {
  24733. anchorPrefix: 'a',
  24734. customTags: null,
  24735. indent: 2,
  24736. indentSeq: true,
  24737. keepCstNodes: false,
  24738. keepNodeTypes: true,
  24739. keepBlobsInJSON: true,
  24740. mapAsMap: false,
  24741. maxAliasCount: 100,
  24742. prettyErrors: false,
  24743. // TODO Set true in v2
  24744. simpleKeys: false,
  24745. version: '1.2'
  24746. };
  24747. const scalarOptions = {
  24748. get binary() {
  24749. return resolveSeq.binaryOptions;
  24750. },
  24751. set binary(opt) {
  24752. Object.assign(resolveSeq.binaryOptions, opt);
  24753. },
  24754. get bool() {
  24755. return resolveSeq.boolOptions;
  24756. },
  24757. set bool(opt) {
  24758. Object.assign(resolveSeq.boolOptions, opt);
  24759. },
  24760. get int() {
  24761. return resolveSeq.intOptions;
  24762. },
  24763. set int(opt) {
  24764. Object.assign(resolveSeq.intOptions, opt);
  24765. },
  24766. get null() {
  24767. return resolveSeq.nullOptions;
  24768. },
  24769. set null(opt) {
  24770. Object.assign(resolveSeq.nullOptions, opt);
  24771. },
  24772. get str() {
  24773. return resolveSeq.strOptions;
  24774. },
  24775. set str(opt) {
  24776. Object.assign(resolveSeq.strOptions, opt);
  24777. }
  24778. };
  24779. const documentOptions = {
  24780. '1.0': {
  24781. schema: 'yaml-1.1',
  24782. merge: true,
  24783. tagPrefixes: [{
  24784. handle: '!',
  24785. prefix: PlainValue$1.defaultTagPrefix
  24786. }, {
  24787. handle: '!!',
  24788. prefix: 'tag:private.yaml.org,2002:'
  24789. }]
  24790. },
  24791. 1.1: {
  24792. schema: 'yaml-1.1',
  24793. merge: true,
  24794. tagPrefixes: [{
  24795. handle: '!',
  24796. prefix: '!'
  24797. }, {
  24798. handle: '!!',
  24799. prefix: PlainValue$1.defaultTagPrefix
  24800. }]
  24801. },
  24802. 1.2: {
  24803. schema: 'core',
  24804. merge: false,
  24805. tagPrefixes: [{
  24806. handle: '!',
  24807. prefix: '!'
  24808. }, {
  24809. handle: '!!',
  24810. prefix: PlainValue$1.defaultTagPrefix
  24811. }]
  24812. }
  24813. };
  24814. function stringifyTag(doc, tag) {
  24815. if ((doc.version || doc.options.version) === '1.0') {
  24816. const priv = tag.match(/^tag:private\.yaml\.org,2002:([^:/]+)$/);
  24817. if (priv) return '!' + priv[1];
  24818. const vocab = tag.match(/^tag:([a-zA-Z0-9-]+)\.yaml\.org,2002:(.*)/);
  24819. return vocab ? `!${vocab[1]}/${vocab[2]}` : `!${tag.replace(/^tag:/, '')}`;
  24820. }
  24821. let p = doc.tagPrefixes.find(p => tag.indexOf(p.prefix) === 0);
  24822. if (!p) {
  24823. const dtp = doc.getDefaults().tagPrefixes;
  24824. p = dtp && dtp.find(p => tag.indexOf(p.prefix) === 0);
  24825. }
  24826. if (!p) return tag[0] === '!' ? tag : `!<${tag}>`;
  24827. const suffix = tag.substr(p.prefix.length).replace(/[!,[\]{}]/g, ch => ({
  24828. '!': '%21',
  24829. ',': '%2C',
  24830. '[': '%5B',
  24831. ']': '%5D',
  24832. '{': '%7B',
  24833. '}': '%7D'
  24834. })[ch]);
  24835. return p.handle + suffix;
  24836. }
  24837. function getTagObject(tags, item) {
  24838. if (item instanceof resolveSeq.Alias) return resolveSeq.Alias;
  24839. if (item.tag) {
  24840. const match = tags.filter(t => t.tag === item.tag);
  24841. if (match.length > 0) return match.find(t => t.format === item.format) || match[0];
  24842. }
  24843. let tagObj, obj;
  24844. if (item instanceof resolveSeq.Scalar) {
  24845. obj = item.value; // TODO: deprecate/remove class check
  24846. const match = tags.filter(t => t.identify && t.identify(obj) || t.class && obj instanceof t.class);
  24847. tagObj = match.find(t => t.format === item.format) || match.find(t => !t.format);
  24848. } else {
  24849. obj = item;
  24850. tagObj = tags.find(t => t.nodeClass && obj instanceof t.nodeClass);
  24851. }
  24852. if (!tagObj) {
  24853. const name = obj && obj.constructor ? obj.constructor.name : typeof obj;
  24854. throw new Error(`Tag not resolved for ${name} value`);
  24855. }
  24856. return tagObj;
  24857. } // needs to be called before value stringifier to allow for circular anchor refs
  24858. function stringifyProps(node, tagObj, {
  24859. anchors,
  24860. doc
  24861. }) {
  24862. const props = [];
  24863. const anchor = doc.anchors.getName(node);
  24864. if (anchor) {
  24865. anchors[anchor] = node;
  24866. props.push(`&${anchor}`);
  24867. }
  24868. if (node.tag) {
  24869. props.push(stringifyTag(doc, node.tag));
  24870. } else if (!tagObj.default) {
  24871. props.push(stringifyTag(doc, tagObj.tag));
  24872. }
  24873. return props.join(' ');
  24874. }
  24875. function stringify$1(item, ctx, onComment, onChompKeep) {
  24876. const {
  24877. anchors,
  24878. schema
  24879. } = ctx.doc;
  24880. let tagObj;
  24881. if (!(item instanceof resolveSeq.Node)) {
  24882. const createCtx = {
  24883. aliasNodes: [],
  24884. onTagObj: o => tagObj = o,
  24885. prevObjects: new Map()
  24886. };
  24887. item = schema.createNode(item, true, null, createCtx);
  24888. for (const alias of createCtx.aliasNodes) {
  24889. alias.source = alias.source.node;
  24890. let name = anchors.getName(alias.source);
  24891. if (!name) {
  24892. name = anchors.newName();
  24893. anchors.map[name] = alias.source;
  24894. }
  24895. }
  24896. }
  24897. if (item instanceof resolveSeq.Pair) return item.toString(ctx, onComment, onChompKeep);
  24898. if (!tagObj) tagObj = getTagObject(schema.tags, item);
  24899. const props = stringifyProps(item, tagObj, ctx);
  24900. if (props.length > 0) ctx.indentAtStart = (ctx.indentAtStart || 0) + props.length + 1;
  24901. const str = typeof tagObj.stringify === 'function' ? tagObj.stringify(item, ctx, onComment, onChompKeep) : item instanceof resolveSeq.Scalar ? resolveSeq.stringifyString(item, ctx, onComment, onChompKeep) : item.toString(ctx, onComment, onChompKeep);
  24902. if (!props) return str;
  24903. return item instanceof resolveSeq.Scalar || str[0] === '{' || str[0] === '[' ? `${props} ${str}` : `${props}\n${ctx.indent}${str}`;
  24904. }
  24905. class Anchors {
  24906. static validAnchorNode(node) {
  24907. return node instanceof resolveSeq.Scalar || node instanceof resolveSeq.YAMLSeq || node instanceof resolveSeq.YAMLMap;
  24908. }
  24909. constructor(prefix) {
  24910. PlainValue$1._defineProperty(this, "map", Object.create(null));
  24911. this.prefix = prefix;
  24912. }
  24913. createAlias(node, name) {
  24914. this.setAnchor(node, name);
  24915. return new resolveSeq.Alias(node);
  24916. }
  24917. createMergePair(...sources) {
  24918. const merge = new resolveSeq.Merge();
  24919. merge.value.items = sources.map(s => {
  24920. if (s instanceof resolveSeq.Alias) {
  24921. if (s.source instanceof resolveSeq.YAMLMap) return s;
  24922. } else if (s instanceof resolveSeq.YAMLMap) {
  24923. return this.createAlias(s);
  24924. }
  24925. throw new Error('Merge sources must be Map nodes or their Aliases');
  24926. });
  24927. return merge;
  24928. }
  24929. getName(node) {
  24930. const {
  24931. map
  24932. } = this;
  24933. return Object.keys(map).find(a => map[a] === node);
  24934. }
  24935. getNames() {
  24936. return Object.keys(this.map);
  24937. }
  24938. getNode(name) {
  24939. return this.map[name];
  24940. }
  24941. newName(prefix) {
  24942. if (!prefix) prefix = this.prefix;
  24943. const names = Object.keys(this.map);
  24944. for (let i = 1; true; ++i) {
  24945. const name = `${prefix}${i}`;
  24946. if (!names.includes(name)) return name;
  24947. }
  24948. } // During parsing, map & aliases contain CST nodes
  24949. resolveNodes() {
  24950. const {
  24951. map,
  24952. _cstAliases
  24953. } = this;
  24954. Object.keys(map).forEach(a => {
  24955. map[a] = map[a].resolved;
  24956. });
  24957. _cstAliases.forEach(a => {
  24958. a.source = a.source.resolved;
  24959. });
  24960. delete this._cstAliases;
  24961. }
  24962. setAnchor(node, name) {
  24963. if (node != null && !Anchors.validAnchorNode(node)) {
  24964. throw new Error('Anchors may only be set for Scalar, Seq and Map nodes');
  24965. }
  24966. if (name && /[\x00-\x19\s,[\]{}]/.test(name)) {
  24967. throw new Error('Anchor names must not contain whitespace or control characters');
  24968. }
  24969. const {
  24970. map
  24971. } = this;
  24972. const prev = node && Object.keys(map).find(a => map[a] === node);
  24973. if (prev) {
  24974. if (!name) {
  24975. return prev;
  24976. } else if (prev !== name) {
  24977. delete map[prev];
  24978. map[name] = node;
  24979. }
  24980. } else {
  24981. if (!name) {
  24982. if (!node) return null;
  24983. name = this.newName();
  24984. }
  24985. map[name] = node;
  24986. }
  24987. return name;
  24988. }
  24989. }
  24990. const visit = (node, tags) => {
  24991. if (node && typeof node === 'object') {
  24992. const {
  24993. tag
  24994. } = node;
  24995. if (node instanceof resolveSeq.Collection) {
  24996. if (tag) tags[tag] = true;
  24997. node.items.forEach(n => visit(n, tags));
  24998. } else if (node instanceof resolveSeq.Pair) {
  24999. visit(node.key, tags);
  25000. visit(node.value, tags);
  25001. } else if (node instanceof resolveSeq.Scalar) {
  25002. if (tag) tags[tag] = true;
  25003. }
  25004. }
  25005. return tags;
  25006. };
  25007. const listTagNames = node => Object.keys(visit(node, {}));
  25008. function parseContents(doc, contents) {
  25009. const comments = {
  25010. before: [],
  25011. after: []
  25012. };
  25013. let body = undefined;
  25014. let spaceBefore = false;
  25015. for (const node of contents) {
  25016. if (node.valueRange) {
  25017. if (body !== undefined) {
  25018. const msg = 'Document contains trailing content not separated by a ... or --- line';
  25019. doc.errors.push(new PlainValue$1.YAMLSyntaxError(node, msg));
  25020. break;
  25021. }
  25022. const res = resolveSeq.resolveNode(doc, node);
  25023. if (spaceBefore) {
  25024. res.spaceBefore = true;
  25025. spaceBefore = false;
  25026. }
  25027. body = res;
  25028. } else if (node.comment !== null) {
  25029. const cc = body === undefined ? comments.before : comments.after;
  25030. cc.push(node.comment);
  25031. } else if (node.type === PlainValue$1.Type.BLANK_LINE) {
  25032. spaceBefore = true;
  25033. if (body === undefined && comments.before.length > 0 && !doc.commentBefore) {
  25034. // space-separated comments at start are parsed as document comments
  25035. doc.commentBefore = comments.before.join('\n');
  25036. comments.before = [];
  25037. }
  25038. }
  25039. }
  25040. doc.contents = body || null;
  25041. if (!body) {
  25042. doc.comment = comments.before.concat(comments.after).join('\n') || null;
  25043. } else {
  25044. const cb = comments.before.join('\n');
  25045. if (cb) {
  25046. const cbNode = body instanceof resolveSeq.Collection && body.items[0] ? body.items[0] : body;
  25047. cbNode.commentBefore = cbNode.commentBefore ? `${cb}\n${cbNode.commentBefore}` : cb;
  25048. }
  25049. doc.comment = comments.after.join('\n') || null;
  25050. }
  25051. }
  25052. function resolveTagDirective({
  25053. tagPrefixes
  25054. }, directive) {
  25055. const [handle, prefix] = directive.parameters;
  25056. if (!handle || !prefix) {
  25057. const msg = 'Insufficient parameters given for %TAG directive';
  25058. throw new PlainValue$1.YAMLSemanticError(directive, msg);
  25059. }
  25060. if (tagPrefixes.some(p => p.handle === handle)) {
  25061. const msg = 'The %TAG directive must only be given at most once per handle in the same document.';
  25062. throw new PlainValue$1.YAMLSemanticError(directive, msg);
  25063. }
  25064. return {
  25065. handle,
  25066. prefix
  25067. };
  25068. }
  25069. function resolveYamlDirective(doc, directive) {
  25070. let [version] = directive.parameters;
  25071. if (directive.name === 'YAML:1.0') version = '1.0';
  25072. if (!version) {
  25073. const msg = 'Insufficient parameters given for %YAML directive';
  25074. throw new PlainValue$1.YAMLSemanticError(directive, msg);
  25075. }
  25076. if (!documentOptions[version]) {
  25077. const v0 = doc.version || doc.options.version;
  25078. const msg = `Document will be parsed as YAML ${v0} rather than YAML ${version}`;
  25079. doc.warnings.push(new PlainValue$1.YAMLWarning(directive, msg));
  25080. }
  25081. return version;
  25082. }
  25083. function parseDirectives(doc, directives, prevDoc) {
  25084. const directiveComments = [];
  25085. let hasDirectives = false;
  25086. for (const directive of directives) {
  25087. const {
  25088. comment,
  25089. name
  25090. } = directive;
  25091. switch (name) {
  25092. case 'TAG':
  25093. try {
  25094. doc.tagPrefixes.push(resolveTagDirective(doc, directive));
  25095. } catch (error) {
  25096. doc.errors.push(error);
  25097. }
  25098. hasDirectives = true;
  25099. break;
  25100. case 'YAML':
  25101. case 'YAML:1.0':
  25102. if (doc.version) {
  25103. const msg = 'The %YAML directive must only be given at most once per document.';
  25104. doc.errors.push(new PlainValue$1.YAMLSemanticError(directive, msg));
  25105. }
  25106. try {
  25107. doc.version = resolveYamlDirective(doc, directive);
  25108. } catch (error) {
  25109. doc.errors.push(error);
  25110. }
  25111. hasDirectives = true;
  25112. break;
  25113. default:
  25114. if (name) {
  25115. const msg = `YAML only supports %TAG and %YAML directives, and not %${name}`;
  25116. doc.warnings.push(new PlainValue$1.YAMLWarning(directive, msg));
  25117. }
  25118. }
  25119. if (comment) directiveComments.push(comment);
  25120. }
  25121. if (prevDoc && !hasDirectives && '1.1' === (doc.version || prevDoc.version || doc.options.version)) {
  25122. const copyTagPrefix = ({
  25123. handle,
  25124. prefix
  25125. }) => ({
  25126. handle,
  25127. prefix
  25128. });
  25129. doc.tagPrefixes = prevDoc.tagPrefixes.map(copyTagPrefix);
  25130. doc.version = prevDoc.version;
  25131. }
  25132. doc.commentBefore = directiveComments.join('\n') || null;
  25133. }
  25134. function assertCollection(contents) {
  25135. if (contents instanceof resolveSeq.Collection) return true;
  25136. throw new Error('Expected a YAML collection as document contents');
  25137. }
  25138. class Document$2 {
  25139. constructor(options) {
  25140. this.anchors = new Anchors(options.anchorPrefix);
  25141. this.commentBefore = null;
  25142. this.comment = null;
  25143. this.contents = null;
  25144. this.directivesEndMarker = null;
  25145. this.errors = [];
  25146. this.options = options;
  25147. this.schema = null;
  25148. this.tagPrefixes = [];
  25149. this.version = null;
  25150. this.warnings = [];
  25151. }
  25152. add(value) {
  25153. assertCollection(this.contents);
  25154. return this.contents.add(value);
  25155. }
  25156. addIn(path, value) {
  25157. assertCollection(this.contents);
  25158. this.contents.addIn(path, value);
  25159. }
  25160. delete(key) {
  25161. assertCollection(this.contents);
  25162. return this.contents.delete(key);
  25163. }
  25164. deleteIn(path) {
  25165. if (resolveSeq.isEmptyPath(path)) {
  25166. if (this.contents == null) return false;
  25167. this.contents = null;
  25168. return true;
  25169. }
  25170. assertCollection(this.contents);
  25171. return this.contents.deleteIn(path);
  25172. }
  25173. getDefaults() {
  25174. return Document$2.defaults[this.version] || Document$2.defaults[this.options.version] || {};
  25175. }
  25176. get(key, keepScalar) {
  25177. return this.contents instanceof resolveSeq.Collection ? this.contents.get(key, keepScalar) : undefined;
  25178. }
  25179. getIn(path, keepScalar) {
  25180. if (resolveSeq.isEmptyPath(path)) return !keepScalar && this.contents instanceof resolveSeq.Scalar ? this.contents.value : this.contents;
  25181. return this.contents instanceof resolveSeq.Collection ? this.contents.getIn(path, keepScalar) : undefined;
  25182. }
  25183. has(key) {
  25184. return this.contents instanceof resolveSeq.Collection ? this.contents.has(key) : false;
  25185. }
  25186. hasIn(path) {
  25187. if (resolveSeq.isEmptyPath(path)) return this.contents !== undefined;
  25188. return this.contents instanceof resolveSeq.Collection ? this.contents.hasIn(path) : false;
  25189. }
  25190. set(key, value) {
  25191. assertCollection(this.contents);
  25192. this.contents.set(key, value);
  25193. }
  25194. setIn(path, value) {
  25195. if (resolveSeq.isEmptyPath(path)) this.contents = value;else {
  25196. assertCollection(this.contents);
  25197. this.contents.setIn(path, value);
  25198. }
  25199. }
  25200. setSchema(id, customTags) {
  25201. if (!id && !customTags && this.schema) return;
  25202. if (typeof id === 'number') id = id.toFixed(1);
  25203. if (id === '1.0' || id === '1.1' || id === '1.2') {
  25204. if (this.version) this.version = id;else this.options.version = id;
  25205. delete this.options.schema;
  25206. } else if (id && typeof id === 'string') {
  25207. this.options.schema = id;
  25208. }
  25209. if (Array.isArray(customTags)) this.options.customTags = customTags;
  25210. const opt = Object.assign({}, this.getDefaults(), this.options);
  25211. this.schema = new Schema$1.Schema(opt);
  25212. }
  25213. parse(node, prevDoc) {
  25214. if (this.options.keepCstNodes) this.cstNode = node;
  25215. if (this.options.keepNodeTypes) this.type = 'DOCUMENT';
  25216. const {
  25217. directives = [],
  25218. contents = [],
  25219. directivesEndMarker,
  25220. error,
  25221. valueRange
  25222. } = node;
  25223. if (error) {
  25224. if (!error.source) error.source = this;
  25225. this.errors.push(error);
  25226. }
  25227. parseDirectives(this, directives, prevDoc);
  25228. if (directivesEndMarker) this.directivesEndMarker = true;
  25229. this.range = valueRange ? [valueRange.start, valueRange.end] : null;
  25230. this.setSchema();
  25231. this.anchors._cstAliases = [];
  25232. parseContents(this, contents);
  25233. this.anchors.resolveNodes();
  25234. if (this.options.prettyErrors) {
  25235. for (const error of this.errors) if (error instanceof PlainValue$1.YAMLError) error.makePretty();
  25236. for (const warn of this.warnings) if (warn instanceof PlainValue$1.YAMLError) warn.makePretty();
  25237. }
  25238. return this;
  25239. }
  25240. listNonDefaultTags() {
  25241. return listTagNames(this.contents).filter(t => t.indexOf(Schema$1.Schema.defaultPrefix) !== 0);
  25242. }
  25243. setTagPrefix(handle, prefix) {
  25244. if (handle[0] !== '!' || handle[handle.length - 1] !== '!') throw new Error('Handle must start and end with !');
  25245. if (prefix) {
  25246. const prev = this.tagPrefixes.find(p => p.handle === handle);
  25247. if (prev) prev.prefix = prefix;else this.tagPrefixes.push({
  25248. handle,
  25249. prefix
  25250. });
  25251. } else {
  25252. this.tagPrefixes = this.tagPrefixes.filter(p => p.handle !== handle);
  25253. }
  25254. }
  25255. toJSON(arg, onAnchor) {
  25256. const {
  25257. keepBlobsInJSON,
  25258. mapAsMap,
  25259. maxAliasCount
  25260. } = this.options;
  25261. const keep = keepBlobsInJSON && (typeof arg !== 'string' || !(this.contents instanceof resolveSeq.Scalar));
  25262. const ctx = {
  25263. doc: this,
  25264. indentStep: ' ',
  25265. keep,
  25266. mapAsMap: keep && !!mapAsMap,
  25267. maxAliasCount,
  25268. stringify: stringify$1 // Requiring directly in Pair would create circular dependencies
  25269. };
  25270. const anchorNames = Object.keys(this.anchors.map);
  25271. if (anchorNames.length > 0) ctx.anchors = new Map(anchorNames.map(name => [this.anchors.map[name], {
  25272. alias: [],
  25273. aliasCount: 0,
  25274. count: 1
  25275. }]));
  25276. const res = resolveSeq.toJSON(this.contents, arg, ctx);
  25277. if (typeof onAnchor === 'function' && ctx.anchors) for (const {
  25278. count,
  25279. res
  25280. } of ctx.anchors.values()) onAnchor(res, count);
  25281. return res;
  25282. }
  25283. toString() {
  25284. if (this.errors.length > 0) throw new Error('Document with errors cannot be stringified');
  25285. const indentSize = this.options.indent;
  25286. if (!Number.isInteger(indentSize) || indentSize <= 0) {
  25287. const s = JSON.stringify(indentSize);
  25288. throw new Error(`"indent" option must be a positive integer, not ${s}`);
  25289. }
  25290. this.setSchema();
  25291. const lines = [];
  25292. let hasDirectives = false;
  25293. if (this.version) {
  25294. let vd = '%YAML 1.2';
  25295. if (this.schema.name === 'yaml-1.1') {
  25296. if (this.version === '1.0') vd = '%YAML:1.0';else if (this.version === '1.1') vd = '%YAML 1.1';
  25297. }
  25298. lines.push(vd);
  25299. hasDirectives = true;
  25300. }
  25301. const tagNames = this.listNonDefaultTags();
  25302. this.tagPrefixes.forEach(({
  25303. handle,
  25304. prefix
  25305. }) => {
  25306. if (tagNames.some(t => t.indexOf(prefix) === 0)) {
  25307. lines.push(`%TAG ${handle} ${prefix}`);
  25308. hasDirectives = true;
  25309. }
  25310. });
  25311. if (hasDirectives || this.directivesEndMarker) lines.push('---');
  25312. if (this.commentBefore) {
  25313. if (hasDirectives || !this.directivesEndMarker) lines.unshift('');
  25314. lines.unshift(this.commentBefore.replace(/^/gm, '#'));
  25315. }
  25316. const ctx = {
  25317. anchors: Object.create(null),
  25318. doc: this,
  25319. indent: '',
  25320. indentStep: ' '.repeat(indentSize),
  25321. stringify: stringify$1 // Requiring directly in nodes would create circular dependencies
  25322. };
  25323. let chompKeep = false;
  25324. let contentComment = null;
  25325. if (this.contents) {
  25326. if (this.contents instanceof resolveSeq.Node) {
  25327. if (this.contents.spaceBefore && (hasDirectives || this.directivesEndMarker)) lines.push('');
  25328. if (this.contents.commentBefore) lines.push(this.contents.commentBefore.replace(/^/gm, '#')); // top-level block scalars need to be indented if followed by a comment
  25329. ctx.forceBlockIndent = !!this.comment;
  25330. contentComment = this.contents.comment;
  25331. }
  25332. const onChompKeep = contentComment ? null : () => chompKeep = true;
  25333. const body = stringify$1(this.contents, ctx, () => contentComment = null, onChompKeep);
  25334. lines.push(resolveSeq.addComment(body, '', contentComment));
  25335. } else if (this.contents !== undefined) {
  25336. lines.push(stringify$1(this.contents, ctx));
  25337. }
  25338. if (this.comment) {
  25339. if ((!chompKeep || contentComment) && lines[lines.length - 1] !== '') lines.push('');
  25340. lines.push(this.comment.replace(/^/gm, '#'));
  25341. }
  25342. return lines.join('\n') + '\n';
  25343. }
  25344. }
  25345. PlainValue$1._defineProperty(Document$2, "defaults", documentOptions);
  25346. Document9b4560a1.Document = Document$2;
  25347. Document9b4560a1.defaultOptions = defaultOptions$1;
  25348. Document9b4560a1.scalarOptions = scalarOptions;
  25349. var parseCst = parseCst$1;
  25350. var Document$1 = Document9b4560a1;
  25351. var Schema = Schema88e323a7;
  25352. var PlainValue = PlainValueEc8e588e;
  25353. var warnings = warnings1000a372;
  25354. function createNode(value, wrapScalars = true, tag) {
  25355. if (tag === undefined && typeof wrapScalars === 'string') {
  25356. tag = wrapScalars;
  25357. wrapScalars = true;
  25358. }
  25359. const options = Object.assign({}, Document$1.Document.defaults[Document$1.defaultOptions.version], Document$1.defaultOptions);
  25360. const schema = new Schema.Schema(options);
  25361. return schema.createNode(value, wrapScalars, tag);
  25362. }
  25363. class Document extends Document$1.Document {
  25364. constructor(options) {
  25365. super(Object.assign({}, Document$1.defaultOptions, options));
  25366. }
  25367. }
  25368. function parseAllDocuments(src, options) {
  25369. const stream = [];
  25370. let prev;
  25371. for (const cstDoc of parseCst.parse(src)) {
  25372. const doc = new Document(options);
  25373. doc.parse(cstDoc, prev);
  25374. stream.push(doc);
  25375. prev = doc;
  25376. }
  25377. return stream;
  25378. }
  25379. function parseDocument(src, options) {
  25380. const cst = parseCst.parse(src);
  25381. const doc = new Document(options).parse(cst[0]);
  25382. if (cst.length > 1) {
  25383. const errMsg = 'Source contains multiple documents; please use YAML.parseAllDocuments()';
  25384. doc.errors.unshift(new PlainValue.YAMLSemanticError(cst[1], errMsg));
  25385. }
  25386. return doc;
  25387. }
  25388. function parse$b(src, options) {
  25389. const doc = parseDocument(src, options);
  25390. doc.warnings.forEach(warning => warnings.warn(warning));
  25391. if (doc.errors.length > 0) throw doc.errors[0];
  25392. return doc.toJSON();
  25393. }
  25394. function stringify(value, options) {
  25395. const doc = new Document(options);
  25396. doc.contents = value;
  25397. return String(doc);
  25398. }
  25399. const YAML = {
  25400. createNode,
  25401. defaultOptions: Document$1.defaultOptions,
  25402. Document,
  25403. parse: parse$b,
  25404. parseAllDocuments,
  25405. parseCST: parseCst.parse,
  25406. parseDocument,
  25407. scalarOptions: Document$1.scalarOptions,
  25408. stringify
  25409. };
  25410. dist.YAML = YAML;
  25411. var yaml$1 = dist.YAML;
  25412. // eslint-disable-next-line node/no-deprecated-api
  25413. const { createRequire, createRequireFromPath } = require$$0__default$4;
  25414. function req$2 (name, rootFile) {
  25415. const create = createRequire || createRequireFromPath;
  25416. const require = create(rootFile);
  25417. return require(name)
  25418. }
  25419. var req_1 = req$2;
  25420. const req$1 = req_1;
  25421. /**
  25422. * Load Options
  25423. *
  25424. * @private
  25425. * @method options
  25426. *
  25427. * @param {Object} config PostCSS Config
  25428. *
  25429. * @return {Object} options PostCSS Options
  25430. */
  25431. const options = (config, file) => {
  25432. if (config.parser && typeof config.parser === 'string') {
  25433. try {
  25434. config.parser = req$1(config.parser, file);
  25435. } catch (err) {
  25436. throw new Error(`Loading PostCSS Parser failed: ${err.message}\n\n(@${file})`)
  25437. }
  25438. }
  25439. if (config.syntax && typeof config.syntax === 'string') {
  25440. try {
  25441. config.syntax = req$1(config.syntax, file);
  25442. } catch (err) {
  25443. throw new Error(`Loading PostCSS Syntax failed: ${err.message}\n\n(@${file})`)
  25444. }
  25445. }
  25446. if (config.stringifier && typeof config.stringifier === 'string') {
  25447. try {
  25448. config.stringifier = req$1(config.stringifier, file);
  25449. } catch (err) {
  25450. throw new Error(`Loading PostCSS Stringifier failed: ${err.message}\n\n(@${file})`)
  25451. }
  25452. }
  25453. if (config.plugins) {
  25454. delete config.plugins;
  25455. }
  25456. return config
  25457. };
  25458. var options_1 = options;
  25459. const req = req_1;
  25460. /**
  25461. * Plugin Loader
  25462. *
  25463. * @private
  25464. * @method load
  25465. *
  25466. * @param {String} plugin PostCSS Plugin Name
  25467. * @param {Object} options PostCSS Plugin Options
  25468. *
  25469. * @return {Function} PostCSS Plugin
  25470. */
  25471. const load = (plugin, options, file) => {
  25472. try {
  25473. if (
  25474. options === null ||
  25475. options === undefined ||
  25476. Object.keys(options).length === 0
  25477. ) {
  25478. return req(plugin, file)
  25479. } else {
  25480. return req(plugin, file)(options)
  25481. }
  25482. } catch (err) {
  25483. throw new Error(`Loading PostCSS Plugin failed: ${err.message}\n\n(@${file})`)
  25484. }
  25485. };
  25486. /**
  25487. * Load Plugins
  25488. *
  25489. * @private
  25490. * @method plugins
  25491. *
  25492. * @param {Object} config PostCSS Config Plugins
  25493. *
  25494. * @return {Array} plugins PostCSS Plugins
  25495. */
  25496. const plugins = (config, file) => {
  25497. let plugins = [];
  25498. if (Array.isArray(config.plugins)) {
  25499. plugins = config.plugins.filter(Boolean);
  25500. } else {
  25501. plugins = Object.keys(config.plugins)
  25502. .filter((plugin) => {
  25503. return config.plugins[plugin] !== false ? plugin : ''
  25504. })
  25505. .map((plugin) => {
  25506. return load(plugin, config.plugins[plugin], file)
  25507. });
  25508. }
  25509. if (plugins.length && plugins.length > 0) {
  25510. plugins.forEach((plugin, i) => {
  25511. if (plugin.default) {
  25512. plugin = plugin.default;
  25513. }
  25514. if (plugin.postcss === true) {
  25515. plugin = plugin();
  25516. } else if (plugin.postcss) {
  25517. plugin = plugin.postcss;
  25518. }
  25519. if (
  25520. // eslint-disable-next-line
  25521. !(
  25522. (typeof plugin === 'object' && Array.isArray(plugin.plugins)) ||
  25523. (typeof plugin === 'object' && plugin.postcssPlugin) ||
  25524. (typeof plugin === 'function')
  25525. )
  25526. ) {
  25527. throw new TypeError(`Invalid PostCSS Plugin found at: plugins[${i}]\n\n(@${file})`)
  25528. }
  25529. });
  25530. }
  25531. return plugins
  25532. };
  25533. var plugins_1 = plugins;
  25534. const resolve$1 = path__default.resolve;
  25535. const config = dist$1;
  25536. const yaml = yaml$1;
  25537. const loadOptions = options_1;
  25538. const loadPlugins = plugins_1;
  25539. /* istanbul ignore next */
  25540. const interopRequireDefault = (obj) => obj && obj.__esModule ? obj : { default: obj };
  25541. /**
  25542. * Process the result from cosmiconfig
  25543. *
  25544. * @param {Object} ctx Config Context
  25545. * @param {Object} result Cosmiconfig result
  25546. *
  25547. * @return {Object} PostCSS Config
  25548. */
  25549. const processResult = (ctx, result) => {
  25550. const file = result.filepath || '';
  25551. let config = interopRequireDefault(result.config).default || {};
  25552. if (typeof config === 'function') {
  25553. config = config(ctx);
  25554. } else {
  25555. config = Object.assign({}, config, ctx);
  25556. }
  25557. if (!config.plugins) {
  25558. config.plugins = [];
  25559. }
  25560. return {
  25561. plugins: loadPlugins(config, file),
  25562. options: loadOptions(config, file),
  25563. file: file
  25564. }
  25565. };
  25566. /**
  25567. * Builds the Config Context
  25568. *
  25569. * @param {Object} ctx Config Context
  25570. *
  25571. * @return {Object} Config Context
  25572. */
  25573. const createContext = (ctx) => {
  25574. /**
  25575. * @type {Object}
  25576. *
  25577. * @prop {String} cwd=process.cwd() Config search start location
  25578. * @prop {String} env=process.env.NODE_ENV Config Enviroment, will be set to `development` by `postcss-load-config` if `process.env.NODE_ENV` is `undefined`
  25579. */
  25580. ctx = Object.assign({
  25581. cwd: process.cwd(),
  25582. env: process.env.NODE_ENV
  25583. }, ctx);
  25584. if (!ctx.env) {
  25585. process.env.NODE_ENV = 'development';
  25586. }
  25587. return ctx
  25588. };
  25589. const addTypeScriptLoader = (options = {}, loader) => {
  25590. const moduleName = 'postcss';
  25591. return {
  25592. ...options,
  25593. searchPlaces: [
  25594. ...(options.searchPlaces || []),
  25595. 'package.json',
  25596. `.${moduleName}rc`,
  25597. `.${moduleName}rc.json`,
  25598. `.${moduleName}rc.yaml`,
  25599. `.${moduleName}rc.yml`,
  25600. `.${moduleName}rc.ts`,
  25601. `.${moduleName}rc.js`,
  25602. `.${moduleName}rc.cjs`,
  25603. `${moduleName}.config.ts`,
  25604. `${moduleName}.config.js`,
  25605. `${moduleName}.config.cjs`
  25606. ],
  25607. loaders: {
  25608. ...options.loaders,
  25609. '.yaml': (filepath, content) => yaml.parse(content),
  25610. '.yml': (filepath, content) => yaml.parse(content),
  25611. '.ts': loader
  25612. }
  25613. }
  25614. };
  25615. const withTypeScriptLoader = (rcFunc) => {
  25616. return (ctx, path, options) => {
  25617. return rcFunc(ctx, path, addTypeScriptLoader(options, (configFile) => {
  25618. let registerer = { enabled () {} };
  25619. try {
  25620. // Register TypeScript compiler instance
  25621. registerer = require('ts-node').register();
  25622. return eval('require')(configFile)
  25623. } catch (err) {
  25624. if (err.code === 'MODULE_NOT_FOUND') {
  25625. throw new Error(
  25626. `'ts-node' is required for the TypeScript configuration files. Make sure it is installed\nError: ${err.message}`
  25627. )
  25628. }
  25629. throw err
  25630. } finally {
  25631. registerer.enabled(false);
  25632. }
  25633. }))
  25634. }
  25635. };
  25636. /**
  25637. * Load Config
  25638. *
  25639. * @method rc
  25640. *
  25641. * @param {Object} ctx Config Context
  25642. * @param {String} path Config Path
  25643. * @param {Object} options Config Options
  25644. *
  25645. * @return {Promise} config PostCSS Config
  25646. */
  25647. const rc = withTypeScriptLoader((ctx, path, options) => {
  25648. /**
  25649. * @type {Object} The full Config Context
  25650. */
  25651. ctx = createContext(ctx);
  25652. /**
  25653. * @type {String} `process.cwd()`
  25654. */
  25655. path = path ? resolve$1(path) : process.cwd();
  25656. return config.lilconfig('postcss', options)
  25657. .search(path)
  25658. .then((result) => {
  25659. if (!result) {
  25660. throw new Error(`No PostCSS Config found in: ${path}`)
  25661. }
  25662. return processResult(ctx, result)
  25663. })
  25664. });
  25665. rc.sync = withTypeScriptLoader((ctx, path, options) => {
  25666. /**
  25667. * @type {Object} The full Config Context
  25668. */
  25669. ctx = createContext(ctx);
  25670. /**
  25671. * @type {String} `process.cwd()`
  25672. */
  25673. path = path ? resolve$1(path) : process.cwd();
  25674. const result = config.lilconfigSync('postcss', options).search(path);
  25675. if (!result) {
  25676. throw new Error(`No PostCSS Config found in: ${path}`)
  25677. }
  25678. return processResult(ctx, result)
  25679. });
  25680. /**
  25681. * Autoload Config for PostCSS
  25682. *
  25683. * @author Michael Ciniawsky @michael-ciniawsky <michael.ciniawsky@gmail.com>
  25684. * @license MIT
  25685. *
  25686. * @module postcss-load-config
  25687. * @version 2.1.0
  25688. *
  25689. * @requires comsiconfig
  25690. * @requires ./options
  25691. * @requires ./plugins
  25692. */
  25693. var src$1 = rc;
  25694. const isDebug$6 = !!process.env.DEBUG;
  25695. const debug$e = createDebugger('vite:sourcemap', {
  25696. onlyWhenFocused: true
  25697. });
  25698. // Virtual modules should be prefixed with a null byte to avoid a
  25699. // false positive "missing source" warning. We also check for certain
  25700. // prefixes used for special handling in esbuildDepPlugin.
  25701. const virtualSourceRE = /^(\0|dep:|browser-external:)/;
  25702. async function injectSourcesContent(map, file, logger) {
  25703. let sourceRoot;
  25704. try {
  25705. // The source root is undefined for virtual modules and permission errors.
  25706. sourceRoot = await fs$n.promises.realpath(path__default.resolve(path__default.dirname(file), map.sourceRoot || ''));
  25707. }
  25708. catch { }
  25709. const missingSources = [];
  25710. map.sourcesContent = await Promise.all(map.sources.map((sourcePath) => {
  25711. if (sourcePath && !virtualSourceRE.test(sourcePath)) {
  25712. sourcePath = decodeURI(sourcePath);
  25713. if (sourceRoot) {
  25714. sourcePath = path__default.resolve(sourceRoot, sourcePath);
  25715. }
  25716. return fs$n.promises.readFile(sourcePath, 'utf-8').catch(() => {
  25717. missingSources.push(sourcePath);
  25718. return null;
  25719. });
  25720. }
  25721. return null;
  25722. }));
  25723. // Use this command…
  25724. // DEBUG="vite:sourcemap" vite build
  25725. // …to log the missing sources.
  25726. if (missingSources.length) {
  25727. logger.warnOnce(`Sourcemap for "${file}" points to missing source files`);
  25728. isDebug$6 && debug$e(`Missing sources:\n ` + missingSources.join(`\n `));
  25729. }
  25730. }
  25731. function genSourceMapUrl(map) {
  25732. if (typeof map !== 'string') {
  25733. map = JSON.stringify(map);
  25734. }
  25735. return `data:application/json;base64,${Buffer.from(map).toString('base64')}`;
  25736. }
  25737. function getCodeWithSourcemap(type, code, map) {
  25738. if (isDebug$6) {
  25739. code += `\n/*${JSON.stringify(map, null, 2).replace(/\*\//g, '*\\/')}*/\n`;
  25740. }
  25741. if (type === 'js') {
  25742. code += `\n//# sourceMappingURL=${genSourceMapUrl(map !== null && map !== void 0 ? map : undefined)}`;
  25743. }
  25744. else if (type === 'css') {
  25745. code += `\n/*# sourceMappingURL=${genSourceMapUrl(map !== null && map !== void 0 ? map : undefined)} */`;
  25746. }
  25747. return code;
  25748. }
  25749. // This file was generated. Do not modify manually!
  25750. var astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 370, 1, 154, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 161, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 19306, 9, 87, 9, 39, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4706, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 262, 6, 10, 9, 357, 0, 62, 13, 1495, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];
  25751. // This file was generated. Do not modify manually!
  25752. var astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 68, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 85, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 190, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1070, 4050, 582, 8634, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8936, 3, 2, 6, 2, 1, 2, 290, 46, 2, 18, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 482, 44, 11, 6, 17, 0, 322, 29, 19, 43, 1269, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4152, 8, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938];
  25753. // This file was generated. Do not modify manually!
  25754. var nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0898-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f";
  25755. // This file was generated. Do not modify manually!
  25756. var nonASCIIidentifierStartChars = "\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\u0560-\u0588\u05d0-\u05ea\u05ef-\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\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\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\u09fc\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\u0af9\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-\u0c5a\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\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-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\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-\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-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7ca\ua7d0\ua7d1\ua7d3\ua7d5-\ua7d9\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\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-\uab69\uab70-\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";
  25757. // These are a run-length and offset encoded representation of the
  25758. // Reserved word lists for various dialects of the language
  25759. var reservedWords = {
  25760. 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",
  25761. 5: "class enum extends super const export import",
  25762. 6: "enum",
  25763. strict: "implements interface let package private protected public static yield",
  25764. strictBind: "eval arguments"
  25765. };
  25766. // And the keywords
  25767. var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";
  25768. var keywords$1 = {
  25769. 5: ecma5AndLessKeywords,
  25770. "5module": ecma5AndLessKeywords + " export import",
  25771. 6: ecma5AndLessKeywords + " const class extends export import super"
  25772. };
  25773. var keywordRelationalOperator = /^in(stanceof)?$/;
  25774. // ## Character categories
  25775. var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  25776. var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  25777. // This has a complexity linear to the value of the code. The
  25778. // assumption is that looking up astral identifier characters is
  25779. // rare.
  25780. function isInAstralSet(code, set) {
  25781. var pos = 0x10000;
  25782. for (var i = 0; i < set.length; i += 2) {
  25783. pos += set[i];
  25784. if (pos > code) { return false }
  25785. pos += set[i + 1];
  25786. if (pos >= code) { return true }
  25787. }
  25788. }
  25789. // Test whether a given character code starts an identifier.
  25790. function isIdentifierStart(code, astral) {
  25791. if (code < 65) { return code === 36 }
  25792. if (code < 91) { return true }
  25793. if (code < 97) { return code === 95 }
  25794. if (code < 123) { return true }
  25795. if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) }
  25796. if (astral === false) { return false }
  25797. return isInAstralSet(code, astralIdentifierStartCodes)
  25798. }
  25799. // Test whether a given character is part of an identifier.
  25800. function isIdentifierChar(code, astral) {
  25801. if (code < 48) { return code === 36 }
  25802. if (code < 58) { return true }
  25803. if (code < 65) { return false }
  25804. if (code < 91) { return true }
  25805. if (code < 97) { return code === 95 }
  25806. if (code < 123) { return true }
  25807. if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) }
  25808. if (astral === false) { return false }
  25809. return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes)
  25810. }
  25811. // ## Token types
  25812. // The assignment of fine-grained, information-carrying type objects
  25813. // allows the tokenizer to store the information it has about a
  25814. // token in a way that is very cheap for the parser to look up.
  25815. // All token type variables start with an underscore, to make them
  25816. // easy to recognize.
  25817. // The `beforeExpr` property is used to disambiguate between regular
  25818. // expressions and divisions. It is set on all token types that can
  25819. // be followed by an expression (thus, a slash after them would be a
  25820. // regular expression).
  25821. //
  25822. // The `startsExpr` property is used to check if the token ends a
  25823. // `yield` expression. It is set on all token types that either can
  25824. // directly start an expression (like a quotation mark) or can
  25825. // continue an expression (like the body of a string).
  25826. //
  25827. // `isLoop` marks a keyword as starting a loop, which is important
  25828. // to know when parsing a label, in order to allow or disallow
  25829. // continue jumps to that label.
  25830. var TokenType = function TokenType(label, conf) {
  25831. if ( conf === void 0 ) conf = {};
  25832. this.label = label;
  25833. this.keyword = conf.keyword;
  25834. this.beforeExpr = !!conf.beforeExpr;
  25835. this.startsExpr = !!conf.startsExpr;
  25836. this.isLoop = !!conf.isLoop;
  25837. this.isAssign = !!conf.isAssign;
  25838. this.prefix = !!conf.prefix;
  25839. this.postfix = !!conf.postfix;
  25840. this.binop = conf.binop || null;
  25841. this.updateContext = null;
  25842. };
  25843. function binop(name, prec) {
  25844. return new TokenType(name, {beforeExpr: true, binop: prec})
  25845. }
  25846. var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true};
  25847. // Map keyword names to token types.
  25848. var keywords = {};
  25849. // Succinct definitions of keyword token types
  25850. function kw(name, options) {
  25851. if ( options === void 0 ) options = {};
  25852. options.keyword = name;
  25853. return keywords[name] = new TokenType(name, options)
  25854. }
  25855. var types$1 = {
  25856. num: new TokenType("num", startsExpr),
  25857. regexp: new TokenType("regexp", startsExpr),
  25858. string: new TokenType("string", startsExpr),
  25859. name: new TokenType("name", startsExpr),
  25860. privateId: new TokenType("privateId", startsExpr),
  25861. eof: new TokenType("eof"),
  25862. // Punctuation token types.
  25863. bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}),
  25864. bracketR: new TokenType("]"),
  25865. braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}),
  25866. braceR: new TokenType("}"),
  25867. parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}),
  25868. parenR: new TokenType(")"),
  25869. comma: new TokenType(",", beforeExpr),
  25870. semi: new TokenType(";", beforeExpr),
  25871. colon: new TokenType(":", beforeExpr),
  25872. dot: new TokenType("."),
  25873. question: new TokenType("?", beforeExpr),
  25874. questionDot: new TokenType("?."),
  25875. arrow: new TokenType("=>", beforeExpr),
  25876. template: new TokenType("template"),
  25877. invalidTemplate: new TokenType("invalidTemplate"),
  25878. ellipsis: new TokenType("...", beforeExpr),
  25879. backQuote: new TokenType("`", startsExpr),
  25880. dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}),
  25881. // Operators. These carry several kinds of properties to help the
  25882. // parser use them properly (the presence of these properties is
  25883. // what categorizes them as operators).
  25884. //
  25885. // `binop`, when present, specifies that this operator is a binary
  25886. // operator, and will refer to its precedence.
  25887. //
  25888. // `prefix` and `postfix` mark the operator as a prefix or postfix
  25889. // unary operator.
  25890. //
  25891. // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
  25892. // binary operators with a very low precedence, that should result
  25893. // in AssignmentExpression nodes.
  25894. eq: new TokenType("=", {beforeExpr: true, isAssign: true}),
  25895. assign: new TokenType("_=", {beforeExpr: true, isAssign: true}),
  25896. incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}),
  25897. prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}),
  25898. logicalOR: binop("||", 1),
  25899. logicalAND: binop("&&", 2),
  25900. bitwiseOR: binop("|", 3),
  25901. bitwiseXOR: binop("^", 4),
  25902. bitwiseAND: binop("&", 5),
  25903. equality: binop("==/!=/===/!==", 6),
  25904. relational: binop("</>/<=/>=", 7),
  25905. bitShift: binop("<</>>/>>>", 8),
  25906. plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}),
  25907. modulo: binop("%", 10),
  25908. star: binop("*", 10),
  25909. slash: binop("/", 10),
  25910. starstar: new TokenType("**", {beforeExpr: true}),
  25911. coalesce: binop("??", 1),
  25912. // Keyword token types.
  25913. _break: kw("break"),
  25914. _case: kw("case", beforeExpr),
  25915. _catch: kw("catch"),
  25916. _continue: kw("continue"),
  25917. _debugger: kw("debugger"),
  25918. _default: kw("default", beforeExpr),
  25919. _do: kw("do", {isLoop: true, beforeExpr: true}),
  25920. _else: kw("else", beforeExpr),
  25921. _finally: kw("finally"),
  25922. _for: kw("for", {isLoop: true}),
  25923. _function: kw("function", startsExpr),
  25924. _if: kw("if"),
  25925. _return: kw("return", beforeExpr),
  25926. _switch: kw("switch"),
  25927. _throw: kw("throw", beforeExpr),
  25928. _try: kw("try"),
  25929. _var: kw("var"),
  25930. _const: kw("const"),
  25931. _while: kw("while", {isLoop: true}),
  25932. _with: kw("with"),
  25933. _new: kw("new", {beforeExpr: true, startsExpr: true}),
  25934. _this: kw("this", startsExpr),
  25935. _super: kw("super", startsExpr),
  25936. _class: kw("class", startsExpr),
  25937. _extends: kw("extends", beforeExpr),
  25938. _export: kw("export"),
  25939. _import: kw("import", startsExpr),
  25940. _null: kw("null", startsExpr),
  25941. _true: kw("true", startsExpr),
  25942. _false: kw("false", startsExpr),
  25943. _in: kw("in", {beforeExpr: true, binop: 7}),
  25944. _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}),
  25945. _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}),
  25946. _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}),
  25947. _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true})
  25948. };
  25949. // Matches a whole line break (where CRLF is considered a single
  25950. // line break). Used to count lines.
  25951. var lineBreak = /\r\n?|\n|\u2028|\u2029/;
  25952. var lineBreakG = new RegExp(lineBreak.source, "g");
  25953. function isNewLine(code) {
  25954. return code === 10 || code === 13 || code === 0x2028 || code === 0x2029
  25955. }
  25956. function nextLineBreak(code, from, end) {
  25957. if ( end === void 0 ) end = code.length;
  25958. for (var i = from; i < end; i++) {
  25959. var next = code.charCodeAt(i);
  25960. if (isNewLine(next))
  25961. { return i < end - 1 && next === 13 && code.charCodeAt(i + 1) === 10 ? i + 2 : i + 1 }
  25962. }
  25963. return -1
  25964. }
  25965. var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
  25966. var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
  25967. var ref = Object.prototype;
  25968. var hasOwnProperty$1 = ref.hasOwnProperty;
  25969. var toString$1 = ref.toString;
  25970. var hasOwn = Object.hasOwn || (function (obj, propName) { return (
  25971. hasOwnProperty$1.call(obj, propName)
  25972. ); });
  25973. var isArray = Array.isArray || (function (obj) { return (
  25974. toString$1.call(obj) === "[object Array]"
  25975. ); });
  25976. function wordsRegexp(words) {
  25977. return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$")
  25978. }
  25979. function codePointToString(code) {
  25980. // UTF-16 Decoding
  25981. if (code <= 0xFFFF) { return String.fromCharCode(code) }
  25982. code -= 0x10000;
  25983. return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00)
  25984. }
  25985. var loneSurrogate = /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/;
  25986. // These are used when `options.locations` is on, for the
  25987. // `startLoc` and `endLoc` properties.
  25988. var Position = function Position(line, col) {
  25989. this.line = line;
  25990. this.column = col;
  25991. };
  25992. Position.prototype.offset = function offset (n) {
  25993. return new Position(this.line, this.column + n)
  25994. };
  25995. var SourceLocation = function SourceLocation(p, start, end) {
  25996. this.start = start;
  25997. this.end = end;
  25998. if (p.sourceFile !== null) { this.source = p.sourceFile; }
  25999. };
  26000. // The `getLineInfo` function is mostly useful when the
  26001. // `locations` option is off (for performance reasons) and you
  26002. // want to find the line/column position for a given character
  26003. // offset. `input` should be the code string that the offset refers
  26004. // into.
  26005. function getLineInfo(input, offset) {
  26006. for (var line = 1, cur = 0;;) {
  26007. var nextBreak = nextLineBreak(input, cur, offset);
  26008. if (nextBreak < 0) { return new Position(line, offset - cur) }
  26009. ++line;
  26010. cur = nextBreak;
  26011. }
  26012. }
  26013. // A second argument must be given to configure the parser process.
  26014. // These options are recognized (only `ecmaVersion` is required):
  26015. var defaultOptions = {
  26016. // `ecmaVersion` indicates the ECMAScript version to parse. Must be
  26017. // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10
  26018. // (2019), 11 (2020), 12 (2021), 13 (2022), or `"latest"` (the
  26019. // latest version the library supports). This influences support
  26020. // for strict mode, the set of reserved words, and support for
  26021. // new syntax features.
  26022. ecmaVersion: null,
  26023. // `sourceType` indicates the mode the code should be parsed in.
  26024. // Can be either `"script"` or `"module"`. This influences global
  26025. // strict mode and parsing of `import` and `export` declarations.
  26026. sourceType: "script",
  26027. // `onInsertedSemicolon` can be a callback that will be called
  26028. // when a semicolon is automatically inserted. It will be passed
  26029. // the position of the comma as an offset, and if `locations` is
  26030. // enabled, it is given the location as a `{line, column}` object
  26031. // as second argument.
  26032. onInsertedSemicolon: null,
  26033. // `onTrailingComma` is similar to `onInsertedSemicolon`, but for
  26034. // trailing commas.
  26035. onTrailingComma: null,
  26036. // By default, reserved words are only enforced if ecmaVersion >= 5.
  26037. // Set `allowReserved` to a boolean value to explicitly turn this on
  26038. // an off. When this option has the value "never", reserved words
  26039. // and keywords can also not be used as property names.
  26040. allowReserved: null,
  26041. // When enabled, a return at the top level is not considered an
  26042. // error.
  26043. allowReturnOutsideFunction: false,
  26044. // When enabled, import/export statements are not constrained to
  26045. // appearing at the top of the program, and an import.meta expression
  26046. // in a script isn't considered an error.
  26047. allowImportExportEverywhere: false,
  26048. // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022.
  26049. // When enabled, await identifiers are allowed to appear at the top-level scope,
  26050. // but they are still not allowed in non-async functions.
  26051. allowAwaitOutsideFunction: null,
  26052. // When enabled, super identifiers are not constrained to
  26053. // appearing in methods and do not raise an error when they appear elsewhere.
  26054. allowSuperOutsideMethod: null,
  26055. // When enabled, hashbang directive in the beginning of file
  26056. // is allowed and treated as a line comment.
  26057. allowHashBang: false,
  26058. // When `locations` is on, `loc` properties holding objects with
  26059. // `start` and `end` properties in `{line, column}` form (with
  26060. // line being 1-based and column 0-based) will be attached to the
  26061. // nodes.
  26062. locations: false,
  26063. // A function can be passed as `onToken` option, which will
  26064. // cause Acorn to call that function with object in the same
  26065. // format as tokens returned from `tokenizer().getToken()`. Note
  26066. // that you are not allowed to call the parser from the
  26067. // callback—that will corrupt its internal state.
  26068. onToken: null,
  26069. // A function can be passed as `onComment` option, which will
  26070. // cause Acorn to call that function with `(block, text, start,
  26071. // end)` parameters whenever a comment is skipped. `block` is a
  26072. // boolean indicating whether this is a block (`/* */`) comment,
  26073. // `text` is the content of the comment, and `start` and `end` are
  26074. // character offsets that denote the start and end of the comment.
  26075. // When the `locations` option is on, two more parameters are
  26076. // passed, the full `{line, column}` locations of the start and
  26077. // end of the comments. Note that you are not allowed to call the
  26078. // parser from the callback—that will corrupt its internal state.
  26079. onComment: null,
  26080. // Nodes have their start and end characters offsets recorded in
  26081. // `start` and `end` properties (directly on the node, rather than
  26082. // the `loc` object, which holds line/column data. To also add a
  26083. // [semi-standardized][range] `range` property holding a `[start,
  26084. // end]` array with the same numbers, set the `ranges` option to
  26085. // `true`.
  26086. //
  26087. // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
  26088. ranges: false,
  26089. // It is possible to parse multiple files into a single AST by
  26090. // passing the tree produced by parsing the first file as
  26091. // `program` option in subsequent parses. This will add the
  26092. // toplevel forms of the parsed file to the `Program` (top) node
  26093. // of an existing parse tree.
  26094. program: null,
  26095. // When `locations` is on, you can pass this to record the source
  26096. // file in every node's `loc` object.
  26097. sourceFile: null,
  26098. // This value, if given, is stored in every node, whether
  26099. // `locations` is on or off.
  26100. directSourceFile: null,
  26101. // When enabled, parenthesized expressions are represented by
  26102. // (non-standard) ParenthesizedExpression nodes
  26103. preserveParens: false
  26104. };
  26105. // Interpret and default an options object
  26106. var warnedAboutEcmaVersion = false;
  26107. function getOptions(opts) {
  26108. var options = {};
  26109. for (var opt in defaultOptions)
  26110. { options[opt] = opts && hasOwn(opts, opt) ? opts[opt] : defaultOptions[opt]; }
  26111. if (options.ecmaVersion === "latest") {
  26112. options.ecmaVersion = 1e8;
  26113. } else if (options.ecmaVersion == null) {
  26114. if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) {
  26115. warnedAboutEcmaVersion = true;
  26116. console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.");
  26117. }
  26118. options.ecmaVersion = 11;
  26119. } else if (options.ecmaVersion >= 2015) {
  26120. options.ecmaVersion -= 2009;
  26121. }
  26122. if (options.allowReserved == null)
  26123. { options.allowReserved = options.ecmaVersion < 5; }
  26124. if (isArray(options.onToken)) {
  26125. var tokens = options.onToken;
  26126. options.onToken = function (token) { return tokens.push(token); };
  26127. }
  26128. if (isArray(options.onComment))
  26129. { options.onComment = pushComment(options, options.onComment); }
  26130. return options
  26131. }
  26132. function pushComment(options, array) {
  26133. return function(block, text, start, end, startLoc, endLoc) {
  26134. var comment = {
  26135. type: block ? "Block" : "Line",
  26136. value: text,
  26137. start: start,
  26138. end: end
  26139. };
  26140. if (options.locations)
  26141. { comment.loc = new SourceLocation(this, startLoc, endLoc); }
  26142. if (options.ranges)
  26143. { comment.range = [start, end]; }
  26144. array.push(comment);
  26145. }
  26146. }
  26147. // Each scope gets a bitset that may contain these flags
  26148. var
  26149. SCOPE_TOP = 1,
  26150. SCOPE_FUNCTION = 2,
  26151. SCOPE_ASYNC = 4,
  26152. SCOPE_GENERATOR = 8,
  26153. SCOPE_ARROW = 16,
  26154. SCOPE_SIMPLE_CATCH = 32,
  26155. SCOPE_SUPER = 64,
  26156. SCOPE_DIRECT_SUPER = 128,
  26157. SCOPE_CLASS_STATIC_BLOCK = 256,
  26158. SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK;
  26159. function functionFlags(async, generator) {
  26160. return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0)
  26161. }
  26162. // Used in checkLVal* and declareName to determine the type of a binding
  26163. var
  26164. BIND_NONE = 0, // Not a binding
  26165. BIND_VAR = 1, // Var-style binding
  26166. BIND_LEXICAL = 2, // Let- or const-style binding
  26167. BIND_FUNCTION = 3, // Function declaration
  26168. BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding
  26169. BIND_OUTSIDE = 5; // Special case for function names as bound inside the function
  26170. var Parser = function Parser(options, input, startPos) {
  26171. this.options = options = getOptions(options);
  26172. this.sourceFile = options.sourceFile;
  26173. this.keywords = wordsRegexp(keywords$1[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);
  26174. var reserved = "";
  26175. if (options.allowReserved !== true) {
  26176. reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3];
  26177. if (options.sourceType === "module") { reserved += " await"; }
  26178. }
  26179. this.reservedWords = wordsRegexp(reserved);
  26180. var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict;
  26181. this.reservedWordsStrict = wordsRegexp(reservedStrict);
  26182. this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind);
  26183. this.input = String(input);
  26184. // Used to signal to callers of `readWord1` whether the word
  26185. // contained any escape sequences. This is needed because words with
  26186. // escape sequences must not be interpreted as keywords.
  26187. this.containsEsc = false;
  26188. // Set up token state
  26189. // The current position of the tokenizer in the input.
  26190. if (startPos) {
  26191. this.pos = startPos;
  26192. this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;
  26193. this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;
  26194. } else {
  26195. this.pos = this.lineStart = 0;
  26196. this.curLine = 1;
  26197. }
  26198. // Properties of the current token:
  26199. // Its type
  26200. this.type = types$1.eof;
  26201. // For tokens that include more information than their type, the value
  26202. this.value = null;
  26203. // Its start and end offset
  26204. this.start = this.end = this.pos;
  26205. // And, if locations are used, the {line, column} object
  26206. // corresponding to those offsets
  26207. this.startLoc = this.endLoc = this.curPosition();
  26208. // Position information for the previous token
  26209. this.lastTokEndLoc = this.lastTokStartLoc = null;
  26210. this.lastTokStart = this.lastTokEnd = this.pos;
  26211. // The context stack is used to superficially track syntactic
  26212. // context to predict whether a regular expression is allowed in a
  26213. // given position.
  26214. this.context = this.initialContext();
  26215. this.exprAllowed = true;
  26216. // Figure out if it's a module code.
  26217. this.inModule = options.sourceType === "module";
  26218. this.strict = this.inModule || this.strictDirective(this.pos);
  26219. // Used to signify the start of a potential arrow function
  26220. this.potentialArrowAt = -1;
  26221. this.potentialArrowInForAwait = false;
  26222. // Positions to delayed-check that yield/await does not exist in default parameters.
  26223. this.yieldPos = this.awaitPos = this.awaitIdentPos = 0;
  26224. // Labels in scope.
  26225. this.labels = [];
  26226. // Thus-far undefined exports.
  26227. this.undefinedExports = Object.create(null);
  26228. // If enabled, skip leading hashbang line.
  26229. if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!")
  26230. { this.skipLineComment(2); }
  26231. // Scope tracking for duplicate variable names (see scope.js)
  26232. this.scopeStack = [];
  26233. this.enterScope(SCOPE_TOP);
  26234. // For RegExp validation
  26235. this.regexpState = null;
  26236. // The stack of private names.
  26237. // Each element has two properties: 'declared' and 'used'.
  26238. // When it exited from the outermost class definition, all used private names must be declared.
  26239. this.privateNameStack = [];
  26240. };
  26241. var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },canAwait: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true },allowNewDotTarget: { configurable: true },inClassStaticBlock: { configurable: true } };
  26242. Parser.prototype.parse = function parse () {
  26243. var node = this.options.program || this.startNode();
  26244. this.nextToken();
  26245. return this.parseTopLevel(node)
  26246. };
  26247. prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 };
  26248. prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 && !this.currentVarScope().inClassFieldInit };
  26249. prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 && !this.currentVarScope().inClassFieldInit };
  26250. prototypeAccessors.canAwait.get = function () {
  26251. for (var i = this.scopeStack.length - 1; i >= 0; i--) {
  26252. var scope = this.scopeStack[i];
  26253. if (scope.inClassFieldInit || scope.flags & SCOPE_CLASS_STATIC_BLOCK) { return false }
  26254. if (scope.flags & SCOPE_FUNCTION) { return (scope.flags & SCOPE_ASYNC) > 0 }
  26255. }
  26256. return (this.inModule && this.options.ecmaVersion >= 13) || this.options.allowAwaitOutsideFunction
  26257. };
  26258. prototypeAccessors.allowSuper.get = function () {
  26259. var ref = this.currentThisScope();
  26260. var flags = ref.flags;
  26261. var inClassFieldInit = ref.inClassFieldInit;
  26262. return (flags & SCOPE_SUPER) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod
  26263. };
  26264. prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 };
  26265. prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) };
  26266. prototypeAccessors.allowNewDotTarget.get = function () {
  26267. var ref = this.currentThisScope();
  26268. var flags = ref.flags;
  26269. var inClassFieldInit = ref.inClassFieldInit;
  26270. return (flags & (SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK)) > 0 || inClassFieldInit
  26271. };
  26272. prototypeAccessors.inClassStaticBlock.get = function () {
  26273. return (this.currentVarScope().flags & SCOPE_CLASS_STATIC_BLOCK) > 0
  26274. };
  26275. Parser.extend = function extend () {
  26276. var plugins = [], len = arguments.length;
  26277. while ( len-- ) plugins[ len ] = arguments[ len ];
  26278. var cls = this;
  26279. for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); }
  26280. return cls
  26281. };
  26282. Parser.parse = function parse (input, options) {
  26283. return new this(options, input).parse()
  26284. };
  26285. Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) {
  26286. var parser = new this(options, input, pos);
  26287. parser.nextToken();
  26288. return parser.parseExpression()
  26289. };
  26290. Parser.tokenizer = function tokenizer (input, options) {
  26291. return new this(options, input)
  26292. };
  26293. Object.defineProperties( Parser.prototype, prototypeAccessors );
  26294. var pp$9 = Parser.prototype;
  26295. // ## Parser utilities
  26296. var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/;
  26297. pp$9.strictDirective = function(start) {
  26298. if (this.options.ecmaVersion < 5) { return false }
  26299. for (;;) {
  26300. // Try to find string literal.
  26301. skipWhiteSpace.lastIndex = start;
  26302. start += skipWhiteSpace.exec(this.input)[0].length;
  26303. var match = literal.exec(this.input.slice(start));
  26304. if (!match) { return false }
  26305. if ((match[1] || match[2]) === "use strict") {
  26306. skipWhiteSpace.lastIndex = start + match[0].length;
  26307. var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length;
  26308. var next = this.input.charAt(end);
  26309. return next === ";" || next === "}" ||
  26310. (lineBreak.test(spaceAfter[0]) &&
  26311. !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "="))
  26312. }
  26313. start += match[0].length;
  26314. // Skip semicolon, if any.
  26315. skipWhiteSpace.lastIndex = start;
  26316. start += skipWhiteSpace.exec(this.input)[0].length;
  26317. if (this.input[start] === ";")
  26318. { start++; }
  26319. }
  26320. };
  26321. // Predicate that tests whether the next token is of the given
  26322. // type, and if yes, consumes it as a side effect.
  26323. pp$9.eat = function(type) {
  26324. if (this.type === type) {
  26325. this.next();
  26326. return true
  26327. } else {
  26328. return false
  26329. }
  26330. };
  26331. // Tests whether parsed token is a contextual keyword.
  26332. pp$9.isContextual = function(name) {
  26333. return this.type === types$1.name && this.value === name && !this.containsEsc
  26334. };
  26335. // Consumes contextual keyword if possible.
  26336. pp$9.eatContextual = function(name) {
  26337. if (!this.isContextual(name)) { return false }
  26338. this.next();
  26339. return true
  26340. };
  26341. // Asserts that following token is given contextual keyword.
  26342. pp$9.expectContextual = function(name) {
  26343. if (!this.eatContextual(name)) { this.unexpected(); }
  26344. };
  26345. // Test whether a semicolon can be inserted at the current position.
  26346. pp$9.canInsertSemicolon = function() {
  26347. return this.type === types$1.eof ||
  26348. this.type === types$1.braceR ||
  26349. lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
  26350. };
  26351. pp$9.insertSemicolon = function() {
  26352. if (this.canInsertSemicolon()) {
  26353. if (this.options.onInsertedSemicolon)
  26354. { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); }
  26355. return true
  26356. }
  26357. };
  26358. // Consume a semicolon, or, failing that, see if we are allowed to
  26359. // pretend that there is a semicolon at this position.
  26360. pp$9.semicolon = function() {
  26361. if (!this.eat(types$1.semi) && !this.insertSemicolon()) { this.unexpected(); }
  26362. };
  26363. pp$9.afterTrailingComma = function(tokType, notNext) {
  26364. if (this.type === tokType) {
  26365. if (this.options.onTrailingComma)
  26366. { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); }
  26367. if (!notNext)
  26368. { this.next(); }
  26369. return true
  26370. }
  26371. };
  26372. // Expect a token of a given type. If found, consume it, otherwise,
  26373. // raise an unexpected token error.
  26374. pp$9.expect = function(type) {
  26375. this.eat(type) || this.unexpected();
  26376. };
  26377. // Raise an unexpected token error.
  26378. pp$9.unexpected = function(pos) {
  26379. this.raise(pos != null ? pos : this.start, "Unexpected token");
  26380. };
  26381. var DestructuringErrors = function DestructuringErrors() {
  26382. this.shorthandAssign =
  26383. this.trailingComma =
  26384. this.parenthesizedAssign =
  26385. this.parenthesizedBind =
  26386. this.doubleProto =
  26387. -1;
  26388. };
  26389. pp$9.checkPatternErrors = function(refDestructuringErrors, isAssign) {
  26390. if (!refDestructuringErrors) { return }
  26391. if (refDestructuringErrors.trailingComma > -1)
  26392. { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); }
  26393. var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;
  26394. if (parens > -1) { this.raiseRecoverable(parens, "Parenthesized pattern"); }
  26395. };
  26396. pp$9.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
  26397. if (!refDestructuringErrors) { return false }
  26398. var shorthandAssign = refDestructuringErrors.shorthandAssign;
  26399. var doubleProto = refDestructuringErrors.doubleProto;
  26400. if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 }
  26401. if (shorthandAssign >= 0)
  26402. { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); }
  26403. if (doubleProto >= 0)
  26404. { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); }
  26405. };
  26406. pp$9.checkYieldAwaitInDefaultParams = function() {
  26407. if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos))
  26408. { this.raise(this.yieldPos, "Yield expression cannot be a default value"); }
  26409. if (this.awaitPos)
  26410. { this.raise(this.awaitPos, "Await expression cannot be a default value"); }
  26411. };
  26412. pp$9.isSimpleAssignTarget = function(expr) {
  26413. if (expr.type === "ParenthesizedExpression")
  26414. { return this.isSimpleAssignTarget(expr.expression) }
  26415. return expr.type === "Identifier" || expr.type === "MemberExpression"
  26416. };
  26417. var pp$8 = Parser.prototype;
  26418. // ### Statement parsing
  26419. // Parse a program. Initializes the parser, reads any number of
  26420. // statements, and wraps them in a Program node. Optionally takes a
  26421. // `program` argument. If present, the statements will be appended
  26422. // to its body instead of creating a new node.
  26423. pp$8.parseTopLevel = function(node) {
  26424. var exports = Object.create(null);
  26425. if (!node.body) { node.body = []; }
  26426. while (this.type !== types$1.eof) {
  26427. var stmt = this.parseStatement(null, true, exports);
  26428. node.body.push(stmt);
  26429. }
  26430. if (this.inModule)
  26431. { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1)
  26432. {
  26433. var name = list[i];
  26434. this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined"));
  26435. } }
  26436. this.adaptDirectivePrologue(node.body);
  26437. this.next();
  26438. node.sourceType = this.options.sourceType;
  26439. return this.finishNode(node, "Program")
  26440. };
  26441. var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"};
  26442. pp$8.isLet = function(context) {
  26443. if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false }
  26444. skipWhiteSpace.lastIndex = this.pos;
  26445. var skip = skipWhiteSpace.exec(this.input);
  26446. var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
  26447. // For ambiguous cases, determine if a LexicalDeclaration (or only a
  26448. // Statement) is allowed here. If context is not empty then only a Statement
  26449. // is allowed. However, `let [` is an explicit negative lookahead for
  26450. // ExpressionStatement, so special-case it first.
  26451. if (nextCh === 91 || nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } // '[', '/', astral
  26452. if (context) { return false }
  26453. if (nextCh === 123) { return true } // '{'
  26454. if (isIdentifierStart(nextCh, true)) {
  26455. var pos = next + 1;
  26456. while (isIdentifierChar(nextCh = this.input.charCodeAt(pos), true)) { ++pos; }
  26457. if (nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true }
  26458. var ident = this.input.slice(next, pos);
  26459. if (!keywordRelationalOperator.test(ident)) { return true }
  26460. }
  26461. return false
  26462. };
  26463. // check 'async [no LineTerminator here] function'
  26464. // - 'async /*foo*/ function' is OK.
  26465. // - 'async /*\n*/ function' is invalid.
  26466. pp$8.isAsyncFunction = function() {
  26467. if (this.options.ecmaVersion < 8 || !this.isContextual("async"))
  26468. { return false }
  26469. skipWhiteSpace.lastIndex = this.pos;
  26470. var skip = skipWhiteSpace.exec(this.input);
  26471. var next = this.pos + skip[0].length, after;
  26472. return !lineBreak.test(this.input.slice(this.pos, next)) &&
  26473. this.input.slice(next, next + 8) === "function" &&
  26474. (next + 8 === this.input.length ||
  26475. !(isIdentifierChar(after = this.input.charCodeAt(next + 8)) || after > 0xd7ff && after < 0xdc00))
  26476. };
  26477. // Parse a single statement.
  26478. //
  26479. // If expecting a statement and finding a slash operator, parse a
  26480. // regular expression literal. This is to handle cases like
  26481. // `if (foo) /blah/.exec(foo)`, where looking at the previous token
  26482. // does not help.
  26483. pp$8.parseStatement = function(context, topLevel, exports) {
  26484. var starttype = this.type, node = this.startNode(), kind;
  26485. if (this.isLet(context)) {
  26486. starttype = types$1._var;
  26487. kind = "let";
  26488. }
  26489. // Most types of statements are recognized by the keyword they
  26490. // start with. Many are trivial to parse, some require a bit of
  26491. // complexity.
  26492. switch (starttype) {
  26493. case types$1._break: case types$1._continue: return this.parseBreakContinueStatement(node, starttype.keyword)
  26494. case types$1._debugger: return this.parseDebuggerStatement(node)
  26495. case types$1._do: return this.parseDoStatement(node)
  26496. case types$1._for: return this.parseForStatement(node)
  26497. case types$1._function:
  26498. // Function as sole body of either an if statement or a labeled statement
  26499. // works, but not when it is part of a labeled statement that is the sole
  26500. // body of an if statement.
  26501. if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); }
  26502. return this.parseFunctionStatement(node, false, !context)
  26503. case types$1._class:
  26504. if (context) { this.unexpected(); }
  26505. return this.parseClass(node, true)
  26506. case types$1._if: return this.parseIfStatement(node)
  26507. case types$1._return: return this.parseReturnStatement(node)
  26508. case types$1._switch: return this.parseSwitchStatement(node)
  26509. case types$1._throw: return this.parseThrowStatement(node)
  26510. case types$1._try: return this.parseTryStatement(node)
  26511. case types$1._const: case types$1._var:
  26512. kind = kind || this.value;
  26513. if (context && kind !== "var") { this.unexpected(); }
  26514. return this.parseVarStatement(node, kind)
  26515. case types$1._while: return this.parseWhileStatement(node)
  26516. case types$1._with: return this.parseWithStatement(node)
  26517. case types$1.braceL: return this.parseBlock(true, node)
  26518. case types$1.semi: return this.parseEmptyStatement(node)
  26519. case types$1._export:
  26520. case types$1._import:
  26521. if (this.options.ecmaVersion > 10 && starttype === types$1._import) {
  26522. skipWhiteSpace.lastIndex = this.pos;
  26523. var skip = skipWhiteSpace.exec(this.input);
  26524. var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
  26525. if (nextCh === 40 || nextCh === 46) // '(' or '.'
  26526. { return this.parseExpressionStatement(node, this.parseExpression()) }
  26527. }
  26528. if (!this.options.allowImportExportEverywhere) {
  26529. if (!topLevel)
  26530. { this.raise(this.start, "'import' and 'export' may only appear at the top level"); }
  26531. if (!this.inModule)
  26532. { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); }
  26533. }
  26534. return starttype === types$1._import ? this.parseImport(node) : this.parseExport(node, exports)
  26535. // If the statement does not start with a statement keyword or a
  26536. // brace, it's an ExpressionStatement or LabeledStatement. We
  26537. // simply start parsing an expression, and afterwards, if the
  26538. // next token is a colon and the expression was a simple
  26539. // Identifier node, we switch to interpreting it as a label.
  26540. default:
  26541. if (this.isAsyncFunction()) {
  26542. if (context) { this.unexpected(); }
  26543. this.next();
  26544. return this.parseFunctionStatement(node, true, !context)
  26545. }
  26546. var maybeName = this.value, expr = this.parseExpression();
  26547. if (starttype === types$1.name && expr.type === "Identifier" && this.eat(types$1.colon))
  26548. { return this.parseLabeledStatement(node, maybeName, expr, context) }
  26549. else { return this.parseExpressionStatement(node, expr) }
  26550. }
  26551. };
  26552. pp$8.parseBreakContinueStatement = function(node, keyword) {
  26553. var isBreak = keyword === "break";
  26554. this.next();
  26555. if (this.eat(types$1.semi) || this.insertSemicolon()) { node.label = null; }
  26556. else if (this.type !== types$1.name) { this.unexpected(); }
  26557. else {
  26558. node.label = this.parseIdent();
  26559. this.semicolon();
  26560. }
  26561. // Verify that there is an actual destination to break or
  26562. // continue to.
  26563. var i = 0;
  26564. for (; i < this.labels.length; ++i) {
  26565. var lab = this.labels[i];
  26566. if (node.label == null || lab.name === node.label.name) {
  26567. if (lab.kind != null && (isBreak || lab.kind === "loop")) { break }
  26568. if (node.label && isBreak) { break }
  26569. }
  26570. }
  26571. if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); }
  26572. return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement")
  26573. };
  26574. pp$8.parseDebuggerStatement = function(node) {
  26575. this.next();
  26576. this.semicolon();
  26577. return this.finishNode(node, "DebuggerStatement")
  26578. };
  26579. pp$8.parseDoStatement = function(node) {
  26580. this.next();
  26581. this.labels.push(loopLabel);
  26582. node.body = this.parseStatement("do");
  26583. this.labels.pop();
  26584. this.expect(types$1._while);
  26585. node.test = this.parseParenExpression();
  26586. if (this.options.ecmaVersion >= 6)
  26587. { this.eat(types$1.semi); }
  26588. else
  26589. { this.semicolon(); }
  26590. return this.finishNode(node, "DoWhileStatement")
  26591. };
  26592. // Disambiguating between a `for` and a `for`/`in` or `for`/`of`
  26593. // loop is non-trivial. Basically, we have to parse the init `var`
  26594. // statement or expression, disallowing the `in` operator (see
  26595. // the second parameter to `parseExpression`), and then check
  26596. // whether the next token is `in` or `of`. When there is no init
  26597. // part (semicolon immediately after the opening parenthesis), it
  26598. // is a regular `for` loop.
  26599. pp$8.parseForStatement = function(node) {
  26600. this.next();
  26601. var awaitAt = (this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await")) ? this.lastTokStart : -1;
  26602. this.labels.push(loopLabel);
  26603. this.enterScope(0);
  26604. this.expect(types$1.parenL);
  26605. if (this.type === types$1.semi) {
  26606. if (awaitAt > -1) { this.unexpected(awaitAt); }
  26607. return this.parseFor(node, null)
  26608. }
  26609. var isLet = this.isLet();
  26610. if (this.type === types$1._var || this.type === types$1._const || isLet) {
  26611. var init$1 = this.startNode(), kind = isLet ? "let" : this.value;
  26612. this.next();
  26613. this.parseVar(init$1, true, kind);
  26614. this.finishNode(init$1, "VariableDeclaration");
  26615. if ((this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) {
  26616. if (this.options.ecmaVersion >= 9) {
  26617. if (this.type === types$1._in) {
  26618. if (awaitAt > -1) { this.unexpected(awaitAt); }
  26619. } else { node.await = awaitAt > -1; }
  26620. }
  26621. return this.parseForIn(node, init$1)
  26622. }
  26623. if (awaitAt > -1) { this.unexpected(awaitAt); }
  26624. return this.parseFor(node, init$1)
  26625. }
  26626. var startsWithLet = this.isContextual("let"), isForOf = false;
  26627. var refDestructuringErrors = new DestructuringErrors;
  26628. var init = this.parseExpression(awaitAt > -1 ? "await" : true, refDestructuringErrors);
  26629. if (this.type === types$1._in || (isForOf = this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
  26630. if (this.options.ecmaVersion >= 9) {
  26631. if (this.type === types$1._in) {
  26632. if (awaitAt > -1) { this.unexpected(awaitAt); }
  26633. } else { node.await = awaitAt > -1; }
  26634. }
  26635. if (startsWithLet && isForOf) { this.raise(init.start, "The left-hand side of a for-of loop may not start with 'let'."); }
  26636. this.toAssignable(init, false, refDestructuringErrors);
  26637. this.checkLValPattern(init);
  26638. return this.parseForIn(node, init)
  26639. } else {
  26640. this.checkExpressionErrors(refDestructuringErrors, true);
  26641. }
  26642. if (awaitAt > -1) { this.unexpected(awaitAt); }
  26643. return this.parseFor(node, init)
  26644. };
  26645. pp$8.parseFunctionStatement = function(node, isAsync, declarationPosition) {
  26646. this.next();
  26647. return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync)
  26648. };
  26649. pp$8.parseIfStatement = function(node) {
  26650. this.next();
  26651. node.test = this.parseParenExpression();
  26652. // allow function declarations in branches, but only in non-strict mode
  26653. node.consequent = this.parseStatement("if");
  26654. node.alternate = this.eat(types$1._else) ? this.parseStatement("if") : null;
  26655. return this.finishNode(node, "IfStatement")
  26656. };
  26657. pp$8.parseReturnStatement = function(node) {
  26658. if (!this.inFunction && !this.options.allowReturnOutsideFunction)
  26659. { this.raise(this.start, "'return' outside of function"); }
  26660. this.next();
  26661. // In `return` (and `break`/`continue`), the keywords with
  26662. // optional arguments, we eagerly look for a semicolon or the
  26663. // possibility to insert one.
  26664. if (this.eat(types$1.semi) || this.insertSemicolon()) { node.argument = null; }
  26665. else { node.argument = this.parseExpression(); this.semicolon(); }
  26666. return this.finishNode(node, "ReturnStatement")
  26667. };
  26668. pp$8.parseSwitchStatement = function(node) {
  26669. this.next();
  26670. node.discriminant = this.parseParenExpression();
  26671. node.cases = [];
  26672. this.expect(types$1.braceL);
  26673. this.labels.push(switchLabel);
  26674. this.enterScope(0);
  26675. // Statements under must be grouped (by label) in SwitchCase
  26676. // nodes. `cur` is used to keep the node that we are currently
  26677. // adding statements to.
  26678. var cur;
  26679. for (var sawDefault = false; this.type !== types$1.braceR;) {
  26680. if (this.type === types$1._case || this.type === types$1._default) {
  26681. var isCase = this.type === types$1._case;
  26682. if (cur) { this.finishNode(cur, "SwitchCase"); }
  26683. node.cases.push(cur = this.startNode());
  26684. cur.consequent = [];
  26685. this.next();
  26686. if (isCase) {
  26687. cur.test = this.parseExpression();
  26688. } else {
  26689. if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); }
  26690. sawDefault = true;
  26691. cur.test = null;
  26692. }
  26693. this.expect(types$1.colon);
  26694. } else {
  26695. if (!cur) { this.unexpected(); }
  26696. cur.consequent.push(this.parseStatement(null));
  26697. }
  26698. }
  26699. this.exitScope();
  26700. if (cur) { this.finishNode(cur, "SwitchCase"); }
  26701. this.next(); // Closing brace
  26702. this.labels.pop();
  26703. return this.finishNode(node, "SwitchStatement")
  26704. };
  26705. pp$8.parseThrowStatement = function(node) {
  26706. this.next();
  26707. if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start)))
  26708. { this.raise(this.lastTokEnd, "Illegal newline after throw"); }
  26709. node.argument = this.parseExpression();
  26710. this.semicolon();
  26711. return this.finishNode(node, "ThrowStatement")
  26712. };
  26713. // Reused empty array added for node fields that are always empty.
  26714. var empty$1 = [];
  26715. pp$8.parseTryStatement = function(node) {
  26716. this.next();
  26717. node.block = this.parseBlock();
  26718. node.handler = null;
  26719. if (this.type === types$1._catch) {
  26720. var clause = this.startNode();
  26721. this.next();
  26722. if (this.eat(types$1.parenL)) {
  26723. clause.param = this.parseBindingAtom();
  26724. var simple = clause.param.type === "Identifier";
  26725. this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0);
  26726. this.checkLValPattern(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL);
  26727. this.expect(types$1.parenR);
  26728. } else {
  26729. if (this.options.ecmaVersion < 10) { this.unexpected(); }
  26730. clause.param = null;
  26731. this.enterScope(0);
  26732. }
  26733. clause.body = this.parseBlock(false);
  26734. this.exitScope();
  26735. node.handler = this.finishNode(clause, "CatchClause");
  26736. }
  26737. node.finalizer = this.eat(types$1._finally) ? this.parseBlock() : null;
  26738. if (!node.handler && !node.finalizer)
  26739. { this.raise(node.start, "Missing catch or finally clause"); }
  26740. return this.finishNode(node, "TryStatement")
  26741. };
  26742. pp$8.parseVarStatement = function(node, kind) {
  26743. this.next();
  26744. this.parseVar(node, false, kind);
  26745. this.semicolon();
  26746. return this.finishNode(node, "VariableDeclaration")
  26747. };
  26748. pp$8.parseWhileStatement = function(node) {
  26749. this.next();
  26750. node.test = this.parseParenExpression();
  26751. this.labels.push(loopLabel);
  26752. node.body = this.parseStatement("while");
  26753. this.labels.pop();
  26754. return this.finishNode(node, "WhileStatement")
  26755. };
  26756. pp$8.parseWithStatement = function(node) {
  26757. if (this.strict) { this.raise(this.start, "'with' in strict mode"); }
  26758. this.next();
  26759. node.object = this.parseParenExpression();
  26760. node.body = this.parseStatement("with");
  26761. return this.finishNode(node, "WithStatement")
  26762. };
  26763. pp$8.parseEmptyStatement = function(node) {
  26764. this.next();
  26765. return this.finishNode(node, "EmptyStatement")
  26766. };
  26767. pp$8.parseLabeledStatement = function(node, maybeName, expr, context) {
  26768. for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1)
  26769. {
  26770. var label = list[i$1];
  26771. if (label.name === maybeName)
  26772. { this.raise(expr.start, "Label '" + maybeName + "' is already declared");
  26773. } }
  26774. var kind = this.type.isLoop ? "loop" : this.type === types$1._switch ? "switch" : null;
  26775. for (var i = this.labels.length - 1; i >= 0; i--) {
  26776. var label$1 = this.labels[i];
  26777. if (label$1.statementStart === node.start) {
  26778. // Update information about previous labels on this node
  26779. label$1.statementStart = this.start;
  26780. label$1.kind = kind;
  26781. } else { break }
  26782. }
  26783. this.labels.push({name: maybeName, kind: kind, statementStart: this.start});
  26784. node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
  26785. this.labels.pop();
  26786. node.label = expr;
  26787. return this.finishNode(node, "LabeledStatement")
  26788. };
  26789. pp$8.parseExpressionStatement = function(node, expr) {
  26790. node.expression = expr;
  26791. this.semicolon();
  26792. return this.finishNode(node, "ExpressionStatement")
  26793. };
  26794. // Parse a semicolon-enclosed block of statements, handling `"use
  26795. // strict"` declarations when `allowStrict` is true (used for
  26796. // function bodies).
  26797. pp$8.parseBlock = function(createNewLexicalScope, node, exitStrict) {
  26798. if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true;
  26799. if ( node === void 0 ) node = this.startNode();
  26800. node.body = [];
  26801. this.expect(types$1.braceL);
  26802. if (createNewLexicalScope) { this.enterScope(0); }
  26803. while (this.type !== types$1.braceR) {
  26804. var stmt = this.parseStatement(null);
  26805. node.body.push(stmt);
  26806. }
  26807. if (exitStrict) { this.strict = false; }
  26808. this.next();
  26809. if (createNewLexicalScope) { this.exitScope(); }
  26810. return this.finishNode(node, "BlockStatement")
  26811. };
  26812. // Parse a regular `for` loop. The disambiguation code in
  26813. // `parseStatement` will already have parsed the init statement or
  26814. // expression.
  26815. pp$8.parseFor = function(node, init) {
  26816. node.init = init;
  26817. this.expect(types$1.semi);
  26818. node.test = this.type === types$1.semi ? null : this.parseExpression();
  26819. this.expect(types$1.semi);
  26820. node.update = this.type === types$1.parenR ? null : this.parseExpression();
  26821. this.expect(types$1.parenR);
  26822. node.body = this.parseStatement("for");
  26823. this.exitScope();
  26824. this.labels.pop();
  26825. return this.finishNode(node, "ForStatement")
  26826. };
  26827. // Parse a `for`/`in` and `for`/`of` loop, which are almost
  26828. // same from parser's perspective.
  26829. pp$8.parseForIn = function(node, init) {
  26830. var isForIn = this.type === types$1._in;
  26831. this.next();
  26832. if (
  26833. init.type === "VariableDeclaration" &&
  26834. init.declarations[0].init != null &&
  26835. (
  26836. !isForIn ||
  26837. this.options.ecmaVersion < 8 ||
  26838. this.strict ||
  26839. init.kind !== "var" ||
  26840. init.declarations[0].id.type !== "Identifier"
  26841. )
  26842. ) {
  26843. this.raise(
  26844. init.start,
  26845. ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer")
  26846. );
  26847. }
  26848. node.left = init;
  26849. node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
  26850. this.expect(types$1.parenR);
  26851. node.body = this.parseStatement("for");
  26852. this.exitScope();
  26853. this.labels.pop();
  26854. return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement")
  26855. };
  26856. // Parse a list of variable declarations.
  26857. pp$8.parseVar = function(node, isFor, kind) {
  26858. node.declarations = [];
  26859. node.kind = kind;
  26860. for (;;) {
  26861. var decl = this.startNode();
  26862. this.parseVarId(decl, kind);
  26863. if (this.eat(types$1.eq)) {
  26864. decl.init = this.parseMaybeAssign(isFor);
  26865. } else if (kind === "const" && !(this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) {
  26866. this.unexpected();
  26867. } else if (decl.id.type !== "Identifier" && !(isFor && (this.type === types$1._in || this.isContextual("of")))) {
  26868. this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
  26869. } else {
  26870. decl.init = null;
  26871. }
  26872. node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
  26873. if (!this.eat(types$1.comma)) { break }
  26874. }
  26875. return node
  26876. };
  26877. pp$8.parseVarId = function(decl, kind) {
  26878. decl.id = this.parseBindingAtom();
  26879. this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false);
  26880. };
  26881. var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4;
  26882. // Parse a function declaration or literal (depending on the
  26883. // `statement & FUNC_STATEMENT`).
  26884. // Remove `allowExpressionBody` for 7.0.0, as it is only called with false
  26885. pp$8.parseFunction = function(node, statement, allowExpressionBody, isAsync, forInit) {
  26886. this.initFunction(node);
  26887. if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) {
  26888. if (this.type === types$1.star && (statement & FUNC_HANGING_STATEMENT))
  26889. { this.unexpected(); }
  26890. node.generator = this.eat(types$1.star);
  26891. }
  26892. if (this.options.ecmaVersion >= 8)
  26893. { node.async = !!isAsync; }
  26894. if (statement & FUNC_STATEMENT) {
  26895. node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types$1.name ? null : this.parseIdent();
  26896. if (node.id && !(statement & FUNC_HANGING_STATEMENT))
  26897. // If it is a regular function declaration in sloppy mode, then it is
  26898. // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding
  26899. // mode depends on properties of the current scope (see
  26900. // treatFunctionsAsVar).
  26901. { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); }
  26902. }
  26903. var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  26904. this.yieldPos = 0;
  26905. this.awaitPos = 0;
  26906. this.awaitIdentPos = 0;
  26907. this.enterScope(functionFlags(node.async, node.generator));
  26908. if (!(statement & FUNC_STATEMENT))
  26909. { node.id = this.type === types$1.name ? this.parseIdent() : null; }
  26910. this.parseFunctionParams(node);
  26911. this.parseFunctionBody(node, allowExpressionBody, false, forInit);
  26912. this.yieldPos = oldYieldPos;
  26913. this.awaitPos = oldAwaitPos;
  26914. this.awaitIdentPos = oldAwaitIdentPos;
  26915. return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression")
  26916. };
  26917. pp$8.parseFunctionParams = function(node) {
  26918. this.expect(types$1.parenL);
  26919. node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8);
  26920. this.checkYieldAwaitInDefaultParams();
  26921. };
  26922. // Parse a class declaration or literal (depending on the
  26923. // `isStatement` parameter).
  26924. pp$8.parseClass = function(node, isStatement) {
  26925. this.next();
  26926. // ecma-262 14.6 Class Definitions
  26927. // A class definition is always strict mode code.
  26928. var oldStrict = this.strict;
  26929. this.strict = true;
  26930. this.parseClassId(node, isStatement);
  26931. this.parseClassSuper(node);
  26932. var privateNameMap = this.enterClassBody();
  26933. var classBody = this.startNode();
  26934. var hadConstructor = false;
  26935. classBody.body = [];
  26936. this.expect(types$1.braceL);
  26937. while (this.type !== types$1.braceR) {
  26938. var element = this.parseClassElement(node.superClass !== null);
  26939. if (element) {
  26940. classBody.body.push(element);
  26941. if (element.type === "MethodDefinition" && element.kind === "constructor") {
  26942. if (hadConstructor) { this.raise(element.start, "Duplicate constructor in the same class"); }
  26943. hadConstructor = true;
  26944. } else if (element.key && element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) {
  26945. this.raiseRecoverable(element.key.start, ("Identifier '#" + (element.key.name) + "' has already been declared"));
  26946. }
  26947. }
  26948. }
  26949. this.strict = oldStrict;
  26950. this.next();
  26951. node.body = this.finishNode(classBody, "ClassBody");
  26952. this.exitClassBody();
  26953. return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression")
  26954. };
  26955. pp$8.parseClassElement = function(constructorAllowsSuper) {
  26956. if (this.eat(types$1.semi)) { return null }
  26957. var ecmaVersion = this.options.ecmaVersion;
  26958. var node = this.startNode();
  26959. var keyName = "";
  26960. var isGenerator = false;
  26961. var isAsync = false;
  26962. var kind = "method";
  26963. var isStatic = false;
  26964. if (this.eatContextual("static")) {
  26965. // Parse static init block
  26966. if (ecmaVersion >= 13 && this.eat(types$1.braceL)) {
  26967. this.parseClassStaticBlock(node);
  26968. return node
  26969. }
  26970. if (this.isClassElementNameStart() || this.type === types$1.star) {
  26971. isStatic = true;
  26972. } else {
  26973. keyName = "static";
  26974. }
  26975. }
  26976. node.static = isStatic;
  26977. if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) {
  26978. if ((this.isClassElementNameStart() || this.type === types$1.star) && !this.canInsertSemicolon()) {
  26979. isAsync = true;
  26980. } else {
  26981. keyName = "async";
  26982. }
  26983. }
  26984. if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(types$1.star)) {
  26985. isGenerator = true;
  26986. }
  26987. if (!keyName && !isAsync && !isGenerator) {
  26988. var lastValue = this.value;
  26989. if (this.eatContextual("get") || this.eatContextual("set")) {
  26990. if (this.isClassElementNameStart()) {
  26991. kind = lastValue;
  26992. } else {
  26993. keyName = lastValue;
  26994. }
  26995. }
  26996. }
  26997. // Parse element name
  26998. if (keyName) {
  26999. // 'async', 'get', 'set', or 'static' were not a keyword contextually.
  27000. // The last token is any of those. Make it the element name.
  27001. node.computed = false;
  27002. node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc);
  27003. node.key.name = keyName;
  27004. this.finishNode(node.key, "Identifier");
  27005. } else {
  27006. this.parseClassElementName(node);
  27007. }
  27008. // Parse element value
  27009. if (ecmaVersion < 13 || this.type === types$1.parenL || kind !== "method" || isGenerator || isAsync) {
  27010. var isConstructor = !node.static && checkKeyName(node, "constructor");
  27011. var allowsDirectSuper = isConstructor && constructorAllowsSuper;
  27012. // Couldn't move this check into the 'parseClassMethod' method for backward compatibility.
  27013. if (isConstructor && kind !== "method") { this.raise(node.key.start, "Constructor can't have get/set modifier"); }
  27014. node.kind = isConstructor ? "constructor" : kind;
  27015. this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper);
  27016. } else {
  27017. this.parseClassField(node);
  27018. }
  27019. return node
  27020. };
  27021. pp$8.isClassElementNameStart = function() {
  27022. return (
  27023. this.type === types$1.name ||
  27024. this.type === types$1.privateId ||
  27025. this.type === types$1.num ||
  27026. this.type === types$1.string ||
  27027. this.type === types$1.bracketL ||
  27028. this.type.keyword
  27029. )
  27030. };
  27031. pp$8.parseClassElementName = function(element) {
  27032. if (this.type === types$1.privateId) {
  27033. if (this.value === "constructor") {
  27034. this.raise(this.start, "Classes can't have an element named '#constructor'");
  27035. }
  27036. element.computed = false;
  27037. element.key = this.parsePrivateIdent();
  27038. } else {
  27039. this.parsePropertyName(element);
  27040. }
  27041. };
  27042. pp$8.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) {
  27043. // Check key and flags
  27044. var key = method.key;
  27045. if (method.kind === "constructor") {
  27046. if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); }
  27047. if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); }
  27048. } else if (method.static && checkKeyName(method, "prototype")) {
  27049. this.raise(key.start, "Classes may not have a static property named prototype");
  27050. }
  27051. // Parse value
  27052. var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper);
  27053. // Check value
  27054. if (method.kind === "get" && value.params.length !== 0)
  27055. { this.raiseRecoverable(value.start, "getter should have no params"); }
  27056. if (method.kind === "set" && value.params.length !== 1)
  27057. { this.raiseRecoverable(value.start, "setter should have exactly one param"); }
  27058. if (method.kind === "set" && value.params[0].type === "RestElement")
  27059. { this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params"); }
  27060. return this.finishNode(method, "MethodDefinition")
  27061. };
  27062. pp$8.parseClassField = function(field) {
  27063. if (checkKeyName(field, "constructor")) {
  27064. this.raise(field.key.start, "Classes can't have a field named 'constructor'");
  27065. } else if (field.static && checkKeyName(field, "prototype")) {
  27066. this.raise(field.key.start, "Classes can't have a static field named 'prototype'");
  27067. }
  27068. if (this.eat(types$1.eq)) {
  27069. // To raise SyntaxError if 'arguments' exists in the initializer.
  27070. var scope = this.currentThisScope();
  27071. var inClassFieldInit = scope.inClassFieldInit;
  27072. scope.inClassFieldInit = true;
  27073. field.value = this.parseMaybeAssign();
  27074. scope.inClassFieldInit = inClassFieldInit;
  27075. } else {
  27076. field.value = null;
  27077. }
  27078. this.semicolon();
  27079. return this.finishNode(field, "PropertyDefinition")
  27080. };
  27081. pp$8.parseClassStaticBlock = function(node) {
  27082. node.body = [];
  27083. var oldLabels = this.labels;
  27084. this.labels = [];
  27085. this.enterScope(SCOPE_CLASS_STATIC_BLOCK | SCOPE_SUPER);
  27086. while (this.type !== types$1.braceR) {
  27087. var stmt = this.parseStatement(null);
  27088. node.body.push(stmt);
  27089. }
  27090. this.next();
  27091. this.exitScope();
  27092. this.labels = oldLabels;
  27093. return this.finishNode(node, "StaticBlock")
  27094. };
  27095. pp$8.parseClassId = function(node, isStatement) {
  27096. if (this.type === types$1.name) {
  27097. node.id = this.parseIdent();
  27098. if (isStatement)
  27099. { this.checkLValSimple(node.id, BIND_LEXICAL, false); }
  27100. } else {
  27101. if (isStatement === true)
  27102. { this.unexpected(); }
  27103. node.id = null;
  27104. }
  27105. };
  27106. pp$8.parseClassSuper = function(node) {
  27107. node.superClass = this.eat(types$1._extends) ? this.parseExprSubscripts(false) : null;
  27108. };
  27109. pp$8.enterClassBody = function() {
  27110. var element = {declared: Object.create(null), used: []};
  27111. this.privateNameStack.push(element);
  27112. return element.declared
  27113. };
  27114. pp$8.exitClassBody = function() {
  27115. var ref = this.privateNameStack.pop();
  27116. var declared = ref.declared;
  27117. var used = ref.used;
  27118. var len = this.privateNameStack.length;
  27119. var parent = len === 0 ? null : this.privateNameStack[len - 1];
  27120. for (var i = 0; i < used.length; ++i) {
  27121. var id = used[i];
  27122. if (!hasOwn(declared, id.name)) {
  27123. if (parent) {
  27124. parent.used.push(id);
  27125. } else {
  27126. this.raiseRecoverable(id.start, ("Private field '#" + (id.name) + "' must be declared in an enclosing class"));
  27127. }
  27128. }
  27129. }
  27130. };
  27131. function isPrivateNameConflicted(privateNameMap, element) {
  27132. var name = element.key.name;
  27133. var curr = privateNameMap[name];
  27134. var next = "true";
  27135. if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) {
  27136. next = (element.static ? "s" : "i") + element.kind;
  27137. }
  27138. // `class { get #a(){}; static set #a(_){} }` is also conflict.
  27139. if (
  27140. curr === "iget" && next === "iset" ||
  27141. curr === "iset" && next === "iget" ||
  27142. curr === "sget" && next === "sset" ||
  27143. curr === "sset" && next === "sget"
  27144. ) {
  27145. privateNameMap[name] = "true";
  27146. return false
  27147. } else if (!curr) {
  27148. privateNameMap[name] = next;
  27149. return false
  27150. } else {
  27151. return true
  27152. }
  27153. }
  27154. function checkKeyName(node, name) {
  27155. var computed = node.computed;
  27156. var key = node.key;
  27157. return !computed && (
  27158. key.type === "Identifier" && key.name === name ||
  27159. key.type === "Literal" && key.value === name
  27160. )
  27161. }
  27162. // Parses module export declaration.
  27163. pp$8.parseExport = function(node, exports) {
  27164. this.next();
  27165. // export * from '...'
  27166. if (this.eat(types$1.star)) {
  27167. if (this.options.ecmaVersion >= 11) {
  27168. if (this.eatContextual("as")) {
  27169. node.exported = this.parseModuleExportName();
  27170. this.checkExport(exports, node.exported, this.lastTokStart);
  27171. } else {
  27172. node.exported = null;
  27173. }
  27174. }
  27175. this.expectContextual("from");
  27176. if (this.type !== types$1.string) { this.unexpected(); }
  27177. node.source = this.parseExprAtom();
  27178. this.semicolon();
  27179. return this.finishNode(node, "ExportAllDeclaration")
  27180. }
  27181. if (this.eat(types$1._default)) { // export default ...
  27182. this.checkExport(exports, "default", this.lastTokStart);
  27183. var isAsync;
  27184. if (this.type === types$1._function || (isAsync = this.isAsyncFunction())) {
  27185. var fNode = this.startNode();
  27186. this.next();
  27187. if (isAsync) { this.next(); }
  27188. node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync);
  27189. } else if (this.type === types$1._class) {
  27190. var cNode = this.startNode();
  27191. node.declaration = this.parseClass(cNode, "nullableID");
  27192. } else {
  27193. node.declaration = this.parseMaybeAssign();
  27194. this.semicolon();
  27195. }
  27196. return this.finishNode(node, "ExportDefaultDeclaration")
  27197. }
  27198. // export var|const|let|function|class ...
  27199. if (this.shouldParseExportStatement()) {
  27200. node.declaration = this.parseStatement(null);
  27201. if (node.declaration.type === "VariableDeclaration")
  27202. { this.checkVariableExport(exports, node.declaration.declarations); }
  27203. else
  27204. { this.checkExport(exports, node.declaration.id, node.declaration.id.start); }
  27205. node.specifiers = [];
  27206. node.source = null;
  27207. } else { // export { x, y as z } [from '...']
  27208. node.declaration = null;
  27209. node.specifiers = this.parseExportSpecifiers(exports);
  27210. if (this.eatContextual("from")) {
  27211. if (this.type !== types$1.string) { this.unexpected(); }
  27212. node.source = this.parseExprAtom();
  27213. } else {
  27214. for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
  27215. // check for keywords used as local names
  27216. var spec = list[i];
  27217. this.checkUnreserved(spec.local);
  27218. // check if export is defined
  27219. this.checkLocalExport(spec.local);
  27220. if (spec.local.type === "Literal") {
  27221. this.raise(spec.local.start, "A string literal cannot be used as an exported binding without `from`.");
  27222. }
  27223. }
  27224. node.source = null;
  27225. }
  27226. this.semicolon();
  27227. }
  27228. return this.finishNode(node, "ExportNamedDeclaration")
  27229. };
  27230. pp$8.checkExport = function(exports, name, pos) {
  27231. if (!exports) { return }
  27232. if (typeof name !== "string")
  27233. { name = name.type === "Identifier" ? name.name : name.value; }
  27234. if (hasOwn(exports, name))
  27235. { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); }
  27236. exports[name] = true;
  27237. };
  27238. pp$8.checkPatternExport = function(exports, pat) {
  27239. var type = pat.type;
  27240. if (type === "Identifier")
  27241. { this.checkExport(exports, pat, pat.start); }
  27242. else if (type === "ObjectPattern")
  27243. { for (var i = 0, list = pat.properties; i < list.length; i += 1)
  27244. {
  27245. var prop = list[i];
  27246. this.checkPatternExport(exports, prop);
  27247. } }
  27248. else if (type === "ArrayPattern")
  27249. { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) {
  27250. var elt = list$1[i$1];
  27251. if (elt) { this.checkPatternExport(exports, elt); }
  27252. } }
  27253. else if (type === "Property")
  27254. { this.checkPatternExport(exports, pat.value); }
  27255. else if (type === "AssignmentPattern")
  27256. { this.checkPatternExport(exports, pat.left); }
  27257. else if (type === "RestElement")
  27258. { this.checkPatternExport(exports, pat.argument); }
  27259. else if (type === "ParenthesizedExpression")
  27260. { this.checkPatternExport(exports, pat.expression); }
  27261. };
  27262. pp$8.checkVariableExport = function(exports, decls) {
  27263. if (!exports) { return }
  27264. for (var i = 0, list = decls; i < list.length; i += 1)
  27265. {
  27266. var decl = list[i];
  27267. this.checkPatternExport(exports, decl.id);
  27268. }
  27269. };
  27270. pp$8.shouldParseExportStatement = function() {
  27271. return this.type.keyword === "var" ||
  27272. this.type.keyword === "const" ||
  27273. this.type.keyword === "class" ||
  27274. this.type.keyword === "function" ||
  27275. this.isLet() ||
  27276. this.isAsyncFunction()
  27277. };
  27278. // Parses a comma-separated list of module exports.
  27279. pp$8.parseExportSpecifiers = function(exports) {
  27280. var nodes = [], first = true;
  27281. // export { x, y as z } [from '...']
  27282. this.expect(types$1.braceL);
  27283. while (!this.eat(types$1.braceR)) {
  27284. if (!first) {
  27285. this.expect(types$1.comma);
  27286. if (this.afterTrailingComma(types$1.braceR)) { break }
  27287. } else { first = false; }
  27288. var node = this.startNode();
  27289. node.local = this.parseModuleExportName();
  27290. node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local;
  27291. this.checkExport(
  27292. exports,
  27293. node.exported,
  27294. node.exported.start
  27295. );
  27296. nodes.push(this.finishNode(node, "ExportSpecifier"));
  27297. }
  27298. return nodes
  27299. };
  27300. // Parses import declaration.
  27301. pp$8.parseImport = function(node) {
  27302. this.next();
  27303. // import '...'
  27304. if (this.type === types$1.string) {
  27305. node.specifiers = empty$1;
  27306. node.source = this.parseExprAtom();
  27307. } else {
  27308. node.specifiers = this.parseImportSpecifiers();
  27309. this.expectContextual("from");
  27310. node.source = this.type === types$1.string ? this.parseExprAtom() : this.unexpected();
  27311. }
  27312. this.semicolon();
  27313. return this.finishNode(node, "ImportDeclaration")
  27314. };
  27315. // Parses a comma-separated list of module imports.
  27316. pp$8.parseImportSpecifiers = function() {
  27317. var nodes = [], first = true;
  27318. if (this.type === types$1.name) {
  27319. // import defaultObj, { x, y as z } from '...'
  27320. var node = this.startNode();
  27321. node.local = this.parseIdent();
  27322. this.checkLValSimple(node.local, BIND_LEXICAL);
  27323. nodes.push(this.finishNode(node, "ImportDefaultSpecifier"));
  27324. if (!this.eat(types$1.comma)) { return nodes }
  27325. }
  27326. if (this.type === types$1.star) {
  27327. var node$1 = this.startNode();
  27328. this.next();
  27329. this.expectContextual("as");
  27330. node$1.local = this.parseIdent();
  27331. this.checkLValSimple(node$1.local, BIND_LEXICAL);
  27332. nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier"));
  27333. return nodes
  27334. }
  27335. this.expect(types$1.braceL);
  27336. while (!this.eat(types$1.braceR)) {
  27337. if (!first) {
  27338. this.expect(types$1.comma);
  27339. if (this.afterTrailingComma(types$1.braceR)) { break }
  27340. } else { first = false; }
  27341. var node$2 = this.startNode();
  27342. node$2.imported = this.parseModuleExportName();
  27343. if (this.eatContextual("as")) {
  27344. node$2.local = this.parseIdent();
  27345. } else {
  27346. this.checkUnreserved(node$2.imported);
  27347. node$2.local = node$2.imported;
  27348. }
  27349. this.checkLValSimple(node$2.local, BIND_LEXICAL);
  27350. nodes.push(this.finishNode(node$2, "ImportSpecifier"));
  27351. }
  27352. return nodes
  27353. };
  27354. pp$8.parseModuleExportName = function() {
  27355. if (this.options.ecmaVersion >= 13 && this.type === types$1.string) {
  27356. var stringLiteral = this.parseLiteral(this.value);
  27357. if (loneSurrogate.test(stringLiteral.value)) {
  27358. this.raise(stringLiteral.start, "An export name cannot include a lone surrogate.");
  27359. }
  27360. return stringLiteral
  27361. }
  27362. return this.parseIdent(true)
  27363. };
  27364. // Set `ExpressionStatement#directive` property for directive prologues.
  27365. pp$8.adaptDirectivePrologue = function(statements) {
  27366. for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) {
  27367. statements[i].directive = statements[i].expression.raw.slice(1, -1);
  27368. }
  27369. };
  27370. pp$8.isDirectiveCandidate = function(statement) {
  27371. return (
  27372. statement.type === "ExpressionStatement" &&
  27373. statement.expression.type === "Literal" &&
  27374. typeof statement.expression.value === "string" &&
  27375. // Reject parenthesized strings.
  27376. (this.input[statement.start] === "\"" || this.input[statement.start] === "'")
  27377. )
  27378. };
  27379. var pp$7 = Parser.prototype;
  27380. // Convert existing expression atom to assignable pattern
  27381. // if possible.
  27382. pp$7.toAssignable = function(node, isBinding, refDestructuringErrors) {
  27383. if (this.options.ecmaVersion >= 6 && node) {
  27384. switch (node.type) {
  27385. case "Identifier":
  27386. if (this.inAsync && node.name === "await")
  27387. { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); }
  27388. break
  27389. case "ObjectPattern":
  27390. case "ArrayPattern":
  27391. case "AssignmentPattern":
  27392. case "RestElement":
  27393. break
  27394. case "ObjectExpression":
  27395. node.type = "ObjectPattern";
  27396. if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  27397. for (var i = 0, list = node.properties; i < list.length; i += 1) {
  27398. var prop = list[i];
  27399. this.toAssignable(prop, isBinding);
  27400. // Early error:
  27401. // AssignmentRestProperty[Yield, Await] :
  27402. // `...` DestructuringAssignmentTarget[Yield, Await]
  27403. //
  27404. // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|.
  27405. if (
  27406. prop.type === "RestElement" &&
  27407. (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")
  27408. ) {
  27409. this.raise(prop.argument.start, "Unexpected token");
  27410. }
  27411. }
  27412. break
  27413. case "Property":
  27414. // AssignmentProperty has type === "Property"
  27415. if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); }
  27416. this.toAssignable(node.value, isBinding);
  27417. break
  27418. case "ArrayExpression":
  27419. node.type = "ArrayPattern";
  27420. if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  27421. this.toAssignableList(node.elements, isBinding);
  27422. break
  27423. case "SpreadElement":
  27424. node.type = "RestElement";
  27425. this.toAssignable(node.argument, isBinding);
  27426. if (node.argument.type === "AssignmentPattern")
  27427. { this.raise(node.argument.start, "Rest elements cannot have a default value"); }
  27428. break
  27429. case "AssignmentExpression":
  27430. if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); }
  27431. node.type = "AssignmentPattern";
  27432. delete node.operator;
  27433. this.toAssignable(node.left, isBinding);
  27434. break
  27435. case "ParenthesizedExpression":
  27436. this.toAssignable(node.expression, isBinding, refDestructuringErrors);
  27437. break
  27438. case "ChainExpression":
  27439. this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side");
  27440. break
  27441. case "MemberExpression":
  27442. if (!isBinding) { break }
  27443. default:
  27444. this.raise(node.start, "Assigning to rvalue");
  27445. }
  27446. } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  27447. return node
  27448. };
  27449. // Convert list of expression atoms to binding list.
  27450. pp$7.toAssignableList = function(exprList, isBinding) {
  27451. var end = exprList.length;
  27452. for (var i = 0; i < end; i++) {
  27453. var elt = exprList[i];
  27454. if (elt) { this.toAssignable(elt, isBinding); }
  27455. }
  27456. if (end) {
  27457. var last = exprList[end - 1];
  27458. if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier")
  27459. { this.unexpected(last.argument.start); }
  27460. }
  27461. return exprList
  27462. };
  27463. // Parses spread element.
  27464. pp$7.parseSpread = function(refDestructuringErrors) {
  27465. var node = this.startNode();
  27466. this.next();
  27467. node.argument = this.parseMaybeAssign(false, refDestructuringErrors);
  27468. return this.finishNode(node, "SpreadElement")
  27469. };
  27470. pp$7.parseRestBinding = function() {
  27471. var node = this.startNode();
  27472. this.next();
  27473. // RestElement inside of a function parameter must be an identifier
  27474. if (this.options.ecmaVersion === 6 && this.type !== types$1.name)
  27475. { this.unexpected(); }
  27476. node.argument = this.parseBindingAtom();
  27477. return this.finishNode(node, "RestElement")
  27478. };
  27479. // Parses lvalue (assignable) atom.
  27480. pp$7.parseBindingAtom = function() {
  27481. if (this.options.ecmaVersion >= 6) {
  27482. switch (this.type) {
  27483. case types$1.bracketL:
  27484. var node = this.startNode();
  27485. this.next();
  27486. node.elements = this.parseBindingList(types$1.bracketR, true, true);
  27487. return this.finishNode(node, "ArrayPattern")
  27488. case types$1.braceL:
  27489. return this.parseObj(true)
  27490. }
  27491. }
  27492. return this.parseIdent()
  27493. };
  27494. pp$7.parseBindingList = function(close, allowEmpty, allowTrailingComma) {
  27495. var elts = [], first = true;
  27496. while (!this.eat(close)) {
  27497. if (first) { first = false; }
  27498. else { this.expect(types$1.comma); }
  27499. if (allowEmpty && this.type === types$1.comma) {
  27500. elts.push(null);
  27501. } else if (allowTrailingComma && this.afterTrailingComma(close)) {
  27502. break
  27503. } else if (this.type === types$1.ellipsis) {
  27504. var rest = this.parseRestBinding();
  27505. this.parseBindingListItem(rest);
  27506. elts.push(rest);
  27507. if (this.type === types$1.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
  27508. this.expect(close);
  27509. break
  27510. } else {
  27511. var elem = this.parseMaybeDefault(this.start, this.startLoc);
  27512. this.parseBindingListItem(elem);
  27513. elts.push(elem);
  27514. }
  27515. }
  27516. return elts
  27517. };
  27518. pp$7.parseBindingListItem = function(param) {
  27519. return param
  27520. };
  27521. // Parses assignment pattern around given atom if possible.
  27522. pp$7.parseMaybeDefault = function(startPos, startLoc, left) {
  27523. left = left || this.parseBindingAtom();
  27524. if (this.options.ecmaVersion < 6 || !this.eat(types$1.eq)) { return left }
  27525. var node = this.startNodeAt(startPos, startLoc);
  27526. node.left = left;
  27527. node.right = this.parseMaybeAssign();
  27528. return this.finishNode(node, "AssignmentPattern")
  27529. };
  27530. // The following three functions all verify that a node is an lvalue —
  27531. // something that can be bound, or assigned to. In order to do so, they perform
  27532. // a variety of checks:
  27533. //
  27534. // - Check that none of the bound/assigned-to identifiers are reserved words.
  27535. // - Record name declarations for bindings in the appropriate scope.
  27536. // - Check duplicate argument names, if checkClashes is set.
  27537. //
  27538. // If a complex binding pattern is encountered (e.g., object and array
  27539. // destructuring), the entire pattern is recursively checked.
  27540. //
  27541. // There are three versions of checkLVal*() appropriate for different
  27542. // circumstances:
  27543. //
  27544. // - checkLValSimple() shall be used if the syntactic construct supports
  27545. // nothing other than identifiers and member expressions. Parenthesized
  27546. // expressions are also correctly handled. This is generally appropriate for
  27547. // constructs for which the spec says
  27548. //
  27549. // > It is a Syntax Error if AssignmentTargetType of [the production] is not
  27550. // > simple.
  27551. //
  27552. // It is also appropriate for checking if an identifier is valid and not
  27553. // defined elsewhere, like import declarations or function/class identifiers.
  27554. //
  27555. // Examples where this is used include:
  27556. // a += …;
  27557. // import a from '…';
  27558. // where a is the node to be checked.
  27559. //
  27560. // - checkLValPattern() shall be used if the syntactic construct supports
  27561. // anything checkLValSimple() supports, as well as object and array
  27562. // destructuring patterns. This is generally appropriate for constructs for
  27563. // which the spec says
  27564. //
  27565. // > It is a Syntax Error if [the production] is neither an ObjectLiteral nor
  27566. // > an ArrayLiteral and AssignmentTargetType of [the production] is not
  27567. // > simple.
  27568. //
  27569. // Examples where this is used include:
  27570. // (a = …);
  27571. // const a = …;
  27572. // try { … } catch (a) { … }
  27573. // where a is the node to be checked.
  27574. //
  27575. // - checkLValInnerPattern() shall be used if the syntactic construct supports
  27576. // anything checkLValPattern() supports, as well as default assignment
  27577. // patterns, rest elements, and other constructs that may appear within an
  27578. // object or array destructuring pattern.
  27579. //
  27580. // As a special case, function parameters also use checkLValInnerPattern(),
  27581. // as they also support defaults and rest constructs.
  27582. //
  27583. // These functions deliberately support both assignment and binding constructs,
  27584. // as the logic for both is exceedingly similar. If the node is the target of
  27585. // an assignment, then bindingType should be set to BIND_NONE. Otherwise, it
  27586. // should be set to the appropriate BIND_* constant, like BIND_VAR or
  27587. // BIND_LEXICAL.
  27588. //
  27589. // If the function is called with a non-BIND_NONE bindingType, then
  27590. // additionally a checkClashes object may be specified to allow checking for
  27591. // duplicate argument names. checkClashes is ignored if the provided construct
  27592. // is an assignment (i.e., bindingType is BIND_NONE).
  27593. pp$7.checkLValSimple = function(expr, bindingType, checkClashes) {
  27594. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  27595. var isBind = bindingType !== BIND_NONE;
  27596. switch (expr.type) {
  27597. case "Identifier":
  27598. if (this.strict && this.reservedWordsStrictBind.test(expr.name))
  27599. { this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); }
  27600. if (isBind) {
  27601. if (bindingType === BIND_LEXICAL && expr.name === "let")
  27602. { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); }
  27603. if (checkClashes) {
  27604. if (hasOwn(checkClashes, expr.name))
  27605. { this.raiseRecoverable(expr.start, "Argument name clash"); }
  27606. checkClashes[expr.name] = true;
  27607. }
  27608. if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); }
  27609. }
  27610. break
  27611. case "ChainExpression":
  27612. this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side");
  27613. break
  27614. case "MemberExpression":
  27615. if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); }
  27616. break
  27617. case "ParenthesizedExpression":
  27618. if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); }
  27619. return this.checkLValSimple(expr.expression, bindingType, checkClashes)
  27620. default:
  27621. this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue");
  27622. }
  27623. };
  27624. pp$7.checkLValPattern = function(expr, bindingType, checkClashes) {
  27625. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  27626. switch (expr.type) {
  27627. case "ObjectPattern":
  27628. for (var i = 0, list = expr.properties; i < list.length; i += 1) {
  27629. var prop = list[i];
  27630. this.checkLValInnerPattern(prop, bindingType, checkClashes);
  27631. }
  27632. break
  27633. case "ArrayPattern":
  27634. for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) {
  27635. var elem = list$1[i$1];
  27636. if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); }
  27637. }
  27638. break
  27639. default:
  27640. this.checkLValSimple(expr, bindingType, checkClashes);
  27641. }
  27642. };
  27643. pp$7.checkLValInnerPattern = function(expr, bindingType, checkClashes) {
  27644. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  27645. switch (expr.type) {
  27646. case "Property":
  27647. // AssignmentProperty has type === "Property"
  27648. this.checkLValInnerPattern(expr.value, bindingType, checkClashes);
  27649. break
  27650. case "AssignmentPattern":
  27651. this.checkLValPattern(expr.left, bindingType, checkClashes);
  27652. break
  27653. case "RestElement":
  27654. this.checkLValPattern(expr.argument, bindingType, checkClashes);
  27655. break
  27656. default:
  27657. this.checkLValPattern(expr, bindingType, checkClashes);
  27658. }
  27659. };
  27660. // The algorithm used to determine whether a regexp can appear at a
  27661. var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) {
  27662. this.token = token;
  27663. this.isExpr = !!isExpr;
  27664. this.preserveSpace = !!preserveSpace;
  27665. this.override = override;
  27666. this.generator = !!generator;
  27667. };
  27668. var types = {
  27669. b_stat: new TokContext("{", false),
  27670. b_expr: new TokContext("{", true),
  27671. b_tmpl: new TokContext("${", false),
  27672. p_stat: new TokContext("(", false),
  27673. p_expr: new TokContext("(", true),
  27674. q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }),
  27675. f_stat: new TokContext("function", false),
  27676. f_expr: new TokContext("function", true),
  27677. f_expr_gen: new TokContext("function", true, false, null, true),
  27678. f_gen: new TokContext("function", false, false, null, true)
  27679. };
  27680. var pp$6 = Parser.prototype;
  27681. pp$6.initialContext = function() {
  27682. return [types.b_stat]
  27683. };
  27684. pp$6.curContext = function() {
  27685. return this.context[this.context.length - 1]
  27686. };
  27687. pp$6.braceIsBlock = function(prevType) {
  27688. var parent = this.curContext();
  27689. if (parent === types.f_expr || parent === types.f_stat)
  27690. { return true }
  27691. if (prevType === types$1.colon && (parent === types.b_stat || parent === types.b_expr))
  27692. { return !parent.isExpr }
  27693. // The check for `tt.name && exprAllowed` detects whether we are
  27694. // after a `yield` or `of` construct. See the `updateContext` for
  27695. // `tt.name`.
  27696. if (prevType === types$1._return || prevType === types$1.name && this.exprAllowed)
  27697. { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }
  27698. if (prevType === types$1._else || prevType === types$1.semi || prevType === types$1.eof || prevType === types$1.parenR || prevType === types$1.arrow)
  27699. { return true }
  27700. if (prevType === types$1.braceL)
  27701. { return parent === types.b_stat }
  27702. if (prevType === types$1._var || prevType === types$1._const || prevType === types$1.name)
  27703. { return false }
  27704. return !this.exprAllowed
  27705. };
  27706. pp$6.inGeneratorContext = function() {
  27707. for (var i = this.context.length - 1; i >= 1; i--) {
  27708. var context = this.context[i];
  27709. if (context.token === "function")
  27710. { return context.generator }
  27711. }
  27712. return false
  27713. };
  27714. pp$6.updateContext = function(prevType) {
  27715. var update, type = this.type;
  27716. if (type.keyword && prevType === types$1.dot)
  27717. { this.exprAllowed = false; }
  27718. else if (update = type.updateContext)
  27719. { update.call(this, prevType); }
  27720. else
  27721. { this.exprAllowed = type.beforeExpr; }
  27722. };
  27723. // Used to handle egde case when token context could not be inferred correctly in tokenize phase
  27724. pp$6.overrideContext = function(tokenCtx) {
  27725. if (this.curContext() !== tokenCtx) {
  27726. this.context[this.context.length - 1] = tokenCtx;
  27727. }
  27728. };
  27729. // Token-specific context update code
  27730. types$1.parenR.updateContext = types$1.braceR.updateContext = function() {
  27731. if (this.context.length === 1) {
  27732. this.exprAllowed = true;
  27733. return
  27734. }
  27735. var out = this.context.pop();
  27736. if (out === types.b_stat && this.curContext().token === "function") {
  27737. out = this.context.pop();
  27738. }
  27739. this.exprAllowed = !out.isExpr;
  27740. };
  27741. types$1.braceL.updateContext = function(prevType) {
  27742. this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr);
  27743. this.exprAllowed = true;
  27744. };
  27745. types$1.dollarBraceL.updateContext = function() {
  27746. this.context.push(types.b_tmpl);
  27747. this.exprAllowed = true;
  27748. };
  27749. types$1.parenL.updateContext = function(prevType) {
  27750. var statementParens = prevType === types$1._if || prevType === types$1._for || prevType === types$1._with || prevType === types$1._while;
  27751. this.context.push(statementParens ? types.p_stat : types.p_expr);
  27752. this.exprAllowed = true;
  27753. };
  27754. types$1.incDec.updateContext = function() {
  27755. // tokExprAllowed stays unchanged
  27756. };
  27757. types$1._function.updateContext = types$1._class.updateContext = function(prevType) {
  27758. if (prevType.beforeExpr && prevType !== types$1._else &&
  27759. !(prevType === types$1.semi && this.curContext() !== types.p_stat) &&
  27760. !(prevType === types$1._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) &&
  27761. !((prevType === types$1.colon || prevType === types$1.braceL) && this.curContext() === types.b_stat))
  27762. { this.context.push(types.f_expr); }
  27763. else
  27764. { this.context.push(types.f_stat); }
  27765. this.exprAllowed = false;
  27766. };
  27767. types$1.backQuote.updateContext = function() {
  27768. if (this.curContext() === types.q_tmpl)
  27769. { this.context.pop(); }
  27770. else
  27771. { this.context.push(types.q_tmpl); }
  27772. this.exprAllowed = false;
  27773. };
  27774. types$1.star.updateContext = function(prevType) {
  27775. if (prevType === types$1._function) {
  27776. var index = this.context.length - 1;
  27777. if (this.context[index] === types.f_expr)
  27778. { this.context[index] = types.f_expr_gen; }
  27779. else
  27780. { this.context[index] = types.f_gen; }
  27781. }
  27782. this.exprAllowed = true;
  27783. };
  27784. types$1.name.updateContext = function(prevType) {
  27785. var allowed = false;
  27786. if (this.options.ecmaVersion >= 6 && prevType !== types$1.dot) {
  27787. if (this.value === "of" && !this.exprAllowed ||
  27788. this.value === "yield" && this.inGeneratorContext())
  27789. { allowed = true; }
  27790. }
  27791. this.exprAllowed = allowed;
  27792. };
  27793. // A recursive descent parser operates by defining functions for all
  27794. var pp$5 = Parser.prototype;
  27795. // Check if property name clashes with already added.
  27796. // Object/class getters and setters are not allowed to clash —
  27797. // either with each other or with an init property — and in
  27798. // strict mode, init properties are also not allowed to be repeated.
  27799. pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) {
  27800. if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement")
  27801. { return }
  27802. if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand))
  27803. { return }
  27804. var key = prop.key;
  27805. var name;
  27806. switch (key.type) {
  27807. case "Identifier": name = key.name; break
  27808. case "Literal": name = String(key.value); break
  27809. default: return
  27810. }
  27811. var kind = prop.kind;
  27812. if (this.options.ecmaVersion >= 6) {
  27813. if (name === "__proto__" && kind === "init") {
  27814. if (propHash.proto) {
  27815. if (refDestructuringErrors) {
  27816. if (refDestructuringErrors.doubleProto < 0) {
  27817. refDestructuringErrors.doubleProto = key.start;
  27818. }
  27819. } else {
  27820. this.raiseRecoverable(key.start, "Redefinition of __proto__ property");
  27821. }
  27822. }
  27823. propHash.proto = true;
  27824. }
  27825. return
  27826. }
  27827. name = "$" + name;
  27828. var other = propHash[name];
  27829. if (other) {
  27830. var redefinition;
  27831. if (kind === "init") {
  27832. redefinition = this.strict && other.init || other.get || other.set;
  27833. } else {
  27834. redefinition = other.init || other[kind];
  27835. }
  27836. if (redefinition)
  27837. { this.raiseRecoverable(key.start, "Redefinition of property"); }
  27838. } else {
  27839. other = propHash[name] = {
  27840. init: false,
  27841. get: false,
  27842. set: false
  27843. };
  27844. }
  27845. other[kind] = true;
  27846. };
  27847. // ### Expression parsing
  27848. // These nest, from the most general expression type at the top to
  27849. // 'atomic', nondivisible expression types at the bottom. Most of
  27850. // the functions will simply let the function(s) below them parse,
  27851. // and, *if* the syntactic construct they handle is present, wrap
  27852. // the AST node that the inner parser gave them in another node.
  27853. // Parse a full expression. The optional arguments are used to
  27854. // forbid the `in` operator (in for loops initalization expressions)
  27855. // and provide reference for storing '=' operator inside shorthand
  27856. // property assignment in contexts where both object expression
  27857. // and object pattern might appear (so it's possible to raise
  27858. // delayed syntax error at correct position).
  27859. pp$5.parseExpression = function(forInit, refDestructuringErrors) {
  27860. var startPos = this.start, startLoc = this.startLoc;
  27861. var expr = this.parseMaybeAssign(forInit, refDestructuringErrors);
  27862. if (this.type === types$1.comma) {
  27863. var node = this.startNodeAt(startPos, startLoc);
  27864. node.expressions = [expr];
  27865. while (this.eat(types$1.comma)) { node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors)); }
  27866. return this.finishNode(node, "SequenceExpression")
  27867. }
  27868. return expr
  27869. };
  27870. // Parse an assignment expression. This includes applications of
  27871. // operators like `+=`.
  27872. pp$5.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) {
  27873. if (this.isContextual("yield")) {
  27874. if (this.inGenerator) { return this.parseYield(forInit) }
  27875. // The tokenizer will assume an expression is allowed after
  27876. // `yield`, but this isn't that kind of yield
  27877. else { this.exprAllowed = false; }
  27878. }
  27879. var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldDoubleProto = -1;
  27880. if (refDestructuringErrors) {
  27881. oldParenAssign = refDestructuringErrors.parenthesizedAssign;
  27882. oldTrailingComma = refDestructuringErrors.trailingComma;
  27883. oldDoubleProto = refDestructuringErrors.doubleProto;
  27884. refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;
  27885. } else {
  27886. refDestructuringErrors = new DestructuringErrors;
  27887. ownDestructuringErrors = true;
  27888. }
  27889. var startPos = this.start, startLoc = this.startLoc;
  27890. if (this.type === types$1.parenL || this.type === types$1.name) {
  27891. this.potentialArrowAt = this.start;
  27892. this.potentialArrowInForAwait = forInit === "await";
  27893. }
  27894. var left = this.parseMaybeConditional(forInit, refDestructuringErrors);
  27895. if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); }
  27896. if (this.type.isAssign) {
  27897. var node = this.startNodeAt(startPos, startLoc);
  27898. node.operator = this.value;
  27899. if (this.type === types$1.eq)
  27900. { left = this.toAssignable(left, false, refDestructuringErrors); }
  27901. if (!ownDestructuringErrors) {
  27902. refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1;
  27903. }
  27904. if (refDestructuringErrors.shorthandAssign >= left.start)
  27905. { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly
  27906. if (this.type === types$1.eq)
  27907. { this.checkLValPattern(left); }
  27908. else
  27909. { this.checkLValSimple(left); }
  27910. node.left = left;
  27911. this.next();
  27912. node.right = this.parseMaybeAssign(forInit);
  27913. if (oldDoubleProto > -1) { refDestructuringErrors.doubleProto = oldDoubleProto; }
  27914. return this.finishNode(node, "AssignmentExpression")
  27915. } else {
  27916. if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); }
  27917. }
  27918. if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; }
  27919. if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; }
  27920. return left
  27921. };
  27922. // Parse a ternary conditional (`?:`) operator.
  27923. pp$5.parseMaybeConditional = function(forInit, refDestructuringErrors) {
  27924. var startPos = this.start, startLoc = this.startLoc;
  27925. var expr = this.parseExprOps(forInit, refDestructuringErrors);
  27926. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  27927. if (this.eat(types$1.question)) {
  27928. var node = this.startNodeAt(startPos, startLoc);
  27929. node.test = expr;
  27930. node.consequent = this.parseMaybeAssign();
  27931. this.expect(types$1.colon);
  27932. node.alternate = this.parseMaybeAssign(forInit);
  27933. return this.finishNode(node, "ConditionalExpression")
  27934. }
  27935. return expr
  27936. };
  27937. // Start the precedence parser.
  27938. pp$5.parseExprOps = function(forInit, refDestructuringErrors) {
  27939. var startPos = this.start, startLoc = this.startLoc;
  27940. var expr = this.parseMaybeUnary(refDestructuringErrors, false, false, forInit);
  27941. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  27942. return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit)
  27943. };
  27944. // Parse binary operators with the operator precedence parsing
  27945. // algorithm. `left` is the left-hand side of the operator.
  27946. // `minPrec` provides context that allows the function to stop and
  27947. // defer further parser to one of its callers when it encounters an
  27948. // operator that has a lower precedence than the set it is parsing.
  27949. pp$5.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) {
  27950. var prec = this.type.binop;
  27951. if (prec != null && (!forInit || this.type !== types$1._in)) {
  27952. if (prec > minPrec) {
  27953. var logical = this.type === types$1.logicalOR || this.type === types$1.logicalAND;
  27954. var coalesce = this.type === types$1.coalesce;
  27955. if (coalesce) {
  27956. // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions.
  27957. // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error.
  27958. prec = types$1.logicalAND.binop;
  27959. }
  27960. var op = this.value;
  27961. this.next();
  27962. var startPos = this.start, startLoc = this.startLoc;
  27963. var right = this.parseExprOp(this.parseMaybeUnary(null, false, false, forInit), startPos, startLoc, prec, forInit);
  27964. var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce);
  27965. if ((logical && this.type === types$1.coalesce) || (coalesce && (this.type === types$1.logicalOR || this.type === types$1.logicalAND))) {
  27966. this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses");
  27967. }
  27968. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit)
  27969. }
  27970. }
  27971. return left
  27972. };
  27973. pp$5.buildBinary = function(startPos, startLoc, left, right, op, logical) {
  27974. if (right.type === "PrivateIdentifier") { this.raise(right.start, "Private identifier can only be left side of binary expression"); }
  27975. var node = this.startNodeAt(startPos, startLoc);
  27976. node.left = left;
  27977. node.operator = op;
  27978. node.right = right;
  27979. return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression")
  27980. };
  27981. // Parse unary operators, both prefix and postfix.
  27982. pp$5.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec, forInit) {
  27983. var startPos = this.start, startLoc = this.startLoc, expr;
  27984. if (this.isContextual("await") && this.canAwait) {
  27985. expr = this.parseAwait(forInit);
  27986. sawUnary = true;
  27987. } else if (this.type.prefix) {
  27988. var node = this.startNode(), update = this.type === types$1.incDec;
  27989. node.operator = this.value;
  27990. node.prefix = true;
  27991. this.next();
  27992. node.argument = this.parseMaybeUnary(null, true, update, forInit);
  27993. this.checkExpressionErrors(refDestructuringErrors, true);
  27994. if (update) { this.checkLValSimple(node.argument); }
  27995. else if (this.strict && node.operator === "delete" &&
  27996. node.argument.type === "Identifier")
  27997. { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); }
  27998. else if (node.operator === "delete" && isPrivateFieldAccess(node.argument))
  27999. { this.raiseRecoverable(node.start, "Private fields can not be deleted"); }
  28000. else { sawUnary = true; }
  28001. expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
  28002. } else if (!sawUnary && this.type === types$1.privateId) {
  28003. if (forInit || this.privateNameStack.length === 0) { this.unexpected(); }
  28004. expr = this.parsePrivateIdent();
  28005. // only could be private fields in 'in', such as #x in obj
  28006. if (this.type !== types$1._in) { this.unexpected(); }
  28007. } else {
  28008. expr = this.parseExprSubscripts(refDestructuringErrors, forInit);
  28009. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  28010. while (this.type.postfix && !this.canInsertSemicolon()) {
  28011. var node$1 = this.startNodeAt(startPos, startLoc);
  28012. node$1.operator = this.value;
  28013. node$1.prefix = false;
  28014. node$1.argument = expr;
  28015. this.checkLValSimple(expr);
  28016. this.next();
  28017. expr = this.finishNode(node$1, "UpdateExpression");
  28018. }
  28019. }
  28020. if (!incDec && this.eat(types$1.starstar)) {
  28021. if (sawUnary)
  28022. { this.unexpected(this.lastTokStart); }
  28023. else
  28024. { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false, false, forInit), "**", false) }
  28025. } else {
  28026. return expr
  28027. }
  28028. };
  28029. function isPrivateFieldAccess(node) {
  28030. return (
  28031. node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" ||
  28032. node.type === "ChainExpression" && isPrivateFieldAccess(node.expression)
  28033. )
  28034. }
  28035. // Parse call, dot, and `[]`-subscript expressions.
  28036. pp$5.parseExprSubscripts = function(refDestructuringErrors, forInit) {
  28037. var startPos = this.start, startLoc = this.startLoc;
  28038. var expr = this.parseExprAtom(refDestructuringErrors, forInit);
  28039. if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")")
  28040. { return expr }
  28041. var result = this.parseSubscripts(expr, startPos, startLoc, false, forInit);
  28042. if (refDestructuringErrors && result.type === "MemberExpression") {
  28043. if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; }
  28044. if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; }
  28045. if (refDestructuringErrors.trailingComma >= result.start) { refDestructuringErrors.trailingComma = -1; }
  28046. }
  28047. return result
  28048. };
  28049. pp$5.parseSubscripts = function(base, startPos, startLoc, noCalls, forInit) {
  28050. var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" &&
  28051. this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 &&
  28052. this.potentialArrowAt === base.start;
  28053. var optionalChained = false;
  28054. while (true) {
  28055. var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit);
  28056. if (element.optional) { optionalChained = true; }
  28057. if (element === base || element.type === "ArrowFunctionExpression") {
  28058. if (optionalChained) {
  28059. var chainNode = this.startNodeAt(startPos, startLoc);
  28060. chainNode.expression = element;
  28061. element = this.finishNode(chainNode, "ChainExpression");
  28062. }
  28063. return element
  28064. }
  28065. base = element;
  28066. }
  28067. };
  28068. pp$5.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) {
  28069. var optionalSupported = this.options.ecmaVersion >= 11;
  28070. var optional = optionalSupported && this.eat(types$1.questionDot);
  28071. if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); }
  28072. var computed = this.eat(types$1.bracketL);
  28073. if (computed || (optional && this.type !== types$1.parenL && this.type !== types$1.backQuote) || this.eat(types$1.dot)) {
  28074. var node = this.startNodeAt(startPos, startLoc);
  28075. node.object = base;
  28076. if (computed) {
  28077. node.property = this.parseExpression();
  28078. this.expect(types$1.bracketR);
  28079. } else if (this.type === types$1.privateId && base.type !== "Super") {
  28080. node.property = this.parsePrivateIdent();
  28081. } else {
  28082. node.property = this.parseIdent(this.options.allowReserved !== "never");
  28083. }
  28084. node.computed = !!computed;
  28085. if (optionalSupported) {
  28086. node.optional = optional;
  28087. }
  28088. base = this.finishNode(node, "MemberExpression");
  28089. } else if (!noCalls && this.eat(types$1.parenL)) {
  28090. var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  28091. this.yieldPos = 0;
  28092. this.awaitPos = 0;
  28093. this.awaitIdentPos = 0;
  28094. var exprList = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);
  28095. if (maybeAsyncArrow && !optional && !this.canInsertSemicolon() && this.eat(types$1.arrow)) {
  28096. this.checkPatternErrors(refDestructuringErrors, false);
  28097. this.checkYieldAwaitInDefaultParams();
  28098. if (this.awaitIdentPos > 0)
  28099. { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); }
  28100. this.yieldPos = oldYieldPos;
  28101. this.awaitPos = oldAwaitPos;
  28102. this.awaitIdentPos = oldAwaitIdentPos;
  28103. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true, forInit)
  28104. }
  28105. this.checkExpressionErrors(refDestructuringErrors, true);
  28106. this.yieldPos = oldYieldPos || this.yieldPos;
  28107. this.awaitPos = oldAwaitPos || this.awaitPos;
  28108. this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;
  28109. var node$1 = this.startNodeAt(startPos, startLoc);
  28110. node$1.callee = base;
  28111. node$1.arguments = exprList;
  28112. if (optionalSupported) {
  28113. node$1.optional = optional;
  28114. }
  28115. base = this.finishNode(node$1, "CallExpression");
  28116. } else if (this.type === types$1.backQuote) {
  28117. if (optional || optionalChained) {
  28118. this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions");
  28119. }
  28120. var node$2 = this.startNodeAt(startPos, startLoc);
  28121. node$2.tag = base;
  28122. node$2.quasi = this.parseTemplate({isTagged: true});
  28123. base = this.finishNode(node$2, "TaggedTemplateExpression");
  28124. }
  28125. return base
  28126. };
  28127. // Parse an atomic expression — either a single token that is an
  28128. // expression, an expression started by a keyword like `function` or
  28129. // `new`, or an expression wrapped in punctuation like `()`, `[]`,
  28130. // or `{}`.
  28131. pp$5.parseExprAtom = function(refDestructuringErrors, forInit) {
  28132. // If a division operator appears in an expression position, the
  28133. // tokenizer got confused, and we force it to read a regexp instead.
  28134. if (this.type === types$1.slash) { this.readRegexp(); }
  28135. var node, canBeArrow = this.potentialArrowAt === this.start;
  28136. switch (this.type) {
  28137. case types$1._super:
  28138. if (!this.allowSuper)
  28139. { this.raise(this.start, "'super' keyword outside a method"); }
  28140. node = this.startNode();
  28141. this.next();
  28142. if (this.type === types$1.parenL && !this.allowDirectSuper)
  28143. { this.raise(node.start, "super() call outside constructor of a subclass"); }
  28144. // The `super` keyword can appear at below:
  28145. // SuperProperty:
  28146. // super [ Expression ]
  28147. // super . IdentifierName
  28148. // SuperCall:
  28149. // super ( Arguments )
  28150. if (this.type !== types$1.dot && this.type !== types$1.bracketL && this.type !== types$1.parenL)
  28151. { this.unexpected(); }
  28152. return this.finishNode(node, "Super")
  28153. case types$1._this:
  28154. node = this.startNode();
  28155. this.next();
  28156. return this.finishNode(node, "ThisExpression")
  28157. case types$1.name:
  28158. var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc;
  28159. var id = this.parseIdent(false);
  28160. if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types$1._function)) {
  28161. this.overrideContext(types.f_expr);
  28162. return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true, forInit)
  28163. }
  28164. if (canBeArrow && !this.canInsertSemicolon()) {
  28165. if (this.eat(types$1.arrow))
  28166. { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false, forInit) }
  28167. if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types$1.name && !containsEsc &&
  28168. (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) {
  28169. id = this.parseIdent(false);
  28170. if (this.canInsertSemicolon() || !this.eat(types$1.arrow))
  28171. { this.unexpected(); }
  28172. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true, forInit)
  28173. }
  28174. }
  28175. return id
  28176. case types$1.regexp:
  28177. var value = this.value;
  28178. node = this.parseLiteral(value.value);
  28179. node.regex = {pattern: value.pattern, flags: value.flags};
  28180. return node
  28181. case types$1.num: case types$1.string:
  28182. return this.parseLiteral(this.value)
  28183. case types$1._null: case types$1._true: case types$1._false:
  28184. node = this.startNode();
  28185. node.value = this.type === types$1._null ? null : this.type === types$1._true;
  28186. node.raw = this.type.keyword;
  28187. this.next();
  28188. return this.finishNode(node, "Literal")
  28189. case types$1.parenL:
  28190. var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow, forInit);
  28191. if (refDestructuringErrors) {
  28192. if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))
  28193. { refDestructuringErrors.parenthesizedAssign = start; }
  28194. if (refDestructuringErrors.parenthesizedBind < 0)
  28195. { refDestructuringErrors.parenthesizedBind = start; }
  28196. }
  28197. return expr
  28198. case types$1.bracketL:
  28199. node = this.startNode();
  28200. this.next();
  28201. node.elements = this.parseExprList(types$1.bracketR, true, true, refDestructuringErrors);
  28202. return this.finishNode(node, "ArrayExpression")
  28203. case types$1.braceL:
  28204. this.overrideContext(types.b_expr);
  28205. return this.parseObj(false, refDestructuringErrors)
  28206. case types$1._function:
  28207. node = this.startNode();
  28208. this.next();
  28209. return this.parseFunction(node, 0)
  28210. case types$1._class:
  28211. return this.parseClass(this.startNode(), false)
  28212. case types$1._new:
  28213. return this.parseNew()
  28214. case types$1.backQuote:
  28215. return this.parseTemplate()
  28216. case types$1._import:
  28217. if (this.options.ecmaVersion >= 11) {
  28218. return this.parseExprImport()
  28219. } else {
  28220. return this.unexpected()
  28221. }
  28222. default:
  28223. this.unexpected();
  28224. }
  28225. };
  28226. pp$5.parseExprImport = function() {
  28227. var node = this.startNode();
  28228. // Consume `import` as an identifier for `import.meta`.
  28229. // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`.
  28230. if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); }
  28231. var meta = this.parseIdent(true);
  28232. switch (this.type) {
  28233. case types$1.parenL:
  28234. return this.parseDynamicImport(node)
  28235. case types$1.dot:
  28236. node.meta = meta;
  28237. return this.parseImportMeta(node)
  28238. default:
  28239. this.unexpected();
  28240. }
  28241. };
  28242. pp$5.parseDynamicImport = function(node) {
  28243. this.next(); // skip `(`
  28244. // Parse node.source.
  28245. node.source = this.parseMaybeAssign();
  28246. // Verify ending.
  28247. if (!this.eat(types$1.parenR)) {
  28248. var errorPos = this.start;
  28249. if (this.eat(types$1.comma) && this.eat(types$1.parenR)) {
  28250. this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()");
  28251. } else {
  28252. this.unexpected(errorPos);
  28253. }
  28254. }
  28255. return this.finishNode(node, "ImportExpression")
  28256. };
  28257. pp$5.parseImportMeta = function(node) {
  28258. this.next(); // skip `.`
  28259. var containsEsc = this.containsEsc;
  28260. node.property = this.parseIdent(true);
  28261. if (node.property.name !== "meta")
  28262. { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); }
  28263. if (containsEsc)
  28264. { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); }
  28265. if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere)
  28266. { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); }
  28267. return this.finishNode(node, "MetaProperty")
  28268. };
  28269. pp$5.parseLiteral = function(value) {
  28270. var node = this.startNode();
  28271. node.value = value;
  28272. node.raw = this.input.slice(this.start, this.end);
  28273. if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); }
  28274. this.next();
  28275. return this.finishNode(node, "Literal")
  28276. };
  28277. pp$5.parseParenExpression = function() {
  28278. this.expect(types$1.parenL);
  28279. var val = this.parseExpression();
  28280. this.expect(types$1.parenR);
  28281. return val
  28282. };
  28283. pp$5.parseParenAndDistinguishExpression = function(canBeArrow, forInit) {
  28284. var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;
  28285. if (this.options.ecmaVersion >= 6) {
  28286. this.next();
  28287. var innerStartPos = this.start, innerStartLoc = this.startLoc;
  28288. var exprList = [], first = true, lastIsComma = false;
  28289. var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart;
  28290. this.yieldPos = 0;
  28291. this.awaitPos = 0;
  28292. // Do not save awaitIdentPos to allow checking awaits nested in parameters
  28293. while (this.type !== types$1.parenR) {
  28294. first ? first = false : this.expect(types$1.comma);
  28295. if (allowTrailingComma && this.afterTrailingComma(types$1.parenR, true)) {
  28296. lastIsComma = true;
  28297. break
  28298. } else if (this.type === types$1.ellipsis) {
  28299. spreadStart = this.start;
  28300. exprList.push(this.parseParenItem(this.parseRestBinding()));
  28301. if (this.type === types$1.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
  28302. break
  28303. } else {
  28304. exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));
  28305. }
  28306. }
  28307. var innerEndPos = this.lastTokEnd, innerEndLoc = this.lastTokEndLoc;
  28308. this.expect(types$1.parenR);
  28309. if (canBeArrow && !this.canInsertSemicolon() && this.eat(types$1.arrow)) {
  28310. this.checkPatternErrors(refDestructuringErrors, false);
  28311. this.checkYieldAwaitInDefaultParams();
  28312. this.yieldPos = oldYieldPos;
  28313. this.awaitPos = oldAwaitPos;
  28314. return this.parseParenArrowList(startPos, startLoc, exprList, forInit)
  28315. }
  28316. if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); }
  28317. if (spreadStart) { this.unexpected(spreadStart); }
  28318. this.checkExpressionErrors(refDestructuringErrors, true);
  28319. this.yieldPos = oldYieldPos || this.yieldPos;
  28320. this.awaitPos = oldAwaitPos || this.awaitPos;
  28321. if (exprList.length > 1) {
  28322. val = this.startNodeAt(innerStartPos, innerStartLoc);
  28323. val.expressions = exprList;
  28324. this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
  28325. } else {
  28326. val = exprList[0];
  28327. }
  28328. } else {
  28329. val = this.parseParenExpression();
  28330. }
  28331. if (this.options.preserveParens) {
  28332. var par = this.startNodeAt(startPos, startLoc);
  28333. par.expression = val;
  28334. return this.finishNode(par, "ParenthesizedExpression")
  28335. } else {
  28336. return val
  28337. }
  28338. };
  28339. pp$5.parseParenItem = function(item) {
  28340. return item
  28341. };
  28342. pp$5.parseParenArrowList = function(startPos, startLoc, exprList, forInit) {
  28343. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, false, forInit)
  28344. };
  28345. // New's precedence is slightly tricky. It must allow its argument to
  28346. // be a `[]` or dot subscript expression, but not a call — at least,
  28347. // not without wrapping it in parentheses. Thus, it uses the noCalls
  28348. // argument to parseSubscripts to prevent it from consuming the
  28349. // argument list.
  28350. var empty = [];
  28351. pp$5.parseNew = function() {
  28352. if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); }
  28353. var node = this.startNode();
  28354. var meta = this.parseIdent(true);
  28355. if (this.options.ecmaVersion >= 6 && this.eat(types$1.dot)) {
  28356. node.meta = meta;
  28357. var containsEsc = this.containsEsc;
  28358. node.property = this.parseIdent(true);
  28359. if (node.property.name !== "target")
  28360. { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); }
  28361. if (containsEsc)
  28362. { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); }
  28363. if (!this.allowNewDotTarget)
  28364. { this.raiseRecoverable(node.start, "'new.target' can only be used in functions and class static block"); }
  28365. return this.finishNode(node, "MetaProperty")
  28366. }
  28367. var startPos = this.start, startLoc = this.startLoc, isImport = this.type === types$1._import;
  28368. node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true, false);
  28369. if (isImport && node.callee.type === "ImportExpression") {
  28370. this.raise(startPos, "Cannot use new with import()");
  28371. }
  28372. if (this.eat(types$1.parenL)) { node.arguments = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false); }
  28373. else { node.arguments = empty; }
  28374. return this.finishNode(node, "NewExpression")
  28375. };
  28376. // Parse template expression.
  28377. pp$5.parseTemplateElement = function(ref) {
  28378. var isTagged = ref.isTagged;
  28379. var elem = this.startNode();
  28380. if (this.type === types$1.invalidTemplate) {
  28381. if (!isTagged) {
  28382. this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");
  28383. }
  28384. elem.value = {
  28385. raw: this.value,
  28386. cooked: null
  28387. };
  28388. } else {
  28389. elem.value = {
  28390. raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
  28391. cooked: this.value
  28392. };
  28393. }
  28394. this.next();
  28395. elem.tail = this.type === types$1.backQuote;
  28396. return this.finishNode(elem, "TemplateElement")
  28397. };
  28398. pp$5.parseTemplate = function(ref) {
  28399. if ( ref === void 0 ) ref = {};
  28400. var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false;
  28401. var node = this.startNode();
  28402. this.next();
  28403. node.expressions = [];
  28404. var curElt = this.parseTemplateElement({isTagged: isTagged});
  28405. node.quasis = [curElt];
  28406. while (!curElt.tail) {
  28407. if (this.type === types$1.eof) { this.raise(this.pos, "Unterminated template literal"); }
  28408. this.expect(types$1.dollarBraceL);
  28409. node.expressions.push(this.parseExpression());
  28410. this.expect(types$1.braceR);
  28411. node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged}));
  28412. }
  28413. this.next();
  28414. return this.finishNode(node, "TemplateLiteral")
  28415. };
  28416. pp$5.isAsyncProp = function(prop) {
  28417. return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" &&
  28418. (this.type === types$1.name || this.type === types$1.num || this.type === types$1.string || this.type === types$1.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === types$1.star)) &&
  28419. !lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
  28420. };
  28421. // Parse an object literal or binding pattern.
  28422. pp$5.parseObj = function(isPattern, refDestructuringErrors) {
  28423. var node = this.startNode(), first = true, propHash = {};
  28424. node.properties = [];
  28425. this.next();
  28426. while (!this.eat(types$1.braceR)) {
  28427. if (!first) {
  28428. this.expect(types$1.comma);
  28429. if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types$1.braceR)) { break }
  28430. } else { first = false; }
  28431. var prop = this.parseProperty(isPattern, refDestructuringErrors);
  28432. if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); }
  28433. node.properties.push(prop);
  28434. }
  28435. return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")
  28436. };
  28437. pp$5.parseProperty = function(isPattern, refDestructuringErrors) {
  28438. var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc;
  28439. if (this.options.ecmaVersion >= 9 && this.eat(types$1.ellipsis)) {
  28440. if (isPattern) {
  28441. prop.argument = this.parseIdent(false);
  28442. if (this.type === types$1.comma) {
  28443. this.raise(this.start, "Comma is not permitted after the rest element");
  28444. }
  28445. return this.finishNode(prop, "RestElement")
  28446. }
  28447. // To disallow parenthesized identifier via `this.toAssignable()`.
  28448. if (this.type === types$1.parenL && refDestructuringErrors) {
  28449. if (refDestructuringErrors.parenthesizedAssign < 0) {
  28450. refDestructuringErrors.parenthesizedAssign = this.start;
  28451. }
  28452. if (refDestructuringErrors.parenthesizedBind < 0) {
  28453. refDestructuringErrors.parenthesizedBind = this.start;
  28454. }
  28455. }
  28456. // Parse argument.
  28457. prop.argument = this.parseMaybeAssign(false, refDestructuringErrors);
  28458. // To disallow trailing comma via `this.toAssignable()`.
  28459. if (this.type === types$1.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {
  28460. refDestructuringErrors.trailingComma = this.start;
  28461. }
  28462. // Finish
  28463. return this.finishNode(prop, "SpreadElement")
  28464. }
  28465. if (this.options.ecmaVersion >= 6) {
  28466. prop.method = false;
  28467. prop.shorthand = false;
  28468. if (isPattern || refDestructuringErrors) {
  28469. startPos = this.start;
  28470. startLoc = this.startLoc;
  28471. }
  28472. if (!isPattern)
  28473. { isGenerator = this.eat(types$1.star); }
  28474. }
  28475. var containsEsc = this.containsEsc;
  28476. this.parsePropertyName(prop);
  28477. if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {
  28478. isAsync = true;
  28479. isGenerator = this.options.ecmaVersion >= 9 && this.eat(types$1.star);
  28480. this.parsePropertyName(prop, refDestructuringErrors);
  28481. } else {
  28482. isAsync = false;
  28483. }
  28484. this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc);
  28485. return this.finishNode(prop, "Property")
  28486. };
  28487. pp$5.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) {
  28488. if ((isGenerator || isAsync) && this.type === types$1.colon)
  28489. { this.unexpected(); }
  28490. if (this.eat(types$1.colon)) {
  28491. prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);
  28492. prop.kind = "init";
  28493. } else if (this.options.ecmaVersion >= 6 && this.type === types$1.parenL) {
  28494. if (isPattern) { this.unexpected(); }
  28495. prop.kind = "init";
  28496. prop.method = true;
  28497. prop.value = this.parseMethod(isGenerator, isAsync);
  28498. } else if (!isPattern && !containsEsc &&
  28499. this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" &&
  28500. (prop.key.name === "get" || prop.key.name === "set") &&
  28501. (this.type !== types$1.comma && this.type !== types$1.braceR && this.type !== types$1.eq)) {
  28502. if (isGenerator || isAsync) { this.unexpected(); }
  28503. prop.kind = prop.key.name;
  28504. this.parsePropertyName(prop);
  28505. prop.value = this.parseMethod(false);
  28506. var paramCount = prop.kind === "get" ? 0 : 1;
  28507. if (prop.value.params.length !== paramCount) {
  28508. var start = prop.value.start;
  28509. if (prop.kind === "get")
  28510. { this.raiseRecoverable(start, "getter should have no params"); }
  28511. else
  28512. { this.raiseRecoverable(start, "setter should have exactly one param"); }
  28513. } else {
  28514. if (prop.kind === "set" && prop.value.params[0].type === "RestElement")
  28515. { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); }
  28516. }
  28517. } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
  28518. if (isGenerator || isAsync) { this.unexpected(); }
  28519. this.checkUnreserved(prop.key);
  28520. if (prop.key.name === "await" && !this.awaitIdentPos)
  28521. { this.awaitIdentPos = startPos; }
  28522. prop.kind = "init";
  28523. if (isPattern) {
  28524. prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
  28525. } else if (this.type === types$1.eq && refDestructuringErrors) {
  28526. if (refDestructuringErrors.shorthandAssign < 0)
  28527. { refDestructuringErrors.shorthandAssign = this.start; }
  28528. prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
  28529. } else {
  28530. prop.value = this.copyNode(prop.key);
  28531. }
  28532. prop.shorthand = true;
  28533. } else { this.unexpected(); }
  28534. };
  28535. pp$5.parsePropertyName = function(prop) {
  28536. if (this.options.ecmaVersion >= 6) {
  28537. if (this.eat(types$1.bracketL)) {
  28538. prop.computed = true;
  28539. prop.key = this.parseMaybeAssign();
  28540. this.expect(types$1.bracketR);
  28541. return prop.key
  28542. } else {
  28543. prop.computed = false;
  28544. }
  28545. }
  28546. return prop.key = this.type === types$1.num || this.type === types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never")
  28547. };
  28548. // Initialize empty function node.
  28549. pp$5.initFunction = function(node) {
  28550. node.id = null;
  28551. if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; }
  28552. if (this.options.ecmaVersion >= 8) { node.async = false; }
  28553. };
  28554. // Parse object or class method.
  28555. pp$5.parseMethod = function(isGenerator, isAsync, allowDirectSuper) {
  28556. var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  28557. this.initFunction(node);
  28558. if (this.options.ecmaVersion >= 6)
  28559. { node.generator = isGenerator; }
  28560. if (this.options.ecmaVersion >= 8)
  28561. { node.async = !!isAsync; }
  28562. this.yieldPos = 0;
  28563. this.awaitPos = 0;
  28564. this.awaitIdentPos = 0;
  28565. this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
  28566. this.expect(types$1.parenL);
  28567. node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8);
  28568. this.checkYieldAwaitInDefaultParams();
  28569. this.parseFunctionBody(node, false, true, false);
  28570. this.yieldPos = oldYieldPos;
  28571. this.awaitPos = oldAwaitPos;
  28572. this.awaitIdentPos = oldAwaitIdentPos;
  28573. return this.finishNode(node, "FunctionExpression")
  28574. };
  28575. // Parse arrow function expression with given parameters.
  28576. pp$5.parseArrowExpression = function(node, params, isAsync, forInit) {
  28577. var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  28578. this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW);
  28579. this.initFunction(node);
  28580. if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; }
  28581. this.yieldPos = 0;
  28582. this.awaitPos = 0;
  28583. this.awaitIdentPos = 0;
  28584. node.params = this.toAssignableList(params, true);
  28585. this.parseFunctionBody(node, true, false, forInit);
  28586. this.yieldPos = oldYieldPos;
  28587. this.awaitPos = oldAwaitPos;
  28588. this.awaitIdentPos = oldAwaitIdentPos;
  28589. return this.finishNode(node, "ArrowFunctionExpression")
  28590. };
  28591. // Parse function body and check parameters.
  28592. pp$5.parseFunctionBody = function(node, isArrowFunction, isMethod, forInit) {
  28593. var isExpression = isArrowFunction && this.type !== types$1.braceL;
  28594. var oldStrict = this.strict, useStrict = false;
  28595. if (isExpression) {
  28596. node.body = this.parseMaybeAssign(forInit);
  28597. node.expression = true;
  28598. this.checkParams(node, false);
  28599. } else {
  28600. var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);
  28601. if (!oldStrict || nonSimple) {
  28602. useStrict = this.strictDirective(this.end);
  28603. // If this is a strict mode function, verify that argument names
  28604. // are not repeated, and it does not try to bind the words `eval`
  28605. // or `arguments`.
  28606. if (useStrict && nonSimple)
  28607. { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); }
  28608. }
  28609. // Start a new scope with regard to labels and the `inFunction`
  28610. // flag (restore them to their old value afterwards).
  28611. var oldLabels = this.labels;
  28612. this.labels = [];
  28613. if (useStrict) { this.strict = true; }
  28614. // Add the params to varDeclaredNames to ensure that an error is thrown
  28615. // if a let/const declaration in the function clashes with one of the params.
  28616. this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params));
  28617. // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'
  28618. if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); }
  28619. node.body = this.parseBlock(false, undefined, useStrict && !oldStrict);
  28620. node.expression = false;
  28621. this.adaptDirectivePrologue(node.body.body);
  28622. this.labels = oldLabels;
  28623. }
  28624. this.exitScope();
  28625. };
  28626. pp$5.isSimpleParamList = function(params) {
  28627. for (var i = 0, list = params; i < list.length; i += 1)
  28628. {
  28629. var param = list[i];
  28630. if (param.type !== "Identifier") { return false
  28631. } }
  28632. return true
  28633. };
  28634. // Checks function params for various disallowed patterns such as using "eval"
  28635. // or "arguments" and duplicate parameters.
  28636. pp$5.checkParams = function(node, allowDuplicates) {
  28637. var nameHash = Object.create(null);
  28638. for (var i = 0, list = node.params; i < list.length; i += 1)
  28639. {
  28640. var param = list[i];
  28641. this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash);
  28642. }
  28643. };
  28644. // Parses a comma-separated list of expressions, and returns them as
  28645. // an array. `close` is the token type that ends the list, and
  28646. // `allowEmpty` can be turned on to allow subsequent commas with
  28647. // nothing in between them to be parsed as `null` (which is needed
  28648. // for array literals).
  28649. pp$5.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
  28650. var elts = [], first = true;
  28651. while (!this.eat(close)) {
  28652. if (!first) {
  28653. this.expect(types$1.comma);
  28654. if (allowTrailingComma && this.afterTrailingComma(close)) { break }
  28655. } else { first = false; }
  28656. var elt = (void 0);
  28657. if (allowEmpty && this.type === types$1.comma)
  28658. { elt = null; }
  28659. else if (this.type === types$1.ellipsis) {
  28660. elt = this.parseSpread(refDestructuringErrors);
  28661. if (refDestructuringErrors && this.type === types$1.comma && refDestructuringErrors.trailingComma < 0)
  28662. { refDestructuringErrors.trailingComma = this.start; }
  28663. } else {
  28664. elt = this.parseMaybeAssign(false, refDestructuringErrors);
  28665. }
  28666. elts.push(elt);
  28667. }
  28668. return elts
  28669. };
  28670. pp$5.checkUnreserved = function(ref) {
  28671. var start = ref.start;
  28672. var end = ref.end;
  28673. var name = ref.name;
  28674. if (this.inGenerator && name === "yield")
  28675. { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); }
  28676. if (this.inAsync && name === "await")
  28677. { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); }
  28678. if (this.currentThisScope().inClassFieldInit && name === "arguments")
  28679. { this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer"); }
  28680. if (this.inClassStaticBlock && (name === "arguments" || name === "await"))
  28681. { this.raise(start, ("Cannot use " + name + " in class static initialization block")); }
  28682. if (this.keywords.test(name))
  28683. { this.raise(start, ("Unexpected keyword '" + name + "'")); }
  28684. if (this.options.ecmaVersion < 6 &&
  28685. this.input.slice(start, end).indexOf("\\") !== -1) { return }
  28686. var re = this.strict ? this.reservedWordsStrict : this.reservedWords;
  28687. if (re.test(name)) {
  28688. if (!this.inAsync && name === "await")
  28689. { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); }
  28690. this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved"));
  28691. }
  28692. };
  28693. // Parse the next token as an identifier. If `liberal` is true (used
  28694. // when parsing properties), it will also convert keywords into
  28695. // identifiers.
  28696. pp$5.parseIdent = function(liberal, isBinding) {
  28697. var node = this.startNode();
  28698. if (this.type === types$1.name) {
  28699. node.name = this.value;
  28700. } else if (this.type.keyword) {
  28701. node.name = this.type.keyword;
  28702. // To fix https://github.com/acornjs/acorn/issues/575
  28703. // `class` and `function` keywords push new context into this.context.
  28704. // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name.
  28705. // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword
  28706. if ((node.name === "class" || node.name === "function") &&
  28707. (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {
  28708. this.context.pop();
  28709. }
  28710. } else {
  28711. this.unexpected();
  28712. }
  28713. this.next(!!liberal);
  28714. this.finishNode(node, "Identifier");
  28715. if (!liberal) {
  28716. this.checkUnreserved(node);
  28717. if (node.name === "await" && !this.awaitIdentPos)
  28718. { this.awaitIdentPos = node.start; }
  28719. }
  28720. return node
  28721. };
  28722. pp$5.parsePrivateIdent = function() {
  28723. var node = this.startNode();
  28724. if (this.type === types$1.privateId) {
  28725. node.name = this.value;
  28726. } else {
  28727. this.unexpected();
  28728. }
  28729. this.next();
  28730. this.finishNode(node, "PrivateIdentifier");
  28731. // For validating existence
  28732. if (this.privateNameStack.length === 0) {
  28733. this.raise(node.start, ("Private field '#" + (node.name) + "' must be declared in an enclosing class"));
  28734. } else {
  28735. this.privateNameStack[this.privateNameStack.length - 1].used.push(node);
  28736. }
  28737. return node
  28738. };
  28739. // Parses yield expression inside generator.
  28740. pp$5.parseYield = function(forInit) {
  28741. if (!this.yieldPos) { this.yieldPos = this.start; }
  28742. var node = this.startNode();
  28743. this.next();
  28744. if (this.type === types$1.semi || this.canInsertSemicolon() || (this.type !== types$1.star && !this.type.startsExpr)) {
  28745. node.delegate = false;
  28746. node.argument = null;
  28747. } else {
  28748. node.delegate = this.eat(types$1.star);
  28749. node.argument = this.parseMaybeAssign(forInit);
  28750. }
  28751. return this.finishNode(node, "YieldExpression")
  28752. };
  28753. pp$5.parseAwait = function(forInit) {
  28754. if (!this.awaitPos) { this.awaitPos = this.start; }
  28755. var node = this.startNode();
  28756. this.next();
  28757. node.argument = this.parseMaybeUnary(null, true, false, forInit);
  28758. return this.finishNode(node, "AwaitExpression")
  28759. };
  28760. var pp$4 = Parser.prototype;
  28761. // This function is used to raise exceptions on parse errors. It
  28762. // takes an offset integer (into the current `input`) to indicate
  28763. // the location of the error, attaches the position to the end
  28764. // of the error message, and then raises a `SyntaxError` with that
  28765. // message.
  28766. pp$4.raise = function(pos, message) {
  28767. var loc = getLineInfo(this.input, pos);
  28768. message += " (" + loc.line + ":" + loc.column + ")";
  28769. var err = new SyntaxError(message);
  28770. err.pos = pos; err.loc = loc; err.raisedAt = this.pos;
  28771. throw err
  28772. };
  28773. pp$4.raiseRecoverable = pp$4.raise;
  28774. pp$4.curPosition = function() {
  28775. if (this.options.locations) {
  28776. return new Position(this.curLine, this.pos - this.lineStart)
  28777. }
  28778. };
  28779. var pp$3 = Parser.prototype;
  28780. var Scope = function Scope(flags) {
  28781. this.flags = flags;
  28782. // A list of var-declared names in the current lexical scope
  28783. this.var = [];
  28784. // A list of lexically-declared names in the current lexical scope
  28785. this.lexical = [];
  28786. // A list of lexically-declared FunctionDeclaration names in the current lexical scope
  28787. this.functions = [];
  28788. // A switch to disallow the identifier reference 'arguments'
  28789. this.inClassFieldInit = false;
  28790. };
  28791. // The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names.
  28792. pp$3.enterScope = function(flags) {
  28793. this.scopeStack.push(new Scope(flags));
  28794. };
  28795. pp$3.exitScope = function() {
  28796. this.scopeStack.pop();
  28797. };
  28798. // The spec says:
  28799. // > At the top level of a function, or script, function declarations are
  28800. // > treated like var declarations rather than like lexical declarations.
  28801. pp$3.treatFunctionsAsVarInScope = function(scope) {
  28802. return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP)
  28803. };
  28804. pp$3.declareName = function(name, bindingType, pos) {
  28805. var redeclared = false;
  28806. if (bindingType === BIND_LEXICAL) {
  28807. var scope = this.currentScope();
  28808. redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
  28809. scope.lexical.push(name);
  28810. if (this.inModule && (scope.flags & SCOPE_TOP))
  28811. { delete this.undefinedExports[name]; }
  28812. } else if (bindingType === BIND_SIMPLE_CATCH) {
  28813. var scope$1 = this.currentScope();
  28814. scope$1.lexical.push(name);
  28815. } else if (bindingType === BIND_FUNCTION) {
  28816. var scope$2 = this.currentScope();
  28817. if (this.treatFunctionsAsVar)
  28818. { redeclared = scope$2.lexical.indexOf(name) > -1; }
  28819. else
  28820. { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; }
  28821. scope$2.functions.push(name);
  28822. } else {
  28823. for (var i = this.scopeStack.length - 1; i >= 0; --i) {
  28824. var scope$3 = this.scopeStack[i];
  28825. if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) ||
  28826. !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) {
  28827. redeclared = true;
  28828. break
  28829. }
  28830. scope$3.var.push(name);
  28831. if (this.inModule && (scope$3.flags & SCOPE_TOP))
  28832. { delete this.undefinedExports[name]; }
  28833. if (scope$3.flags & SCOPE_VAR) { break }
  28834. }
  28835. }
  28836. if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); }
  28837. };
  28838. pp$3.checkLocalExport = function(id) {
  28839. // scope.functions must be empty as Module code is always strict.
  28840. if (this.scopeStack[0].lexical.indexOf(id.name) === -1 &&
  28841. this.scopeStack[0].var.indexOf(id.name) === -1) {
  28842. this.undefinedExports[id.name] = id;
  28843. }
  28844. };
  28845. pp$3.currentScope = function() {
  28846. return this.scopeStack[this.scopeStack.length - 1]
  28847. };
  28848. pp$3.currentVarScope = function() {
  28849. for (var i = this.scopeStack.length - 1;; i--) {
  28850. var scope = this.scopeStack[i];
  28851. if (scope.flags & SCOPE_VAR) { return scope }
  28852. }
  28853. };
  28854. // Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`.
  28855. pp$3.currentThisScope = function() {
  28856. for (var i = this.scopeStack.length - 1;; i--) {
  28857. var scope = this.scopeStack[i];
  28858. if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope }
  28859. }
  28860. };
  28861. var Node = function Node(parser, pos, loc) {
  28862. this.type = "";
  28863. this.start = pos;
  28864. this.end = 0;
  28865. if (parser.options.locations)
  28866. { this.loc = new SourceLocation(parser, loc); }
  28867. if (parser.options.directSourceFile)
  28868. { this.sourceFile = parser.options.directSourceFile; }
  28869. if (parser.options.ranges)
  28870. { this.range = [pos, 0]; }
  28871. };
  28872. // Start an AST node, attaching a start offset.
  28873. var pp$2 = Parser.prototype;
  28874. pp$2.startNode = function() {
  28875. return new Node(this, this.start, this.startLoc)
  28876. };
  28877. pp$2.startNodeAt = function(pos, loc) {
  28878. return new Node(this, pos, loc)
  28879. };
  28880. // Finish an AST node, adding `type` and `end` properties.
  28881. function finishNodeAt(node, type, pos, loc) {
  28882. node.type = type;
  28883. node.end = pos;
  28884. if (this.options.locations)
  28885. { node.loc.end = loc; }
  28886. if (this.options.ranges)
  28887. { node.range[1] = pos; }
  28888. return node
  28889. }
  28890. pp$2.finishNode = function(node, type) {
  28891. return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)
  28892. };
  28893. // Finish node at given position
  28894. pp$2.finishNodeAt = function(node, type, pos, loc) {
  28895. return finishNodeAt.call(this, node, type, pos, loc)
  28896. };
  28897. pp$2.copyNode = function(node) {
  28898. var newNode = new Node(this, node.start, this.startLoc);
  28899. for (var prop in node) { newNode[prop] = node[prop]; }
  28900. return newNode
  28901. };
  28902. // This file contains Unicode properties extracted from the ECMAScript
  28903. // specification. The lists are extracted like so:
  28904. // $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText)
  28905. // #table-binary-unicode-properties
  28906. var ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS";
  28907. var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic";
  28908. var ecma11BinaryProperties = ecma10BinaryProperties;
  28909. var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict";
  28910. var ecma13BinaryProperties = ecma12BinaryProperties;
  28911. var unicodeBinaryProperties = {
  28912. 9: ecma9BinaryProperties,
  28913. 10: ecma10BinaryProperties,
  28914. 11: ecma11BinaryProperties,
  28915. 12: ecma12BinaryProperties,
  28916. 13: ecma13BinaryProperties
  28917. };
  28918. // #table-unicode-general-category-values
  28919. var unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu";
  28920. // #table-unicode-script-values
  28921. var ecma9ScriptValues = "Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb";
  28922. var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";
  28923. var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";
  28924. var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";
  28925. var ecma13ScriptValues = ecma12ScriptValues + " Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith";
  28926. var unicodeScriptValues = {
  28927. 9: ecma9ScriptValues,
  28928. 10: ecma10ScriptValues,
  28929. 11: ecma11ScriptValues,
  28930. 12: ecma12ScriptValues,
  28931. 13: ecma13ScriptValues
  28932. };
  28933. var data = {};
  28934. function buildUnicodeData(ecmaVersion) {
  28935. var d = data[ecmaVersion] = {
  28936. binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues),
  28937. nonBinary: {
  28938. General_Category: wordsRegexp(unicodeGeneralCategoryValues),
  28939. Script: wordsRegexp(unicodeScriptValues[ecmaVersion])
  28940. }
  28941. };
  28942. d.nonBinary.Script_Extensions = d.nonBinary.Script;
  28943. d.nonBinary.gc = d.nonBinary.General_Category;
  28944. d.nonBinary.sc = d.nonBinary.Script;
  28945. d.nonBinary.scx = d.nonBinary.Script_Extensions;
  28946. }
  28947. for (var i$1 = 0, list = [9, 10, 11, 12, 13]; i$1 < list.length; i$1 += 1) {
  28948. var ecmaVersion = list[i$1];
  28949. buildUnicodeData(ecmaVersion);
  28950. }
  28951. var pp$1 = Parser.prototype;
  28952. var RegExpValidationState = function RegExpValidationState(parser) {
  28953. this.parser = parser;
  28954. this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : "");
  28955. this.unicodeProperties = data[parser.options.ecmaVersion >= 13 ? 13 : parser.options.ecmaVersion];
  28956. this.source = "";
  28957. this.flags = "";
  28958. this.start = 0;
  28959. this.switchU = false;
  28960. this.switchN = false;
  28961. this.pos = 0;
  28962. this.lastIntValue = 0;
  28963. this.lastStringValue = "";
  28964. this.lastAssertionIsQuantifiable = false;
  28965. this.numCapturingParens = 0;
  28966. this.maxBackReference = 0;
  28967. this.groupNames = [];
  28968. this.backReferenceNames = [];
  28969. };
  28970. RegExpValidationState.prototype.reset = function reset (start, pattern, flags) {
  28971. var unicode = flags.indexOf("u") !== -1;
  28972. this.start = start | 0;
  28973. this.source = pattern + "";
  28974. this.flags = flags;
  28975. this.switchU = unicode && this.parser.options.ecmaVersion >= 6;
  28976. this.switchN = unicode && this.parser.options.ecmaVersion >= 9;
  28977. };
  28978. RegExpValidationState.prototype.raise = function raise (message) {
  28979. this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message));
  28980. };
  28981. // If u flag is given, this returns the code point at the index (it combines a surrogate pair).
  28982. // Otherwise, this returns the code unit of the index (can be a part of a surrogate pair).
  28983. RegExpValidationState.prototype.at = function at (i, forceU) {
  28984. if ( forceU === void 0 ) forceU = false;
  28985. var s = this.source;
  28986. var l = s.length;
  28987. if (i >= l) {
  28988. return -1
  28989. }
  28990. var c = s.charCodeAt(i);
  28991. if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) {
  28992. return c
  28993. }
  28994. var next = s.charCodeAt(i + 1);
  28995. return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c
  28996. };
  28997. RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) {
  28998. if ( forceU === void 0 ) forceU = false;
  28999. var s = this.source;
  29000. var l = s.length;
  29001. if (i >= l) {
  29002. return l
  29003. }
  29004. var c = s.charCodeAt(i), next;
  29005. if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l ||
  29006. (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) {
  29007. return i + 1
  29008. }
  29009. return i + 2
  29010. };
  29011. RegExpValidationState.prototype.current = function current (forceU) {
  29012. if ( forceU === void 0 ) forceU = false;
  29013. return this.at(this.pos, forceU)
  29014. };
  29015. RegExpValidationState.prototype.lookahead = function lookahead (forceU) {
  29016. if ( forceU === void 0 ) forceU = false;
  29017. return this.at(this.nextIndex(this.pos, forceU), forceU)
  29018. };
  29019. RegExpValidationState.prototype.advance = function advance (forceU) {
  29020. if ( forceU === void 0 ) forceU = false;
  29021. this.pos = this.nextIndex(this.pos, forceU);
  29022. };
  29023. RegExpValidationState.prototype.eat = function eat (ch, forceU) {
  29024. if ( forceU === void 0 ) forceU = false;
  29025. if (this.current(forceU) === ch) {
  29026. this.advance(forceU);
  29027. return true
  29028. }
  29029. return false
  29030. };
  29031. /**
  29032. * Validate the flags part of a given RegExpLiteral.
  29033. *
  29034. * @param {RegExpValidationState} state The state to validate RegExp.
  29035. * @returns {void}
  29036. */
  29037. pp$1.validateRegExpFlags = function(state) {
  29038. var validFlags = state.validFlags;
  29039. var flags = state.flags;
  29040. for (var i = 0; i < flags.length; i++) {
  29041. var flag = flags.charAt(i);
  29042. if (validFlags.indexOf(flag) === -1) {
  29043. this.raise(state.start, "Invalid regular expression flag");
  29044. }
  29045. if (flags.indexOf(flag, i + 1) > -1) {
  29046. this.raise(state.start, "Duplicate regular expression flag");
  29047. }
  29048. }
  29049. };
  29050. /**
  29051. * Validate the pattern part of a given RegExpLiteral.
  29052. *
  29053. * @param {RegExpValidationState} state The state to validate RegExp.
  29054. * @returns {void}
  29055. */
  29056. pp$1.validateRegExpPattern = function(state) {
  29057. this.regexp_pattern(state);
  29058. // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of
  29059. // parsing contains a |GroupName|, reparse with the goal symbol
  29060. // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError*
  29061. // exception if _P_ did not conform to the grammar, if any elements of _P_
  29062. // were not matched by the parse, or if any Early Error conditions exist.
  29063. if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) {
  29064. state.switchN = true;
  29065. this.regexp_pattern(state);
  29066. }
  29067. };
  29068. // https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern
  29069. pp$1.regexp_pattern = function(state) {
  29070. state.pos = 0;
  29071. state.lastIntValue = 0;
  29072. state.lastStringValue = "";
  29073. state.lastAssertionIsQuantifiable = false;
  29074. state.numCapturingParens = 0;
  29075. state.maxBackReference = 0;
  29076. state.groupNames.length = 0;
  29077. state.backReferenceNames.length = 0;
  29078. this.regexp_disjunction(state);
  29079. if (state.pos !== state.source.length) {
  29080. // Make the same messages as V8.
  29081. if (state.eat(0x29 /* ) */)) {
  29082. state.raise("Unmatched ')'");
  29083. }
  29084. if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) {
  29085. state.raise("Lone quantifier brackets");
  29086. }
  29087. }
  29088. if (state.maxBackReference > state.numCapturingParens) {
  29089. state.raise("Invalid escape");
  29090. }
  29091. for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) {
  29092. var name = list[i];
  29093. if (state.groupNames.indexOf(name) === -1) {
  29094. state.raise("Invalid named capture referenced");
  29095. }
  29096. }
  29097. };
  29098. // https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction
  29099. pp$1.regexp_disjunction = function(state) {
  29100. this.regexp_alternative(state);
  29101. while (state.eat(0x7C /* | */)) {
  29102. this.regexp_alternative(state);
  29103. }
  29104. // Make the same message as V8.
  29105. if (this.regexp_eatQuantifier(state, true)) {
  29106. state.raise("Nothing to repeat");
  29107. }
  29108. if (state.eat(0x7B /* { */)) {
  29109. state.raise("Lone quantifier brackets");
  29110. }
  29111. };
  29112. // https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative
  29113. pp$1.regexp_alternative = function(state) {
  29114. while (state.pos < state.source.length && this.regexp_eatTerm(state))
  29115. { }
  29116. };
  29117. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term
  29118. pp$1.regexp_eatTerm = function(state) {
  29119. if (this.regexp_eatAssertion(state)) {
  29120. // Handle `QuantifiableAssertion Quantifier` alternative.
  29121. // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion
  29122. // is a QuantifiableAssertion.
  29123. if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) {
  29124. // Make the same message as V8.
  29125. if (state.switchU) {
  29126. state.raise("Invalid quantifier");
  29127. }
  29128. }
  29129. return true
  29130. }
  29131. if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) {
  29132. this.regexp_eatQuantifier(state);
  29133. return true
  29134. }
  29135. return false
  29136. };
  29137. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion
  29138. pp$1.regexp_eatAssertion = function(state) {
  29139. var start = state.pos;
  29140. state.lastAssertionIsQuantifiable = false;
  29141. // ^, $
  29142. if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) {
  29143. return true
  29144. }
  29145. // \b \B
  29146. if (state.eat(0x5C /* \ */)) {
  29147. if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) {
  29148. return true
  29149. }
  29150. state.pos = start;
  29151. }
  29152. // Lookahead / Lookbehind
  29153. if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) {
  29154. var lookbehind = false;
  29155. if (this.options.ecmaVersion >= 9) {
  29156. lookbehind = state.eat(0x3C /* < */);
  29157. }
  29158. if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) {
  29159. this.regexp_disjunction(state);
  29160. if (!state.eat(0x29 /* ) */)) {
  29161. state.raise("Unterminated group");
  29162. }
  29163. state.lastAssertionIsQuantifiable = !lookbehind;
  29164. return true
  29165. }
  29166. }
  29167. state.pos = start;
  29168. return false
  29169. };
  29170. // https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier
  29171. pp$1.regexp_eatQuantifier = function(state, noError) {
  29172. if ( noError === void 0 ) noError = false;
  29173. if (this.regexp_eatQuantifierPrefix(state, noError)) {
  29174. state.eat(0x3F /* ? */);
  29175. return true
  29176. }
  29177. return false
  29178. };
  29179. // https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix
  29180. pp$1.regexp_eatQuantifierPrefix = function(state, noError) {
  29181. return (
  29182. state.eat(0x2A /* * */) ||
  29183. state.eat(0x2B /* + */) ||
  29184. state.eat(0x3F /* ? */) ||
  29185. this.regexp_eatBracedQuantifier(state, noError)
  29186. )
  29187. };
  29188. pp$1.regexp_eatBracedQuantifier = function(state, noError) {
  29189. var start = state.pos;
  29190. if (state.eat(0x7B /* { */)) {
  29191. var min = 0, max = -1;
  29192. if (this.regexp_eatDecimalDigits(state)) {
  29193. min = state.lastIntValue;
  29194. if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) {
  29195. max = state.lastIntValue;
  29196. }
  29197. if (state.eat(0x7D /* } */)) {
  29198. // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term
  29199. if (max !== -1 && max < min && !noError) {
  29200. state.raise("numbers out of order in {} quantifier");
  29201. }
  29202. return true
  29203. }
  29204. }
  29205. if (state.switchU && !noError) {
  29206. state.raise("Incomplete quantifier");
  29207. }
  29208. state.pos = start;
  29209. }
  29210. return false
  29211. };
  29212. // https://www.ecma-international.org/ecma-262/8.0/#prod-Atom
  29213. pp$1.regexp_eatAtom = function(state) {
  29214. return (
  29215. this.regexp_eatPatternCharacters(state) ||
  29216. state.eat(0x2E /* . */) ||
  29217. this.regexp_eatReverseSolidusAtomEscape(state) ||
  29218. this.regexp_eatCharacterClass(state) ||
  29219. this.regexp_eatUncapturingGroup(state) ||
  29220. this.regexp_eatCapturingGroup(state)
  29221. )
  29222. };
  29223. pp$1.regexp_eatReverseSolidusAtomEscape = function(state) {
  29224. var start = state.pos;
  29225. if (state.eat(0x5C /* \ */)) {
  29226. if (this.regexp_eatAtomEscape(state)) {
  29227. return true
  29228. }
  29229. state.pos = start;
  29230. }
  29231. return false
  29232. };
  29233. pp$1.regexp_eatUncapturingGroup = function(state) {
  29234. var start = state.pos;
  29235. if (state.eat(0x28 /* ( */)) {
  29236. if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) {
  29237. this.regexp_disjunction(state);
  29238. if (state.eat(0x29 /* ) */)) {
  29239. return true
  29240. }
  29241. state.raise("Unterminated group");
  29242. }
  29243. state.pos = start;
  29244. }
  29245. return false
  29246. };
  29247. pp$1.regexp_eatCapturingGroup = function(state) {
  29248. if (state.eat(0x28 /* ( */)) {
  29249. if (this.options.ecmaVersion >= 9) {
  29250. this.regexp_groupSpecifier(state);
  29251. } else if (state.current() === 0x3F /* ? */) {
  29252. state.raise("Invalid group");
  29253. }
  29254. this.regexp_disjunction(state);
  29255. if (state.eat(0x29 /* ) */)) {
  29256. state.numCapturingParens += 1;
  29257. return true
  29258. }
  29259. state.raise("Unterminated group");
  29260. }
  29261. return false
  29262. };
  29263. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom
  29264. pp$1.regexp_eatExtendedAtom = function(state) {
  29265. return (
  29266. state.eat(0x2E /* . */) ||
  29267. this.regexp_eatReverseSolidusAtomEscape(state) ||
  29268. this.regexp_eatCharacterClass(state) ||
  29269. this.regexp_eatUncapturingGroup(state) ||
  29270. this.regexp_eatCapturingGroup(state) ||
  29271. this.regexp_eatInvalidBracedQuantifier(state) ||
  29272. this.regexp_eatExtendedPatternCharacter(state)
  29273. )
  29274. };
  29275. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier
  29276. pp$1.regexp_eatInvalidBracedQuantifier = function(state) {
  29277. if (this.regexp_eatBracedQuantifier(state, true)) {
  29278. state.raise("Nothing to repeat");
  29279. }
  29280. return false
  29281. };
  29282. // https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter
  29283. pp$1.regexp_eatSyntaxCharacter = function(state) {
  29284. var ch = state.current();
  29285. if (isSyntaxCharacter(ch)) {
  29286. state.lastIntValue = ch;
  29287. state.advance();
  29288. return true
  29289. }
  29290. return false
  29291. };
  29292. function isSyntaxCharacter(ch) {
  29293. return (
  29294. ch === 0x24 /* $ */ ||
  29295. ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ ||
  29296. ch === 0x2E /* . */ ||
  29297. ch === 0x3F /* ? */ ||
  29298. ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ ||
  29299. ch >= 0x7B /* { */ && ch <= 0x7D /* } */
  29300. )
  29301. }
  29302. // https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter
  29303. // But eat eager.
  29304. pp$1.regexp_eatPatternCharacters = function(state) {
  29305. var start = state.pos;
  29306. var ch = 0;
  29307. while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) {
  29308. state.advance();
  29309. }
  29310. return state.pos !== start
  29311. };
  29312. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter
  29313. pp$1.regexp_eatExtendedPatternCharacter = function(state) {
  29314. var ch = state.current();
  29315. if (
  29316. ch !== -1 &&
  29317. ch !== 0x24 /* $ */ &&
  29318. !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) &&
  29319. ch !== 0x2E /* . */ &&
  29320. ch !== 0x3F /* ? */ &&
  29321. ch !== 0x5B /* [ */ &&
  29322. ch !== 0x5E /* ^ */ &&
  29323. ch !== 0x7C /* | */
  29324. ) {
  29325. state.advance();
  29326. return true
  29327. }
  29328. return false
  29329. };
  29330. // GroupSpecifier ::
  29331. // [empty]
  29332. // `?` GroupName
  29333. pp$1.regexp_groupSpecifier = function(state) {
  29334. if (state.eat(0x3F /* ? */)) {
  29335. if (this.regexp_eatGroupName(state)) {
  29336. if (state.groupNames.indexOf(state.lastStringValue) !== -1) {
  29337. state.raise("Duplicate capture group name");
  29338. }
  29339. state.groupNames.push(state.lastStringValue);
  29340. return
  29341. }
  29342. state.raise("Invalid group");
  29343. }
  29344. };
  29345. // GroupName ::
  29346. // `<` RegExpIdentifierName `>`
  29347. // Note: this updates `state.lastStringValue` property with the eaten name.
  29348. pp$1.regexp_eatGroupName = function(state) {
  29349. state.lastStringValue = "";
  29350. if (state.eat(0x3C /* < */)) {
  29351. if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) {
  29352. return true
  29353. }
  29354. state.raise("Invalid capture group name");
  29355. }
  29356. return false
  29357. };
  29358. // RegExpIdentifierName ::
  29359. // RegExpIdentifierStart
  29360. // RegExpIdentifierName RegExpIdentifierPart
  29361. // Note: this updates `state.lastStringValue` property with the eaten name.
  29362. pp$1.regexp_eatRegExpIdentifierName = function(state) {
  29363. state.lastStringValue = "";
  29364. if (this.regexp_eatRegExpIdentifierStart(state)) {
  29365. state.lastStringValue += codePointToString(state.lastIntValue);
  29366. while (this.regexp_eatRegExpIdentifierPart(state)) {
  29367. state.lastStringValue += codePointToString(state.lastIntValue);
  29368. }
  29369. return true
  29370. }
  29371. return false
  29372. };
  29373. // RegExpIdentifierStart ::
  29374. // UnicodeIDStart
  29375. // `$`
  29376. // `_`
  29377. // `\` RegExpUnicodeEscapeSequence[+U]
  29378. pp$1.regexp_eatRegExpIdentifierStart = function(state) {
  29379. var start = state.pos;
  29380. var forceU = this.options.ecmaVersion >= 11;
  29381. var ch = state.current(forceU);
  29382. state.advance(forceU);
  29383. if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
  29384. ch = state.lastIntValue;
  29385. }
  29386. if (isRegExpIdentifierStart(ch)) {
  29387. state.lastIntValue = ch;
  29388. return true
  29389. }
  29390. state.pos = start;
  29391. return false
  29392. };
  29393. function isRegExpIdentifierStart(ch) {
  29394. return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */
  29395. }
  29396. // RegExpIdentifierPart ::
  29397. // UnicodeIDContinue
  29398. // `$`
  29399. // `_`
  29400. // `\` RegExpUnicodeEscapeSequence[+U]
  29401. // <ZWNJ>
  29402. // <ZWJ>
  29403. pp$1.regexp_eatRegExpIdentifierPart = function(state) {
  29404. var start = state.pos;
  29405. var forceU = this.options.ecmaVersion >= 11;
  29406. var ch = state.current(forceU);
  29407. state.advance(forceU);
  29408. if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
  29409. ch = state.lastIntValue;
  29410. }
  29411. if (isRegExpIdentifierPart(ch)) {
  29412. state.lastIntValue = ch;
  29413. return true
  29414. }
  29415. state.pos = start;
  29416. return false
  29417. };
  29418. function isRegExpIdentifierPart(ch) {
  29419. return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* <ZWNJ> */ || ch === 0x200D /* <ZWJ> */
  29420. }
  29421. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape
  29422. pp$1.regexp_eatAtomEscape = function(state) {
  29423. if (
  29424. this.regexp_eatBackReference(state) ||
  29425. this.regexp_eatCharacterClassEscape(state) ||
  29426. this.regexp_eatCharacterEscape(state) ||
  29427. (state.switchN && this.regexp_eatKGroupName(state))
  29428. ) {
  29429. return true
  29430. }
  29431. if (state.switchU) {
  29432. // Make the same message as V8.
  29433. if (state.current() === 0x63 /* c */) {
  29434. state.raise("Invalid unicode escape");
  29435. }
  29436. state.raise("Invalid escape");
  29437. }
  29438. return false
  29439. };
  29440. pp$1.regexp_eatBackReference = function(state) {
  29441. var start = state.pos;
  29442. if (this.regexp_eatDecimalEscape(state)) {
  29443. var n = state.lastIntValue;
  29444. if (state.switchU) {
  29445. // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape
  29446. if (n > state.maxBackReference) {
  29447. state.maxBackReference = n;
  29448. }
  29449. return true
  29450. }
  29451. if (n <= state.numCapturingParens) {
  29452. return true
  29453. }
  29454. state.pos = start;
  29455. }
  29456. return false
  29457. };
  29458. pp$1.regexp_eatKGroupName = function(state) {
  29459. if (state.eat(0x6B /* k */)) {
  29460. if (this.regexp_eatGroupName(state)) {
  29461. state.backReferenceNames.push(state.lastStringValue);
  29462. return true
  29463. }
  29464. state.raise("Invalid named reference");
  29465. }
  29466. return false
  29467. };
  29468. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape
  29469. pp$1.regexp_eatCharacterEscape = function(state) {
  29470. return (
  29471. this.regexp_eatControlEscape(state) ||
  29472. this.regexp_eatCControlLetter(state) ||
  29473. this.regexp_eatZero(state) ||
  29474. this.regexp_eatHexEscapeSequence(state) ||
  29475. this.regexp_eatRegExpUnicodeEscapeSequence(state, false) ||
  29476. (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) ||
  29477. this.regexp_eatIdentityEscape(state)
  29478. )
  29479. };
  29480. pp$1.regexp_eatCControlLetter = function(state) {
  29481. var start = state.pos;
  29482. if (state.eat(0x63 /* c */)) {
  29483. if (this.regexp_eatControlLetter(state)) {
  29484. return true
  29485. }
  29486. state.pos = start;
  29487. }
  29488. return false
  29489. };
  29490. pp$1.regexp_eatZero = function(state) {
  29491. if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) {
  29492. state.lastIntValue = 0;
  29493. state.advance();
  29494. return true
  29495. }
  29496. return false
  29497. };
  29498. // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape
  29499. pp$1.regexp_eatControlEscape = function(state) {
  29500. var ch = state.current();
  29501. if (ch === 0x74 /* t */) {
  29502. state.lastIntValue = 0x09; /* \t */
  29503. state.advance();
  29504. return true
  29505. }
  29506. if (ch === 0x6E /* n */) {
  29507. state.lastIntValue = 0x0A; /* \n */
  29508. state.advance();
  29509. return true
  29510. }
  29511. if (ch === 0x76 /* v */) {
  29512. state.lastIntValue = 0x0B; /* \v */
  29513. state.advance();
  29514. return true
  29515. }
  29516. if (ch === 0x66 /* f */) {
  29517. state.lastIntValue = 0x0C; /* \f */
  29518. state.advance();
  29519. return true
  29520. }
  29521. if (ch === 0x72 /* r */) {
  29522. state.lastIntValue = 0x0D; /* \r */
  29523. state.advance();
  29524. return true
  29525. }
  29526. return false
  29527. };
  29528. // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter
  29529. pp$1.regexp_eatControlLetter = function(state) {
  29530. var ch = state.current();
  29531. if (isControlLetter(ch)) {
  29532. state.lastIntValue = ch % 0x20;
  29533. state.advance();
  29534. return true
  29535. }
  29536. return false
  29537. };
  29538. function isControlLetter(ch) {
  29539. return (
  29540. (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) ||
  29541. (ch >= 0x61 /* a */ && ch <= 0x7A /* z */)
  29542. )
  29543. }
  29544. // https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence
  29545. pp$1.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) {
  29546. if ( forceU === void 0 ) forceU = false;
  29547. var start = state.pos;
  29548. var switchU = forceU || state.switchU;
  29549. if (state.eat(0x75 /* u */)) {
  29550. if (this.regexp_eatFixedHexDigits(state, 4)) {
  29551. var lead = state.lastIntValue;
  29552. if (switchU && lead >= 0xD800 && lead <= 0xDBFF) {
  29553. var leadSurrogateEnd = state.pos;
  29554. if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) {
  29555. var trail = state.lastIntValue;
  29556. if (trail >= 0xDC00 && trail <= 0xDFFF) {
  29557. state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
  29558. return true
  29559. }
  29560. }
  29561. state.pos = leadSurrogateEnd;
  29562. state.lastIntValue = lead;
  29563. }
  29564. return true
  29565. }
  29566. if (
  29567. switchU &&
  29568. state.eat(0x7B /* { */) &&
  29569. this.regexp_eatHexDigits(state) &&
  29570. state.eat(0x7D /* } */) &&
  29571. isValidUnicode(state.lastIntValue)
  29572. ) {
  29573. return true
  29574. }
  29575. if (switchU) {
  29576. state.raise("Invalid unicode escape");
  29577. }
  29578. state.pos = start;
  29579. }
  29580. return false
  29581. };
  29582. function isValidUnicode(ch) {
  29583. return ch >= 0 && ch <= 0x10FFFF
  29584. }
  29585. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape
  29586. pp$1.regexp_eatIdentityEscape = function(state) {
  29587. if (state.switchU) {
  29588. if (this.regexp_eatSyntaxCharacter(state)) {
  29589. return true
  29590. }
  29591. if (state.eat(0x2F /* / */)) {
  29592. state.lastIntValue = 0x2F; /* / */
  29593. return true
  29594. }
  29595. return false
  29596. }
  29597. var ch = state.current();
  29598. if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) {
  29599. state.lastIntValue = ch;
  29600. state.advance();
  29601. return true
  29602. }
  29603. return false
  29604. };
  29605. // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape
  29606. pp$1.regexp_eatDecimalEscape = function(state) {
  29607. state.lastIntValue = 0;
  29608. var ch = state.current();
  29609. if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) {
  29610. do {
  29611. state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
  29612. state.advance();
  29613. } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */)
  29614. return true
  29615. }
  29616. return false
  29617. };
  29618. // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape
  29619. pp$1.regexp_eatCharacterClassEscape = function(state) {
  29620. var ch = state.current();
  29621. if (isCharacterClassEscape(ch)) {
  29622. state.lastIntValue = -1;
  29623. state.advance();
  29624. return true
  29625. }
  29626. if (
  29627. state.switchU &&
  29628. this.options.ecmaVersion >= 9 &&
  29629. (ch === 0x50 /* P */ || ch === 0x70 /* p */)
  29630. ) {
  29631. state.lastIntValue = -1;
  29632. state.advance();
  29633. if (
  29634. state.eat(0x7B /* { */) &&
  29635. this.regexp_eatUnicodePropertyValueExpression(state) &&
  29636. state.eat(0x7D /* } */)
  29637. ) {
  29638. return true
  29639. }
  29640. state.raise("Invalid property name");
  29641. }
  29642. return false
  29643. };
  29644. function isCharacterClassEscape(ch) {
  29645. return (
  29646. ch === 0x64 /* d */ ||
  29647. ch === 0x44 /* D */ ||
  29648. ch === 0x73 /* s */ ||
  29649. ch === 0x53 /* S */ ||
  29650. ch === 0x77 /* w */ ||
  29651. ch === 0x57 /* W */
  29652. )
  29653. }
  29654. // UnicodePropertyValueExpression ::
  29655. // UnicodePropertyName `=` UnicodePropertyValue
  29656. // LoneUnicodePropertyNameOrValue
  29657. pp$1.regexp_eatUnicodePropertyValueExpression = function(state) {
  29658. var start = state.pos;
  29659. // UnicodePropertyName `=` UnicodePropertyValue
  29660. if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) {
  29661. var name = state.lastStringValue;
  29662. if (this.regexp_eatUnicodePropertyValue(state)) {
  29663. var value = state.lastStringValue;
  29664. this.regexp_validateUnicodePropertyNameAndValue(state, name, value);
  29665. return true
  29666. }
  29667. }
  29668. state.pos = start;
  29669. // LoneUnicodePropertyNameOrValue
  29670. if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {
  29671. var nameOrValue = state.lastStringValue;
  29672. this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue);
  29673. return true
  29674. }
  29675. return false
  29676. };
  29677. pp$1.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {
  29678. if (!hasOwn(state.unicodeProperties.nonBinary, name))
  29679. { state.raise("Invalid property name"); }
  29680. if (!state.unicodeProperties.nonBinary[name].test(value))
  29681. { state.raise("Invalid property value"); }
  29682. };
  29683. pp$1.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) {
  29684. if (!state.unicodeProperties.binary.test(nameOrValue))
  29685. { state.raise("Invalid property name"); }
  29686. };
  29687. // UnicodePropertyName ::
  29688. // UnicodePropertyNameCharacters
  29689. pp$1.regexp_eatUnicodePropertyName = function(state) {
  29690. var ch = 0;
  29691. state.lastStringValue = "";
  29692. while (isUnicodePropertyNameCharacter(ch = state.current())) {
  29693. state.lastStringValue += codePointToString(ch);
  29694. state.advance();
  29695. }
  29696. return state.lastStringValue !== ""
  29697. };
  29698. function isUnicodePropertyNameCharacter(ch) {
  29699. return isControlLetter(ch) || ch === 0x5F /* _ */
  29700. }
  29701. // UnicodePropertyValue ::
  29702. // UnicodePropertyValueCharacters
  29703. pp$1.regexp_eatUnicodePropertyValue = function(state) {
  29704. var ch = 0;
  29705. state.lastStringValue = "";
  29706. while (isUnicodePropertyValueCharacter(ch = state.current())) {
  29707. state.lastStringValue += codePointToString(ch);
  29708. state.advance();
  29709. }
  29710. return state.lastStringValue !== ""
  29711. };
  29712. function isUnicodePropertyValueCharacter(ch) {
  29713. return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch)
  29714. }
  29715. // LoneUnicodePropertyNameOrValue ::
  29716. // UnicodePropertyValueCharacters
  29717. pp$1.regexp_eatLoneUnicodePropertyNameOrValue = function(state) {
  29718. return this.regexp_eatUnicodePropertyValue(state)
  29719. };
  29720. // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass
  29721. pp$1.regexp_eatCharacterClass = function(state) {
  29722. if (state.eat(0x5B /* [ */)) {
  29723. state.eat(0x5E /* ^ */);
  29724. this.regexp_classRanges(state);
  29725. if (state.eat(0x5D /* ] */)) {
  29726. return true
  29727. }
  29728. // Unreachable since it threw "unterminated regular expression" error before.
  29729. state.raise("Unterminated character class");
  29730. }
  29731. return false
  29732. };
  29733. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges
  29734. // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges
  29735. // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash
  29736. pp$1.regexp_classRanges = function(state) {
  29737. while (this.regexp_eatClassAtom(state)) {
  29738. var left = state.lastIntValue;
  29739. if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) {
  29740. var right = state.lastIntValue;
  29741. if (state.switchU && (left === -1 || right === -1)) {
  29742. state.raise("Invalid character class");
  29743. }
  29744. if (left !== -1 && right !== -1 && left > right) {
  29745. state.raise("Range out of order in character class");
  29746. }
  29747. }
  29748. }
  29749. };
  29750. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom
  29751. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash
  29752. pp$1.regexp_eatClassAtom = function(state) {
  29753. var start = state.pos;
  29754. if (state.eat(0x5C /* \ */)) {
  29755. if (this.regexp_eatClassEscape(state)) {
  29756. return true
  29757. }
  29758. if (state.switchU) {
  29759. // Make the same message as V8.
  29760. var ch$1 = state.current();
  29761. if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) {
  29762. state.raise("Invalid class escape");
  29763. }
  29764. state.raise("Invalid escape");
  29765. }
  29766. state.pos = start;
  29767. }
  29768. var ch = state.current();
  29769. if (ch !== 0x5D /* ] */) {
  29770. state.lastIntValue = ch;
  29771. state.advance();
  29772. return true
  29773. }
  29774. return false
  29775. };
  29776. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape
  29777. pp$1.regexp_eatClassEscape = function(state) {
  29778. var start = state.pos;
  29779. if (state.eat(0x62 /* b */)) {
  29780. state.lastIntValue = 0x08; /* <BS> */
  29781. return true
  29782. }
  29783. if (state.switchU && state.eat(0x2D /* - */)) {
  29784. state.lastIntValue = 0x2D; /* - */
  29785. return true
  29786. }
  29787. if (!state.switchU && state.eat(0x63 /* c */)) {
  29788. if (this.regexp_eatClassControlLetter(state)) {
  29789. return true
  29790. }
  29791. state.pos = start;
  29792. }
  29793. return (
  29794. this.regexp_eatCharacterClassEscape(state) ||
  29795. this.regexp_eatCharacterEscape(state)
  29796. )
  29797. };
  29798. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter
  29799. pp$1.regexp_eatClassControlLetter = function(state) {
  29800. var ch = state.current();
  29801. if (isDecimalDigit(ch) || ch === 0x5F /* _ */) {
  29802. state.lastIntValue = ch % 0x20;
  29803. state.advance();
  29804. return true
  29805. }
  29806. return false
  29807. };
  29808. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
  29809. pp$1.regexp_eatHexEscapeSequence = function(state) {
  29810. var start = state.pos;
  29811. if (state.eat(0x78 /* x */)) {
  29812. if (this.regexp_eatFixedHexDigits(state, 2)) {
  29813. return true
  29814. }
  29815. if (state.switchU) {
  29816. state.raise("Invalid escape");
  29817. }
  29818. state.pos = start;
  29819. }
  29820. return false
  29821. };
  29822. // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits
  29823. pp$1.regexp_eatDecimalDigits = function(state) {
  29824. var start = state.pos;
  29825. var ch = 0;
  29826. state.lastIntValue = 0;
  29827. while (isDecimalDigit(ch = state.current())) {
  29828. state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
  29829. state.advance();
  29830. }
  29831. return state.pos !== start
  29832. };
  29833. function isDecimalDigit(ch) {
  29834. return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */
  29835. }
  29836. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits
  29837. pp$1.regexp_eatHexDigits = function(state) {
  29838. var start = state.pos;
  29839. var ch = 0;
  29840. state.lastIntValue = 0;
  29841. while (isHexDigit(ch = state.current())) {
  29842. state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
  29843. state.advance();
  29844. }
  29845. return state.pos !== start
  29846. };
  29847. function isHexDigit(ch) {
  29848. return (
  29849. (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) ||
  29850. (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) ||
  29851. (ch >= 0x61 /* a */ && ch <= 0x66 /* f */)
  29852. )
  29853. }
  29854. function hexToInt(ch) {
  29855. if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) {
  29856. return 10 + (ch - 0x41 /* A */)
  29857. }
  29858. if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) {
  29859. return 10 + (ch - 0x61 /* a */)
  29860. }
  29861. return ch - 0x30 /* 0 */
  29862. }
  29863. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence
  29864. // Allows only 0-377(octal) i.e. 0-255(decimal).
  29865. pp$1.regexp_eatLegacyOctalEscapeSequence = function(state) {
  29866. if (this.regexp_eatOctalDigit(state)) {
  29867. var n1 = state.lastIntValue;
  29868. if (this.regexp_eatOctalDigit(state)) {
  29869. var n2 = state.lastIntValue;
  29870. if (n1 <= 3 && this.regexp_eatOctalDigit(state)) {
  29871. state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue;
  29872. } else {
  29873. state.lastIntValue = n1 * 8 + n2;
  29874. }
  29875. } else {
  29876. state.lastIntValue = n1;
  29877. }
  29878. return true
  29879. }
  29880. return false
  29881. };
  29882. // https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit
  29883. pp$1.regexp_eatOctalDigit = function(state) {
  29884. var ch = state.current();
  29885. if (isOctalDigit(ch)) {
  29886. state.lastIntValue = ch - 0x30; /* 0 */
  29887. state.advance();
  29888. return true
  29889. }
  29890. state.lastIntValue = 0;
  29891. return false
  29892. };
  29893. function isOctalDigit(ch) {
  29894. return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */
  29895. }
  29896. // https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits
  29897. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit
  29898. // And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
  29899. pp$1.regexp_eatFixedHexDigits = function(state, length) {
  29900. var start = state.pos;
  29901. state.lastIntValue = 0;
  29902. for (var i = 0; i < length; ++i) {
  29903. var ch = state.current();
  29904. if (!isHexDigit(ch)) {
  29905. state.pos = start;
  29906. return false
  29907. }
  29908. state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
  29909. state.advance();
  29910. }
  29911. return true
  29912. };
  29913. // Object type used to represent tokens. Note that normally, tokens
  29914. // simply exist as properties on the parser object. This is only
  29915. // used for the onToken callback and the external tokenizer.
  29916. var Token = function Token(p) {
  29917. this.type = p.type;
  29918. this.value = p.value;
  29919. this.start = p.start;
  29920. this.end = p.end;
  29921. if (p.options.locations)
  29922. { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); }
  29923. if (p.options.ranges)
  29924. { this.range = [p.start, p.end]; }
  29925. };
  29926. // ## Tokenizer
  29927. var pp = Parser.prototype;
  29928. // Move to the next token
  29929. pp.next = function(ignoreEscapeSequenceInKeyword) {
  29930. if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc)
  29931. { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); }
  29932. if (this.options.onToken)
  29933. { this.options.onToken(new Token(this)); }
  29934. this.lastTokEnd = this.end;
  29935. this.lastTokStart = this.start;
  29936. this.lastTokEndLoc = this.endLoc;
  29937. this.lastTokStartLoc = this.startLoc;
  29938. this.nextToken();
  29939. };
  29940. pp.getToken = function() {
  29941. this.next();
  29942. return new Token(this)
  29943. };
  29944. // If we're in an ES6 environment, make parsers iterable
  29945. if (typeof Symbol !== "undefined")
  29946. { pp[Symbol.iterator] = function() {
  29947. var this$1$1 = this;
  29948. return {
  29949. next: function () {
  29950. var token = this$1$1.getToken();
  29951. return {
  29952. done: token.type === types$1.eof,
  29953. value: token
  29954. }
  29955. }
  29956. }
  29957. }; }
  29958. // Toggle strict mode. Re-reads the next number or string to please
  29959. // pedantic tests (`"use strict"; 010;` should fail).
  29960. // Read a single token, updating the parser object's token-related
  29961. // properties.
  29962. pp.nextToken = function() {
  29963. var curContext = this.curContext();
  29964. if (!curContext || !curContext.preserveSpace) { this.skipSpace(); }
  29965. this.start = this.pos;
  29966. if (this.options.locations) { this.startLoc = this.curPosition(); }
  29967. if (this.pos >= this.input.length) { return this.finishToken(types$1.eof) }
  29968. if (curContext.override) { return curContext.override(this) }
  29969. else { this.readToken(this.fullCharCodeAtPos()); }
  29970. };
  29971. pp.readToken = function(code) {
  29972. // Identifier or keyword. '\uXXXX' sequences are allowed in
  29973. // identifiers, so '\' also dispatches to that.
  29974. if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)
  29975. { return this.readWord() }
  29976. return this.getTokenFromCode(code)
  29977. };
  29978. pp.fullCharCodeAtPos = function() {
  29979. var code = this.input.charCodeAt(this.pos);
  29980. if (code <= 0xd7ff || code >= 0xdc00) { return code }
  29981. var next = this.input.charCodeAt(this.pos + 1);
  29982. return next <= 0xdbff || next >= 0xe000 ? code : (code << 10) + next - 0x35fdc00
  29983. };
  29984. pp.skipBlockComment = function() {
  29985. var startLoc = this.options.onComment && this.curPosition();
  29986. var start = this.pos, end = this.input.indexOf("*/", this.pos += 2);
  29987. if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); }
  29988. this.pos = end + 2;
  29989. if (this.options.locations) {
  29990. for (var nextBreak = (void 0), pos = start; (nextBreak = nextLineBreak(this.input, pos, this.pos)) > -1;) {
  29991. ++this.curLine;
  29992. pos = this.lineStart = nextBreak;
  29993. }
  29994. }
  29995. if (this.options.onComment)
  29996. { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,
  29997. startLoc, this.curPosition()); }
  29998. };
  29999. pp.skipLineComment = function(startSkip) {
  30000. var start = this.pos;
  30001. var startLoc = this.options.onComment && this.curPosition();
  30002. var ch = this.input.charCodeAt(this.pos += startSkip);
  30003. while (this.pos < this.input.length && !isNewLine(ch)) {
  30004. ch = this.input.charCodeAt(++this.pos);
  30005. }
  30006. if (this.options.onComment)
  30007. { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos,
  30008. startLoc, this.curPosition()); }
  30009. };
  30010. // Called at the start of the parse and after every token. Skips
  30011. // whitespace and comments, and.
  30012. pp.skipSpace = function() {
  30013. loop: while (this.pos < this.input.length) {
  30014. var ch = this.input.charCodeAt(this.pos);
  30015. switch (ch) {
  30016. case 32: case 160: // ' '
  30017. ++this.pos;
  30018. break
  30019. case 13:
  30020. if (this.input.charCodeAt(this.pos + 1) === 10) {
  30021. ++this.pos;
  30022. }
  30023. case 10: case 8232: case 8233:
  30024. ++this.pos;
  30025. if (this.options.locations) {
  30026. ++this.curLine;
  30027. this.lineStart = this.pos;
  30028. }
  30029. break
  30030. case 47: // '/'
  30031. switch (this.input.charCodeAt(this.pos + 1)) {
  30032. case 42: // '*'
  30033. this.skipBlockComment();
  30034. break
  30035. case 47:
  30036. this.skipLineComment(2);
  30037. break
  30038. default:
  30039. break loop
  30040. }
  30041. break
  30042. default:
  30043. if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
  30044. ++this.pos;
  30045. } else {
  30046. break loop
  30047. }
  30048. }
  30049. }
  30050. };
  30051. // Called at the end of every token. Sets `end`, `val`, and
  30052. // maintains `context` and `exprAllowed`, and skips the space after
  30053. // the token, so that the next one's `start` will point at the
  30054. // right position.
  30055. pp.finishToken = function(type, val) {
  30056. this.end = this.pos;
  30057. if (this.options.locations) { this.endLoc = this.curPosition(); }
  30058. var prevType = this.type;
  30059. this.type = type;
  30060. this.value = val;
  30061. this.updateContext(prevType);
  30062. };
  30063. // ### Token reading
  30064. // This is the function that is called to fetch the next token. It
  30065. // is somewhat obscure, because it works in character codes rather
  30066. // than characters, and because operator parsing has been inlined
  30067. // into it.
  30068. //
  30069. // All in the name of speed.
  30070. //
  30071. pp.readToken_dot = function() {
  30072. var next = this.input.charCodeAt(this.pos + 1);
  30073. if (next >= 48 && next <= 57) { return this.readNumber(true) }
  30074. var next2 = this.input.charCodeAt(this.pos + 2);
  30075. if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'
  30076. this.pos += 3;
  30077. return this.finishToken(types$1.ellipsis)
  30078. } else {
  30079. ++this.pos;
  30080. return this.finishToken(types$1.dot)
  30081. }
  30082. };
  30083. pp.readToken_slash = function() { // '/'
  30084. var next = this.input.charCodeAt(this.pos + 1);
  30085. if (this.exprAllowed) { ++this.pos; return this.readRegexp() }
  30086. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  30087. return this.finishOp(types$1.slash, 1)
  30088. };
  30089. pp.readToken_mult_modulo_exp = function(code) { // '%*'
  30090. var next = this.input.charCodeAt(this.pos + 1);
  30091. var size = 1;
  30092. var tokentype = code === 42 ? types$1.star : types$1.modulo;
  30093. // exponentiation operator ** and **=
  30094. if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) {
  30095. ++size;
  30096. tokentype = types$1.starstar;
  30097. next = this.input.charCodeAt(this.pos + 2);
  30098. }
  30099. if (next === 61) { return this.finishOp(types$1.assign, size + 1) }
  30100. return this.finishOp(tokentype, size)
  30101. };
  30102. pp.readToken_pipe_amp = function(code) { // '|&'
  30103. var next = this.input.charCodeAt(this.pos + 1);
  30104. if (next === code) {
  30105. if (this.options.ecmaVersion >= 12) {
  30106. var next2 = this.input.charCodeAt(this.pos + 2);
  30107. if (next2 === 61) { return this.finishOp(types$1.assign, 3) }
  30108. }
  30109. return this.finishOp(code === 124 ? types$1.logicalOR : types$1.logicalAND, 2)
  30110. }
  30111. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  30112. return this.finishOp(code === 124 ? types$1.bitwiseOR : types$1.bitwiseAND, 1)
  30113. };
  30114. pp.readToken_caret = function() { // '^'
  30115. var next = this.input.charCodeAt(this.pos + 1);
  30116. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  30117. return this.finishOp(types$1.bitwiseXOR, 1)
  30118. };
  30119. pp.readToken_plus_min = function(code) { // '+-'
  30120. var next = this.input.charCodeAt(this.pos + 1);
  30121. if (next === code) {
  30122. if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 &&
  30123. (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {
  30124. // A `-->` line comment
  30125. this.skipLineComment(3);
  30126. this.skipSpace();
  30127. return this.nextToken()
  30128. }
  30129. return this.finishOp(types$1.incDec, 2)
  30130. }
  30131. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  30132. return this.finishOp(types$1.plusMin, 1)
  30133. };
  30134. pp.readToken_lt_gt = function(code) { // '<>'
  30135. var next = this.input.charCodeAt(this.pos + 1);
  30136. var size = 1;
  30137. if (next === code) {
  30138. size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
  30139. if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types$1.assign, size + 1) }
  30140. return this.finishOp(types$1.bitShift, size)
  30141. }
  30142. if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 &&
  30143. this.input.charCodeAt(this.pos + 3) === 45) {
  30144. // `<!--`, an XML-style comment that should be interpreted as a line comment
  30145. this.skipLineComment(4);
  30146. this.skipSpace();
  30147. return this.nextToken()
  30148. }
  30149. if (next === 61) { size = 2; }
  30150. return this.finishOp(types$1.relational, size)
  30151. };
  30152. pp.readToken_eq_excl = function(code) { // '=!'
  30153. var next = this.input.charCodeAt(this.pos + 1);
  30154. if (next === 61) { return this.finishOp(types$1.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2) }
  30155. if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { // '=>'
  30156. this.pos += 2;
  30157. return this.finishToken(types$1.arrow)
  30158. }
  30159. return this.finishOp(code === 61 ? types$1.eq : types$1.prefix, 1)
  30160. };
  30161. pp.readToken_question = function() { // '?'
  30162. var ecmaVersion = this.options.ecmaVersion;
  30163. if (ecmaVersion >= 11) {
  30164. var next = this.input.charCodeAt(this.pos + 1);
  30165. if (next === 46) {
  30166. var next2 = this.input.charCodeAt(this.pos + 2);
  30167. if (next2 < 48 || next2 > 57) { return this.finishOp(types$1.questionDot, 2) }
  30168. }
  30169. if (next === 63) {
  30170. if (ecmaVersion >= 12) {
  30171. var next2$1 = this.input.charCodeAt(this.pos + 2);
  30172. if (next2$1 === 61) { return this.finishOp(types$1.assign, 3) }
  30173. }
  30174. return this.finishOp(types$1.coalesce, 2)
  30175. }
  30176. }
  30177. return this.finishOp(types$1.question, 1)
  30178. };
  30179. pp.readToken_numberSign = function() { // '#'
  30180. var ecmaVersion = this.options.ecmaVersion;
  30181. var code = 35; // '#'
  30182. if (ecmaVersion >= 13) {
  30183. ++this.pos;
  30184. code = this.fullCharCodeAtPos();
  30185. if (isIdentifierStart(code, true) || code === 92 /* '\' */) {
  30186. return this.finishToken(types$1.privateId, this.readWord1())
  30187. }
  30188. }
  30189. this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
  30190. };
  30191. pp.getTokenFromCode = function(code) {
  30192. switch (code) {
  30193. // The interpretation of a dot depends on whether it is followed
  30194. // by a digit or another two dots.
  30195. case 46: // '.'
  30196. return this.readToken_dot()
  30197. // Punctuation tokens.
  30198. case 40: ++this.pos; return this.finishToken(types$1.parenL)
  30199. case 41: ++this.pos; return this.finishToken(types$1.parenR)
  30200. case 59: ++this.pos; return this.finishToken(types$1.semi)
  30201. case 44: ++this.pos; return this.finishToken(types$1.comma)
  30202. case 91: ++this.pos; return this.finishToken(types$1.bracketL)
  30203. case 93: ++this.pos; return this.finishToken(types$1.bracketR)
  30204. case 123: ++this.pos; return this.finishToken(types$1.braceL)
  30205. case 125: ++this.pos; return this.finishToken(types$1.braceR)
  30206. case 58: ++this.pos; return this.finishToken(types$1.colon)
  30207. case 96: // '`'
  30208. if (this.options.ecmaVersion < 6) { break }
  30209. ++this.pos;
  30210. return this.finishToken(types$1.backQuote)
  30211. case 48: // '0'
  30212. var next = this.input.charCodeAt(this.pos + 1);
  30213. if (next === 120 || next === 88) { return this.readRadixNumber(16) } // '0x', '0X' - hex number
  30214. if (this.options.ecmaVersion >= 6) {
  30215. if (next === 111 || next === 79) { return this.readRadixNumber(8) } // '0o', '0O' - octal number
  30216. if (next === 98 || next === 66) { return this.readRadixNumber(2) } // '0b', '0B' - binary number
  30217. }
  30218. // Anything else beginning with a digit is an integer, octal
  30219. // number, or float.
  30220. case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9
  30221. return this.readNumber(false)
  30222. // Quotes produce strings.
  30223. case 34: case 39: // '"', "'"
  30224. return this.readString(code)
  30225. // Operators are parsed inline in tiny state machines. '=' (61) is
  30226. // often referred to. `finishOp` simply skips the amount of
  30227. // characters it is given as second argument, and returns a token
  30228. // of the type given by its first argument.
  30229. case 47: // '/'
  30230. return this.readToken_slash()
  30231. case 37: case 42: // '%*'
  30232. return this.readToken_mult_modulo_exp(code)
  30233. case 124: case 38: // '|&'
  30234. return this.readToken_pipe_amp(code)
  30235. case 94: // '^'
  30236. return this.readToken_caret()
  30237. case 43: case 45: // '+-'
  30238. return this.readToken_plus_min(code)
  30239. case 60: case 62: // '<>'
  30240. return this.readToken_lt_gt(code)
  30241. case 61: case 33: // '=!'
  30242. return this.readToken_eq_excl(code)
  30243. case 63: // '?'
  30244. return this.readToken_question()
  30245. case 126: // '~'
  30246. return this.finishOp(types$1.prefix, 1)
  30247. case 35: // '#'
  30248. return this.readToken_numberSign()
  30249. }
  30250. this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
  30251. };
  30252. pp.finishOp = function(type, size) {
  30253. var str = this.input.slice(this.pos, this.pos + size);
  30254. this.pos += size;
  30255. return this.finishToken(type, str)
  30256. };
  30257. pp.readRegexp = function() {
  30258. var escaped, inClass, start = this.pos;
  30259. for (;;) {
  30260. if (this.pos >= this.input.length) { this.raise(start, "Unterminated regular expression"); }
  30261. var ch = this.input.charAt(this.pos);
  30262. if (lineBreak.test(ch)) { this.raise(start, "Unterminated regular expression"); }
  30263. if (!escaped) {
  30264. if (ch === "[") { inClass = true; }
  30265. else if (ch === "]" && inClass) { inClass = false; }
  30266. else if (ch === "/" && !inClass) { break }
  30267. escaped = ch === "\\";
  30268. } else { escaped = false; }
  30269. ++this.pos;
  30270. }
  30271. var pattern = this.input.slice(start, this.pos);
  30272. ++this.pos;
  30273. var flagsStart = this.pos;
  30274. var flags = this.readWord1();
  30275. if (this.containsEsc) { this.unexpected(flagsStart); }
  30276. // Validate pattern
  30277. var state = this.regexpState || (this.regexpState = new RegExpValidationState(this));
  30278. state.reset(start, pattern, flags);
  30279. this.validateRegExpFlags(state);
  30280. this.validateRegExpPattern(state);
  30281. // Create Literal#value property value.
  30282. var value = null;
  30283. try {
  30284. value = new RegExp(pattern, flags);
  30285. } catch (e) {
  30286. // ESTree requires null if it failed to instantiate RegExp object.
  30287. // https://github.com/estree/estree/blob/a27003adf4fd7bfad44de9cef372a2eacd527b1c/es5.md#regexpliteral
  30288. }
  30289. return this.finishToken(types$1.regexp, {pattern: pattern, flags: flags, value: value})
  30290. };
  30291. // Read an integer in the given radix. Return null if zero digits
  30292. // were read, the integer value otherwise. When `len` is given, this
  30293. // will return `null` unless the integer has exactly `len` digits.
  30294. pp.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) {
  30295. // `len` is used for character escape sequences. In that case, disallow separators.
  30296. var allowSeparators = this.options.ecmaVersion >= 12 && len === undefined;
  30297. // `maybeLegacyOctalNumericLiteral` is true if it doesn't have prefix (0x,0o,0b)
  30298. // and isn't fraction part nor exponent part. In that case, if the first digit
  30299. // is zero then disallow separators.
  30300. var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48;
  30301. var start = this.pos, total = 0, lastCode = 0;
  30302. for (var i = 0, e = len == null ? Infinity : len; i < e; ++i, ++this.pos) {
  30303. var code = this.input.charCodeAt(this.pos), val = (void 0);
  30304. if (allowSeparators && code === 95) {
  30305. if (isLegacyOctalNumericLiteral) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals"); }
  30306. if (lastCode === 95) { this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore"); }
  30307. if (i === 0) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits"); }
  30308. lastCode = code;
  30309. continue
  30310. }
  30311. if (code >= 97) { val = code - 97 + 10; } // a
  30312. else if (code >= 65) { val = code - 65 + 10; } // A
  30313. else if (code >= 48 && code <= 57) { val = code - 48; } // 0-9
  30314. else { val = Infinity; }
  30315. if (val >= radix) { break }
  30316. lastCode = code;
  30317. total = total * radix + val;
  30318. }
  30319. if (allowSeparators && lastCode === 95) { this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits"); }
  30320. if (this.pos === start || len != null && this.pos - start !== len) { return null }
  30321. return total
  30322. };
  30323. function stringToNumber(str, isLegacyOctalNumericLiteral) {
  30324. if (isLegacyOctalNumericLiteral) {
  30325. return parseInt(str, 8)
  30326. }
  30327. // `parseFloat(value)` stops parsing at the first numeric separator then returns a wrong value.
  30328. return parseFloat(str.replace(/_/g, ""))
  30329. }
  30330. function stringToBigInt(str) {
  30331. if (typeof BigInt !== "function") {
  30332. return null
  30333. }
  30334. // `BigInt(value)` throws syntax error if the string contains numeric separators.
  30335. return BigInt(str.replace(/_/g, ""))
  30336. }
  30337. pp.readRadixNumber = function(radix) {
  30338. var start = this.pos;
  30339. this.pos += 2; // 0x
  30340. var val = this.readInt(radix);
  30341. if (val == null) { this.raise(this.start + 2, "Expected number in radix " + radix); }
  30342. if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
  30343. val = stringToBigInt(this.input.slice(start, this.pos));
  30344. ++this.pos;
  30345. } else if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  30346. return this.finishToken(types$1.num, val)
  30347. };
  30348. // Read an integer, octal integer, or floating-point number.
  30349. pp.readNumber = function(startsWithDot) {
  30350. var start = this.pos;
  30351. if (!startsWithDot && this.readInt(10, undefined, true) === null) { this.raise(start, "Invalid number"); }
  30352. var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  30353. if (octal && this.strict) { this.raise(start, "Invalid number"); }
  30354. var next = this.input.charCodeAt(this.pos);
  30355. if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {
  30356. var val$1 = stringToBigInt(this.input.slice(start, this.pos));
  30357. ++this.pos;
  30358. if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  30359. return this.finishToken(types$1.num, val$1)
  30360. }
  30361. if (octal && /[89]/.test(this.input.slice(start, this.pos))) { octal = false; }
  30362. if (next === 46 && !octal) { // '.'
  30363. ++this.pos;
  30364. this.readInt(10);
  30365. next = this.input.charCodeAt(this.pos);
  30366. }
  30367. if ((next === 69 || next === 101) && !octal) { // 'eE'
  30368. next = this.input.charCodeAt(++this.pos);
  30369. if (next === 43 || next === 45) { ++this.pos; } // '+-'
  30370. if (this.readInt(10) === null) { this.raise(start, "Invalid number"); }
  30371. }
  30372. if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  30373. var val = stringToNumber(this.input.slice(start, this.pos), octal);
  30374. return this.finishToken(types$1.num, val)
  30375. };
  30376. // Read a string value, interpreting backslash-escapes.
  30377. pp.readCodePoint = function() {
  30378. var ch = this.input.charCodeAt(this.pos), code;
  30379. if (ch === 123) { // '{'
  30380. if (this.options.ecmaVersion < 6) { this.unexpected(); }
  30381. var codePos = ++this.pos;
  30382. code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
  30383. ++this.pos;
  30384. if (code > 0x10FFFF) { this.invalidStringToken(codePos, "Code point out of bounds"); }
  30385. } else {
  30386. code = this.readHexChar(4);
  30387. }
  30388. return code
  30389. };
  30390. pp.readString = function(quote) {
  30391. var out = "", chunkStart = ++this.pos;
  30392. for (;;) {
  30393. if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated string constant"); }
  30394. var ch = this.input.charCodeAt(this.pos);
  30395. if (ch === quote) { break }
  30396. if (ch === 92) { // '\'
  30397. out += this.input.slice(chunkStart, this.pos);
  30398. out += this.readEscapedChar(false);
  30399. chunkStart = this.pos;
  30400. } else if (ch === 0x2028 || ch === 0x2029) {
  30401. if (this.options.ecmaVersion < 10) { this.raise(this.start, "Unterminated string constant"); }
  30402. ++this.pos;
  30403. if (this.options.locations) {
  30404. this.curLine++;
  30405. this.lineStart = this.pos;
  30406. }
  30407. } else {
  30408. if (isNewLine(ch)) { this.raise(this.start, "Unterminated string constant"); }
  30409. ++this.pos;
  30410. }
  30411. }
  30412. out += this.input.slice(chunkStart, this.pos++);
  30413. return this.finishToken(types$1.string, out)
  30414. };
  30415. // Reads template string tokens.
  30416. var INVALID_TEMPLATE_ESCAPE_ERROR = {};
  30417. pp.tryReadTemplateToken = function() {
  30418. this.inTemplateElement = true;
  30419. try {
  30420. this.readTmplToken();
  30421. } catch (err) {
  30422. if (err === INVALID_TEMPLATE_ESCAPE_ERROR) {
  30423. this.readInvalidTemplateToken();
  30424. } else {
  30425. throw err
  30426. }
  30427. }
  30428. this.inTemplateElement = false;
  30429. };
  30430. pp.invalidStringToken = function(position, message) {
  30431. if (this.inTemplateElement && this.options.ecmaVersion >= 9) {
  30432. throw INVALID_TEMPLATE_ESCAPE_ERROR
  30433. } else {
  30434. this.raise(position, message);
  30435. }
  30436. };
  30437. pp.readTmplToken = function() {
  30438. var out = "", chunkStart = this.pos;
  30439. for (;;) {
  30440. if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated template"); }
  30441. var ch = this.input.charCodeAt(this.pos);
  30442. if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) { // '`', '${'
  30443. if (this.pos === this.start && (this.type === types$1.template || this.type === types$1.invalidTemplate)) {
  30444. if (ch === 36) {
  30445. this.pos += 2;
  30446. return this.finishToken(types$1.dollarBraceL)
  30447. } else {
  30448. ++this.pos;
  30449. return this.finishToken(types$1.backQuote)
  30450. }
  30451. }
  30452. out += this.input.slice(chunkStart, this.pos);
  30453. return this.finishToken(types$1.template, out)
  30454. }
  30455. if (ch === 92) { // '\'
  30456. out += this.input.slice(chunkStart, this.pos);
  30457. out += this.readEscapedChar(true);
  30458. chunkStart = this.pos;
  30459. } else if (isNewLine(ch)) {
  30460. out += this.input.slice(chunkStart, this.pos);
  30461. ++this.pos;
  30462. switch (ch) {
  30463. case 13:
  30464. if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; }
  30465. case 10:
  30466. out += "\n";
  30467. break
  30468. default:
  30469. out += String.fromCharCode(ch);
  30470. break
  30471. }
  30472. if (this.options.locations) {
  30473. ++this.curLine;
  30474. this.lineStart = this.pos;
  30475. }
  30476. chunkStart = this.pos;
  30477. } else {
  30478. ++this.pos;
  30479. }
  30480. }
  30481. };
  30482. // Reads a template token to search for the end, without validating any escape sequences
  30483. pp.readInvalidTemplateToken = function() {
  30484. for (; this.pos < this.input.length; this.pos++) {
  30485. switch (this.input[this.pos]) {
  30486. case "\\":
  30487. ++this.pos;
  30488. break
  30489. case "$":
  30490. if (this.input[this.pos + 1] !== "{") {
  30491. break
  30492. }
  30493. // falls through
  30494. case "`":
  30495. return this.finishToken(types$1.invalidTemplate, this.input.slice(this.start, this.pos))
  30496. // no default
  30497. }
  30498. }
  30499. this.raise(this.start, "Unterminated template");
  30500. };
  30501. // Used to read escaped characters
  30502. pp.readEscapedChar = function(inTemplate) {
  30503. var ch = this.input.charCodeAt(++this.pos);
  30504. ++this.pos;
  30505. switch (ch) {
  30506. case 110: return "\n" // 'n' -> '\n'
  30507. case 114: return "\r" // 'r' -> '\r'
  30508. case 120: return String.fromCharCode(this.readHexChar(2)) // 'x'
  30509. case 117: return codePointToString(this.readCodePoint()) // 'u'
  30510. case 116: return "\t" // 't' -> '\t'
  30511. case 98: return "\b" // 'b' -> '\b'
  30512. case 118: return "\u000b" // 'v' -> '\u000b'
  30513. case 102: return "\f" // 'f' -> '\f'
  30514. case 13: if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; } // '\r\n'
  30515. case 10: // ' \n'
  30516. if (this.options.locations) { this.lineStart = this.pos; ++this.curLine; }
  30517. return ""
  30518. case 56:
  30519. case 57:
  30520. if (this.strict) {
  30521. this.invalidStringToken(
  30522. this.pos - 1,
  30523. "Invalid escape sequence"
  30524. );
  30525. }
  30526. if (inTemplate) {
  30527. var codePos = this.pos - 1;
  30528. this.invalidStringToken(
  30529. codePos,
  30530. "Invalid escape sequence in template string"
  30531. );
  30532. return null
  30533. }
  30534. default:
  30535. if (ch >= 48 && ch <= 55) {
  30536. var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
  30537. var octal = parseInt(octalStr, 8);
  30538. if (octal > 255) {
  30539. octalStr = octalStr.slice(0, -1);
  30540. octal = parseInt(octalStr, 8);
  30541. }
  30542. this.pos += octalStr.length - 1;
  30543. ch = this.input.charCodeAt(this.pos);
  30544. if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) {
  30545. this.invalidStringToken(
  30546. this.pos - 1 - octalStr.length,
  30547. inTemplate
  30548. ? "Octal literal in template string"
  30549. : "Octal literal in strict mode"
  30550. );
  30551. }
  30552. return String.fromCharCode(octal)
  30553. }
  30554. if (isNewLine(ch)) {
  30555. // Unicode new line characters after \ get removed from output in both
  30556. // template literals and strings
  30557. return ""
  30558. }
  30559. return String.fromCharCode(ch)
  30560. }
  30561. };
  30562. // Used to read character escape sequences ('\x', '\u', '\U').
  30563. pp.readHexChar = function(len) {
  30564. var codePos = this.pos;
  30565. var n = this.readInt(16, len);
  30566. if (n === null) { this.invalidStringToken(codePos, "Bad character escape sequence"); }
  30567. return n
  30568. };
  30569. // Read an identifier, and return it as a string. Sets `this.containsEsc`
  30570. // to whether the word contained a '\u' escape.
  30571. //
  30572. // Incrementally adds only escaped chars, adding other chunks as-is
  30573. // as a micro-optimization.
  30574. pp.readWord1 = function() {
  30575. this.containsEsc = false;
  30576. var word = "", first = true, chunkStart = this.pos;
  30577. var astral = this.options.ecmaVersion >= 6;
  30578. while (this.pos < this.input.length) {
  30579. var ch = this.fullCharCodeAtPos();
  30580. if (isIdentifierChar(ch, astral)) {
  30581. this.pos += ch <= 0xffff ? 1 : 2;
  30582. } else if (ch === 92) { // "\"
  30583. this.containsEsc = true;
  30584. word += this.input.slice(chunkStart, this.pos);
  30585. var escStart = this.pos;
  30586. if (this.input.charCodeAt(++this.pos) !== 117) // "u"
  30587. { this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX"); }
  30588. ++this.pos;
  30589. var esc = this.readCodePoint();
  30590. if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral))
  30591. { this.invalidStringToken(escStart, "Invalid Unicode escape"); }
  30592. word += codePointToString(esc);
  30593. chunkStart = this.pos;
  30594. } else {
  30595. break
  30596. }
  30597. first = false;
  30598. }
  30599. return word + this.input.slice(chunkStart, this.pos)
  30600. };
  30601. // Read an identifier or keyword token. Will check for reserved
  30602. // words when necessary.
  30603. pp.readWord = function() {
  30604. var word = this.readWord1();
  30605. var type = types$1.name;
  30606. if (this.keywords.test(word)) {
  30607. type = keywords[word];
  30608. }
  30609. return this.finishToken(type, word)
  30610. };
  30611. // Acorn is a tiny, fast JavaScript parser written in JavaScript.
  30612. var version = "8.7.1";
  30613. Parser.acorn = {
  30614. Parser: Parser,
  30615. version: version,
  30616. defaultOptions: defaultOptions,
  30617. Position: Position,
  30618. SourceLocation: SourceLocation,
  30619. getLineInfo: getLineInfo,
  30620. Node: Node,
  30621. TokenType: TokenType,
  30622. tokTypes: types$1,
  30623. keywordTypes: keywords,
  30624. TokContext: TokContext,
  30625. tokContexts: types,
  30626. isIdentifierChar: isIdentifierChar,
  30627. isIdentifierStart: isIdentifierStart,
  30628. Token: Token,
  30629. isNewLine: isNewLine,
  30630. lineBreak: lineBreak,
  30631. lineBreakG: lineBreakG,
  30632. nonASCIIwhitespace: nonASCIIwhitespace
  30633. };
  30634. // The main exported interface (under `self.acorn` when in the
  30635. // browser) is a `parse` function that takes a code string and
  30636. // returns an abstract syntax tree as specified by [Mozilla parser
  30637. // API][api].
  30638. //
  30639. // [api]: https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API
  30640. function parse$a(input, options) {
  30641. return Parser.parse(input, options)
  30642. }
  30643. // This function tries to parse a single expression at a given
  30644. // offset in a string. Useful for parsing mixed-language formats
  30645. // that embed JavaScript expressions.
  30646. function parseExpressionAt(input, pos, options) {
  30647. return Parser.parseExpressionAt(input, pos, options)
  30648. }
  30649. // Acorn is organized as a tokenizer and a recursive-descent parser.
  30650. // The `tokenizer` export provides an interface to the tokenizer.
  30651. function tokenizer(input, options) {
  30652. return Parser.tokenizer(input, options)
  30653. }
  30654. var acorn = {
  30655. __proto__: null,
  30656. Node: Node,
  30657. Parser: Parser,
  30658. Position: Position,
  30659. SourceLocation: SourceLocation,
  30660. TokContext: TokContext,
  30661. Token: Token,
  30662. TokenType: TokenType,
  30663. defaultOptions: defaultOptions,
  30664. getLineInfo: getLineInfo,
  30665. isIdentifierChar: isIdentifierChar,
  30666. isIdentifierStart: isIdentifierStart,
  30667. isNewLine: isNewLine,
  30668. keywordTypes: keywords,
  30669. lineBreak: lineBreak,
  30670. lineBreakG: lineBreakG,
  30671. nonASCIIwhitespace: nonASCIIwhitespace,
  30672. parse: parse$a,
  30673. parseExpressionAt: parseExpressionAt,
  30674. tokContexts: types,
  30675. tokTypes: types$1,
  30676. tokenizer: tokenizer,
  30677. version: version
  30678. };
  30679. function stripLiteral(code) {
  30680. const FILL = " ";
  30681. let result = "";
  30682. function fulfill(index) {
  30683. if (index > result.length)
  30684. result += code.slice(result.length, index).replace(/[^\n]/g, FILL);
  30685. }
  30686. const tokens = tokenizer(code, {
  30687. ecmaVersion: "latest",
  30688. sourceType: "module"
  30689. });
  30690. for (const token of tokens) {
  30691. fulfill(token.start);
  30692. if (token.type.label === "string")
  30693. result += code[token.start] + FILL.repeat(token.end - token.start - 2) + code[token.end - 1];
  30694. else if (token.type.label === "template")
  30695. result += FILL.repeat(token.end - token.start);
  30696. else
  30697. result += code.slice(token.start, token.end);
  30698. }
  30699. fulfill(code.length);
  30700. return result;
  30701. }
  30702. const mimes$1 = {
  30703. "ez": "application/andrew-inset",
  30704. "aw": "application/applixware",
  30705. "atom": "application/atom+xml",
  30706. "atomcat": "application/atomcat+xml",
  30707. "atomdeleted": "application/atomdeleted+xml",
  30708. "atomsvc": "application/atomsvc+xml",
  30709. "dwd": "application/atsc-dwd+xml",
  30710. "held": "application/atsc-held+xml",
  30711. "rsat": "application/atsc-rsat+xml",
  30712. "bdoc": "application/bdoc",
  30713. "xcs": "application/calendar+xml",
  30714. "ccxml": "application/ccxml+xml",
  30715. "cdfx": "application/cdfx+xml",
  30716. "cdmia": "application/cdmi-capability",
  30717. "cdmic": "application/cdmi-container",
  30718. "cdmid": "application/cdmi-domain",
  30719. "cdmio": "application/cdmi-object",
  30720. "cdmiq": "application/cdmi-queue",
  30721. "cu": "application/cu-seeme",
  30722. "mpd": "application/dash+xml",
  30723. "davmount": "application/davmount+xml",
  30724. "dbk": "application/docbook+xml",
  30725. "dssc": "application/dssc+der",
  30726. "xdssc": "application/dssc+xml",
  30727. "es": "application/ecmascript",
  30728. "ecma": "application/ecmascript",
  30729. "emma": "application/emma+xml",
  30730. "emotionml": "application/emotionml+xml",
  30731. "epub": "application/epub+zip",
  30732. "exi": "application/exi",
  30733. "fdt": "application/fdt+xml",
  30734. "pfr": "application/font-tdpfr",
  30735. "geojson": "application/geo+json",
  30736. "gml": "application/gml+xml",
  30737. "gpx": "application/gpx+xml",
  30738. "gxf": "application/gxf",
  30739. "gz": "application/gzip",
  30740. "hjson": "application/hjson",
  30741. "stk": "application/hyperstudio",
  30742. "ink": "application/inkml+xml",
  30743. "inkml": "application/inkml+xml",
  30744. "ipfix": "application/ipfix",
  30745. "its": "application/its+xml",
  30746. "jar": "application/java-archive",
  30747. "war": "application/java-archive",
  30748. "ear": "application/java-archive",
  30749. "ser": "application/java-serialized-object",
  30750. "class": "application/java-vm",
  30751. "js": "application/javascript",
  30752. "mjs": "application/javascript",
  30753. "json": "application/json",
  30754. "map": "application/json",
  30755. "json5": "application/json5",
  30756. "jsonml": "application/jsonml+json",
  30757. "jsonld": "application/ld+json",
  30758. "lgr": "application/lgr+xml",
  30759. "lostxml": "application/lost+xml",
  30760. "hqx": "application/mac-binhex40",
  30761. "cpt": "application/mac-compactpro",
  30762. "mads": "application/mads+xml",
  30763. "webmanifest": "application/manifest+json",
  30764. "mrc": "application/marc",
  30765. "mrcx": "application/marcxml+xml",
  30766. "ma": "application/mathematica",
  30767. "nb": "application/mathematica",
  30768. "mb": "application/mathematica",
  30769. "mathml": "application/mathml+xml",
  30770. "mbox": "application/mbox",
  30771. "mscml": "application/mediaservercontrol+xml",
  30772. "metalink": "application/metalink+xml",
  30773. "meta4": "application/metalink4+xml",
  30774. "mets": "application/mets+xml",
  30775. "maei": "application/mmt-aei+xml",
  30776. "musd": "application/mmt-usd+xml",
  30777. "mods": "application/mods+xml",
  30778. "m21": "application/mp21",
  30779. "mp21": "application/mp21",
  30780. "mp4s": "application/mp4",
  30781. "m4p": "application/mp4",
  30782. "doc": "application/msword",
  30783. "dot": "application/msword",
  30784. "mxf": "application/mxf",
  30785. "nq": "application/n-quads",
  30786. "nt": "application/n-triples",
  30787. "cjs": "application/node",
  30788. "bin": "application/octet-stream",
  30789. "dms": "application/octet-stream",
  30790. "lrf": "application/octet-stream",
  30791. "mar": "application/octet-stream",
  30792. "so": "application/octet-stream",
  30793. "dist": "application/octet-stream",
  30794. "distz": "application/octet-stream",
  30795. "pkg": "application/octet-stream",
  30796. "bpk": "application/octet-stream",
  30797. "dump": "application/octet-stream",
  30798. "elc": "application/octet-stream",
  30799. "deploy": "application/octet-stream",
  30800. "exe": "application/octet-stream",
  30801. "dll": "application/octet-stream",
  30802. "deb": "application/octet-stream",
  30803. "dmg": "application/octet-stream",
  30804. "iso": "application/octet-stream",
  30805. "img": "application/octet-stream",
  30806. "msi": "application/octet-stream",
  30807. "msp": "application/octet-stream",
  30808. "msm": "application/octet-stream",
  30809. "buffer": "application/octet-stream",
  30810. "oda": "application/oda",
  30811. "opf": "application/oebps-package+xml",
  30812. "ogx": "application/ogg",
  30813. "omdoc": "application/omdoc+xml",
  30814. "onetoc": "application/onenote",
  30815. "onetoc2": "application/onenote",
  30816. "onetmp": "application/onenote",
  30817. "onepkg": "application/onenote",
  30818. "oxps": "application/oxps",
  30819. "relo": "application/p2p-overlay+xml",
  30820. "xer": "application/patch-ops-error+xml",
  30821. "pdf": "application/pdf",
  30822. "pgp": "application/pgp-encrypted",
  30823. "asc": "application/pgp-signature",
  30824. "sig": "application/pgp-signature",
  30825. "prf": "application/pics-rules",
  30826. "p10": "application/pkcs10",
  30827. "p7m": "application/pkcs7-mime",
  30828. "p7c": "application/pkcs7-mime",
  30829. "p7s": "application/pkcs7-signature",
  30830. "p8": "application/pkcs8",
  30831. "ac": "application/pkix-attr-cert",
  30832. "cer": "application/pkix-cert",
  30833. "crl": "application/pkix-crl",
  30834. "pkipath": "application/pkix-pkipath",
  30835. "pki": "application/pkixcmp",
  30836. "pls": "application/pls+xml",
  30837. "ai": "application/postscript",
  30838. "eps": "application/postscript",
  30839. "ps": "application/postscript",
  30840. "provx": "application/provenance+xml",
  30841. "cww": "application/prs.cww",
  30842. "pskcxml": "application/pskc+xml",
  30843. "raml": "application/raml+yaml",
  30844. "rdf": "application/rdf+xml",
  30845. "owl": "application/rdf+xml",
  30846. "rif": "application/reginfo+xml",
  30847. "rnc": "application/relax-ng-compact-syntax",
  30848. "rl": "application/resource-lists+xml",
  30849. "rld": "application/resource-lists-diff+xml",
  30850. "rs": "application/rls-services+xml",
  30851. "rapd": "application/route-apd+xml",
  30852. "sls": "application/route-s-tsid+xml",
  30853. "rusd": "application/route-usd+xml",
  30854. "gbr": "application/rpki-ghostbusters",
  30855. "mft": "application/rpki-manifest",
  30856. "roa": "application/rpki-roa",
  30857. "rsd": "application/rsd+xml",
  30858. "rss": "application/rss+xml",
  30859. "rtf": "application/rtf",
  30860. "sbml": "application/sbml+xml",
  30861. "scq": "application/scvp-cv-request",
  30862. "scs": "application/scvp-cv-response",
  30863. "spq": "application/scvp-vp-request",
  30864. "spp": "application/scvp-vp-response",
  30865. "sdp": "application/sdp",
  30866. "senmlx": "application/senml+xml",
  30867. "sensmlx": "application/sensml+xml",
  30868. "setpay": "application/set-payment-initiation",
  30869. "setreg": "application/set-registration-initiation",
  30870. "shf": "application/shf+xml",
  30871. "siv": "application/sieve",
  30872. "sieve": "application/sieve",
  30873. "smi": "application/smil+xml",
  30874. "smil": "application/smil+xml",
  30875. "rq": "application/sparql-query",
  30876. "srx": "application/sparql-results+xml",
  30877. "gram": "application/srgs",
  30878. "grxml": "application/srgs+xml",
  30879. "sru": "application/sru+xml",
  30880. "ssdl": "application/ssdl+xml",
  30881. "ssml": "application/ssml+xml",
  30882. "swidtag": "application/swid+xml",
  30883. "tei": "application/tei+xml",
  30884. "teicorpus": "application/tei+xml",
  30885. "tfi": "application/thraud+xml",
  30886. "tsd": "application/timestamped-data",
  30887. "toml": "application/toml",
  30888. "trig": "application/trig",
  30889. "ttml": "application/ttml+xml",
  30890. "ubj": "application/ubjson",
  30891. "rsheet": "application/urc-ressheet+xml",
  30892. "td": "application/urc-targetdesc+xml",
  30893. "vxml": "application/voicexml+xml",
  30894. "wasm": "application/wasm",
  30895. "wgt": "application/widget",
  30896. "hlp": "application/winhlp",
  30897. "wsdl": "application/wsdl+xml",
  30898. "wspolicy": "application/wspolicy+xml",
  30899. "xaml": "application/xaml+xml",
  30900. "xav": "application/xcap-att+xml",
  30901. "xca": "application/xcap-caps+xml",
  30902. "xdf": "application/xcap-diff+xml",
  30903. "xel": "application/xcap-el+xml",
  30904. "xns": "application/xcap-ns+xml",
  30905. "xenc": "application/xenc+xml",
  30906. "xhtml": "application/xhtml+xml",
  30907. "xht": "application/xhtml+xml",
  30908. "xlf": "application/xliff+xml",
  30909. "xml": "application/xml",
  30910. "xsl": "application/xml",
  30911. "xsd": "application/xml",
  30912. "rng": "application/xml",
  30913. "dtd": "application/xml-dtd",
  30914. "xop": "application/xop+xml",
  30915. "xpl": "application/xproc+xml",
  30916. "xslt": "application/xml",
  30917. "xspf": "application/xspf+xml",
  30918. "mxml": "application/xv+xml",
  30919. "xhvml": "application/xv+xml",
  30920. "xvml": "application/xv+xml",
  30921. "xvm": "application/xv+xml",
  30922. "yang": "application/yang",
  30923. "yin": "application/yin+xml",
  30924. "zip": "application/zip",
  30925. "3gpp": "video/3gpp",
  30926. "adp": "audio/adpcm",
  30927. "amr": "audio/amr",
  30928. "au": "audio/basic",
  30929. "snd": "audio/basic",
  30930. "mid": "audio/midi",
  30931. "midi": "audio/midi",
  30932. "kar": "audio/midi",
  30933. "rmi": "audio/midi",
  30934. "mxmf": "audio/mobile-xmf",
  30935. "mp3": "audio/mpeg",
  30936. "m4a": "audio/mp4",
  30937. "mp4a": "audio/mp4",
  30938. "mpga": "audio/mpeg",
  30939. "mp2": "audio/mpeg",
  30940. "mp2a": "audio/mpeg",
  30941. "m2a": "audio/mpeg",
  30942. "m3a": "audio/mpeg",
  30943. "oga": "audio/ogg",
  30944. "ogg": "audio/ogg",
  30945. "spx": "audio/ogg",
  30946. "opus": "audio/ogg",
  30947. "s3m": "audio/s3m",
  30948. "sil": "audio/silk",
  30949. "wav": "audio/wav",
  30950. "weba": "audio/webm",
  30951. "xm": "audio/xm",
  30952. "ttc": "font/collection",
  30953. "otf": "font/otf",
  30954. "ttf": "font/ttf",
  30955. "woff": "font/woff",
  30956. "woff2": "font/woff2",
  30957. "exr": "image/aces",
  30958. "apng": "image/apng",
  30959. "avif": "image/avif",
  30960. "bmp": "image/bmp",
  30961. "cgm": "image/cgm",
  30962. "drle": "image/dicom-rle",
  30963. "emf": "image/emf",
  30964. "fits": "image/fits",
  30965. "g3": "image/g3fax",
  30966. "gif": "image/gif",
  30967. "heic": "image/heic",
  30968. "heics": "image/heic-sequence",
  30969. "heif": "image/heif",
  30970. "heifs": "image/heif-sequence",
  30971. "hej2": "image/hej2k",
  30972. "hsj2": "image/hsj2",
  30973. "ief": "image/ief",
  30974. "jls": "image/jls",
  30975. "jp2": "image/jp2",
  30976. "jpg2": "image/jp2",
  30977. "jpeg": "image/jpeg",
  30978. "jpg": "image/jpeg",
  30979. "jpe": "image/jpeg",
  30980. "jph": "image/jph",
  30981. "jhc": "image/jphc",
  30982. "jpm": "image/jpm",
  30983. "jpx": "image/jpx",
  30984. "jpf": "image/jpx",
  30985. "jxr": "image/jxr",
  30986. "jxra": "image/jxra",
  30987. "jxrs": "image/jxrs",
  30988. "jxs": "image/jxs",
  30989. "jxsc": "image/jxsc",
  30990. "jxsi": "image/jxsi",
  30991. "jxss": "image/jxss",
  30992. "ktx": "image/ktx",
  30993. "ktx2": "image/ktx2",
  30994. "png": "image/png",
  30995. "btif": "image/prs.btif",
  30996. "pti": "image/prs.pti",
  30997. "sgi": "image/sgi",
  30998. "svg": "image/svg+xml",
  30999. "svgz": "image/svg+xml",
  31000. "t38": "image/t38",
  31001. "tif": "image/tiff",
  31002. "tiff": "image/tiff",
  31003. "tfx": "image/tiff-fx",
  31004. "webp": "image/webp",
  31005. "wmf": "image/wmf",
  31006. "disposition-notification": "message/disposition-notification",
  31007. "u8msg": "message/global",
  31008. "u8dsn": "message/global-delivery-status",
  31009. "u8mdn": "message/global-disposition-notification",
  31010. "u8hdr": "message/global-headers",
  31011. "eml": "message/rfc822",
  31012. "mime": "message/rfc822",
  31013. "3mf": "model/3mf",
  31014. "gltf": "model/gltf+json",
  31015. "glb": "model/gltf-binary",
  31016. "igs": "model/iges",
  31017. "iges": "model/iges",
  31018. "msh": "model/mesh",
  31019. "mesh": "model/mesh",
  31020. "silo": "model/mesh",
  31021. "mtl": "model/mtl",
  31022. "obj": "model/obj",
  31023. "stpz": "model/step+zip",
  31024. "stpxz": "model/step-xml+zip",
  31025. "stl": "model/stl",
  31026. "wrl": "model/vrml",
  31027. "vrml": "model/vrml",
  31028. "x3db": "model/x3d+fastinfoset",
  31029. "x3dbz": "model/x3d+binary",
  31030. "x3dv": "model/x3d-vrml",
  31031. "x3dvz": "model/x3d+vrml",
  31032. "x3d": "model/x3d+xml",
  31033. "x3dz": "model/x3d+xml",
  31034. "appcache": "text/cache-manifest",
  31035. "manifest": "text/cache-manifest",
  31036. "ics": "text/calendar",
  31037. "ifb": "text/calendar",
  31038. "coffee": "text/coffeescript",
  31039. "litcoffee": "text/coffeescript",
  31040. "css": "text/css",
  31041. "csv": "text/csv",
  31042. "html": "text/html",
  31043. "htm": "text/html",
  31044. "shtml": "text/html",
  31045. "jade": "text/jade",
  31046. "jsx": "text/jsx",
  31047. "less": "text/less",
  31048. "markdown": "text/markdown",
  31049. "md": "text/markdown",
  31050. "mml": "text/mathml",
  31051. "mdx": "text/mdx",
  31052. "n3": "text/n3",
  31053. "txt": "text/plain",
  31054. "text": "text/plain",
  31055. "conf": "text/plain",
  31056. "def": "text/plain",
  31057. "list": "text/plain",
  31058. "log": "text/plain",
  31059. "in": "text/plain",
  31060. "ini": "text/plain",
  31061. "dsc": "text/prs.lines.tag",
  31062. "rtx": "text/richtext",
  31063. "sgml": "text/sgml",
  31064. "sgm": "text/sgml",
  31065. "shex": "text/shex",
  31066. "slim": "text/slim",
  31067. "slm": "text/slim",
  31068. "spdx": "text/spdx",
  31069. "stylus": "text/stylus",
  31070. "styl": "text/stylus",
  31071. "tsv": "text/tab-separated-values",
  31072. "t": "text/troff",
  31073. "tr": "text/troff",
  31074. "roff": "text/troff",
  31075. "man": "text/troff",
  31076. "me": "text/troff",
  31077. "ms": "text/troff",
  31078. "ttl": "text/turtle",
  31079. "uri": "text/uri-list",
  31080. "uris": "text/uri-list",
  31081. "urls": "text/uri-list",
  31082. "vcard": "text/vcard",
  31083. "vtt": "text/vtt",
  31084. "yaml": "text/yaml",
  31085. "yml": "text/yaml",
  31086. "3gp": "video/3gpp",
  31087. "3g2": "video/3gpp2",
  31088. "h261": "video/h261",
  31089. "h263": "video/h263",
  31090. "h264": "video/h264",
  31091. "m4s": "video/iso.segment",
  31092. "jpgv": "video/jpeg",
  31093. "jpgm": "image/jpm",
  31094. "mj2": "video/mj2",
  31095. "mjp2": "video/mj2",
  31096. "ts": "video/mp2t",
  31097. "mp4": "video/mp4",
  31098. "mp4v": "video/mp4",
  31099. "mpg4": "video/mp4",
  31100. "mpeg": "video/mpeg",
  31101. "mpg": "video/mpeg",
  31102. "mpe": "video/mpeg",
  31103. "m1v": "video/mpeg",
  31104. "m2v": "video/mpeg",
  31105. "ogv": "video/ogg",
  31106. "qt": "video/quicktime",
  31107. "mov": "video/quicktime",
  31108. "webm": "video/webm"
  31109. };
  31110. function lookup(extn) {
  31111. let tmp = ('' + extn).trim().toLowerCase();
  31112. let idx = tmp.lastIndexOf('.');
  31113. return mimes$1[!~idx ? tmp : tmp.substring(++idx)];
  31114. }
  31115. const assetUrlRE = /__VITE_ASSET__([a-z\d]{8})__(?:\$_(.*?)__)?/g;
  31116. const rawRE = /(\?|&)raw(?:&|$)/;
  31117. const urlRE = /(\?|&)url(?:&|$)/;
  31118. const assetCache = new WeakMap();
  31119. const assetHashToFilenameMap = new WeakMap();
  31120. // save hashes of the files that has been emitted in build watch
  31121. const emittedHashMap = new WeakMap();
  31122. /**
  31123. * Also supports loading plain strings with import text from './foo.txt?raw'
  31124. */
  31125. function assetPlugin(config) {
  31126. // assetHashToFilenameMap initialization in buildStart causes getAssetFilename to return undefined
  31127. assetHashToFilenameMap.set(config, new Map());
  31128. // add own dictionary entry by directly assigning mrmine
  31129. // https://github.com/lukeed/mrmime/issues/3
  31130. mimes$1['ico'] = 'image/x-icon';
  31131. return {
  31132. name: 'vite:asset',
  31133. buildStart() {
  31134. assetCache.set(config, new Map());
  31135. emittedHashMap.set(config, new Set());
  31136. },
  31137. resolveId(id) {
  31138. if (!config.assetsInclude(cleanUrl(id))) {
  31139. return;
  31140. }
  31141. // imports to absolute urls pointing to files in /public
  31142. // will fail to resolve in the main resolver. handle them here.
  31143. const publicFile = checkPublicFile(id, config);
  31144. if (publicFile) {
  31145. return id;
  31146. }
  31147. },
  31148. async load(id) {
  31149. if (id.startsWith('\0')) {
  31150. // Rollup convention, this id should be handled by the
  31151. // plugin that marked it with \0
  31152. return;
  31153. }
  31154. // raw requests, read from disk
  31155. if (rawRE.test(id)) {
  31156. const file = checkPublicFile(id, config) || cleanUrl(id);
  31157. // raw query, read file and return as string
  31158. return `export default ${JSON.stringify(await fs$n.promises.readFile(file, 'utf-8'))}`;
  31159. }
  31160. if (!config.assetsInclude(cleanUrl(id)) && !urlRE.test(id)) {
  31161. return;
  31162. }
  31163. id = id.replace(urlRE, '$1').replace(/[\?&]$/, '');
  31164. const url = await fileToUrl(id, config, this);
  31165. return `export default ${JSON.stringify(url)}`;
  31166. },
  31167. renderChunk(code, chunk) {
  31168. let match;
  31169. let s;
  31170. // Urls added with JS using e.g.
  31171. // imgElement.src = "my/file.png" are using quotes
  31172. // Urls added in CSS that is imported in JS end up like
  31173. // var inlined = ".inlined{color:green;background:url(__VITE_ASSET__5aa0ddc0__)}\n";
  31174. // In both cases, the wrapping should already be fine
  31175. while ((match = assetUrlRE.exec(code))) {
  31176. s = s || (s = new MagicString(code));
  31177. const [full, hash, postfix = ''] = match;
  31178. // some internal plugins may still need to emit chunks (e.g. worker) so
  31179. // fallback to this.getFileName for that.
  31180. const file = getAssetFilename(hash, config) || this.getFileName(hash);
  31181. chunk.viteMetadata.importedAssets.add(cleanUrl(file));
  31182. const outputFilepath = config.base + file + postfix;
  31183. s.overwrite(match.index, match.index + full.length, outputFilepath, {
  31184. contentOnly: true
  31185. });
  31186. }
  31187. if (s) {
  31188. return {
  31189. code: s.toString(),
  31190. map: config.build.sourcemap ? s.generateMap({ hires: true }) : null
  31191. };
  31192. }
  31193. else {
  31194. return null;
  31195. }
  31196. },
  31197. generateBundle(_, bundle) {
  31198. // do not emit assets for SSR build
  31199. if (config.command === 'build' && config.build.ssr) {
  31200. for (const file in bundle) {
  31201. if (bundle[file].type === 'asset' &&
  31202. !file.includes('ssr-manifest.json')) {
  31203. delete bundle[file];
  31204. }
  31205. }
  31206. }
  31207. }
  31208. };
  31209. }
  31210. function checkPublicFile(url, { publicDir }) {
  31211. // note if the file is in /public, the resolver would have returned it
  31212. // as-is so it's not going to be a fully resolved path.
  31213. if (!publicDir || !url.startsWith('/')) {
  31214. return;
  31215. }
  31216. const publicFile = path__default.join(publicDir, cleanUrl(url));
  31217. if (fs__default.existsSync(publicFile)) {
  31218. return publicFile;
  31219. }
  31220. else {
  31221. return;
  31222. }
  31223. }
  31224. async function fileToUrl(id, config, ctx) {
  31225. if (config.command === 'serve') {
  31226. return fileToDevUrl(id, config);
  31227. }
  31228. else {
  31229. return fileToBuiltUrl(id, config, ctx);
  31230. }
  31231. }
  31232. function fileToDevUrl(id, config) {
  31233. var _a, _b;
  31234. let rtn;
  31235. if (checkPublicFile(id, config)) {
  31236. // in public dir, keep the url as-is
  31237. rtn = id;
  31238. }
  31239. else if (id.startsWith(config.root)) {
  31240. // in project root, infer short public path
  31241. rtn = '/' + path__default.posix.relative(config.root, id);
  31242. }
  31243. else {
  31244. // outside of project root, use absolute fs path
  31245. // (this is special handled by the serve static middleware
  31246. rtn = path__default.posix.join(FS_PREFIX + id);
  31247. }
  31248. const origin = (_b = (_a = config.server) === null || _a === void 0 ? void 0 : _a.origin) !== null && _b !== void 0 ? _b : '';
  31249. return origin + config.base + rtn.replace(/^\//, '');
  31250. }
  31251. function getAssetFilename(hash, config) {
  31252. var _a;
  31253. return (_a = assetHashToFilenameMap.get(config)) === null || _a === void 0 ? void 0 : _a.get(hash);
  31254. }
  31255. /**
  31256. * converts the source filepath of the asset to the output filename based on the assetFileNames option. \
  31257. * this function imitates the behavior of rollup.js. \
  31258. * https://rollupjs.org/guide/en/#outputassetfilenames
  31259. *
  31260. * @example
  31261. * ```ts
  31262. * const content = Buffer.from('text');
  31263. * const fileName = assetFileNamesToFileName(
  31264. * 'assets/[name].[hash][extname]',
  31265. * '/path/to/file.txt',
  31266. * getAssetHash(content),
  31267. * content
  31268. * )
  31269. * // fileName: 'assets/file.982d9e3e.txt'
  31270. * ```
  31271. *
  31272. * @param assetFileNames filename pattern. e.g. `'assets/[name].[hash][extname]'`
  31273. * @param file filepath of the asset
  31274. * @param contentHash hash of the asset. used for `'[hash]'` placeholder
  31275. * @param content content of the asset. passed to `assetFileNames` if `assetFileNames` is a function
  31276. * @returns output filename
  31277. */
  31278. function assetFileNamesToFileName(assetFileNames, file, contentHash, content) {
  31279. const basename = path__default.basename(file);
  31280. // placeholders for `assetFileNames`
  31281. // `hash` is slightly different from the rollup's one
  31282. const extname = path__default.extname(basename);
  31283. const ext = extname.substring(1);
  31284. const name = basename.slice(0, -extname.length);
  31285. const hash = contentHash;
  31286. if (typeof assetFileNames === 'function') {
  31287. assetFileNames = assetFileNames({
  31288. name: file,
  31289. source: content,
  31290. type: 'asset'
  31291. });
  31292. if (typeof assetFileNames !== 'string') {
  31293. throw new TypeError('assetFileNames must return a string');
  31294. }
  31295. }
  31296. else if (typeof assetFileNames !== 'string') {
  31297. throw new TypeError('assetFileNames must be a string or a function');
  31298. }
  31299. const fileName = assetFileNames.replace(/\[\w+\]/g, (placeholder) => {
  31300. switch (placeholder) {
  31301. case '[ext]':
  31302. return ext;
  31303. case '[extname]':
  31304. return extname;
  31305. case '[hash]':
  31306. return hash;
  31307. case '[name]':
  31308. return name;
  31309. }
  31310. throw new Error(`invalid placeholder ${placeholder} in assetFileNames "${assetFileNames}"`);
  31311. });
  31312. return fileName;
  31313. }
  31314. /**
  31315. * Register an asset to be emitted as part of the bundle (if necessary)
  31316. * and returns the resolved public URL
  31317. */
  31318. async function fileToBuiltUrl(id, config, pluginContext, skipPublicCheck = false) {
  31319. var _a, _b, _c;
  31320. if (!skipPublicCheck && checkPublicFile(id, config)) {
  31321. return config.base + id.slice(1);
  31322. }
  31323. const cache = assetCache.get(config);
  31324. const cached = cache.get(id);
  31325. if (cached) {
  31326. return cached;
  31327. }
  31328. const file = cleanUrl(id);
  31329. const content = await fs$n.promises.readFile(file);
  31330. let url;
  31331. if (config.build.lib ||
  31332. (!file.endsWith('.svg') &&
  31333. content.length < Number(config.build.assetsInlineLimit))) {
  31334. // base64 inlined as a string
  31335. url = `data:${lookup(file)};base64,${content.toString('base64')}`;
  31336. }
  31337. else {
  31338. // emit as asset
  31339. // rollup supports `import.meta.ROLLUP_FILE_URL_*`, but it generates code
  31340. // that uses runtime url sniffing and it can be verbose when targeting
  31341. // non-module format. It also fails to cascade the asset content change
  31342. // into the chunk's hash, so we have to do our own content hashing here.
  31343. // https://bundlers.tooling.report/hashing/asset-cascade/
  31344. // https://github.com/rollup/rollup/issues/3415
  31345. const map = assetHashToFilenameMap.get(config);
  31346. const contentHash = getAssetHash(content);
  31347. const { search, hash } = require$$0$6.parse(id);
  31348. const postfix = (search || '') + (hash || '');
  31349. const output = (_b = (_a = config.build) === null || _a === void 0 ? void 0 : _a.rollupOptions) === null || _b === void 0 ? void 0 : _b.output;
  31350. const assetFileNames = (_c = (output && !Array.isArray(output) ? output.assetFileNames : undefined)) !== null && _c !== void 0 ? _c :
  31351. // defaults to '<assetsDir>/[name].[hash][extname]'
  31352. // slightly different from rollup's one ('assets/[name]-[hash][extname]')
  31353. path__default.posix.join(config.build.assetsDir, '[name].[hash][extname]');
  31354. const fileName = assetFileNamesToFileName(assetFileNames, file, contentHash, content);
  31355. if (!map.has(contentHash)) {
  31356. map.set(contentHash, fileName);
  31357. }
  31358. const emittedSet = emittedHashMap.get(config);
  31359. if (!emittedSet.has(contentHash)) {
  31360. const name = normalizePath$3(path__default.relative(config.root, file));
  31361. pluginContext.emitFile({
  31362. name,
  31363. fileName,
  31364. type: 'asset',
  31365. source: content
  31366. });
  31367. emittedSet.add(contentHash);
  31368. }
  31369. url = `__VITE_ASSET__${contentHash}__${postfix ? `$_${postfix}__` : ``}`;
  31370. }
  31371. cache.set(id, url);
  31372. return url;
  31373. }
  31374. function getAssetHash(content) {
  31375. return require$$1$1.createHash('sha256').update(content).digest('hex').slice(0, 8);
  31376. }
  31377. async function urlToBuiltUrl(url, importer, config, pluginContext) {
  31378. if (checkPublicFile(url, config)) {
  31379. return config.base + url.slice(1);
  31380. }
  31381. const file = url.startsWith('/')
  31382. ? path__default.join(config.root, url)
  31383. : path__default.join(path__default.dirname(importer), url);
  31384. return fileToBuiltUrl(file, config, pluginContext,
  31385. // skip public check since we just did it above
  31386. true);
  31387. }
  31388. const modulePreloadPolyfillId = 'vite/modulepreload-polyfill';
  31389. function modulePreloadPolyfillPlugin(config) {
  31390. // `isModernFlag` is only available during build since it is resolved by `vite:build-import-analysis`
  31391. const skip = config.command !== 'build' || config.build.ssr;
  31392. let polyfillString;
  31393. return {
  31394. name: 'vite:modulepreload-polyfill',
  31395. resolveId(id) {
  31396. if (id === modulePreloadPolyfillId) {
  31397. return id;
  31398. }
  31399. },
  31400. load(id) {
  31401. if (id === modulePreloadPolyfillId) {
  31402. if (skip) {
  31403. return '';
  31404. }
  31405. if (!polyfillString) {
  31406. polyfillString =
  31407. `const p = ${polyfill.toString()};` + `${isModernFlag}&&p();`;
  31408. }
  31409. return polyfillString;
  31410. }
  31411. }
  31412. };
  31413. }
  31414. function polyfill() {
  31415. const relList = document.createElement('link').relList;
  31416. if (relList && relList.supports && relList.supports('modulepreload')) {
  31417. return;
  31418. }
  31419. for (const link of document.querySelectorAll('link[rel="modulepreload"]')) {
  31420. processPreload(link);
  31421. }
  31422. new MutationObserver((mutations) => {
  31423. for (const mutation of mutations) {
  31424. if (mutation.type !== 'childList') {
  31425. continue;
  31426. }
  31427. for (const node of mutation.addedNodes) {
  31428. if (node.tagName === 'LINK' && node.rel === 'modulepreload')
  31429. processPreload(node);
  31430. }
  31431. }
  31432. }).observe(document, { childList: true, subtree: true });
  31433. function getFetchOpts(script) {
  31434. const fetchOpts = {};
  31435. if (script.integrity)
  31436. fetchOpts.integrity = script.integrity;
  31437. if (script.referrerpolicy)
  31438. fetchOpts.referrerPolicy = script.referrerpolicy;
  31439. if (script.crossorigin === 'use-credentials')
  31440. fetchOpts.credentials = 'include';
  31441. else if (script.crossorigin === 'anonymous')
  31442. fetchOpts.credentials = 'omit';
  31443. else
  31444. fetchOpts.credentials = 'same-origin';
  31445. return fetchOpts;
  31446. }
  31447. function processPreload(link) {
  31448. if (link.ep)
  31449. // ep marker = processed
  31450. return;
  31451. link.ep = true;
  31452. // prepopulate the load record
  31453. const fetchOpts = getFetchOpts(link);
  31454. fetch(link.href, fetchOpts);
  31455. }
  31456. }
  31457. const htmlProxyRE$1 = /\?html-proxy=?[&inline\-css]*&index=(\d+)\.(js|css)$/;
  31458. const inlineCSSRE$1 = /__VITE_INLINE_CSS__([a-z\d]{8}_\d+)__/g;
  31459. // Do not allow preceding '.', but do allow preceding '...' for spread operations
  31460. const inlineImportRE = /(?<!(?<!\.\.)\.)\bimport\s*\(("([^"]|(?<=\\)")*"|'([^']|(?<=\\)')*')\)/g;
  31461. const htmlLangRE = /\.(html|htm)$/;
  31462. const isHTMLProxy = (id) => htmlProxyRE$1.test(id);
  31463. const isHTMLRequest = (request) => htmlLangRE.test(request);
  31464. // HTML Proxy Caches are stored by config -> filePath -> index
  31465. const htmlProxyMap = new WeakMap();
  31466. // HTML Proxy Transform result are stored by config
  31467. // `${hash(importer)}_${query.index}` -> transformed css code
  31468. // PS: key like `hash(/vite/packages/playground/assets/index.html)_1`)
  31469. const htmlProxyResult = new Map();
  31470. function htmlInlineProxyPlugin(config) {
  31471. // Should do this when `constructor` rather than when `buildStart`,
  31472. // `buildStart` will be triggered multiple times then the cached result will be emptied.
  31473. // https://github.com/vitejs/vite/issues/6372
  31474. htmlProxyMap.set(config, new Map());
  31475. return {
  31476. name: 'vite:html-inline-proxy',
  31477. resolveId(id) {
  31478. if (htmlProxyRE$1.test(id)) {
  31479. return id;
  31480. }
  31481. },
  31482. load(id) {
  31483. const proxyMatch = id.match(htmlProxyRE$1);
  31484. if (proxyMatch) {
  31485. const index = Number(proxyMatch[1]);
  31486. const file = cleanUrl(id);
  31487. const url = file.replace(normalizePath$3(config.root), '');
  31488. const result = htmlProxyMap.get(config).get(url)[index];
  31489. if (result) {
  31490. return result;
  31491. }
  31492. else {
  31493. throw new Error(`No matching HTML proxy module found from ${id}`);
  31494. }
  31495. }
  31496. }
  31497. };
  31498. }
  31499. function addToHTMLProxyCache(config, filePath, index, result) {
  31500. if (!htmlProxyMap.get(config)) {
  31501. htmlProxyMap.set(config, new Map());
  31502. }
  31503. if (!htmlProxyMap.get(config).get(filePath)) {
  31504. htmlProxyMap.get(config).set(filePath, []);
  31505. }
  31506. htmlProxyMap.get(config).get(filePath)[index] = result;
  31507. }
  31508. function addToHTMLProxyTransformResult(hash, code) {
  31509. htmlProxyResult.set(hash, code);
  31510. }
  31511. // this extends the config in @vue/compiler-sfc with <link href>
  31512. const assetAttrsConfig = {
  31513. link: ['href'],
  31514. video: ['src', 'poster'],
  31515. source: ['src', 'srcset'],
  31516. img: ['src', 'srcset'],
  31517. image: ['xlink:href', 'href'],
  31518. use: ['xlink:href', 'href']
  31519. };
  31520. const isAsyncScriptMap = new WeakMap();
  31521. async function traverseHtml(html, filePath, visitor) {
  31522. // lazy load compiler
  31523. const { parse, transform } = await Promise.resolve().then(function () { return require('./dep-0fd6fea3.js'); }).then(function (n) { return n.compilerDom_cjs; });
  31524. // @vue/compiler-core doesn't like lowercase doctypes
  31525. html = html.replace(/<!doctype\s/i, '<!DOCTYPE ');
  31526. try {
  31527. const ast = parse(html, { comments: true });
  31528. transform(ast, {
  31529. nodeTransforms: [visitor]
  31530. });
  31531. }
  31532. catch (e) {
  31533. handleParseError(e, html, filePath);
  31534. }
  31535. }
  31536. function getScriptInfo(node) {
  31537. let src;
  31538. let isModule = false;
  31539. let isAsync = false;
  31540. for (let i = 0; i < node.props.length; i++) {
  31541. const p = node.props[i];
  31542. if (p.type === 6 /* ATTRIBUTE */) {
  31543. if (p.name === 'src') {
  31544. src = p;
  31545. }
  31546. else if (p.name === 'type' && p.value && p.value.content === 'module') {
  31547. isModule = true;
  31548. }
  31549. else if (p.name === 'async') {
  31550. isAsync = true;
  31551. }
  31552. }
  31553. }
  31554. return { src, isModule, isAsync };
  31555. }
  31556. /**
  31557. * Format Vue @type {CompilerError} to @type {RollupError}
  31558. */
  31559. function formatParseError(compilerError, id, html) {
  31560. const formattedError = { ...compilerError };
  31561. if (compilerError.loc) {
  31562. formattedError.frame = generateCodeFrame(html, compilerError.loc.start.offset);
  31563. formattedError.loc = {
  31564. file: id,
  31565. line: compilerError.loc.start.line,
  31566. column: compilerError.loc.start.column
  31567. };
  31568. }
  31569. return formattedError;
  31570. }
  31571. function handleParseError(compilerError, html, filePath) {
  31572. const parseError = {
  31573. loc: filePath,
  31574. frame: '',
  31575. ...formatParseError(compilerError, filePath, html)
  31576. };
  31577. throw new Error(`Unable to parse HTML; ${compilerError.message}\n at ${JSON.stringify(parseError.loc)}\n${parseError.frame}`);
  31578. }
  31579. /**
  31580. * Compiles index.html into an entry js module
  31581. */
  31582. function buildHtmlPlugin(config) {
  31583. const [preHooks, postHooks] = resolveHtmlTransforms(config.plugins);
  31584. const processedHtml = new Map();
  31585. const isExcludedUrl = (url) => url.startsWith('#') ||
  31586. isExternalUrl(url) ||
  31587. isDataUrl(url) ||
  31588. checkPublicFile(url, config);
  31589. // Same reason with `htmlInlineProxyPlugin`
  31590. isAsyncScriptMap.set(config, new Map());
  31591. return {
  31592. name: 'vite:build-html',
  31593. async transform(html, id) {
  31594. var _a, _b;
  31595. if (id.endsWith('.html')) {
  31596. const publicPath = `/${slash(path__default.relative(config.root, id))}`;
  31597. // pre-transform
  31598. html = await applyHtmlTransforms(html, preHooks, {
  31599. path: publicPath,
  31600. filename: id
  31601. });
  31602. let js = '';
  31603. const s = new MagicString(html);
  31604. const assetUrls = [];
  31605. const scriptUrls = [];
  31606. let inlineModuleIndex = -1;
  31607. let everyScriptIsAsync = true;
  31608. let someScriptsAreAsync = false;
  31609. let someScriptsAreDefer = false;
  31610. await traverseHtml(html, id, (node) => {
  31611. if (node.type !== 1 /* ELEMENT */) {
  31612. return;
  31613. }
  31614. let shouldRemove = false;
  31615. // script tags
  31616. if (node.tag === 'script') {
  31617. const { src, isModule, isAsync } = getScriptInfo(node);
  31618. const url = src && src.value && src.value.content;
  31619. const isPublicFile = !!(url && checkPublicFile(url, config));
  31620. if (isPublicFile) {
  31621. // referencing public dir url, prefix with base
  31622. s.overwrite(src.value.loc.start.offset, src.value.loc.end.offset, `"${config.base + url.slice(1)}"`, { contentOnly: true });
  31623. }
  31624. if (isModule) {
  31625. inlineModuleIndex++;
  31626. if (url && !isExcludedUrl(url)) {
  31627. // <script type="module" src="..."/>
  31628. // add it as an import
  31629. js += `\nimport ${JSON.stringify(url)}`;
  31630. shouldRemove = true;
  31631. }
  31632. else if (node.children.length) {
  31633. const contents = node.children
  31634. .map((child) => child.content || '')
  31635. .join('');
  31636. // <script type="module">...</script>
  31637. const filePath = id.replace(normalizePath$3(config.root), '');
  31638. addToHTMLProxyCache(config, filePath, inlineModuleIndex, {
  31639. code: contents
  31640. });
  31641. js += `\nimport "${id}?html-proxy&index=${inlineModuleIndex}.js"`;
  31642. shouldRemove = true;
  31643. }
  31644. everyScriptIsAsync && (everyScriptIsAsync = isAsync);
  31645. someScriptsAreAsync || (someScriptsAreAsync = isAsync);
  31646. someScriptsAreDefer || (someScriptsAreDefer = !isAsync);
  31647. }
  31648. else if (url && !isPublicFile) {
  31649. if (!isExcludedUrl(url)) {
  31650. config.logger.warn(`<script src="${url}"> in "${publicPath}" can't be bundled without type="module" attribute`);
  31651. }
  31652. }
  31653. else if (node.children.length) {
  31654. const scriptNode = node.children.pop();
  31655. const cleanCode = stripLiteral(scriptNode.content);
  31656. let match;
  31657. while ((match = inlineImportRE.exec(cleanCode))) {
  31658. const { 1: url, index } = match;
  31659. const startUrl = cleanCode.indexOf(url, index);
  31660. const start = startUrl + 1;
  31661. const end = start + url.length - 2;
  31662. scriptUrls.push({
  31663. start: start + scriptNode.loc.start.offset,
  31664. end: end + scriptNode.loc.start.offset,
  31665. url: scriptNode.content.slice(start, end)
  31666. });
  31667. }
  31668. }
  31669. }
  31670. // For asset references in index.html, also generate an import
  31671. // statement for each - this will be handled by the asset plugin
  31672. const assetAttrs = assetAttrsConfig[node.tag];
  31673. if (assetAttrs) {
  31674. for (const p of node.props) {
  31675. if (p.type === 6 /* ATTRIBUTE */ &&
  31676. p.value &&
  31677. assetAttrs.includes(p.name)) {
  31678. // assetsUrl may be encodeURI
  31679. const url = decodeURI(p.value.content);
  31680. if (!isExcludedUrl(url)) {
  31681. if (node.tag === 'link' && isCSSRequest(url)) {
  31682. // CSS references, convert to import
  31683. js += `\nimport ${JSON.stringify(url)}`;
  31684. shouldRemove = true;
  31685. }
  31686. else {
  31687. assetUrls.push(p);
  31688. }
  31689. }
  31690. else if (checkPublicFile(url, config)) {
  31691. s.overwrite(p.value.loc.start.offset, p.value.loc.end.offset, `"${config.base + url.slice(1)}"`, { contentOnly: true });
  31692. }
  31693. }
  31694. }
  31695. }
  31696. // <tag style="... url(...) ..."></tag>
  31697. // extract inline styles as virtual css and add class attribute to tag for selecting
  31698. const inlineStyle = node.props.find((prop) => prop.name === 'style' &&
  31699. prop.type === 6 /* ATTRIBUTE */ &&
  31700. prop.value &&
  31701. prop.value.content.includes('url(') // only url(...) in css need to emit file
  31702. );
  31703. if (inlineStyle) {
  31704. inlineModuleIndex++;
  31705. // replace `inline style` to class
  31706. // and import css in js code
  31707. const styleNode = inlineStyle.value;
  31708. const code = styleNode.content;
  31709. const filePath = id.replace(normalizePath$3(config.root), '');
  31710. addToHTMLProxyCache(config, filePath, inlineModuleIndex, { code });
  31711. // will transform with css plugin and cache result with css-post plugin
  31712. js += `\nimport "${id}?html-proxy&inline-css&index=${inlineModuleIndex}.css"`;
  31713. const hash = getAssetHash(cleanUrl(id));
  31714. // will transform in `applyHtmlTransforms`
  31715. s.overwrite(styleNode.loc.start.offset, styleNode.loc.end.offset, `"__VITE_INLINE_CSS__${hash}_${inlineModuleIndex}__"`, { contentOnly: true });
  31716. }
  31717. // <style>...</style>
  31718. if (node.tag === 'style' && node.children.length) {
  31719. const styleNode = node.children.pop();
  31720. const filePath = id.replace(normalizePath$3(config.root), '');
  31721. inlineModuleIndex++;
  31722. addToHTMLProxyCache(config, filePath, inlineModuleIndex, {
  31723. code: styleNode.content
  31724. });
  31725. js += `\nimport "${id}?html-proxy&inline-css&index=${inlineModuleIndex}.css"`;
  31726. const hash = getAssetHash(cleanUrl(id));
  31727. // will transform in `applyHtmlTransforms`
  31728. s.overwrite(styleNode.loc.start.offset, styleNode.loc.end.offset, `__VITE_INLINE_CSS__${hash}_${inlineModuleIndex}__`, { contentOnly: true });
  31729. }
  31730. if (shouldRemove) {
  31731. // remove the script tag from the html. we are going to inject new
  31732. // ones in the end.
  31733. s.remove(node.loc.start.offset, node.loc.end.offset);
  31734. }
  31735. });
  31736. isAsyncScriptMap.get(config).set(id, everyScriptIsAsync);
  31737. if (someScriptsAreAsync && someScriptsAreDefer) {
  31738. config.logger.warn(`\nMixed async and defer script modules in ${id}, output script will fallback to defer. Every script, including inline ones, need to be marked as async for your output script to be async.`);
  31739. }
  31740. // for each encountered asset url, rewrite original html so that it
  31741. // references the post-build location, ignoring empty attributes and
  31742. // attributes that directly reference named output.
  31743. const namedOutput = Object.keys(((_b = (_a = config === null || config === void 0 ? void 0 : config.build) === null || _a === void 0 ? void 0 : _a.rollupOptions) === null || _b === void 0 ? void 0 : _b.input) || {});
  31744. for (const attr of assetUrls) {
  31745. const value = attr.value;
  31746. // assetsUrl may be encodeURI
  31747. const content = decodeURI(value.content);
  31748. if (content !== '' && // Empty attribute
  31749. !namedOutput.includes(content) && // Direct reference to named output
  31750. !namedOutput.includes(content.replace(/^\//, '')) // Allow for absolute references as named output can't be an absolute path
  31751. ) {
  31752. try {
  31753. const url = attr.name === 'srcset'
  31754. ? await processSrcSet(content, ({ url }) => urlToBuiltUrl(url, id, config, this))
  31755. : await urlToBuiltUrl(content, id, config, this);
  31756. s.overwrite(value.loc.start.offset, value.loc.end.offset, `"${url}"`, { contentOnly: true });
  31757. }
  31758. catch (e) {
  31759. if (e.code !== 'ENOENT') {
  31760. throw e;
  31761. }
  31762. }
  31763. }
  31764. }
  31765. // emit <script>import("./aaa")</script> asset
  31766. for (const { start, end, url } of scriptUrls) {
  31767. if (!isExcludedUrl(url)) {
  31768. s.overwrite(start, end, await urlToBuiltUrl(url, id, config, this), { contentOnly: true });
  31769. }
  31770. else if (checkPublicFile(url, config)) {
  31771. s.overwrite(start, end, config.base + url.slice(1), {
  31772. contentOnly: true
  31773. });
  31774. }
  31775. }
  31776. processedHtml.set(id, s.toString());
  31777. // inject module preload polyfill only when configured and needed
  31778. if (config.build.polyfillModulePreload &&
  31779. (someScriptsAreAsync || someScriptsAreDefer)) {
  31780. js = `import "${modulePreloadPolyfillId}";\n${js}`;
  31781. }
  31782. return js;
  31783. }
  31784. },
  31785. async generateBundle(options, bundle) {
  31786. const analyzedChunk = new Map();
  31787. const getImportedChunks = (chunk, seen = new Set()) => {
  31788. const chunks = [];
  31789. chunk.imports.forEach((file) => {
  31790. const importee = bundle[file];
  31791. if ((importee === null || importee === void 0 ? void 0 : importee.type) === 'chunk' && !seen.has(file)) {
  31792. seen.add(file);
  31793. // post-order traversal
  31794. chunks.push(...getImportedChunks(importee, seen));
  31795. chunks.push(importee);
  31796. }
  31797. });
  31798. return chunks;
  31799. };
  31800. const toScriptTag = (chunk, isAsync) => ({
  31801. tag: 'script',
  31802. attrs: {
  31803. ...(isAsync ? { async: true } : {}),
  31804. type: 'module',
  31805. crossorigin: true,
  31806. src: toPublicPath(chunk.fileName, config)
  31807. }
  31808. });
  31809. const toPreloadTag = (chunk) => ({
  31810. tag: 'link',
  31811. attrs: {
  31812. rel: 'modulepreload',
  31813. href: toPublicPath(chunk.fileName, config)
  31814. }
  31815. });
  31816. const getCssTagsForChunk = (chunk, seen = new Set()) => {
  31817. const tags = [];
  31818. if (!analyzedChunk.has(chunk)) {
  31819. analyzedChunk.set(chunk, 1);
  31820. chunk.imports.forEach((file) => {
  31821. const importee = bundle[file];
  31822. if ((importee === null || importee === void 0 ? void 0 : importee.type) === 'chunk') {
  31823. tags.push(...getCssTagsForChunk(importee, seen));
  31824. }
  31825. });
  31826. }
  31827. chunk.viteMetadata.importedCss.forEach((file) => {
  31828. if (!seen.has(file)) {
  31829. seen.add(file);
  31830. tags.push({
  31831. tag: 'link',
  31832. attrs: {
  31833. rel: 'stylesheet',
  31834. href: toPublicPath(file, config)
  31835. }
  31836. });
  31837. }
  31838. });
  31839. return tags;
  31840. };
  31841. for (const [id, html] of processedHtml) {
  31842. const isAsync = isAsyncScriptMap.get(config).get(id);
  31843. let result = html;
  31844. // find corresponding entry chunk
  31845. const chunk = Object.values(bundle).find((chunk) => chunk.type === 'chunk' &&
  31846. chunk.isEntry &&
  31847. chunk.facadeModuleId === id);
  31848. let canInlineEntry = false;
  31849. // inject chunk asset links
  31850. if (chunk) {
  31851. // an entry chunk can be inlined if
  31852. // - it's an ES module (e.g. not generated by the legacy plugin)
  31853. // - it contains no meaningful code other than import statements
  31854. if (options.format === 'es' && isEntirelyImport(chunk.code)) {
  31855. canInlineEntry = true;
  31856. }
  31857. // when not inlined, inject <script> for entry and modulepreload its dependencies
  31858. // when inlined, discard entry chunk and inject <script> for everything in post-order
  31859. const imports = getImportedChunks(chunk);
  31860. const assetTags = canInlineEntry
  31861. ? imports.map((chunk) => toScriptTag(chunk, isAsync))
  31862. : [toScriptTag(chunk, isAsync), ...imports.map(toPreloadTag)];
  31863. assetTags.push(...getCssTagsForChunk(chunk));
  31864. result = injectToHead(result, assetTags);
  31865. }
  31866. // inject css link when cssCodeSplit is false
  31867. if (!config.build.cssCodeSplit) {
  31868. const cssChunk = Object.values(bundle).find((chunk) => chunk.type === 'asset' && chunk.name === 'style.css');
  31869. if (cssChunk) {
  31870. result = injectToHead(result, [
  31871. {
  31872. tag: 'link',
  31873. attrs: {
  31874. rel: 'stylesheet',
  31875. href: toPublicPath(cssChunk.fileName, config)
  31876. }
  31877. }
  31878. ]);
  31879. }
  31880. }
  31881. // no use assets plugin because it will emit file
  31882. let match;
  31883. let s;
  31884. while ((match = inlineCSSRE$1.exec(result))) {
  31885. s || (s = new MagicString(result));
  31886. const { 0: full, 1: scopedName } = match;
  31887. const cssTransformedCode = htmlProxyResult.get(scopedName);
  31888. s.overwrite(match.index, match.index + full.length, cssTransformedCode, { contentOnly: true });
  31889. }
  31890. if (s) {
  31891. result = s.toString();
  31892. }
  31893. const relativeUrlPath = path__default.posix.relative(config.root, id);
  31894. result = await applyHtmlTransforms(result, postHooks, {
  31895. path: '/' + relativeUrlPath,
  31896. filename: id,
  31897. bundle,
  31898. chunk
  31899. });
  31900. // resolve asset url references
  31901. result = result.replace(assetUrlRE, (_, fileHash, postfix = '') => {
  31902. return config.base + getAssetFilename(fileHash, config) + postfix;
  31903. });
  31904. if (chunk && canInlineEntry) {
  31905. // all imports from entry have been inlined to html, prevent rollup from outputting it
  31906. delete bundle[chunk.fileName];
  31907. }
  31908. const shortEmitName = path__default.relative(config.root, id);
  31909. this.emitFile({
  31910. type: 'asset',
  31911. fileName: shortEmitName,
  31912. source: result
  31913. });
  31914. }
  31915. }
  31916. };
  31917. }
  31918. function resolveHtmlTransforms(plugins) {
  31919. const preHooks = [];
  31920. const postHooks = [];
  31921. for (const plugin of plugins) {
  31922. const hook = plugin.transformIndexHtml;
  31923. if (hook) {
  31924. if (typeof hook === 'function') {
  31925. postHooks.push(hook);
  31926. }
  31927. else if (hook.enforce === 'pre') {
  31928. preHooks.push(hook.transform);
  31929. }
  31930. else {
  31931. postHooks.push(hook.transform);
  31932. }
  31933. }
  31934. }
  31935. return [preHooks, postHooks];
  31936. }
  31937. async function applyHtmlTransforms(html, hooks, ctx) {
  31938. const headTags = [];
  31939. const headPrependTags = [];
  31940. const bodyTags = [];
  31941. const bodyPrependTags = [];
  31942. for (const hook of hooks) {
  31943. const res = await hook(html, ctx);
  31944. if (!res) {
  31945. continue;
  31946. }
  31947. if (typeof res === 'string') {
  31948. html = res;
  31949. }
  31950. else {
  31951. let tags;
  31952. if (Array.isArray(res)) {
  31953. tags = res;
  31954. }
  31955. else {
  31956. html = res.html || html;
  31957. tags = res.tags;
  31958. }
  31959. for (const tag of tags) {
  31960. if (tag.injectTo === 'body') {
  31961. bodyTags.push(tag);
  31962. }
  31963. else if (tag.injectTo === 'body-prepend') {
  31964. bodyPrependTags.push(tag);
  31965. }
  31966. else if (tag.injectTo === 'head') {
  31967. headTags.push(tag);
  31968. }
  31969. else {
  31970. headPrependTags.push(tag);
  31971. }
  31972. }
  31973. }
  31974. }
  31975. // inject tags
  31976. if (headPrependTags.length) {
  31977. html = injectToHead(html, headPrependTags, true);
  31978. }
  31979. if (headTags.length) {
  31980. html = injectToHead(html, headTags);
  31981. }
  31982. if (bodyPrependTags.length) {
  31983. html = injectToBody(html, bodyPrependTags, true);
  31984. }
  31985. if (bodyTags.length) {
  31986. html = injectToBody(html, bodyTags);
  31987. }
  31988. return html;
  31989. }
  31990. const importRE = /\bimport\s*("[^"]*[^\\]"|'[^']*[^\\]');*/g;
  31991. const commentRE$1 = /\/\*[\s\S]*?\*\/|\/\/.*$/gm;
  31992. function isEntirelyImport(code) {
  31993. // only consider "side-effect" imports, which match <script type=module> semantics exactly
  31994. // the regexes will remove too little in some exotic cases, but false-negatives are alright
  31995. return !code.replace(importRE, '').replace(commentRE$1, '').trim().length;
  31996. }
  31997. function toPublicPath(filename, config) {
  31998. return isExternalUrl(filename) ? filename : config.base + filename;
  31999. }
  32000. const headInjectRE = /([ \t]*)<\/head>/i;
  32001. const headPrependInjectRE = /([ \t]*)<head[^>]*>/i;
  32002. const htmlInjectRE = /<\/html>/i;
  32003. const htmlPrependInjectRE = /([ \t]*)<html[^>]*>/i;
  32004. const bodyInjectRE = /([ \t]*)<\/body>/i;
  32005. const bodyPrependInjectRE = /([ \t]*)<body[^>]*>/i;
  32006. const doctypePrependInjectRE = /<!doctype html>/i;
  32007. function injectToHead(html, tags, prepend = false) {
  32008. if (prepend) {
  32009. // inject as the first element of head
  32010. if (headPrependInjectRE.test(html)) {
  32011. return html.replace(headPrependInjectRE, (match, p1) => `${match}\n${serializeTags(tags, incrementIndent(p1))}`);
  32012. }
  32013. }
  32014. else {
  32015. // inject before head close
  32016. if (headInjectRE.test(html)) {
  32017. // respect indentation of head tag
  32018. return html.replace(headInjectRE, (match, p1) => `${serializeTags(tags, incrementIndent(p1))}${match}`);
  32019. }
  32020. // try to inject before the body tag
  32021. if (bodyPrependInjectRE.test(html)) {
  32022. return html.replace(bodyPrependInjectRE, (match, p1) => `${serializeTags(tags, p1)}\n${match}`);
  32023. }
  32024. }
  32025. // if no head tag is present, we prepend the tag for both prepend and append
  32026. return prependInjectFallback(html, tags);
  32027. }
  32028. function injectToBody(html, tags, prepend = false) {
  32029. if (prepend) {
  32030. // inject after body open
  32031. if (bodyPrependInjectRE.test(html)) {
  32032. return html.replace(bodyPrependInjectRE, (match, p1) => `${match}\n${serializeTags(tags, incrementIndent(p1))}`);
  32033. }
  32034. // if no there is no body tag, inject after head or fallback to prepend in html
  32035. if (headInjectRE.test(html)) {
  32036. return html.replace(headInjectRE, (match, p1) => `${match}\n${serializeTags(tags, p1)}`);
  32037. }
  32038. return prependInjectFallback(html, tags);
  32039. }
  32040. else {
  32041. // inject before body close
  32042. if (bodyInjectRE.test(html)) {
  32043. return html.replace(bodyInjectRE, (match, p1) => `${serializeTags(tags, incrementIndent(p1))}${match}`);
  32044. }
  32045. // if no body tag is present, append to the html tag, or at the end of the file
  32046. if (htmlInjectRE.test(html)) {
  32047. return html.replace(htmlInjectRE, `${serializeTags(tags)}\n$&`);
  32048. }
  32049. return html + `\n` + serializeTags(tags);
  32050. }
  32051. }
  32052. function prependInjectFallback(html, tags) {
  32053. // prepend to the html tag, append after doctype, or the document start
  32054. if (htmlPrependInjectRE.test(html)) {
  32055. return html.replace(htmlPrependInjectRE, `$&\n${serializeTags(tags)}`);
  32056. }
  32057. if (doctypePrependInjectRE.test(html)) {
  32058. return html.replace(doctypePrependInjectRE, `$&\n${serializeTags(tags)}`);
  32059. }
  32060. return serializeTags(tags) + html;
  32061. }
  32062. const unaryTags = new Set(['link', 'meta', 'base']);
  32063. function serializeTag({ tag, attrs, children }, indent = '') {
  32064. if (unaryTags.has(tag)) {
  32065. return `<${tag}${serializeAttrs(attrs)}>`;
  32066. }
  32067. else {
  32068. return `<${tag}${serializeAttrs(attrs)}>${serializeTags(children, incrementIndent(indent))}</${tag}>`;
  32069. }
  32070. }
  32071. function serializeTags(tags, indent = '') {
  32072. if (typeof tags === 'string') {
  32073. return tags;
  32074. }
  32075. else if (tags && tags.length) {
  32076. return tags.map((tag) => `${indent}${serializeTag(tag, indent)}\n`).join('');
  32077. }
  32078. return '';
  32079. }
  32080. function serializeAttrs(attrs) {
  32081. let res = '';
  32082. for (const key in attrs) {
  32083. if (typeof attrs[key] === 'boolean') {
  32084. res += attrs[key] ? ` ${key}` : ``;
  32085. }
  32086. else {
  32087. res += ` ${key}=${JSON.stringify(attrs[key])}`;
  32088. }
  32089. }
  32090. return res;
  32091. }
  32092. function incrementIndent(indent = '') {
  32093. return `${indent}${indent[0] === '\t' ? '\t' : ' '}`;
  32094. }
  32095. const cssLangs = `\\.(css|less|sass|scss|styl|stylus|pcss|postcss)($|\\?)`;
  32096. const cssLangRE = new RegExp(cssLangs);
  32097. const cssModuleRE = new RegExp(`\\.module${cssLangs}`);
  32098. const directRequestRE = /(\?|&)direct\b/;
  32099. const htmlProxyRE = /(\?|&)html-proxy\b/;
  32100. const commonjsProxyRE = /\?commonjs-proxy/;
  32101. const inlineRE = /(\?|&)inline\b/;
  32102. const inlineCSSRE = /(\?|&)inline-css\b/;
  32103. const usedRE = /(\?|&)used\b/;
  32104. const varRE = /^var\(/i;
  32105. const isCSSRequest = (request) => cssLangRE.test(request);
  32106. const isDirectCSSRequest = (request) => cssLangRE.test(request) && directRequestRE.test(request);
  32107. const isDirectRequest = (request) => directRequestRE.test(request);
  32108. const cssModulesCache = new WeakMap();
  32109. const removedPureCssFilesCache = new WeakMap();
  32110. const postcssConfigCache = new WeakMap();
  32111. /**
  32112. * Plugin applied before user plugins
  32113. */
  32114. function cssPlugin(config) {
  32115. let server;
  32116. let moduleCache;
  32117. const resolveUrl = config.createResolver({
  32118. preferRelative: true,
  32119. tryIndex: false,
  32120. extensions: []
  32121. });
  32122. const atImportResolvers = createCSSResolvers(config);
  32123. return {
  32124. name: 'vite:css',
  32125. configureServer(_server) {
  32126. server = _server;
  32127. },
  32128. buildStart() {
  32129. // Ensure a new cache for every build (i.e. rebuilding in watch mode)
  32130. moduleCache = new Map();
  32131. cssModulesCache.set(config, moduleCache);
  32132. removedPureCssFilesCache.set(config, new Map());
  32133. },
  32134. async transform(raw, id, options) {
  32135. var _a, _b;
  32136. if (!isCSSRequest(id) ||
  32137. commonjsProxyRE.test(id) ||
  32138. SPECIAL_QUERY_RE.test(id)) {
  32139. return;
  32140. }
  32141. const ssr = (options === null || options === void 0 ? void 0 : options.ssr) === true;
  32142. const urlReplacer = async (url, importer) => {
  32143. if (checkPublicFile(url, config)) {
  32144. return config.base + url.slice(1);
  32145. }
  32146. const resolved = await resolveUrl(url, importer);
  32147. if (resolved) {
  32148. return fileToUrl(resolved, config, this);
  32149. }
  32150. return url;
  32151. };
  32152. const { code: css, modules, deps, map } = await compileCSS(id, raw, config, urlReplacer, atImportResolvers, server);
  32153. if (modules) {
  32154. moduleCache.set(id, modules);
  32155. }
  32156. // track deps for build watch mode
  32157. if (config.command === 'build' && config.build.watch && deps) {
  32158. for (const file of deps) {
  32159. this.addWatchFile(file);
  32160. }
  32161. }
  32162. // dev
  32163. if (server) {
  32164. // server only logic for handling CSS @import dependency hmr
  32165. const { moduleGraph } = server;
  32166. const thisModule = moduleGraph.getModuleById(id);
  32167. if (thisModule) {
  32168. // CSS modules cannot self-accept since it exports values
  32169. const isSelfAccepting = !modules && !inlineRE.test(id) && !htmlProxyRE.test(id);
  32170. if (deps) {
  32171. // record deps in the module graph so edits to @import css can trigger
  32172. // main import to hot update
  32173. const depModules = new Set();
  32174. for (const file of deps) {
  32175. depModules.add(isCSSRequest(file)
  32176. ? moduleGraph.createFileOnlyEntry(file)
  32177. : await moduleGraph.ensureEntryFromUrl((await fileToUrl(file, config, this)).replace(((_b = (_a = config.server) === null || _a === void 0 ? void 0 : _a.origin) !== null && _b !== void 0 ? _b : '') + config.base, '/'), ssr));
  32178. }
  32179. moduleGraph.updateModuleInfo(thisModule, depModules,
  32180. // The root CSS proxy module is self-accepting and should not
  32181. // have an explicit accept list
  32182. new Set(), isSelfAccepting, ssr);
  32183. for (const file of deps) {
  32184. this.addWatchFile(file);
  32185. }
  32186. }
  32187. else {
  32188. thisModule.isSelfAccepting = isSelfAccepting;
  32189. }
  32190. }
  32191. }
  32192. return {
  32193. code: css,
  32194. map
  32195. };
  32196. }
  32197. };
  32198. }
  32199. /**
  32200. * Plugin applied after user plugins
  32201. */
  32202. function cssPostPlugin(config) {
  32203. // styles initialization in buildStart causes a styling loss in watch
  32204. const styles = new Map();
  32205. let pureCssChunks;
  32206. // when there are multiple rollup outputs and extracting CSS, only emit once,
  32207. // since output formats have no effect on the generated CSS.
  32208. let outputToExtractedCSSMap;
  32209. let hasEmitted = false;
  32210. return {
  32211. name: 'vite:css-post',
  32212. buildStart() {
  32213. // Ensure new caches for every build (i.e. rebuilding in watch mode)
  32214. pureCssChunks = new Set();
  32215. outputToExtractedCSSMap = new Map();
  32216. hasEmitted = false;
  32217. },
  32218. async transform(css, id, options) {
  32219. if (!isCSSRequest(id) ||
  32220. commonjsProxyRE.test(id) ||
  32221. SPECIAL_QUERY_RE.test(id)) {
  32222. return;
  32223. }
  32224. const inlined = inlineRE.test(id);
  32225. const modules = cssModulesCache.get(config).get(id);
  32226. // #6984, #7552
  32227. // `foo.module.css` => modulesCode
  32228. // `foo.module.css?inline` => cssContent
  32229. const modulesCode = modules &&
  32230. !inlined &&
  32231. dataToEsm(modules, { namedExports: true, preferConst: true });
  32232. if (config.command === 'serve') {
  32233. const getContentWithSourcemap = async (content) => {
  32234. var _a;
  32235. if ((_a = config.css) === null || _a === void 0 ? void 0 : _a.devSourcemap) {
  32236. const sourcemap = this.getCombinedSourcemap();
  32237. await injectSourcesContent(sourcemap, cleanUrl(id), config.logger);
  32238. return getCodeWithSourcemap('css', content, sourcemap);
  32239. }
  32240. return content;
  32241. };
  32242. if (isDirectCSSRequest(id)) {
  32243. return await getContentWithSourcemap(css);
  32244. }
  32245. // server only
  32246. if (options === null || options === void 0 ? void 0 : options.ssr) {
  32247. return modulesCode || `export default ${JSON.stringify(css)}`;
  32248. }
  32249. if (inlined) {
  32250. return `export default ${JSON.stringify(css)}`;
  32251. }
  32252. const cssContent = await getContentWithSourcemap(css);
  32253. return [
  32254. `import { updateStyle as __vite__updateStyle, removeStyle as __vite__removeStyle } from ${JSON.stringify(path__default.posix.join(config.base, CLIENT_PUBLIC_PATH))}`,
  32255. `const __vite__id = ${JSON.stringify(id)}`,
  32256. `const __vite__css = ${JSON.stringify(cssContent)}`,
  32257. `__vite__updateStyle(__vite__id, __vite__css)`,
  32258. // css modules exports change on edit so it can't self accept
  32259. `${modulesCode ||
  32260. `import.meta.hot.accept()\nexport default __vite__css`}`,
  32261. `import.meta.hot.prune(() => __vite__removeStyle(__vite__id))`
  32262. ].join('\n');
  32263. }
  32264. // build CSS handling ----------------------------------------------------
  32265. // record css
  32266. // cache css compile result to map
  32267. // and then use the cache replace inline-style-flag when `generateBundle` in vite:build-html plugin
  32268. const inlineCSS = inlineCSSRE.test(id);
  32269. const isHTMLProxy = htmlProxyRE.test(id);
  32270. const query = parseRequest(id);
  32271. if (inlineCSS && isHTMLProxy) {
  32272. addToHTMLProxyTransformResult(`${getAssetHash(cleanUrl(id))}_${Number.parseInt(query.index)}`, css);
  32273. return `export default ''`;
  32274. }
  32275. if (!inlined) {
  32276. styles.set(id, css);
  32277. }
  32278. let code;
  32279. if (usedRE.test(id)) {
  32280. if (modulesCode) {
  32281. code = modulesCode;
  32282. }
  32283. else {
  32284. let content = css;
  32285. if (config.build.minify) {
  32286. content = await minifyCSS(content, config);
  32287. }
  32288. code = `export default ${JSON.stringify(content)}`;
  32289. }
  32290. }
  32291. else {
  32292. // if moduleCode exists return it **even if** it does not have `?used`
  32293. // this will disable tree-shake to work with `import './foo.module.css'` but this usually does not happen
  32294. // this is a limitation of the current approach by `?used` to make tree-shake work
  32295. // See #8936 for more details
  32296. code = modulesCode || `export default ''`;
  32297. }
  32298. return {
  32299. code,
  32300. map: { mappings: '' },
  32301. // avoid the css module from being tree-shaken so that we can retrieve
  32302. // it in renderChunk()
  32303. moduleSideEffects: inlined ? false : 'no-treeshake'
  32304. };
  32305. },
  32306. async renderChunk(code, chunk, opts) {
  32307. let chunkCSS = '';
  32308. let isPureCssChunk = true;
  32309. const ids = Object.keys(chunk.modules);
  32310. for (const id of ids) {
  32311. if (!isCSSRequest(id) ||
  32312. cssModuleRE.test(id) ||
  32313. commonjsProxyRE.test(id)) {
  32314. isPureCssChunk = false;
  32315. }
  32316. if (styles.has(id)) {
  32317. chunkCSS += styles.get(id);
  32318. }
  32319. }
  32320. if (!chunkCSS) {
  32321. return null;
  32322. }
  32323. // resolve asset URL placeholders to their built file URLs and perform
  32324. // minification if necessary
  32325. const processChunkCSS = async (css, { inlined, minify }) => {
  32326. // replace asset url references with resolved url.
  32327. const isRelativeBase = config.base === '' || config.base.startsWith('.');
  32328. css = css.replace(assetUrlRE, (_, fileHash, postfix = '') => {
  32329. const filename = getAssetFilename(fileHash, config) + postfix;
  32330. chunk.viteMetadata.importedAssets.add(cleanUrl(filename));
  32331. if (!isRelativeBase || inlined) {
  32332. // absolute base or relative base but inlined (injected as style tag into
  32333. // index.html) use the base as-is
  32334. return config.base + filename;
  32335. }
  32336. else {
  32337. // relative base + extracted CSS - asset file will be in the same dir
  32338. return `./${path__default.posix.basename(filename)}`;
  32339. }
  32340. });
  32341. // only external @imports and @charset should exist at this point
  32342. // hoist them to the top of the CSS chunk per spec (#1845 and #6333)
  32343. if (css.includes('@import') || css.includes('@charset')) {
  32344. css = await hoistAtRules(css);
  32345. }
  32346. if (minify && config.build.minify) {
  32347. css = await minifyCSS(css, config);
  32348. }
  32349. return css;
  32350. };
  32351. if (config.build.cssCodeSplit) {
  32352. if (isPureCssChunk) {
  32353. // this is a shared CSS-only chunk that is empty.
  32354. pureCssChunks.add(chunk.fileName);
  32355. }
  32356. if (opts.format === 'es' || opts.format === 'cjs') {
  32357. chunkCSS = await processChunkCSS(chunkCSS, {
  32358. inlined: false,
  32359. minify: true
  32360. });
  32361. // emit corresponding css file
  32362. const fileHandle = this.emitFile({
  32363. name: chunk.name + '.css',
  32364. type: 'asset',
  32365. source: chunkCSS
  32366. });
  32367. chunk.viteMetadata.importedCss.add(this.getFileName(fileHandle));
  32368. }
  32369. else if (!config.build.ssr) {
  32370. // legacy build, inline css
  32371. chunkCSS = await processChunkCSS(chunkCSS, {
  32372. inlined: true,
  32373. minify: true
  32374. });
  32375. const style = `__vite_style__`;
  32376. const injectCode = `var ${style} = document.createElement('style');` +
  32377. `${style}.innerHTML = ${JSON.stringify(chunkCSS)};` +
  32378. `document.head.appendChild(${style});`;
  32379. if (config.build.sourcemap) {
  32380. const s = new MagicString(code);
  32381. s.prepend(injectCode);
  32382. return {
  32383. code: s.toString(),
  32384. map: s.generateMap({ hires: true })
  32385. };
  32386. }
  32387. else {
  32388. return { code: injectCode + code };
  32389. }
  32390. }
  32391. }
  32392. else {
  32393. // non-split extracted CSS will be minified together
  32394. chunkCSS = await processChunkCSS(chunkCSS, {
  32395. inlined: false,
  32396. minify: false
  32397. });
  32398. outputToExtractedCSSMap.set(opts, (outputToExtractedCSSMap.get(opts) || '') + chunkCSS);
  32399. }
  32400. return null;
  32401. },
  32402. async generateBundle(opts, bundle) {
  32403. // @ts-ignore asset emits are skipped in legacy bundle
  32404. if (opts.__vite_skip_asset_emit__) {
  32405. return;
  32406. }
  32407. // remove empty css chunks and their imports
  32408. if (pureCssChunks.size) {
  32409. const emptyChunkFiles = [...pureCssChunks]
  32410. .map((file) => path__default.basename(file))
  32411. .join('|')
  32412. .replace(/\./g, '\\.');
  32413. const emptyChunkRE = new RegExp(opts.format === 'es'
  32414. ? `\\bimport\\s*["'][^"']*(?:${emptyChunkFiles})["'];\n?`
  32415. : `\\brequire\\(\\s*["'][^"']*(?:${emptyChunkFiles})["']\\);\n?`, 'g');
  32416. for (const file in bundle) {
  32417. const chunk = bundle[file];
  32418. if (chunk.type === 'chunk') {
  32419. // remove pure css chunk from other chunk's imports,
  32420. // and also register the emitted CSS files under the importer
  32421. // chunks instead.
  32422. chunk.imports = chunk.imports.filter((file) => {
  32423. if (pureCssChunks.has(file)) {
  32424. const { viteMetadata: { importedCss } } = bundle[file];
  32425. importedCss.forEach((file) => chunk.viteMetadata.importedCss.add(file));
  32426. return false;
  32427. }
  32428. return true;
  32429. });
  32430. chunk.code = chunk.code.replace(emptyChunkRE,
  32431. // remove css import while preserving source map location
  32432. (m) => `/* empty css ${''.padEnd(m.length - 15)}*/`);
  32433. }
  32434. }
  32435. const removedPureCssFiles = removedPureCssFilesCache.get(config);
  32436. pureCssChunks.forEach((fileName) => {
  32437. removedPureCssFiles.set(fileName, bundle[fileName]);
  32438. delete bundle[fileName];
  32439. });
  32440. }
  32441. let extractedCss = outputToExtractedCSSMap.get(opts);
  32442. if (extractedCss && !hasEmitted) {
  32443. hasEmitted = true;
  32444. // minify css
  32445. if (config.build.minify) {
  32446. extractedCss = await minifyCSS(extractedCss, config);
  32447. }
  32448. this.emitFile({
  32449. name: 'style.css',
  32450. type: 'asset',
  32451. source: extractedCss
  32452. });
  32453. }
  32454. }
  32455. };
  32456. }
  32457. function createCSSResolvers(config) {
  32458. let cssResolve;
  32459. let sassResolve;
  32460. let lessResolve;
  32461. return {
  32462. get css() {
  32463. return (cssResolve ||
  32464. (cssResolve = config.createResolver({
  32465. extensions: ['.css'],
  32466. mainFields: ['style'],
  32467. tryIndex: false,
  32468. preferRelative: true
  32469. })));
  32470. },
  32471. get sass() {
  32472. return (sassResolve ||
  32473. (sassResolve = config.createResolver({
  32474. extensions: ['.scss', '.sass', '.css'],
  32475. mainFields: ['sass', 'style'],
  32476. tryIndex: true,
  32477. tryPrefix: '_',
  32478. preferRelative: true
  32479. })));
  32480. },
  32481. get less() {
  32482. return (lessResolve ||
  32483. (lessResolve = config.createResolver({
  32484. extensions: ['.less', '.css'],
  32485. mainFields: ['less', 'style'],
  32486. tryIndex: false,
  32487. preferRelative: true
  32488. })));
  32489. }
  32490. };
  32491. }
  32492. function getCssResolversKeys(resolvers) {
  32493. return Object.keys(resolvers);
  32494. }
  32495. async function compileCSS(id, code, config, urlReplacer, atImportResolvers, server) {
  32496. var _a;
  32497. const { modules: modulesOptions, preprocessorOptions, devSourcemap } = config.css || {};
  32498. const isModule = modulesOptions !== false && cssModuleRE.test(id);
  32499. // although at serve time it can work without processing, we do need to
  32500. // crawl them in order to register watch dependencies.
  32501. const needInlineImport = code.includes('@import');
  32502. const hasUrl = cssUrlRE.test(code) || cssImageSetRE.test(code);
  32503. const postcssConfig = await resolvePostcssConfig(config);
  32504. const lang = (_a = id.match(cssLangRE)) === null || _a === void 0 ? void 0 : _a[1];
  32505. // 1. plain css that needs no processing
  32506. if (lang === 'css' &&
  32507. !postcssConfig &&
  32508. !isModule &&
  32509. !needInlineImport &&
  32510. !hasUrl) {
  32511. return { code, map: null };
  32512. }
  32513. let preprocessorMap;
  32514. let modules;
  32515. const deps = new Set();
  32516. // 2. pre-processors: sass etc.
  32517. if (isPreProcessor(lang)) {
  32518. const preProcessor = preProcessors[lang];
  32519. let opts = (preprocessorOptions && preprocessorOptions[lang]) || {};
  32520. // support @import from node dependencies by default
  32521. switch (lang) {
  32522. case "scss" /* scss */:
  32523. case "sass" /* sass */:
  32524. opts = {
  32525. includePaths: ['node_modules'],
  32526. alias: config.resolve.alias,
  32527. ...opts
  32528. };
  32529. break;
  32530. case "less" /* less */:
  32531. case "styl" /* styl */:
  32532. case "stylus" /* stylus */:
  32533. opts = {
  32534. paths: ['node_modules'],
  32535. alias: config.resolve.alias,
  32536. ...opts
  32537. };
  32538. }
  32539. // important: set this for relative import resolving
  32540. opts.filename = cleanUrl(id);
  32541. opts.enableSourcemap = devSourcemap !== null && devSourcemap !== void 0 ? devSourcemap : false;
  32542. const preprocessResult = await preProcessor(code, config.root, opts, atImportResolvers);
  32543. if (preprocessResult.errors.length) {
  32544. throw preprocessResult.errors[0];
  32545. }
  32546. code = preprocessResult.code;
  32547. preprocessorMap = combineSourcemapsIfExists(opts.filename, preprocessResult.map, preprocessResult.additionalMap);
  32548. if (preprocessResult.deps) {
  32549. preprocessResult.deps.forEach((dep) => {
  32550. // sometimes sass registers the file itself as a dep
  32551. if (normalizePath$3(dep) !== normalizePath$3(opts.filename)) {
  32552. deps.add(dep);
  32553. }
  32554. });
  32555. }
  32556. }
  32557. // 3. postcss
  32558. const postcssOptions = (postcssConfig && postcssConfig.options) || {};
  32559. const postcssPlugins = postcssConfig && postcssConfig.plugins ? postcssConfig.plugins.slice() : [];
  32560. if (needInlineImport) {
  32561. postcssPlugins.unshift((await Promise.resolve().then(function () { return require('./dep-a9015192.js'); }).then(function (n) { return n.index; })).default({
  32562. async resolve(id, basedir) {
  32563. const publicFile = checkPublicFile(id, config);
  32564. if (publicFile) {
  32565. return publicFile;
  32566. }
  32567. const resolved = await atImportResolvers.css(id, path__default.join(basedir, '*'));
  32568. if (resolved) {
  32569. return path__default.resolve(resolved);
  32570. }
  32571. return id;
  32572. }
  32573. }));
  32574. }
  32575. postcssPlugins.push(UrlRewritePostcssPlugin({
  32576. replacer: urlReplacer
  32577. }));
  32578. if (isModule) {
  32579. postcssPlugins.unshift((await Promise.resolve().then(function () { return require('./dep-aa4ab47b.js'); }).then(function (n) { return n.index; })).default({
  32580. ...modulesOptions,
  32581. getJSON(cssFileName, _modules, outputFileName) {
  32582. modules = _modules;
  32583. if (modulesOptions && typeof modulesOptions.getJSON === 'function') {
  32584. modulesOptions.getJSON(cssFileName, _modules, outputFileName);
  32585. }
  32586. },
  32587. async resolve(id) {
  32588. for (const key of getCssResolversKeys(atImportResolvers)) {
  32589. const resolved = await atImportResolvers[key](id);
  32590. if (resolved) {
  32591. return path__default.resolve(resolved);
  32592. }
  32593. }
  32594. return id;
  32595. }
  32596. }));
  32597. }
  32598. if (!postcssPlugins.length) {
  32599. return {
  32600. code,
  32601. map: preprocessorMap
  32602. };
  32603. }
  32604. // postcss is an unbundled dep and should be lazy imported
  32605. const postcssResult = await (await Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require('postcss')); }))
  32606. .default(postcssPlugins)
  32607. .process(code, {
  32608. ...postcssOptions,
  32609. to: id,
  32610. from: id,
  32611. map: {
  32612. inline: false,
  32613. annotation: false,
  32614. // postcss may return virtual files
  32615. // we cannot obtain content of them, so this needs to be enabled
  32616. sourcesContent: true
  32617. // when "prev: preprocessorMap", the result map may include duplicate filename in `postcssResult.map.sources`
  32618. // prev: preprocessorMap,
  32619. }
  32620. });
  32621. // record CSS dependencies from @imports
  32622. for (const message of postcssResult.messages) {
  32623. if (message.type === 'dependency') {
  32624. deps.add(normalizePath$3(message.file));
  32625. }
  32626. else if (message.type === 'dir-dependency') {
  32627. // https://github.com/postcss/postcss/blob/main/docs/guidelines/plugin.md#3-dependencies
  32628. const { dir, glob: globPattern = '**' } = message;
  32629. const pattern = normalizePath$3(path__default.resolve(path__default.dirname(id), dir)) + `/` + globPattern;
  32630. const files = out.sync(pattern, {
  32631. ignore: ['**/node_modules/**']
  32632. });
  32633. for (let i = 0; i < files.length; i++) {
  32634. deps.add(files[i]);
  32635. }
  32636. if (server) {
  32637. // register glob importers so we can trigger updates on file add/remove
  32638. if (!(id in server._globImporters)) {
  32639. server._globImporters[id] = {
  32640. module: server.moduleGraph.getModuleById(id),
  32641. importGlobs: []
  32642. };
  32643. }
  32644. server._globImporters[id].importGlobs.push({
  32645. base: config.root,
  32646. pattern
  32647. });
  32648. }
  32649. }
  32650. else if (message.type === 'warning') {
  32651. let msg = `[vite:css] ${message.text}`;
  32652. if (message.line && message.column) {
  32653. msg += `\n${generateCodeFrame(code, {
  32654. line: message.line,
  32655. column: message.column
  32656. })}`;
  32657. }
  32658. config.logger.warn(colors$1.yellow(msg));
  32659. }
  32660. }
  32661. if (!devSourcemap) {
  32662. return {
  32663. ast: postcssResult,
  32664. code: postcssResult.css,
  32665. map: { mappings: '' },
  32666. modules,
  32667. deps
  32668. };
  32669. }
  32670. const rawPostcssMap = postcssResult.map.toJSON();
  32671. const postcssMap = formatPostcssSourceMap(
  32672. // version property of rawPostcssMap is declared as string
  32673. // but actually it is a number
  32674. rawPostcssMap, cleanUrl(id));
  32675. return {
  32676. ast: postcssResult,
  32677. code: postcssResult.css,
  32678. map: combineSourcemapsIfExists(cleanUrl(id), postcssMap, preprocessorMap),
  32679. modules,
  32680. deps
  32681. };
  32682. }
  32683. function formatPostcssSourceMap(rawMap, file) {
  32684. const inputFileDir = path__default.dirname(file);
  32685. const sources = rawMap.sources.map((source) => {
  32686. const cleanSource = cleanUrl(decodeURIComponent(source));
  32687. // postcss returns virtual files
  32688. if (/^<.+>$/.test(cleanSource)) {
  32689. return `\0${cleanSource}`;
  32690. }
  32691. return normalizePath$3(path__default.resolve(inputFileDir, cleanSource));
  32692. });
  32693. return {
  32694. file,
  32695. mappings: rawMap.mappings,
  32696. names: rawMap.names,
  32697. sources,
  32698. sourcesContent: rawMap.sourcesContent,
  32699. version: rawMap.version
  32700. };
  32701. }
  32702. function combineSourcemapsIfExists(filename, map1, map2) {
  32703. return map1 && map2
  32704. ? combineSourcemaps(filename, [
  32705. // type of version property of ExistingRawSourceMap is number
  32706. // but it is always 3
  32707. map1,
  32708. map2
  32709. ])
  32710. : map1;
  32711. }
  32712. async function resolvePostcssConfig(config) {
  32713. var _a;
  32714. let result = postcssConfigCache.get(config);
  32715. if (result !== undefined) {
  32716. return result;
  32717. }
  32718. // inline postcss config via vite config
  32719. const inlineOptions = (_a = config.css) === null || _a === void 0 ? void 0 : _a.postcss;
  32720. if (isObject$1(inlineOptions)) {
  32721. const options = { ...inlineOptions };
  32722. delete options.plugins;
  32723. result = {
  32724. options,
  32725. plugins: inlineOptions.plugins || []
  32726. };
  32727. }
  32728. else {
  32729. const searchPath = typeof inlineOptions === 'string' ? inlineOptions : config.root;
  32730. try {
  32731. // @ts-ignore
  32732. result = await src$1({}, searchPath);
  32733. }
  32734. catch (e) {
  32735. if (!/No PostCSS Config found/.test(e.message)) {
  32736. if (e instanceof Error) {
  32737. const { name, message, stack } = e;
  32738. e.name = 'Failed to load PostCSS config';
  32739. e.message = `Failed to load PostCSS config (searchPath: ${searchPath}): [${name}] ${message}\n${stack}`;
  32740. e.stack = ''; // add stack to message to retain stack
  32741. throw e;
  32742. }
  32743. else {
  32744. throw new Error(`Failed to load PostCSS config: ${e}`);
  32745. }
  32746. }
  32747. result = null;
  32748. }
  32749. }
  32750. postcssConfigCache.set(config, result);
  32751. return result;
  32752. }
  32753. // https://drafts.csswg.org/css-syntax-3/#identifier-code-point
  32754. const cssUrlRE = /(?<=^|[^\w\-\u0080-\uffff])url\(\s*('[^']+'|"[^"]+"|[^'")]+)\s*\)/;
  32755. const cssDataUriRE = /(?<=^|[^\w\-\u0080-\uffff])data-uri\(\s*('[^']+'|"[^"]+"|[^'")]+)\s*\)/;
  32756. const importCssRE = /@import ('[^']+\.css'|"[^"]+\.css"|[^'")]+\.css)/;
  32757. const cssImageSetRE = /(?<=image-set\()((?:[\w\-]+\([^\)]*\)|[^)])*)(?=\))/;
  32758. const UrlRewritePostcssPlugin = (opts) => {
  32759. if (!opts) {
  32760. throw new Error('base or replace is required');
  32761. }
  32762. return {
  32763. postcssPlugin: 'vite-url-rewrite',
  32764. Once(root) {
  32765. const promises = [];
  32766. root.walkDecls((declaration) => {
  32767. const isCssUrl = cssUrlRE.test(declaration.value);
  32768. const isCssImageSet = cssImageSetRE.test(declaration.value);
  32769. if (isCssUrl || isCssImageSet) {
  32770. const replacerForDeclaration = (rawUrl) => {
  32771. var _a;
  32772. const importer = (_a = declaration.source) === null || _a === void 0 ? void 0 : _a.input.file;
  32773. return opts.replacer(rawUrl, importer);
  32774. };
  32775. const rewriterToUse = isCssImageSet
  32776. ? rewriteCssImageSet
  32777. : rewriteCssUrls;
  32778. promises.push(rewriterToUse(declaration.value, replacerForDeclaration).then((url) => {
  32779. declaration.value = url;
  32780. }));
  32781. }
  32782. });
  32783. if (promises.length) {
  32784. return Promise.all(promises);
  32785. }
  32786. }
  32787. };
  32788. };
  32789. UrlRewritePostcssPlugin.postcss = true;
  32790. function rewriteCssUrls(css, replacer) {
  32791. return asyncReplace(css, cssUrlRE, async (match) => {
  32792. const [matched, rawUrl] = match;
  32793. return await doUrlReplace(rawUrl, matched, replacer);
  32794. });
  32795. }
  32796. function rewriteCssDataUris(css, replacer) {
  32797. return asyncReplace(css, cssDataUriRE, async (match) => {
  32798. const [matched, rawUrl] = match;
  32799. return await doUrlReplace(rawUrl, matched, replacer, 'data-uri');
  32800. });
  32801. }
  32802. function rewriteImportCss(css, replacer) {
  32803. return asyncReplace(css, importCssRE, async (match) => {
  32804. const [matched, rawUrl] = match;
  32805. return await doImportCSSReplace(rawUrl, matched, replacer);
  32806. });
  32807. }
  32808. // TODO: image and cross-fade could contain a "url" that needs to be processed
  32809. // https://drafts.csswg.org/css-images-4/#image-notation
  32810. // https://drafts.csswg.org/css-images-4/#cross-fade-function
  32811. const cssNotProcessedRE = /(gradient|element|cross-fade|image)\(/;
  32812. async function rewriteCssImageSet(css, replacer) {
  32813. return await asyncReplace(css, cssImageSetRE, async (match) => {
  32814. const [, rawUrl] = match;
  32815. const url = await processSrcSet(rawUrl, async ({ url }) => {
  32816. // the url maybe url(...)
  32817. if (cssUrlRE.test(url)) {
  32818. return await rewriteCssUrls(url, replacer);
  32819. }
  32820. if (!cssNotProcessedRE.test(url)) {
  32821. return await doUrlReplace(url, url, replacer);
  32822. }
  32823. return url;
  32824. });
  32825. return url;
  32826. });
  32827. }
  32828. async function doUrlReplace(rawUrl, matched, replacer, funcName = 'url') {
  32829. let wrap = '';
  32830. const first = rawUrl[0];
  32831. if (first === `"` || first === `'`) {
  32832. wrap = first;
  32833. rawUrl = rawUrl.slice(1, -1);
  32834. }
  32835. if (isExternalUrl(rawUrl) ||
  32836. isDataUrl(rawUrl) ||
  32837. rawUrl.startsWith('#') ||
  32838. varRE.test(rawUrl)) {
  32839. return matched;
  32840. }
  32841. const newUrl = await replacer(rawUrl);
  32842. if (wrap === '' && newUrl !== encodeURI(newUrl)) {
  32843. // The new url might need wrapping even if the original did not have it, e.g. if a space was added during replacement
  32844. wrap = "'";
  32845. }
  32846. return `${funcName}(${wrap}${newUrl}${wrap})`;
  32847. }
  32848. async function doImportCSSReplace(rawUrl, matched, replacer) {
  32849. let wrap = '';
  32850. const first = rawUrl[0];
  32851. if (first === `"` || first === `'`) {
  32852. wrap = first;
  32853. rawUrl = rawUrl.slice(1, -1);
  32854. }
  32855. if (isExternalUrl(rawUrl) || isDataUrl(rawUrl) || rawUrl.startsWith('#')) {
  32856. return matched;
  32857. }
  32858. return `@import ${wrap}${await replacer(rawUrl)}${wrap}`;
  32859. }
  32860. async function minifyCSS(css, config) {
  32861. try {
  32862. const { code, warnings } = await esbuild.transform(css, {
  32863. loader: 'css',
  32864. minify: true,
  32865. target: config.build.cssTarget || undefined
  32866. });
  32867. if (warnings.length) {
  32868. const msgs = await esbuild.formatMessages(warnings, { kind: 'warning' });
  32869. config.logger.warn(colors$1.yellow(`warnings when minifying css:\n${msgs.join('\n')}`));
  32870. }
  32871. return code;
  32872. }
  32873. catch (e) {
  32874. if (e.errors) {
  32875. const msgs = await esbuild.formatMessages(e.errors, { kind: 'error' });
  32876. e.frame = '\n' + msgs.join('\n');
  32877. e.loc = e.errors[0].location;
  32878. }
  32879. throw e;
  32880. }
  32881. }
  32882. async function hoistAtRules(css) {
  32883. const s = new MagicString(css);
  32884. const cleanCss = emptyCssComments(css);
  32885. let match;
  32886. // #1845
  32887. // CSS @import can only appear at top of the file. We need to hoist all @import
  32888. // to top when multiple files are concatenated.
  32889. // match until semicolon that's not in quotes
  32890. const atImportRE = /@import\s*(?:url\([^\)]*\)|"([^"]|(?<=\\)")*"|'([^']|(?<=\\)')*'|[^;]*).*?;/gm;
  32891. while ((match = atImportRE.exec(cleanCss))) {
  32892. s.remove(match.index, match.index + match[0].length);
  32893. // Use `appendLeft` instead of `prepend` to preserve original @import order
  32894. s.appendLeft(0, match[0]);
  32895. }
  32896. // #6333
  32897. // CSS @charset must be the top-first in the file, hoist the first to top
  32898. const atCharsetRE = /@charset\s*(?:"([^"]|(?<=\\)")*"|'([^']|(?<=\\)')*'|[^;]*).*?;/gm;
  32899. let foundCharset = false;
  32900. while ((match = atCharsetRE.exec(cleanCss))) {
  32901. s.remove(match.index, match.index + match[0].length);
  32902. if (!foundCharset) {
  32903. s.prepend(match[0]);
  32904. foundCharset = true;
  32905. }
  32906. }
  32907. return s.toString();
  32908. }
  32909. const loadedPreprocessors = {};
  32910. function loadPreprocessor(lang, root) {
  32911. var _a, _b;
  32912. if (lang in loadedPreprocessors) {
  32913. return loadedPreprocessors[lang];
  32914. }
  32915. try {
  32916. // Search for the preprocessor in the root directory first, and fall back
  32917. // to the default require paths.
  32918. const fallbackPaths = ((_b = (_a = require.resolve).paths) === null || _b === void 0 ? void 0 : _b.call(_a, lang)) || [];
  32919. const resolved = require.resolve(lang, { paths: [root, ...fallbackPaths] });
  32920. return (loadedPreprocessors[lang] = require(resolved));
  32921. }
  32922. catch (e) {
  32923. if (e.code === 'MODULE_NOT_FOUND') {
  32924. throw new Error(`Preprocessor dependency "${lang}" not found. Did you install it?`);
  32925. }
  32926. else {
  32927. const message = new Error(`Preprocessor dependency "${lang}" failed to load:\n${e.message}`);
  32928. message.stack = e.stack + '\n' + message.stack;
  32929. throw message;
  32930. }
  32931. }
  32932. }
  32933. // .scss/.sass processor
  32934. const scss = async (source, root, options, resolvers) => {
  32935. const render = loadPreprocessor("sass" /* sass */, root).render;
  32936. const internalImporter = (url, importer, done) => {
  32937. resolvers.sass(url, importer).then((resolved) => {
  32938. if (resolved) {
  32939. rebaseUrls(resolved, options.filename, options.alias)
  32940. .then((data) => done === null || done === void 0 ? void 0 : done(data))
  32941. .catch((data) => done === null || done === void 0 ? void 0 : done(data));
  32942. }
  32943. else {
  32944. done === null || done === void 0 ? void 0 : done(null);
  32945. }
  32946. });
  32947. };
  32948. const importer = [internalImporter];
  32949. if (options.importer) {
  32950. Array.isArray(options.importer)
  32951. ? importer.push(...options.importer)
  32952. : importer.push(options.importer);
  32953. }
  32954. const { content: data, map: additionalMap } = await getSource(source, options.filename, options.additionalData, options.enableSourcemap);
  32955. const finalOptions = {
  32956. ...options,
  32957. data,
  32958. file: options.filename,
  32959. outFile: options.filename,
  32960. importer,
  32961. ...(options.enableSourcemap
  32962. ? {
  32963. sourceMap: true,
  32964. omitSourceMapUrl: true,
  32965. sourceMapRoot: path__default.dirname(options.filename)
  32966. }
  32967. : {})
  32968. };
  32969. try {
  32970. const result = await new Promise((resolve, reject) => {
  32971. render(finalOptions, (err, res) => {
  32972. if (err) {
  32973. reject(err);
  32974. }
  32975. else {
  32976. resolve(res);
  32977. }
  32978. });
  32979. });
  32980. const deps = result.stats.includedFiles;
  32981. const map = result.map
  32982. ? JSON.parse(result.map.toString())
  32983. : undefined;
  32984. return {
  32985. code: result.css.toString(),
  32986. map,
  32987. additionalMap,
  32988. errors: [],
  32989. deps
  32990. };
  32991. }
  32992. catch (e) {
  32993. // normalize SASS error
  32994. e.id = e.file;
  32995. e.frame = e.formatted;
  32996. return { code: '', errors: [e], deps: [] };
  32997. }
  32998. };
  32999. const sass = (source, root, options, aliasResolver) => scss(source, root, {
  33000. ...options,
  33001. indentedSyntax: true
  33002. }, aliasResolver);
  33003. /**
  33004. * relative url() inside \@imported sass and less files must be rebased to use
  33005. * root file as base.
  33006. */
  33007. async function rebaseUrls(file, rootFile, alias) {
  33008. file = path__default.resolve(file); // ensure os-specific flashes
  33009. // in the same dir, no need to rebase
  33010. const fileDir = path__default.dirname(file);
  33011. const rootDir = path__default.dirname(rootFile);
  33012. if (fileDir === rootDir) {
  33013. return { file };
  33014. }
  33015. const content = fs__default.readFileSync(file, 'utf-8');
  33016. // no url()
  33017. const hasUrls = cssUrlRE.test(content);
  33018. // data-uri() calls
  33019. const hasDataUris = cssDataUriRE.test(content);
  33020. // no @import xxx.css
  33021. const hasImportCss = importCssRE.test(content);
  33022. if (!hasUrls && !hasDataUris && !hasImportCss) {
  33023. return { file };
  33024. }
  33025. let rebased;
  33026. const rebaseFn = (url) => {
  33027. if (url.startsWith('/'))
  33028. return url;
  33029. // match alias, no need to rewrite
  33030. for (const { find } of alias) {
  33031. const matches = typeof find === 'string' ? url.startsWith(find) : find.test(url);
  33032. if (matches) {
  33033. return url;
  33034. }
  33035. }
  33036. const absolute = path__default.resolve(fileDir, url);
  33037. const relative = path__default.relative(rootDir, absolute);
  33038. return normalizePath$3(relative);
  33039. };
  33040. // fix css imports in less such as `@import "foo.css"`
  33041. if (hasImportCss) {
  33042. rebased = await rewriteImportCss(content, rebaseFn);
  33043. }
  33044. if (hasUrls) {
  33045. rebased = await rewriteCssUrls(rebased || content, rebaseFn);
  33046. }
  33047. if (hasDataUris) {
  33048. rebased = await rewriteCssDataUris(rebased || content, rebaseFn);
  33049. }
  33050. return {
  33051. file,
  33052. contents: rebased
  33053. };
  33054. }
  33055. // .less
  33056. const less = async (source, root, options, resolvers) => {
  33057. const nodeLess = loadPreprocessor("less" /* less */, root);
  33058. const viteResolverPlugin = createViteLessPlugin(nodeLess, options.filename, options.alias, resolvers);
  33059. const { content, map: additionalMap } = await getSource(source, options.filename, options.additionalData, options.enableSourcemap);
  33060. let result;
  33061. try {
  33062. result = await nodeLess.render(content, {
  33063. ...options,
  33064. plugins: [viteResolverPlugin, ...(options.plugins || [])],
  33065. ...(options.enableSourcemap
  33066. ? {
  33067. sourceMap: {
  33068. outputSourceFiles: true,
  33069. sourceMapFileInline: false
  33070. }
  33071. }
  33072. : {})
  33073. });
  33074. }
  33075. catch (e) {
  33076. const error = e;
  33077. // normalize error info
  33078. const normalizedError = new Error(error.message || error.type);
  33079. normalizedError.loc = {
  33080. file: error.filename || options.filename,
  33081. line: error.line,
  33082. column: error.column
  33083. };
  33084. return { code: '', errors: [normalizedError], deps: [] };
  33085. }
  33086. const map = result.map && JSON.parse(result.map);
  33087. if (map) {
  33088. delete map.sourcesContent;
  33089. }
  33090. return {
  33091. code: result.css.toString(),
  33092. map,
  33093. additionalMap,
  33094. deps: result.imports,
  33095. errors: []
  33096. };
  33097. };
  33098. /**
  33099. * Less manager, lazy initialized
  33100. */
  33101. let ViteLessManager;
  33102. function createViteLessPlugin(less, rootFile, alias, resolvers) {
  33103. if (!ViteLessManager) {
  33104. ViteLessManager = class ViteManager extends less.FileManager {
  33105. constructor(rootFile, resolvers, alias) {
  33106. super();
  33107. this.rootFile = rootFile;
  33108. this.resolvers = resolvers;
  33109. this.alias = alias;
  33110. }
  33111. supports() {
  33112. return true;
  33113. }
  33114. supportsSync() {
  33115. return false;
  33116. }
  33117. async loadFile(filename, dir, opts, env) {
  33118. const resolved = await this.resolvers.less(filename, path__default.join(dir, '*'));
  33119. if (resolved) {
  33120. const result = await rebaseUrls(resolved, this.rootFile, this.alias);
  33121. let contents;
  33122. if (result && 'contents' in result) {
  33123. contents = result.contents;
  33124. }
  33125. else {
  33126. contents = fs__default.readFileSync(resolved, 'utf-8');
  33127. }
  33128. return {
  33129. filename: path__default.resolve(resolved),
  33130. contents
  33131. };
  33132. }
  33133. else {
  33134. return super.loadFile(filename, dir, opts, env);
  33135. }
  33136. }
  33137. };
  33138. }
  33139. return {
  33140. install(_, pluginManager) {
  33141. pluginManager.addFileManager(new ViteLessManager(rootFile, resolvers, alias));
  33142. },
  33143. minVersion: [3, 0, 0]
  33144. };
  33145. }
  33146. // .styl
  33147. const styl = async (source, root, options) => {
  33148. var _a;
  33149. const nodeStylus = loadPreprocessor("stylus" /* stylus */, root);
  33150. // Get source with preprocessor options.additionalData. Make sure a new line separator
  33151. // is added to avoid any render error, as added stylus content may not have semi-colon separators
  33152. const { content, map: additionalMap } = await getSource(source, options.filename, options.additionalData, options.enableSourcemap, '\n');
  33153. // Get preprocessor options.imports dependencies as stylus
  33154. // does not return them with its builtin `.deps()` method
  33155. const importsDeps = ((_a = options.imports) !== null && _a !== void 0 ? _a : []).map((dep) => path__default.resolve(dep));
  33156. try {
  33157. const ref = nodeStylus(content, options);
  33158. if (options.enableSourcemap) {
  33159. ref.set('sourcemap', {
  33160. comment: false,
  33161. inline: false,
  33162. basePath: root
  33163. });
  33164. }
  33165. const result = ref.render();
  33166. // Concat imports deps with computed deps
  33167. const deps = [...ref.deps(), ...importsDeps];
  33168. // @ts-expect-error sourcemap exists
  33169. const map = ref.sourcemap;
  33170. return {
  33171. code: result,
  33172. map: formatStylusSourceMap(map, root),
  33173. additionalMap,
  33174. errors: [],
  33175. deps
  33176. };
  33177. }
  33178. catch (e) {
  33179. return { code: '', errors: [e], deps: [] };
  33180. }
  33181. };
  33182. function formatStylusSourceMap(mapBefore, root) {
  33183. if (!mapBefore)
  33184. return undefined;
  33185. const map = { ...mapBefore };
  33186. const resolveFromRoot = (p) => normalizePath$3(path__default.resolve(root, p));
  33187. if (map.file) {
  33188. map.file = resolveFromRoot(map.file);
  33189. }
  33190. map.sources = map.sources.map(resolveFromRoot);
  33191. return map;
  33192. }
  33193. async function getSource(source, filename, additionalData, enableSourcemap, sep = '') {
  33194. if (!additionalData)
  33195. return { content: source };
  33196. if (typeof additionalData === 'function') {
  33197. const newContent = await additionalData(source, filename);
  33198. if (typeof newContent === 'string') {
  33199. return { content: newContent };
  33200. }
  33201. return newContent;
  33202. }
  33203. if (!enableSourcemap) {
  33204. return { content: additionalData + sep + source };
  33205. }
  33206. const ms = new MagicString(source);
  33207. ms.appendLeft(0, sep);
  33208. ms.appendLeft(0, additionalData);
  33209. const map = ms.generateMap({ hires: true });
  33210. map.file = filename;
  33211. map.sources = [filename];
  33212. return {
  33213. content: ms.toString(),
  33214. map
  33215. };
  33216. }
  33217. const preProcessors = Object.freeze({
  33218. ["less" /* less */]: less,
  33219. ["sass" /* sass */]: sass,
  33220. ["scss" /* scss */]: scss,
  33221. ["styl" /* styl */]: styl,
  33222. ["stylus" /* stylus */]: styl
  33223. });
  33224. function isPreProcessor(lang) {
  33225. return lang && lang in preProcessors;
  33226. }
  33227. function formatGlobRelativePattern(base, pattern) {
  33228. let parentDepth = 0;
  33229. while (pattern.startsWith('../')) {
  33230. pattern = pattern.slice(3);
  33231. base = path__default.resolve(base, '../');
  33232. parentDepth++;
  33233. }
  33234. if (pattern.startsWith('./')) {
  33235. pattern = pattern.slice(2);
  33236. }
  33237. return { base, pattern, parentDepth, isAbsolute: false };
  33238. }
  33239. async function transformImportGlob(source, pos, importer, importIndex, root, logger, normalizeUrl, resolve, preload = true) {
  33240. var _a;
  33241. const isEager = source.slice(pos, pos + 21) === 'import.meta.globEager';
  33242. const isEagerDefault = isEager && source.slice(pos + 21, pos + 28) === 'Default';
  33243. const err = (msg) => {
  33244. const e = new Error(`Invalid glob import syntax: ${msg}`);
  33245. e.pos = pos;
  33246. return e;
  33247. };
  33248. importer = cleanUrl(importer);
  33249. const importerBasename = path__default.basename(importer);
  33250. const [userPattern, options, endIndex] = lexGlobPattern(source, pos);
  33251. let globParams = null;
  33252. if (userPattern.startsWith('/')) {
  33253. globParams = {
  33254. isAbsolute: true,
  33255. base: path__default.resolve(root),
  33256. pattern: userPattern.slice(1),
  33257. parentDepth: 0
  33258. };
  33259. }
  33260. else if (userPattern.startsWith('.')) {
  33261. globParams = formatGlobRelativePattern(path__default.dirname(importer), userPattern);
  33262. }
  33263. else if (resolve) {
  33264. const resolvedId = await resolve(userPattern, importer);
  33265. if (resolvedId) {
  33266. const importerDirname = path__default.dirname(importer);
  33267. globParams = formatGlobRelativePattern(importerDirname, normalizePath$3(path__default.relative(importerDirname, resolvedId)));
  33268. }
  33269. }
  33270. if (!globParams) {
  33271. throw err(`pattern must start with "." or "/" (relative to project root) or alias path`);
  33272. }
  33273. const { base, parentDepth, isAbsolute, pattern } = globParams;
  33274. const files = out.sync(pattern, {
  33275. cwd: base,
  33276. // Ignore node_modules by default unless explicitly indicated in the pattern
  33277. ignore: /(^|\/)node_modules\//.test(pattern) ? [] : ['**/node_modules/**']
  33278. });
  33279. const imports = [];
  33280. let importsString = ``;
  33281. let entries = ``;
  33282. for (let i = 0; i < files.length; i++) {
  33283. // skip importer itself
  33284. if (files[i] === importerBasename)
  33285. continue;
  33286. const file = isAbsolute
  33287. ? `/${files[i]}`
  33288. : parentDepth
  33289. ? `${'../'.repeat(parentDepth)}${files[i]}`
  33290. : `./${files[i]}`;
  33291. let importee = file;
  33292. if (normalizeUrl) {
  33293. [importee] = await normalizeUrl(file, pos);
  33294. }
  33295. imports.push(importee);
  33296. // TODO remove assert syntax for the Vite 3.0 release.
  33297. const isRawAssert = ((_a = options === null || options === void 0 ? void 0 : options.assert) === null || _a === void 0 ? void 0 : _a.type) === 'raw';
  33298. const isRawType = (options === null || options === void 0 ? void 0 : options.as) === 'raw';
  33299. if (isRawType || isRawAssert) {
  33300. if (isRawAssert) {
  33301. logger.warn(colors$1.yellow(colors$1.bold("(!) import.meta.glob('...', { assert: { type: 'raw' }}) is deprecated. Use import.meta.glob('...', { as: 'raw' }) instead.")));
  33302. }
  33303. entries += ` ${JSON.stringify(file)}: ${JSON.stringify(await fs$n.promises.readFile(path__default.join(base, files[i]), 'utf-8'))},`;
  33304. }
  33305. else {
  33306. const importeeUrl = isCSSRequest(importee) ? `${importee}?used` : importee;
  33307. if (isEager) {
  33308. const identifier = `__glob_${importIndex}_${i}`;
  33309. // css imports injecting a ?used query to export the css string
  33310. importsString += `import ${isEagerDefault ? `` : `* as `}${identifier} from ${JSON.stringify(importeeUrl)};`;
  33311. entries += ` ${JSON.stringify(file)}: ${identifier},`;
  33312. }
  33313. else {
  33314. let imp = `import(${JSON.stringify(importeeUrl)})`;
  33315. if (!normalizeUrl && preload) {
  33316. imp =
  33317. `(${isModernFlag}` +
  33318. `? ${preloadMethod}(()=>${imp},"${preloadMarker}")` +
  33319. `: ${imp})`;
  33320. }
  33321. entries += ` ${JSON.stringify(file)}: () => ${imp},`;
  33322. }
  33323. }
  33324. }
  33325. return {
  33326. imports,
  33327. importsString,
  33328. exp: `{${entries}}`,
  33329. endIndex,
  33330. isEager,
  33331. pattern,
  33332. base
  33333. };
  33334. }
  33335. function lexGlobPattern(code, pos) {
  33336. let state = 0 /* inCall */;
  33337. let pattern = '';
  33338. let i = code.indexOf(`(`, pos) + 1;
  33339. outer: for (; i < code.length; i++) {
  33340. const char = code.charAt(i);
  33341. switch (state) {
  33342. case 0 /* inCall */:
  33343. if (char === `'`) {
  33344. state = 1 /* inSingleQuoteString */;
  33345. }
  33346. else if (char === `"`) {
  33347. state = 2 /* inDoubleQuoteString */;
  33348. }
  33349. else if (char === '`') {
  33350. state = 3 /* inTemplateString */;
  33351. }
  33352. else if (/\s/.test(char)) {
  33353. continue;
  33354. }
  33355. else {
  33356. error$2(i);
  33357. }
  33358. break;
  33359. case 1 /* inSingleQuoteString */:
  33360. if (char === `'`) {
  33361. break outer;
  33362. }
  33363. else {
  33364. pattern += char;
  33365. }
  33366. break;
  33367. case 2 /* inDoubleQuoteString */:
  33368. if (char === `"`) {
  33369. break outer;
  33370. }
  33371. else {
  33372. pattern += char;
  33373. }
  33374. break;
  33375. case 3 /* inTemplateString */:
  33376. if (char === '`') {
  33377. break outer;
  33378. }
  33379. else {
  33380. pattern += char;
  33381. }
  33382. break;
  33383. default:
  33384. throw new Error('unknown import.meta.glob lexer state');
  33385. }
  33386. }
  33387. const noCommentCode = code
  33388. .slice(i + 1)
  33389. .replace(singlelineCommentsRE, blankReplacer)
  33390. .replace(multilineCommentsRE, blankReplacer);
  33391. const endIndex = noCommentCode.indexOf(')');
  33392. const optionString = noCommentCode.substring(0, endIndex);
  33393. const commaIndex = optionString.indexOf(',');
  33394. let options = {};
  33395. if (commaIndex > -1) {
  33396. options = lib$2.parse(optionString.substring(commaIndex + 1));
  33397. }
  33398. return [pattern, options, endIndex + i + 2];
  33399. }
  33400. function error$2(pos) {
  33401. const err = new Error(`import.meta.glob() can only accept string literals.`);
  33402. err.pos = pos;
  33403. throw err;
  33404. }
  33405. /**
  33406. * A flag for injected helpers. This flag will be set to `false` if the output
  33407. * target is not native es - so that injected helper logic can be conditionally
  33408. * dropped.
  33409. */
  33410. const isModernFlag = `__VITE_IS_MODERN__`;
  33411. const preloadMethod = `__vitePreload`;
  33412. const preloadMarker = `__VITE_PRELOAD__`;
  33413. const preloadBaseMarker = `__VITE_PRELOAD_BASE__`;
  33414. const preloadHelperId = 'vite/preload-helper';
  33415. const preloadMarkerWithQuote = `"${preloadMarker}"`;
  33416. const dynamicImportPrefixRE = /import\s*\(/;
  33417. /**
  33418. * Helper for preloading CSS and direct imports of async chunks in parallel to
  33419. * the async chunk itself.
  33420. */
  33421. function detectScriptRel() {
  33422. // @ts-ignore
  33423. const relList = document.createElement('link').relList;
  33424. // @ts-ignore
  33425. return relList && relList.supports && relList.supports('modulepreload')
  33426. ? 'modulepreload'
  33427. : 'preload';
  33428. }
  33429. function preload(baseModule, deps) {
  33430. // @ts-ignore
  33431. if (!__VITE_IS_MODERN__ || !deps || deps.length === 0) {
  33432. return baseModule();
  33433. }
  33434. return Promise.all(deps.map((dep) => {
  33435. // @ts-ignore
  33436. dep = `${base}${dep}`;
  33437. // @ts-ignore
  33438. if (dep in seen)
  33439. return;
  33440. // @ts-ignore
  33441. seen[dep] = true;
  33442. const isCss = dep.endsWith('.css');
  33443. const cssSelector = isCss ? '[rel="stylesheet"]' : '';
  33444. // @ts-ignore check if the file is already preloaded by SSR markup
  33445. if (document.querySelector(`link[href="${dep}"]${cssSelector}`)) {
  33446. return;
  33447. }
  33448. // @ts-ignore
  33449. const link = document.createElement('link');
  33450. // @ts-ignore
  33451. link.rel = isCss ? 'stylesheet' : scriptRel;
  33452. if (!isCss) {
  33453. link.as = 'script';
  33454. link.crossOrigin = '';
  33455. }
  33456. link.href = dep;
  33457. // @ts-ignore
  33458. document.head.appendChild(link);
  33459. if (isCss) {
  33460. return new Promise((res, rej) => {
  33461. link.addEventListener('load', res);
  33462. link.addEventListener('error', () => rej(new Error(`Unable to preload CSS for ${dep}`)));
  33463. });
  33464. }
  33465. })).then(() => baseModule());
  33466. }
  33467. /**
  33468. * Build only. During serve this is performed as part of ./importAnalysis.
  33469. */
  33470. function buildImportAnalysisPlugin(config) {
  33471. const ssr = !!config.build.ssr;
  33472. const isWorker = config.isWorker;
  33473. const insertPreload = !(ssr || !!config.build.lib || isWorker);
  33474. const scriptRel = config.build.polyfillModulePreload
  33475. ? `'modulepreload'`
  33476. : `(${detectScriptRel.toString()})()`;
  33477. const preloadCode = `const scriptRel = ${scriptRel};const seen = {};const base = '${preloadBaseMarker}';export const ${preloadMethod} = ${preload.toString()}`;
  33478. const resolve = config.createResolver({
  33479. preferRelative: true,
  33480. tryIndex: false,
  33481. extensions: []
  33482. });
  33483. return {
  33484. name: 'vite:build-import-analysis',
  33485. resolveId(id) {
  33486. if (id === preloadHelperId) {
  33487. return id;
  33488. }
  33489. },
  33490. load(id) {
  33491. if (id === preloadHelperId) {
  33492. return preloadCode.replace(preloadBaseMarker, config.base);
  33493. }
  33494. },
  33495. async transform(source, importer) {
  33496. if (importer.includes('node_modules') &&
  33497. !source.includes('import.meta.glob') &&
  33498. !dynamicImportPrefixRE.test(source)) {
  33499. return;
  33500. }
  33501. await init;
  33502. let imports = [];
  33503. try {
  33504. imports = parse$e(source)[0];
  33505. }
  33506. catch (e) {
  33507. this.error(e, e.idx);
  33508. }
  33509. if (!imports.length) {
  33510. return null;
  33511. }
  33512. let s;
  33513. const str = () => s || (s = new MagicString(source));
  33514. let needPreloadHelper = false;
  33515. for (let index = 0; index < imports.length; index++) {
  33516. const { s: start, e: end, ss: expStart, se: expEnd, n: specifier, d: dynamicIndex } = imports[index];
  33517. const isDynamic = dynamicIndex > -1;
  33518. // import.meta.glob
  33519. if (source.slice(start, end) === 'import.meta' &&
  33520. source.slice(end, end + 5) === '.glob') {
  33521. // es worker allow globEager / glob
  33522. // iife worker just allow globEager
  33523. if (isWorker &&
  33524. config.worker.format === 'iife' &&
  33525. source.slice(end, end + 10) !== '.globEager') {
  33526. this.error('`import.meta.glob` is not supported in workers with `iife` format, use `import.meta.globEager` instead.', end);
  33527. }
  33528. const { importsString, exp, endIndex, isEager } = await transformImportGlob(source, start, importer, index, config.root, config.logger, undefined, resolve, insertPreload);
  33529. str().prepend(importsString);
  33530. str().overwrite(expStart, endIndex, exp, { contentOnly: true });
  33531. if (!isEager) {
  33532. needPreloadHelper = true;
  33533. }
  33534. continue;
  33535. }
  33536. if (isDynamic && insertPreload) {
  33537. needPreloadHelper = true;
  33538. str().prependLeft(expStart, `${preloadMethod}(() => `);
  33539. str().appendRight(expEnd, `,${isModernFlag}?"${preloadMarker}":void 0)`);
  33540. }
  33541. // Differentiate CSS imports that use the default export from those that
  33542. // do not by injecting a ?used query - this allows us to avoid including
  33543. // the CSS string when unnecessary (esbuild has trouble tree-shaking
  33544. // them)
  33545. if (specifier &&
  33546. isCSSRequest(specifier) &&
  33547. // always inject ?used query when it is a dynamic import
  33548. // because there is no way to check whether the default export is used
  33549. (source.slice(expStart, start).includes('from') || isDynamic) &&
  33550. // edge case for package names ending with .css (e.g normalize.css)
  33551. !(bareImportRE.test(specifier) && !specifier.includes('/'))) {
  33552. const url = specifier.replace(/\?|$/, (m) => `?used${m ? '&' : ''}`);
  33553. str().overwrite(start, end, isDynamic ? `'${url}'` : url, {
  33554. contentOnly: true
  33555. });
  33556. }
  33557. }
  33558. if (needPreloadHelper &&
  33559. insertPreload &&
  33560. !source.includes(`const ${preloadMethod} =`)) {
  33561. str().prepend(`import { ${preloadMethod} } from "${preloadHelperId}";`);
  33562. }
  33563. if (s) {
  33564. return {
  33565. code: s.toString(),
  33566. map: config.build.sourcemap ? s.generateMap({ hires: true }) : null
  33567. };
  33568. }
  33569. },
  33570. renderChunk(code, _, { format }) {
  33571. // make sure we only perform the preload logic in modern builds.
  33572. if (code.indexOf(isModernFlag) > -1) {
  33573. const re = new RegExp(isModernFlag, 'g');
  33574. const isModern = String(format === 'es');
  33575. if (config.build.sourcemap) {
  33576. const s = new MagicString(code);
  33577. let match;
  33578. while ((match = re.exec(code))) {
  33579. s.overwrite(match.index, match.index + isModernFlag.length, isModern, { contentOnly: true });
  33580. }
  33581. return {
  33582. code: s.toString(),
  33583. map: s.generateMap({ hires: true })
  33584. };
  33585. }
  33586. else {
  33587. return code.replace(re, isModern);
  33588. }
  33589. }
  33590. return null;
  33591. },
  33592. generateBundle({ format }, bundle) {
  33593. if (format !== 'es' || ssr || isWorker) {
  33594. return;
  33595. }
  33596. for (const file in bundle) {
  33597. const chunk = bundle[file];
  33598. // can't use chunk.dynamicImports.length here since some modules e.g.
  33599. // dynamic import to constant json may get inlined.
  33600. if (chunk.type === 'chunk' && chunk.code.indexOf(preloadMarker) > -1) {
  33601. const code = chunk.code;
  33602. let imports;
  33603. try {
  33604. imports = parse$e(code)[0].filter((i) => i.d > -1);
  33605. }
  33606. catch (e) {
  33607. this.error(e, e.idx);
  33608. }
  33609. const s = new MagicString(code);
  33610. const rewroteMarkerStartPos = new Set(); // position of the leading double quote
  33611. if (imports.length) {
  33612. for (let index = 0; index < imports.length; index++) {
  33613. // To handle escape sequences in specifier strings, the .n field will be provided where possible.
  33614. const { n: name, s: start, e: end, ss: expStart, se: expEnd } = imports[index];
  33615. // check the chunk being imported
  33616. let url = name;
  33617. if (!url) {
  33618. const rawUrl = code.slice(start, end);
  33619. if (rawUrl[0] === `"` && rawUrl[rawUrl.length - 1] === `"`)
  33620. url = rawUrl.slice(1, -1);
  33621. }
  33622. const deps = new Set();
  33623. let hasRemovedPureCssChunk = false;
  33624. if (url) {
  33625. const ownerFilename = chunk.fileName;
  33626. // literal import - trace direct imports and add to deps
  33627. const analyzed = new Set();
  33628. const addDeps = (filename) => {
  33629. if (filename === ownerFilename)
  33630. return;
  33631. if (analyzed.has(filename))
  33632. return;
  33633. analyzed.add(filename);
  33634. const chunk = bundle[filename];
  33635. if (chunk) {
  33636. deps.add(chunk.fileName);
  33637. chunk.viteMetadata.importedCss.forEach((file) => {
  33638. deps.add(file);
  33639. });
  33640. chunk.imports.forEach(addDeps);
  33641. }
  33642. else {
  33643. const removedPureCssFiles = removedPureCssFilesCache.get(config);
  33644. const chunk = removedPureCssFiles.get(filename);
  33645. if (chunk) {
  33646. if (chunk.viteMetadata.importedCss.size) {
  33647. chunk.viteMetadata.importedCss.forEach((file) => {
  33648. deps.add(file);
  33649. });
  33650. hasRemovedPureCssChunk = true;
  33651. }
  33652. s.overwrite(expStart, expEnd, 'Promise.resolve({})', {
  33653. contentOnly: true
  33654. });
  33655. }
  33656. }
  33657. };
  33658. const normalizedFile = path__default.posix.join(path__default.posix.dirname(chunk.fileName), url);
  33659. addDeps(normalizedFile);
  33660. }
  33661. let markerStartPos = code.indexOf(preloadMarkerWithQuote, end);
  33662. // fix issue #3051
  33663. if (markerStartPos === -1 && imports.length === 1) {
  33664. markerStartPos = code.indexOf(preloadMarkerWithQuote);
  33665. }
  33666. if (markerStartPos > 0) {
  33667. s.overwrite(markerStartPos, markerStartPos + preloadMarkerWithQuote.length,
  33668. // the dep list includes the main chunk, so only need to
  33669. // preload when there are actual other deps.
  33670. deps.size > 1 ||
  33671. // main chunk is removed
  33672. (hasRemovedPureCssChunk && deps.size > 0)
  33673. ? `[${[...deps].map((d) => JSON.stringify(d)).join(',')}]`
  33674. : `[]`, { contentOnly: true });
  33675. rewroteMarkerStartPos.add(markerStartPos);
  33676. }
  33677. }
  33678. }
  33679. // there may still be markers due to inlined dynamic imports, remove
  33680. // all the markers regardless
  33681. let markerStartPos = code.indexOf(preloadMarkerWithQuote);
  33682. while (markerStartPos >= 0) {
  33683. if (!rewroteMarkerStartPos.has(markerStartPos)) {
  33684. s.overwrite(markerStartPos, markerStartPos + preloadMarkerWithQuote.length, 'void 0', { contentOnly: true });
  33685. }
  33686. markerStartPos = code.indexOf(preloadMarkerWithQuote, markerStartPos + preloadMarkerWithQuote.length);
  33687. }
  33688. if (s.hasChanged()) {
  33689. chunk.code = s.toString();
  33690. if (config.build.sourcemap && chunk.map) {
  33691. const nextMap = s.generateMap({
  33692. source: chunk.fileName,
  33693. hires: true
  33694. });
  33695. const map = combineSourcemaps(chunk.fileName, [nextMap, chunk.map], false);
  33696. map.toUrl = () => genSourceMapUrl(map);
  33697. chunk.map = map;
  33698. }
  33699. }
  33700. }
  33701. }
  33702. }
  33703. };
  33704. }
  33705. /**
  33706. * @param {object} exports
  33707. * @param {Set<string>} keys
  33708. */
  33709. function loop(exports, keys) {
  33710. if (typeof exports === 'string') {
  33711. return exports;
  33712. }
  33713. if (exports) {
  33714. let idx, tmp;
  33715. if (Array.isArray(exports)) {
  33716. for (idx=0; idx < exports.length; idx++) {
  33717. if (tmp = loop(exports[idx], keys)) return tmp;
  33718. }
  33719. } else {
  33720. for (idx in exports) {
  33721. if (keys.has(idx)) {
  33722. return loop(exports[idx], keys);
  33723. }
  33724. }
  33725. }
  33726. }
  33727. }
  33728. /**
  33729. * @param {string} name The package name
  33730. * @param {string} entry The target entry, eg "."
  33731. * @param {number} [condition] Unmatched condition?
  33732. */
  33733. function bail(name, entry, condition) {
  33734. throw new Error(
  33735. condition
  33736. ? `No known conditions for "${entry}" entry in "${name}" package`
  33737. : `Missing "${entry}" export in "${name}" package`
  33738. );
  33739. }
  33740. /**
  33741. * @param {string} name the package name
  33742. * @param {string} entry the target path/import
  33743. */
  33744. function toName(name, entry) {
  33745. return entry === name ? '.'
  33746. : entry[0] === '.' ? entry
  33747. : entry.replace(new RegExp('^' + name + '\/'), './');
  33748. }
  33749. /**
  33750. * @param {object} pkg package.json contents
  33751. * @param {string} [entry] entry name or import path
  33752. * @param {object} [options]
  33753. * @param {boolean} [options.browser]
  33754. * @param {boolean} [options.require]
  33755. * @param {string[]} [options.conditions]
  33756. * @param {boolean} [options.unsafe]
  33757. */
  33758. function resolve(pkg, entry='.', options={}) {
  33759. let { name, exports } = pkg;
  33760. if (exports) {
  33761. let { browser, require, unsafe, conditions=[] } = options;
  33762. let target = toName(name, entry);
  33763. if (target[0] !== '.') target = './' + target;
  33764. if (typeof exports === 'string') {
  33765. return target === '.' ? exports : bail(name, target);
  33766. }
  33767. let allows = new Set(['default', ...conditions]);
  33768. unsafe || allows.add(require ? 'require' : 'import');
  33769. unsafe || allows.add(browser ? 'browser' : 'node');
  33770. let key, tmp, isSingle=false;
  33771. for (key in exports) {
  33772. isSingle = key[0] !== '.';
  33773. break;
  33774. }
  33775. if (isSingle) {
  33776. return target === '.'
  33777. ? loop(exports, allows) || bail(name, target, 1)
  33778. : bail(name, target);
  33779. }
  33780. if (tmp = exports[target]) {
  33781. return loop(tmp, allows) || bail(name, target, 1);
  33782. }
  33783. for (key in exports) {
  33784. tmp = key[key.length - 1];
  33785. if (tmp === '/' && target.startsWith(key)) {
  33786. return (tmp = loop(exports[key], allows))
  33787. ? (tmp + target.substring(key.length))
  33788. : bail(name, target, 1);
  33789. }
  33790. if (tmp === '*' && target.startsWith(key.slice(0, -1))) {
  33791. // do not trigger if no *content* to inject
  33792. if (target.substring(key.length - 1).length > 0) {
  33793. return (tmp = loop(exports[key], allows))
  33794. ? tmp.replace('*', target.substring(key.length - 1))
  33795. : bail(name, target, 1);
  33796. }
  33797. }
  33798. }
  33799. return bail(name, target);
  33800. }
  33801. }
  33802. const externalTypes = [
  33803. 'css',
  33804. // supported pre-processor types
  33805. 'less',
  33806. 'sass',
  33807. 'scss',
  33808. 'styl',
  33809. 'stylus',
  33810. 'pcss',
  33811. 'postcss',
  33812. // known SFC types
  33813. 'vue',
  33814. 'svelte',
  33815. 'marko',
  33816. 'astro',
  33817. // JSX/TSX may be configured to be compiled differently from how esbuild
  33818. // handles it by default, so exclude them as well
  33819. 'jsx',
  33820. 'tsx',
  33821. ...KNOWN_ASSET_TYPES
  33822. ];
  33823. function esbuildDepPlugin(qualified, exportsData, config) {
  33824. // remove optimizable extensions from `externalTypes` list
  33825. const allExternalTypes = config.optimizeDeps.extensions
  33826. ? externalTypes.filter((type) => { var _a; return !((_a = config.optimizeDeps.extensions) === null || _a === void 0 ? void 0 : _a.includes('.' + type)); })
  33827. : externalTypes;
  33828. // default resolver which prefers ESM
  33829. const _resolve = config.createResolver({ asSrc: false, scan: true });
  33830. // cjs resolver that prefers Node
  33831. const _resolveRequire = config.createResolver({
  33832. asSrc: false,
  33833. isRequire: true,
  33834. scan: true
  33835. });
  33836. const resolve = (id, importer, kind, resolveDir) => {
  33837. let _importer;
  33838. // explicit resolveDir - this is passed only during yarn pnp resolve for
  33839. // entries
  33840. if (resolveDir) {
  33841. _importer = normalizePath$3(path__default.join(resolveDir, '*'));
  33842. }
  33843. else {
  33844. // map importer ids to file paths for correct resolution
  33845. _importer = importer in qualified ? qualified[importer] : importer;
  33846. }
  33847. const resolver = kind.startsWith('require') ? _resolveRequire : _resolve;
  33848. return resolver(id, _importer, undefined);
  33849. };
  33850. return {
  33851. name: 'vite:dep-pre-bundle',
  33852. setup(build) {
  33853. // externalize assets and commonly known non-js file types
  33854. build.onResolve({
  33855. filter: new RegExp(`\\.(` + allExternalTypes.join('|') + `)(\\?.*)?$`)
  33856. }, async ({ path: id, importer, kind }) => {
  33857. const resolved = await resolve(id, importer, kind);
  33858. if (resolved) {
  33859. return {
  33860. path: resolved,
  33861. external: true
  33862. };
  33863. }
  33864. });
  33865. function resolveEntry(id) {
  33866. const flatId = flattenId(id);
  33867. if (flatId in qualified) {
  33868. return {
  33869. path: flatId,
  33870. namespace: 'dep'
  33871. };
  33872. }
  33873. }
  33874. build.onResolve({ filter: /^[\w@][^:]/ }, async ({ path: id, importer, kind }) => {
  33875. var _a;
  33876. if (moduleListContains((_a = config.optimizeDeps) === null || _a === void 0 ? void 0 : _a.exclude, id)) {
  33877. return {
  33878. path: id,
  33879. external: true
  33880. };
  33881. }
  33882. // ensure esbuild uses our resolved entries
  33883. let entry;
  33884. // if this is an entry, return entry namespace resolve result
  33885. if (!importer) {
  33886. if ((entry = resolveEntry(id)))
  33887. return entry;
  33888. // check if this is aliased to an entry - also return entry namespace
  33889. const aliased = await _resolve(id, undefined, true);
  33890. if (aliased && (entry = resolveEntry(aliased))) {
  33891. return entry;
  33892. }
  33893. }
  33894. // use vite's own resolver
  33895. const resolved = await resolve(id, importer, kind);
  33896. if (resolved) {
  33897. if (resolved.startsWith(browserExternalId)) {
  33898. return {
  33899. path: id,
  33900. namespace: 'browser-external'
  33901. };
  33902. }
  33903. if (isExternalUrl(resolved)) {
  33904. return {
  33905. path: resolved,
  33906. external: true
  33907. };
  33908. }
  33909. return {
  33910. path: path__default.resolve(resolved)
  33911. };
  33912. }
  33913. });
  33914. // For entry files, we'll read it ourselves and construct a proxy module
  33915. // to retain the entry's raw id instead of file path so that esbuild
  33916. // outputs desired output file structure.
  33917. // It is necessary to do the re-exporting to separate the virtual proxy
  33918. // module from the actual module since the actual module may get
  33919. // referenced via relative imports - if we don't separate the proxy and
  33920. // the actual module, esbuild will create duplicated copies of the same
  33921. // module!
  33922. const root = path__default.resolve(config.root);
  33923. build.onLoad({ filter: /.*/, namespace: 'dep' }, ({ path: id }) => {
  33924. const entryFile = qualified[id];
  33925. let relativePath = normalizePath$3(path__default.relative(root, entryFile));
  33926. if (!relativePath.startsWith('./') &&
  33927. !relativePath.startsWith('../') &&
  33928. relativePath !== '.') {
  33929. relativePath = `./${relativePath}`;
  33930. }
  33931. let contents = '';
  33932. const data = exportsData[id];
  33933. const [imports, exports] = data;
  33934. if (!imports.length && !exports.length) {
  33935. // cjs
  33936. contents += `export default require("${relativePath}");`;
  33937. }
  33938. else {
  33939. if (exports.includes('default')) {
  33940. contents += `import d from "${relativePath}";export default d;`;
  33941. }
  33942. if (data.hasReExports ||
  33943. exports.length > 1 ||
  33944. exports[0] !== 'default') {
  33945. contents += `\nexport * from "${relativePath}"`;
  33946. }
  33947. }
  33948. return {
  33949. loader: 'js',
  33950. contents,
  33951. resolveDir: root
  33952. };
  33953. });
  33954. build.onLoad({ filter: /.*/, namespace: 'browser-external' }, ({ path: id }) => {
  33955. return {
  33956. contents: `export default new Proxy({}, {
  33957. get() {
  33958. throw new Error('Module "${id}" has been externalized for ` +
  33959. `browser compatibility and cannot be accessed in client code.')
  33960. }
  33961. })`
  33962. };
  33963. });
  33964. // yarn 2 pnp compat
  33965. if (isRunningWithYarnPnp) {
  33966. build.onResolve({ filter: /.*/ }, async ({ path, importer, kind, resolveDir }) => ({
  33967. // pass along resolveDir for entries
  33968. path: await resolve(path, importer, kind, resolveDir)
  33969. }));
  33970. build.onLoad({ filter: /.*/ }, async (args) => ({
  33971. contents: await require('fs').promises.readFile(args.path),
  33972. loader: 'default'
  33973. }));
  33974. }
  33975. }
  33976. };
  33977. }
  33978. var ansiRegex$1 = ({onlyFirst = false} = {}) => {
  33979. const pattern = [
  33980. '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)',
  33981. '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))'
  33982. ].join('|');
  33983. return new RegExp(pattern, onlyFirst ? undefined : 'g');
  33984. };
  33985. const ansiRegex = ansiRegex$1;
  33986. var stripAnsi = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string;
  33987. function prepareError(err) {
  33988. // only copy the information we need and avoid serializing unnecessary
  33989. // properties, since some errors may attach full objects (e.g. PostCSS)
  33990. return {
  33991. message: stripAnsi(err.message),
  33992. stack: stripAnsi(cleanStack(err.stack || '')),
  33993. id: err.id,
  33994. frame: stripAnsi(err.frame || ''),
  33995. plugin: err.plugin,
  33996. pluginCode: err.pluginCode,
  33997. loc: err.loc
  33998. };
  33999. }
  34000. function buildErrorMessage(err, args = [], includeStack = true) {
  34001. if (err.plugin)
  34002. args.push(` Plugin: ${colors$1.magenta(err.plugin)}`);
  34003. if (err.id)
  34004. args.push(` File: ${colors$1.cyan(err.id)}`);
  34005. if (err.frame)
  34006. args.push(colors$1.yellow(pad(err.frame)));
  34007. if (includeStack && err.stack)
  34008. args.push(pad(cleanStack(err.stack)));
  34009. return args.join('\n');
  34010. }
  34011. function cleanStack(stack) {
  34012. return stack
  34013. .split(/\n/g)
  34014. .filter((l) => /^\s*at/.test(l))
  34015. .join('\n');
  34016. }
  34017. function logError(server, err) {
  34018. const msg = buildErrorMessage(err, [
  34019. colors$1.red(`Internal server error: ${err.message}`)
  34020. ]);
  34021. server.config.logger.error(msg, {
  34022. clear: true,
  34023. timestamp: true,
  34024. error: err
  34025. });
  34026. server.ws.send({
  34027. type: 'error',
  34028. err: prepareError(err)
  34029. });
  34030. }
  34031. function errorMiddleware(server, allowNext = false) {
  34032. // note the 4 args must be kept for connect to treat this as error middleware
  34033. // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
  34034. return function viteErrorMiddleware(err, _req, res, next) {
  34035. logError(server, err);
  34036. if (allowNext) {
  34037. next();
  34038. }
  34039. else {
  34040. res.statusCode = 500;
  34041. res.end(`
  34042. <!DOCTYPE html>
  34043. <html lang="en">
  34044. <head>
  34045. <meta charset="UTF-8" />
  34046. <title>Error</title>
  34047. <script type="module">
  34048. import { ErrorOverlay } from '/@vite/client'
  34049. document.body.appendChild(new ErrorOverlay(${JSON.stringify(prepareError(err)).replace(/</g, '\\u003c')}))
  34050. </script>
  34051. </head>
  34052. <body>
  34053. </body>
  34054. </html>
  34055. `);
  34056. }
  34057. };
  34058. }
  34059. /**
  34060. * This file is refactored into TypeScript based on
  34061. * https://github.com/preactjs/wmr/blob/main/packages/wmr/src/lib/rollup-plugin-container.js
  34062. */
  34063. let parser = Parser;
  34064. async function createPluginContainer({ plugins, logger, root, build: { rollupOptions } }, moduleGraph, watcher) {
  34065. const isDebug = process.env.DEBUG;
  34066. const seenResolves = {};
  34067. const debugResolve = createDebugger('vite:resolve');
  34068. const debugPluginResolve = createDebugger('vite:plugin-resolve', {
  34069. onlyWhenFocused: 'vite:plugin'
  34070. });
  34071. const debugPluginTransform = createDebugger('vite:plugin-transform', {
  34072. onlyWhenFocused: 'vite:plugin'
  34073. });
  34074. // ---------------------------------------------------------------------------
  34075. const watchFiles = new Set();
  34076. // get rollup version
  34077. const rollupPkgPath = path$r.resolve(require.resolve('rollup'), '../../package.json');
  34078. const minimalContext = {
  34079. meta: {
  34080. rollupVersion: JSON.parse(fs__default.readFileSync(rollupPkgPath, 'utf-8'))
  34081. .version,
  34082. watchMode: true
  34083. }
  34084. };
  34085. function warnIncompatibleMethod(method, plugin) {
  34086. logger.warn(colors$1.cyan(`[plugin:${plugin}] `) +
  34087. colors$1.yellow(`context method ${colors$1.bold(`${method}()`)} is not supported in serve mode. This plugin is likely not vite-compatible.`));
  34088. }
  34089. // throw when an unsupported ModuleInfo property is accessed,
  34090. // so that incompatible plugins fail in a non-cryptic way.
  34091. const ModuleInfoProxy = {
  34092. get(info, key) {
  34093. if (key in info) {
  34094. return info[key];
  34095. }
  34096. throw Error(`[vite] The "${key}" property of ModuleInfo is not supported.`);
  34097. }
  34098. };
  34099. // same default value of "moduleInfo.meta" as in Rollup
  34100. const EMPTY_OBJECT = Object.freeze({});
  34101. function getModuleInfo(id) {
  34102. const module = moduleGraph === null || moduleGraph === void 0 ? void 0 : moduleGraph.getModuleById(id);
  34103. if (!module) {
  34104. return null;
  34105. }
  34106. if (!module.info) {
  34107. module.info = new Proxy({ id, meta: module.meta || EMPTY_OBJECT }, ModuleInfoProxy);
  34108. }
  34109. return module.info;
  34110. }
  34111. function updateModuleInfo(id, { meta }) {
  34112. if (meta) {
  34113. const moduleInfo = getModuleInfo(id);
  34114. if (moduleInfo) {
  34115. moduleInfo.meta = { ...moduleInfo.meta, ...meta };
  34116. }
  34117. }
  34118. }
  34119. // we should create a new context for each async hook pipeline so that the
  34120. // active plugin in that pipeline can be tracked in a concurrency-safe manner.
  34121. // using a class to make creating new contexts more efficient
  34122. class Context {
  34123. constructor(initialPlugin) {
  34124. this.meta = minimalContext.meta;
  34125. this.ssr = false;
  34126. this._scan = false;
  34127. this._activeId = null;
  34128. this._activeCode = null;
  34129. this._addedImports = null;
  34130. this._activePlugin = initialPlugin || null;
  34131. }
  34132. parse(code, opts = {}) {
  34133. return parser.parse(code, {
  34134. sourceType: 'module',
  34135. ecmaVersion: 'latest',
  34136. locations: true,
  34137. ...opts
  34138. });
  34139. }
  34140. async resolve(id, importer, options) {
  34141. let skip;
  34142. if ((options === null || options === void 0 ? void 0 : options.skipSelf) && this._activePlugin) {
  34143. skip = new Set(this._resolveSkips);
  34144. skip.add(this._activePlugin);
  34145. }
  34146. let out = await container.resolveId(id, importer, {
  34147. skip,
  34148. ssr: this.ssr,
  34149. scan: this._scan
  34150. });
  34151. if (typeof out === 'string')
  34152. out = { id: out };
  34153. return out;
  34154. }
  34155. getModuleInfo(id) {
  34156. return getModuleInfo(id);
  34157. }
  34158. getModuleIds() {
  34159. return moduleGraph
  34160. ? moduleGraph.idToModuleMap.keys()
  34161. : Array.prototype[Symbol.iterator]();
  34162. }
  34163. addWatchFile(id) {
  34164. watchFiles.add(id);
  34165. (this._addedImports || (this._addedImports = new Set())).add(id);
  34166. if (watcher)
  34167. ensureWatchedFile(watcher, id, root);
  34168. }
  34169. getWatchFiles() {
  34170. return [...watchFiles];
  34171. }
  34172. emitFile(assetOrFile) {
  34173. warnIncompatibleMethod(`emitFile`, this._activePlugin.name);
  34174. return '';
  34175. }
  34176. setAssetSource() {
  34177. warnIncompatibleMethod(`setAssetSource`, this._activePlugin.name);
  34178. }
  34179. getFileName() {
  34180. warnIncompatibleMethod(`getFileName`, this._activePlugin.name);
  34181. return '';
  34182. }
  34183. warn(e, position) {
  34184. const err = formatError(e, position, this);
  34185. const msg = buildErrorMessage(err, [colors$1.yellow(`warning: ${err.message}`)], false);
  34186. logger.warn(msg, {
  34187. clear: true,
  34188. timestamp: true
  34189. });
  34190. }
  34191. error(e, position) {
  34192. // error thrown here is caught by the transform middleware and passed on
  34193. // the the error middleware.
  34194. throw formatError(e, position, this);
  34195. }
  34196. }
  34197. function formatError(e, position, ctx) {
  34198. const err = (typeof e === 'string' ? new Error(e) : e);
  34199. if (err.pluginCode) {
  34200. return err; // The plugin likely called `this.error`
  34201. }
  34202. if (err.file && err.name === 'CssSyntaxError') {
  34203. err.id = normalizePath$3(err.file);
  34204. }
  34205. if (ctx._activePlugin)
  34206. err.plugin = ctx._activePlugin.name;
  34207. if (ctx._activeId && !err.id)
  34208. err.id = ctx._activeId;
  34209. if (ctx._activeCode) {
  34210. err.pluginCode = ctx._activeCode;
  34211. const pos = position != null
  34212. ? position
  34213. : err.pos != null
  34214. ? err.pos
  34215. : // some rollup plugins, e.g. json, sets position instead of pos
  34216. err.position;
  34217. if (pos != null) {
  34218. let errLocation;
  34219. try {
  34220. errLocation = numberToPos(ctx._activeCode, pos);
  34221. }
  34222. catch (err2) {
  34223. logger.error(colors$1.red(`Error in error handler:\n${err2.stack || err2.message}\n`),
  34224. // print extra newline to separate the two errors
  34225. { error: err2 });
  34226. throw err;
  34227. }
  34228. err.loc = err.loc || {
  34229. file: err.id,
  34230. ...errLocation
  34231. };
  34232. err.frame = err.frame || generateCodeFrame(ctx._activeCode, pos);
  34233. }
  34234. else if (err.loc) {
  34235. // css preprocessors may report errors in an included file
  34236. if (!err.frame) {
  34237. let code = ctx._activeCode;
  34238. if (err.loc.file) {
  34239. err.id = normalizePath$3(err.loc.file);
  34240. try {
  34241. code = fs__default.readFileSync(err.loc.file, 'utf-8');
  34242. }
  34243. catch { }
  34244. }
  34245. err.frame = generateCodeFrame(code, err.loc);
  34246. }
  34247. }
  34248. else if (err.line && err.column) {
  34249. err.loc = {
  34250. file: err.id,
  34251. line: err.line,
  34252. column: err.column
  34253. };
  34254. err.frame = err.frame || generateCodeFrame(err.id, err.loc);
  34255. }
  34256. if (err.loc && ctx instanceof TransformContext) {
  34257. const rawSourceMap = ctx._getCombinedSourcemap();
  34258. if (rawSourceMap) {
  34259. const traced = new TraceMap(rawSourceMap);
  34260. const { source, line, column } = originalPositionFor$1(traced, {
  34261. line: Number(err.loc.line),
  34262. column: Number(err.loc.column)
  34263. });
  34264. if (source && line != null && column != null) {
  34265. err.loc = { file: source, line, column };
  34266. }
  34267. }
  34268. }
  34269. }
  34270. return err;
  34271. }
  34272. class TransformContext extends Context {
  34273. constructor(filename, code, inMap) {
  34274. super();
  34275. this.originalSourcemap = null;
  34276. this.sourcemapChain = [];
  34277. this.combinedMap = null;
  34278. this.filename = filename;
  34279. this.originalCode = code;
  34280. if (inMap) {
  34281. this.sourcemapChain.push(inMap);
  34282. }
  34283. }
  34284. _getCombinedSourcemap(createIfNull = false) {
  34285. let combinedMap = this.combinedMap;
  34286. for (let m of this.sourcemapChain) {
  34287. if (typeof m === 'string')
  34288. m = JSON.parse(m);
  34289. if (!('version' in m)) {
  34290. // empty, nullified source map
  34291. combinedMap = this.combinedMap = null;
  34292. this.sourcemapChain.length = 0;
  34293. break;
  34294. }
  34295. if (!combinedMap) {
  34296. combinedMap = m;
  34297. }
  34298. else {
  34299. combinedMap = combineSourcemaps(cleanUrl(this.filename), [
  34300. {
  34301. ...m,
  34302. sourcesContent: combinedMap.sourcesContent
  34303. },
  34304. combinedMap
  34305. ]);
  34306. }
  34307. }
  34308. if (!combinedMap) {
  34309. return createIfNull
  34310. ? new MagicString(this.originalCode).generateMap({
  34311. includeContent: true,
  34312. hires: true,
  34313. source: cleanUrl(this.filename)
  34314. })
  34315. : null;
  34316. }
  34317. if (combinedMap !== this.combinedMap) {
  34318. this.combinedMap = combinedMap;
  34319. this.sourcemapChain.length = 0;
  34320. }
  34321. return this.combinedMap;
  34322. }
  34323. getCombinedSourcemap() {
  34324. return this._getCombinedSourcemap(true);
  34325. }
  34326. }
  34327. let closed = false;
  34328. const container = {
  34329. options: await (async () => {
  34330. let options = rollupOptions;
  34331. for (const plugin of plugins) {
  34332. if (!plugin.options)
  34333. continue;
  34334. options =
  34335. (await plugin.options.call(minimalContext, options)) || options;
  34336. }
  34337. if (options.acornInjectPlugins) {
  34338. parser = Parser.extend(options.acornInjectPlugins);
  34339. }
  34340. return {
  34341. acorn,
  34342. acornInjectPlugins: [],
  34343. ...options
  34344. };
  34345. })(),
  34346. getModuleInfo,
  34347. async buildStart() {
  34348. await Promise.all(plugins.map((plugin) => {
  34349. if (plugin.buildStart) {
  34350. return plugin.buildStart.call(new Context(plugin), container.options);
  34351. }
  34352. }));
  34353. },
  34354. async resolveId(rawId, importer = path$r.join(root, 'index.html'), options) {
  34355. const skip = options === null || options === void 0 ? void 0 : options.skip;
  34356. const ssr = options === null || options === void 0 ? void 0 : options.ssr;
  34357. const scan = !!(options === null || options === void 0 ? void 0 : options.scan);
  34358. const ctx = new Context();
  34359. ctx.ssr = !!ssr;
  34360. ctx._scan = scan;
  34361. ctx._resolveSkips = skip;
  34362. const resolveStart = isDebug ? perf_hooks.performance.now() : 0;
  34363. let id = null;
  34364. const partial = {};
  34365. for (const plugin of plugins) {
  34366. if (!plugin.resolveId)
  34367. continue;
  34368. if (skip === null || skip === void 0 ? void 0 : skip.has(plugin))
  34369. continue;
  34370. ctx._activePlugin = plugin;
  34371. const pluginResolveStart = isDebug ? perf_hooks.performance.now() : 0;
  34372. const result = await plugin.resolveId.call(ctx, rawId, importer, { ssr, scan });
  34373. if (!result)
  34374. continue;
  34375. if (typeof result === 'string') {
  34376. id = result;
  34377. }
  34378. else {
  34379. id = result.id;
  34380. Object.assign(partial, result);
  34381. }
  34382. isDebug &&
  34383. debugPluginResolve(timeFrom(pluginResolveStart), plugin.name, prettifyUrl(id, root));
  34384. // resolveId() is hookFirst - first non-null result is returned.
  34385. break;
  34386. }
  34387. if (isDebug && rawId !== id && !rawId.startsWith(FS_PREFIX)) {
  34388. const key = rawId + id;
  34389. // avoid spamming
  34390. if (!seenResolves[key]) {
  34391. seenResolves[key] = true;
  34392. debugResolve(`${timeFrom(resolveStart)} ${colors$1.cyan(rawId)} -> ${colors$1.dim(id)}`);
  34393. }
  34394. }
  34395. if (id) {
  34396. partial.id = isExternalUrl(id) ? id : normalizePath$3(id);
  34397. return partial;
  34398. }
  34399. else {
  34400. return null;
  34401. }
  34402. },
  34403. async load(id, options) {
  34404. const ssr = options === null || options === void 0 ? void 0 : options.ssr;
  34405. const ctx = new Context();
  34406. ctx.ssr = !!ssr;
  34407. for (const plugin of plugins) {
  34408. if (!plugin.load)
  34409. continue;
  34410. ctx._activePlugin = plugin;
  34411. const result = await plugin.load.call(ctx, id, { ssr });
  34412. if (result != null) {
  34413. if (isObject$1(result)) {
  34414. updateModuleInfo(id, result);
  34415. }
  34416. return result;
  34417. }
  34418. }
  34419. return null;
  34420. },
  34421. async transform(code, id, options) {
  34422. const inMap = options === null || options === void 0 ? void 0 : options.inMap;
  34423. const ssr = options === null || options === void 0 ? void 0 : options.ssr;
  34424. const ctx = new TransformContext(id, code, inMap);
  34425. ctx.ssr = !!ssr;
  34426. for (const plugin of plugins) {
  34427. if (!plugin.transform)
  34428. continue;
  34429. ctx._activePlugin = plugin;
  34430. ctx._activeId = id;
  34431. ctx._activeCode = code;
  34432. const start = isDebug ? perf_hooks.performance.now() : 0;
  34433. let result;
  34434. try {
  34435. result = await plugin.transform.call(ctx, code, id, { ssr });
  34436. }
  34437. catch (e) {
  34438. ctx.error(e);
  34439. }
  34440. if (!result)
  34441. continue;
  34442. isDebug &&
  34443. debugPluginTransform(timeFrom(start), plugin.name, prettifyUrl(id, root));
  34444. if (isObject$1(result)) {
  34445. if (result.code !== undefined) {
  34446. code = result.code;
  34447. if (result.map) {
  34448. ctx.sourcemapChain.push(result.map);
  34449. }
  34450. }
  34451. updateModuleInfo(id, result);
  34452. }
  34453. else {
  34454. code = result;
  34455. }
  34456. }
  34457. return {
  34458. code,
  34459. map: ctx._getCombinedSourcemap()
  34460. };
  34461. },
  34462. async close() {
  34463. if (closed)
  34464. return;
  34465. const ctx = new Context();
  34466. await Promise.all(plugins.map((p) => p.buildEnd && p.buildEnd.call(ctx)));
  34467. await Promise.all(plugins.map((p) => p.closeBundle && p.closeBundle.call(ctx)));
  34468. closed = true;
  34469. }
  34470. };
  34471. return container;
  34472. }
  34473. const debug$d = createDebugger('vite:deps');
  34474. const htmlTypesRE = /\.(html|vue|svelte|astro)$/;
  34475. // A simple regex to detect import sources. This is only used on
  34476. // <script lang="ts"> blocks in vue (setup only) or svelte files, since
  34477. // seemingly unused imports are dropped by esbuild when transpiling TS which
  34478. // prevents it from crawling further.
  34479. // We can't use es-module-lexer because it can't handle TS, and don't want to
  34480. // use Acorn because it's slow. Luckily this doesn't have to be bullet proof
  34481. // since even missed imports can be caught at runtime, and false positives will
  34482. // simply be ignored.
  34483. const importsRE = /(?<!\/\/.*)(?<=^|;|\*\/)\s*import(?!\s+type)(?:[\w*{}\n\r\t, ]+from\s*)?\s*("[^"]+"|'[^']+')\s*(?=$|;|\/\/|\/\*)/gm;
  34484. async function scanImports(config) {
  34485. var _a, _b, _c;
  34486. const start = perf_hooks.performance.now();
  34487. let entries = [];
  34488. const explicitEntryPatterns = config.optimizeDeps.entries;
  34489. const buildInput = (_a = config.build.rollupOptions) === null || _a === void 0 ? void 0 : _a.input;
  34490. if (explicitEntryPatterns) {
  34491. entries = await globEntries(explicitEntryPatterns, config);
  34492. }
  34493. else if (buildInput) {
  34494. const resolvePath = (p) => path__default.resolve(config.root, p);
  34495. if (typeof buildInput === 'string') {
  34496. entries = [resolvePath(buildInput)];
  34497. }
  34498. else if (Array.isArray(buildInput)) {
  34499. entries = buildInput.map(resolvePath);
  34500. }
  34501. else if (isObject$1(buildInput)) {
  34502. entries = Object.values(buildInput).map(resolvePath);
  34503. }
  34504. else {
  34505. throw new Error('invalid rollupOptions.input value.');
  34506. }
  34507. }
  34508. else {
  34509. entries = await globEntries('**/*.html', config);
  34510. }
  34511. // Non-supported entry file types and virtual files should not be scanned for
  34512. // dependencies.
  34513. entries = entries.filter((entry) => (JS_TYPES_RE.test(entry) || htmlTypesRE.test(entry)) &&
  34514. fs__default.existsSync(entry));
  34515. if (!entries.length) {
  34516. if (!explicitEntryPatterns && !config.optimizeDeps.include) {
  34517. config.logger.warn(colors$1.yellow('(!) Could not auto-determine entry point from rollupOptions or html files ' +
  34518. 'and there are no explicit optimizeDeps.include patterns. ' +
  34519. 'Skipping dependency pre-bundling.'));
  34520. }
  34521. return { deps: {}, missing: {} };
  34522. }
  34523. else {
  34524. debug$d(`Crawling dependencies using entries:\n ${entries.join('\n ')}`);
  34525. }
  34526. const deps = {};
  34527. const missing = {};
  34528. const container = await createPluginContainer(config);
  34529. const plugin = esbuildScanPlugin(config, container, deps, missing, entries);
  34530. const { plugins = [], ...esbuildOptions } = (_c = (_b = config.optimizeDeps) === null || _b === void 0 ? void 0 : _b.esbuildOptions) !== null && _c !== void 0 ? _c : {};
  34531. await Promise.all(entries.map((entry) => esbuild.build({
  34532. absWorkingDir: process.cwd(),
  34533. write: false,
  34534. entryPoints: [entry],
  34535. bundle: true,
  34536. format: 'esm',
  34537. logLevel: 'error',
  34538. plugins: [...plugins, plugin],
  34539. ...esbuildOptions
  34540. })));
  34541. debug$d(`Scan completed in ${(perf_hooks.performance.now() - start).toFixed(2)}ms:`, deps);
  34542. return {
  34543. // Ensure a fixed order so hashes are stable and improve logs
  34544. deps: orderedDependencies(deps),
  34545. missing
  34546. };
  34547. }
  34548. function orderedDependencies(deps) {
  34549. const depsList = Object.entries(deps);
  34550. // Ensure the same browserHash for the same set of dependencies
  34551. depsList.sort((a, b) => a[0].localeCompare(b[0]));
  34552. return Object.fromEntries(depsList);
  34553. }
  34554. function globEntries(pattern, config) {
  34555. return out(pattern, {
  34556. cwd: config.root,
  34557. ignore: [
  34558. '**/node_modules/**',
  34559. `**/${config.build.outDir}/**`,
  34560. // if there aren't explicit entries, also ignore other common folders
  34561. ...(config.optimizeDeps.entries
  34562. ? []
  34563. : [`**/__tests__/**`, `**/coverage/**`])
  34564. ],
  34565. absolute: true
  34566. });
  34567. }
  34568. const scriptModuleRE = /(<script\b[^>]*type\s*=\s*(?:"module"|'module')[^>]*>)(.*?)<\/script>/gims;
  34569. const scriptRE = /(<script\b(?:\s[^>]*>|>))(.*?)<\/script>/gims;
  34570. const commentRE = /<!--.*?-->/gs;
  34571. const srcRE = /\bsrc\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/im;
  34572. const typeRE = /\btype\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/im;
  34573. const langRE = /\blang\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/im;
  34574. const contextRE = /\bcontext\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/im;
  34575. function esbuildScanPlugin(config, container, depImports, missing, entries) {
  34576. var _a, _b;
  34577. const seen = new Map();
  34578. const resolve = async (id, importer) => {
  34579. const key = id + (importer && path__default.dirname(importer));
  34580. if (seen.has(key)) {
  34581. return seen.get(key);
  34582. }
  34583. const resolved = await container.resolveId(id, importer && normalizePath$3(importer), {
  34584. scan: true
  34585. });
  34586. const res = resolved === null || resolved === void 0 ? void 0 : resolved.id;
  34587. seen.set(key, res);
  34588. return res;
  34589. };
  34590. const include = (_a = config.optimizeDeps) === null || _a === void 0 ? void 0 : _a.include;
  34591. const exclude = [
  34592. ...(((_b = config.optimizeDeps) === null || _b === void 0 ? void 0 : _b.exclude) || []),
  34593. '@vite/client',
  34594. '@vite/env'
  34595. ];
  34596. const isOptimizable = (id) => {
  34597. var _a;
  34598. return OPTIMIZABLE_ENTRY_RE.test(id) ||
  34599. !!((_a = config.optimizeDeps.extensions) === null || _a === void 0 ? void 0 : _a.some((ext) => id.endsWith(ext)));
  34600. };
  34601. const externalUnlessEntry = ({ path }) => ({
  34602. path,
  34603. external: !entries.includes(path)
  34604. });
  34605. return {
  34606. name: 'vite:dep-scan',
  34607. setup(build) {
  34608. const scripts = {};
  34609. // external urls
  34610. build.onResolve({ filter: externalRE }, ({ path }) => ({
  34611. path,
  34612. external: true
  34613. }));
  34614. // data urls
  34615. build.onResolve({ filter: dataUrlRE }, ({ path }) => ({
  34616. path,
  34617. external: true
  34618. }));
  34619. // local scripts (`<script>` in Svelte and `<script setup>` in Vue)
  34620. build.onResolve({ filter: virtualModuleRE }, ({ path }) => {
  34621. return {
  34622. // strip prefix to get valid filesystem path so esbuild can resolve imports in the file
  34623. path: path.replace(virtualModulePrefix, ''),
  34624. namespace: 'script'
  34625. };
  34626. });
  34627. build.onLoad({ filter: /.*/, namespace: 'script' }, ({ path }) => {
  34628. return scripts[path];
  34629. });
  34630. // html types: extract script contents -----------------------------------
  34631. build.onResolve({ filter: htmlTypesRE }, async ({ path, importer }) => {
  34632. const resolved = await resolve(path, importer);
  34633. if (!resolved)
  34634. return;
  34635. // It is possible for the scanner to scan html types in node_modules.
  34636. // If we can optimize this html type, skip it so it's handled by the
  34637. // bare import resolve, and recorded as optimization dep.
  34638. if (resolved.includes('node_modules') && isOptimizable(resolved))
  34639. return;
  34640. return {
  34641. path: resolved,
  34642. namespace: 'html'
  34643. };
  34644. });
  34645. // extract scripts inside HTML-like files and treat it as a js module
  34646. build.onLoad({ filter: htmlTypesRE, namespace: 'html' }, async ({ path }) => {
  34647. let raw = fs__default.readFileSync(path, 'utf-8');
  34648. // Avoid matching the content of the comment
  34649. raw = raw.replace(commentRE, '<!---->');
  34650. const isHtml = path.endsWith('.html');
  34651. const regex = isHtml ? scriptModuleRE : scriptRE;
  34652. regex.lastIndex = 0;
  34653. let js = '';
  34654. let scriptId = 0;
  34655. let match;
  34656. while ((match = regex.exec(raw))) {
  34657. const [, openTag, content] = match;
  34658. const typeMatch = openTag.match(typeRE);
  34659. const type = typeMatch && (typeMatch[1] || typeMatch[2] || typeMatch[3]);
  34660. const langMatch = openTag.match(langRE);
  34661. const lang = langMatch && (langMatch[1] || langMatch[2] || langMatch[3]);
  34662. // skip type="application/ld+json" and other non-JS types
  34663. if (type &&
  34664. !(type.includes('javascript') ||
  34665. type.includes('ecmascript') ||
  34666. type === 'module')) {
  34667. continue;
  34668. }
  34669. let loader = 'js';
  34670. if (lang === 'ts' || lang === 'tsx' || lang === 'jsx') {
  34671. loader = lang;
  34672. }
  34673. else if (path.endsWith('.astro')) {
  34674. loader = 'ts';
  34675. }
  34676. const srcMatch = openTag.match(srcRE);
  34677. if (srcMatch) {
  34678. const src = srcMatch[1] || srcMatch[2] || srcMatch[3];
  34679. js += `import ${JSON.stringify(src)}\n`;
  34680. }
  34681. else if (content.trim()) {
  34682. // The reason why virtual modules are needed:
  34683. // 1. There can be module scripts (`<script context="module">` in Svelte and `<script>` in Vue)
  34684. // or local scripts (`<script>` in Svelte and `<script setup>` in Vue)
  34685. // 2. There can be multiple module scripts in html
  34686. // We need to handle these separately in case variable names are reused between them
  34687. // append imports in TS to prevent esbuild from removing them
  34688. // since they may be used in the template
  34689. const contents = content +
  34690. (loader.startsWith('ts') ? extractImportPaths(content) : '');
  34691. const key = `${path}?id=${scriptId++}`;
  34692. if (contents.includes('import.meta.glob')) {
  34693. scripts[key] = {
  34694. // transformGlob already transforms to js
  34695. loader: 'js',
  34696. contents: await transformGlob(contents, path, config.root, loader, resolve, config.logger)
  34697. };
  34698. }
  34699. else {
  34700. scripts[key] = {
  34701. loader,
  34702. contents
  34703. };
  34704. }
  34705. const virtualModulePath = JSON.stringify(virtualModulePrefix + key);
  34706. const contextMatch = openTag.match(contextRE);
  34707. const context = contextMatch &&
  34708. (contextMatch[1] || contextMatch[2] || contextMatch[3]);
  34709. // Especially for Svelte files, exports in <script context="module"> means module exports,
  34710. // exports in <script> means component props. To avoid having two same export name from the
  34711. // star exports, we need to ignore exports in <script>
  34712. if (path.endsWith('.svelte') && context !== 'module') {
  34713. js += `import ${virtualModulePath}\n`;
  34714. }
  34715. else {
  34716. js += `export * from ${virtualModulePath}\n`;
  34717. }
  34718. }
  34719. }
  34720. // This will trigger incorrectly if `export default` is contained
  34721. // anywhere in a string. Svelte and Astro files can't have
  34722. // `export default` as code so we know if it's encountered it's a
  34723. // false positive (e.g. contained in a string)
  34724. if (!path.endsWith('.vue') || !js.includes('export default')) {
  34725. js += '\nexport default {}';
  34726. }
  34727. return {
  34728. loader: 'js',
  34729. contents: js
  34730. };
  34731. });
  34732. // bare imports: record and externalize ----------------------------------
  34733. build.onResolve({
  34734. // avoid matching windows volume
  34735. filter: /^[\w@][^:]/
  34736. }, async ({ path: id, importer }) => {
  34737. if (moduleListContains(exclude, id)) {
  34738. return externalUnlessEntry({ path: id });
  34739. }
  34740. if (depImports[id]) {
  34741. return externalUnlessEntry({ path: id });
  34742. }
  34743. const resolved = await resolve(id, importer);
  34744. if (resolved) {
  34745. if (shouldExternalizeDep(resolved, id)) {
  34746. return externalUnlessEntry({ path: id });
  34747. }
  34748. if (resolved.includes('node_modules') || (include === null || include === void 0 ? void 0 : include.includes(id))) {
  34749. // dependency or forced included, externalize and stop crawling
  34750. if (isOptimizable(resolved)) {
  34751. depImports[id] = resolved;
  34752. }
  34753. return externalUnlessEntry({ path: id });
  34754. }
  34755. else if (isScannable(resolved)) {
  34756. const namespace = htmlTypesRE.test(resolved) ? 'html' : undefined;
  34757. // linked package, keep crawling
  34758. return {
  34759. path: path__default.resolve(resolved),
  34760. namespace
  34761. };
  34762. }
  34763. else {
  34764. return externalUnlessEntry({ path: id });
  34765. }
  34766. }
  34767. else {
  34768. missing[id] = normalizePath$3(importer);
  34769. }
  34770. });
  34771. // Externalized file types -----------------------------------------------
  34772. // these are done on raw ids using esbuild's native regex filter so it
  34773. // should be faster than doing it in the catch-all via js
  34774. // they are done after the bare import resolve because a package name
  34775. // may end with these extensions
  34776. // css & json
  34777. build.onResolve({
  34778. filter: /\.(css|less|sass|scss|styl|stylus|pcss|postcss|json)$/
  34779. }, externalUnlessEntry);
  34780. // known asset types
  34781. build.onResolve({
  34782. filter: new RegExp(`\\.(${KNOWN_ASSET_TYPES.join('|')})$`)
  34783. }, externalUnlessEntry);
  34784. // known vite query types: ?worker, ?raw
  34785. build.onResolve({ filter: SPECIAL_QUERY_RE }, ({ path }) => ({
  34786. path,
  34787. external: true
  34788. }));
  34789. // catch all -------------------------------------------------------------
  34790. build.onResolve({
  34791. filter: /.*/
  34792. }, async ({ path: id, importer }) => {
  34793. // use vite resolver to support urls and omitted extensions
  34794. const resolved = await resolve(id, importer);
  34795. if (resolved) {
  34796. if (shouldExternalizeDep(resolved, id) || !isScannable(resolved)) {
  34797. return externalUnlessEntry({ path: id });
  34798. }
  34799. const namespace = htmlTypesRE.test(resolved) ? 'html' : undefined;
  34800. return {
  34801. path: path__default.resolve(cleanUrl(resolved)),
  34802. namespace
  34803. };
  34804. }
  34805. else {
  34806. // resolve failed... probably unsupported type
  34807. return externalUnlessEntry({ path: id });
  34808. }
  34809. });
  34810. // for jsx/tsx, we need to access the content and check for
  34811. // presence of import.meta.glob, since it results in import relationships
  34812. // but isn't crawled by esbuild.
  34813. build.onLoad({ filter: JS_TYPES_RE }, ({ path: id }) => {
  34814. var _a, _b, _c;
  34815. let ext = path__default.extname(id).slice(1);
  34816. if (ext === 'mjs')
  34817. ext = 'js';
  34818. let contents = fs__default.readFileSync(id, 'utf-8');
  34819. if (ext.endsWith('x') && config.esbuild && config.esbuild.jsxInject) {
  34820. contents = config.esbuild.jsxInject + `\n` + contents;
  34821. }
  34822. const loader = ((_c = (_b = (_a = config.optimizeDeps) === null || _a === void 0 ? void 0 : _a.esbuildOptions) === null || _b === void 0 ? void 0 : _b.loader) === null || _c === void 0 ? void 0 : _c[`.${ext}`]) ||
  34823. ext;
  34824. if (contents.includes('import.meta.glob')) {
  34825. return transformGlob(contents, id, config.root, loader, resolve, config.logger).then((contents) => ({
  34826. loader,
  34827. contents
  34828. }));
  34829. }
  34830. return {
  34831. loader,
  34832. contents
  34833. };
  34834. });
  34835. }
  34836. };
  34837. }
  34838. async function transformGlob(source, importer, root, loader, resolve, logger) {
  34839. // transform the content first since es-module-lexer can't handle non-js
  34840. if (loader !== 'js') {
  34841. source = (await esbuild.transform(source, { loader })).code;
  34842. }
  34843. await init;
  34844. const imports = parse$e(source)[0];
  34845. const s = new MagicString(source);
  34846. for (let index = 0; index < imports.length; index++) {
  34847. const { s: start, e: end, ss: expStart } = imports[index];
  34848. const url = source.slice(start, end);
  34849. if (url !== 'import.meta')
  34850. continue;
  34851. if (source.slice(end, end + 5) !== '.glob')
  34852. continue;
  34853. const { importsString, exp, endIndex } = await transformImportGlob(source, start, normalizePath$3(importer), index, root, logger, undefined, resolve);
  34854. s.prepend(importsString);
  34855. s.overwrite(expStart, endIndex, exp, { contentOnly: true });
  34856. }
  34857. return s.toString();
  34858. }
  34859. /**
  34860. * when using TS + (Vue + `<script setup>`) or Svelte, imports may seem
  34861. * unused to esbuild and dropped in the build output, which prevents
  34862. * esbuild from crawling further.
  34863. * the solution is to add `import 'x'` for every source to force
  34864. * esbuild to keep crawling due to potential side effects.
  34865. */
  34866. function extractImportPaths(code) {
  34867. // empty singleline & multiline comments to avoid matching comments
  34868. code = code
  34869. .replace(multilineCommentsRE, '/* */')
  34870. .replace(singlelineCommentsRE, '');
  34871. let js = '';
  34872. let m;
  34873. while ((m = importsRE.exec(code)) != null) {
  34874. // This is necessary to avoid infinite loops with zero-width matches
  34875. if (m.index === importsRE.lastIndex) {
  34876. importsRE.lastIndex++;
  34877. }
  34878. js += `\nimport ${m[1]}`;
  34879. }
  34880. return js;
  34881. }
  34882. function shouldExternalizeDep(resolvedId, rawId) {
  34883. // not a valid file path
  34884. if (!path__default.isAbsolute(resolvedId)) {
  34885. return true;
  34886. }
  34887. // virtual id
  34888. if (resolvedId === rawId || resolvedId.includes('\0')) {
  34889. return true;
  34890. }
  34891. return false;
  34892. }
  34893. function isScannable(id) {
  34894. return JS_TYPES_RE.test(id) || htmlTypesRE.test(id);
  34895. }
  34896. const debuggerViteDeps = createDebugger('vite:deps');
  34897. const debug$c = debuggerViteDeps;
  34898. const isDebugEnabled$1 = _debug('vite:deps').enabled;
  34899. const jsExtensionRE = /\.js$/i;
  34900. const jsMapExtensionRE = /\.js\.map$/i;
  34901. /**
  34902. * Used by Vite CLI when running `vite optimize`
  34903. */
  34904. async function optimizeDeps(config, force = config.server.force, asCommand = false) {
  34905. const log = asCommand ? config.logger.info : debug$c;
  34906. const cachedMetadata = loadCachedDepOptimizationMetadata(config, force, asCommand);
  34907. if (cachedMetadata) {
  34908. return cachedMetadata;
  34909. }
  34910. const depsInfo = await discoverProjectDependencies(config);
  34911. const depsString = depsLogString(Object.keys(depsInfo));
  34912. log(colors$1.green(`Optimizing dependencies:\n ${depsString}`));
  34913. const result = await runOptimizeDeps(config, depsInfo);
  34914. await result.commit();
  34915. return result.metadata;
  34916. }
  34917. function createOptimizedDepsMetadata(config, timestamp) {
  34918. const hash = getDepHash(config);
  34919. return {
  34920. hash,
  34921. browserHash: getOptimizedBrowserHash(hash, {}, timestamp),
  34922. optimized: {},
  34923. chunks: {},
  34924. discovered: {},
  34925. depInfoList: []
  34926. };
  34927. }
  34928. function addOptimizedDepInfo(metadata, type, depInfo) {
  34929. metadata[type][depInfo.id] = depInfo;
  34930. metadata.depInfoList.push(depInfo);
  34931. return depInfo;
  34932. }
  34933. /**
  34934. * Creates the initial dep optimization metadata, loading it from the deps cache
  34935. * if it exists and pre-bundling isn't forced
  34936. */
  34937. function loadCachedDepOptimizationMetadata(config, force = config.server.force, asCommand = false) {
  34938. const log = asCommand ? config.logger.info : debug$c;
  34939. // Before Vite 2.9, dependencies were cached in the root of the cacheDir
  34940. // For compat, we remove the cache if we find the old structure
  34941. if (fs__default.existsSync(path__default.join(config.cacheDir, '_metadata.json'))) {
  34942. emptyDir(config.cacheDir);
  34943. }
  34944. const depsCacheDir = getDepsCacheDir(config);
  34945. if (!force) {
  34946. let cachedMetadata;
  34947. try {
  34948. const cachedMetadataPath = path__default.join(depsCacheDir, '_metadata.json');
  34949. cachedMetadata = parseOptimizedDepsMetadata(fs__default.readFileSync(cachedMetadataPath, 'utf-8'), depsCacheDir);
  34950. }
  34951. catch (e) { }
  34952. // hash is consistent, no need to re-bundle
  34953. if (cachedMetadata && cachedMetadata.hash === getDepHash(config)) {
  34954. log('Hash is consistent. Skipping. Use --force to override.');
  34955. // Nothing to commit or cancel as we are using the cache, we only
  34956. // need to resolve the processing promise so requests can move on
  34957. return cachedMetadata;
  34958. }
  34959. }
  34960. else {
  34961. config.logger.info('Forced re-optimization of dependencies');
  34962. }
  34963. // Start with a fresh cache
  34964. removeDirSync(depsCacheDir);
  34965. }
  34966. /**
  34967. * Initial optimizeDeps at server start. Perform a fast scan using esbuild to
  34968. * find deps to pre-bundle and include user hard-coded dependencies
  34969. */
  34970. async function discoverProjectDependencies(config, timestamp) {
  34971. const { deps, missing } = await scanImports(config);
  34972. const missingIds = Object.keys(missing);
  34973. if (missingIds.length) {
  34974. throw new Error(`The following dependencies are imported but could not be resolved:\n\n ${missingIds
  34975. .map((id) => `${colors$1.cyan(id)} ${colors$1.white(colors$1.dim(`(imported by ${missing[id]})`))}`)
  34976. .join(`\n `)}\n\nAre they installed?`);
  34977. }
  34978. await addManuallyIncludedOptimizeDeps(deps, config);
  34979. const browserHash = getOptimizedBrowserHash(getDepHash(config), deps, timestamp);
  34980. const discovered = {};
  34981. for (const id in deps) {
  34982. const entry = deps[id];
  34983. discovered[id] = {
  34984. id,
  34985. file: getOptimizedDepPath(id, config),
  34986. src: entry,
  34987. browserHash: browserHash
  34988. };
  34989. }
  34990. return discovered;
  34991. }
  34992. function depsLogString(qualifiedIds) {
  34993. if (isDebugEnabled$1) {
  34994. return colors$1.yellow(qualifiedIds.join(`\n `));
  34995. }
  34996. else {
  34997. const total = qualifiedIds.length;
  34998. const maxListed = 5;
  34999. const listed = Math.min(total, maxListed);
  35000. const extra = Math.max(0, total - maxListed);
  35001. return colors$1.yellow(qualifiedIds.slice(0, listed).join(`, `) +
  35002. (extra > 0 ? `, ...and ${extra} more` : ``));
  35003. }
  35004. }
  35005. /**
  35006. * Internally, Vite uses this function to prepare a optimizeDeps run. When Vite starts, we can get
  35007. * the metadata and start the server without waiting for the optimizeDeps processing to be completed
  35008. */
  35009. async function runOptimizeDeps(config, depsInfo) {
  35010. var _a, _b, _c, _d, _e;
  35011. config = {
  35012. ...config,
  35013. command: 'build'
  35014. };
  35015. const depsCacheDir = getDepsCacheDir(config);
  35016. const processingCacheDir = getProcessingDepsCacheDir(config);
  35017. // Create a temporal directory so we don't need to delete optimized deps
  35018. // until they have been processed. This also avoids leaving the deps cache
  35019. // directory in a corrupted state if there is an error
  35020. if (fs__default.existsSync(processingCacheDir)) {
  35021. emptyDir(processingCacheDir);
  35022. }
  35023. else {
  35024. fs__default.mkdirSync(processingCacheDir, { recursive: true });
  35025. }
  35026. // a hint for Node.js
  35027. // all files in the cache directory should be recognized as ES modules
  35028. writeFile(path__default.resolve(processingCacheDir, 'package.json'), JSON.stringify({ type: 'module' }));
  35029. const metadata = createOptimizedDepsMetadata(config);
  35030. metadata.browserHash = getOptimizedBrowserHash(metadata.hash, depsFromOptimizedDepInfo(depsInfo));
  35031. // We prebundle dependencies with esbuild and cache them, but there is no need
  35032. // to wait here. Code that needs to access the cached deps needs to await
  35033. // the optimizedDepInfo.processing promise for each dep
  35034. const qualifiedIds = Object.keys(depsInfo);
  35035. if (!qualifiedIds.length) {
  35036. return {
  35037. metadata,
  35038. commit() {
  35039. // Write metadata file, delete `deps` folder and rename the `processing` folder to `deps`
  35040. return commitProcessingDepsCacheSync();
  35041. },
  35042. cancel
  35043. };
  35044. }
  35045. // esbuild generates nested directory output with lowest common ancestor base
  35046. // this is unpredictable and makes it difficult to analyze entry / output
  35047. // mapping. So what we do here is:
  35048. // 1. flatten all ids to eliminate slash
  35049. // 2. in the plugin, read the entry ourselves as virtual files to retain the
  35050. // path.
  35051. const flatIdDeps = {};
  35052. const idToExports = {};
  35053. const flatIdToExports = {};
  35054. const { plugins = [], ...esbuildOptions } = (_b = (_a = config.optimizeDeps) === null || _a === void 0 ? void 0 : _a.esbuildOptions) !== null && _b !== void 0 ? _b : {};
  35055. await init;
  35056. for (const id in depsInfo) {
  35057. const flatId = flattenId(id);
  35058. const filePath = (flatIdDeps[flatId] = depsInfo[id].src);
  35059. let exportsData;
  35060. if ((_c = config.optimizeDeps.extensions) === null || _c === void 0 ? void 0 : _c.some((ext) => filePath.endsWith(ext))) {
  35061. // For custom supported extensions, build the entry file to transform it into JS,
  35062. // and then parse with es-module-lexer. Note that the `bundle` option is not `true`,
  35063. // so only the entry file is being transformed.
  35064. const result = await esbuild.build({
  35065. ...esbuildOptions,
  35066. plugins,
  35067. entryPoints: [filePath],
  35068. write: false,
  35069. format: 'esm'
  35070. });
  35071. exportsData = parse$e(result.outputFiles[0].text);
  35072. }
  35073. else {
  35074. const entryContent = fs__default.readFileSync(filePath, 'utf-8');
  35075. try {
  35076. exportsData = parse$e(entryContent);
  35077. }
  35078. catch {
  35079. const loader = ((_d = esbuildOptions.loader) === null || _d === void 0 ? void 0 : _d[path__default.extname(filePath)]) || 'jsx';
  35080. debug$c(`Unable to parse dependency: ${id}. Trying again with a ${loader} transform.`);
  35081. const transformed = await transformWithEsbuild(entryContent, filePath, {
  35082. loader
  35083. });
  35084. // Ensure that optimization won't fail by defaulting '.js' to the JSX parser.
  35085. // This is useful for packages such as Gatsby.
  35086. esbuildOptions.loader = {
  35087. '.js': 'jsx',
  35088. ...esbuildOptions.loader
  35089. };
  35090. exportsData = parse$e(transformed.code);
  35091. }
  35092. for (const { ss, se } of exportsData[0]) {
  35093. const exp = entryContent.slice(ss, se);
  35094. if (/export\s+\*\s+from/.test(exp)) {
  35095. exportsData.hasReExports = true;
  35096. }
  35097. }
  35098. }
  35099. idToExports[id] = exportsData;
  35100. flatIdToExports[flatId] = exportsData;
  35101. }
  35102. const define = {
  35103. 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || config.mode)
  35104. };
  35105. for (const key in config.define) {
  35106. const value = config.define[key];
  35107. define[key] = typeof value === 'string' ? value : JSON.stringify(value);
  35108. }
  35109. const start = perf_hooks.performance.now();
  35110. const result = await esbuild.build({
  35111. absWorkingDir: process.cwd(),
  35112. entryPoints: Object.keys(flatIdDeps),
  35113. bundle: true,
  35114. format: 'esm',
  35115. target: config.build.target || undefined,
  35116. external: (_e = config.optimizeDeps) === null || _e === void 0 ? void 0 : _e.exclude,
  35117. logLevel: 'error',
  35118. splitting: true,
  35119. sourcemap: true,
  35120. outdir: processingCacheDir,
  35121. ignoreAnnotations: true,
  35122. metafile: true,
  35123. define,
  35124. plugins: [
  35125. ...plugins,
  35126. esbuildDepPlugin(flatIdDeps, flatIdToExports, config)
  35127. ],
  35128. ...esbuildOptions
  35129. });
  35130. const meta = result.metafile;
  35131. // the paths in `meta.outputs` are relative to `process.cwd()`
  35132. const processingCacheDirOutputPath = path__default.relative(process.cwd(), processingCacheDir);
  35133. for (const id in depsInfo) {
  35134. const output = esbuildOutputFromId(meta.outputs, id, processingCacheDir);
  35135. addOptimizedDepInfo(metadata, 'optimized', {
  35136. ...depsInfo[id],
  35137. needsInterop: needsInterop(id, idToExports[id], output),
  35138. // We only need to hash the output.imports in to check for stability, but adding the hash
  35139. // and file path gives us a unique hash that may be useful for other things in the future
  35140. fileHash: getHash(metadata.hash + depsInfo[id].file + JSON.stringify(output.imports)),
  35141. browserHash: metadata.browserHash
  35142. });
  35143. }
  35144. for (const o of Object.keys(meta.outputs)) {
  35145. if (!o.match(jsMapExtensionRE)) {
  35146. const id = path__default
  35147. .relative(processingCacheDirOutputPath, o)
  35148. .replace(jsExtensionRE, '');
  35149. const file = getOptimizedDepPath(id, config);
  35150. if (!findOptimizedDepInfoInRecord(metadata.optimized, (depInfo) => depInfo.file === file)) {
  35151. addOptimizedDepInfo(metadata, 'chunks', {
  35152. id,
  35153. file,
  35154. needsInterop: false,
  35155. browserHash: metadata.browserHash
  35156. });
  35157. }
  35158. }
  35159. }
  35160. const dataPath = path__default.join(processingCacheDir, '_metadata.json');
  35161. writeFile(dataPath, stringifyOptimizedDepsMetadata(metadata, depsCacheDir));
  35162. debug$c(`deps bundled in ${(perf_hooks.performance.now() - start).toFixed(2)}ms`);
  35163. return {
  35164. metadata,
  35165. commit() {
  35166. // Write metadata file, delete `deps` folder and rename the new `processing` folder to `deps` in sync
  35167. return commitProcessingDepsCacheSync();
  35168. },
  35169. cancel
  35170. };
  35171. async function commitProcessingDepsCacheSync() {
  35172. // Processing is done, we can now replace the depsCacheDir with processingCacheDir
  35173. // Rewire the file paths from the temporal processing dir to the final deps cache dir
  35174. await removeDir(depsCacheDir);
  35175. await renameDir(processingCacheDir, depsCacheDir);
  35176. }
  35177. function cancel() {
  35178. removeDirSync(processingCacheDir);
  35179. }
  35180. }
  35181. async function findKnownImports(config) {
  35182. const deps = (await scanImports(config)).deps;
  35183. await addManuallyIncludedOptimizeDeps(deps, config);
  35184. return Object.keys(deps);
  35185. }
  35186. async function addManuallyIncludedOptimizeDeps(deps, config) {
  35187. var _a;
  35188. const include = (_a = config.optimizeDeps) === null || _a === void 0 ? void 0 : _a.include;
  35189. if (include) {
  35190. const resolve = config.createResolver({ asSrc: false });
  35191. for (const id of include) {
  35192. // normalize 'foo >bar` as 'foo > bar' to prevent same id being added
  35193. // and for pretty printing
  35194. const normalizedId = normalizeId(id);
  35195. if (!deps[normalizedId]) {
  35196. const entry = await resolve(id);
  35197. if (entry) {
  35198. deps[normalizedId] = entry;
  35199. }
  35200. else {
  35201. throw new Error(`Failed to resolve force included dependency: ${colors$1.cyan(id)}`);
  35202. }
  35203. }
  35204. }
  35205. }
  35206. }
  35207. function newDepOptimizationProcessing() {
  35208. let resolve;
  35209. const promise = new Promise((_resolve) => {
  35210. resolve = _resolve;
  35211. });
  35212. return { promise, resolve: resolve };
  35213. }
  35214. // Convert to { id: src }
  35215. function depsFromOptimizedDepInfo(depsInfo) {
  35216. return Object.fromEntries(Object.entries(depsInfo).map((d) => [d[0], d[1].src]));
  35217. }
  35218. function getOptimizedDepPath(id, config) {
  35219. return normalizePath$3(path__default.resolve(getDepsCacheDir(config), flattenId(id) + '.js'));
  35220. }
  35221. function getDepsCacheDir(config) {
  35222. return normalizePath$3(path__default.resolve(config.cacheDir, 'deps'));
  35223. }
  35224. function getProcessingDepsCacheDir(config) {
  35225. return normalizePath$3(path__default.resolve(config.cacheDir, 'processing'));
  35226. }
  35227. function isOptimizedDepFile(id, config) {
  35228. return id.startsWith(getDepsCacheDir(config));
  35229. }
  35230. function createIsOptimizedDepUrl(config) {
  35231. const { root } = config;
  35232. const depsCacheDir = getDepsCacheDir(config);
  35233. // determine the url prefix of files inside cache directory
  35234. const depsCacheDirRelative = normalizePath$3(path__default.relative(root, depsCacheDir));
  35235. const depsCacheDirPrefix = depsCacheDirRelative.startsWith('../')
  35236. ? // if the cache directory is outside root, the url prefix would be something
  35237. // like '/@fs/absolute/path/to/node_modules/.vite'
  35238. `/@fs/${normalizePath$3(depsCacheDir).replace(/^\//, '')}`
  35239. : // if the cache directory is inside root, the url prefix would be something
  35240. // like '/node_modules/.vite'
  35241. `/${depsCacheDirRelative}`;
  35242. return function isOptimizedDepUrl(url) {
  35243. return url.startsWith(depsCacheDirPrefix);
  35244. };
  35245. }
  35246. function parseOptimizedDepsMetadata(jsonMetadata, depsCacheDir) {
  35247. const { hash, browserHash, optimized, chunks } = JSON.parse(jsonMetadata, (key, value) => {
  35248. // Paths can be absolute or relative to the deps cache dir where
  35249. // the _metadata.json is located
  35250. if (key === 'file' || key === 'src') {
  35251. return normalizePath$3(path__default.resolve(depsCacheDir, value));
  35252. }
  35253. return value;
  35254. });
  35255. if (!chunks ||
  35256. Object.values(optimized).some((depInfo) => !depInfo.fileHash)) {
  35257. // outdated _metadata.json version, ignore
  35258. return;
  35259. }
  35260. const metadata = {
  35261. hash,
  35262. browserHash,
  35263. optimized: {},
  35264. discovered: {},
  35265. chunks: {},
  35266. depInfoList: []
  35267. };
  35268. for (const id of Object.keys(optimized)) {
  35269. addOptimizedDepInfo(metadata, 'optimized', {
  35270. ...optimized[id],
  35271. id,
  35272. browserHash
  35273. });
  35274. }
  35275. for (const id of Object.keys(chunks)) {
  35276. addOptimizedDepInfo(metadata, 'chunks', {
  35277. ...chunks[id],
  35278. id,
  35279. browserHash,
  35280. needsInterop: false
  35281. });
  35282. }
  35283. return metadata;
  35284. }
  35285. /**
  35286. * Stringify metadata for deps cache. Remove processing promises
  35287. * and individual dep info browserHash. Once the cache is reload
  35288. * the next time the server start we need to use the global
  35289. * browserHash to allow long term caching
  35290. */
  35291. function stringifyOptimizedDepsMetadata(metadata, depsCacheDir) {
  35292. const { hash, browserHash, optimized, chunks } = metadata;
  35293. return JSON.stringify({
  35294. hash,
  35295. browserHash,
  35296. optimized: Object.fromEntries(Object.values(optimized).map(({ id, src, file, fileHash, needsInterop }) => [
  35297. id,
  35298. {
  35299. src,
  35300. file,
  35301. fileHash,
  35302. needsInterop
  35303. }
  35304. ])),
  35305. chunks: Object.fromEntries(Object.values(chunks).map(({ id, file }) => [id, { file }]))
  35306. }, (key, value) => {
  35307. // Paths can be absolute or relative to the deps cache dir where
  35308. // the _metadata.json is located
  35309. if (key === 'file' || key === 'src') {
  35310. return normalizePath$3(path__default.relative(depsCacheDir, value));
  35311. }
  35312. return value;
  35313. }, 2);
  35314. }
  35315. function esbuildOutputFromId(outputs, id, cacheDirOutputPath) {
  35316. const flatId = flattenId(id) + '.js';
  35317. return outputs[normalizePath$3(path__default.relative(process.cwd(), path__default.join(cacheDirOutputPath, flatId)))];
  35318. }
  35319. // https://github.com/vitejs/vite/issues/1724#issuecomment-767619642
  35320. // a list of modules that pretends to be ESM but still uses `require`.
  35321. // this causes esbuild to wrap them as CJS even when its entry appears to be ESM.
  35322. const KNOWN_INTEROP_IDS = new Set(['moment']);
  35323. function needsInterop(id, exportsData, output) {
  35324. if (KNOWN_INTEROP_IDS.has(id)) {
  35325. return true;
  35326. }
  35327. const [imports, exports] = exportsData;
  35328. // entry has no ESM syntax - likely CJS or UMD
  35329. if (!exports.length && !imports.length) {
  35330. return true;
  35331. }
  35332. // if a peer dependency used require() on a ESM dependency, esbuild turns the
  35333. // ESM dependency's entry chunk into a single default export... detect
  35334. // such cases by checking exports mismatch, and force interop.
  35335. const generatedExports = output.exports;
  35336. if (!generatedExports ||
  35337. (isSingleDefaultExport(generatedExports) && !isSingleDefaultExport(exports))) {
  35338. return true;
  35339. }
  35340. return false;
  35341. }
  35342. function isSingleDefaultExport(exports) {
  35343. return exports.length === 1 && exports[0] === 'default';
  35344. }
  35345. const lockfileFormats = ['package-lock.json', 'yarn.lock', 'pnpm-lock.yaml'];
  35346. function getDepHash(config) {
  35347. var _a, _b, _c, _d, _e, _f;
  35348. let content = lookupFile(config.root, lockfileFormats) || '';
  35349. // also take config into account
  35350. // only a subset of config options that can affect dep optimization
  35351. content += JSON.stringify({
  35352. mode: process.env.NODE_ENV || config.mode,
  35353. root: config.root,
  35354. define: config.define,
  35355. resolve: config.resolve,
  35356. buildTarget: config.build.target,
  35357. assetsInclude: config.assetsInclude,
  35358. plugins: config.plugins.map((p) => p.name),
  35359. optimizeDeps: {
  35360. include: (_a = config.optimizeDeps) === null || _a === void 0 ? void 0 : _a.include,
  35361. exclude: (_b = config.optimizeDeps) === null || _b === void 0 ? void 0 : _b.exclude,
  35362. esbuildOptions: {
  35363. ...(_c = config.optimizeDeps) === null || _c === void 0 ? void 0 : _c.esbuildOptions,
  35364. plugins: (_f = (_e = (_d = config.optimizeDeps) === null || _d === void 0 ? void 0 : _d.esbuildOptions) === null || _e === void 0 ? void 0 : _e.plugins) === null || _f === void 0 ? void 0 : _f.map((p) => p.name)
  35365. }
  35366. }
  35367. }, (_, value) => {
  35368. if (typeof value === 'function' || value instanceof RegExp) {
  35369. return value.toString();
  35370. }
  35371. return value;
  35372. });
  35373. return getHash(content);
  35374. }
  35375. function getOptimizedBrowserHash(hash, deps, timestamp = '') {
  35376. return getHash(hash + JSON.stringify(deps) + timestamp);
  35377. }
  35378. function getHash(text) {
  35379. return require$$1$1.createHash('sha256').update(text).digest('hex').substring(0, 8);
  35380. }
  35381. function optimizedDepInfoFromId(metadata, id) {
  35382. return (metadata.optimized[id] || metadata.discovered[id] || metadata.chunks[id]);
  35383. }
  35384. function optimizedDepInfoFromFile(metadata, file) {
  35385. return metadata.depInfoList.find((depInfo) => depInfo.file === file);
  35386. }
  35387. function findOptimizedDepInfoInRecord(dependenciesInfo, callbackFn) {
  35388. for (const o of Object.keys(dependenciesInfo)) {
  35389. const info = dependenciesInfo[o];
  35390. if (callbackFn(info, o)) {
  35391. return info;
  35392. }
  35393. }
  35394. }
  35395. async function optimizedDepNeedsInterop(metadata, file) {
  35396. const depInfo = optimizedDepInfoFromFile(metadata, file);
  35397. if (!depInfo)
  35398. return undefined;
  35399. // Wait until the dependency has been pre-bundled
  35400. await depInfo.processing;
  35401. return depInfo === null || depInfo === void 0 ? void 0 : depInfo.needsInterop;
  35402. }
  35403. var index$1 = {
  35404. __proto__: null,
  35405. debuggerViteDeps: debuggerViteDeps,
  35406. optimizeDeps: optimizeDeps,
  35407. createOptimizedDepsMetadata: createOptimizedDepsMetadata,
  35408. addOptimizedDepInfo: addOptimizedDepInfo,
  35409. loadCachedDepOptimizationMetadata: loadCachedDepOptimizationMetadata,
  35410. discoverProjectDependencies: discoverProjectDependencies,
  35411. depsLogString: depsLogString,
  35412. runOptimizeDeps: runOptimizeDeps,
  35413. findKnownImports: findKnownImports,
  35414. newDepOptimizationProcessing: newDepOptimizationProcessing,
  35415. depsFromOptimizedDepInfo: depsFromOptimizedDepInfo,
  35416. getOptimizedDepPath: getOptimizedDepPath,
  35417. getDepsCacheDir: getDepsCacheDir,
  35418. isOptimizedDepFile: isOptimizedDepFile,
  35419. createIsOptimizedDepUrl: createIsOptimizedDepUrl,
  35420. getDepHash: getDepHash,
  35421. getHash: getHash,
  35422. optimizedDepInfoFromId: optimizedDepInfoFromId,
  35423. optimizedDepInfoFromFile: optimizedDepInfoFromFile,
  35424. optimizedDepNeedsInterop: optimizedDepNeedsInterop
  35425. };
  35426. const isDebug$5 = process.env.DEBUG;
  35427. const debug$b = createDebugger('vite:resolve-details', {
  35428. onlyWhenFocused: true
  35429. });
  35430. function invalidatePackageData(packageCache, pkgPath) {
  35431. packageCache.delete(pkgPath);
  35432. const pkgDir = path__default.dirname(pkgPath);
  35433. packageCache.forEach((pkg, cacheKey) => {
  35434. if (pkg.dir === pkgDir) {
  35435. packageCache.delete(cacheKey);
  35436. }
  35437. });
  35438. }
  35439. function resolvePackageData(id, basedir, preserveSymlinks = false, packageCache) {
  35440. let pkg;
  35441. let cacheKey;
  35442. if (packageCache) {
  35443. cacheKey = `${id}&${basedir}&${preserveSymlinks}`;
  35444. if ((pkg = packageCache.get(cacheKey))) {
  35445. return pkg;
  35446. }
  35447. }
  35448. let pkgPath;
  35449. try {
  35450. pkgPath = resolveFrom(`${id}/package.json`, basedir, preserveSymlinks);
  35451. pkg = loadPackageData(pkgPath, true, packageCache);
  35452. if (packageCache) {
  35453. packageCache.set(cacheKey, pkg);
  35454. }
  35455. return pkg;
  35456. }
  35457. catch (e) {
  35458. if (e instanceof SyntaxError) {
  35459. isDebug$5 && debug$b(`Parsing failed: ${pkgPath}`);
  35460. }
  35461. // Ignore error for missing package.json
  35462. else if (e.code !== 'MODULE_NOT_FOUND') {
  35463. throw e;
  35464. }
  35465. }
  35466. return null;
  35467. }
  35468. function loadPackageData(pkgPath, preserveSymlinks, packageCache) {
  35469. if (!preserveSymlinks) {
  35470. pkgPath = fs__default.realpathSync.native(pkgPath);
  35471. }
  35472. let cached;
  35473. if ((cached = packageCache === null || packageCache === void 0 ? void 0 : packageCache.get(pkgPath))) {
  35474. return cached;
  35475. }
  35476. const data = JSON.parse(fs__default.readFileSync(pkgPath, 'utf-8'));
  35477. const pkgDir = path__default.dirname(pkgPath);
  35478. const { sideEffects } = data;
  35479. let hasSideEffects;
  35480. if (typeof sideEffects === 'boolean') {
  35481. hasSideEffects = () => sideEffects;
  35482. }
  35483. else if (Array.isArray(sideEffects)) {
  35484. hasSideEffects = createFilter$1(sideEffects, null, { resolve: pkgDir });
  35485. }
  35486. else {
  35487. hasSideEffects = () => true;
  35488. }
  35489. const pkg = {
  35490. dir: pkgDir,
  35491. data,
  35492. hasSideEffects,
  35493. webResolvedImports: {},
  35494. nodeResolvedImports: {},
  35495. setResolvedCache(key, entry, targetWeb) {
  35496. if (targetWeb) {
  35497. pkg.webResolvedImports[key] = entry;
  35498. }
  35499. else {
  35500. pkg.nodeResolvedImports[key] = entry;
  35501. }
  35502. },
  35503. getResolvedCache(key, targetWeb) {
  35504. if (targetWeb) {
  35505. return pkg.webResolvedImports[key];
  35506. }
  35507. else {
  35508. return pkg.nodeResolvedImports[key];
  35509. }
  35510. }
  35511. };
  35512. packageCache === null || packageCache === void 0 ? void 0 : packageCache.set(pkgPath, pkg);
  35513. return pkg;
  35514. }
  35515. function watchPackageDataPlugin(config) {
  35516. const watchQueue = new Set();
  35517. let watchFile = (id) => {
  35518. watchQueue.add(id);
  35519. };
  35520. const { packageCache } = config;
  35521. const setPackageData = packageCache.set.bind(packageCache);
  35522. packageCache.set = (id, pkg) => {
  35523. if (id.endsWith('.json')) {
  35524. watchFile(id);
  35525. }
  35526. return setPackageData(id, pkg);
  35527. };
  35528. return {
  35529. name: 'vite:watch-package-data',
  35530. buildStart() {
  35531. watchFile = this.addWatchFile;
  35532. watchQueue.forEach(watchFile);
  35533. watchQueue.clear();
  35534. },
  35535. buildEnd() {
  35536. watchFile = (id) => watchQueue.add(id);
  35537. },
  35538. watchChange(id) {
  35539. if (id.endsWith('/package.json')) {
  35540. invalidatePackageData(packageCache, id);
  35541. }
  35542. }
  35543. };
  35544. }
  35545. // special id for paths marked with browser: false
  35546. // https://github.com/defunctzombie/package-browser-field-spec#ignore-a-module
  35547. const browserExternalId = '__vite-browser-external';
  35548. const isDebug$4 = process.env.DEBUG;
  35549. const debug$a = createDebugger('vite:resolve-details', {
  35550. onlyWhenFocused: true
  35551. });
  35552. function resolvePlugin(baseOptions) {
  35553. const { root, isProduction, asSrc, ssrConfig, preferRelative = false } = baseOptions;
  35554. let server;
  35555. let isOptimizedDepUrl;
  35556. const { target: ssrTarget, noExternal: ssrNoExternal } = ssrConfig !== null && ssrConfig !== void 0 ? ssrConfig : {};
  35557. return {
  35558. name: 'vite:resolve',
  35559. configureServer(_server) {
  35560. server = _server;
  35561. isOptimizedDepUrl = createIsOptimizedDepUrl(server.config);
  35562. },
  35563. async resolveId(id, importer, resolveOpts) {
  35564. var _a, _b, _c, _d, _e, _f, _g, _h;
  35565. const ssr = (resolveOpts === null || resolveOpts === void 0 ? void 0 : resolveOpts.ssr) === true;
  35566. if (id.startsWith(browserExternalId)) {
  35567. return id;
  35568. }
  35569. // fast path for commonjs proxy modules
  35570. if (/\?commonjs/.test(id) || id === 'commonjsHelpers.js') {
  35571. return;
  35572. }
  35573. const targetWeb = !ssr || ssrTarget === 'webworker';
  35574. // this is passed by @rollup/plugin-commonjs
  35575. const isRequire = (_c = (_b = (_a = resolveOpts === null || resolveOpts === void 0 ? void 0 : resolveOpts.custom) === null || _a === void 0 ? void 0 : _a['node-resolve']) === null || _b === void 0 ? void 0 : _b.isRequire) !== null && _c !== void 0 ? _c : false;
  35576. const options = {
  35577. isRequire,
  35578. ...baseOptions,
  35579. scan: (_d = resolveOpts === null || resolveOpts === void 0 ? void 0 : resolveOpts.scan) !== null && _d !== void 0 ? _d : baseOptions.scan
  35580. };
  35581. if (importer) {
  35582. if (isTsRequest(importer)) {
  35583. options.isFromTsImporter = true;
  35584. }
  35585. else {
  35586. const moduleLang = (_g = (_f = (_e = this.getModuleInfo(importer)) === null || _e === void 0 ? void 0 : _e.meta) === null || _f === void 0 ? void 0 : _f.vite) === null || _g === void 0 ? void 0 : _g.lang;
  35587. options.isFromTsImporter = moduleLang && isTsRequest(`.${moduleLang}`);
  35588. }
  35589. }
  35590. let res;
  35591. // resolve pre-bundled deps requests, these could be resolved by
  35592. // tryFileResolve or /fs/ resolution but these files may not yet
  35593. // exists if we are in the middle of a deps re-processing
  35594. if (asSrc && (isOptimizedDepUrl === null || isOptimizedDepUrl === void 0 ? void 0 : isOptimizedDepUrl(id))) {
  35595. const optimizedPath = id.startsWith(FS_PREFIX)
  35596. ? fsPathFromId(id)
  35597. : normalizePath$3(ensureVolumeInPath(path__default.resolve(root, id.slice(1))));
  35598. return optimizedPath;
  35599. }
  35600. // explicit fs paths that starts with /@fs/*
  35601. if (asSrc && id.startsWith(FS_PREFIX)) {
  35602. const fsPath = fsPathFromId(id);
  35603. res = tryFsResolve(fsPath, options);
  35604. isDebug$4 && debug$a(`[@fs] ${colors$1.cyan(id)} -> ${colors$1.dim(res)}`);
  35605. // always return here even if res doesn't exist since /@fs/ is explicit
  35606. // if the file doesn't exist it should be a 404
  35607. return res || fsPath;
  35608. }
  35609. // URL
  35610. // /foo -> /fs-root/foo
  35611. if (asSrc && id.startsWith('/')) {
  35612. const fsPath = path__default.resolve(root, id.slice(1));
  35613. if ((res = tryFsResolve(fsPath, options))) {
  35614. isDebug$4 && debug$a(`[url] ${colors$1.cyan(id)} -> ${colors$1.dim(res)}`);
  35615. return res;
  35616. }
  35617. }
  35618. // relative
  35619. if (id.startsWith('.') || (preferRelative && /^\w/.test(id))) {
  35620. const basedir = importer ? path__default.dirname(importer) : process.cwd();
  35621. const fsPath = path__default.resolve(basedir, id);
  35622. // handle browser field mapping for relative imports
  35623. const normalizedFsPath = normalizePath$3(fsPath);
  35624. if ((server === null || server === void 0 ? void 0 : server._optimizedDeps) &&
  35625. isOptimizedDepFile(normalizedFsPath, server.config)) {
  35626. // Optimized files could not yet exist in disk, resolve to the full path
  35627. // Inject the current browserHash version if the path doesn't have one
  35628. if (!normalizedFsPath.match(DEP_VERSION_RE)) {
  35629. const browserHash = (_h = optimizedDepInfoFromFile(server._optimizedDeps.metadata, normalizedFsPath)) === null || _h === void 0 ? void 0 : _h.browserHash;
  35630. if (browserHash) {
  35631. return injectQuery(normalizedFsPath, `v=${browserHash}`);
  35632. }
  35633. }
  35634. return normalizedFsPath;
  35635. }
  35636. const pathFromBasedir = normalizedFsPath.slice(basedir.length);
  35637. if (pathFromBasedir.startsWith('/node_modules/')) {
  35638. // normalize direct imports from node_modules to bare imports, so the
  35639. // hashing logic is shared and we avoid duplicated modules #2503
  35640. const bareImport = pathFromBasedir.slice('/node_modules/'.length);
  35641. if ((res = tryNodeResolve(bareImport, importer, options, targetWeb, server, ssr)) &&
  35642. res.id.startsWith(normalizedFsPath)) {
  35643. return res;
  35644. }
  35645. }
  35646. if (targetWeb &&
  35647. (res = tryResolveBrowserMapping(fsPath, importer, options, true))) {
  35648. return res;
  35649. }
  35650. if ((res = tryFsResolve(fsPath, options))) {
  35651. isDebug$4 &&
  35652. debug$a(`[relative] ${colors$1.cyan(id)} -> ${colors$1.dim(res)}`);
  35653. const pkg = importer != null && idToPkgMap.get(importer);
  35654. if (pkg) {
  35655. idToPkgMap.set(res, pkg);
  35656. return {
  35657. id: res,
  35658. moduleSideEffects: pkg.hasSideEffects(res)
  35659. };
  35660. }
  35661. return res;
  35662. }
  35663. }
  35664. // absolute fs paths
  35665. if (path__default.isAbsolute(id) && (res = tryFsResolve(id, options))) {
  35666. isDebug$4 && debug$a(`[fs] ${colors$1.cyan(id)} -> ${colors$1.dim(res)}`);
  35667. return res;
  35668. }
  35669. // external
  35670. if (isExternalUrl(id)) {
  35671. return {
  35672. id,
  35673. external: true
  35674. };
  35675. }
  35676. // data uri: pass through (this only happens during build and will be
  35677. // handled by dedicated plugin)
  35678. if (isDataUrl(id)) {
  35679. return null;
  35680. }
  35681. // bare package imports, perform node resolve
  35682. if (bareImportRE.test(id)) {
  35683. if (asSrc &&
  35684. server &&
  35685. !ssr &&
  35686. !options.scan &&
  35687. (res = await tryOptimizedResolve(id, server, importer))) {
  35688. return res;
  35689. }
  35690. if (targetWeb &&
  35691. (res = tryResolveBrowserMapping(id, importer, options, false))) {
  35692. return res;
  35693. }
  35694. if ((res = tryNodeResolve(id, importer, options, targetWeb, server, ssr))) {
  35695. return res;
  35696. }
  35697. // node built-ins.
  35698. // externalize if building for SSR, otherwise redirect to empty module
  35699. if (isBuiltin(id)) {
  35700. if (ssr) {
  35701. if (ssrNoExternal === true) {
  35702. let message = `Cannot bundle Node.js built-in "${id}"`;
  35703. if (importer) {
  35704. message += ` imported from "${path__default.relative(process.cwd(), importer)}"`;
  35705. }
  35706. message += `. Consider disabling ssr.noExternal or remove the built-in dependency.`;
  35707. this.error(message);
  35708. }
  35709. return {
  35710. id,
  35711. external: true
  35712. };
  35713. }
  35714. else {
  35715. if (!asSrc) {
  35716. debug$a(`externalized node built-in "${id}" to empty module. ` +
  35717. `(imported by: ${colors$1.white(colors$1.dim(importer))})`);
  35718. }
  35719. return isProduction
  35720. ? browserExternalId
  35721. : `${browserExternalId}:${id}`;
  35722. }
  35723. }
  35724. }
  35725. isDebug$4 && debug$a(`[fallthrough] ${colors$1.dim(id)}`);
  35726. },
  35727. load(id) {
  35728. if (id.startsWith(browserExternalId)) {
  35729. return isProduction
  35730. ? `export default {}`
  35731. : `export default new Proxy({}, {
  35732. get() {
  35733. throw new Error('Module "${id.slice(browserExternalId.length + 1)}" has been externalized for browser compatibility and cannot be accessed in client code.')
  35734. }
  35735. })`;
  35736. }
  35737. }
  35738. };
  35739. }
  35740. function splitFileAndPostfix(path) {
  35741. let file = path;
  35742. let postfix = '';
  35743. let postfixIndex = path.indexOf('?');
  35744. if (postfixIndex < 0) {
  35745. postfixIndex = path.indexOf('#');
  35746. }
  35747. if (postfixIndex > 0) {
  35748. file = path.slice(0, postfixIndex);
  35749. postfix = path.slice(postfixIndex);
  35750. }
  35751. return { file, postfix };
  35752. }
  35753. function tryFsResolve(fsPath, options, tryIndex = true, targetWeb = true) {
  35754. const { file, postfix } = splitFileAndPostfix(fsPath);
  35755. let res;
  35756. // if we fould postfix exist, we should first try resolving file with postfix. details see #4703.
  35757. if (postfix &&
  35758. (res = tryResolveFile(fsPath, '', options, false, targetWeb, options.tryPrefix, options.skipPackageJson))) {
  35759. return res;
  35760. }
  35761. if ((res = tryResolveFile(file, postfix, options, false, targetWeb, options.tryPrefix, options.skipPackageJson))) {
  35762. return res;
  35763. }
  35764. for (const ext of options.extensions || DEFAULT_EXTENSIONS$1) {
  35765. if (postfix &&
  35766. (res = tryResolveFile(fsPath + ext, '', options, false, targetWeb, options.tryPrefix, options.skipPackageJson))) {
  35767. return res;
  35768. }
  35769. if ((res = tryResolveFile(file + ext, postfix, options, false, targetWeb, options.tryPrefix, options.skipPackageJson))) {
  35770. return res;
  35771. }
  35772. }
  35773. if (postfix &&
  35774. (res = tryResolveFile(fsPath, '', options, tryIndex, targetWeb, options.tryPrefix, options.skipPackageJson))) {
  35775. return res;
  35776. }
  35777. if ((res = tryResolveFile(file, postfix, options, tryIndex, targetWeb, options.tryPrefix, options.skipPackageJson))) {
  35778. return res;
  35779. }
  35780. }
  35781. function tryResolveFile(file, postfix, options, tryIndex, targetWeb, tryPrefix, skipPackageJson) {
  35782. // #2051 if we don't have read permission on a directory, existsSync() still
  35783. // works and will result in massively slow subsequent checks (which are
  35784. // unnecessary in the first place)
  35785. if (isFileReadable(file)) {
  35786. if (!fs__default.statSync(file).isDirectory()) {
  35787. return getRealPath(file, options.preserveSymlinks) + postfix;
  35788. }
  35789. else if (tryIndex) {
  35790. if (!skipPackageJson) {
  35791. const pkgPath = file + '/package.json';
  35792. try {
  35793. // path points to a node package
  35794. const pkg = loadPackageData(pkgPath, options.preserveSymlinks);
  35795. const resolved = resolvePackageEntry(file, pkg, targetWeb, options);
  35796. return resolved;
  35797. }
  35798. catch (e) {
  35799. if (e.code !== 'ENOENT') {
  35800. throw e;
  35801. }
  35802. }
  35803. }
  35804. const index = tryFsResolve(file + '/index', options);
  35805. if (index)
  35806. return index + postfix;
  35807. }
  35808. }
  35809. const tryTsExtension = options.isFromTsImporter && isPossibleTsOutput(file);
  35810. if (tryTsExtension) {
  35811. const tsSrcPaths = getPotentialTsSrcPaths(file);
  35812. for (const srcPath of tsSrcPaths) {
  35813. const res = tryResolveFile(srcPath, postfix, options, tryIndex, targetWeb, tryPrefix, skipPackageJson);
  35814. if (res)
  35815. return res;
  35816. }
  35817. return;
  35818. }
  35819. if (tryPrefix) {
  35820. const prefixed = `${path__default.dirname(file)}/${tryPrefix}${path__default.basename(file)}`;
  35821. return tryResolveFile(prefixed, postfix, options, tryIndex, targetWeb);
  35822. }
  35823. }
  35824. const idToPkgMap = new Map();
  35825. function tryNodeResolve(id, importer, options, targetWeb, server, ssr) {
  35826. var _a;
  35827. const { root, dedupe, isBuild, preserveSymlinks, packageCache } = options;
  35828. // split id by last '>' for nested selected packages, for example:
  35829. // 'foo > bar > baz' => 'foo > bar' & 'baz'
  35830. // 'foo' => '' & 'foo'
  35831. const lastArrowIndex = id.lastIndexOf('>');
  35832. const nestedRoot = id.substring(0, lastArrowIndex).trim();
  35833. const nestedPath = id.substring(lastArrowIndex + 1).trim();
  35834. const possiblePkgIds = [];
  35835. for (let prevSlashIndex = -1;;) {
  35836. let slashIndex = nestedPath.indexOf('/', prevSlashIndex + 1);
  35837. if (slashIndex < 0) {
  35838. slashIndex = nestedPath.length;
  35839. }
  35840. const part = nestedPath.slice(prevSlashIndex + 1, (prevSlashIndex = slashIndex));
  35841. if (!part) {
  35842. break;
  35843. }
  35844. // Assume path parts with an extension are not package roots, except for the
  35845. // first path part (since periods are sadly allowed in package names).
  35846. // At the same time, skip the first path part if it begins with "@"
  35847. // (since "@foo/bar" should be treated as the top-level path).
  35848. if (possiblePkgIds.length ? path__default.extname(part) : part[0] === '@') {
  35849. continue;
  35850. }
  35851. const possiblePkgId = nestedPath.slice(0, slashIndex);
  35852. possiblePkgIds.push(possiblePkgId);
  35853. }
  35854. let basedir;
  35855. if (dedupe === null || dedupe === void 0 ? void 0 : dedupe.some((id) => possiblePkgIds.includes(id))) {
  35856. basedir = root;
  35857. }
  35858. else if (importer &&
  35859. path__default.isAbsolute(importer) &&
  35860. fs__default.existsSync(cleanUrl(importer))) {
  35861. basedir = path__default.dirname(importer);
  35862. }
  35863. else {
  35864. basedir = root;
  35865. }
  35866. // nested node module, step-by-step resolve to the basedir of the nestedPath
  35867. if (nestedRoot) {
  35868. basedir = nestedResolveFrom(nestedRoot, basedir, preserveSymlinks);
  35869. }
  35870. let pkg;
  35871. const pkgId = possiblePkgIds.reverse().find((pkgId) => {
  35872. pkg = resolvePackageData(pkgId, basedir, preserveSymlinks, packageCache);
  35873. return pkg;
  35874. });
  35875. if (!pkg) {
  35876. return;
  35877. }
  35878. let resolveId = resolvePackageEntry;
  35879. let unresolvedId = pkgId;
  35880. if (unresolvedId !== nestedPath) {
  35881. resolveId = resolveDeepImport;
  35882. unresolvedId = '.' + nestedPath.slice(pkgId.length);
  35883. }
  35884. let resolved;
  35885. try {
  35886. resolved = resolveId(unresolvedId, pkg, targetWeb, options);
  35887. }
  35888. catch (err) {
  35889. if (!options.tryEsmOnly) {
  35890. throw err;
  35891. }
  35892. }
  35893. if (!resolved && options.tryEsmOnly) {
  35894. resolved = resolveId(unresolvedId, pkg, targetWeb, {
  35895. ...options,
  35896. isRequire: false,
  35897. mainFields: DEFAULT_MAIN_FIELDS,
  35898. extensions: DEFAULT_EXTENSIONS$1
  35899. });
  35900. }
  35901. if (!resolved) {
  35902. return;
  35903. }
  35904. // link id to pkg for browser field mapping check
  35905. idToPkgMap.set(resolved, pkg);
  35906. if (isBuild) {
  35907. // Resolve package side effects for build so that rollup can better
  35908. // perform tree-shaking
  35909. return {
  35910. id: resolved,
  35911. moduleSideEffects: pkg.hasSideEffects(resolved)
  35912. };
  35913. }
  35914. else {
  35915. if (!resolved.includes('node_modules') || // linked
  35916. !server || // build
  35917. !server._optimizedDeps || // resolving before listening to the server
  35918. options.scan // initial esbuild scan phase
  35919. ) {
  35920. return { id: resolved };
  35921. }
  35922. // if we reach here, it's a valid dep import that hasn't been optimized.
  35923. const isJsType = OPTIMIZABLE_ENTRY_RE.test(resolved);
  35924. const exclude = (_a = server.config.optimizeDeps) === null || _a === void 0 ? void 0 : _a.exclude;
  35925. if (!isJsType ||
  35926. (importer === null || importer === void 0 ? void 0 : importer.includes('node_modules')) ||
  35927. (exclude === null || exclude === void 0 ? void 0 : exclude.includes(pkgId)) ||
  35928. (exclude === null || exclude === void 0 ? void 0 : exclude.includes(nestedPath)) ||
  35929. SPECIAL_QUERY_RE.test(resolved) ||
  35930. ssr) {
  35931. // excluded from optimization
  35932. // Inject a version query to npm deps so that the browser
  35933. // can cache it without re-validation, but only do so for known js types.
  35934. // otherwise we may introduce duplicated modules for externalized files
  35935. // from pre-bundled deps.
  35936. const versionHash = server._optimizedDeps.metadata.browserHash;
  35937. if (versionHash && isJsType) {
  35938. resolved = injectQuery(resolved, `v=${versionHash}`);
  35939. }
  35940. }
  35941. else {
  35942. // this is a missing import, queue optimize-deps re-run and
  35943. // get a resolved its optimized info
  35944. const optimizedInfo = server._optimizedDeps.registerMissingImport(id, resolved);
  35945. resolved = getOptimizedUrl(optimizedInfo);
  35946. }
  35947. return { id: resolved };
  35948. }
  35949. }
  35950. const getOptimizedUrl = (optimizedData) => `${optimizedData.file}?v=${optimizedData.browserHash}`;
  35951. async function tryOptimizedResolve(id, server, importer) {
  35952. const optimizedDeps = server._optimizedDeps;
  35953. if (!optimizedDeps)
  35954. return;
  35955. await optimizedDeps.scanProcessing;
  35956. const depInfo = optimizedDepInfoFromId(optimizedDeps.metadata, id);
  35957. if (depInfo) {
  35958. return getOptimizedUrl(depInfo);
  35959. }
  35960. if (!importer)
  35961. return;
  35962. // further check if id is imported by nested dependency
  35963. let resolvedSrc;
  35964. for (const optimizedData of optimizedDeps.metadata.depInfoList) {
  35965. if (!optimizedData.src)
  35966. continue; // Ignore chunks
  35967. const pkgPath = optimizedData.id;
  35968. // check for scenarios, e.g.
  35969. // pkgPath => "my-lib > foo"
  35970. // id => "foo"
  35971. // this narrows the need to do a full resolve
  35972. if (!pkgPath.endsWith(id))
  35973. continue;
  35974. // lazily initialize resolvedSrc
  35975. if (resolvedSrc == null) {
  35976. try {
  35977. // this may throw errors if unable to resolve, e.g. aliased id
  35978. resolvedSrc = normalizePath$3(resolveFrom(id, path__default.dirname(importer)));
  35979. }
  35980. catch {
  35981. // this is best-effort only so swallow errors
  35982. break;
  35983. }
  35984. }
  35985. // match by src to correctly identify if id belongs to nested dependency
  35986. if (optimizedData.src === resolvedSrc) {
  35987. return getOptimizedUrl(optimizedData);
  35988. }
  35989. }
  35990. }
  35991. function resolvePackageEntry(id, { dir, data, setResolvedCache, getResolvedCache }, targetWeb, options) {
  35992. var _a, _b;
  35993. const cached = getResolvedCache('.', targetWeb);
  35994. if (cached) {
  35995. return cached;
  35996. }
  35997. try {
  35998. let entryPoint;
  35999. // resolve exports field with highest priority
  36000. // using https://github.com/lukeed/resolve.exports
  36001. if (data.exports) {
  36002. entryPoint = resolveExports(data, '.', options, targetWeb);
  36003. }
  36004. // if exports resolved to .mjs, still resolve other fields.
  36005. // This is because .mjs files can technically import .cjs files which would
  36006. // make them invalid for pure ESM environments - so if other module/browser
  36007. // fields are present, prioritize those instead.
  36008. if (targetWeb && (!entryPoint || entryPoint.endsWith('.mjs'))) {
  36009. // check browser field
  36010. // https://github.com/defunctzombie/package-browser-field-spec
  36011. const browserEntry = typeof data.browser === 'string'
  36012. ? data.browser
  36013. : isObject$1(data.browser) && data.browser['.'];
  36014. if (browserEntry) {
  36015. // check if the package also has a "module" field.
  36016. if (!options.isRequire &&
  36017. typeof data.module === 'string' &&
  36018. data.module !== browserEntry) {
  36019. // if both are present, we may have a problem: some package points both
  36020. // to ESM, with "module" targeting Node.js, while some packages points
  36021. // "module" to browser ESM and "browser" to UMD.
  36022. // the heuristics here is to actually read the browser entry when
  36023. // possible and check for hints of UMD. If it is UMD, prefer "module"
  36024. // instead; Otherwise, assume it's ESM and use it.
  36025. const resolvedBrowserEntry = tryFsResolve(path__default.join(dir, browserEntry), options);
  36026. if (resolvedBrowserEntry) {
  36027. const content = fs__default.readFileSync(resolvedBrowserEntry, 'utf-8');
  36028. if ((/typeof exports\s*==/.test(content) &&
  36029. /typeof module\s*==/.test(content)) ||
  36030. /module\.exports\s*=/.test(content)) {
  36031. // likely UMD or CJS(!!! e.g. firebase 7.x), prefer module
  36032. entryPoint = data.module;
  36033. }
  36034. }
  36035. }
  36036. else {
  36037. entryPoint = browserEntry;
  36038. }
  36039. }
  36040. }
  36041. if (!entryPoint || entryPoint.endsWith('.mjs')) {
  36042. for (const field of options.mainFields || DEFAULT_MAIN_FIELDS) {
  36043. if (typeof data[field] === 'string') {
  36044. entryPoint = data[field];
  36045. break;
  36046. }
  36047. }
  36048. }
  36049. entryPoint || (entryPoint = data.main);
  36050. // try default entry when entry is not define
  36051. // https://nodejs.org/api/modules.html#all-together
  36052. const entryPoints = entryPoint
  36053. ? [entryPoint]
  36054. : ['index.js', 'index.json', 'index.node'];
  36055. for (let entry of entryPoints) {
  36056. // make sure we don't get scripts when looking for sass
  36057. if (((_a = options.mainFields) === null || _a === void 0 ? void 0 : _a[0]) === 'sass' &&
  36058. !((_b = options.extensions) === null || _b === void 0 ? void 0 : _b.includes(path__default.extname(entry)))) {
  36059. entry = '';
  36060. options.skipPackageJson = true;
  36061. }
  36062. // resolve object browser field in package.json
  36063. const { browser: browserField } = data;
  36064. if (targetWeb && isObject$1(browserField)) {
  36065. entry = mapWithBrowserField(entry, browserField) || entry;
  36066. }
  36067. const entryPointPath = path__default.join(dir, entry);
  36068. const resolvedEntryPoint = tryFsResolve(entryPointPath, options);
  36069. if (resolvedEntryPoint) {
  36070. isDebug$4 &&
  36071. debug$a(`[package entry] ${colors$1.cyan(id)} -> ${colors$1.dim(resolvedEntryPoint)}`);
  36072. setResolvedCache('.', resolvedEntryPoint, targetWeb);
  36073. return resolvedEntryPoint;
  36074. }
  36075. }
  36076. packageEntryFailure(id);
  36077. }
  36078. catch (e) {
  36079. packageEntryFailure(id, e.message);
  36080. }
  36081. }
  36082. function packageEntryFailure(id, details) {
  36083. throw new Error(`Failed to resolve entry for package "${id}". ` +
  36084. `The package may have incorrect main/module/exports specified in its package.json` +
  36085. (details ? ': ' + details : '.'));
  36086. }
  36087. function resolveExports(pkg, key, options, targetWeb) {
  36088. const conditions = [options.isProduction ? 'production' : 'development'];
  36089. if (!options.isRequire) {
  36090. conditions.push('module');
  36091. }
  36092. if (options.conditions) {
  36093. conditions.push(...options.conditions);
  36094. }
  36095. return resolve(pkg, key, {
  36096. browser: targetWeb,
  36097. require: options.isRequire,
  36098. conditions
  36099. });
  36100. }
  36101. function resolveDeepImport(id, { webResolvedImports, setResolvedCache, getResolvedCache, dir, data }, targetWeb, options) {
  36102. const cache = getResolvedCache(id, targetWeb);
  36103. if (cache) {
  36104. return cache;
  36105. }
  36106. let relativeId = id;
  36107. const { exports: exportsField, browser: browserField } = data;
  36108. // map relative based on exports data
  36109. if (exportsField) {
  36110. if (isObject$1(exportsField) && !Array.isArray(exportsField)) {
  36111. // resolve without postfix (see #7098)
  36112. const { file, postfix } = splitFileAndPostfix(relativeId);
  36113. const exportsId = resolveExports(data, file, options, targetWeb);
  36114. if (exportsId !== undefined) {
  36115. relativeId = exportsId + postfix;
  36116. }
  36117. else {
  36118. relativeId = undefined;
  36119. }
  36120. }
  36121. else {
  36122. // not exposed
  36123. relativeId = undefined;
  36124. }
  36125. if (!relativeId) {
  36126. throw new Error(`Package subpath '${relativeId}' is not defined by "exports" in ` +
  36127. `${path__default.join(dir, 'package.json')}.`);
  36128. }
  36129. }
  36130. else if (targetWeb && isObject$1(browserField)) {
  36131. // resolve without postfix (see #7098)
  36132. const { file, postfix } = splitFileAndPostfix(relativeId);
  36133. const mapped = mapWithBrowserField(file, browserField);
  36134. if (mapped) {
  36135. relativeId = mapped + postfix;
  36136. }
  36137. else if (mapped === false) {
  36138. return (webResolvedImports[id] = browserExternalId);
  36139. }
  36140. }
  36141. if (relativeId) {
  36142. const resolved = tryFsResolve(path__default.join(dir, relativeId), options, !exportsField, // try index only if no exports field
  36143. targetWeb);
  36144. if (resolved) {
  36145. isDebug$4 &&
  36146. debug$a(`[node/deep-import] ${colors$1.cyan(id)} -> ${colors$1.dim(resolved)}`);
  36147. setResolvedCache(id, resolved, targetWeb);
  36148. return resolved;
  36149. }
  36150. }
  36151. }
  36152. function tryResolveBrowserMapping(id, importer, options, isFilePath) {
  36153. let res;
  36154. const pkg = importer && idToPkgMap.get(importer);
  36155. if (pkg && isObject$1(pkg.data.browser)) {
  36156. const mapId = isFilePath ? './' + slash(path__default.relative(pkg.dir, id)) : id;
  36157. const browserMappedPath = mapWithBrowserField(mapId, pkg.data.browser);
  36158. if (browserMappedPath) {
  36159. const fsPath = path__default.join(pkg.dir, browserMappedPath);
  36160. if ((res = tryFsResolve(fsPath, options))) {
  36161. isDebug$4 &&
  36162. debug$a(`[browser mapped] ${colors$1.cyan(id)} -> ${colors$1.dim(res)}`);
  36163. idToPkgMap.set(res, pkg);
  36164. return {
  36165. id: res,
  36166. moduleSideEffects: pkg.hasSideEffects(res)
  36167. };
  36168. }
  36169. }
  36170. else if (browserMappedPath === false) {
  36171. return browserExternalId;
  36172. }
  36173. }
  36174. }
  36175. /**
  36176. * given a relative path in pkg dir,
  36177. * return a relative path in pkg dir,
  36178. * mapped with the "map" object
  36179. *
  36180. * - Returning `undefined` means there is no browser mapping for this id
  36181. * - Returning `false` means this id is explicitly externalized for browser
  36182. */
  36183. function mapWithBrowserField(relativePathInPkgDir, map) {
  36184. const normalizedPath = path__default.posix.normalize(relativePathInPkgDir);
  36185. for (const key in map) {
  36186. const normalizedKey = path__default.posix.normalize(key);
  36187. if (normalizedPath === normalizedKey ||
  36188. equalWithoutSuffix(normalizedPath, normalizedKey, '.js') ||
  36189. equalWithoutSuffix(normalizedPath, normalizedKey, '/index.js')) {
  36190. return map[key];
  36191. }
  36192. }
  36193. }
  36194. function equalWithoutSuffix(path, key, suffix) {
  36195. return key.endsWith(suffix) && key.slice(0, -suffix.length) === path;
  36196. }
  36197. function getRealPath(resolved, preserveSymlinks) {
  36198. resolved = ensureVolumeInPath(resolved);
  36199. if (!preserveSymlinks && browserExternalId !== resolved) {
  36200. resolved = fs__default.realpathSync(resolved);
  36201. }
  36202. return normalizePath$3(resolved);
  36203. }
  36204. const debug$9 = createDebugger('vite:ssr-external');
  36205. /**
  36206. * Converts "parent > child" syntax to just "child"
  36207. */
  36208. function stripNesting(packages) {
  36209. return packages.map((s) => {
  36210. const arr = s.split('>');
  36211. return arr[arr.length - 1].trim();
  36212. });
  36213. }
  36214. /**
  36215. * Heuristics for determining whether a dependency should be externalized for
  36216. * server-side rendering.
  36217. */
  36218. function resolveSSRExternal(config, knownImports) {
  36219. var _a;
  36220. // strip nesting since knownImports may be passed in from optimizeDeps which
  36221. // supports a "parent > child" syntax
  36222. knownImports = stripNesting(knownImports);
  36223. const ssrConfig = config.ssr;
  36224. if ((ssrConfig === null || ssrConfig === void 0 ? void 0 : ssrConfig.noExternal) === true) {
  36225. return [];
  36226. }
  36227. const ssrExternals = new Set();
  36228. const seen = new Set();
  36229. (_a = ssrConfig === null || ssrConfig === void 0 ? void 0 : ssrConfig.external) === null || _a === void 0 ? void 0 : _a.forEach((id) => {
  36230. ssrExternals.add(id);
  36231. seen.add(id);
  36232. });
  36233. collectExternals(config.root, config.resolve.preserveSymlinks, ssrExternals, seen, config.logger);
  36234. const importedDeps = knownImports.map(getNpmPackageName).filter(isDefined);
  36235. for (const dep of importedDeps) {
  36236. // Assume external if not yet seen
  36237. // At this point, the project root and any linked packages have had their dependencies checked,
  36238. // so we can safely mark any knownImports not yet seen as external. They are guaranteed to be
  36239. // dependencies of packages in node_modules.
  36240. if (!seen.has(dep)) {
  36241. ssrExternals.add(dep);
  36242. }
  36243. }
  36244. // ensure `vite/dynamic-import-polyfill` is bundled (issue #1865)
  36245. ssrExternals.delete('vite');
  36246. let externals = [...ssrExternals];
  36247. if (ssrConfig === null || ssrConfig === void 0 ? void 0 : ssrConfig.noExternal) {
  36248. externals = externals.filter(createFilter$1(undefined, ssrConfig.noExternal, { resolve: false }));
  36249. }
  36250. return externals;
  36251. }
  36252. const CJS_CONTENT_RE = /\bmodule\.exports\b|\bexports[.\[]|\brequire\s*\(|\bObject\.(defineProperty|defineProperties|assign)\s*\(\s*exports\b/;
  36253. // do we need to do this ahead of time or could we do it lazily?
  36254. function collectExternals(root, preserveSymlinks, ssrExternals, seen, logger) {
  36255. var _a;
  36256. const rootPkgContent = lookupFile(root, ['package.json']);
  36257. if (!rootPkgContent) {
  36258. return;
  36259. }
  36260. const rootPkg = JSON.parse(rootPkgContent);
  36261. const deps = {
  36262. ...rootPkg.devDependencies,
  36263. ...rootPkg.dependencies
  36264. };
  36265. const resolveOptions = {
  36266. root,
  36267. preserveSymlinks,
  36268. isProduction: false,
  36269. isBuild: true
  36270. };
  36271. const depsToTrace = new Set();
  36272. for (const id in deps) {
  36273. if (seen.has(id))
  36274. continue;
  36275. seen.add(id);
  36276. let esmEntry;
  36277. let requireEntry;
  36278. try {
  36279. esmEntry = (_a = tryNodeResolve(id, undefined, resolveOptions, true, // we set `targetWeb` to `true` to get the ESM entry
  36280. undefined, true)) === null || _a === void 0 ? void 0 : _a.id;
  36281. // normalizePath required for windows. tryNodeResolve uses normalizePath
  36282. // which returns with '/', require.resolve returns with '\\'
  36283. requireEntry = normalizePath$3(require.resolve(id, { paths: [root] }));
  36284. }
  36285. catch (e) {
  36286. try {
  36287. // no main entry, but deep imports may be allowed
  36288. const pkgPath = resolveFrom(`${id}/package.json`, root);
  36289. if (pkgPath.includes('node_modules')) {
  36290. ssrExternals.add(id);
  36291. }
  36292. else {
  36293. depsToTrace.add(path__default.dirname(pkgPath));
  36294. }
  36295. continue;
  36296. }
  36297. catch { }
  36298. // resolve failed, assume include
  36299. debug$9(`Failed to resolve entries for package "${id}"\n`, e);
  36300. continue;
  36301. }
  36302. // no esm entry but has require entry
  36303. if (!esmEntry) {
  36304. ssrExternals.add(id);
  36305. }
  36306. // trace the dependencies of linked packages
  36307. else if (!esmEntry.includes('node_modules')) {
  36308. const pkgPath = resolveFrom(`${id}/package.json`, root);
  36309. depsToTrace.add(path__default.dirname(pkgPath));
  36310. }
  36311. // has separate esm/require entry, assume require entry is cjs
  36312. else if (esmEntry !== requireEntry) {
  36313. ssrExternals.add(id);
  36314. }
  36315. // if we're externalizing ESM and CJS should basically just always do it?
  36316. // or are there others like SystemJS / AMD that we'd need to handle?
  36317. // for now, we'll just leave this as is
  36318. else if (/\.m?js$/.test(esmEntry)) {
  36319. const pkgPath = resolveFrom(`${id}/package.json`, root);
  36320. const pkgContent = fs__default.readFileSync(pkgPath, 'utf-8');
  36321. if (!pkgContent) {
  36322. continue;
  36323. }
  36324. const pkg = JSON.parse(pkgContent);
  36325. if (pkg.type === 'module' || esmEntry.endsWith('.mjs')) {
  36326. ssrExternals.add(id);
  36327. continue;
  36328. }
  36329. // check if the entry is cjs
  36330. const content = fs__default.readFileSync(esmEntry, 'utf-8');
  36331. if (CJS_CONTENT_RE.test(content)) {
  36332. ssrExternals.add(id);
  36333. continue;
  36334. }
  36335. logger.warn(`${id} doesn't appear to be written in CJS, but also doesn't appear to be a valid ES module (i.e. it doesn't have "type": "module" or an .mjs extension for the entry point). Please contact the package author to fix.`);
  36336. }
  36337. }
  36338. for (const depRoot of depsToTrace) {
  36339. collectExternals(depRoot, preserveSymlinks, ssrExternals, seen, logger);
  36340. }
  36341. }
  36342. function shouldExternalizeForSSR(id, externals) {
  36343. const should = externals.some((e) => {
  36344. if (id === e) {
  36345. return true;
  36346. }
  36347. // deep imports, check ext before externalizing - only externalize
  36348. // extension-less imports and explicit .js imports
  36349. if (id.startsWith(e + '/') && (!path__default.extname(id) || id.endsWith('.js'))) {
  36350. return true;
  36351. }
  36352. });
  36353. return should;
  36354. }
  36355. function getNpmPackageName(importPath) {
  36356. const parts = importPath.split('/');
  36357. if (parts[0].startsWith('@')) {
  36358. if (!parts[1])
  36359. return null;
  36360. return `${parts[0]}/${parts[1]}`;
  36361. }
  36362. else {
  36363. return parts[0];
  36364. }
  36365. }
  36366. function ssrManifestPlugin(config) {
  36367. // module id => preload assets mapping
  36368. const ssrManifest = {};
  36369. const base = config.base;
  36370. return {
  36371. name: 'vite:ssr-manifest',
  36372. generateBundle(_options, bundle) {
  36373. var _a;
  36374. for (const file in bundle) {
  36375. const chunk = bundle[file];
  36376. if (chunk.type === 'chunk') {
  36377. for (const id in chunk.modules) {
  36378. const normalizedId = normalizePath$3(path$r.relative(config.root, id));
  36379. const mappedChunks = (_a = ssrManifest[normalizedId]) !== null && _a !== void 0 ? _a : (ssrManifest[normalizedId] = []);
  36380. if (!chunk.isEntry) {
  36381. mappedChunks.push(base + chunk.fileName);
  36382. // <link> tags for entry chunks are already generated in static HTML,
  36383. // so we only need to record info for non-entry chunks.
  36384. chunk.viteMetadata.importedCss.forEach((file) => {
  36385. mappedChunks.push(base + file);
  36386. });
  36387. }
  36388. chunk.viteMetadata.importedAssets.forEach((file) => {
  36389. mappedChunks.push(base + file);
  36390. });
  36391. }
  36392. if (chunk.code.includes(preloadMethod)) {
  36393. // generate css deps map
  36394. const code = chunk.code;
  36395. let imports;
  36396. try {
  36397. imports = parse$e(code)[0].filter((i) => i.n && i.d > -1);
  36398. }
  36399. catch (e) {
  36400. this.error(e, e.idx);
  36401. }
  36402. if (imports.length) {
  36403. for (let index = 0; index < imports.length; index++) {
  36404. const { s: start, e: end, n: name } = imports[index];
  36405. // check the chunk being imported
  36406. const url = code.slice(start, end);
  36407. const deps = [];
  36408. const ownerFilename = chunk.fileName;
  36409. // literal import - trace direct imports and add to deps
  36410. const analyzed = new Set();
  36411. const addDeps = (filename) => {
  36412. if (filename === ownerFilename)
  36413. return;
  36414. if (analyzed.has(filename))
  36415. return;
  36416. analyzed.add(filename);
  36417. const chunk = bundle[filename];
  36418. if (chunk) {
  36419. chunk.viteMetadata.importedCss.forEach((file) => {
  36420. deps.push(`/${file}`);
  36421. });
  36422. chunk.imports.forEach(addDeps);
  36423. }
  36424. };
  36425. const normalizedFile = normalizePath$3(path$r.join(path$r.dirname(chunk.fileName), url.slice(1, -1)));
  36426. addDeps(normalizedFile);
  36427. ssrManifest[path$r.basename(name)] = deps;
  36428. }
  36429. }
  36430. }
  36431. }
  36432. }
  36433. this.emitFile({
  36434. fileName: typeof config.build.ssrManifest === 'string'
  36435. ? config.build.ssrManifest
  36436. : 'ssr-manifest.json',
  36437. type: 'asset',
  36438. source: JSON.stringify(ssrManifest, null, 2)
  36439. });
  36440. }
  36441. };
  36442. }
  36443. /**
  36444. * Convert `new URL('./foo.png', import.meta.url)` to its resolved built URL
  36445. *
  36446. * Supports template string with dynamic segments:
  36447. * ```
  36448. * new URL(`./dir/${name}.png`, import.meta.url)
  36449. * // transformed to
  36450. * import.meta.globEager('./dir/**.png')[`./dir/${name}.png`].default
  36451. * ```
  36452. */
  36453. function assetImportMetaUrlPlugin(config) {
  36454. return {
  36455. name: 'vite:asset-import-meta-url',
  36456. async transform(code, id, options) {
  36457. if (!(options === null || options === void 0 ? void 0 : options.ssr) &&
  36458. code.includes('new URL') &&
  36459. code.includes(`import.meta.url`)) {
  36460. let s;
  36461. const assetImportMetaUrlRE = /\bnew\s+URL\s*\(\s*('[^']+'|"[^"]+"|`[^`]+`)\s*,\s*import\.meta\.url\s*,?\s*\)/g;
  36462. const cleanString = stripLiteral(code);
  36463. let match;
  36464. while ((match = assetImportMetaUrlRE.exec(cleanString))) {
  36465. const { 0: exp, 1: emptyUrl, index } = match;
  36466. const urlStart = cleanString.indexOf(emptyUrl, index);
  36467. const urlEnd = urlStart + emptyUrl.length;
  36468. const rawUrl = code.slice(urlStart, urlEnd);
  36469. if (!s)
  36470. s = new MagicString(code);
  36471. // potential dynamic template string
  36472. if (rawUrl[0] === '`' && /\$\{/.test(rawUrl)) {
  36473. const ast = this.parse(rawUrl);
  36474. const templateLiteral = ast.body[0].expression;
  36475. if (templateLiteral.expressions.length) {
  36476. const pattern = buildGlobPattern(templateLiteral);
  36477. // Note: native import.meta.url is not supported in the baseline
  36478. // target so we use the global location here. It can be
  36479. // window.location or self.location in case it is used in a Web Worker.
  36480. // @see https://developer.mozilla.org/en-US/docs/Web/API/Window/self
  36481. s.overwrite(index, index + exp.length, `new URL(import.meta.globEagerDefault(${JSON.stringify(pattern)})[${rawUrl}], self.location)`, { contentOnly: true });
  36482. continue;
  36483. }
  36484. }
  36485. const url = rawUrl.slice(1, -1);
  36486. const file = path__default.resolve(path__default.dirname(id), url);
  36487. // Get final asset URL. Catch error if the file does not exist,
  36488. // in which we can resort to the initial URL and let it resolve in runtime
  36489. const builtUrl = await fileToUrl(file, config, this).catch(() => {
  36490. const rawExp = code.slice(index, index + exp.length);
  36491. config.logger.warnOnce(`\n${rawExp} doesn't exist at build time, it will remain unchanged to be resolved at runtime`);
  36492. return url;
  36493. });
  36494. s.overwrite(index, index + exp.length, `new URL(${JSON.stringify(builtUrl)}, self.location)`, { contentOnly: true });
  36495. }
  36496. if (s) {
  36497. return {
  36498. code: s.toString(),
  36499. map: config.build.sourcemap ? s.generateMap({ hires: true }) : null
  36500. };
  36501. }
  36502. }
  36503. return null;
  36504. }
  36505. };
  36506. }
  36507. function buildGlobPattern(ast) {
  36508. let pattern = '';
  36509. let lastElementIndex = -1;
  36510. for (const exp of ast.expressions) {
  36511. for (let i = lastElementIndex + 1; i < ast.quasis.length; i++) {
  36512. const el = ast.quasis[i];
  36513. if (el.end < exp.start) {
  36514. pattern += el.value.raw;
  36515. lastElementIndex = i;
  36516. }
  36517. }
  36518. pattern += '**';
  36519. }
  36520. for (let i = lastElementIndex + 1; i < ast.quasis.length; i++) {
  36521. pattern += ast.quasis[i].value.raw;
  36522. }
  36523. return pattern;
  36524. }
  36525. /**
  36526. * A plugin to provide build load fallback for arbitrary request with queries.
  36527. */
  36528. function loadFallbackPlugin() {
  36529. return {
  36530. name: 'vite:load-fallback',
  36531. async load(id) {
  36532. try {
  36533. // if we don't add `await` here, we couldn't catch the error in readFile
  36534. return await fs$n.promises.readFile(cleanUrl(id), 'utf-8');
  36535. }
  36536. catch (e) {
  36537. return fs$n.promises.readFile(id, 'utf-8');
  36538. }
  36539. }
  36540. };
  36541. }
  36542. /**
  36543. * plugin to ensure rollup can watch correctly.
  36544. */
  36545. function ensureWatchPlugin() {
  36546. return {
  36547. name: 'vite:ensure-watch',
  36548. load(id) {
  36549. if (queryRE.test(id)) {
  36550. this.addWatchFile(cleanUrl(id));
  36551. }
  36552. return null;
  36553. }
  36554. };
  36555. }
  36556. function resolveBuildOptions(raw) {
  36557. const resolved = {
  36558. target: 'modules',
  36559. polyfillModulePreload: true,
  36560. outDir: 'dist',
  36561. assetsDir: 'assets',
  36562. assetsInlineLimit: 4096,
  36563. cssCodeSplit: !(raw === null || raw === void 0 ? void 0 : raw.lib),
  36564. cssTarget: false,
  36565. sourcemap: false,
  36566. rollupOptions: {},
  36567. minify: (raw === null || raw === void 0 ? void 0 : raw.ssr) ? false : 'esbuild',
  36568. terserOptions: {},
  36569. write: true,
  36570. emptyOutDir: null,
  36571. manifest: false,
  36572. lib: false,
  36573. ssr: false,
  36574. ssrManifest: false,
  36575. reportCompressedSize: true,
  36576. // brotliSize: true,
  36577. chunkSizeWarningLimit: 500,
  36578. watch: null,
  36579. ...raw,
  36580. commonjsOptions: {
  36581. include: [/node_modules/],
  36582. extensions: ['.js', '.cjs'],
  36583. ...raw === null || raw === void 0 ? void 0 : raw.commonjsOptions
  36584. },
  36585. dynamicImportVarsOptions: {
  36586. warnOnError: true,
  36587. exclude: [/node_modules/],
  36588. ...raw === null || raw === void 0 ? void 0 : raw.dynamicImportVarsOptions
  36589. }
  36590. };
  36591. // handle special build targets
  36592. if (resolved.target === 'modules') {
  36593. // Support browserslist
  36594. // "defaults and supports es6-module and supports es6-module-dynamic-import",
  36595. resolved.target = [
  36596. 'es2019',
  36597. 'edge88',
  36598. 'firefox78',
  36599. 'chrome87',
  36600. 'safari13.1'
  36601. ];
  36602. }
  36603. else if (resolved.target === 'esnext' && resolved.minify === 'terser') {
  36604. // esnext + terser: limit to es2019 so it can be minified by terser
  36605. resolved.target = 'es2019';
  36606. }
  36607. if (!resolved.cssTarget) {
  36608. resolved.cssTarget = resolved.target;
  36609. }
  36610. // normalize false string into actual false
  36611. if (resolved.minify === 'false') {
  36612. resolved.minify = false;
  36613. }
  36614. if (resolved.minify === true) {
  36615. resolved.minify = 'esbuild';
  36616. }
  36617. return resolved;
  36618. }
  36619. function resolveBuildPlugins(config) {
  36620. const options = config.build;
  36621. return {
  36622. pre: [
  36623. ...(options.watch ? [ensureWatchPlugin()] : []),
  36624. watchPackageDataPlugin(config),
  36625. commonjs(options.commonjsOptions),
  36626. dataURIPlugin(),
  36627. dynamicImportVariables(options.dynamicImportVarsOptions),
  36628. assetImportMetaUrlPlugin(config),
  36629. ...(options.rollupOptions.plugins
  36630. ? options.rollupOptions.plugins.filter(Boolean)
  36631. : [])
  36632. ],
  36633. post: [
  36634. buildImportAnalysisPlugin(config),
  36635. ...(config.esbuild !== false ? [buildEsbuildPlugin(config)] : []),
  36636. ...(options.minify ? [terserPlugin(config)] : []),
  36637. ...(options.manifest ? [manifestPlugin(config)] : []),
  36638. ...(options.ssrManifest ? [ssrManifestPlugin(config)] : []),
  36639. buildReporterPlugin(config),
  36640. loadFallbackPlugin()
  36641. ]
  36642. };
  36643. }
  36644. /**
  36645. * Track parallel build calls and only stop the esbuild service when all
  36646. * builds are done. (#1098)
  36647. */
  36648. let parallelCallCounts = 0;
  36649. // we use a separate counter to track since the call may error before the
  36650. // bundle is even pushed.
  36651. const parallelBuilds = [];
  36652. /**
  36653. * Bundles the app for production.
  36654. * Returns a Promise containing the build result.
  36655. */
  36656. async function build(inlineConfig = {}) {
  36657. parallelCallCounts++;
  36658. try {
  36659. return await doBuild(inlineConfig);
  36660. }
  36661. finally {
  36662. parallelCallCounts--;
  36663. if (parallelCallCounts <= 0) {
  36664. await Promise.all(parallelBuilds.map((bundle) => bundle.close()));
  36665. parallelBuilds.length = 0;
  36666. }
  36667. }
  36668. }
  36669. async function doBuild(inlineConfig = {}) {
  36670. var _a, _b, _c, _d;
  36671. const config = await resolveConfig(inlineConfig, 'build', 'production');
  36672. const options = config.build;
  36673. const ssr = !!options.ssr;
  36674. const libOptions = options.lib;
  36675. config.logger.info(colors$1.cyan(`vite v${require('vite/package.json').version} ${colors$1.green(`building ${ssr ? `SSR bundle ` : ``}for ${config.mode}...`)}`));
  36676. const resolve = (p) => path__default.resolve(config.root, p);
  36677. const input = libOptions
  36678. ? resolve(libOptions.entry)
  36679. : typeof options.ssr === 'string'
  36680. ? resolve(options.ssr)
  36681. : ((_a = options.rollupOptions) === null || _a === void 0 ? void 0 : _a.input) || resolve('index.html');
  36682. if (ssr && typeof input === 'string' && input.endsWith('.html')) {
  36683. throw new Error(`rollupOptions.input should not be an html file when building for SSR. ` +
  36684. `Please specify a dedicated SSR entry.`);
  36685. }
  36686. const outDir = resolve(options.outDir);
  36687. // inject ssr arg to plugin load/transform hooks
  36688. const plugins = (ssr ? config.plugins.map((p) => injectSsrFlagToHooks(p)) : config.plugins);
  36689. // inject ssrExternal if present
  36690. const userExternal = (_b = options.rollupOptions) === null || _b === void 0 ? void 0 : _b.external;
  36691. let external = userExternal;
  36692. if (ssr) {
  36693. // see if we have cached deps data available
  36694. let knownImports;
  36695. const dataPath = path__default.join(getDepsCacheDir(config), '_metadata.json');
  36696. try {
  36697. const data = JSON.parse(fs__default.readFileSync(dataPath, 'utf-8'));
  36698. knownImports = Object.keys(data.optimized);
  36699. }
  36700. catch (e) { }
  36701. if (!knownImports) {
  36702. // no dev deps optimization data, do a fresh scan
  36703. knownImports = await findKnownImports(config);
  36704. }
  36705. external = resolveExternal(resolveSSRExternal(config, knownImports), userExternal);
  36706. }
  36707. const rollup = require('rollup');
  36708. const rollupOptions = {
  36709. input,
  36710. context: 'globalThis',
  36711. preserveEntrySignatures: ssr
  36712. ? 'allow-extension'
  36713. : libOptions
  36714. ? 'strict'
  36715. : false,
  36716. ...options.rollupOptions,
  36717. plugins,
  36718. external,
  36719. onwarn(warning, warn) {
  36720. onRollupWarning(warning, warn, config);
  36721. }
  36722. };
  36723. const outputBuildError = (e) => {
  36724. let msg = colors$1.red((e.plugin ? `[${e.plugin}] ` : '') + e.message);
  36725. if (e.id) {
  36726. msg += `\nfile: ${colors$1.cyan(e.id + (e.loc ? `:${e.loc.line}:${e.loc.column}` : ''))}`;
  36727. }
  36728. if (e.frame) {
  36729. msg += `\n` + colors$1.yellow(e.frame);
  36730. }
  36731. config.logger.error(msg, { error: e });
  36732. };
  36733. try {
  36734. const buildOutputOptions = (output = {}) => {
  36735. // @ts-ignore
  36736. if (output.output) {
  36737. config.logger.warn(`You've set "rollupOptions.output.output" in your config. ` +
  36738. `This is deprecated and will override all Vite.js default output options. ` +
  36739. `Please use "rollupOptions.output" instead.`);
  36740. }
  36741. return {
  36742. dir: outDir,
  36743. format: ssr ? 'cjs' : 'es',
  36744. exports: ssr ? 'named' : 'auto',
  36745. sourcemap: options.sourcemap,
  36746. name: libOptions ? libOptions.name : undefined,
  36747. entryFileNames: ssr
  36748. ? `[name].js`
  36749. : libOptions
  36750. ? resolveLibFilename(libOptions, output.format || 'es', config.root)
  36751. : path__default.posix.join(options.assetsDir, `[name].[hash].js`),
  36752. chunkFileNames: libOptions
  36753. ? `[name].js`
  36754. : path__default.posix.join(options.assetsDir, `[name].[hash].js`),
  36755. assetFileNames: libOptions
  36756. ? `[name].[ext]`
  36757. : path__default.posix.join(options.assetsDir, `[name].[hash].[ext]`),
  36758. // #764 add `Symbol.toStringTag` when build es module into cjs chunk
  36759. // #1048 add `Symbol.toStringTag` for module default export
  36760. namespaceToStringTag: true,
  36761. inlineDynamicImports: ssr && typeof input === 'string',
  36762. ...output
  36763. };
  36764. };
  36765. // resolve lib mode outputs
  36766. const outputs = resolveBuildOutputs((_c = options.rollupOptions) === null || _c === void 0 ? void 0 : _c.output, libOptions, config.logger);
  36767. // watch file changes with rollup
  36768. if (config.build.watch) {
  36769. config.logger.info(colors$1.cyan(`\nwatching for file changes...`));
  36770. const output = [];
  36771. if (Array.isArray(outputs)) {
  36772. for (const resolvedOutput of outputs) {
  36773. output.push(buildOutputOptions(resolvedOutput));
  36774. }
  36775. }
  36776. else {
  36777. output.push(buildOutputOptions(outputs));
  36778. }
  36779. const watcherOptions = config.build.watch;
  36780. const watcher = rollup.watch({
  36781. ...rollupOptions,
  36782. output,
  36783. watch: {
  36784. ...watcherOptions,
  36785. chokidar: {
  36786. ignoreInitial: true,
  36787. ignorePermissionErrors: true,
  36788. ...watcherOptions.chokidar,
  36789. ignored: [
  36790. '**/node_modules/**',
  36791. '**/.git/**',
  36792. ...(((_d = watcherOptions === null || watcherOptions === void 0 ? void 0 : watcherOptions.chokidar) === null || _d === void 0 ? void 0 : _d.ignored) || [])
  36793. ]
  36794. }
  36795. }
  36796. });
  36797. watcher.on('event', (event) => {
  36798. if (event.code === 'BUNDLE_START') {
  36799. config.logger.info(colors$1.cyan(`\nbuild started...`));
  36800. if (options.write) {
  36801. prepareOutDir(outDir, options.emptyOutDir, config);
  36802. }
  36803. }
  36804. else if (event.code === 'BUNDLE_END') {
  36805. event.result.close();
  36806. config.logger.info(colors$1.cyan(`built in ${event.duration}ms.`));
  36807. }
  36808. else if (event.code === 'ERROR') {
  36809. outputBuildError(event.error);
  36810. }
  36811. });
  36812. // stop watching
  36813. watcher.close();
  36814. return watcher;
  36815. }
  36816. // write or generate files with rollup
  36817. const bundle = await rollup.rollup(rollupOptions);
  36818. parallelBuilds.push(bundle);
  36819. const generate = (output = {}) => {
  36820. return bundle[options.write ? 'write' : 'generate'](buildOutputOptions(output));
  36821. };
  36822. if (options.write) {
  36823. prepareOutDir(outDir, options.emptyOutDir, config);
  36824. }
  36825. if (Array.isArray(outputs)) {
  36826. const res = [];
  36827. for (const output of outputs) {
  36828. res.push(await generate(output));
  36829. }
  36830. return res;
  36831. }
  36832. else {
  36833. return await generate(outputs);
  36834. }
  36835. }
  36836. catch (e) {
  36837. outputBuildError(e);
  36838. throw e;
  36839. }
  36840. }
  36841. function prepareOutDir(outDir, emptyOutDir, config) {
  36842. if (fs__default.existsSync(outDir)) {
  36843. if (emptyOutDir == null &&
  36844. !normalizePath$3(outDir).startsWith(config.root + '/')) {
  36845. // warn if outDir is outside of root
  36846. config.logger.warn(colors$1.yellow(`\n${colors$1.bold(`(!)`)} outDir ${colors$1.white(colors$1.dim(outDir))} is not inside project root and will not be emptied.\n` +
  36847. `Use --emptyOutDir to override.\n`));
  36848. }
  36849. else if (emptyOutDir !== false) {
  36850. emptyDir(outDir, ['.git']);
  36851. }
  36852. }
  36853. if (config.publicDir && fs__default.existsSync(config.publicDir)) {
  36854. copyDir(config.publicDir, outDir);
  36855. }
  36856. }
  36857. function getPkgName(root) {
  36858. const { name } = JSON.parse(lookupFile(root, ['package.json']) || `{}`);
  36859. return (name === null || name === void 0 ? void 0 : name.startsWith('@')) ? name.split('/')[1] : name;
  36860. }
  36861. function resolveLibFilename(libOptions, format, root) {
  36862. if (typeof libOptions.fileName === 'function') {
  36863. return libOptions.fileName(format);
  36864. }
  36865. const name = libOptions.fileName || getPkgName(root);
  36866. if (!name)
  36867. throw new Error('Name in package.json is required if option "build.lib.fileName" is not provided.');
  36868. return `${name}.${format}.js`;
  36869. }
  36870. function resolveBuildOutputs(outputs, libOptions, logger) {
  36871. if (libOptions) {
  36872. const formats = libOptions.formats || ['es', 'umd'];
  36873. if ((formats.includes('umd') || formats.includes('iife')) &&
  36874. !libOptions.name) {
  36875. throw new Error(`Option "build.lib.name" is required when output formats ` +
  36876. `include "umd" or "iife".`);
  36877. }
  36878. if (!outputs) {
  36879. return formats.map((format) => ({ format }));
  36880. }
  36881. else if (!Array.isArray(outputs)) {
  36882. return formats.map((format) => ({ ...outputs, format }));
  36883. }
  36884. else if (libOptions.formats) {
  36885. // user explicitly specifying own output array
  36886. logger.warn(colors$1.yellow(`"build.lib.formats" will be ignored because ` +
  36887. `"build.rollupOptions.output" is already an array format`));
  36888. }
  36889. }
  36890. return outputs;
  36891. }
  36892. const warningIgnoreList = [`CIRCULAR_DEPENDENCY`, `THIS_IS_UNDEFINED`];
  36893. const dynamicImportWarningIgnoreList = [
  36894. `Unsupported expression`,
  36895. `statically analyzed`
  36896. ];
  36897. function onRollupWarning(warning, warn, config) {
  36898. var _a;
  36899. if (warning.code === 'UNRESOLVED_IMPORT') {
  36900. const id = warning.source;
  36901. const importer = warning.importer;
  36902. // throw unless it's commonjs external...
  36903. if (!importer || !/\?commonjs-external$/.test(importer)) {
  36904. throw new Error(`[vite]: Rollup failed to resolve import "${id}" from "${importer}".\n` +
  36905. `This is most likely unintended because it can break your application at runtime.\n` +
  36906. `If you do want to externalize this module explicitly add it to\n` +
  36907. `\`build.rollupOptions.external\``);
  36908. }
  36909. }
  36910. if (warning.plugin === 'rollup-plugin-dynamic-import-variables' &&
  36911. dynamicImportWarningIgnoreList.some((msg) => warning.message.includes(msg))) {
  36912. return;
  36913. }
  36914. if (!warningIgnoreList.includes(warning.code)) {
  36915. const userOnWarn = (_a = config.build.rollupOptions) === null || _a === void 0 ? void 0 : _a.onwarn;
  36916. if (userOnWarn) {
  36917. userOnWarn(warning, warn);
  36918. }
  36919. else if (warning.code === 'PLUGIN_WARNING') {
  36920. config.logger.warn(`${colors$1.bold(colors$1.yellow(`[plugin:${warning.plugin}]`))} ${colors$1.yellow(warning.message)}`);
  36921. }
  36922. else {
  36923. warn(warning);
  36924. }
  36925. }
  36926. }
  36927. function resolveExternal(ssrExternals, user) {
  36928. return (id, parentId, isResolved) => {
  36929. if (shouldExternalizeForSSR(id, ssrExternals)) {
  36930. return true;
  36931. }
  36932. if (user) {
  36933. if (typeof user === 'function') {
  36934. return user(id, parentId, isResolved);
  36935. }
  36936. else if (Array.isArray(user)) {
  36937. return user.some((test) => isExternal(id, test));
  36938. }
  36939. else {
  36940. return isExternal(id, user);
  36941. }
  36942. }
  36943. };
  36944. }
  36945. function isExternal(id, test) {
  36946. if (typeof test === 'string') {
  36947. return id === test;
  36948. }
  36949. else {
  36950. return test.test(id);
  36951. }
  36952. }
  36953. function injectSsrFlagToHooks(plugin) {
  36954. const { resolveId, load, transform } = plugin;
  36955. return {
  36956. ...plugin,
  36957. resolveId: wrapSsrResolveId(resolveId),
  36958. load: wrapSsrLoad(load),
  36959. transform: wrapSsrTransform(transform)
  36960. };
  36961. }
  36962. function wrapSsrResolveId(fn) {
  36963. if (!fn)
  36964. return;
  36965. return function (id, importer, options) {
  36966. return fn.call(this, id, importer, injectSsrFlag(options));
  36967. };
  36968. }
  36969. function wrapSsrLoad(fn) {
  36970. if (!fn)
  36971. return;
  36972. return function (id, ...args) {
  36973. // @ts-expect-error: Receiving options param to be future-proof if Rollup adds it
  36974. return fn.call(this, id, injectSsrFlag(args[0]));
  36975. };
  36976. }
  36977. function wrapSsrTransform(fn) {
  36978. if (!fn)
  36979. return;
  36980. return function (code, importer, ...args) {
  36981. // @ts-expect-error: Receiving options param to be future-proof if Rollup adds it
  36982. return fn.call(this, code, importer, injectSsrFlag(args[0]));
  36983. };
  36984. }
  36985. function injectSsrFlag(options) {
  36986. return { ...(options !== null && options !== void 0 ? options : {}), ssr: true };
  36987. }
  36988. var build$1 = {
  36989. __proto__: null,
  36990. resolveBuildOptions: resolveBuildOptions,
  36991. resolveBuildPlugins: resolveBuildPlugins,
  36992. build: build,
  36993. resolveLibFilename: resolveLibFilename,
  36994. onRollupWarning: onRollupWarning
  36995. };
  36996. var src = {exports: {}};
  36997. var browser = {exports: {}};
  36998. var debug$8 = {exports: {}};
  36999. /**
  37000. * Helpers.
  37001. */
  37002. var s = 1000;
  37003. var m = s * 60;
  37004. var h = m * 60;
  37005. var d = h * 24;
  37006. var y = d * 365.25;
  37007. /**
  37008. * Parse or format the given `val`.
  37009. *
  37010. * Options:
  37011. *
  37012. * - `long` verbose formatting [false]
  37013. *
  37014. * @param {String|Number} val
  37015. * @param {Object} [options]
  37016. * @throws {Error} throw an error if val is not a non-empty string or a number
  37017. * @return {String|Number}
  37018. * @api public
  37019. */
  37020. var ms = function(val, options) {
  37021. options = options || {};
  37022. var type = typeof val;
  37023. if (type === 'string' && val.length > 0) {
  37024. return parse$9(val);
  37025. } else if (type === 'number' && isNaN(val) === false) {
  37026. return options.long ? fmtLong(val) : fmtShort(val);
  37027. }
  37028. throw new Error(
  37029. 'val is not a non-empty string or a valid number. val=' +
  37030. JSON.stringify(val)
  37031. );
  37032. };
  37033. /**
  37034. * Parse the given `str` and return milliseconds.
  37035. *
  37036. * @param {String} str
  37037. * @return {Number}
  37038. * @api private
  37039. */
  37040. function parse$9(str) {
  37041. str = String(str);
  37042. if (str.length > 100) {
  37043. return;
  37044. }
  37045. var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(
  37046. str
  37047. );
  37048. if (!match) {
  37049. return;
  37050. }
  37051. var n = parseFloat(match[1]);
  37052. var type = (match[2] || 'ms').toLowerCase();
  37053. switch (type) {
  37054. case 'years':
  37055. case 'year':
  37056. case 'yrs':
  37057. case 'yr':
  37058. case 'y':
  37059. return n * y;
  37060. case 'days':
  37061. case 'day':
  37062. case 'd':
  37063. return n * d;
  37064. case 'hours':
  37065. case 'hour':
  37066. case 'hrs':
  37067. case 'hr':
  37068. case 'h':
  37069. return n * h;
  37070. case 'minutes':
  37071. case 'minute':
  37072. case 'mins':
  37073. case 'min':
  37074. case 'm':
  37075. return n * m;
  37076. case 'seconds':
  37077. case 'second':
  37078. case 'secs':
  37079. case 'sec':
  37080. case 's':
  37081. return n * s;
  37082. case 'milliseconds':
  37083. case 'millisecond':
  37084. case 'msecs':
  37085. case 'msec':
  37086. case 'ms':
  37087. return n;
  37088. default:
  37089. return undefined;
  37090. }
  37091. }
  37092. /**
  37093. * Short format for `ms`.
  37094. *
  37095. * @param {Number} ms
  37096. * @return {String}
  37097. * @api private
  37098. */
  37099. function fmtShort(ms) {
  37100. if (ms >= d) {
  37101. return Math.round(ms / d) + 'd';
  37102. }
  37103. if (ms >= h) {
  37104. return Math.round(ms / h) + 'h';
  37105. }
  37106. if (ms >= m) {
  37107. return Math.round(ms / m) + 'm';
  37108. }
  37109. if (ms >= s) {
  37110. return Math.round(ms / s) + 's';
  37111. }
  37112. return ms + 'ms';
  37113. }
  37114. /**
  37115. * Long format for `ms`.
  37116. *
  37117. * @param {Number} ms
  37118. * @return {String}
  37119. * @api private
  37120. */
  37121. function fmtLong(ms) {
  37122. return plural(ms, d, 'day') ||
  37123. plural(ms, h, 'hour') ||
  37124. plural(ms, m, 'minute') ||
  37125. plural(ms, s, 'second') ||
  37126. ms + ' ms';
  37127. }
  37128. /**
  37129. * Pluralization helper.
  37130. */
  37131. function plural(ms, n, name) {
  37132. if (ms < n) {
  37133. return;
  37134. }
  37135. if (ms < n * 1.5) {
  37136. return Math.floor(ms / n) + ' ' + name;
  37137. }
  37138. return Math.ceil(ms / n) + ' ' + name + 's';
  37139. }
  37140. (function (module, exports) {
  37141. /**
  37142. * This is the common logic for both the Node.js and web browser
  37143. * implementations of `debug()`.
  37144. *
  37145. * Expose `debug()` as the module.
  37146. */
  37147. exports = module.exports = createDebug.debug = createDebug['default'] = createDebug;
  37148. exports.coerce = coerce;
  37149. exports.disable = disable;
  37150. exports.enable = enable;
  37151. exports.enabled = enabled;
  37152. exports.humanize = ms;
  37153. /**
  37154. * The currently active debug mode names, and names to skip.
  37155. */
  37156. exports.names = [];
  37157. exports.skips = [];
  37158. /**
  37159. * Map of special "%n" handling functions, for the debug "format" argument.
  37160. *
  37161. * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
  37162. */
  37163. exports.formatters = {};
  37164. /**
  37165. * Previous log timestamp.
  37166. */
  37167. var prevTime;
  37168. /**
  37169. * Select a color.
  37170. * @param {String} namespace
  37171. * @return {Number}
  37172. * @api private
  37173. */
  37174. function selectColor(namespace) {
  37175. var hash = 0, i;
  37176. for (i in namespace) {
  37177. hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
  37178. hash |= 0; // Convert to 32bit integer
  37179. }
  37180. return exports.colors[Math.abs(hash) % exports.colors.length];
  37181. }
  37182. /**
  37183. * Create a debugger with the given `namespace`.
  37184. *
  37185. * @param {String} namespace
  37186. * @return {Function}
  37187. * @api public
  37188. */
  37189. function createDebug(namespace) {
  37190. function debug() {
  37191. // disabled?
  37192. if (!debug.enabled) return;
  37193. var self = debug;
  37194. // set `diff` timestamp
  37195. var curr = +new Date();
  37196. var ms = curr - (prevTime || curr);
  37197. self.diff = ms;
  37198. self.prev = prevTime;
  37199. self.curr = curr;
  37200. prevTime = curr;
  37201. // turn the `arguments` into a proper Array
  37202. var args = new Array(arguments.length);
  37203. for (var i = 0; i < args.length; i++) {
  37204. args[i] = arguments[i];
  37205. }
  37206. args[0] = exports.coerce(args[0]);
  37207. if ('string' !== typeof args[0]) {
  37208. // anything else let's inspect with %O
  37209. args.unshift('%O');
  37210. }
  37211. // apply any `formatters` transformations
  37212. var index = 0;
  37213. args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {
  37214. // if we encounter an escaped % then don't increase the array index
  37215. if (match === '%%') return match;
  37216. index++;
  37217. var formatter = exports.formatters[format];
  37218. if ('function' === typeof formatter) {
  37219. var val = args[index];
  37220. match = formatter.call(self, val);
  37221. // now we need to remove `args[index]` since it's inlined in the `format`
  37222. args.splice(index, 1);
  37223. index--;
  37224. }
  37225. return match;
  37226. });
  37227. // apply env-specific formatting (colors, etc.)
  37228. exports.formatArgs.call(self, args);
  37229. var logFn = debug.log || exports.log || console.log.bind(console);
  37230. logFn.apply(self, args);
  37231. }
  37232. debug.namespace = namespace;
  37233. debug.enabled = exports.enabled(namespace);
  37234. debug.useColors = exports.useColors();
  37235. debug.color = selectColor(namespace);
  37236. // env-specific initialization logic for debug instances
  37237. if ('function' === typeof exports.init) {
  37238. exports.init(debug);
  37239. }
  37240. return debug;
  37241. }
  37242. /**
  37243. * Enables a debug mode by namespaces. This can include modes
  37244. * separated by a colon and wildcards.
  37245. *
  37246. * @param {String} namespaces
  37247. * @api public
  37248. */
  37249. function enable(namespaces) {
  37250. exports.save(namespaces);
  37251. exports.names = [];
  37252. exports.skips = [];
  37253. var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
  37254. var len = split.length;
  37255. for (var i = 0; i < len; i++) {
  37256. if (!split[i]) continue; // ignore empty strings
  37257. namespaces = split[i].replace(/\*/g, '.*?');
  37258. if (namespaces[0] === '-') {
  37259. exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
  37260. } else {
  37261. exports.names.push(new RegExp('^' + namespaces + '$'));
  37262. }
  37263. }
  37264. }
  37265. /**
  37266. * Disable debug output.
  37267. *
  37268. * @api public
  37269. */
  37270. function disable() {
  37271. exports.enable('');
  37272. }
  37273. /**
  37274. * Returns true if the given mode name is enabled, false otherwise.
  37275. *
  37276. * @param {String} name
  37277. * @return {Boolean}
  37278. * @api public
  37279. */
  37280. function enabled(name) {
  37281. var i, len;
  37282. for (i = 0, len = exports.skips.length; i < len; i++) {
  37283. if (exports.skips[i].test(name)) {
  37284. return false;
  37285. }
  37286. }
  37287. for (i = 0, len = exports.names.length; i < len; i++) {
  37288. if (exports.names[i].test(name)) {
  37289. return true;
  37290. }
  37291. }
  37292. return false;
  37293. }
  37294. /**
  37295. * Coerce `val`.
  37296. *
  37297. * @param {Mixed} val
  37298. * @return {Mixed}
  37299. * @api private
  37300. */
  37301. function coerce(val) {
  37302. if (val instanceof Error) return val.stack || val.message;
  37303. return val;
  37304. }
  37305. }(debug$8, debug$8.exports));
  37306. /**
  37307. * This is the web browser implementation of `debug()`.
  37308. *
  37309. * Expose `debug()` as the module.
  37310. */
  37311. (function (module, exports) {
  37312. exports = module.exports = debug$8.exports;
  37313. exports.log = log;
  37314. exports.formatArgs = formatArgs;
  37315. exports.save = save;
  37316. exports.load = load;
  37317. exports.useColors = useColors;
  37318. exports.storage = 'undefined' != typeof chrome
  37319. && 'undefined' != typeof chrome.storage
  37320. ? chrome.storage.local
  37321. : localstorage();
  37322. /**
  37323. * Colors.
  37324. */
  37325. exports.colors = [
  37326. 'lightseagreen',
  37327. 'forestgreen',
  37328. 'goldenrod',
  37329. 'dodgerblue',
  37330. 'darkorchid',
  37331. 'crimson'
  37332. ];
  37333. /**
  37334. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  37335. * and the Firebug extension (any Firefox version) are known
  37336. * to support "%c" CSS customizations.
  37337. *
  37338. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  37339. */
  37340. function useColors() {
  37341. // NB: In an Electron preload script, document will be defined but not fully
  37342. // initialized. Since we know we're in Chrome, we'll just detect this case
  37343. // explicitly
  37344. if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') {
  37345. return true;
  37346. }
  37347. // is webkit? http://stackoverflow.com/a/16459606/376773
  37348. // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
  37349. return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
  37350. // is firebug? http://stackoverflow.com/a/398120/376773
  37351. (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
  37352. // is firefox >= v31?
  37353. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  37354. (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
  37355. // double check webkit in userAgent just in case we are in a worker
  37356. (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
  37357. }
  37358. /**
  37359. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  37360. */
  37361. exports.formatters.j = function(v) {
  37362. try {
  37363. return JSON.stringify(v);
  37364. } catch (err) {
  37365. return '[UnexpectedJSONParseError]: ' + err.message;
  37366. }
  37367. };
  37368. /**
  37369. * Colorize log arguments if enabled.
  37370. *
  37371. * @api public
  37372. */
  37373. function formatArgs(args) {
  37374. var useColors = this.useColors;
  37375. args[0] = (useColors ? '%c' : '')
  37376. + this.namespace
  37377. + (useColors ? ' %c' : ' ')
  37378. + args[0]
  37379. + (useColors ? '%c ' : ' ')
  37380. + '+' + exports.humanize(this.diff);
  37381. if (!useColors) return;
  37382. var c = 'color: ' + this.color;
  37383. args.splice(1, 0, c, 'color: inherit');
  37384. // the final "%c" is somewhat tricky, because there could be other
  37385. // arguments passed either before or after the %c, so we need to
  37386. // figure out the correct index to insert the CSS into
  37387. var index = 0;
  37388. var lastC = 0;
  37389. args[0].replace(/%[a-zA-Z%]/g, function(match) {
  37390. if ('%%' === match) return;
  37391. index++;
  37392. if ('%c' === match) {
  37393. // we only are interested in the *last* %c
  37394. // (the user may have provided their own)
  37395. lastC = index;
  37396. }
  37397. });
  37398. args.splice(lastC, 0, c);
  37399. }
  37400. /**
  37401. * Invokes `console.log()` when available.
  37402. * No-op when `console.log` is not a "function".
  37403. *
  37404. * @api public
  37405. */
  37406. function log() {
  37407. // this hackery is required for IE8/9, where
  37408. // the `console.log` function doesn't have 'apply'
  37409. return 'object' === typeof console
  37410. && console.log
  37411. && Function.prototype.apply.call(console.log, console, arguments);
  37412. }
  37413. /**
  37414. * Save `namespaces`.
  37415. *
  37416. * @param {String} namespaces
  37417. * @api private
  37418. */
  37419. function save(namespaces) {
  37420. try {
  37421. if (null == namespaces) {
  37422. exports.storage.removeItem('debug');
  37423. } else {
  37424. exports.storage.debug = namespaces;
  37425. }
  37426. } catch(e) {}
  37427. }
  37428. /**
  37429. * Load `namespaces`.
  37430. *
  37431. * @return {String} returns the previously persisted debug modes
  37432. * @api private
  37433. */
  37434. function load() {
  37435. var r;
  37436. try {
  37437. r = exports.storage.debug;
  37438. } catch(e) {}
  37439. // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
  37440. if (!r && typeof process !== 'undefined' && 'env' in process) {
  37441. r = process.env.DEBUG;
  37442. }
  37443. return r;
  37444. }
  37445. /**
  37446. * Enable namespaces listed in `localStorage.debug` initially.
  37447. */
  37448. exports.enable(load());
  37449. /**
  37450. * Localstorage attempts to return the localstorage.
  37451. *
  37452. * This is necessary because safari throws
  37453. * when a user disables cookies/localstorage
  37454. * and you attempt to access it.
  37455. *
  37456. * @return {LocalStorage}
  37457. * @api private
  37458. */
  37459. function localstorage() {
  37460. try {
  37461. return window.localStorage;
  37462. } catch (e) {}
  37463. }
  37464. }(browser, browser.exports));
  37465. var node = {exports: {}};
  37466. /**
  37467. * Module dependencies.
  37468. */
  37469. (function (module, exports) {
  37470. var tty = require$$0__default;
  37471. var util = require$$0__default$2;
  37472. /**
  37473. * This is the Node.js implementation of `debug()`.
  37474. *
  37475. * Expose `debug()` as the module.
  37476. */
  37477. exports = module.exports = debug$8.exports;
  37478. exports.init = init;
  37479. exports.log = log;
  37480. exports.formatArgs = formatArgs;
  37481. exports.save = save;
  37482. exports.load = load;
  37483. exports.useColors = useColors;
  37484. /**
  37485. * Colors.
  37486. */
  37487. exports.colors = [6, 2, 3, 4, 5, 1];
  37488. /**
  37489. * Build up the default `inspectOpts` object from the environment variables.
  37490. *
  37491. * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
  37492. */
  37493. exports.inspectOpts = Object.keys(process.env).filter(function (key) {
  37494. return /^debug_/i.test(key);
  37495. }).reduce(function (obj, key) {
  37496. // camel-case
  37497. var prop = key
  37498. .substring(6)
  37499. .toLowerCase()
  37500. .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() });
  37501. // coerce string value into JS value
  37502. var val = process.env[key];
  37503. if (/^(yes|on|true|enabled)$/i.test(val)) val = true;
  37504. else if (/^(no|off|false|disabled)$/i.test(val)) val = false;
  37505. else if (val === 'null') val = null;
  37506. else val = Number(val);
  37507. obj[prop] = val;
  37508. return obj;
  37509. }, {});
  37510. /**
  37511. * The file descriptor to write the `debug()` calls to.
  37512. * Set the `DEBUG_FD` env variable to override with another value. i.e.:
  37513. *
  37514. * $ DEBUG_FD=3 node script.js 3>debug.log
  37515. */
  37516. var fd = parseInt(process.env.DEBUG_FD, 10) || 2;
  37517. if (1 !== fd && 2 !== fd) {
  37518. util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')();
  37519. }
  37520. var stream = 1 === fd ? process.stdout :
  37521. 2 === fd ? process.stderr :
  37522. createWritableStdioStream(fd);
  37523. /**
  37524. * Is stdout a TTY? Colored output is enabled when `true`.
  37525. */
  37526. function useColors() {
  37527. return 'colors' in exports.inspectOpts
  37528. ? Boolean(exports.inspectOpts.colors)
  37529. : tty.isatty(fd);
  37530. }
  37531. /**
  37532. * Map %o to `util.inspect()`, all on a single line.
  37533. */
  37534. exports.formatters.o = function(v) {
  37535. this.inspectOpts.colors = this.useColors;
  37536. return util.inspect(v, this.inspectOpts)
  37537. .split('\n').map(function(str) {
  37538. return str.trim()
  37539. }).join(' ');
  37540. };
  37541. /**
  37542. * Map %o to `util.inspect()`, allowing multiple lines if needed.
  37543. */
  37544. exports.formatters.O = function(v) {
  37545. this.inspectOpts.colors = this.useColors;
  37546. return util.inspect(v, this.inspectOpts);
  37547. };
  37548. /**
  37549. * Adds ANSI color escape codes if enabled.
  37550. *
  37551. * @api public
  37552. */
  37553. function formatArgs(args) {
  37554. var name = this.namespace;
  37555. var useColors = this.useColors;
  37556. if (useColors) {
  37557. var c = this.color;
  37558. var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m';
  37559. args[0] = prefix + args[0].split('\n').join('\n' + prefix);
  37560. args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m');
  37561. } else {
  37562. args[0] = new Date().toUTCString()
  37563. + ' ' + name + ' ' + args[0];
  37564. }
  37565. }
  37566. /**
  37567. * Invokes `util.format()` with the specified arguments and writes to `stream`.
  37568. */
  37569. function log() {
  37570. return stream.write(util.format.apply(util, arguments) + '\n');
  37571. }
  37572. /**
  37573. * Save `namespaces`.
  37574. *
  37575. * @param {String} namespaces
  37576. * @api private
  37577. */
  37578. function save(namespaces) {
  37579. if (null == namespaces) {
  37580. // If you set a process.env field to null or undefined, it gets cast to the
  37581. // string 'null' or 'undefined'. Just delete instead.
  37582. delete process.env.DEBUG;
  37583. } else {
  37584. process.env.DEBUG = namespaces;
  37585. }
  37586. }
  37587. /**
  37588. * Load `namespaces`.
  37589. *
  37590. * @return {String} returns the previously persisted debug modes
  37591. * @api private
  37592. */
  37593. function load() {
  37594. return process.env.DEBUG;
  37595. }
  37596. /**
  37597. * Copied from `node/src/node.js`.
  37598. *
  37599. * XXX: It's lame that node doesn't expose this API out-of-the-box. It also
  37600. * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame.
  37601. */
  37602. function createWritableStdioStream (fd) {
  37603. var stream;
  37604. var tty_wrap = process.binding('tty_wrap');
  37605. // Note stream._type is used for test-module-load-list.js
  37606. switch (tty_wrap.guessHandleType(fd)) {
  37607. case 'TTY':
  37608. stream = new tty.WriteStream(fd);
  37609. stream._type = 'tty';
  37610. // Hack to have stream not keep the event loop alive.
  37611. // See https://github.com/joyent/node/issues/1726
  37612. if (stream._handle && stream._handle.unref) {
  37613. stream._handle.unref();
  37614. }
  37615. break;
  37616. case 'FILE':
  37617. var fs = fs__default;
  37618. stream = new fs.SyncWriteStream(fd, { autoClose: false });
  37619. stream._type = 'fs';
  37620. break;
  37621. case 'PIPE':
  37622. case 'TCP':
  37623. var net = require$$3__default;
  37624. stream = new net.Socket({
  37625. fd: fd,
  37626. readable: false,
  37627. writable: true
  37628. });
  37629. // FIXME Should probably have an option in net.Socket to create a
  37630. // stream from an existing fd which is writable only. But for now
  37631. // we'll just add this hack and set the `readable` member to false.
  37632. // Test: ./node test/fixtures/echo.js < /etc/passwd
  37633. stream.readable = false;
  37634. stream.read = null;
  37635. stream._type = 'pipe';
  37636. // FIXME Hack to have stream not keep the event loop alive.
  37637. // See https://github.com/joyent/node/issues/1726
  37638. if (stream._handle && stream._handle.unref) {
  37639. stream._handle.unref();
  37640. }
  37641. break;
  37642. default:
  37643. // Probably an error on in uv_guess_handle()
  37644. throw new Error('Implement me. Unknown stream file type!');
  37645. }
  37646. // For supporting legacy API we put the FD here.
  37647. stream.fd = fd;
  37648. stream._isStdio = true;
  37649. return stream;
  37650. }
  37651. /**
  37652. * Init logic for `debug` instances.
  37653. *
  37654. * Create a new `inspectOpts` object in case `useColors` is set
  37655. * differently for a particular `debug` instance.
  37656. */
  37657. function init (debug) {
  37658. debug.inspectOpts = {};
  37659. var keys = Object.keys(exports.inspectOpts);
  37660. for (var i = 0; i < keys.length; i++) {
  37661. debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
  37662. }
  37663. }
  37664. /**
  37665. * Enable namespaces listed in `process.env.DEBUG` initially.
  37666. */
  37667. exports.enable(load());
  37668. }(node, node.exports));
  37669. /**
  37670. * Detect Electron renderer process, which is node, but we should
  37671. * treat as a browser.
  37672. */
  37673. if (typeof process !== 'undefined' && process.type === 'renderer') {
  37674. src.exports = browser.exports;
  37675. } else {
  37676. src.exports = node.exports;
  37677. }
  37678. /*!
  37679. * encodeurl
  37680. * Copyright(c) 2016 Douglas Christopher Wilson
  37681. * MIT Licensed
  37682. */
  37683. /**
  37684. * Module exports.
  37685. * @public
  37686. */
  37687. var encodeurl = encodeUrl$1;
  37688. /**
  37689. * RegExp to match non-URL code points, *after* encoding (i.e. not including "%")
  37690. * and including invalid escape sequences.
  37691. * @private
  37692. */
  37693. var ENCODE_CHARS_REGEXP = /(?:[^\x21\x25\x26-\x3B\x3D\x3F-\x5B\x5D\x5F\x61-\x7A\x7E]|%(?:[^0-9A-Fa-f]|[0-9A-Fa-f][^0-9A-Fa-f]|$))+/g;
  37694. /**
  37695. * RegExp to match unmatched surrogate pair.
  37696. * @private
  37697. */
  37698. var UNMATCHED_SURROGATE_PAIR_REGEXP = /(^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]|[\uD800-\uDBFF]([^\uDC00-\uDFFF]|$)/g;
  37699. /**
  37700. * String to replace unmatched surrogate pair with.
  37701. * @private
  37702. */
  37703. var UNMATCHED_SURROGATE_PAIR_REPLACE = '$1\uFFFD$2';
  37704. /**
  37705. * Encode a URL to a percent-encoded form, excluding already-encoded sequences.
  37706. *
  37707. * This function will take an already-encoded URL and encode all the non-URL
  37708. * code points. This function will not encode the "%" character unless it is
  37709. * not part of a valid sequence (`%20` will be left as-is, but `%foo` will
  37710. * be encoded as `%25foo`).
  37711. *
  37712. * This encode is meant to be "safe" and does not throw errors. It will try as
  37713. * hard as it can to properly encode the given URL, including replacing any raw,
  37714. * unpaired surrogate pairs with the Unicode replacement character prior to
  37715. * encoding.
  37716. *
  37717. * @param {string} url
  37718. * @return {string}
  37719. * @public
  37720. */
  37721. function encodeUrl$1 (url) {
  37722. return String(url)
  37723. .replace(UNMATCHED_SURROGATE_PAIR_REGEXP, UNMATCHED_SURROGATE_PAIR_REPLACE)
  37724. .replace(ENCODE_CHARS_REGEXP, encodeURI)
  37725. }
  37726. /*!
  37727. * escape-html
  37728. * Copyright(c) 2012-2013 TJ Holowaychuk
  37729. * Copyright(c) 2015 Andreas Lubbe
  37730. * Copyright(c) 2015 Tiancheng "Timothy" Gu
  37731. * MIT Licensed
  37732. */
  37733. /**
  37734. * Module variables.
  37735. * @private
  37736. */
  37737. var matchHtmlRegExp = /["'&<>]/;
  37738. /**
  37739. * Module exports.
  37740. * @public
  37741. */
  37742. var escapeHtml_1 = escapeHtml$1;
  37743. /**
  37744. * Escape special characters in the given string of html.
  37745. *
  37746. * @param {string} string The string to escape for inserting into HTML
  37747. * @return {string}
  37748. * @public
  37749. */
  37750. function escapeHtml$1(string) {
  37751. var str = '' + string;
  37752. var match = matchHtmlRegExp.exec(str);
  37753. if (!match) {
  37754. return str;
  37755. }
  37756. var escape;
  37757. var html = '';
  37758. var index = 0;
  37759. var lastIndex = 0;
  37760. for (index = match.index; index < str.length; index++) {
  37761. switch (str.charCodeAt(index)) {
  37762. case 34: // "
  37763. escape = '&quot;';
  37764. break;
  37765. case 38: // &
  37766. escape = '&amp;';
  37767. break;
  37768. case 39: // '
  37769. escape = '&#39;';
  37770. break;
  37771. case 60: // <
  37772. escape = '&lt;';
  37773. break;
  37774. case 62: // >
  37775. escape = '&gt;';
  37776. break;
  37777. default:
  37778. continue;
  37779. }
  37780. if (lastIndex !== index) {
  37781. html += str.substring(lastIndex, index);
  37782. }
  37783. lastIndex = index + 1;
  37784. html += escape;
  37785. }
  37786. return lastIndex !== index
  37787. ? html + str.substring(lastIndex, index)
  37788. : html;
  37789. }
  37790. var onFinished$2 = {exports: {}};
  37791. /*!
  37792. * ee-first
  37793. * Copyright(c) 2014 Jonathan Ong
  37794. * MIT Licensed
  37795. */
  37796. /**
  37797. * Module exports.
  37798. * @public
  37799. */
  37800. var eeFirst = first$1;
  37801. /**
  37802. * Get the first event in a set of event emitters and event pairs.
  37803. *
  37804. * @param {array} stuff
  37805. * @param {function} done
  37806. * @public
  37807. */
  37808. function first$1(stuff, done) {
  37809. if (!Array.isArray(stuff))
  37810. throw new TypeError('arg must be an array of [ee, events...] arrays')
  37811. var cleanups = [];
  37812. for (var i = 0; i < stuff.length; i++) {
  37813. var arr = stuff[i];
  37814. if (!Array.isArray(arr) || arr.length < 2)
  37815. throw new TypeError('each array member must be [ee, events...]')
  37816. var ee = arr[0];
  37817. for (var j = 1; j < arr.length; j++) {
  37818. var event = arr[j];
  37819. var fn = listener(event, callback);
  37820. // listen to the event
  37821. ee.on(event, fn);
  37822. // push this listener to the list of cleanups
  37823. cleanups.push({
  37824. ee: ee,
  37825. event: event,
  37826. fn: fn,
  37827. });
  37828. }
  37829. }
  37830. function callback() {
  37831. cleanup();
  37832. done.apply(null, arguments);
  37833. }
  37834. function cleanup() {
  37835. var x;
  37836. for (var i = 0; i < cleanups.length; i++) {
  37837. x = cleanups[i];
  37838. x.ee.removeListener(x.event, x.fn);
  37839. }
  37840. }
  37841. function thunk(fn) {
  37842. done = fn;
  37843. }
  37844. thunk.cancel = cleanup;
  37845. return thunk
  37846. }
  37847. /**
  37848. * Create the event listener.
  37849. * @private
  37850. */
  37851. function listener(event, done) {
  37852. return function onevent(arg1) {
  37853. var args = new Array(arguments.length);
  37854. var ee = this;
  37855. var err = event === 'error'
  37856. ? arg1
  37857. : null;
  37858. // copy args to prevent arguments escaping scope
  37859. for (var i = 0; i < args.length; i++) {
  37860. args[i] = arguments[i];
  37861. }
  37862. done(err, ee, event, args);
  37863. }
  37864. }
  37865. /*!
  37866. * on-finished
  37867. * Copyright(c) 2013 Jonathan Ong
  37868. * Copyright(c) 2014 Douglas Christopher Wilson
  37869. * MIT Licensed
  37870. */
  37871. /**
  37872. * Module exports.
  37873. * @public
  37874. */
  37875. onFinished$2.exports = onFinished$1;
  37876. onFinished$2.exports.isFinished = isFinished$1;
  37877. /**
  37878. * Module dependencies.
  37879. * @private
  37880. */
  37881. var first = eeFirst;
  37882. /**
  37883. * Variables.
  37884. * @private
  37885. */
  37886. /* istanbul ignore next */
  37887. var defer$2 = typeof setImmediate === 'function'
  37888. ? setImmediate
  37889. : function(fn){ process.nextTick(fn.bind.apply(fn, arguments)); };
  37890. /**
  37891. * Invoke callback when the response has finished, useful for
  37892. * cleaning up resources afterwards.
  37893. *
  37894. * @param {object} msg
  37895. * @param {function} listener
  37896. * @return {object}
  37897. * @public
  37898. */
  37899. function onFinished$1(msg, listener) {
  37900. if (isFinished$1(msg) !== false) {
  37901. defer$2(listener, null, msg);
  37902. return msg
  37903. }
  37904. // attach the listener to the message
  37905. attachListener(msg, listener);
  37906. return msg
  37907. }
  37908. /**
  37909. * Determine if message is already finished.
  37910. *
  37911. * @param {object} msg
  37912. * @return {boolean}
  37913. * @public
  37914. */
  37915. function isFinished$1(msg) {
  37916. var socket = msg.socket;
  37917. if (typeof msg.finished === 'boolean') {
  37918. // OutgoingMessage
  37919. return Boolean(msg.finished || (socket && !socket.writable))
  37920. }
  37921. if (typeof msg.complete === 'boolean') {
  37922. // IncomingMessage
  37923. return Boolean(msg.upgrade || !socket || !socket.readable || (msg.complete && !msg.readable))
  37924. }
  37925. // don't know
  37926. return undefined
  37927. }
  37928. /**
  37929. * Attach a finished listener to the message.
  37930. *
  37931. * @param {object} msg
  37932. * @param {function} callback
  37933. * @private
  37934. */
  37935. function attachFinishedListener(msg, callback) {
  37936. var eeMsg;
  37937. var eeSocket;
  37938. var finished = false;
  37939. function onFinish(error) {
  37940. eeMsg.cancel();
  37941. eeSocket.cancel();
  37942. finished = true;
  37943. callback(error);
  37944. }
  37945. // finished on first message event
  37946. eeMsg = eeSocket = first([[msg, 'end', 'finish']], onFinish);
  37947. function onSocket(socket) {
  37948. // remove listener
  37949. msg.removeListener('socket', onSocket);
  37950. if (finished) return
  37951. if (eeMsg !== eeSocket) return
  37952. // finished on first socket event
  37953. eeSocket = first([[socket, 'error', 'close']], onFinish);
  37954. }
  37955. if (msg.socket) {
  37956. // socket already assigned
  37957. onSocket(msg.socket);
  37958. return
  37959. }
  37960. // wait for socket to be assigned
  37961. msg.on('socket', onSocket);
  37962. if (msg.socket === undefined) {
  37963. // node.js 0.8 patch
  37964. patchAssignSocket(msg, onSocket);
  37965. }
  37966. }
  37967. /**
  37968. * Attach the listener to the message.
  37969. *
  37970. * @param {object} msg
  37971. * @return {function}
  37972. * @private
  37973. */
  37974. function attachListener(msg, listener) {
  37975. var attached = msg.__onFinished;
  37976. // create a private single listener with queue
  37977. if (!attached || !attached.queue) {
  37978. attached = msg.__onFinished = createListener(msg);
  37979. attachFinishedListener(msg, attached);
  37980. }
  37981. attached.queue.push(listener);
  37982. }
  37983. /**
  37984. * Create listener on message.
  37985. *
  37986. * @param {object} msg
  37987. * @return {function}
  37988. * @private
  37989. */
  37990. function createListener(msg) {
  37991. function listener(err) {
  37992. if (msg.__onFinished === listener) msg.__onFinished = null;
  37993. if (!listener.queue) return
  37994. var queue = listener.queue;
  37995. listener.queue = null;
  37996. for (var i = 0; i < queue.length; i++) {
  37997. queue[i](err, msg);
  37998. }
  37999. }
  38000. listener.queue = [];
  38001. return listener
  38002. }
  38003. /**
  38004. * Patch ServerResponse.prototype.assignSocket for node.js 0.8.
  38005. *
  38006. * @param {ServerResponse} res
  38007. * @param {function} callback
  38008. * @private
  38009. */
  38010. function patchAssignSocket(res, callback) {
  38011. var assignSocket = res.assignSocket;
  38012. if (typeof assignSocket !== 'function') return
  38013. // res.on('socket', callback) is broken in 0.8
  38014. res.assignSocket = function _assignSocket(socket) {
  38015. assignSocket.call(this, socket);
  38016. callback(socket);
  38017. };
  38018. }
  38019. var parseurl$1 = {exports: {}};
  38020. /*!
  38021. * parseurl
  38022. * Copyright(c) 2014 Jonathan Ong
  38023. * Copyright(c) 2014-2017 Douglas Christopher Wilson
  38024. * MIT Licensed
  38025. */
  38026. /**
  38027. * Module dependencies.
  38028. * @private
  38029. */
  38030. var url$3 = require$$0__default$5;
  38031. var parse$8 = url$3.parse;
  38032. var Url = url$3.Url;
  38033. /**
  38034. * Module exports.
  38035. * @public
  38036. */
  38037. parseurl$1.exports = parseurl;
  38038. parseurl$1.exports.original = originalurl;
  38039. /**
  38040. * Parse the `req` url with memoization.
  38041. *
  38042. * @param {ServerRequest} req
  38043. * @return {Object}
  38044. * @public
  38045. */
  38046. function parseurl (req) {
  38047. var url = req.url;
  38048. if (url === undefined) {
  38049. // URL is undefined
  38050. return undefined
  38051. }
  38052. var parsed = req._parsedUrl;
  38053. if (fresh(url, parsed)) {
  38054. // Return cached URL parse
  38055. return parsed
  38056. }
  38057. // Parse the URL
  38058. parsed = fastparse(url);
  38059. parsed._raw = url;
  38060. return (req._parsedUrl = parsed)
  38061. }
  38062. /**
  38063. * Parse the `req` original url with fallback and memoization.
  38064. *
  38065. * @param {ServerRequest} req
  38066. * @return {Object}
  38067. * @public
  38068. */
  38069. function originalurl (req) {
  38070. var url = req.originalUrl;
  38071. if (typeof url !== 'string') {
  38072. // Fallback
  38073. return parseurl(req)
  38074. }
  38075. var parsed = req._parsedOriginalUrl;
  38076. if (fresh(url, parsed)) {
  38077. // Return cached URL parse
  38078. return parsed
  38079. }
  38080. // Parse the URL
  38081. parsed = fastparse(url);
  38082. parsed._raw = url;
  38083. return (req._parsedOriginalUrl = parsed)
  38084. }
  38085. /**
  38086. * Parse the `str` url with fast-path short-cut.
  38087. *
  38088. * @param {string} str
  38089. * @return {Object}
  38090. * @private
  38091. */
  38092. function fastparse (str) {
  38093. if (typeof str !== 'string' || str.charCodeAt(0) !== 0x2f /* / */) {
  38094. return parse$8(str)
  38095. }
  38096. var pathname = str;
  38097. var query = null;
  38098. var search = null;
  38099. // This takes the regexp from https://github.com/joyent/node/pull/7878
  38100. // Which is /^(\/[^?#\s]*)(\?[^#\s]*)?$/
  38101. // And unrolls it into a for loop
  38102. for (var i = 1; i < str.length; i++) {
  38103. switch (str.charCodeAt(i)) {
  38104. case 0x3f: /* ? */
  38105. if (search === null) {
  38106. pathname = str.substring(0, i);
  38107. query = str.substring(i + 1);
  38108. search = str.substring(i);
  38109. }
  38110. break
  38111. case 0x09: /* \t */
  38112. case 0x0a: /* \n */
  38113. case 0x0c: /* \f */
  38114. case 0x0d: /* \r */
  38115. case 0x20: /* */
  38116. case 0x23: /* # */
  38117. case 0xa0:
  38118. case 0xfeff:
  38119. return parse$8(str)
  38120. }
  38121. }
  38122. var url = Url !== undefined
  38123. ? new Url()
  38124. : {};
  38125. url.path = str;
  38126. url.href = str;
  38127. url.pathname = pathname;
  38128. if (search !== null) {
  38129. url.query = query;
  38130. url.search = search;
  38131. }
  38132. return url
  38133. }
  38134. /**
  38135. * Determine if parsed is still fresh for url.
  38136. *
  38137. * @param {string} url
  38138. * @param {object} parsedUrl
  38139. * @return {boolean}
  38140. * @private
  38141. */
  38142. function fresh (url, parsedUrl) {
  38143. return typeof parsedUrl === 'object' &&
  38144. parsedUrl !== null &&
  38145. (Url === undefined || parsedUrl instanceof Url) &&
  38146. parsedUrl._raw === url
  38147. }
  38148. var require$$0$1 = {
  38149. "100": "Continue",
  38150. "101": "Switching Protocols",
  38151. "102": "Processing",
  38152. "103": "Early Hints",
  38153. "200": "OK",
  38154. "201": "Created",
  38155. "202": "Accepted",
  38156. "203": "Non-Authoritative Information",
  38157. "204": "No Content",
  38158. "205": "Reset Content",
  38159. "206": "Partial Content",
  38160. "207": "Multi-Status",
  38161. "208": "Already Reported",
  38162. "226": "IM Used",
  38163. "300": "Multiple Choices",
  38164. "301": "Moved Permanently",
  38165. "302": "Found",
  38166. "303": "See Other",
  38167. "304": "Not Modified",
  38168. "305": "Use Proxy",
  38169. "306": "(Unused)",
  38170. "307": "Temporary Redirect",
  38171. "308": "Permanent Redirect",
  38172. "400": "Bad Request",
  38173. "401": "Unauthorized",
  38174. "402": "Payment Required",
  38175. "403": "Forbidden",
  38176. "404": "Not Found",
  38177. "405": "Method Not Allowed",
  38178. "406": "Not Acceptable",
  38179. "407": "Proxy Authentication Required",
  38180. "408": "Request Timeout",
  38181. "409": "Conflict",
  38182. "410": "Gone",
  38183. "411": "Length Required",
  38184. "412": "Precondition Failed",
  38185. "413": "Payload Too Large",
  38186. "414": "URI Too Long",
  38187. "415": "Unsupported Media Type",
  38188. "416": "Range Not Satisfiable",
  38189. "417": "Expectation Failed",
  38190. "418": "I'm a teapot",
  38191. "421": "Misdirected Request",
  38192. "422": "Unprocessable Entity",
  38193. "423": "Locked",
  38194. "424": "Failed Dependency",
  38195. "425": "Unordered Collection",
  38196. "426": "Upgrade Required",
  38197. "428": "Precondition Required",
  38198. "429": "Too Many Requests",
  38199. "431": "Request Header Fields Too Large",
  38200. "451": "Unavailable For Legal Reasons",
  38201. "500": "Internal Server Error",
  38202. "501": "Not Implemented",
  38203. "502": "Bad Gateway",
  38204. "503": "Service Unavailable",
  38205. "504": "Gateway Timeout",
  38206. "505": "HTTP Version Not Supported",
  38207. "506": "Variant Also Negotiates",
  38208. "507": "Insufficient Storage",
  38209. "508": "Loop Detected",
  38210. "509": "Bandwidth Limit Exceeded",
  38211. "510": "Not Extended",
  38212. "511": "Network Authentication Required"
  38213. };
  38214. /*!
  38215. * statuses
  38216. * Copyright(c) 2014 Jonathan Ong
  38217. * Copyright(c) 2016 Douglas Christopher Wilson
  38218. * MIT Licensed
  38219. */
  38220. /**
  38221. * Module dependencies.
  38222. * @private
  38223. */
  38224. var codes = require$$0$1;
  38225. /**
  38226. * Module exports.
  38227. * @public
  38228. */
  38229. var statuses$1 = status;
  38230. // status code to message map
  38231. status.STATUS_CODES = codes;
  38232. // array of status codes
  38233. status.codes = populateStatusesMap(status, codes);
  38234. // status codes for redirects
  38235. status.redirect = {
  38236. 300: true,
  38237. 301: true,
  38238. 302: true,
  38239. 303: true,
  38240. 305: true,
  38241. 307: true,
  38242. 308: true
  38243. };
  38244. // status codes for empty bodies
  38245. status.empty = {
  38246. 204: true,
  38247. 205: true,
  38248. 304: true
  38249. };
  38250. // status codes for when you should retry the request
  38251. status.retry = {
  38252. 502: true,
  38253. 503: true,
  38254. 504: true
  38255. };
  38256. /**
  38257. * Populate the statuses map for given codes.
  38258. * @private
  38259. */
  38260. function populateStatusesMap (statuses, codes) {
  38261. var arr = [];
  38262. Object.keys(codes).forEach(function forEachCode (code) {
  38263. var message = codes[code];
  38264. var status = Number(code);
  38265. // Populate properties
  38266. statuses[status] = message;
  38267. statuses[message] = status;
  38268. statuses[message.toLowerCase()] = status;
  38269. // Add to array
  38270. arr.push(status);
  38271. });
  38272. return arr
  38273. }
  38274. /**
  38275. * Get the status code.
  38276. *
  38277. * Given a number, this will throw if it is not a known status
  38278. * code, otherwise the code will be returned. Given a string,
  38279. * the string will be parsed for a number and return the code
  38280. * if valid, otherwise will lookup the code assuming this is
  38281. * the status message.
  38282. *
  38283. * @param {string|number} code
  38284. * @returns {number}
  38285. * @public
  38286. */
  38287. function status (code) {
  38288. if (typeof code === 'number') {
  38289. if (!status[code]) throw new Error('invalid status code: ' + code)
  38290. return code
  38291. }
  38292. if (typeof code !== 'string') {
  38293. throw new TypeError('code must be a number or string')
  38294. }
  38295. // '403'
  38296. var n = parseInt(code, 10);
  38297. if (!isNaN(n)) {
  38298. if (!status[n]) throw new Error('invalid status code: ' + n)
  38299. return n
  38300. }
  38301. n = status[code.toLowerCase()];
  38302. if (!n) throw new Error('invalid status message: "' + code + '"')
  38303. return n
  38304. }
  38305. /*!
  38306. * unpipe
  38307. * Copyright(c) 2015 Douglas Christopher Wilson
  38308. * MIT Licensed
  38309. */
  38310. /**
  38311. * Module exports.
  38312. * @public
  38313. */
  38314. var unpipe_1 = unpipe$1;
  38315. /**
  38316. * Determine if there are Node.js pipe-like data listeners.
  38317. * @private
  38318. */
  38319. function hasPipeDataListeners(stream) {
  38320. var listeners = stream.listeners('data');
  38321. for (var i = 0; i < listeners.length; i++) {
  38322. if (listeners[i].name === 'ondata') {
  38323. return true
  38324. }
  38325. }
  38326. return false
  38327. }
  38328. /**
  38329. * Unpipe a stream from all destinations.
  38330. *
  38331. * @param {object} stream
  38332. * @public
  38333. */
  38334. function unpipe$1(stream) {
  38335. if (!stream) {
  38336. throw new TypeError('argument stream is required')
  38337. }
  38338. if (typeof stream.unpipe === 'function') {
  38339. // new-style
  38340. stream.unpipe();
  38341. return
  38342. }
  38343. // Node.js 0.8 hack
  38344. if (!hasPipeDataListeners(stream)) {
  38345. return
  38346. }
  38347. var listener;
  38348. var listeners = stream.listeners('close');
  38349. for (var i = 0; i < listeners.length; i++) {
  38350. listener = listeners[i];
  38351. if (listener.name !== 'cleanup' && listener.name !== 'onclose') {
  38352. continue
  38353. }
  38354. // invoke the listener
  38355. listener.call(stream);
  38356. }
  38357. }
  38358. /*!
  38359. * finalhandler
  38360. * Copyright(c) 2014-2017 Douglas Christopher Wilson
  38361. * MIT Licensed
  38362. */
  38363. /**
  38364. * Module dependencies.
  38365. * @private
  38366. */
  38367. var debug$7 = src.exports('finalhandler');
  38368. var encodeUrl = encodeurl;
  38369. var escapeHtml = escapeHtml_1;
  38370. var onFinished = onFinished$2.exports;
  38371. var parseUrl$1 = parseurl$1.exports;
  38372. var statuses = statuses$1;
  38373. var unpipe = unpipe_1;
  38374. /**
  38375. * Module variables.
  38376. * @private
  38377. */
  38378. var DOUBLE_SPACE_REGEXP = /\x20{2}/g;
  38379. var NEWLINE_REGEXP = /\n/g;
  38380. /* istanbul ignore next */
  38381. var defer$1 = typeof setImmediate === 'function'
  38382. ? setImmediate
  38383. : function (fn) { process.nextTick(fn.bind.apply(fn, arguments)); };
  38384. var isFinished = onFinished.isFinished;
  38385. /**
  38386. * Create a minimal HTML document.
  38387. *
  38388. * @param {string} message
  38389. * @private
  38390. */
  38391. function createHtmlDocument (message) {
  38392. var body = escapeHtml(message)
  38393. .replace(NEWLINE_REGEXP, '<br>')
  38394. .replace(DOUBLE_SPACE_REGEXP, ' &nbsp;');
  38395. return '<!DOCTYPE html>\n' +
  38396. '<html lang="en">\n' +
  38397. '<head>\n' +
  38398. '<meta charset="utf-8">\n' +
  38399. '<title>Error</title>\n' +
  38400. '</head>\n' +
  38401. '<body>\n' +
  38402. '<pre>' + body + '</pre>\n' +
  38403. '</body>\n' +
  38404. '</html>\n'
  38405. }
  38406. /**
  38407. * Module exports.
  38408. * @public
  38409. */
  38410. var finalhandler_1 = finalhandler$1;
  38411. /**
  38412. * Create a function to handle the final response.
  38413. *
  38414. * @param {Request} req
  38415. * @param {Response} res
  38416. * @param {Object} [options]
  38417. * @return {Function}
  38418. * @public
  38419. */
  38420. function finalhandler$1 (req, res, options) {
  38421. var opts = options || {};
  38422. // get environment
  38423. var env = opts.env || process.env.NODE_ENV || 'development';
  38424. // get error callback
  38425. var onerror = opts.onerror;
  38426. return function (err) {
  38427. var headers;
  38428. var msg;
  38429. var status;
  38430. // ignore 404 on in-flight response
  38431. if (!err && headersSent(res)) {
  38432. debug$7('cannot 404 after headers sent');
  38433. return
  38434. }
  38435. // unhandled error
  38436. if (err) {
  38437. // respect status code from error
  38438. status = getErrorStatusCode(err);
  38439. if (status === undefined) {
  38440. // fallback to status code on response
  38441. status = getResponseStatusCode(res);
  38442. } else {
  38443. // respect headers from error
  38444. headers = getErrorHeaders(err);
  38445. }
  38446. // get error message
  38447. msg = getErrorMessage(err, status, env);
  38448. } else {
  38449. // not found
  38450. status = 404;
  38451. msg = 'Cannot ' + req.method + ' ' + encodeUrl(getResourceName(req));
  38452. }
  38453. debug$7('default %s', status);
  38454. // schedule onerror callback
  38455. if (err && onerror) {
  38456. defer$1(onerror, err, req, res);
  38457. }
  38458. // cannot actually respond
  38459. if (headersSent(res)) {
  38460. debug$7('cannot %d after headers sent', status);
  38461. req.socket.destroy();
  38462. return
  38463. }
  38464. // send response
  38465. send$2(req, res, status, headers, msg);
  38466. }
  38467. }
  38468. /**
  38469. * Get headers from Error object.
  38470. *
  38471. * @param {Error} err
  38472. * @return {object}
  38473. * @private
  38474. */
  38475. function getErrorHeaders (err) {
  38476. if (!err.headers || typeof err.headers !== 'object') {
  38477. return undefined
  38478. }
  38479. var headers = Object.create(null);
  38480. var keys = Object.keys(err.headers);
  38481. for (var i = 0; i < keys.length; i++) {
  38482. var key = keys[i];
  38483. headers[key] = err.headers[key];
  38484. }
  38485. return headers
  38486. }
  38487. /**
  38488. * Get message from Error object, fallback to status message.
  38489. *
  38490. * @param {Error} err
  38491. * @param {number} status
  38492. * @param {string} env
  38493. * @return {string}
  38494. * @private
  38495. */
  38496. function getErrorMessage (err, status, env) {
  38497. var msg;
  38498. if (env !== 'production') {
  38499. // use err.stack, which typically includes err.message
  38500. msg = err.stack;
  38501. // fallback to err.toString() when possible
  38502. if (!msg && typeof err.toString === 'function') {
  38503. msg = err.toString();
  38504. }
  38505. }
  38506. return msg || statuses[status]
  38507. }
  38508. /**
  38509. * Get status code from Error object.
  38510. *
  38511. * @param {Error} err
  38512. * @return {number}
  38513. * @private
  38514. */
  38515. function getErrorStatusCode (err) {
  38516. // check err.status
  38517. if (typeof err.status === 'number' && err.status >= 400 && err.status < 600) {
  38518. return err.status
  38519. }
  38520. // check err.statusCode
  38521. if (typeof err.statusCode === 'number' && err.statusCode >= 400 && err.statusCode < 600) {
  38522. return err.statusCode
  38523. }
  38524. return undefined
  38525. }
  38526. /**
  38527. * Get resource name for the request.
  38528. *
  38529. * This is typically just the original pathname of the request
  38530. * but will fallback to "resource" is that cannot be determined.
  38531. *
  38532. * @param {IncomingMessage} req
  38533. * @return {string}
  38534. * @private
  38535. */
  38536. function getResourceName (req) {
  38537. try {
  38538. return parseUrl$1.original(req).pathname
  38539. } catch (e) {
  38540. return 'resource'
  38541. }
  38542. }
  38543. /**
  38544. * Get status code from response.
  38545. *
  38546. * @param {OutgoingMessage} res
  38547. * @return {number}
  38548. * @private
  38549. */
  38550. function getResponseStatusCode (res) {
  38551. var status = res.statusCode;
  38552. // default status code to 500 if outside valid range
  38553. if (typeof status !== 'number' || status < 400 || status > 599) {
  38554. status = 500;
  38555. }
  38556. return status
  38557. }
  38558. /**
  38559. * Determine if the response headers have been sent.
  38560. *
  38561. * @param {object} res
  38562. * @returns {boolean}
  38563. * @private
  38564. */
  38565. function headersSent (res) {
  38566. return typeof res.headersSent !== 'boolean'
  38567. ? Boolean(res._header)
  38568. : res.headersSent
  38569. }
  38570. /**
  38571. * Send response.
  38572. *
  38573. * @param {IncomingMessage} req
  38574. * @param {OutgoingMessage} res
  38575. * @param {number} status
  38576. * @param {object} headers
  38577. * @param {string} message
  38578. * @private
  38579. */
  38580. function send$2 (req, res, status, headers, message) {
  38581. function write () {
  38582. // response body
  38583. var body = createHtmlDocument(message);
  38584. // response status
  38585. res.statusCode = status;
  38586. res.statusMessage = statuses[status];
  38587. // response headers
  38588. setHeaders(res, headers);
  38589. // security headers
  38590. res.setHeader('Content-Security-Policy', "default-src 'none'");
  38591. res.setHeader('X-Content-Type-Options', 'nosniff');
  38592. // standard headers
  38593. res.setHeader('Content-Type', 'text/html; charset=utf-8');
  38594. res.setHeader('Content-Length', Buffer.byteLength(body, 'utf8'));
  38595. if (req.method === 'HEAD') {
  38596. res.end();
  38597. return
  38598. }
  38599. res.end(body, 'utf8');
  38600. }
  38601. if (isFinished(req)) {
  38602. write();
  38603. return
  38604. }
  38605. // unpipe everything from the request
  38606. unpipe(req);
  38607. // flush the request
  38608. onFinished(req, write);
  38609. req.resume();
  38610. }
  38611. /**
  38612. * Set response headers from an object.
  38613. *
  38614. * @param {OutgoingMessage} res
  38615. * @param {object} headers
  38616. * @private
  38617. */
  38618. function setHeaders (res, headers) {
  38619. if (!headers) {
  38620. return
  38621. }
  38622. var keys = Object.keys(headers);
  38623. for (var i = 0; i < keys.length; i++) {
  38624. var key = keys[i];
  38625. res.setHeader(key, headers[key]);
  38626. }
  38627. }
  38628. var utilsMerge = {exports: {}};
  38629. /**
  38630. * Merge object b with object a.
  38631. *
  38632. * var a = { foo: 'bar' }
  38633. * , b = { bar: 'baz' };
  38634. *
  38635. * merge(a, b);
  38636. * // => { foo: 'bar', bar: 'baz' }
  38637. *
  38638. * @param {Object} a
  38639. * @param {Object} b
  38640. * @return {Object}
  38641. * @api public
  38642. */
  38643. (function (module, exports) {
  38644. module.exports = function(a, b){
  38645. if (a && b) {
  38646. for (var key in b) {
  38647. a[key] = b[key];
  38648. }
  38649. }
  38650. return a;
  38651. };
  38652. }(utilsMerge));
  38653. /*!
  38654. * connect
  38655. * Copyright(c) 2010 Sencha Inc.
  38656. * Copyright(c) 2011 TJ Holowaychuk
  38657. * Copyright(c) 2015 Douglas Christopher Wilson
  38658. * MIT Licensed
  38659. */
  38660. /**
  38661. * Module dependencies.
  38662. * @private
  38663. */
  38664. var debug$6 = src.exports('connect:dispatcher');
  38665. var EventEmitter$3 = require$$0__default$1.EventEmitter;
  38666. var finalhandler = finalhandler_1;
  38667. var http$4 = require$$1__default$1;
  38668. var merge = utilsMerge.exports;
  38669. var parseUrl = parseurl$1.exports;
  38670. /**
  38671. * Module exports.
  38672. * @public
  38673. */
  38674. var connect = createServer$1;
  38675. /**
  38676. * Module variables.
  38677. * @private
  38678. */
  38679. var env = process.env.NODE_ENV || 'development';
  38680. var proto = {};
  38681. /* istanbul ignore next */
  38682. var defer = typeof setImmediate === 'function'
  38683. ? setImmediate
  38684. : function(fn){ process.nextTick(fn.bind.apply(fn, arguments)); };
  38685. /**
  38686. * Create a new connect server.
  38687. *
  38688. * @return {function}
  38689. * @public
  38690. */
  38691. function createServer$1() {
  38692. function app(req, res, next){ app.handle(req, res, next); }
  38693. merge(app, proto);
  38694. merge(app, EventEmitter$3.prototype);
  38695. app.route = '/';
  38696. app.stack = [];
  38697. return app;
  38698. }
  38699. /**
  38700. * Utilize the given middleware `handle` to the given `route`,
  38701. * defaulting to _/_. This "route" is the mount-point for the
  38702. * middleware, when given a value other than _/_ the middleware
  38703. * is only effective when that segment is present in the request's
  38704. * pathname.
  38705. *
  38706. * For example if we were to mount a function at _/admin_, it would
  38707. * be invoked on _/admin_, and _/admin/settings_, however it would
  38708. * not be invoked for _/_, or _/posts_.
  38709. *
  38710. * @param {String|Function|Server} route, callback or server
  38711. * @param {Function|Server} callback or server
  38712. * @return {Server} for chaining
  38713. * @public
  38714. */
  38715. proto.use = function use(route, fn) {
  38716. var handle = fn;
  38717. var path = route;
  38718. // default route to '/'
  38719. if (typeof route !== 'string') {
  38720. handle = route;
  38721. path = '/';
  38722. }
  38723. // wrap sub-apps
  38724. if (typeof handle.handle === 'function') {
  38725. var server = handle;
  38726. server.route = path;
  38727. handle = function (req, res, next) {
  38728. server.handle(req, res, next);
  38729. };
  38730. }
  38731. // wrap vanilla http.Servers
  38732. if (handle instanceof http$4.Server) {
  38733. handle = handle.listeners('request')[0];
  38734. }
  38735. // strip trailing slash
  38736. if (path[path.length - 1] === '/') {
  38737. path = path.slice(0, -1);
  38738. }
  38739. // add the middleware
  38740. debug$6('use %s %s', path || '/', handle.name || 'anonymous');
  38741. this.stack.push({ route: path, handle: handle });
  38742. return this;
  38743. };
  38744. /**
  38745. * Handle server requests, punting them down
  38746. * the middleware stack.
  38747. *
  38748. * @private
  38749. */
  38750. proto.handle = function handle(req, res, out) {
  38751. var index = 0;
  38752. var protohost = getProtohost(req.url) || '';
  38753. var removed = '';
  38754. var slashAdded = false;
  38755. var stack = this.stack;
  38756. // final function handler
  38757. var done = out || finalhandler(req, res, {
  38758. env: env,
  38759. onerror: logerror
  38760. });
  38761. // store the original URL
  38762. req.originalUrl = req.originalUrl || req.url;
  38763. function next(err) {
  38764. if (slashAdded) {
  38765. req.url = req.url.substr(1);
  38766. slashAdded = false;
  38767. }
  38768. if (removed.length !== 0) {
  38769. req.url = protohost + removed + req.url.substr(protohost.length);
  38770. removed = '';
  38771. }
  38772. // next callback
  38773. var layer = stack[index++];
  38774. // all done
  38775. if (!layer) {
  38776. defer(done, err);
  38777. return;
  38778. }
  38779. // route data
  38780. var path = parseUrl(req).pathname || '/';
  38781. var route = layer.route;
  38782. // skip this layer if the route doesn't match
  38783. if (path.toLowerCase().substr(0, route.length) !== route.toLowerCase()) {
  38784. return next(err);
  38785. }
  38786. // skip if route match does not border "/", ".", or end
  38787. var c = path.length > route.length && path[route.length];
  38788. if (c && c !== '/' && c !== '.') {
  38789. return next(err);
  38790. }
  38791. // trim off the part of the url that matches the route
  38792. if (route.length !== 0 && route !== '/') {
  38793. removed = route;
  38794. req.url = protohost + req.url.substr(protohost.length + removed.length);
  38795. // ensure leading slash
  38796. if (!protohost && req.url[0] !== '/') {
  38797. req.url = '/' + req.url;
  38798. slashAdded = true;
  38799. }
  38800. }
  38801. // call the layer handle
  38802. call(layer.handle, route, err, req, res, next);
  38803. }
  38804. next();
  38805. };
  38806. /**
  38807. * Listen for connections.
  38808. *
  38809. * This method takes the same arguments
  38810. * as node's `http.Server#listen()`.
  38811. *
  38812. * HTTP and HTTPS:
  38813. *
  38814. * If you run your application both as HTTP
  38815. * and HTTPS you may wrap them individually,
  38816. * since your Connect "server" is really just
  38817. * a JavaScript `Function`.
  38818. *
  38819. * var connect = require('connect')
  38820. * , http = require('http')
  38821. * , https = require('https');
  38822. *
  38823. * var app = connect();
  38824. *
  38825. * http.createServer(app).listen(80);
  38826. * https.createServer(options, app).listen(443);
  38827. *
  38828. * @return {http.Server}
  38829. * @api public
  38830. */
  38831. proto.listen = function listen() {
  38832. var server = http$4.createServer(this);
  38833. return server.listen.apply(server, arguments);
  38834. };
  38835. /**
  38836. * Invoke a route handle.
  38837. * @private
  38838. */
  38839. function call(handle, route, err, req, res, next) {
  38840. var arity = handle.length;
  38841. var error = err;
  38842. var hasError = Boolean(err);
  38843. debug$6('%s %s : %s', handle.name || '<anonymous>', route, req.originalUrl);
  38844. try {
  38845. if (hasError && arity === 4) {
  38846. // error-handling middleware
  38847. handle(err, req, res, next);
  38848. return;
  38849. } else if (!hasError && arity < 4) {
  38850. // request-handling middleware
  38851. handle(req, res, next);
  38852. return;
  38853. }
  38854. } catch (e) {
  38855. // replace the error
  38856. error = e;
  38857. }
  38858. // continue
  38859. next(error);
  38860. }
  38861. /**
  38862. * Log error using console.error.
  38863. *
  38864. * @param {Error} err
  38865. * @private
  38866. */
  38867. function logerror(err) {
  38868. if (env !== 'test') console.error(err.stack || err.toString());
  38869. }
  38870. /**
  38871. * Get get protocol + host for a URL.
  38872. *
  38873. * @param {string} url
  38874. * @private
  38875. */
  38876. function getProtohost(url) {
  38877. if (url.length === 0 || url[0] === '/') {
  38878. return undefined;
  38879. }
  38880. var fqdnIndex = url.indexOf('://');
  38881. return fqdnIndex !== -1 && url.lastIndexOf('?', fqdnIndex) === -1
  38882. ? url.substr(0, url.indexOf('/', 3 + fqdnIndex))
  38883. : undefined;
  38884. }
  38885. var lib$1 = {exports: {}};
  38886. /*
  38887. object-assign
  38888. (c) Sindre Sorhus
  38889. @license MIT
  38890. */
  38891. /* eslint-disable no-unused-vars */
  38892. var getOwnPropertySymbols = Object.getOwnPropertySymbols;
  38893. var hasOwnProperty = Object.prototype.hasOwnProperty;
  38894. var propIsEnumerable = Object.prototype.propertyIsEnumerable;
  38895. function toObject(val) {
  38896. if (val === null || val === undefined) {
  38897. throw new TypeError('Object.assign cannot be called with null or undefined');
  38898. }
  38899. return Object(val);
  38900. }
  38901. function shouldUseNative() {
  38902. try {
  38903. if (!Object.assign) {
  38904. return false;
  38905. }
  38906. // Detect buggy property enumeration order in older V8 versions.
  38907. // https://bugs.chromium.org/p/v8/issues/detail?id=4118
  38908. var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
  38909. test1[5] = 'de';
  38910. if (Object.getOwnPropertyNames(test1)[0] === '5') {
  38911. return false;
  38912. }
  38913. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  38914. var test2 = {};
  38915. for (var i = 0; i < 10; i++) {
  38916. test2['_' + String.fromCharCode(i)] = i;
  38917. }
  38918. var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
  38919. return test2[n];
  38920. });
  38921. if (order2.join('') !== '0123456789') {
  38922. return false;
  38923. }
  38924. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  38925. var test3 = {};
  38926. 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
  38927. test3[letter] = letter;
  38928. });
  38929. if (Object.keys(Object.assign({}, test3)).join('') !==
  38930. 'abcdefghijklmnopqrst') {
  38931. return false;
  38932. }
  38933. return true;
  38934. } catch (err) {
  38935. // We don't expect any of the above to throw, but better to be safe.
  38936. return false;
  38937. }
  38938. }
  38939. var objectAssign = shouldUseNative() ? Object.assign : function (target, source) {
  38940. var from;
  38941. var to = toObject(target);
  38942. var symbols;
  38943. for (var s = 1; s < arguments.length; s++) {
  38944. from = Object(arguments[s]);
  38945. for (var key in from) {
  38946. if (hasOwnProperty.call(from, key)) {
  38947. to[key] = from[key];
  38948. }
  38949. }
  38950. if (getOwnPropertySymbols) {
  38951. symbols = getOwnPropertySymbols(from);
  38952. for (var i = 0; i < symbols.length; i++) {
  38953. if (propIsEnumerable.call(from, symbols[i])) {
  38954. to[symbols[i]] = from[symbols[i]];
  38955. }
  38956. }
  38957. }
  38958. }
  38959. return to;
  38960. };
  38961. var vary$1 = {exports: {}};
  38962. /*!
  38963. * vary
  38964. * Copyright(c) 2014-2017 Douglas Christopher Wilson
  38965. * MIT Licensed
  38966. */
  38967. /**
  38968. * Module exports.
  38969. */
  38970. vary$1.exports = vary;
  38971. vary$1.exports.append = append;
  38972. /**
  38973. * RegExp to match field-name in RFC 7230 sec 3.2
  38974. *
  38975. * field-name = token
  38976. * token = 1*tchar
  38977. * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*"
  38978. * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
  38979. * / DIGIT / ALPHA
  38980. * ; any VCHAR, except delimiters
  38981. */
  38982. var FIELD_NAME_REGEXP = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
  38983. /**
  38984. * Append a field to a vary header.
  38985. *
  38986. * @param {String} header
  38987. * @param {String|Array} field
  38988. * @return {String}
  38989. * @public
  38990. */
  38991. function append (header, field) {
  38992. if (typeof header !== 'string') {
  38993. throw new TypeError('header argument is required')
  38994. }
  38995. if (!field) {
  38996. throw new TypeError('field argument is required')
  38997. }
  38998. // get fields array
  38999. var fields = !Array.isArray(field)
  39000. ? parse$7(String(field))
  39001. : field;
  39002. // assert on invalid field names
  39003. for (var j = 0; j < fields.length; j++) {
  39004. if (!FIELD_NAME_REGEXP.test(fields[j])) {
  39005. throw new TypeError('field argument contains an invalid header name')
  39006. }
  39007. }
  39008. // existing, unspecified vary
  39009. if (header === '*') {
  39010. return header
  39011. }
  39012. // enumerate current values
  39013. var val = header;
  39014. var vals = parse$7(header.toLowerCase());
  39015. // unspecified vary
  39016. if (fields.indexOf('*') !== -1 || vals.indexOf('*') !== -1) {
  39017. return '*'
  39018. }
  39019. for (var i = 0; i < fields.length; i++) {
  39020. var fld = fields[i].toLowerCase();
  39021. // append value (case-preserving)
  39022. if (vals.indexOf(fld) === -1) {
  39023. vals.push(fld);
  39024. val = val
  39025. ? val + ', ' + fields[i]
  39026. : fields[i];
  39027. }
  39028. }
  39029. return val
  39030. }
  39031. /**
  39032. * Parse a vary header into an array.
  39033. *
  39034. * @param {String} header
  39035. * @return {Array}
  39036. * @private
  39037. */
  39038. function parse$7 (header) {
  39039. var end = 0;
  39040. var list = [];
  39041. var start = 0;
  39042. // gather tokens
  39043. for (var i = 0, len = header.length; i < len; i++) {
  39044. switch (header.charCodeAt(i)) {
  39045. case 0x20: /* */
  39046. if (start === end) {
  39047. start = end = i + 1;
  39048. }
  39049. break
  39050. case 0x2c: /* , */
  39051. list.push(header.substring(start, end));
  39052. start = end = i + 1;
  39053. break
  39054. default:
  39055. end = i + 1;
  39056. break
  39057. }
  39058. }
  39059. // final token
  39060. list.push(header.substring(start, end));
  39061. return list
  39062. }
  39063. /**
  39064. * Mark that a request is varied on a header field.
  39065. *
  39066. * @param {Object} res
  39067. * @param {String|Array} field
  39068. * @public
  39069. */
  39070. function vary (res, field) {
  39071. if (!res || !res.getHeader || !res.setHeader) {
  39072. // quack quack
  39073. throw new TypeError('res argument is required')
  39074. }
  39075. // get existing header
  39076. var val = res.getHeader('Vary') || '';
  39077. var header = Array.isArray(val)
  39078. ? val.join(', ')
  39079. : String(val);
  39080. // set new header
  39081. if ((val = append(header, field))) {
  39082. res.setHeader('Vary', val);
  39083. }
  39084. }
  39085. (function () {
  39086. var assign = objectAssign;
  39087. var vary = vary$1.exports;
  39088. var defaults = {
  39089. origin: '*',
  39090. methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
  39091. preflightContinue: false,
  39092. optionsSuccessStatus: 204
  39093. };
  39094. function isString(s) {
  39095. return typeof s === 'string' || s instanceof String;
  39096. }
  39097. function isOriginAllowed(origin, allowedOrigin) {
  39098. if (Array.isArray(allowedOrigin)) {
  39099. for (var i = 0; i < allowedOrigin.length; ++i) {
  39100. if (isOriginAllowed(origin, allowedOrigin[i])) {
  39101. return true;
  39102. }
  39103. }
  39104. return false;
  39105. } else if (isString(allowedOrigin)) {
  39106. return origin === allowedOrigin;
  39107. } else if (allowedOrigin instanceof RegExp) {
  39108. return allowedOrigin.test(origin);
  39109. } else {
  39110. return !!allowedOrigin;
  39111. }
  39112. }
  39113. function configureOrigin(options, req) {
  39114. var requestOrigin = req.headers.origin,
  39115. headers = [],
  39116. isAllowed;
  39117. if (!options.origin || options.origin === '*') {
  39118. // allow any origin
  39119. headers.push([{
  39120. key: 'Access-Control-Allow-Origin',
  39121. value: '*'
  39122. }]);
  39123. } else if (isString(options.origin)) {
  39124. // fixed origin
  39125. headers.push([{
  39126. key: 'Access-Control-Allow-Origin',
  39127. value: options.origin
  39128. }]);
  39129. headers.push([{
  39130. key: 'Vary',
  39131. value: 'Origin'
  39132. }]);
  39133. } else {
  39134. isAllowed = isOriginAllowed(requestOrigin, options.origin);
  39135. // reflect origin
  39136. headers.push([{
  39137. key: 'Access-Control-Allow-Origin',
  39138. value: isAllowed ? requestOrigin : false
  39139. }]);
  39140. headers.push([{
  39141. key: 'Vary',
  39142. value: 'Origin'
  39143. }]);
  39144. }
  39145. return headers;
  39146. }
  39147. function configureMethods(options) {
  39148. var methods = options.methods;
  39149. if (methods.join) {
  39150. methods = options.methods.join(','); // .methods is an array, so turn it into a string
  39151. }
  39152. return {
  39153. key: 'Access-Control-Allow-Methods',
  39154. value: methods
  39155. };
  39156. }
  39157. function configureCredentials(options) {
  39158. if (options.credentials === true) {
  39159. return {
  39160. key: 'Access-Control-Allow-Credentials',
  39161. value: 'true'
  39162. };
  39163. }
  39164. return null;
  39165. }
  39166. function configureAllowedHeaders(options, req) {
  39167. var allowedHeaders = options.allowedHeaders || options.headers;
  39168. var headers = [];
  39169. if (!allowedHeaders) {
  39170. allowedHeaders = req.headers['access-control-request-headers']; // .headers wasn't specified, so reflect the request headers
  39171. headers.push([{
  39172. key: 'Vary',
  39173. value: 'Access-Control-Request-Headers'
  39174. }]);
  39175. } else if (allowedHeaders.join) {
  39176. allowedHeaders = allowedHeaders.join(','); // .headers is an array, so turn it into a string
  39177. }
  39178. if (allowedHeaders && allowedHeaders.length) {
  39179. headers.push([{
  39180. key: 'Access-Control-Allow-Headers',
  39181. value: allowedHeaders
  39182. }]);
  39183. }
  39184. return headers;
  39185. }
  39186. function configureExposedHeaders(options) {
  39187. var headers = options.exposedHeaders;
  39188. if (!headers) {
  39189. return null;
  39190. } else if (headers.join) {
  39191. headers = headers.join(','); // .headers is an array, so turn it into a string
  39192. }
  39193. if (headers && headers.length) {
  39194. return {
  39195. key: 'Access-Control-Expose-Headers',
  39196. value: headers
  39197. };
  39198. }
  39199. return null;
  39200. }
  39201. function configureMaxAge(options) {
  39202. var maxAge = (typeof options.maxAge === 'number' || options.maxAge) && options.maxAge.toString();
  39203. if (maxAge && maxAge.length) {
  39204. return {
  39205. key: 'Access-Control-Max-Age',
  39206. value: maxAge
  39207. };
  39208. }
  39209. return null;
  39210. }
  39211. function applyHeaders(headers, res) {
  39212. for (var i = 0, n = headers.length; i < n; i++) {
  39213. var header = headers[i];
  39214. if (header) {
  39215. if (Array.isArray(header)) {
  39216. applyHeaders(header, res);
  39217. } else if (header.key === 'Vary' && header.value) {
  39218. vary(res, header.value);
  39219. } else if (header.value) {
  39220. res.setHeader(header.key, header.value);
  39221. }
  39222. }
  39223. }
  39224. }
  39225. function cors(options, req, res, next) {
  39226. var headers = [],
  39227. method = req.method && req.method.toUpperCase && req.method.toUpperCase();
  39228. if (method === 'OPTIONS') {
  39229. // preflight
  39230. headers.push(configureOrigin(options, req));
  39231. headers.push(configureCredentials(options));
  39232. headers.push(configureMethods(options));
  39233. headers.push(configureAllowedHeaders(options, req));
  39234. headers.push(configureMaxAge(options));
  39235. headers.push(configureExposedHeaders(options));
  39236. applyHeaders(headers, res);
  39237. if (options.preflightContinue) {
  39238. next();
  39239. } else {
  39240. // Safari (and potentially other browsers) need content-length 0,
  39241. // for 204 or they just hang waiting for a body
  39242. res.statusCode = options.optionsSuccessStatus;
  39243. res.setHeader('Content-Length', '0');
  39244. res.end();
  39245. }
  39246. } else {
  39247. // actual response
  39248. headers.push(configureOrigin(options, req));
  39249. headers.push(configureCredentials(options));
  39250. headers.push(configureExposedHeaders(options));
  39251. applyHeaders(headers, res);
  39252. next();
  39253. }
  39254. }
  39255. function middlewareWrapper(o) {
  39256. // if options are static (either via defaults or custom options passed in), wrap in a function
  39257. var optionsCallback = null;
  39258. if (typeof o === 'function') {
  39259. optionsCallback = o;
  39260. } else {
  39261. optionsCallback = function (req, cb) {
  39262. cb(null, o);
  39263. };
  39264. }
  39265. return function corsMiddleware(req, res, next) {
  39266. optionsCallback(req, function (err, options) {
  39267. if (err) {
  39268. next(err);
  39269. } else {
  39270. var corsOptions = assign({}, defaults, options);
  39271. var originCallback = null;
  39272. if (corsOptions.origin && typeof corsOptions.origin === 'function') {
  39273. originCallback = corsOptions.origin;
  39274. } else if (corsOptions.origin) {
  39275. originCallback = function (origin, cb) {
  39276. cb(null, corsOptions.origin);
  39277. };
  39278. }
  39279. if (originCallback) {
  39280. originCallback(req.headers.origin, function (err2, origin) {
  39281. if (err2 || !origin) {
  39282. next(err2);
  39283. } else {
  39284. corsOptions.origin = origin;
  39285. cors(corsOptions, req, res, next);
  39286. }
  39287. });
  39288. } else {
  39289. next();
  39290. }
  39291. }
  39292. });
  39293. };
  39294. }
  39295. // can pass either an options hash, an options delegate, or nothing
  39296. lib$1.exports = middlewareWrapper;
  39297. }());
  39298. var corsMiddleware = lib$1.exports;
  39299. var chokidar = {};
  39300. const fs$a = fs__default;
  39301. const { Readable } = require$$0__default$3;
  39302. const sysPath$3 = path__default;
  39303. const { promisify: promisify$3 } = require$$0__default$2;
  39304. const picomatch$2 = picomatch$6;
  39305. const readdir$1 = promisify$3(fs$a.readdir);
  39306. const stat$3 = promisify$3(fs$a.stat);
  39307. const lstat$2 = promisify$3(fs$a.lstat);
  39308. const realpath$1 = promisify$3(fs$a.realpath);
  39309. /**
  39310. * @typedef {Object} EntryInfo
  39311. * @property {String} path
  39312. * @property {String} fullPath
  39313. * @property {fs.Stats=} stats
  39314. * @property {fs.Dirent=} dirent
  39315. * @property {String} basename
  39316. */
  39317. const BANG$2 = '!';
  39318. const RECURSIVE_ERROR_CODE = 'READDIRP_RECURSIVE_ERROR';
  39319. const NORMAL_FLOW_ERRORS = new Set(['ENOENT', 'EPERM', 'EACCES', 'ELOOP', RECURSIVE_ERROR_CODE]);
  39320. const FILE_TYPE = 'files';
  39321. const DIR_TYPE = 'directories';
  39322. const FILE_DIR_TYPE = 'files_directories';
  39323. const EVERYTHING_TYPE = 'all';
  39324. const ALL_TYPES = [FILE_TYPE, DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE];
  39325. const isNormalFlowError = error => NORMAL_FLOW_ERRORS.has(error.code);
  39326. const [maj, min] = process.versions.node.split('.').slice(0, 2).map(n => Number.parseInt(n, 10));
  39327. const wantBigintFsStats = process.platform === 'win32' && (maj > 10 || (maj === 10 && min >= 5));
  39328. const normalizeFilter = filter => {
  39329. if (filter === undefined) return;
  39330. if (typeof filter === 'function') return filter;
  39331. if (typeof filter === 'string') {
  39332. const glob = picomatch$2(filter.trim());
  39333. return entry => glob(entry.basename);
  39334. }
  39335. if (Array.isArray(filter)) {
  39336. const positive = [];
  39337. const negative = [];
  39338. for (const item of filter) {
  39339. const trimmed = item.trim();
  39340. if (trimmed.charAt(0) === BANG$2) {
  39341. negative.push(picomatch$2(trimmed.slice(1)));
  39342. } else {
  39343. positive.push(picomatch$2(trimmed));
  39344. }
  39345. }
  39346. if (negative.length > 0) {
  39347. if (positive.length > 0) {
  39348. return entry =>
  39349. positive.some(f => f(entry.basename)) && !negative.some(f => f(entry.basename));
  39350. }
  39351. return entry => !negative.some(f => f(entry.basename));
  39352. }
  39353. return entry => positive.some(f => f(entry.basename));
  39354. }
  39355. };
  39356. class ReaddirpStream extends Readable {
  39357. static get defaultOptions() {
  39358. return {
  39359. root: '.',
  39360. /* eslint-disable no-unused-vars */
  39361. fileFilter: (path) => true,
  39362. directoryFilter: (path) => true,
  39363. /* eslint-enable no-unused-vars */
  39364. type: FILE_TYPE,
  39365. lstat: false,
  39366. depth: 2147483648,
  39367. alwaysStat: false
  39368. };
  39369. }
  39370. constructor(options = {}) {
  39371. super({
  39372. objectMode: true,
  39373. autoDestroy: true,
  39374. highWaterMark: options.highWaterMark || 4096
  39375. });
  39376. const opts = { ...ReaddirpStream.defaultOptions, ...options };
  39377. const { root, type } = opts;
  39378. this._fileFilter = normalizeFilter(opts.fileFilter);
  39379. this._directoryFilter = normalizeFilter(opts.directoryFilter);
  39380. const statMethod = opts.lstat ? lstat$2 : stat$3;
  39381. // Use bigint stats if it's windows and stat() supports options (node 10+).
  39382. if (wantBigintFsStats) {
  39383. this._stat = path => statMethod(path, { bigint: true });
  39384. } else {
  39385. this._stat = statMethod;
  39386. }
  39387. this._maxDepth = opts.depth;
  39388. this._wantsDir = [DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type);
  39389. this._wantsFile = [FILE_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type);
  39390. this._wantsEverything = type === EVERYTHING_TYPE;
  39391. this._root = sysPath$3.resolve(root);
  39392. this._isDirent = ('Dirent' in fs$a) && !opts.alwaysStat;
  39393. this._statsProp = this._isDirent ? 'dirent' : 'stats';
  39394. this._rdOptions = { encoding: 'utf8', withFileTypes: this._isDirent };
  39395. // Launch stream with one parent, the root dir.
  39396. this.parents = [this._exploreDir(root, 1)];
  39397. this.reading = false;
  39398. this.parent = undefined;
  39399. }
  39400. async _read(batch) {
  39401. if (this.reading) return;
  39402. this.reading = true;
  39403. try {
  39404. while (!this.destroyed && batch > 0) {
  39405. const { path, depth, files = [] } = this.parent || {};
  39406. if (files.length > 0) {
  39407. const slice = files.splice(0, batch).map(dirent => this._formatEntry(dirent, path));
  39408. for (const entry of await Promise.all(slice)) {
  39409. if (this.destroyed) return;
  39410. const entryType = await this._getEntryType(entry);
  39411. if (entryType === 'directory' && this._directoryFilter(entry)) {
  39412. if (depth <= this._maxDepth) {
  39413. this.parents.push(this._exploreDir(entry.fullPath, depth + 1));
  39414. }
  39415. if (this._wantsDir) {
  39416. this.push(entry);
  39417. batch--;
  39418. }
  39419. } else if ((entryType === 'file' || this._includeAsFile(entry)) && this._fileFilter(entry)) {
  39420. if (this._wantsFile) {
  39421. this.push(entry);
  39422. batch--;
  39423. }
  39424. }
  39425. }
  39426. } else {
  39427. const parent = this.parents.pop();
  39428. if (!parent) {
  39429. this.push(null);
  39430. break;
  39431. }
  39432. this.parent = await parent;
  39433. if (this.destroyed) return;
  39434. }
  39435. }
  39436. } catch (error) {
  39437. this.destroy(error);
  39438. } finally {
  39439. this.reading = false;
  39440. }
  39441. }
  39442. async _exploreDir(path, depth) {
  39443. let files;
  39444. try {
  39445. files = await readdir$1(path, this._rdOptions);
  39446. } catch (error) {
  39447. this._onError(error);
  39448. }
  39449. return { files, depth, path };
  39450. }
  39451. async _formatEntry(dirent, path) {
  39452. let entry;
  39453. try {
  39454. const basename = this._isDirent ? dirent.name : dirent;
  39455. const fullPath = sysPath$3.resolve(sysPath$3.join(path, basename));
  39456. entry = { path: sysPath$3.relative(this._root, fullPath), fullPath, basename };
  39457. entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);
  39458. } catch (err) {
  39459. this._onError(err);
  39460. }
  39461. return entry;
  39462. }
  39463. _onError(err) {
  39464. if (isNormalFlowError(err) && !this.destroyed) {
  39465. this.emit('warn', err);
  39466. } else {
  39467. this.destroy(err);
  39468. }
  39469. }
  39470. async _getEntryType(entry) {
  39471. // entry may be undefined, because a warning or an error were emitted
  39472. // and the statsProp is undefined
  39473. const stats = entry && entry[this._statsProp];
  39474. if (!stats) {
  39475. return;
  39476. }
  39477. if (stats.isFile()) {
  39478. return 'file';
  39479. }
  39480. if (stats.isDirectory()) {
  39481. return 'directory';
  39482. }
  39483. if (stats && stats.isSymbolicLink()) {
  39484. const full = entry.fullPath;
  39485. try {
  39486. const entryRealPath = await realpath$1(full);
  39487. const entryRealPathStats = await lstat$2(entryRealPath);
  39488. if (entryRealPathStats.isFile()) {
  39489. return 'file';
  39490. }
  39491. if (entryRealPathStats.isDirectory()) {
  39492. const len = entryRealPath.length;
  39493. if (full.startsWith(entryRealPath) && full.substr(len, 1) === sysPath$3.sep) {
  39494. const recursiveError = new Error(
  39495. `Circular symlink detected: "${full}" points to "${entryRealPath}"`
  39496. );
  39497. recursiveError.code = RECURSIVE_ERROR_CODE;
  39498. return this._onError(recursiveError);
  39499. }
  39500. return 'directory';
  39501. }
  39502. } catch (error) {
  39503. this._onError(error);
  39504. }
  39505. }
  39506. }
  39507. _includeAsFile(entry) {
  39508. const stats = entry && entry[this._statsProp];
  39509. return stats && this._wantsEverything && !stats.isDirectory();
  39510. }
  39511. }
  39512. /**
  39513. * @typedef {Object} ReaddirpArguments
  39514. * @property {Function=} fileFilter
  39515. * @property {Function=} directoryFilter
  39516. * @property {String=} type
  39517. * @property {Number=} depth
  39518. * @property {String=} root
  39519. * @property {Boolean=} lstat
  39520. * @property {Boolean=} bigint
  39521. */
  39522. /**
  39523. * Main function which ends up calling readdirRec and reads all files and directories in given root recursively.
  39524. * @param {String} root Root directory
  39525. * @param {ReaddirpArguments=} options Options to specify root (start directory), filters and recursion depth
  39526. */
  39527. const readdirp$1 = (root, options = {}) => {
  39528. let type = options.entryType || options.type;
  39529. if (type === 'both') type = FILE_DIR_TYPE; // backwards-compatibility
  39530. if (type) options.type = type;
  39531. if (!root) {
  39532. throw new Error('readdirp: root argument is required. Usage: readdirp(root, options)');
  39533. } else if (typeof root !== 'string') {
  39534. throw new TypeError('readdirp: root argument must be a string. Usage: readdirp(root, options)');
  39535. } else if (type && !ALL_TYPES.includes(type)) {
  39536. throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(', ')}`);
  39537. }
  39538. options.root = root;
  39539. return new ReaddirpStream(options);
  39540. };
  39541. const readdirpPromise = (root, options = {}) => {
  39542. return new Promise((resolve, reject) => {
  39543. const files = [];
  39544. readdirp$1(root, options)
  39545. .on('data', entry => files.push(entry))
  39546. .on('end', () => resolve(files))
  39547. .on('error', error => reject(error));
  39548. });
  39549. };
  39550. readdirp$1.promise = readdirpPromise;
  39551. readdirp$1.ReaddirpStream = ReaddirpStream;
  39552. readdirp$1.default = readdirp$1;
  39553. var readdirp_1 = readdirp$1;
  39554. var anymatch$2 = {exports: {}};
  39555. /*!
  39556. * normalize-path <https://github.com/jonschlinkert/normalize-path>
  39557. *
  39558. * Copyright (c) 2014-2018, Jon Schlinkert.
  39559. * Released under the MIT License.
  39560. */
  39561. var normalizePath$2 = function(path, stripTrailing) {
  39562. if (typeof path !== 'string') {
  39563. throw new TypeError('expected path to be a string');
  39564. }
  39565. if (path === '\\' || path === '/') return '/';
  39566. var len = path.length;
  39567. if (len <= 1) return path;
  39568. // ensure that win32 namespaces has two leading slashes, so that the path is
  39569. // handled properly by the win32 version of path.parse() after being normalized
  39570. // https://msdn.microsoft.com/library/windows/desktop/aa365247(v=vs.85).aspx#namespaces
  39571. var prefix = '';
  39572. if (len > 4 && path[3] === '\\') {
  39573. var ch = path[2];
  39574. if ((ch === '?' || ch === '.') && path.slice(0, 2) === '\\\\') {
  39575. path = path.slice(2);
  39576. prefix = '//';
  39577. }
  39578. }
  39579. var segs = path.split(/[/\\]+/);
  39580. if (stripTrailing !== false && segs[segs.length - 1] === '') {
  39581. segs.pop();
  39582. }
  39583. return prefix + segs.join('/');
  39584. };
  39585. Object.defineProperty(anymatch$2.exports, "__esModule", { value: true });
  39586. const picomatch$1 = picomatch$6;
  39587. const normalizePath$1 = normalizePath$2;
  39588. /**
  39589. * @typedef {(testString: string) => boolean} AnymatchFn
  39590. * @typedef {string|RegExp|AnymatchFn} AnymatchPattern
  39591. * @typedef {AnymatchPattern|AnymatchPattern[]} AnymatchMatcher
  39592. */
  39593. const BANG$1 = '!';
  39594. const DEFAULT_OPTIONS = {returnIndex: false};
  39595. const arrify$1 = (item) => Array.isArray(item) ? item : [item];
  39596. /**
  39597. * @param {AnymatchPattern} matcher
  39598. * @param {object} options
  39599. * @returns {AnymatchFn}
  39600. */
  39601. const createPattern = (matcher, options) => {
  39602. if (typeof matcher === 'function') {
  39603. return matcher;
  39604. }
  39605. if (typeof matcher === 'string') {
  39606. const glob = picomatch$1(matcher, options);
  39607. return (string) => matcher === string || glob(string);
  39608. }
  39609. if (matcher instanceof RegExp) {
  39610. return (string) => matcher.test(string);
  39611. }
  39612. return (string) => false;
  39613. };
  39614. /**
  39615. * @param {Array<Function>} patterns
  39616. * @param {Array<Function>} negPatterns
  39617. * @param {String|Array} args
  39618. * @param {Boolean} returnIndex
  39619. * @returns {boolean|number}
  39620. */
  39621. const matchPatterns = (patterns, negPatterns, args, returnIndex) => {
  39622. const isList = Array.isArray(args);
  39623. const _path = isList ? args[0] : args;
  39624. if (!isList && typeof _path !== 'string') {
  39625. throw new TypeError('anymatch: second argument must be a string: got ' +
  39626. Object.prototype.toString.call(_path))
  39627. }
  39628. const path = normalizePath$1(_path);
  39629. for (let index = 0; index < negPatterns.length; index++) {
  39630. const nglob = negPatterns[index];
  39631. if (nglob(path)) {
  39632. return returnIndex ? -1 : false;
  39633. }
  39634. }
  39635. const applied = isList && [path].concat(args.slice(1));
  39636. for (let index = 0; index < patterns.length; index++) {
  39637. const pattern = patterns[index];
  39638. if (isList ? pattern(...applied) : pattern(path)) {
  39639. return returnIndex ? index : true;
  39640. }
  39641. }
  39642. return returnIndex ? -1 : false;
  39643. };
  39644. /**
  39645. * @param {AnymatchMatcher} matchers
  39646. * @param {Array|string} testString
  39647. * @param {object} options
  39648. * @returns {boolean|number|Function}
  39649. */
  39650. const anymatch$1 = (matchers, testString, options = DEFAULT_OPTIONS) => {
  39651. if (matchers == null) {
  39652. throw new TypeError('anymatch: specify first argument');
  39653. }
  39654. const opts = typeof options === 'boolean' ? {returnIndex: options} : options;
  39655. const returnIndex = opts.returnIndex || false;
  39656. // Early cache for matchers.
  39657. const mtchers = arrify$1(matchers);
  39658. const negatedGlobs = mtchers
  39659. .filter(item => typeof item === 'string' && item.charAt(0) === BANG$1)
  39660. .map(item => item.slice(1))
  39661. .map(item => picomatch$1(item, opts));
  39662. const patterns = mtchers
  39663. .filter(item => typeof item !== 'string' || (typeof item === 'string' && item.charAt(0) !== BANG$1))
  39664. .map(matcher => createPattern(matcher, opts));
  39665. if (testString == null) {
  39666. return (testString, ri = false) => {
  39667. const returnIndex = typeof ri === 'boolean' ? ri : false;
  39668. return matchPatterns(patterns, negatedGlobs, testString, returnIndex);
  39669. }
  39670. }
  39671. return matchPatterns(patterns, negatedGlobs, testString, returnIndex);
  39672. };
  39673. anymatch$1.default = anymatch$1;
  39674. anymatch$2.exports = anymatch$1;
  39675. var require$$0 = [
  39676. "3dm",
  39677. "3ds",
  39678. "3g2",
  39679. "3gp",
  39680. "7z",
  39681. "a",
  39682. "aac",
  39683. "adp",
  39684. "ai",
  39685. "aif",
  39686. "aiff",
  39687. "alz",
  39688. "ape",
  39689. "apk",
  39690. "appimage",
  39691. "ar",
  39692. "arj",
  39693. "asf",
  39694. "au",
  39695. "avi",
  39696. "bak",
  39697. "baml",
  39698. "bh",
  39699. "bin",
  39700. "bk",
  39701. "bmp",
  39702. "btif",
  39703. "bz2",
  39704. "bzip2",
  39705. "cab",
  39706. "caf",
  39707. "cgm",
  39708. "class",
  39709. "cmx",
  39710. "cpio",
  39711. "cr2",
  39712. "cur",
  39713. "dat",
  39714. "dcm",
  39715. "deb",
  39716. "dex",
  39717. "djvu",
  39718. "dll",
  39719. "dmg",
  39720. "dng",
  39721. "doc",
  39722. "docm",
  39723. "docx",
  39724. "dot",
  39725. "dotm",
  39726. "dra",
  39727. "DS_Store",
  39728. "dsk",
  39729. "dts",
  39730. "dtshd",
  39731. "dvb",
  39732. "dwg",
  39733. "dxf",
  39734. "ecelp4800",
  39735. "ecelp7470",
  39736. "ecelp9600",
  39737. "egg",
  39738. "eol",
  39739. "eot",
  39740. "epub",
  39741. "exe",
  39742. "f4v",
  39743. "fbs",
  39744. "fh",
  39745. "fla",
  39746. "flac",
  39747. "flatpak",
  39748. "fli",
  39749. "flv",
  39750. "fpx",
  39751. "fst",
  39752. "fvt",
  39753. "g3",
  39754. "gh",
  39755. "gif",
  39756. "graffle",
  39757. "gz",
  39758. "gzip",
  39759. "h261",
  39760. "h263",
  39761. "h264",
  39762. "icns",
  39763. "ico",
  39764. "ief",
  39765. "img",
  39766. "ipa",
  39767. "iso",
  39768. "jar",
  39769. "jpeg",
  39770. "jpg",
  39771. "jpgv",
  39772. "jpm",
  39773. "jxr",
  39774. "key",
  39775. "ktx",
  39776. "lha",
  39777. "lib",
  39778. "lvp",
  39779. "lz",
  39780. "lzh",
  39781. "lzma",
  39782. "lzo",
  39783. "m3u",
  39784. "m4a",
  39785. "m4v",
  39786. "mar",
  39787. "mdi",
  39788. "mht",
  39789. "mid",
  39790. "midi",
  39791. "mj2",
  39792. "mka",
  39793. "mkv",
  39794. "mmr",
  39795. "mng",
  39796. "mobi",
  39797. "mov",
  39798. "movie",
  39799. "mp3",
  39800. "mp4",
  39801. "mp4a",
  39802. "mpeg",
  39803. "mpg",
  39804. "mpga",
  39805. "mxu",
  39806. "nef",
  39807. "npx",
  39808. "numbers",
  39809. "nupkg",
  39810. "o",
  39811. "odp",
  39812. "ods",
  39813. "odt",
  39814. "oga",
  39815. "ogg",
  39816. "ogv",
  39817. "otf",
  39818. "ott",
  39819. "pages",
  39820. "pbm",
  39821. "pcx",
  39822. "pdb",
  39823. "pdf",
  39824. "pea",
  39825. "pgm",
  39826. "pic",
  39827. "png",
  39828. "pnm",
  39829. "pot",
  39830. "potm",
  39831. "potx",
  39832. "ppa",
  39833. "ppam",
  39834. "ppm",
  39835. "pps",
  39836. "ppsm",
  39837. "ppsx",
  39838. "ppt",
  39839. "pptm",
  39840. "pptx",
  39841. "psd",
  39842. "pya",
  39843. "pyc",
  39844. "pyo",
  39845. "pyv",
  39846. "qt",
  39847. "rar",
  39848. "ras",
  39849. "raw",
  39850. "resources",
  39851. "rgb",
  39852. "rip",
  39853. "rlc",
  39854. "rmf",
  39855. "rmvb",
  39856. "rpm",
  39857. "rtf",
  39858. "rz",
  39859. "s3m",
  39860. "s7z",
  39861. "scpt",
  39862. "sgi",
  39863. "shar",
  39864. "snap",
  39865. "sil",
  39866. "sketch",
  39867. "slk",
  39868. "smv",
  39869. "snk",
  39870. "so",
  39871. "stl",
  39872. "suo",
  39873. "sub",
  39874. "swf",
  39875. "tar",
  39876. "tbz",
  39877. "tbz2",
  39878. "tga",
  39879. "tgz",
  39880. "thmx",
  39881. "tif",
  39882. "tiff",
  39883. "tlz",
  39884. "ttc",
  39885. "ttf",
  39886. "txz",
  39887. "udf",
  39888. "uvh",
  39889. "uvi",
  39890. "uvm",
  39891. "uvp",
  39892. "uvs",
  39893. "uvu",
  39894. "viv",
  39895. "vob",
  39896. "war",
  39897. "wav",
  39898. "wax",
  39899. "wbmp",
  39900. "wdp",
  39901. "weba",
  39902. "webm",
  39903. "webp",
  39904. "whl",
  39905. "wim",
  39906. "wm",
  39907. "wma",
  39908. "wmv",
  39909. "wmx",
  39910. "woff",
  39911. "woff2",
  39912. "wrm",
  39913. "wvx",
  39914. "xbm",
  39915. "xif",
  39916. "xla",
  39917. "xlam",
  39918. "xls",
  39919. "xlsb",
  39920. "xlsm",
  39921. "xlsx",
  39922. "xlt",
  39923. "xltm",
  39924. "xltx",
  39925. "xm",
  39926. "xmind",
  39927. "xpi",
  39928. "xpm",
  39929. "xwd",
  39930. "xz",
  39931. "z",
  39932. "zip",
  39933. "zipx"
  39934. ];
  39935. var binaryExtensions$1 = require$$0;
  39936. const path$8 = path__default;
  39937. const binaryExtensions = binaryExtensions$1;
  39938. const extensions = new Set(binaryExtensions);
  39939. var isBinaryPath$1 = filePath => extensions.has(path$8.extname(filePath).slice(1).toLowerCase());
  39940. var constants$1 = {};
  39941. (function (exports) {
  39942. const {sep} = path__default;
  39943. const {platform} = process;
  39944. const os = require$$2__default;
  39945. exports.EV_ALL = 'all';
  39946. exports.EV_READY = 'ready';
  39947. exports.EV_ADD = 'add';
  39948. exports.EV_CHANGE = 'change';
  39949. exports.EV_ADD_DIR = 'addDir';
  39950. exports.EV_UNLINK = 'unlink';
  39951. exports.EV_UNLINK_DIR = 'unlinkDir';
  39952. exports.EV_RAW = 'raw';
  39953. exports.EV_ERROR = 'error';
  39954. exports.STR_DATA = 'data';
  39955. exports.STR_END = 'end';
  39956. exports.STR_CLOSE = 'close';
  39957. exports.FSEVENT_CREATED = 'created';
  39958. exports.FSEVENT_MODIFIED = 'modified';
  39959. exports.FSEVENT_DELETED = 'deleted';
  39960. exports.FSEVENT_MOVED = 'moved';
  39961. exports.FSEVENT_CLONED = 'cloned';
  39962. exports.FSEVENT_UNKNOWN = 'unknown';
  39963. exports.FSEVENT_TYPE_FILE = 'file';
  39964. exports.FSEVENT_TYPE_DIRECTORY = 'directory';
  39965. exports.FSEVENT_TYPE_SYMLINK = 'symlink';
  39966. exports.KEY_LISTENERS = 'listeners';
  39967. exports.KEY_ERR = 'errHandlers';
  39968. exports.KEY_RAW = 'rawEmitters';
  39969. exports.HANDLER_KEYS = [exports.KEY_LISTENERS, exports.KEY_ERR, exports.KEY_RAW];
  39970. exports.DOT_SLASH = `.${sep}`;
  39971. exports.BACK_SLASH_RE = /\\/g;
  39972. exports.DOUBLE_SLASH_RE = /\/\//;
  39973. exports.SLASH_OR_BACK_SLASH_RE = /[/\\]/;
  39974. exports.DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/;
  39975. exports.REPLACER_RE = /^\.[/\\]/;
  39976. exports.SLASH = '/';
  39977. exports.SLASH_SLASH = '//';
  39978. exports.BRACE_START = '{';
  39979. exports.BANG = '!';
  39980. exports.ONE_DOT = '.';
  39981. exports.TWO_DOTS = '..';
  39982. exports.STAR = '*';
  39983. exports.GLOBSTAR = '**';
  39984. exports.ROOT_GLOBSTAR = '/**/*';
  39985. exports.SLASH_GLOBSTAR = '/**';
  39986. exports.DIR_SUFFIX = 'Dir';
  39987. exports.ANYMATCH_OPTS = {dot: true};
  39988. exports.STRING_TYPE = 'string';
  39989. exports.FUNCTION_TYPE = 'function';
  39990. exports.EMPTY_STR = '';
  39991. exports.EMPTY_FN = () => {};
  39992. exports.IDENTITY_FN = val => val;
  39993. exports.isWindows = platform === 'win32';
  39994. exports.isMacos = platform === 'darwin';
  39995. exports.isLinux = platform === 'linux';
  39996. exports.isIBMi = os.type() === 'OS400';
  39997. }(constants$1));
  39998. const fs$9 = fs__default;
  39999. const sysPath$2 = path__default;
  40000. const { promisify: promisify$2 } = require$$0__default$2;
  40001. const isBinaryPath = isBinaryPath$1;
  40002. const {
  40003. isWindows: isWindows$2,
  40004. isLinux,
  40005. EMPTY_FN: EMPTY_FN$2,
  40006. EMPTY_STR: EMPTY_STR$1,
  40007. KEY_LISTENERS,
  40008. KEY_ERR,
  40009. KEY_RAW,
  40010. HANDLER_KEYS,
  40011. EV_CHANGE: EV_CHANGE$2,
  40012. EV_ADD: EV_ADD$2,
  40013. EV_ADD_DIR: EV_ADD_DIR$2,
  40014. EV_ERROR: EV_ERROR$2,
  40015. STR_DATA: STR_DATA$1,
  40016. STR_END: STR_END$2,
  40017. BRACE_START: BRACE_START$1,
  40018. STAR
  40019. } = constants$1;
  40020. const THROTTLE_MODE_WATCH = 'watch';
  40021. const open$1 = promisify$2(fs$9.open);
  40022. const stat$2 = promisify$2(fs$9.stat);
  40023. const lstat$1 = promisify$2(fs$9.lstat);
  40024. const close = promisify$2(fs$9.close);
  40025. const fsrealpath = promisify$2(fs$9.realpath);
  40026. const statMethods$1 = { lstat: lstat$1, stat: stat$2 };
  40027. // TODO: emit errors properly. Example: EMFILE on Macos.
  40028. const foreach = (val, fn) => {
  40029. if (val instanceof Set) {
  40030. val.forEach(fn);
  40031. } else {
  40032. fn(val);
  40033. }
  40034. };
  40035. const addAndConvert = (main, prop, item) => {
  40036. let container = main[prop];
  40037. if (!(container instanceof Set)) {
  40038. main[prop] = container = new Set([container]);
  40039. }
  40040. container.add(item);
  40041. };
  40042. const clearItem = cont => key => {
  40043. const set = cont[key];
  40044. if (set instanceof Set) {
  40045. set.clear();
  40046. } else {
  40047. delete cont[key];
  40048. }
  40049. };
  40050. const delFromSet = (main, prop, item) => {
  40051. const container = main[prop];
  40052. if (container instanceof Set) {
  40053. container.delete(item);
  40054. } else if (container === item) {
  40055. delete main[prop];
  40056. }
  40057. };
  40058. const isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val;
  40059. /**
  40060. * @typedef {String} Path
  40061. */
  40062. // fs_watch helpers
  40063. // object to hold per-process fs_watch instances
  40064. // (may be shared across chokidar FSWatcher instances)
  40065. /**
  40066. * @typedef {Object} FsWatchContainer
  40067. * @property {Set} listeners
  40068. * @property {Set} errHandlers
  40069. * @property {Set} rawEmitters
  40070. * @property {fs.FSWatcher=} watcher
  40071. * @property {Boolean=} watcherUnusable
  40072. */
  40073. /**
  40074. * @type {Map<String,FsWatchContainer>}
  40075. */
  40076. const FsWatchInstances = new Map();
  40077. /**
  40078. * Instantiates the fs_watch interface
  40079. * @param {String} path to be watched
  40080. * @param {Object} options to be passed to fs_watch
  40081. * @param {Function} listener main event handler
  40082. * @param {Function} errHandler emits info about errors
  40083. * @param {Function} emitRaw emits raw event data
  40084. * @returns {fs.FSWatcher} new fsevents instance
  40085. */
  40086. function createFsWatchInstance(path, options, listener, errHandler, emitRaw) {
  40087. const handleEvent = (rawEvent, evPath) => {
  40088. listener(path);
  40089. emitRaw(rawEvent, evPath, {watchedPath: path});
  40090. // emit based on events occurring for files from a directory's watcher in
  40091. // case the file's watcher misses it (and rely on throttling to de-dupe)
  40092. if (evPath && path !== evPath) {
  40093. fsWatchBroadcast(
  40094. sysPath$2.resolve(path, evPath), KEY_LISTENERS, sysPath$2.join(path, evPath)
  40095. );
  40096. }
  40097. };
  40098. try {
  40099. return fs$9.watch(path, options, handleEvent);
  40100. } catch (error) {
  40101. errHandler(error);
  40102. }
  40103. }
  40104. /**
  40105. * Helper for passing fs_watch event data to a collection of listeners
  40106. * @param {Path} fullPath absolute path bound to fs_watch instance
  40107. * @param {String} type listener type
  40108. * @param {*=} val1 arguments to be passed to listeners
  40109. * @param {*=} val2
  40110. * @param {*=} val3
  40111. */
  40112. const fsWatchBroadcast = (fullPath, type, val1, val2, val3) => {
  40113. const cont = FsWatchInstances.get(fullPath);
  40114. if (!cont) return;
  40115. foreach(cont[type], (listener) => {
  40116. listener(val1, val2, val3);
  40117. });
  40118. };
  40119. /**
  40120. * Instantiates the fs_watch interface or binds listeners
  40121. * to an existing one covering the same file system entry
  40122. * @param {String} path
  40123. * @param {String} fullPath absolute path
  40124. * @param {Object} options to be passed to fs_watch
  40125. * @param {Object} handlers container for event listener functions
  40126. */
  40127. const setFsWatchListener = (path, fullPath, options, handlers) => {
  40128. const {listener, errHandler, rawEmitter} = handlers;
  40129. let cont = FsWatchInstances.get(fullPath);
  40130. /** @type {fs.FSWatcher=} */
  40131. let watcher;
  40132. if (!options.persistent) {
  40133. watcher = createFsWatchInstance(
  40134. path, options, listener, errHandler, rawEmitter
  40135. );
  40136. return watcher.close.bind(watcher);
  40137. }
  40138. if (cont) {
  40139. addAndConvert(cont, KEY_LISTENERS, listener);
  40140. addAndConvert(cont, KEY_ERR, errHandler);
  40141. addAndConvert(cont, KEY_RAW, rawEmitter);
  40142. } else {
  40143. watcher = createFsWatchInstance(
  40144. path,
  40145. options,
  40146. fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS),
  40147. errHandler, // no need to use broadcast here
  40148. fsWatchBroadcast.bind(null, fullPath, KEY_RAW)
  40149. );
  40150. if (!watcher) return;
  40151. watcher.on(EV_ERROR$2, async (error) => {
  40152. const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
  40153. cont.watcherUnusable = true; // documented since Node 10.4.1
  40154. // Workaround for https://github.com/joyent/node/issues/4337
  40155. if (isWindows$2 && error.code === 'EPERM') {
  40156. try {
  40157. const fd = await open$1(path, 'r');
  40158. await close(fd);
  40159. broadcastErr(error);
  40160. } catch (err) {}
  40161. } else {
  40162. broadcastErr(error);
  40163. }
  40164. });
  40165. cont = {
  40166. listeners: listener,
  40167. errHandlers: errHandler,
  40168. rawEmitters: rawEmitter,
  40169. watcher
  40170. };
  40171. FsWatchInstances.set(fullPath, cont);
  40172. }
  40173. // const index = cont.listeners.indexOf(listener);
  40174. // removes this instance's listeners and closes the underlying fs_watch
  40175. // instance if there are no more listeners left
  40176. return () => {
  40177. delFromSet(cont, KEY_LISTENERS, listener);
  40178. delFromSet(cont, KEY_ERR, errHandler);
  40179. delFromSet(cont, KEY_RAW, rawEmitter);
  40180. if (isEmptySet(cont.listeners)) {
  40181. // Check to protect against issue gh-730.
  40182. // if (cont.watcherUnusable) {
  40183. cont.watcher.close();
  40184. // }
  40185. FsWatchInstances.delete(fullPath);
  40186. HANDLER_KEYS.forEach(clearItem(cont));
  40187. cont.watcher = undefined;
  40188. Object.freeze(cont);
  40189. }
  40190. };
  40191. };
  40192. // fs_watchFile helpers
  40193. // object to hold per-process fs_watchFile instances
  40194. // (may be shared across chokidar FSWatcher instances)
  40195. const FsWatchFileInstances = new Map();
  40196. /**
  40197. * Instantiates the fs_watchFile interface or binds listeners
  40198. * to an existing one covering the same file system entry
  40199. * @param {String} path to be watched
  40200. * @param {String} fullPath absolute path
  40201. * @param {Object} options options to be passed to fs_watchFile
  40202. * @param {Object} handlers container for event listener functions
  40203. * @returns {Function} closer
  40204. */
  40205. const setFsWatchFileListener = (path, fullPath, options, handlers) => {
  40206. const {listener, rawEmitter} = handlers;
  40207. let cont = FsWatchFileInstances.get(fullPath);
  40208. const copts = cont && cont.options;
  40209. if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {
  40210. fs$9.unwatchFile(fullPath);
  40211. cont = undefined;
  40212. }
  40213. /* eslint-enable no-unused-vars, prefer-destructuring */
  40214. if (cont) {
  40215. addAndConvert(cont, KEY_LISTENERS, listener);
  40216. addAndConvert(cont, KEY_RAW, rawEmitter);
  40217. } else {
  40218. // TODO
  40219. // listeners.add(listener);
  40220. // rawEmitters.add(rawEmitter);
  40221. cont = {
  40222. listeners: listener,
  40223. rawEmitters: rawEmitter,
  40224. options,
  40225. watcher: fs$9.watchFile(fullPath, options, (curr, prev) => {
  40226. foreach(cont.rawEmitters, (rawEmitter) => {
  40227. rawEmitter(EV_CHANGE$2, fullPath, {curr, prev});
  40228. });
  40229. const currmtime = curr.mtimeMs;
  40230. if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {
  40231. foreach(cont.listeners, (listener) => listener(path, curr));
  40232. }
  40233. })
  40234. };
  40235. FsWatchFileInstances.set(fullPath, cont);
  40236. }
  40237. // const index = cont.listeners.indexOf(listener);
  40238. // Removes this instance's listeners and closes the underlying fs_watchFile
  40239. // instance if there are no more listeners left.
  40240. return () => {
  40241. delFromSet(cont, KEY_LISTENERS, listener);
  40242. delFromSet(cont, KEY_RAW, rawEmitter);
  40243. if (isEmptySet(cont.listeners)) {
  40244. FsWatchFileInstances.delete(fullPath);
  40245. fs$9.unwatchFile(fullPath);
  40246. cont.options = cont.watcher = undefined;
  40247. Object.freeze(cont);
  40248. }
  40249. };
  40250. };
  40251. /**
  40252. * @mixin
  40253. */
  40254. class NodeFsHandler$1 {
  40255. /**
  40256. * @param {import("../index").FSWatcher} fsW
  40257. */
  40258. constructor(fsW) {
  40259. this.fsw = fsW;
  40260. this._boundHandleError = (error) => fsW._handleError(error);
  40261. }
  40262. /**
  40263. * Watch file for changes with fs_watchFile or fs_watch.
  40264. * @param {String} path to file or dir
  40265. * @param {Function} listener on fs change
  40266. * @returns {Function} closer for the watcher instance
  40267. */
  40268. _watchWithNodeFs(path, listener) {
  40269. const opts = this.fsw.options;
  40270. const directory = sysPath$2.dirname(path);
  40271. const basename = sysPath$2.basename(path);
  40272. const parent = this.fsw._getWatchedDir(directory);
  40273. parent.add(basename);
  40274. const absolutePath = sysPath$2.resolve(path);
  40275. const options = {persistent: opts.persistent};
  40276. if (!listener) listener = EMPTY_FN$2;
  40277. let closer;
  40278. if (opts.usePolling) {
  40279. options.interval = opts.enableBinaryInterval && isBinaryPath(basename) ?
  40280. opts.binaryInterval : opts.interval;
  40281. closer = setFsWatchFileListener(path, absolutePath, options, {
  40282. listener,
  40283. rawEmitter: this.fsw._emitRaw
  40284. });
  40285. } else {
  40286. closer = setFsWatchListener(path, absolutePath, options, {
  40287. listener,
  40288. errHandler: this._boundHandleError,
  40289. rawEmitter: this.fsw._emitRaw
  40290. });
  40291. }
  40292. return closer;
  40293. }
  40294. /**
  40295. * Watch a file and emit add event if warranted.
  40296. * @param {Path} file Path
  40297. * @param {fs.Stats} stats result of fs_stat
  40298. * @param {Boolean} initialAdd was the file added at watch instantiation?
  40299. * @returns {Function} closer for the watcher instance
  40300. */
  40301. _handleFile(file, stats, initialAdd) {
  40302. if (this.fsw.closed) {
  40303. return;
  40304. }
  40305. const dirname = sysPath$2.dirname(file);
  40306. const basename = sysPath$2.basename(file);
  40307. const parent = this.fsw._getWatchedDir(dirname);
  40308. // stats is always present
  40309. let prevStats = stats;
  40310. // if the file is already being watched, do nothing
  40311. if (parent.has(basename)) return;
  40312. const listener = async (path, newStats) => {
  40313. if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5)) return;
  40314. if (!newStats || newStats.mtimeMs === 0) {
  40315. try {
  40316. const newStats = await stat$2(file);
  40317. if (this.fsw.closed) return;
  40318. // Check that change event was not fired because of changed only accessTime.
  40319. const at = newStats.atimeMs;
  40320. const mt = newStats.mtimeMs;
  40321. if (!at || at <= mt || mt !== prevStats.mtimeMs) {
  40322. this.fsw._emit(EV_CHANGE$2, file, newStats);
  40323. }
  40324. if (isLinux && prevStats.ino !== newStats.ino) {
  40325. this.fsw._closeFile(path);
  40326. prevStats = newStats;
  40327. this.fsw._addPathCloser(path, this._watchWithNodeFs(file, listener));
  40328. } else {
  40329. prevStats = newStats;
  40330. }
  40331. } catch (error) {
  40332. // Fix issues where mtime is null but file is still present
  40333. this.fsw._remove(dirname, basename);
  40334. }
  40335. // add is about to be emitted if file not already tracked in parent
  40336. } else if (parent.has(basename)) {
  40337. // Check that change event was not fired because of changed only accessTime.
  40338. const at = newStats.atimeMs;
  40339. const mt = newStats.mtimeMs;
  40340. if (!at || at <= mt || mt !== prevStats.mtimeMs) {
  40341. this.fsw._emit(EV_CHANGE$2, file, newStats);
  40342. }
  40343. prevStats = newStats;
  40344. }
  40345. };
  40346. // kick off the watcher
  40347. const closer = this._watchWithNodeFs(file, listener);
  40348. // emit an add event if we're supposed to
  40349. if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) {
  40350. if (!this.fsw._throttle(EV_ADD$2, file, 0)) return;
  40351. this.fsw._emit(EV_ADD$2, file, stats);
  40352. }
  40353. return closer;
  40354. }
  40355. /**
  40356. * Handle symlinks encountered while reading a dir.
  40357. * @param {Object} entry returned by readdirp
  40358. * @param {String} directory path of dir being read
  40359. * @param {String} path of this item
  40360. * @param {String} item basename of this item
  40361. * @returns {Promise<Boolean>} true if no more processing is needed for this entry.
  40362. */
  40363. async _handleSymlink(entry, directory, path, item) {
  40364. if (this.fsw.closed) {
  40365. return;
  40366. }
  40367. const full = entry.fullPath;
  40368. const dir = this.fsw._getWatchedDir(directory);
  40369. if (!this.fsw.options.followSymlinks) {
  40370. // watch symlink directly (don't follow) and detect changes
  40371. this.fsw._incrReadyCount();
  40372. let linkPath;
  40373. try {
  40374. linkPath = await fsrealpath(path);
  40375. } catch (e) {
  40376. this.fsw._emitReady();
  40377. return true;
  40378. }
  40379. if (this.fsw.closed) return;
  40380. if (dir.has(item)) {
  40381. if (this.fsw._symlinkPaths.get(full) !== linkPath) {
  40382. this.fsw._symlinkPaths.set(full, linkPath);
  40383. this.fsw._emit(EV_CHANGE$2, path, entry.stats);
  40384. }
  40385. } else {
  40386. dir.add(item);
  40387. this.fsw._symlinkPaths.set(full, linkPath);
  40388. this.fsw._emit(EV_ADD$2, path, entry.stats);
  40389. }
  40390. this.fsw._emitReady();
  40391. return true;
  40392. }
  40393. // don't follow the same symlink more than once
  40394. if (this.fsw._symlinkPaths.has(full)) {
  40395. return true;
  40396. }
  40397. this.fsw._symlinkPaths.set(full, true);
  40398. }
  40399. _handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {
  40400. // Normalize the directory name on Windows
  40401. directory = sysPath$2.join(directory, EMPTY_STR$1);
  40402. if (!wh.hasGlob) {
  40403. throttler = this.fsw._throttle('readdir', directory, 1000);
  40404. if (!throttler) return;
  40405. }
  40406. const previous = this.fsw._getWatchedDir(wh.path);
  40407. const current = new Set();
  40408. let stream = this.fsw._readdirp(directory, {
  40409. fileFilter: entry => wh.filterPath(entry),
  40410. directoryFilter: entry => wh.filterDir(entry),
  40411. depth: 0
  40412. }).on(STR_DATA$1, async (entry) => {
  40413. if (this.fsw.closed) {
  40414. stream = undefined;
  40415. return;
  40416. }
  40417. const item = entry.path;
  40418. let path = sysPath$2.join(directory, item);
  40419. current.add(item);
  40420. if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path, item)) {
  40421. return;
  40422. }
  40423. if (this.fsw.closed) {
  40424. stream = undefined;
  40425. return;
  40426. }
  40427. // Files that present in current directory snapshot
  40428. // but absent in previous are added to watch list and
  40429. // emit `add` event.
  40430. if (item === target || !target && !previous.has(item)) {
  40431. this.fsw._incrReadyCount();
  40432. // ensure relativeness of path is preserved in case of watcher reuse
  40433. path = sysPath$2.join(dir, sysPath$2.relative(dir, path));
  40434. this._addToNodeFs(path, initialAdd, wh, depth + 1);
  40435. }
  40436. }).on(EV_ERROR$2, this._boundHandleError);
  40437. return new Promise(resolve =>
  40438. stream.once(STR_END$2, () => {
  40439. if (this.fsw.closed) {
  40440. stream = undefined;
  40441. return;
  40442. }
  40443. const wasThrottled = throttler ? throttler.clear() : false;
  40444. resolve();
  40445. // Files that absent in current directory snapshot
  40446. // but present in previous emit `remove` event
  40447. // and are removed from @watched[directory].
  40448. previous.getChildren().filter((item) => {
  40449. return item !== directory &&
  40450. !current.has(item) &&
  40451. // in case of intersecting globs;
  40452. // a path may have been filtered out of this readdir, but
  40453. // shouldn't be removed because it matches a different glob
  40454. (!wh.hasGlob || wh.filterPath({
  40455. fullPath: sysPath$2.resolve(directory, item)
  40456. }));
  40457. }).forEach((item) => {
  40458. this.fsw._remove(directory, item);
  40459. });
  40460. stream = undefined;
  40461. // one more time for any missed in case changes came in extremely quickly
  40462. if (wasThrottled) this._handleRead(directory, false, wh, target, dir, depth, throttler);
  40463. })
  40464. );
  40465. }
  40466. /**
  40467. * Read directory to add / remove files from `@watched` list and re-read it on change.
  40468. * @param {String} dir fs path
  40469. * @param {fs.Stats} stats
  40470. * @param {Boolean} initialAdd
  40471. * @param {Number} depth relative to user-supplied path
  40472. * @param {String} target child path targeted for watch
  40473. * @param {Object} wh Common watch helpers for this path
  40474. * @param {String} realpath
  40475. * @returns {Promise<Function>} closer for the watcher instance.
  40476. */
  40477. async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath) {
  40478. const parentDir = this.fsw._getWatchedDir(sysPath$2.dirname(dir));
  40479. const tracked = parentDir.has(sysPath$2.basename(dir));
  40480. if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {
  40481. if (!wh.hasGlob || wh.globFilter(dir)) this.fsw._emit(EV_ADD_DIR$2, dir, stats);
  40482. }
  40483. // ensure dir is tracked (harmless if redundant)
  40484. parentDir.add(sysPath$2.basename(dir));
  40485. this.fsw._getWatchedDir(dir);
  40486. let throttler;
  40487. let closer;
  40488. const oDepth = this.fsw.options.depth;
  40489. if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath)) {
  40490. if (!target) {
  40491. await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);
  40492. if (this.fsw.closed) return;
  40493. }
  40494. closer = this._watchWithNodeFs(dir, (dirPath, stats) => {
  40495. // if current directory is removed, do nothing
  40496. if (stats && stats.mtimeMs === 0) return;
  40497. this._handleRead(dirPath, false, wh, target, dir, depth, throttler);
  40498. });
  40499. }
  40500. return closer;
  40501. }
  40502. /**
  40503. * Handle added file, directory, or glob pattern.
  40504. * Delegates call to _handleFile / _handleDir after checks.
  40505. * @param {String} path to file or ir
  40506. * @param {Boolean} initialAdd was the file added at watch instantiation?
  40507. * @param {Object} priorWh depth relative to user-supplied path
  40508. * @param {Number} depth Child path actually targeted for watch
  40509. * @param {String=} target Child path actually targeted for watch
  40510. * @returns {Promise}
  40511. */
  40512. async _addToNodeFs(path, initialAdd, priorWh, depth, target) {
  40513. const ready = this.fsw._emitReady;
  40514. if (this.fsw._isIgnored(path) || this.fsw.closed) {
  40515. ready();
  40516. return false;
  40517. }
  40518. const wh = this.fsw._getWatchHelpers(path, depth);
  40519. if (!wh.hasGlob && priorWh) {
  40520. wh.hasGlob = priorWh.hasGlob;
  40521. wh.globFilter = priorWh.globFilter;
  40522. wh.filterPath = entry => priorWh.filterPath(entry);
  40523. wh.filterDir = entry => priorWh.filterDir(entry);
  40524. }
  40525. // evaluate what is at the path we're being asked to watch
  40526. try {
  40527. const stats = await statMethods$1[wh.statMethod](wh.watchPath);
  40528. if (this.fsw.closed) return;
  40529. if (this.fsw._isIgnored(wh.watchPath, stats)) {
  40530. ready();
  40531. return false;
  40532. }
  40533. const follow = this.fsw.options.followSymlinks && !path.includes(STAR) && !path.includes(BRACE_START$1);
  40534. let closer;
  40535. if (stats.isDirectory()) {
  40536. const absPath = sysPath$2.resolve(path);
  40537. const targetPath = follow ? await fsrealpath(path) : path;
  40538. if (this.fsw.closed) return;
  40539. closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
  40540. if (this.fsw.closed) return;
  40541. // preserve this symlink's target path
  40542. if (absPath !== targetPath && targetPath !== undefined) {
  40543. this.fsw._symlinkPaths.set(absPath, targetPath);
  40544. }
  40545. } else if (stats.isSymbolicLink()) {
  40546. const targetPath = follow ? await fsrealpath(path) : path;
  40547. if (this.fsw.closed) return;
  40548. const parent = sysPath$2.dirname(wh.watchPath);
  40549. this.fsw._getWatchedDir(parent).add(wh.watchPath);
  40550. this.fsw._emit(EV_ADD$2, wh.watchPath, stats);
  40551. closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath);
  40552. if (this.fsw.closed) return;
  40553. // preserve this symlink's target path
  40554. if (targetPath !== undefined) {
  40555. this.fsw._symlinkPaths.set(sysPath$2.resolve(path), targetPath);
  40556. }
  40557. } else {
  40558. closer = this._handleFile(wh.watchPath, stats, initialAdd);
  40559. }
  40560. ready();
  40561. this.fsw._addPathCloser(path, closer);
  40562. return false;
  40563. } catch (error) {
  40564. if (this.fsw._handleError(error)) {
  40565. ready();
  40566. return path;
  40567. }
  40568. }
  40569. }
  40570. }
  40571. var nodefsHandler = NodeFsHandler$1;
  40572. var fseventsHandler = {exports: {}};
  40573. const fs$8 = fs__default;
  40574. const sysPath$1 = path__default;
  40575. const { promisify: promisify$1 } = require$$0__default$2;
  40576. let fsevents;
  40577. try {
  40578. fsevents = eval('require')('fsevents');
  40579. } catch (error) {
  40580. if (process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR) console.error(error);
  40581. }
  40582. if (fsevents) {
  40583. // TODO: real check
  40584. const mtch = process.version.match(/v(\d+)\.(\d+)/);
  40585. if (mtch && mtch[1] && mtch[2]) {
  40586. const maj = Number.parseInt(mtch[1], 10);
  40587. const min = Number.parseInt(mtch[2], 10);
  40588. if (maj === 8 && min < 16) {
  40589. fsevents = undefined;
  40590. }
  40591. }
  40592. }
  40593. const {
  40594. EV_ADD: EV_ADD$1,
  40595. EV_CHANGE: EV_CHANGE$1,
  40596. EV_ADD_DIR: EV_ADD_DIR$1,
  40597. EV_UNLINK: EV_UNLINK$1,
  40598. EV_ERROR: EV_ERROR$1,
  40599. STR_DATA,
  40600. STR_END: STR_END$1,
  40601. FSEVENT_CREATED,
  40602. FSEVENT_MODIFIED,
  40603. FSEVENT_DELETED,
  40604. FSEVENT_MOVED,
  40605. // FSEVENT_CLONED,
  40606. FSEVENT_UNKNOWN,
  40607. FSEVENT_TYPE_FILE,
  40608. FSEVENT_TYPE_DIRECTORY,
  40609. FSEVENT_TYPE_SYMLINK,
  40610. ROOT_GLOBSTAR,
  40611. DIR_SUFFIX,
  40612. DOT_SLASH,
  40613. FUNCTION_TYPE: FUNCTION_TYPE$1,
  40614. EMPTY_FN: EMPTY_FN$1,
  40615. IDENTITY_FN
  40616. } = constants$1;
  40617. const Depth = (value) => isNaN(value) ? {} : {depth: value};
  40618. const stat$1 = promisify$1(fs$8.stat);
  40619. const lstat = promisify$1(fs$8.lstat);
  40620. const realpath = promisify$1(fs$8.realpath);
  40621. const statMethods = { stat: stat$1, lstat };
  40622. /**
  40623. * @typedef {String} Path
  40624. */
  40625. /**
  40626. * @typedef {Object} FsEventsWatchContainer
  40627. * @property {Set<Function>} listeners
  40628. * @property {Function} rawEmitter
  40629. * @property {{stop: Function}} watcher
  40630. */
  40631. // fsevents instance helper functions
  40632. /**
  40633. * Object to hold per-process fsevents instances (may be shared across chokidar FSWatcher instances)
  40634. * @type {Map<Path,FsEventsWatchContainer>}
  40635. */
  40636. const FSEventsWatchers = new Map();
  40637. // Threshold of duplicate path prefixes at which to start
  40638. // consolidating going forward
  40639. const consolidateThreshhold = 10;
  40640. const wrongEventFlags = new Set([
  40641. 69888, 70400, 71424, 72704, 73472, 131328, 131840, 262912
  40642. ]);
  40643. /**
  40644. * Instantiates the fsevents interface
  40645. * @param {Path} path path to be watched
  40646. * @param {Function} callback called when fsevents is bound and ready
  40647. * @returns {{stop: Function}} new fsevents instance
  40648. */
  40649. const createFSEventsInstance = (path, callback) => {
  40650. const stop = fsevents.watch(path, callback);
  40651. return {stop};
  40652. };
  40653. /**
  40654. * Instantiates the fsevents interface or binds listeners to an existing one covering
  40655. * the same file tree.
  40656. * @param {Path} path - to be watched
  40657. * @param {Path} realPath - real path for symlinks
  40658. * @param {Function} listener - called when fsevents emits events
  40659. * @param {Function} rawEmitter - passes data to listeners of the 'raw' event
  40660. * @returns {Function} closer
  40661. */
  40662. function setFSEventsListener(path, realPath, listener, rawEmitter) {
  40663. let watchPath = sysPath$1.extname(realPath) ? sysPath$1.dirname(realPath) : realPath;
  40664. const parentPath = sysPath$1.dirname(watchPath);
  40665. let cont = FSEventsWatchers.get(watchPath);
  40666. // If we've accumulated a substantial number of paths that
  40667. // could have been consolidated by watching one directory
  40668. // above the current one, create a watcher on the parent
  40669. // path instead, so that we do consolidate going forward.
  40670. if (couldConsolidate(parentPath)) {
  40671. watchPath = parentPath;
  40672. }
  40673. const resolvedPath = sysPath$1.resolve(path);
  40674. const hasSymlink = resolvedPath !== realPath;
  40675. const filteredListener = (fullPath, flags, info) => {
  40676. if (hasSymlink) fullPath = fullPath.replace(realPath, resolvedPath);
  40677. if (
  40678. fullPath === resolvedPath ||
  40679. !fullPath.indexOf(resolvedPath + sysPath$1.sep)
  40680. ) listener(fullPath, flags, info);
  40681. };
  40682. // check if there is already a watcher on a parent path
  40683. // modifies `watchPath` to the parent path when it finds a match
  40684. let watchedParent = false;
  40685. for (const watchedPath of FSEventsWatchers.keys()) {
  40686. if (realPath.indexOf(sysPath$1.resolve(watchedPath) + sysPath$1.sep) === 0) {
  40687. watchPath = watchedPath;
  40688. cont = FSEventsWatchers.get(watchPath);
  40689. watchedParent = true;
  40690. break;
  40691. }
  40692. }
  40693. if (cont || watchedParent) {
  40694. cont.listeners.add(filteredListener);
  40695. } else {
  40696. cont = {
  40697. listeners: new Set([filteredListener]),
  40698. rawEmitter,
  40699. watcher: createFSEventsInstance(watchPath, (fullPath, flags) => {
  40700. if (!cont.listeners.size) return;
  40701. const info = fsevents.getInfo(fullPath, flags);
  40702. cont.listeners.forEach(list => {
  40703. list(fullPath, flags, info);
  40704. });
  40705. cont.rawEmitter(info.event, fullPath, info);
  40706. })
  40707. };
  40708. FSEventsWatchers.set(watchPath, cont);
  40709. }
  40710. // removes this instance's listeners and closes the underlying fsevents
  40711. // instance if there are no more listeners left
  40712. return () => {
  40713. const lst = cont.listeners;
  40714. lst.delete(filteredListener);
  40715. if (!lst.size) {
  40716. FSEventsWatchers.delete(watchPath);
  40717. if (cont.watcher) return cont.watcher.stop().then(() => {
  40718. cont.rawEmitter = cont.watcher = undefined;
  40719. Object.freeze(cont);
  40720. });
  40721. }
  40722. };
  40723. }
  40724. // Decide whether or not we should start a new higher-level
  40725. // parent watcher
  40726. const couldConsolidate = (path) => {
  40727. let count = 0;
  40728. for (const watchPath of FSEventsWatchers.keys()) {
  40729. if (watchPath.indexOf(path) === 0) {
  40730. count++;
  40731. if (count >= consolidateThreshhold) {
  40732. return true;
  40733. }
  40734. }
  40735. }
  40736. return false;
  40737. };
  40738. // returns boolean indicating whether fsevents can be used
  40739. const canUse = () => fsevents && FSEventsWatchers.size < 128;
  40740. // determines subdirectory traversal levels from root to path
  40741. const calcDepth = (path, root) => {
  40742. let i = 0;
  40743. while (!path.indexOf(root) && (path = sysPath$1.dirname(path)) !== root) i++;
  40744. return i;
  40745. };
  40746. // returns boolean indicating whether the fsevents' event info has the same type
  40747. // as the one returned by fs.stat
  40748. const sameTypes = (info, stats) => (
  40749. info.type === FSEVENT_TYPE_DIRECTORY && stats.isDirectory() ||
  40750. info.type === FSEVENT_TYPE_SYMLINK && stats.isSymbolicLink() ||
  40751. info.type === FSEVENT_TYPE_FILE && stats.isFile()
  40752. );
  40753. /**
  40754. * @mixin
  40755. */
  40756. class FsEventsHandler$1 {
  40757. /**
  40758. * @param {import('../index').FSWatcher} fsw
  40759. */
  40760. constructor(fsw) {
  40761. this.fsw = fsw;
  40762. }
  40763. checkIgnored(path, stats) {
  40764. const ipaths = this.fsw._ignoredPaths;
  40765. if (this.fsw._isIgnored(path, stats)) {
  40766. ipaths.add(path);
  40767. if (stats && stats.isDirectory()) {
  40768. ipaths.add(path + ROOT_GLOBSTAR);
  40769. }
  40770. return true;
  40771. }
  40772. ipaths.delete(path);
  40773. ipaths.delete(path + ROOT_GLOBSTAR);
  40774. }
  40775. addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts) {
  40776. const event = watchedDir.has(item) ? EV_CHANGE$1 : EV_ADD$1;
  40777. this.handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  40778. }
  40779. async checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts) {
  40780. try {
  40781. const stats = await stat$1(path);
  40782. if (this.fsw.closed) return;
  40783. if (sameTypes(info, stats)) {
  40784. this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  40785. } else {
  40786. this.handleEvent(EV_UNLINK$1, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  40787. }
  40788. } catch (error) {
  40789. if (error.code === 'EACCES') {
  40790. this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  40791. } else {
  40792. this.handleEvent(EV_UNLINK$1, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  40793. }
  40794. }
  40795. }
  40796. handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts) {
  40797. if (this.fsw.closed || this.checkIgnored(path)) return;
  40798. if (event === EV_UNLINK$1) {
  40799. const isDirectory = info.type === FSEVENT_TYPE_DIRECTORY;
  40800. // suppress unlink events on never before seen files
  40801. if (isDirectory || watchedDir.has(item)) {
  40802. this.fsw._remove(parent, item, isDirectory);
  40803. }
  40804. } else {
  40805. if (event === EV_ADD$1) {
  40806. // track new directories
  40807. if (info.type === FSEVENT_TYPE_DIRECTORY) this.fsw._getWatchedDir(path);
  40808. if (info.type === FSEVENT_TYPE_SYMLINK && opts.followSymlinks) {
  40809. // push symlinks back to the top of the stack to get handled
  40810. const curDepth = opts.depth === undefined ?
  40811. undefined : calcDepth(fullPath, realPath) + 1;
  40812. return this._addToFsEvents(path, false, true, curDepth);
  40813. }
  40814. // track new paths
  40815. // (other than symlinks being followed, which will be tracked soon)
  40816. this.fsw._getWatchedDir(parent).add(item);
  40817. }
  40818. /**
  40819. * @type {'add'|'addDir'|'unlink'|'unlinkDir'}
  40820. */
  40821. const eventName = info.type === FSEVENT_TYPE_DIRECTORY ? event + DIR_SUFFIX : event;
  40822. this.fsw._emit(eventName, path);
  40823. if (eventName === EV_ADD_DIR$1) this._addToFsEvents(path, false, true);
  40824. }
  40825. }
  40826. /**
  40827. * Handle symlinks encountered during directory scan
  40828. * @param {String} watchPath - file/dir path to be watched with fsevents
  40829. * @param {String} realPath - real path (in case of symlinks)
  40830. * @param {Function} transform - path transformer
  40831. * @param {Function} globFilter - path filter in case a glob pattern was provided
  40832. * @returns {Function} closer for the watcher instance
  40833. */
  40834. _watchWithFsEvents(watchPath, realPath, transform, globFilter) {
  40835. if (this.fsw.closed || this.fsw._isIgnored(watchPath)) return;
  40836. const opts = this.fsw.options;
  40837. const watchCallback = async (fullPath, flags, info) => {
  40838. if (this.fsw.closed) return;
  40839. if (
  40840. opts.depth !== undefined &&
  40841. calcDepth(fullPath, realPath) > opts.depth
  40842. ) return;
  40843. const path = transform(sysPath$1.join(
  40844. watchPath, sysPath$1.relative(watchPath, fullPath)
  40845. ));
  40846. if (globFilter && !globFilter(path)) return;
  40847. // ensure directories are tracked
  40848. const parent = sysPath$1.dirname(path);
  40849. const item = sysPath$1.basename(path);
  40850. const watchedDir = this.fsw._getWatchedDir(
  40851. info.type === FSEVENT_TYPE_DIRECTORY ? path : parent
  40852. );
  40853. // correct for wrong events emitted
  40854. if (wrongEventFlags.has(flags) || info.event === FSEVENT_UNKNOWN) {
  40855. if (typeof opts.ignored === FUNCTION_TYPE$1) {
  40856. let stats;
  40857. try {
  40858. stats = await stat$1(path);
  40859. } catch (error) {}
  40860. if (this.fsw.closed) return;
  40861. if (this.checkIgnored(path, stats)) return;
  40862. if (sameTypes(info, stats)) {
  40863. this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  40864. } else {
  40865. this.handleEvent(EV_UNLINK$1, path, fullPath, realPath, parent, watchedDir, item, info, opts);
  40866. }
  40867. } else {
  40868. this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  40869. }
  40870. } else {
  40871. switch (info.event) {
  40872. case FSEVENT_CREATED:
  40873. case FSEVENT_MODIFIED:
  40874. return this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  40875. case FSEVENT_DELETED:
  40876. case FSEVENT_MOVED:
  40877. return this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts);
  40878. }
  40879. }
  40880. };
  40881. const closer = setFSEventsListener(
  40882. watchPath,
  40883. realPath,
  40884. watchCallback,
  40885. this.fsw._emitRaw
  40886. );
  40887. this.fsw._emitReady();
  40888. return closer;
  40889. }
  40890. /**
  40891. * Handle symlinks encountered during directory scan
  40892. * @param {String} linkPath path to symlink
  40893. * @param {String} fullPath absolute path to the symlink
  40894. * @param {Function} transform pre-existing path transformer
  40895. * @param {Number} curDepth level of subdirectories traversed to where symlink is
  40896. * @returns {Promise<void>}
  40897. */
  40898. async _handleFsEventsSymlink(linkPath, fullPath, transform, curDepth) {
  40899. // don't follow the same symlink more than once
  40900. if (this.fsw.closed || this.fsw._symlinkPaths.has(fullPath)) return;
  40901. this.fsw._symlinkPaths.set(fullPath, true);
  40902. this.fsw._incrReadyCount();
  40903. try {
  40904. const linkTarget = await realpath(linkPath);
  40905. if (this.fsw.closed) return;
  40906. if (this.fsw._isIgnored(linkTarget)) {
  40907. return this.fsw._emitReady();
  40908. }
  40909. this.fsw._incrReadyCount();
  40910. // add the linkTarget for watching with a wrapper for transform
  40911. // that causes emitted paths to incorporate the link's path
  40912. this._addToFsEvents(linkTarget || linkPath, (path) => {
  40913. let aliasedPath = linkPath;
  40914. if (linkTarget && linkTarget !== DOT_SLASH) {
  40915. aliasedPath = path.replace(linkTarget, linkPath);
  40916. } else if (path !== DOT_SLASH) {
  40917. aliasedPath = sysPath$1.join(linkPath, path);
  40918. }
  40919. return transform(aliasedPath);
  40920. }, false, curDepth);
  40921. } catch(error) {
  40922. if (this.fsw._handleError(error)) {
  40923. return this.fsw._emitReady();
  40924. }
  40925. }
  40926. }
  40927. /**
  40928. *
  40929. * @param {Path} newPath
  40930. * @param {fs.Stats} stats
  40931. */
  40932. emitAdd(newPath, stats, processPath, opts, forceAdd) {
  40933. const pp = processPath(newPath);
  40934. const isDir = stats.isDirectory();
  40935. const dirObj = this.fsw._getWatchedDir(sysPath$1.dirname(pp));
  40936. const base = sysPath$1.basename(pp);
  40937. // ensure empty dirs get tracked
  40938. if (isDir) this.fsw._getWatchedDir(pp);
  40939. if (dirObj.has(base)) return;
  40940. dirObj.add(base);
  40941. if (!opts.ignoreInitial || forceAdd === true) {
  40942. this.fsw._emit(isDir ? EV_ADD_DIR$1 : EV_ADD$1, pp, stats);
  40943. }
  40944. }
  40945. initWatch(realPath, path, wh, processPath) {
  40946. if (this.fsw.closed) return;
  40947. const closer = this._watchWithFsEvents(
  40948. wh.watchPath,
  40949. sysPath$1.resolve(realPath || wh.watchPath),
  40950. processPath,
  40951. wh.globFilter
  40952. );
  40953. this.fsw._addPathCloser(path, closer);
  40954. }
  40955. /**
  40956. * Handle added path with fsevents
  40957. * @param {String} path file/dir path or glob pattern
  40958. * @param {Function|Boolean=} transform converts working path to what the user expects
  40959. * @param {Boolean=} forceAdd ensure add is emitted
  40960. * @param {Number=} priorDepth Level of subdirectories already traversed.
  40961. * @returns {Promise<void>}
  40962. */
  40963. async _addToFsEvents(path, transform, forceAdd, priorDepth) {
  40964. if (this.fsw.closed) {
  40965. return;
  40966. }
  40967. const opts = this.fsw.options;
  40968. const processPath = typeof transform === FUNCTION_TYPE$1 ? transform : IDENTITY_FN;
  40969. const wh = this.fsw._getWatchHelpers(path);
  40970. // evaluate what is at the path we're being asked to watch
  40971. try {
  40972. const stats = await statMethods[wh.statMethod](wh.watchPath);
  40973. if (this.fsw.closed) return;
  40974. if (this.fsw._isIgnored(wh.watchPath, stats)) {
  40975. throw null;
  40976. }
  40977. if (stats.isDirectory()) {
  40978. // emit addDir unless this is a glob parent
  40979. if (!wh.globFilter) this.emitAdd(processPath(path), stats, processPath, opts, forceAdd);
  40980. // don't recurse further if it would exceed depth setting
  40981. if (priorDepth && priorDepth > opts.depth) return;
  40982. // scan the contents of the dir
  40983. this.fsw._readdirp(wh.watchPath, {
  40984. fileFilter: entry => wh.filterPath(entry),
  40985. directoryFilter: entry => wh.filterDir(entry),
  40986. ...Depth(opts.depth - (priorDepth || 0))
  40987. }).on(STR_DATA, (entry) => {
  40988. // need to check filterPath on dirs b/c filterDir is less restrictive
  40989. if (this.fsw.closed) {
  40990. return;
  40991. }
  40992. if (entry.stats.isDirectory() && !wh.filterPath(entry)) return;
  40993. const joinedPath = sysPath$1.join(wh.watchPath, entry.path);
  40994. const {fullPath} = entry;
  40995. if (wh.followSymlinks && entry.stats.isSymbolicLink()) {
  40996. // preserve the current depth here since it can't be derived from
  40997. // real paths past the symlink
  40998. const curDepth = opts.depth === undefined ?
  40999. undefined : calcDepth(joinedPath, sysPath$1.resolve(wh.watchPath)) + 1;
  41000. this._handleFsEventsSymlink(joinedPath, fullPath, processPath, curDepth);
  41001. } else {
  41002. this.emitAdd(joinedPath, entry.stats, processPath, opts, forceAdd);
  41003. }
  41004. }).on(EV_ERROR$1, EMPTY_FN$1).on(STR_END$1, () => {
  41005. this.fsw._emitReady();
  41006. });
  41007. } else {
  41008. this.emitAdd(wh.watchPath, stats, processPath, opts, forceAdd);
  41009. this.fsw._emitReady();
  41010. }
  41011. } catch (error) {
  41012. if (!error || this.fsw._handleError(error)) {
  41013. // TODO: Strange thing: "should not choke on an ignored watch path" will be failed without 2 ready calls -__-
  41014. this.fsw._emitReady();
  41015. this.fsw._emitReady();
  41016. }
  41017. }
  41018. if (opts.persistent && forceAdd !== true) {
  41019. if (typeof transform === FUNCTION_TYPE$1) {
  41020. // realpath has already been resolved
  41021. this.initWatch(undefined, path, wh, processPath);
  41022. } else {
  41023. let realPath;
  41024. try {
  41025. realPath = await realpath(wh.watchPath);
  41026. } catch (e) {}
  41027. this.initWatch(realPath, path, wh, processPath);
  41028. }
  41029. }
  41030. }
  41031. }
  41032. fseventsHandler.exports = FsEventsHandler$1;
  41033. fseventsHandler.exports.canUse = canUse;
  41034. const { EventEmitter: EventEmitter$2 } = require$$0__default$1;
  41035. const fs$7 = fs__default;
  41036. const sysPath = path__default;
  41037. const { promisify } = require$$0__default$2;
  41038. const readdirp = readdirp_1;
  41039. const anymatch = anymatch$2.exports.default;
  41040. const globParent = globParent$2;
  41041. const isGlob = isGlob$2;
  41042. const braces$1 = braces_1;
  41043. const normalizePath = normalizePath$2;
  41044. const NodeFsHandler = nodefsHandler;
  41045. const FsEventsHandler = fseventsHandler.exports;
  41046. const {
  41047. EV_ALL,
  41048. EV_READY,
  41049. EV_ADD,
  41050. EV_CHANGE,
  41051. EV_UNLINK,
  41052. EV_ADD_DIR,
  41053. EV_UNLINK_DIR,
  41054. EV_RAW,
  41055. EV_ERROR,
  41056. STR_CLOSE,
  41057. STR_END,
  41058. BACK_SLASH_RE,
  41059. DOUBLE_SLASH_RE,
  41060. SLASH_OR_BACK_SLASH_RE,
  41061. DOT_RE,
  41062. REPLACER_RE,
  41063. SLASH,
  41064. SLASH_SLASH,
  41065. BRACE_START,
  41066. BANG,
  41067. ONE_DOT,
  41068. TWO_DOTS,
  41069. GLOBSTAR,
  41070. SLASH_GLOBSTAR,
  41071. ANYMATCH_OPTS,
  41072. STRING_TYPE,
  41073. FUNCTION_TYPE,
  41074. EMPTY_STR,
  41075. EMPTY_FN,
  41076. isWindows: isWindows$1,
  41077. isMacos,
  41078. isIBMi
  41079. } = constants$1;
  41080. const stat = promisify(fs$7.stat);
  41081. const readdir = promisify(fs$7.readdir);
  41082. /**
  41083. * @typedef {String} Path
  41084. * @typedef {'all'|'add'|'addDir'|'change'|'unlink'|'unlinkDir'|'raw'|'error'|'ready'} EventName
  41085. * @typedef {'readdir'|'watch'|'add'|'remove'|'change'} ThrottleType
  41086. */
  41087. /**
  41088. *
  41089. * @typedef {Object} WatchHelpers
  41090. * @property {Boolean} followSymlinks
  41091. * @property {'stat'|'lstat'} statMethod
  41092. * @property {Path} path
  41093. * @property {Path} watchPath
  41094. * @property {Function} entryPath
  41095. * @property {Boolean} hasGlob
  41096. * @property {Object} globFilter
  41097. * @property {Function} filterPath
  41098. * @property {Function} filterDir
  41099. */
  41100. const arrify = (value = []) => Array.isArray(value) ? value : [value];
  41101. const flatten = (list, result = []) => {
  41102. list.forEach(item => {
  41103. if (Array.isArray(item)) {
  41104. flatten(item, result);
  41105. } else {
  41106. result.push(item);
  41107. }
  41108. });
  41109. return result;
  41110. };
  41111. const unifyPaths = (paths_) => {
  41112. /**
  41113. * @type {Array<String>}
  41114. */
  41115. const paths = flatten(arrify(paths_));
  41116. if (!paths.every(p => typeof p === STRING_TYPE)) {
  41117. throw new TypeError(`Non-string provided as watch path: ${paths}`);
  41118. }
  41119. return paths.map(normalizePathToUnix);
  41120. };
  41121. // If SLASH_SLASH occurs at the beginning of path, it is not replaced
  41122. // because "//StoragePC/DrivePool/Movies" is a valid network path
  41123. const toUnix = (string) => {
  41124. let str = string.replace(BACK_SLASH_RE, SLASH);
  41125. let prepend = false;
  41126. if (str.startsWith(SLASH_SLASH)) {
  41127. prepend = true;
  41128. }
  41129. while (str.match(DOUBLE_SLASH_RE)) {
  41130. str = str.replace(DOUBLE_SLASH_RE, SLASH);
  41131. }
  41132. if (prepend) {
  41133. str = SLASH + str;
  41134. }
  41135. return str;
  41136. };
  41137. // Our version of upath.normalize
  41138. // TODO: this is not equal to path-normalize module - investigate why
  41139. const normalizePathToUnix = (path) => toUnix(sysPath.normalize(toUnix(path)));
  41140. const normalizeIgnored = (cwd = EMPTY_STR) => (path) => {
  41141. if (typeof path !== STRING_TYPE) return path;
  41142. return normalizePathToUnix(sysPath.isAbsolute(path) ? path : sysPath.join(cwd, path));
  41143. };
  41144. const getAbsolutePath = (path, cwd) => {
  41145. if (sysPath.isAbsolute(path)) {
  41146. return path;
  41147. }
  41148. if (path.startsWith(BANG)) {
  41149. return BANG + sysPath.join(cwd, path.slice(1));
  41150. }
  41151. return sysPath.join(cwd, path);
  41152. };
  41153. const undef = (opts, key) => opts[key] === undefined;
  41154. /**
  41155. * Directory entry.
  41156. * @property {Path} path
  41157. * @property {Set<Path>} items
  41158. */
  41159. class DirEntry {
  41160. /**
  41161. * @param {Path} dir
  41162. * @param {Function} removeWatcher
  41163. */
  41164. constructor(dir, removeWatcher) {
  41165. this.path = dir;
  41166. this._removeWatcher = removeWatcher;
  41167. /** @type {Set<Path>} */
  41168. this.items = new Set();
  41169. }
  41170. add(item) {
  41171. const {items} = this;
  41172. if (!items) return;
  41173. if (item !== ONE_DOT && item !== TWO_DOTS) items.add(item);
  41174. }
  41175. async remove(item) {
  41176. const {items} = this;
  41177. if (!items) return;
  41178. items.delete(item);
  41179. if (items.size > 0) return;
  41180. const dir = this.path;
  41181. try {
  41182. await readdir(dir);
  41183. } catch (err) {
  41184. if (this._removeWatcher) {
  41185. this._removeWatcher(sysPath.dirname(dir), sysPath.basename(dir));
  41186. }
  41187. }
  41188. }
  41189. has(item) {
  41190. const {items} = this;
  41191. if (!items) return;
  41192. return items.has(item);
  41193. }
  41194. /**
  41195. * @returns {Array<String>}
  41196. */
  41197. getChildren() {
  41198. const {items} = this;
  41199. if (!items) return;
  41200. return [...items.values()];
  41201. }
  41202. dispose() {
  41203. this.items.clear();
  41204. delete this.path;
  41205. delete this._removeWatcher;
  41206. delete this.items;
  41207. Object.freeze(this);
  41208. }
  41209. }
  41210. const STAT_METHOD_F = 'stat';
  41211. const STAT_METHOD_L = 'lstat';
  41212. class WatchHelper {
  41213. constructor(path, watchPath, follow, fsw) {
  41214. this.fsw = fsw;
  41215. this.path = path = path.replace(REPLACER_RE, EMPTY_STR);
  41216. this.watchPath = watchPath;
  41217. this.fullWatchPath = sysPath.resolve(watchPath);
  41218. this.hasGlob = watchPath !== path;
  41219. /** @type {object|boolean} */
  41220. if (path === EMPTY_STR) this.hasGlob = false;
  41221. this.globSymlink = this.hasGlob && follow ? undefined : false;
  41222. this.globFilter = this.hasGlob ? anymatch(path, undefined, ANYMATCH_OPTS) : false;
  41223. this.dirParts = this.getDirParts(path);
  41224. this.dirParts.forEach((parts) => {
  41225. if (parts.length > 1) parts.pop();
  41226. });
  41227. this.followSymlinks = follow;
  41228. this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;
  41229. }
  41230. checkGlobSymlink(entry) {
  41231. // only need to resolve once
  41232. // first entry should always have entry.parentDir === EMPTY_STR
  41233. if (this.globSymlink === undefined) {
  41234. this.globSymlink = entry.fullParentDir === this.fullWatchPath ?
  41235. false : {realPath: entry.fullParentDir, linkPath: this.fullWatchPath};
  41236. }
  41237. if (this.globSymlink) {
  41238. return entry.fullPath.replace(this.globSymlink.realPath, this.globSymlink.linkPath);
  41239. }
  41240. return entry.fullPath;
  41241. }
  41242. entryPath(entry) {
  41243. return sysPath.join(this.watchPath,
  41244. sysPath.relative(this.watchPath, this.checkGlobSymlink(entry))
  41245. );
  41246. }
  41247. filterPath(entry) {
  41248. const {stats} = entry;
  41249. if (stats && stats.isSymbolicLink()) return this.filterDir(entry);
  41250. const resolvedPath = this.entryPath(entry);
  41251. const matchesGlob = this.hasGlob && typeof this.globFilter === FUNCTION_TYPE ?
  41252. this.globFilter(resolvedPath) : true;
  41253. return matchesGlob &&
  41254. this.fsw._isntIgnored(resolvedPath, stats) &&
  41255. this.fsw._hasReadPermissions(stats);
  41256. }
  41257. getDirParts(path) {
  41258. if (!this.hasGlob) return [];
  41259. const parts = [];
  41260. const expandedPath = path.includes(BRACE_START) ? braces$1.expand(path) : [path];
  41261. expandedPath.forEach((path) => {
  41262. parts.push(sysPath.relative(this.watchPath, path).split(SLASH_OR_BACK_SLASH_RE));
  41263. });
  41264. return parts;
  41265. }
  41266. filterDir(entry) {
  41267. if (this.hasGlob) {
  41268. const entryParts = this.getDirParts(this.checkGlobSymlink(entry));
  41269. let globstar = false;
  41270. this.unmatchedGlob = !this.dirParts.some((parts) => {
  41271. return parts.every((part, i) => {
  41272. if (part === GLOBSTAR) globstar = true;
  41273. return globstar || !entryParts[0][i] || anymatch(part, entryParts[0][i], ANYMATCH_OPTS);
  41274. });
  41275. });
  41276. }
  41277. return !this.unmatchedGlob && this.fsw._isntIgnored(this.entryPath(entry), entry.stats);
  41278. }
  41279. }
  41280. /**
  41281. * Watches files & directories for changes. Emitted events:
  41282. * `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error`
  41283. *
  41284. * new FSWatcher()
  41285. * .add(directories)
  41286. * .on('add', path => log('File', path, 'was added'))
  41287. */
  41288. class FSWatcher extends EventEmitter$2 {
  41289. // Not indenting methods for history sake; for now.
  41290. constructor(_opts) {
  41291. super();
  41292. const opts = {};
  41293. if (_opts) Object.assign(opts, _opts); // for frozen objects
  41294. /** @type {Map<String, DirEntry>} */
  41295. this._watched = new Map();
  41296. /** @type {Map<String, Array>} */
  41297. this._closers = new Map();
  41298. /** @type {Set<String>} */
  41299. this._ignoredPaths = new Set();
  41300. /** @type {Map<ThrottleType, Map>} */
  41301. this._throttled = new Map();
  41302. /** @type {Map<Path, String|Boolean>} */
  41303. this._symlinkPaths = new Map();
  41304. this._streams = new Set();
  41305. this.closed = false;
  41306. // Set up default options.
  41307. if (undef(opts, 'persistent')) opts.persistent = true;
  41308. if (undef(opts, 'ignoreInitial')) opts.ignoreInitial = false;
  41309. if (undef(opts, 'ignorePermissionErrors')) opts.ignorePermissionErrors = false;
  41310. if (undef(opts, 'interval')) opts.interval = 100;
  41311. if (undef(opts, 'binaryInterval')) opts.binaryInterval = 300;
  41312. if (undef(opts, 'disableGlobbing')) opts.disableGlobbing = false;
  41313. opts.enableBinaryInterval = opts.binaryInterval !== opts.interval;
  41314. // Enable fsevents on OS X when polling isn't explicitly enabled.
  41315. if (undef(opts, 'useFsEvents')) opts.useFsEvents = !opts.usePolling;
  41316. // If we can't use fsevents, ensure the options reflect it's disabled.
  41317. const canUseFsEvents = FsEventsHandler.canUse();
  41318. if (!canUseFsEvents) opts.useFsEvents = false;
  41319. // Use polling on Mac if not using fsevents.
  41320. // Other platforms use non-polling fs_watch.
  41321. if (undef(opts, 'usePolling') && !opts.useFsEvents) {
  41322. opts.usePolling = isMacos;
  41323. }
  41324. // Always default to polling on IBM i because fs.watch() is not available on IBM i.
  41325. if(isIBMi) {
  41326. opts.usePolling = true;
  41327. }
  41328. // Global override (useful for end-developers that need to force polling for all
  41329. // instances of chokidar, regardless of usage/dependency depth)
  41330. const envPoll = process.env.CHOKIDAR_USEPOLLING;
  41331. if (envPoll !== undefined) {
  41332. const envLower = envPoll.toLowerCase();
  41333. if (envLower === 'false' || envLower === '0') {
  41334. opts.usePolling = false;
  41335. } else if (envLower === 'true' || envLower === '1') {
  41336. opts.usePolling = true;
  41337. } else {
  41338. opts.usePolling = !!envLower;
  41339. }
  41340. }
  41341. const envInterval = process.env.CHOKIDAR_INTERVAL;
  41342. if (envInterval) {
  41343. opts.interval = Number.parseInt(envInterval, 10);
  41344. }
  41345. // Editor atomic write normalization enabled by default with fs.watch
  41346. if (undef(opts, 'atomic')) opts.atomic = !opts.usePolling && !opts.useFsEvents;
  41347. if (opts.atomic) this._pendingUnlinks = new Map();
  41348. if (undef(opts, 'followSymlinks')) opts.followSymlinks = true;
  41349. if (undef(opts, 'awaitWriteFinish')) opts.awaitWriteFinish = false;
  41350. if (opts.awaitWriteFinish === true) opts.awaitWriteFinish = {};
  41351. const awf = opts.awaitWriteFinish;
  41352. if (awf) {
  41353. if (!awf.stabilityThreshold) awf.stabilityThreshold = 2000;
  41354. if (!awf.pollInterval) awf.pollInterval = 100;
  41355. this._pendingWrites = new Map();
  41356. }
  41357. if (opts.ignored) opts.ignored = arrify(opts.ignored);
  41358. let readyCalls = 0;
  41359. this._emitReady = () => {
  41360. readyCalls++;
  41361. if (readyCalls >= this._readyCount) {
  41362. this._emitReady = EMPTY_FN;
  41363. this._readyEmitted = true;
  41364. // use process.nextTick to allow time for listener to be bound
  41365. process.nextTick(() => this.emit(EV_READY));
  41366. }
  41367. };
  41368. this._emitRaw = (...args) => this.emit(EV_RAW, ...args);
  41369. this._readyEmitted = false;
  41370. this.options = opts;
  41371. // Initialize with proper watcher.
  41372. if (opts.useFsEvents) {
  41373. this._fsEventsHandler = new FsEventsHandler(this);
  41374. } else {
  41375. this._nodeFsHandler = new NodeFsHandler(this);
  41376. }
  41377. // You’re frozen when your heart’s not open.
  41378. Object.freeze(opts);
  41379. }
  41380. // Public methods
  41381. /**
  41382. * Adds paths to be watched on an existing FSWatcher instance
  41383. * @param {Path|Array<Path>} paths_
  41384. * @param {String=} _origAdd private; for handling non-existent paths to be watched
  41385. * @param {Boolean=} _internal private; indicates a non-user add
  41386. * @returns {FSWatcher} for chaining
  41387. */
  41388. add(paths_, _origAdd, _internal) {
  41389. const {cwd, disableGlobbing} = this.options;
  41390. this.closed = false;
  41391. let paths = unifyPaths(paths_);
  41392. if (cwd) {
  41393. paths = paths.map((path) => {
  41394. const absPath = getAbsolutePath(path, cwd);
  41395. // Check `path` instead of `absPath` because the cwd portion can't be a glob
  41396. if (disableGlobbing || !isGlob(path)) {
  41397. return absPath;
  41398. }
  41399. return normalizePath(absPath);
  41400. });
  41401. }
  41402. // set aside negated glob strings
  41403. paths = paths.filter((path) => {
  41404. if (path.startsWith(BANG)) {
  41405. this._ignoredPaths.add(path.slice(1));
  41406. return false;
  41407. }
  41408. // if a path is being added that was previously ignored, stop ignoring it
  41409. this._ignoredPaths.delete(path);
  41410. this._ignoredPaths.delete(path + SLASH_GLOBSTAR);
  41411. // reset the cached userIgnored anymatch fn
  41412. // to make ignoredPaths changes effective
  41413. this._userIgnored = undefined;
  41414. return true;
  41415. });
  41416. if (this.options.useFsEvents && this._fsEventsHandler) {
  41417. if (!this._readyCount) this._readyCount = paths.length;
  41418. if (this.options.persistent) this._readyCount *= 2;
  41419. paths.forEach((path) => this._fsEventsHandler._addToFsEvents(path));
  41420. } else {
  41421. if (!this._readyCount) this._readyCount = 0;
  41422. this._readyCount += paths.length;
  41423. Promise.all(
  41424. paths.map(async path => {
  41425. const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, 0, 0, _origAdd);
  41426. if (res) this._emitReady();
  41427. return res;
  41428. })
  41429. ).then(results => {
  41430. if (this.closed) return;
  41431. results.filter(item => item).forEach(item => {
  41432. this.add(sysPath.dirname(item), sysPath.basename(_origAdd || item));
  41433. });
  41434. });
  41435. }
  41436. return this;
  41437. }
  41438. /**
  41439. * Close watchers or start ignoring events from specified paths.
  41440. * @param {Path|Array<Path>} paths_ - string or array of strings, file/directory paths and/or globs
  41441. * @returns {FSWatcher} for chaining
  41442. */
  41443. unwatch(paths_) {
  41444. if (this.closed) return this;
  41445. const paths = unifyPaths(paths_);
  41446. const {cwd} = this.options;
  41447. paths.forEach((path) => {
  41448. // convert to absolute path unless relative path already matches
  41449. if (!sysPath.isAbsolute(path) && !this._closers.has(path)) {
  41450. if (cwd) path = sysPath.join(cwd, path);
  41451. path = sysPath.resolve(path);
  41452. }
  41453. this._closePath(path);
  41454. this._ignoredPaths.add(path);
  41455. if (this._watched.has(path)) {
  41456. this._ignoredPaths.add(path + SLASH_GLOBSTAR);
  41457. }
  41458. // reset the cached userIgnored anymatch fn
  41459. // to make ignoredPaths changes effective
  41460. this._userIgnored = undefined;
  41461. });
  41462. return this;
  41463. }
  41464. /**
  41465. * Close watchers and remove all listeners from watched paths.
  41466. * @returns {Promise<void>}.
  41467. */
  41468. close() {
  41469. if (this.closed) return this._closePromise;
  41470. this.closed = true;
  41471. // Memory management.
  41472. this.removeAllListeners();
  41473. const closers = [];
  41474. this._closers.forEach(closerList => closerList.forEach(closer => {
  41475. const promise = closer();
  41476. if (promise instanceof Promise) closers.push(promise);
  41477. }));
  41478. this._streams.forEach(stream => stream.destroy());
  41479. this._userIgnored = undefined;
  41480. this._readyCount = 0;
  41481. this._readyEmitted = false;
  41482. this._watched.forEach(dirent => dirent.dispose());
  41483. ['closers', 'watched', 'streams', 'symlinkPaths', 'throttled'].forEach(key => {
  41484. this[`_${key}`].clear();
  41485. });
  41486. this._closePromise = closers.length ? Promise.all(closers).then(() => undefined) : Promise.resolve();
  41487. return this._closePromise;
  41488. }
  41489. /**
  41490. * Expose list of watched paths
  41491. * @returns {Object} for chaining
  41492. */
  41493. getWatched() {
  41494. const watchList = {};
  41495. this._watched.forEach((entry, dir) => {
  41496. const key = this.options.cwd ? sysPath.relative(this.options.cwd, dir) : dir;
  41497. watchList[key || ONE_DOT] = entry.getChildren().sort();
  41498. });
  41499. return watchList;
  41500. }
  41501. emitWithAll(event, args) {
  41502. this.emit(...args);
  41503. if (event !== EV_ERROR) this.emit(EV_ALL, ...args);
  41504. }
  41505. // Common helpers
  41506. // --------------
  41507. /**
  41508. * Normalize and emit events.
  41509. * Calling _emit DOES NOT MEAN emit() would be called!
  41510. * @param {EventName} event Type of event
  41511. * @param {Path} path File or directory path
  41512. * @param {*=} val1 arguments to be passed with event
  41513. * @param {*=} val2
  41514. * @param {*=} val3
  41515. * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
  41516. */
  41517. async _emit(event, path, val1, val2, val3) {
  41518. if (this.closed) return;
  41519. const opts = this.options;
  41520. if (isWindows$1) path = sysPath.normalize(path);
  41521. if (opts.cwd) path = sysPath.relative(opts.cwd, path);
  41522. /** @type Array<any> */
  41523. const args = [event, path];
  41524. if (val3 !== undefined) args.push(val1, val2, val3);
  41525. else if (val2 !== undefined) args.push(val1, val2);
  41526. else if (val1 !== undefined) args.push(val1);
  41527. const awf = opts.awaitWriteFinish;
  41528. let pw;
  41529. if (awf && (pw = this._pendingWrites.get(path))) {
  41530. pw.lastChange = new Date();
  41531. return this;
  41532. }
  41533. if (opts.atomic) {
  41534. if (event === EV_UNLINK) {
  41535. this._pendingUnlinks.set(path, args);
  41536. setTimeout(() => {
  41537. this._pendingUnlinks.forEach((entry, path) => {
  41538. this.emit(...entry);
  41539. this.emit(EV_ALL, ...entry);
  41540. this._pendingUnlinks.delete(path);
  41541. });
  41542. }, typeof opts.atomic === 'number' ? opts.atomic : 100);
  41543. return this;
  41544. }
  41545. if (event === EV_ADD && this._pendingUnlinks.has(path)) {
  41546. event = args[0] = EV_CHANGE;
  41547. this._pendingUnlinks.delete(path);
  41548. }
  41549. }
  41550. if (awf && (event === EV_ADD || event === EV_CHANGE) && this._readyEmitted) {
  41551. const awfEmit = (err, stats) => {
  41552. if (err) {
  41553. event = args[0] = EV_ERROR;
  41554. args[1] = err;
  41555. this.emitWithAll(event, args);
  41556. } else if (stats) {
  41557. // if stats doesn't exist the file must have been deleted
  41558. if (args.length > 2) {
  41559. args[2] = stats;
  41560. } else {
  41561. args.push(stats);
  41562. }
  41563. this.emitWithAll(event, args);
  41564. }
  41565. };
  41566. this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit);
  41567. return this;
  41568. }
  41569. if (event === EV_CHANGE) {
  41570. const isThrottled = !this._throttle(EV_CHANGE, path, 50);
  41571. if (isThrottled) return this;
  41572. }
  41573. if (opts.alwaysStat && val1 === undefined &&
  41574. (event === EV_ADD || event === EV_ADD_DIR || event === EV_CHANGE)
  41575. ) {
  41576. const fullPath = opts.cwd ? sysPath.join(opts.cwd, path) : path;
  41577. let stats;
  41578. try {
  41579. stats = await stat(fullPath);
  41580. } catch (err) {}
  41581. // Suppress event when fs_stat fails, to avoid sending undefined 'stat'
  41582. if (!stats || this.closed) return;
  41583. args.push(stats);
  41584. }
  41585. this.emitWithAll(event, args);
  41586. return this;
  41587. }
  41588. /**
  41589. * Common handler for errors
  41590. * @param {Error} error
  41591. * @returns {Error|Boolean} The error if defined, otherwise the value of the FSWatcher instance's `closed` flag
  41592. */
  41593. _handleError(error) {
  41594. const code = error && error.code;
  41595. if (error && code !== 'ENOENT' && code !== 'ENOTDIR' &&
  41596. (!this.options.ignorePermissionErrors || (code !== 'EPERM' && code !== 'EACCES'))
  41597. ) {
  41598. this.emit(EV_ERROR, error);
  41599. }
  41600. return error || this.closed;
  41601. }
  41602. /**
  41603. * Helper utility for throttling
  41604. * @param {ThrottleType} actionType type being throttled
  41605. * @param {Path} path being acted upon
  41606. * @param {Number} timeout duration of time to suppress duplicate actions
  41607. * @returns {Object|false} tracking object or false if action should be suppressed
  41608. */
  41609. _throttle(actionType, path, timeout) {
  41610. if (!this._throttled.has(actionType)) {
  41611. this._throttled.set(actionType, new Map());
  41612. }
  41613. /** @type {Map<Path, Object>} */
  41614. const action = this._throttled.get(actionType);
  41615. /** @type {Object} */
  41616. const actionPath = action.get(path);
  41617. if (actionPath) {
  41618. actionPath.count++;
  41619. return false;
  41620. }
  41621. let timeoutObject;
  41622. const clear = () => {
  41623. const item = action.get(path);
  41624. const count = item ? item.count : 0;
  41625. action.delete(path);
  41626. clearTimeout(timeoutObject);
  41627. if (item) clearTimeout(item.timeoutObject);
  41628. return count;
  41629. };
  41630. timeoutObject = setTimeout(clear, timeout);
  41631. const thr = {timeoutObject, clear, count: 0};
  41632. action.set(path, thr);
  41633. return thr;
  41634. }
  41635. _incrReadyCount() {
  41636. return this._readyCount++;
  41637. }
  41638. /**
  41639. * Awaits write operation to finish.
  41640. * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.
  41641. * @param {Path} path being acted upon
  41642. * @param {Number} threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished
  41643. * @param {EventName} event
  41644. * @param {Function} awfEmit Callback to be called when ready for event to be emitted.
  41645. */
  41646. _awaitWriteFinish(path, threshold, event, awfEmit) {
  41647. let timeoutHandler;
  41648. let fullPath = path;
  41649. if (this.options.cwd && !sysPath.isAbsolute(path)) {
  41650. fullPath = sysPath.join(this.options.cwd, path);
  41651. }
  41652. const now = new Date();
  41653. const awaitWriteFinish = (prevStat) => {
  41654. fs$7.stat(fullPath, (err, curStat) => {
  41655. if (err || !this._pendingWrites.has(path)) {
  41656. if (err && err.code !== 'ENOENT') awfEmit(err);
  41657. return;
  41658. }
  41659. const now = Number(new Date());
  41660. if (prevStat && curStat.size !== prevStat.size) {
  41661. this._pendingWrites.get(path).lastChange = now;
  41662. }
  41663. const pw = this._pendingWrites.get(path);
  41664. const df = now - pw.lastChange;
  41665. if (df >= threshold) {
  41666. this._pendingWrites.delete(path);
  41667. awfEmit(undefined, curStat);
  41668. } else {
  41669. timeoutHandler = setTimeout(
  41670. awaitWriteFinish,
  41671. this.options.awaitWriteFinish.pollInterval,
  41672. curStat
  41673. );
  41674. }
  41675. });
  41676. };
  41677. if (!this._pendingWrites.has(path)) {
  41678. this._pendingWrites.set(path, {
  41679. lastChange: now,
  41680. cancelWait: () => {
  41681. this._pendingWrites.delete(path);
  41682. clearTimeout(timeoutHandler);
  41683. return event;
  41684. }
  41685. });
  41686. timeoutHandler = setTimeout(
  41687. awaitWriteFinish,
  41688. this.options.awaitWriteFinish.pollInterval
  41689. );
  41690. }
  41691. }
  41692. _getGlobIgnored() {
  41693. return [...this._ignoredPaths.values()];
  41694. }
  41695. /**
  41696. * Determines whether user has asked to ignore this path.
  41697. * @param {Path} path filepath or dir
  41698. * @param {fs.Stats=} stats result of fs.stat
  41699. * @returns {Boolean}
  41700. */
  41701. _isIgnored(path, stats) {
  41702. if (this.options.atomic && DOT_RE.test(path)) return true;
  41703. if (!this._userIgnored) {
  41704. const {cwd} = this.options;
  41705. const ign = this.options.ignored;
  41706. const ignored = ign && ign.map(normalizeIgnored(cwd));
  41707. const paths = arrify(ignored)
  41708. .filter((path) => typeof path === STRING_TYPE && !isGlob(path))
  41709. .map((path) => path + SLASH_GLOBSTAR);
  41710. const list = this._getGlobIgnored().map(normalizeIgnored(cwd)).concat(ignored, paths);
  41711. this._userIgnored = anymatch(list, undefined, ANYMATCH_OPTS);
  41712. }
  41713. return this._userIgnored([path, stats]);
  41714. }
  41715. _isntIgnored(path, stat) {
  41716. return !this._isIgnored(path, stat);
  41717. }
  41718. /**
  41719. * Provides a set of common helpers and properties relating to symlink and glob handling.
  41720. * @param {Path} path file, directory, or glob pattern being watched
  41721. * @param {Number=} depth at any depth > 0, this isn't a glob
  41722. * @returns {WatchHelper} object containing helpers for this path
  41723. */
  41724. _getWatchHelpers(path, depth) {
  41725. const watchPath = depth || this.options.disableGlobbing || !isGlob(path) ? path : globParent(path);
  41726. const follow = this.options.followSymlinks;
  41727. return new WatchHelper(path, watchPath, follow, this);
  41728. }
  41729. // Directory helpers
  41730. // -----------------
  41731. /**
  41732. * Provides directory tracking objects
  41733. * @param {String} directory path of the directory
  41734. * @returns {DirEntry} the directory's tracking object
  41735. */
  41736. _getWatchedDir(directory) {
  41737. if (!this._boundRemove) this._boundRemove = this._remove.bind(this);
  41738. const dir = sysPath.resolve(directory);
  41739. if (!this._watched.has(dir)) this._watched.set(dir, new DirEntry(dir, this._boundRemove));
  41740. return this._watched.get(dir);
  41741. }
  41742. // File helpers
  41743. // ------------
  41744. /**
  41745. * Check for read permissions.
  41746. * Based on this answer on SO: https://stackoverflow.com/a/11781404/1358405
  41747. * @param {fs.Stats} stats - object, result of fs_stat
  41748. * @returns {Boolean} indicates whether the file can be read
  41749. */
  41750. _hasReadPermissions(stats) {
  41751. if (this.options.ignorePermissionErrors) return true;
  41752. // stats.mode may be bigint
  41753. const md = stats && Number.parseInt(stats.mode, 10);
  41754. const st = md & 0o777;
  41755. const it = Number.parseInt(st.toString(8)[0], 10);
  41756. return Boolean(4 & it);
  41757. }
  41758. /**
  41759. * Handles emitting unlink events for
  41760. * files and directories, and via recursion, for
  41761. * files and directories within directories that are unlinked
  41762. * @param {String} directory within which the following item is located
  41763. * @param {String} item base path of item/directory
  41764. * @returns {void}
  41765. */
  41766. _remove(directory, item, isDirectory) {
  41767. // if what is being deleted is a directory, get that directory's paths
  41768. // for recursive deleting and cleaning of watched object
  41769. // if it is not a directory, nestedDirectoryChildren will be empty array
  41770. const path = sysPath.join(directory, item);
  41771. const fullPath = sysPath.resolve(path);
  41772. isDirectory = isDirectory != null
  41773. ? isDirectory
  41774. : this._watched.has(path) || this._watched.has(fullPath);
  41775. // prevent duplicate handling in case of arriving here nearly simultaneously
  41776. // via multiple paths (such as _handleFile and _handleDir)
  41777. if (!this._throttle('remove', path, 100)) return;
  41778. // if the only watched file is removed, watch for its return
  41779. if (!isDirectory && !this.options.useFsEvents && this._watched.size === 1) {
  41780. this.add(directory, item, true);
  41781. }
  41782. // This will create a new entry in the watched object in either case
  41783. // so we got to do the directory check beforehand
  41784. const wp = this._getWatchedDir(path);
  41785. const nestedDirectoryChildren = wp.getChildren();
  41786. // Recursively remove children directories / files.
  41787. nestedDirectoryChildren.forEach(nested => this._remove(path, nested));
  41788. // Check if item was on the watched list and remove it
  41789. const parent = this._getWatchedDir(directory);
  41790. const wasTracked = parent.has(item);
  41791. parent.remove(item);
  41792. // Fixes issue #1042 -> Relative paths were detected and added as symlinks
  41793. // (https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L612),
  41794. // but never removed from the map in case the path was deleted.
  41795. // This leads to an incorrect state if the path was recreated:
  41796. // https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L553
  41797. if (this._symlinkPaths.has(fullPath)) {
  41798. this._symlinkPaths.delete(fullPath);
  41799. }
  41800. // If we wait for this file to be fully written, cancel the wait.
  41801. let relPath = path;
  41802. if (this.options.cwd) relPath = sysPath.relative(this.options.cwd, path);
  41803. if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
  41804. const event = this._pendingWrites.get(relPath).cancelWait();
  41805. if (event === EV_ADD) return;
  41806. }
  41807. // The Entry will either be a directory that just got removed
  41808. // or a bogus entry to a file, in either case we have to remove it
  41809. this._watched.delete(path);
  41810. this._watched.delete(fullPath);
  41811. const eventName = isDirectory ? EV_UNLINK_DIR : EV_UNLINK;
  41812. if (wasTracked && !this._isIgnored(path)) this._emit(eventName, path);
  41813. // Avoid conflicts if we later create another file with the same name
  41814. if (!this.options.useFsEvents) {
  41815. this._closePath(path);
  41816. }
  41817. }
  41818. /**
  41819. * Closes all watchers for a path
  41820. * @param {Path} path
  41821. */
  41822. _closePath(path) {
  41823. this._closeFile(path);
  41824. const dir = sysPath.dirname(path);
  41825. this._getWatchedDir(dir).remove(sysPath.basename(path));
  41826. }
  41827. /**
  41828. * Closes only file-specific watchers
  41829. * @param {Path} path
  41830. */
  41831. _closeFile(path) {
  41832. const closers = this._closers.get(path);
  41833. if (!closers) return;
  41834. closers.forEach(closer => closer());
  41835. this._closers.delete(path);
  41836. }
  41837. /**
  41838. *
  41839. * @param {Path} path
  41840. * @param {Function} closer
  41841. */
  41842. _addPathCloser(path, closer) {
  41843. if (!closer) return;
  41844. let list = this._closers.get(path);
  41845. if (!list) {
  41846. list = [];
  41847. this._closers.set(path, list);
  41848. }
  41849. list.push(closer);
  41850. }
  41851. _readdirp(root, opts) {
  41852. if (this.closed) return;
  41853. const options = {type: EV_ALL, alwaysStat: true, lstat: true, ...opts};
  41854. let stream = readdirp(root, options);
  41855. this._streams.add(stream);
  41856. stream.once(STR_CLOSE, () => {
  41857. stream = undefined;
  41858. });
  41859. stream.once(STR_END, () => {
  41860. if (stream) {
  41861. this._streams.delete(stream);
  41862. stream = undefined;
  41863. }
  41864. });
  41865. return stream;
  41866. }
  41867. }
  41868. // Export FSWatcher class
  41869. chokidar.FSWatcher = FSWatcher;
  41870. /**
  41871. * Instantiates watcher with paths to be tracked.
  41872. * @param {String|Array<String>} paths file/directory paths and/or globs
  41873. * @param {Object=} options chokidar opts
  41874. * @returns an instance of FSWatcher for chaining.
  41875. */
  41876. const watch = (paths, options) => {
  41877. const watcher = new FSWatcher(options);
  41878. watcher.add(paths);
  41879. return watcher;
  41880. };
  41881. chokidar.watch = watch;
  41882. var shellQuote$1 = {};
  41883. shellQuote$1.quote = function (xs) {
  41884. return xs.map(function (s) {
  41885. if (s && typeof s === 'object') {
  41886. return s.op.replace(/(.)/g, '\\$1');
  41887. }
  41888. else if (/["\s]/.test(s) && !/'/.test(s)) {
  41889. return "'" + s.replace(/(['\\])/g, '\\$1') + "'";
  41890. }
  41891. else if (/["'\s]/.test(s)) {
  41892. return '"' + s.replace(/(["\\$`!])/g, '\\$1') + '"';
  41893. }
  41894. else {
  41895. return String(s).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@\[\\\]^`{|}])/g, '$1\\$2');
  41896. }
  41897. }).join(' ');
  41898. };
  41899. // '<(' is process substitution operator and
  41900. // can be parsed the same as control operator
  41901. var CONTROL = '(?:' + [
  41902. '\\|\\|', '\\&\\&', ';;', '\\|\\&', '\\<\\(', '>>', '>\\&', '[&;()|<>]'
  41903. ].join('|') + ')';
  41904. var META = '|&;()<> \\t';
  41905. var BAREWORD = '(\\\\[\'"' + META + ']|[^\\s\'"' + META + '])+';
  41906. var SINGLE_QUOTE = '"((\\\\"|[^"])*?)"';
  41907. var DOUBLE_QUOTE = '\'((\\\\\'|[^\'])*?)\'';
  41908. var TOKEN = '';
  41909. for (var i = 0; i < 4; i++) {
  41910. TOKEN += (Math.pow(16,8)*Math.random()).toString(16);
  41911. }
  41912. shellQuote$1.parse = function (s, env, opts) {
  41913. var mapped = parse$6(s, env, opts);
  41914. if (typeof env !== 'function') return mapped;
  41915. return mapped.reduce(function (acc, s) {
  41916. if (typeof s === 'object') return acc.concat(s);
  41917. var xs = s.split(RegExp('(' + TOKEN + '.*?' + TOKEN + ')', 'g'));
  41918. if (xs.length === 1) return acc.concat(xs[0]);
  41919. return acc.concat(xs.filter(Boolean).map(function (x) {
  41920. if (RegExp('^' + TOKEN).test(x)) {
  41921. return JSON.parse(x.split(TOKEN)[1]);
  41922. }
  41923. else return x;
  41924. }));
  41925. }, []);
  41926. };
  41927. function parse$6 (s, env, opts) {
  41928. var chunker = new RegExp([
  41929. '(' + CONTROL + ')', // control chars
  41930. '(' + BAREWORD + '|' + SINGLE_QUOTE + '|' + DOUBLE_QUOTE + ')*'
  41931. ].join('|'), 'g');
  41932. var match = s.match(chunker).filter(Boolean);
  41933. var commented = false;
  41934. if (!match) return [];
  41935. if (!env) env = {};
  41936. if (!opts) opts = {};
  41937. return match.map(function (s, j) {
  41938. if (commented) {
  41939. return;
  41940. }
  41941. if (RegExp('^' + CONTROL + '$').test(s)) {
  41942. return { op: s };
  41943. }
  41944. // Hand-written scanner/parser for Bash quoting rules:
  41945. //
  41946. // 1. inside single quotes, all characters are printed literally.
  41947. // 2. inside double quotes, all characters are printed literally
  41948. // except variables prefixed by '$' and backslashes followed by
  41949. // either a double quote or another backslash.
  41950. // 3. outside of any quotes, backslashes are treated as escape
  41951. // characters and not printed (unless they are themselves escaped)
  41952. // 4. quote context can switch mid-token if there is no whitespace
  41953. // between the two quote contexts (e.g. all'one'"token" parses as
  41954. // "allonetoken")
  41955. var SQ = "'";
  41956. var DQ = '"';
  41957. var DS = '$';
  41958. var BS = opts.escape || '\\';
  41959. var quote = false;
  41960. var esc = false;
  41961. var out = '';
  41962. var isGlob = false;
  41963. for (var i = 0, len = s.length; i < len; i++) {
  41964. var c = s.charAt(i);
  41965. isGlob = isGlob || (!quote && (c === '*' || c === '?'));
  41966. if (esc) {
  41967. out += c;
  41968. esc = false;
  41969. }
  41970. else if (quote) {
  41971. if (c === quote) {
  41972. quote = false;
  41973. }
  41974. else if (quote == SQ) {
  41975. out += c;
  41976. }
  41977. else { // Double quote
  41978. if (c === BS) {
  41979. i += 1;
  41980. c = s.charAt(i);
  41981. if (c === DQ || c === BS || c === DS) {
  41982. out += c;
  41983. } else {
  41984. out += BS + c;
  41985. }
  41986. }
  41987. else if (c === DS) {
  41988. out += parseEnvVar();
  41989. }
  41990. else {
  41991. out += c;
  41992. }
  41993. }
  41994. }
  41995. else if (c === DQ || c === SQ) {
  41996. quote = c;
  41997. }
  41998. else if (RegExp('^' + CONTROL + '$').test(c)) {
  41999. return { op: s };
  42000. }
  42001. else if (RegExp('^#$').test(c)) {
  42002. commented = true;
  42003. if (out.length){
  42004. return [out, { comment: s.slice(i+1) + match.slice(j+1).join(' ') }];
  42005. }
  42006. return [{ comment: s.slice(i+1) + match.slice(j+1).join(' ') }];
  42007. }
  42008. else if (c === BS) {
  42009. esc = true;
  42010. }
  42011. else if (c === DS) {
  42012. out += parseEnvVar();
  42013. }
  42014. else out += c;
  42015. }
  42016. if (isGlob) return {op: 'glob', pattern: out};
  42017. return out;
  42018. function parseEnvVar() {
  42019. i += 1;
  42020. var varend, varname;
  42021. //debugger
  42022. if (s.charAt(i) === '{') {
  42023. i += 1;
  42024. if (s.charAt(i) === '}') {
  42025. throw new Error("Bad substitution: " + s.substr(i - 2, 3));
  42026. }
  42027. varend = s.indexOf('}', i);
  42028. if (varend < 0) {
  42029. throw new Error("Bad substitution: " + s.substr(i));
  42030. }
  42031. varname = s.substr(i, varend - i);
  42032. i = varend;
  42033. }
  42034. else if (/[*@#?$!_\-]/.test(s.charAt(i))) {
  42035. varname = s.charAt(i);
  42036. i += 1;
  42037. }
  42038. else {
  42039. varend = s.substr(i).match(/[^\w\d_]/);
  42040. if (!varend) {
  42041. varname = s.substr(i);
  42042. i = s.length;
  42043. } else {
  42044. varname = s.substr(i, varend.index);
  42045. i += varend.index - 1;
  42046. }
  42047. }
  42048. return getVar(null, '', varname);
  42049. }
  42050. })
  42051. // finalize parsed aruments
  42052. .reduce(function(prev, arg){
  42053. if (arg === undefined){
  42054. return prev;
  42055. }
  42056. return prev.concat(arg);
  42057. },[]);
  42058. function getVar (_, pre, key) {
  42059. var r = typeof env === 'function' ? env(key) : env[key];
  42060. if (r === undefined && key != '')
  42061. r = '';
  42062. else if (r === undefined)
  42063. r = '$';
  42064. if (typeof r === 'object') {
  42065. return pre + TOKEN + JSON.stringify(r) + TOKEN;
  42066. }
  42067. else return pre + r;
  42068. }
  42069. }
  42070. var osx = {
  42071. '/Applications/Atom.app/Contents/MacOS/Atom': 'atom',
  42072. '/Applications/Atom Beta.app/Contents/MacOS/Atom Beta':
  42073. '/Applications/Atom Beta.app/Contents/MacOS/Atom Beta',
  42074. '/Applications/Brackets.app/Contents/MacOS/Brackets': 'brackets',
  42075. '/Applications/Sublime Text.app/Contents/MacOS/Sublime Text':
  42076. '/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl',
  42077. '/Applications/Sublime Text.app/Contents/MacOS/sublime_text':
  42078. '/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl',
  42079. '/Applications/Sublime Text 2.app/Contents/MacOS/Sublime Text 2':
  42080. '/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl',
  42081. '/Applications/Sublime Text Dev.app/Contents/MacOS/Sublime Text':
  42082. '/Applications/Sublime Text Dev.app/Contents/SharedSupport/bin/subl',
  42083. '/Applications/Visual Studio Code.app/Contents/MacOS/Electron': 'code',
  42084. '/Applications/Visual Studio Code - Insiders.app/Contents/MacOS/Electron':
  42085. 'code-insiders',
  42086. '/Applications/AppCode.app/Contents/MacOS/appcode':
  42087. '/Applications/AppCode.app/Contents/MacOS/appcode',
  42088. '/Applications/CLion.app/Contents/MacOS/clion':
  42089. '/Applications/CLion.app/Contents/MacOS/clion',
  42090. '/Applications/IntelliJ IDEA.app/Contents/MacOS/idea':
  42091. '/Applications/IntelliJ IDEA.app/Contents/MacOS/idea',
  42092. '/Applications/PhpStorm.app/Contents/MacOS/phpstorm':
  42093. '/Applications/PhpStorm.app/Contents/MacOS/phpstorm',
  42094. '/Applications/PyCharm.app/Contents/MacOS/pycharm':
  42095. '/Applications/PyCharm.app/Contents/MacOS/pycharm',
  42096. '/Applications/PyCharm CE.app/Contents/MacOS/pycharm':
  42097. '/Applications/PyCharm CE.app/Contents/MacOS/pycharm',
  42098. '/Applications/RubyMine.app/Contents/MacOS/rubymine':
  42099. '/Applications/RubyMine.app/Contents/MacOS/rubymine',
  42100. '/Applications/WebStorm.app/Contents/MacOS/webstorm':
  42101. '/Applications/WebStorm.app/Contents/MacOS/webstorm'
  42102. };
  42103. var linux = {
  42104. atom: 'atom',
  42105. Brackets: 'brackets',
  42106. code: 'code',
  42107. emacs: 'emacs',
  42108. 'idea.sh': 'idea',
  42109. 'phpstorm.sh': 'phpstorm',
  42110. 'pycharm.sh': 'pycharm',
  42111. 'rubymine.sh': 'rubymine',
  42112. sublime_text: 'subl',
  42113. vim: 'vim',
  42114. 'webstorm.sh': 'webstorm'
  42115. };
  42116. var windows$1 = [
  42117. 'Brackets.exe',
  42118. 'Code.exe',
  42119. 'atom.exe',
  42120. 'sublime_text.exe',
  42121. 'notepad++.exe',
  42122. 'clion.exe',
  42123. 'clion64.exe',
  42124. 'idea.exe',
  42125. 'idea64.exe',
  42126. 'phpstorm.exe',
  42127. 'phpstorm64.exe',
  42128. 'pycharm.exe',
  42129. 'pycharm64.exe',
  42130. 'rubymine.exe',
  42131. 'rubymine64.exe',
  42132. 'webstorm.exe',
  42133. 'webstorm64.exe'
  42134. ];
  42135. const path$7 = path__default;
  42136. const shellQuote = shellQuote$1;
  42137. const childProcess$2 = require$$2__default$1;
  42138. // Map from full process name to binary that starts the process
  42139. // We can't just re-use full process name, because it will spawn a new instance
  42140. // of the app every time
  42141. const COMMON_EDITORS_OSX = osx;
  42142. const COMMON_EDITORS_LINUX = linux;
  42143. const COMMON_EDITORS_WIN = windows$1;
  42144. var guess = function guessEditor (specifiedEditor) {
  42145. if (specifiedEditor) {
  42146. return shellQuote.parse(specifiedEditor)
  42147. }
  42148. // We can find out which editor is currently running by:
  42149. // `ps x` on macOS and Linux
  42150. // `Get-Process` on Windows
  42151. try {
  42152. if (process.platform === 'darwin') {
  42153. const output = childProcess$2.execSync('ps x').toString();
  42154. const processNames = Object.keys(COMMON_EDITORS_OSX);
  42155. for (let i = 0; i < processNames.length; i++) {
  42156. const processName = processNames[i];
  42157. if (output.indexOf(processName) !== -1) {
  42158. return [COMMON_EDITORS_OSX[processName]]
  42159. }
  42160. }
  42161. } else if (process.platform === 'win32') {
  42162. const output = childProcess$2
  42163. .execSync('powershell -Command "Get-Process | Select-Object Path"', {
  42164. stdio: ['pipe', 'pipe', 'ignore']
  42165. })
  42166. .toString();
  42167. const runningProcesses = output.split('\r\n');
  42168. for (let i = 0; i < runningProcesses.length; i++) {
  42169. // `Get-Process` sometimes returns empty lines
  42170. if (!runningProcesses[i]) {
  42171. continue
  42172. }
  42173. const fullProcessPath = runningProcesses[i].trim();
  42174. const shortProcessName = path$7.basename(fullProcessPath);
  42175. if (COMMON_EDITORS_WIN.indexOf(shortProcessName) !== -1) {
  42176. return [fullProcessPath]
  42177. }
  42178. }
  42179. } else if (process.platform === 'linux') {
  42180. // --no-heading No header line
  42181. // x List all processes owned by you
  42182. // -o comm Need only names column
  42183. const output = childProcess$2
  42184. .execSync('ps x --no-heading -o comm --sort=comm')
  42185. .toString();
  42186. const processNames = Object.keys(COMMON_EDITORS_LINUX);
  42187. for (let i = 0; i < processNames.length; i++) {
  42188. const processName = processNames[i];
  42189. if (output.indexOf(processName) !== -1) {
  42190. return [COMMON_EDITORS_LINUX[processName]]
  42191. }
  42192. }
  42193. }
  42194. } catch (error) {
  42195. // Ignore...
  42196. }
  42197. // Last resort, use old skool env vars
  42198. if (process.env.VISUAL) {
  42199. return [process.env.VISUAL]
  42200. } else if (process.env.EDITOR) {
  42201. return [process.env.EDITOR]
  42202. }
  42203. return [null]
  42204. };
  42205. const path$6 = path__default;
  42206. // normalize file/line numbers into command line args for specific editors
  42207. var getArgs = function getArgumentsForPosition (
  42208. editor,
  42209. fileName,
  42210. lineNumber,
  42211. columnNumber = 1
  42212. ) {
  42213. const editorBasename = path$6.basename(editor).replace(/\.(exe|cmd|bat)$/i, '');
  42214. switch (editorBasename) {
  42215. case 'atom':
  42216. case 'Atom':
  42217. case 'Atom Beta':
  42218. case 'subl':
  42219. case 'sublime':
  42220. case 'sublime_text':
  42221. case 'wstorm':
  42222. case 'charm':
  42223. return [`${fileName}:${lineNumber}:${columnNumber}`]
  42224. case 'notepad++':
  42225. return ['-n' + lineNumber, fileName]
  42226. case 'vim':
  42227. case 'mvim':
  42228. return [`+call cursor(${lineNumber}, ${columnNumber})`, fileName]
  42229. case 'joe':
  42230. return ['+' + `${lineNumber}`, fileName]
  42231. case 'emacs':
  42232. case 'emacsclient':
  42233. return [`+${lineNumber}:${columnNumber}`, fileName]
  42234. case 'rmate':
  42235. case 'mate':
  42236. case 'mine':
  42237. return ['--line', lineNumber, fileName]
  42238. case 'code':
  42239. case 'code-insiders':
  42240. case 'Code':
  42241. return ['-r', '-g', `${fileName}:${lineNumber}:${columnNumber}`]
  42242. case 'appcode':
  42243. case 'clion':
  42244. case 'clion64':
  42245. case 'idea':
  42246. case 'idea64':
  42247. case 'phpstorm':
  42248. case 'phpstorm64':
  42249. case 'pycharm':
  42250. case 'pycharm64':
  42251. case 'rubymine':
  42252. case 'rubymine64':
  42253. case 'webstorm':
  42254. case 'webstorm64':
  42255. return ['--line', lineNumber, fileName]
  42256. }
  42257. // For all others, drop the lineNumber until we have
  42258. // a mapping above, since providing the lineNumber incorrectly
  42259. // can result in errors or confusing behavior.
  42260. return [fileName]
  42261. };
  42262. /**
  42263. * Copyright (c) 2015-present, Facebook, Inc.
  42264. *
  42265. * This source code is licensed under the MIT license found in the
  42266. * LICENSE file at
  42267. * https://github.com/facebookincubator/create-react-app/blob/master/LICENSE
  42268. *
  42269. * Modified by Yuxi Evan You
  42270. */
  42271. const fs$6 = fs__default;
  42272. const os$1 = require$$2__default;
  42273. const path$5 = path__default;
  42274. const colors = picocolors.exports;
  42275. const childProcess$1 = require$$2__default$1;
  42276. const guessEditor = guess;
  42277. const getArgumentsForPosition = getArgs;
  42278. function wrapErrorCallback (cb) {
  42279. return (fileName, errorMessage) => {
  42280. console.log();
  42281. console.log(
  42282. colors.red('Could not open ' + path$5.basename(fileName) + ' in the editor.')
  42283. );
  42284. if (errorMessage) {
  42285. if (errorMessage[errorMessage.length - 1] !== '.') {
  42286. errorMessage += '.';
  42287. }
  42288. console.log(
  42289. colors.red('The editor process exited with an error: ' + errorMessage)
  42290. );
  42291. }
  42292. console.log();
  42293. if (cb) cb(fileName, errorMessage);
  42294. }
  42295. }
  42296. function isTerminalEditor (editor) {
  42297. switch (editor) {
  42298. case 'vim':
  42299. case 'emacs':
  42300. case 'nano':
  42301. return true
  42302. }
  42303. return false
  42304. }
  42305. const positionRE = /:(\d+)(:(\d+))?$/;
  42306. function parseFile (file) {
  42307. const fileName = file.replace(positionRE, '');
  42308. const match = file.match(positionRE);
  42309. const lineNumber = match && match[1];
  42310. const columnNumber = match && match[3];
  42311. return {
  42312. fileName,
  42313. lineNumber,
  42314. columnNumber
  42315. }
  42316. }
  42317. let _childProcess = null;
  42318. function launchEditor (file, specifiedEditor, onErrorCallback) {
  42319. const parsed = parseFile(file);
  42320. let { fileName } = parsed;
  42321. const { lineNumber, columnNumber } = parsed;
  42322. if (!fs$6.existsSync(fileName)) {
  42323. return
  42324. }
  42325. if (typeof specifiedEditor === 'function') {
  42326. onErrorCallback = specifiedEditor;
  42327. specifiedEditor = undefined;
  42328. }
  42329. onErrorCallback = wrapErrorCallback(onErrorCallback);
  42330. const [editor, ...args] = guessEditor(specifiedEditor);
  42331. if (!editor) {
  42332. onErrorCallback(fileName, null);
  42333. return
  42334. }
  42335. if (
  42336. process.platform === 'linux' &&
  42337. fileName.startsWith('/mnt/') &&
  42338. /Microsoft/i.test(os$1.release())
  42339. ) {
  42340. // Assume WSL / "Bash on Ubuntu on Windows" is being used, and
  42341. // that the file exists on the Windows file system.
  42342. // `os.release()` is "4.4.0-43-Microsoft" in the current release
  42343. // build of WSL, see: https://github.com/Microsoft/BashOnWindows/issues/423#issuecomment-221627364
  42344. // When a Windows editor is specified, interop functionality can
  42345. // handle the path translation, but only if a relative path is used.
  42346. fileName = path$5.relative('', fileName);
  42347. }
  42348. if (lineNumber) {
  42349. const extraArgs = getArgumentsForPosition(editor, fileName, lineNumber, columnNumber);
  42350. args.push.apply(args, extraArgs);
  42351. } else {
  42352. args.push(fileName);
  42353. }
  42354. if (_childProcess && isTerminalEditor(editor)) {
  42355. // There's an existing editor process already and it's attached
  42356. // to the terminal, so go kill it. Otherwise two separate editor
  42357. // instances attach to the stdin/stdout which gets confusing.
  42358. _childProcess.kill('SIGKILL');
  42359. }
  42360. if (process.platform === 'win32') {
  42361. // On Windows, launch the editor in a shell because spawn can only
  42362. // launch .exe files.
  42363. _childProcess = childProcess$1.spawn(
  42364. 'cmd.exe',
  42365. ['/C', editor].concat(args),
  42366. { stdio: 'inherit' }
  42367. );
  42368. } else {
  42369. _childProcess = childProcess$1.spawn(editor, args, { stdio: 'inherit' });
  42370. }
  42371. _childProcess.on('exit', function (errorCode) {
  42372. _childProcess = null;
  42373. if (errorCode) {
  42374. onErrorCallback(fileName, '(code ' + errorCode + ')');
  42375. }
  42376. });
  42377. _childProcess.on('error', function (error) {
  42378. onErrorCallback(fileName, error.message);
  42379. });
  42380. }
  42381. var launchEditor_1 = launchEditor;
  42382. const url$2 = require$$0__default$5;
  42383. const path$4 = path__default;
  42384. const launch = launchEditor_1;
  42385. var launchEditorMiddleware = (specifiedEditor, srcRoot, onErrorCallback) => {
  42386. if (typeof specifiedEditor === 'function') {
  42387. onErrorCallback = specifiedEditor;
  42388. specifiedEditor = undefined;
  42389. }
  42390. if (typeof srcRoot === 'function') {
  42391. onErrorCallback = srcRoot;
  42392. srcRoot = undefined;
  42393. }
  42394. srcRoot = srcRoot || process.cwd();
  42395. return function launchEditorMiddleware (req, res, next) {
  42396. const { file } = url$2.parse(req.url, true).query || {};
  42397. if (!file) {
  42398. res.statusCode = 500;
  42399. res.end(`launch-editor-middleware: required query param "file" is missing.`);
  42400. } else {
  42401. launch(path$4.resolve(srcRoot, file), specifiedEditor, onErrorCallback);
  42402. res.end();
  42403. }
  42404. }
  42405. };
  42406. async function resolveHttpServer({ proxy }, app, httpsOptions) {
  42407. if (!httpsOptions) {
  42408. return require('http').createServer(app);
  42409. }
  42410. if (proxy) {
  42411. // #484 fallback to http1 when proxy is needed.
  42412. return require('https').createServer(httpsOptions, app);
  42413. }
  42414. else {
  42415. return require('http2').createSecureServer({
  42416. ...httpsOptions,
  42417. allowHTTP1: true
  42418. }, app);
  42419. }
  42420. }
  42421. async function resolveHttpsConfig(https, cacheDir) {
  42422. if (!https)
  42423. return undefined;
  42424. const httpsOption = isObject$1(https) ? { ...https } : {};
  42425. const { ca, cert, key, pfx } = httpsOption;
  42426. Object.assign(httpsOption, {
  42427. ca: readFileIfExists(ca),
  42428. cert: readFileIfExists(cert),
  42429. key: readFileIfExists(key),
  42430. pfx: readFileIfExists(pfx)
  42431. });
  42432. if (!httpsOption.key || !httpsOption.cert) {
  42433. httpsOption.cert = httpsOption.key = await getCertificate(cacheDir);
  42434. }
  42435. return httpsOption;
  42436. }
  42437. function readFileIfExists(value) {
  42438. if (typeof value === 'string') {
  42439. try {
  42440. return fs__default.readFileSync(path__default.resolve(value));
  42441. }
  42442. catch (e) {
  42443. return value;
  42444. }
  42445. }
  42446. return value;
  42447. }
  42448. async function getCertificate(cacheDir) {
  42449. const cachePath = path__default.join(cacheDir, '_cert.pem');
  42450. try {
  42451. const [stat, content] = await Promise.all([
  42452. fs$n.promises.stat(cachePath),
  42453. fs$n.promises.readFile(cachePath, 'utf8')
  42454. ]);
  42455. if (Date.now() - stat.ctime.valueOf() > 30 * 24 * 60 * 60 * 1000) {
  42456. throw new Error('cache is outdated.');
  42457. }
  42458. return content;
  42459. }
  42460. catch {
  42461. const content = (await Promise.resolve().then(function () { return require('./dep-24755698.js'); })).createCertificate();
  42462. fs$n.promises
  42463. .mkdir(cacheDir, { recursive: true })
  42464. .then(() => fs$n.promises.writeFile(cachePath, content))
  42465. .catch(() => { });
  42466. return content;
  42467. }
  42468. }
  42469. async function httpServerStart(httpServer, serverOptions) {
  42470. return new Promise((resolve, reject) => {
  42471. let { port, strictPort, host, logger } = serverOptions;
  42472. const onError = (e) => {
  42473. if (e.code === 'EADDRINUSE') {
  42474. if (strictPort) {
  42475. httpServer.removeListener('error', onError);
  42476. reject(new Error(`Port ${port} is already in use`));
  42477. }
  42478. else {
  42479. logger.info(`Port ${port} is in use, trying another one...`);
  42480. httpServer.listen(++port, host);
  42481. }
  42482. }
  42483. else {
  42484. httpServer.removeListener('error', onError);
  42485. reject(e);
  42486. }
  42487. };
  42488. httpServer.on('error', onError);
  42489. httpServer.listen(port, host, () => {
  42490. httpServer.removeListener('error', onError);
  42491. resolve(port);
  42492. });
  42493. });
  42494. }
  42495. /*!
  42496. * etag
  42497. * Copyright(c) 2014-2016 Douglas Christopher Wilson
  42498. * MIT Licensed
  42499. */
  42500. /**
  42501. * Module exports.
  42502. * @public
  42503. */
  42504. var etag_1 = etag;
  42505. /**
  42506. * Module dependencies.
  42507. * @private
  42508. */
  42509. var crypto = require$$1__default$2;
  42510. var Stats = fs__default.Stats;
  42511. /**
  42512. * Module variables.
  42513. * @private
  42514. */
  42515. var toString = Object.prototype.toString;
  42516. /**
  42517. * Generate an entity tag.
  42518. *
  42519. * @param {Buffer|string} entity
  42520. * @return {string}
  42521. * @private
  42522. */
  42523. function entitytag (entity) {
  42524. if (entity.length === 0) {
  42525. // fast-path empty
  42526. return '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"'
  42527. }
  42528. // compute hash of entity
  42529. var hash = crypto
  42530. .createHash('sha1')
  42531. .update(entity, 'utf8')
  42532. .digest('base64')
  42533. .substring(0, 27);
  42534. // compute length of entity
  42535. var len = typeof entity === 'string'
  42536. ? Buffer.byteLength(entity, 'utf8')
  42537. : entity.length;
  42538. return '"' + len.toString(16) + '-' + hash + '"'
  42539. }
  42540. /**
  42541. * Create a simple ETag.
  42542. *
  42543. * @param {string|Buffer|Stats} entity
  42544. * @param {object} [options]
  42545. * @param {boolean} [options.weak]
  42546. * @return {String}
  42547. * @public
  42548. */
  42549. function etag (entity, options) {
  42550. if (entity == null) {
  42551. throw new TypeError('argument entity is required')
  42552. }
  42553. // support fs.Stats object
  42554. var isStats = isstats(entity);
  42555. var weak = options && typeof options.weak === 'boolean'
  42556. ? options.weak
  42557. : isStats;
  42558. // validate argument
  42559. if (!isStats && typeof entity !== 'string' && !Buffer.isBuffer(entity)) {
  42560. throw new TypeError('argument entity must be string, Buffer, or fs.Stats')
  42561. }
  42562. // generate entity tag
  42563. var tag = isStats
  42564. ? stattag(entity)
  42565. : entitytag(entity);
  42566. return weak
  42567. ? 'W/' + tag
  42568. : tag
  42569. }
  42570. /**
  42571. * Determine if object is a Stats object.
  42572. *
  42573. * @param {object} obj
  42574. * @return {boolean}
  42575. * @api private
  42576. */
  42577. function isstats (obj) {
  42578. // genuine fs.Stats
  42579. if (typeof Stats === 'function' && obj instanceof Stats) {
  42580. return true
  42581. }
  42582. // quack quack
  42583. return obj && typeof obj === 'object' &&
  42584. 'ctime' in obj && toString.call(obj.ctime) === '[object Date]' &&
  42585. 'mtime' in obj && toString.call(obj.mtime) === '[object Date]' &&
  42586. 'ino' in obj && typeof obj.ino === 'number' &&
  42587. 'size' in obj && typeof obj.size === 'number'
  42588. }
  42589. /**
  42590. * Generate a tag for a stat.
  42591. *
  42592. * @param {object} stat
  42593. * @return {string}
  42594. * @private
  42595. */
  42596. function stattag (stat) {
  42597. var mtime = stat.mtime.getTime().toString(16);
  42598. var size = stat.size.toString(16);
  42599. return '"' + size + '-' + mtime + '"'
  42600. }
  42601. var convertSourceMap = {};
  42602. var safeBuffer = {exports: {}};
  42603. /* eslint-disable node/no-deprecated-api */
  42604. (function (module, exports) {
  42605. var buffer = require$$0__default$6;
  42606. var Buffer = buffer.Buffer;
  42607. // alternative to using Object.keys for old browsers
  42608. function copyProps (src, dst) {
  42609. for (var key in src) {
  42610. dst[key] = src[key];
  42611. }
  42612. }
  42613. if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
  42614. module.exports = buffer;
  42615. } else {
  42616. // Copy properties from require('buffer')
  42617. copyProps(buffer, exports);
  42618. exports.Buffer = SafeBuffer;
  42619. }
  42620. function SafeBuffer (arg, encodingOrOffset, length) {
  42621. return Buffer(arg, encodingOrOffset, length)
  42622. }
  42623. // Copy static methods from Buffer
  42624. copyProps(Buffer, SafeBuffer);
  42625. SafeBuffer.from = function (arg, encodingOrOffset, length) {
  42626. if (typeof arg === 'number') {
  42627. throw new TypeError('Argument must not be a number')
  42628. }
  42629. return Buffer(arg, encodingOrOffset, length)
  42630. };
  42631. SafeBuffer.alloc = function (size, fill, encoding) {
  42632. if (typeof size !== 'number') {
  42633. throw new TypeError('Argument must be a number')
  42634. }
  42635. var buf = Buffer(size);
  42636. if (fill !== undefined) {
  42637. if (typeof encoding === 'string') {
  42638. buf.fill(fill, encoding);
  42639. } else {
  42640. buf.fill(fill);
  42641. }
  42642. } else {
  42643. buf.fill(0);
  42644. }
  42645. return buf
  42646. };
  42647. SafeBuffer.allocUnsafe = function (size) {
  42648. if (typeof size !== 'number') {
  42649. throw new TypeError('Argument must be a number')
  42650. }
  42651. return Buffer(size)
  42652. };
  42653. SafeBuffer.allocUnsafeSlow = function (size) {
  42654. if (typeof size !== 'number') {
  42655. throw new TypeError('Argument must be a number')
  42656. }
  42657. return buffer.SlowBuffer(size)
  42658. };
  42659. }(safeBuffer, safeBuffer.exports));
  42660. (function (exports) {
  42661. var fs = fs__default;
  42662. var path = path__default;
  42663. var SafeBuffer = safeBuffer.exports;
  42664. Object.defineProperty(exports, 'commentRegex', {
  42665. get: function getCommentRegex () {
  42666. return /^\s*\/(?:\/|\*)[@#]\s+sourceMappingURL=data:(?:application|text)\/json;(?:charset[:=]\S+?;)?base64,(?:.*)$/mg;
  42667. }
  42668. });
  42669. Object.defineProperty(exports, 'mapFileCommentRegex', {
  42670. get: function getMapFileCommentRegex () {
  42671. // Matches sourceMappingURL in either // or /* comment styles.
  42672. return /(?:\/\/[@#][ \t]+sourceMappingURL=([^\s'"`]+?)[ \t]*$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^\*]+?)[ \t]*(?:\*\/){1}[ \t]*$)/mg;
  42673. }
  42674. });
  42675. function decodeBase64(base64) {
  42676. return (SafeBuffer.Buffer.from(base64, 'base64') || "").toString();
  42677. }
  42678. function stripComment(sm) {
  42679. return sm.split(',').pop();
  42680. }
  42681. function readFromFileMap(sm, dir) {
  42682. // NOTE: this will only work on the server since it attempts to read the map file
  42683. var r = exports.mapFileCommentRegex.exec(sm);
  42684. // for some odd reason //# .. captures in 1 and /* .. */ in 2
  42685. var filename = r[1] || r[2];
  42686. var filepath = path.resolve(dir, filename);
  42687. try {
  42688. return fs.readFileSync(filepath, 'utf8');
  42689. } catch (e) {
  42690. throw new Error('An error occurred while trying to read the map file at ' + filepath + '\n' + e);
  42691. }
  42692. }
  42693. function Converter (sm, opts) {
  42694. opts = opts || {};
  42695. if (opts.isFileComment) sm = readFromFileMap(sm, opts.commentFileDir);
  42696. if (opts.hasComment) sm = stripComment(sm);
  42697. if (opts.isEncoded) sm = decodeBase64(sm);
  42698. if (opts.isJSON || opts.isEncoded) sm = JSON.parse(sm);
  42699. this.sourcemap = sm;
  42700. }
  42701. Converter.prototype.toJSON = function (space) {
  42702. return JSON.stringify(this.sourcemap, null, space);
  42703. };
  42704. Converter.prototype.toBase64 = function () {
  42705. var json = this.toJSON();
  42706. return (SafeBuffer.Buffer.from(json, 'utf8') || "").toString('base64');
  42707. };
  42708. Converter.prototype.toComment = function (options) {
  42709. var base64 = this.toBase64();
  42710. var data = 'sourceMappingURL=data:application/json;charset=utf-8;base64,' + base64;
  42711. return options && options.multiline ? '/*# ' + data + ' */' : '//# ' + data;
  42712. };
  42713. // returns copy instead of original
  42714. Converter.prototype.toObject = function () {
  42715. return JSON.parse(this.toJSON());
  42716. };
  42717. Converter.prototype.addProperty = function (key, value) {
  42718. if (this.sourcemap.hasOwnProperty(key)) throw new Error('property "' + key + '" already exists on the sourcemap, use set property instead');
  42719. return this.setProperty(key, value);
  42720. };
  42721. Converter.prototype.setProperty = function (key, value) {
  42722. this.sourcemap[key] = value;
  42723. return this;
  42724. };
  42725. Converter.prototype.getProperty = function (key) {
  42726. return this.sourcemap[key];
  42727. };
  42728. exports.fromObject = function (obj) {
  42729. return new Converter(obj);
  42730. };
  42731. exports.fromJSON = function (json) {
  42732. return new Converter(json, { isJSON: true });
  42733. };
  42734. exports.fromBase64 = function (base64) {
  42735. return new Converter(base64, { isEncoded: true });
  42736. };
  42737. exports.fromComment = function (comment) {
  42738. comment = comment
  42739. .replace(/^\/\*/g, '//')
  42740. .replace(/\*\/$/g, '');
  42741. return new Converter(comment, { isEncoded: true, hasComment: true });
  42742. };
  42743. exports.fromMapFileComment = function (comment, dir) {
  42744. return new Converter(comment, { commentFileDir: dir, isFileComment: true, isJSON: true });
  42745. };
  42746. // Finds last sourcemap comment in file or returns null if none was found
  42747. exports.fromSource = function (content) {
  42748. var m = content.match(exports.commentRegex);
  42749. return m ? exports.fromComment(m.pop()) : null;
  42750. };
  42751. // Finds last sourcemap comment in file or returns null if none was found
  42752. exports.fromMapFileSource = function (content, dir) {
  42753. var m = content.match(exports.mapFileCommentRegex);
  42754. return m ? exports.fromMapFileComment(m.pop(), dir) : null;
  42755. };
  42756. exports.removeComments = function (src) {
  42757. return src.replace(exports.commentRegex, '');
  42758. };
  42759. exports.removeMapFileComments = function (src) {
  42760. return src.replace(exports.mapFileCommentRegex, '');
  42761. };
  42762. exports.generateMapFileComment = function (file, options) {
  42763. var data = 'sourceMappingURL=' + file;
  42764. return options && options.multiline ? '/*# ' + data + ' */' : '//# ' + data;
  42765. };
  42766. }(convertSourceMap));
  42767. /**
  42768. *
  42769. * @param {Node} param
  42770. * @returns {string[]}
  42771. */
  42772. function extract_names(param) {
  42773. return extract_identifiers(param).map(node => node.name);
  42774. }
  42775. /**
  42776. *
  42777. * @param {Node} param
  42778. * @param {Identifier[]} nodes
  42779. * @returns {Identifier[]}
  42780. */
  42781. function extract_identifiers(param, nodes = []) {
  42782. switch (param.type) {
  42783. case 'Identifier':
  42784. nodes.push(param);
  42785. break;
  42786. case 'MemberExpression':
  42787. let object = param;
  42788. while (object.type === 'MemberExpression') {
  42789. object = /** @type {any} */ (object.object);
  42790. }
  42791. nodes.push(/** @type {any} */ (object));
  42792. break;
  42793. case 'ObjectPattern':
  42794. /**
  42795. *
  42796. * @param {Property | RestElement} prop
  42797. */
  42798. const handle_prop = (prop) => {
  42799. if (prop.type === 'RestElement') {
  42800. extract_identifiers(prop.argument, nodes);
  42801. } else {
  42802. extract_identifiers(prop.value, nodes);
  42803. }
  42804. };
  42805. param.properties.forEach(handle_prop);
  42806. break;
  42807. case 'ArrayPattern':
  42808. /**
  42809. *
  42810. * @param {Node} element
  42811. */
  42812. const handle_element = (element) => {
  42813. if (element) extract_identifiers(element, nodes);
  42814. };
  42815. param.elements.forEach(handle_element);
  42816. break;
  42817. case 'RestElement':
  42818. extract_identifiers(param.argument, nodes);
  42819. break;
  42820. case 'AssignmentPattern':
  42821. extract_identifiers(param.left, nodes);
  42822. break;
  42823. }
  42824. return nodes;
  42825. }
  42826. const ssrModuleExportsKey = `__vite_ssr_exports__`;
  42827. const ssrImportKey = `__vite_ssr_import__`;
  42828. const ssrDynamicImportKey = `__vite_ssr_dynamic_import__`;
  42829. const ssrExportAllKey = `__vite_ssr_exportAll__`;
  42830. const ssrImportMetaKey = `__vite_ssr_import_meta__`;
  42831. async function ssrTransform(code, inMap, url) {
  42832. const s = new MagicString(code);
  42833. let ast;
  42834. try {
  42835. ast = parser.parse(code, {
  42836. sourceType: 'module',
  42837. ecmaVersion: 'latest',
  42838. locations: true,
  42839. allowHashBang: true
  42840. });
  42841. }
  42842. catch (err) {
  42843. if (!err.loc || !err.loc.line)
  42844. throw err;
  42845. const line = err.loc.line;
  42846. throw new Error(`Parse failure: ${err.message}\nContents of line ${line}: ${code.split('\n')[line - 1]}`);
  42847. }
  42848. let uid = 0;
  42849. const deps = new Set();
  42850. const dynamicDeps = new Set();
  42851. const idToImportMap = new Map();
  42852. const declaredConst = new Set();
  42853. function defineImport(node, source) {
  42854. deps.add(source);
  42855. const importId = `__vite_ssr_import_${uid++}__`;
  42856. s.appendLeft(node.start, `const ${importId} = await ${ssrImportKey}(${JSON.stringify(source)});\n`);
  42857. return importId;
  42858. }
  42859. function defineExport(position, name, local = name) {
  42860. s.appendLeft(position, `\nObject.defineProperty(${ssrModuleExportsKey}, "${name}", ` +
  42861. `{ enumerable: true, configurable: true, get(){ return ${local} }});`);
  42862. }
  42863. // 1. check all import statements and record id -> importName map
  42864. for (const node of ast.body) {
  42865. // import foo from 'foo' --> foo -> __import_foo__.default
  42866. // import { baz } from 'foo' --> baz -> __import_foo__.baz
  42867. // import * as ok from 'foo' --> ok -> __import_foo__
  42868. if (node.type === 'ImportDeclaration') {
  42869. const importId = defineImport(node, node.source.value);
  42870. for (const spec of node.specifiers) {
  42871. if (spec.type === 'ImportSpecifier') {
  42872. idToImportMap.set(spec.local.name, `${importId}.${spec.imported.name}`);
  42873. }
  42874. else if (spec.type === 'ImportDefaultSpecifier') {
  42875. idToImportMap.set(spec.local.name, `${importId}.default`);
  42876. }
  42877. else {
  42878. // namespace specifier
  42879. idToImportMap.set(spec.local.name, importId);
  42880. }
  42881. }
  42882. s.remove(node.start, node.end);
  42883. }
  42884. }
  42885. // 2. check all export statements and define exports
  42886. for (const node of ast.body) {
  42887. // named exports
  42888. if (node.type === 'ExportNamedDeclaration') {
  42889. if (node.declaration) {
  42890. if (node.declaration.type === 'FunctionDeclaration' ||
  42891. node.declaration.type === 'ClassDeclaration') {
  42892. // export function foo() {}
  42893. defineExport(node.end, node.declaration.id.name);
  42894. }
  42895. else {
  42896. // export const foo = 1, bar = 2
  42897. for (const declaration of node.declaration.declarations) {
  42898. const names = extract_names(declaration.id);
  42899. for (const name of names) {
  42900. defineExport(node.end, name);
  42901. }
  42902. }
  42903. }
  42904. s.remove(node.start, node.declaration.start);
  42905. }
  42906. else {
  42907. s.remove(node.start, node.end);
  42908. if (node.source) {
  42909. // export { foo, bar } from './foo'
  42910. const importId = defineImport(node, node.source.value);
  42911. for (const spec of node.specifiers) {
  42912. defineExport(node.end, spec.exported.name, `${importId}.${spec.local.name}`);
  42913. }
  42914. }
  42915. else {
  42916. // export { foo, bar }
  42917. for (const spec of node.specifiers) {
  42918. const local = spec.local.name;
  42919. const binding = idToImportMap.get(local);
  42920. defineExport(node.end, spec.exported.name, binding || local);
  42921. }
  42922. }
  42923. }
  42924. }
  42925. // default export
  42926. if (node.type === 'ExportDefaultDeclaration') {
  42927. const expressionTypes = ['FunctionExpression', 'ClassExpression'];
  42928. if ('id' in node.declaration &&
  42929. node.declaration.id &&
  42930. !expressionTypes.includes(node.declaration.type)) {
  42931. // named hoistable/class exports
  42932. // export default function foo() {}
  42933. // export default class A {}
  42934. const { name } = node.declaration.id;
  42935. s.remove(node.start, node.start + 15 /* 'export default '.length */);
  42936. s.append(`\nObject.defineProperty(${ssrModuleExportsKey}, "default", ` +
  42937. `{ enumerable: true, value: ${name} });`);
  42938. }
  42939. else {
  42940. // anonymous default exports
  42941. s.overwrite(node.start, node.start + 14 /* 'export default'.length */, `${ssrModuleExportsKey}.default =`, { contentOnly: true });
  42942. }
  42943. }
  42944. // export * from './foo'
  42945. if (node.type === 'ExportAllDeclaration') {
  42946. if (node.exported) {
  42947. const importId = defineImport(node, node.source.value);
  42948. s.remove(node.start, node.end);
  42949. defineExport(node.end, node.exported.name, `${importId}`);
  42950. }
  42951. else {
  42952. const importId = defineImport(node, node.source.value);
  42953. s.remove(node.start, node.end);
  42954. s.appendLeft(node.end, `${ssrExportAllKey}(${importId});`);
  42955. }
  42956. }
  42957. }
  42958. // 3. convert references to import bindings & import.meta references
  42959. walk(ast, {
  42960. onIdentifier(id, parent, parentStack) {
  42961. const grandparent = parentStack[1];
  42962. const binding = idToImportMap.get(id.name);
  42963. if (!binding) {
  42964. return;
  42965. }
  42966. if (isStaticProperty(parent) && parent.shorthand) {
  42967. // let binding used in a property shorthand
  42968. // { foo } -> { foo: __import_x__.foo }
  42969. // skip for destructuring patterns
  42970. if (!isNodeInPatternWeakMap.get(parent) ||
  42971. isInDestructuringAssignment(parent, parentStack)) {
  42972. s.appendLeft(id.end, `: ${binding}`);
  42973. }
  42974. }
  42975. else if ((parent.type === 'PropertyDefinition' &&
  42976. (grandparent === null || grandparent === void 0 ? void 0 : grandparent.type) === 'ClassBody') ||
  42977. (parent.type === 'ClassDeclaration' && id === parent.superClass)) {
  42978. if (!declaredConst.has(id.name)) {
  42979. declaredConst.add(id.name);
  42980. // locate the top-most node containing the class declaration
  42981. const topNode = parentStack[parentStack.length - 2];
  42982. s.prependRight(topNode.start, `const ${id.name} = ${binding};\n`);
  42983. }
  42984. }
  42985. else {
  42986. s.overwrite(id.start, id.end, binding, { contentOnly: true });
  42987. }
  42988. },
  42989. onImportMeta(node) {
  42990. s.overwrite(node.start, node.end, ssrImportMetaKey, { contentOnly: true });
  42991. },
  42992. onDynamicImport(node) {
  42993. s.overwrite(node.start, node.start + 6, ssrDynamicImportKey, {
  42994. contentOnly: true
  42995. });
  42996. if (node.type === 'ImportExpression' && node.source.type === 'Literal') {
  42997. dynamicDeps.add(node.source.value);
  42998. }
  42999. }
  43000. });
  43001. let map = s.generateMap({ hires: true });
  43002. if (inMap && inMap.mappings && inMap.sources.length > 0) {
  43003. map = combineSourcemaps(url, [
  43004. {
  43005. ...map,
  43006. sources: inMap.sources,
  43007. sourcesContent: inMap.sourcesContent
  43008. },
  43009. inMap
  43010. ]);
  43011. }
  43012. else {
  43013. map.sources = [url];
  43014. map.sourcesContent = [code];
  43015. }
  43016. return {
  43017. code: s.toString(),
  43018. map,
  43019. deps: [...deps],
  43020. dynamicDeps: [...dynamicDeps]
  43021. };
  43022. }
  43023. const isNodeInPatternWeakMap = new WeakMap();
  43024. /**
  43025. * Same logic from \@vue/compiler-core & \@vue/compiler-sfc
  43026. * Except this is using acorn AST
  43027. */
  43028. function walk(root, { onIdentifier, onImportMeta, onDynamicImport }) {
  43029. const parentStack = [];
  43030. const scopeMap = new WeakMap();
  43031. const identifiers = [];
  43032. const setScope = (node, name) => {
  43033. let scopeIds = scopeMap.get(node);
  43034. if (scopeIds && scopeIds.has(name)) {
  43035. return;
  43036. }
  43037. if (!scopeIds) {
  43038. scopeIds = new Set();
  43039. scopeMap.set(node, scopeIds);
  43040. }
  43041. scopeIds.add(name);
  43042. };
  43043. function isInScope(name, parents) {
  43044. return parents.some((node) => { var _a; return node && ((_a = scopeMap.get(node)) === null || _a === void 0 ? void 0 : _a.has(name)); });
  43045. }
  43046. function handlePattern(p, parentFunction) {
  43047. if (p.type === 'Identifier') {
  43048. setScope(parentFunction, p.name);
  43049. }
  43050. else if (p.type === 'RestElement') {
  43051. handlePattern(p.argument, parentFunction);
  43052. }
  43053. else if (p.type === 'ObjectPattern') {
  43054. p.properties.forEach((property) => {
  43055. if (property.type === 'RestElement') {
  43056. setScope(parentFunction, property.argument.name);
  43057. }
  43058. else {
  43059. handlePattern(property.value, parentFunction);
  43060. }
  43061. });
  43062. }
  43063. else if (p.type === 'ArrayPattern') {
  43064. p.elements.forEach((element) => {
  43065. if (element) {
  43066. handlePattern(element, parentFunction);
  43067. }
  43068. });
  43069. }
  43070. else if (p.type === 'AssignmentPattern') {
  43071. handlePattern(p.left, parentFunction);
  43072. }
  43073. else {
  43074. setScope(parentFunction, p.name);
  43075. }
  43076. }
  43077. walk$2(root, {
  43078. enter(node, parent) {
  43079. if (node.type === 'ImportDeclaration') {
  43080. return this.skip();
  43081. }
  43082. parent && parentStack.unshift(parent);
  43083. if (node.type === 'MetaProperty' && node.meta.name === 'import') {
  43084. onImportMeta(node);
  43085. }
  43086. else if (node.type === 'ImportExpression') {
  43087. onDynamicImport(node);
  43088. }
  43089. if (node.type === 'Identifier') {
  43090. if (!isInScope(node.name, parentStack) &&
  43091. isRefIdentifier(node, parent, parentStack)) {
  43092. // record the identifier, for DFS -> BFS
  43093. identifiers.push([node, parentStack.slice(0)]);
  43094. }
  43095. }
  43096. else if (isFunction(node)) {
  43097. // If it is a function declaration, it could be shadowing an import
  43098. // Add its name to the scope so it won't get replaced
  43099. if (node.type === 'FunctionDeclaration') {
  43100. const parentFunction = findParentFunction(parentStack);
  43101. if (parentFunction) {
  43102. setScope(parentFunction, node.id.name);
  43103. }
  43104. }
  43105. // walk function expressions and add its arguments to known identifiers
  43106. // so that we don't prefix them
  43107. node.params.forEach((p) => {
  43108. if (p.type === 'ObjectPattern' || p.type === 'ArrayPattern') {
  43109. handlePattern(p, node);
  43110. return;
  43111. }
  43112. walk$2(p.type === 'AssignmentPattern' ? p.left : p, {
  43113. enter(child, parent) {
  43114. // skip params default value of destructure
  43115. if ((parent === null || parent === void 0 ? void 0 : parent.type) === 'AssignmentPattern' &&
  43116. (parent === null || parent === void 0 ? void 0 : parent.right) === child) {
  43117. return this.skip();
  43118. }
  43119. if (child.type !== 'Identifier')
  43120. return;
  43121. // do not record as scope variable if is a destructuring keyword
  43122. if (isStaticPropertyKey(child, parent))
  43123. return;
  43124. // do not record if this is a default value
  43125. // assignment of a destructuring variable
  43126. if (((parent === null || parent === void 0 ? void 0 : parent.type) === 'TemplateLiteral' &&
  43127. (parent === null || parent === void 0 ? void 0 : parent.expressions.includes(child))) ||
  43128. ((parent === null || parent === void 0 ? void 0 : parent.type) === 'CallExpression' && (parent === null || parent === void 0 ? void 0 : parent.callee) === child)) {
  43129. return;
  43130. }
  43131. setScope(node, child.name);
  43132. }
  43133. });
  43134. });
  43135. }
  43136. else if (node.type === 'Property' && parent.type === 'ObjectPattern') {
  43137. // mark property in destructuring pattern
  43138. isNodeInPatternWeakMap.set(node, true);
  43139. }
  43140. else if (node.type === 'VariableDeclarator') {
  43141. const parentFunction = findParentFunction(parentStack);
  43142. if (parentFunction) {
  43143. handlePattern(node.id, parentFunction);
  43144. }
  43145. }
  43146. },
  43147. leave(node, parent) {
  43148. parent && parentStack.shift();
  43149. }
  43150. });
  43151. // emit the identifier events in BFS so the hoisted declarations
  43152. // can be captured correctly
  43153. identifiers.forEach(([node, stack]) => {
  43154. if (!isInScope(node.name, stack))
  43155. onIdentifier(node, stack[0], stack);
  43156. });
  43157. }
  43158. function isRefIdentifier(id, parent, parentStack) {
  43159. // declaration id
  43160. if (parent.type === 'CatchClause' ||
  43161. ((parent.type === 'VariableDeclarator' ||
  43162. parent.type === 'ClassDeclaration') &&
  43163. parent.id === id)) {
  43164. return false;
  43165. }
  43166. if (isFunction(parent)) {
  43167. // function declaration/expression id
  43168. if (parent.id === id) {
  43169. return false;
  43170. }
  43171. // params list
  43172. if (parent.params.includes(id)) {
  43173. return false;
  43174. }
  43175. }
  43176. // class method name
  43177. if (parent.type === 'MethodDefinition' && !parent.computed) {
  43178. return false;
  43179. }
  43180. // property key
  43181. // this also covers object destructuring pattern
  43182. if (isStaticPropertyKey(id, parent) || isNodeInPatternWeakMap.get(parent)) {
  43183. return false;
  43184. }
  43185. // non-assignment array destructuring pattern
  43186. if (parent.type === 'ArrayPattern' &&
  43187. !isInDestructuringAssignment(parent, parentStack)) {
  43188. return false;
  43189. }
  43190. // member expression property
  43191. if (parent.type === 'MemberExpression' &&
  43192. parent.property === id &&
  43193. !parent.computed) {
  43194. return false;
  43195. }
  43196. if (parent.type === 'ExportSpecifier') {
  43197. return false;
  43198. }
  43199. // is a special keyword but parsed as identifier
  43200. if (id.name === 'arguments') {
  43201. return false;
  43202. }
  43203. return true;
  43204. }
  43205. const isStaticProperty = (node) => node && node.type === 'Property' && !node.computed;
  43206. const isStaticPropertyKey = (node, parent) => isStaticProperty(parent) && parent.key === node;
  43207. function isFunction(node) {
  43208. return /Function(?:Expression|Declaration)$|Method$/.test(node.type);
  43209. }
  43210. function findParentFunction(parentStack) {
  43211. return parentStack.find((i) => isFunction(i));
  43212. }
  43213. function isInDestructuringAssignment(parent, parentStack) {
  43214. if (parent &&
  43215. (parent.type === 'Property' || parent.type === 'ArrayPattern')) {
  43216. return parentStack.some((i) => i.type === 'AssignmentExpression');
  43217. }
  43218. return false;
  43219. }
  43220. function totalist(dir, callback, pre='') {
  43221. dir = path$r.resolve('.', dir);
  43222. let arr = fs$n.readdirSync(dir);
  43223. let i=0, abs, stats;
  43224. for (; i < arr.length; i++) {
  43225. abs = path$r.join(dir, arr[i]);
  43226. stats = fs$n.statSync(abs);
  43227. stats.isDirectory()
  43228. ? totalist(abs, callback, path$r.join(pre, arr[i]))
  43229. : callback(path$r.join(pre, arr[i]), abs, stats);
  43230. }
  43231. }
  43232. /**
  43233. * @typedef ParsedURL
  43234. * @type {import('.').ParsedURL}
  43235. */
  43236. /**
  43237. * @typedef Request
  43238. * @property {string} url
  43239. * @property {ParsedURL} _parsedUrl
  43240. */
  43241. /**
  43242. * @param {Request} req
  43243. * @returns {ParsedURL|void}
  43244. */
  43245. function parse$5(req) {
  43246. let raw = req.url;
  43247. if (raw == null) return;
  43248. let prev = req._parsedUrl;
  43249. if (prev && prev.raw === raw) return prev;
  43250. let pathname=raw, search='', query;
  43251. if (raw.length > 1) {
  43252. let idx = raw.indexOf('?', 1);
  43253. if (idx !== -1) {
  43254. search = raw.substring(idx);
  43255. pathname = raw.substring(0, idx);
  43256. if (search.length > 1) {
  43257. query = qs__namespace.parse(search.substring(1));
  43258. }
  43259. }
  43260. }
  43261. return req._parsedUrl = { pathname, search, query, raw };
  43262. }
  43263. const noop$2 = () => {};
  43264. function isMatch(uri, arr) {
  43265. for (let i=0; i < arr.length; i++) {
  43266. if (arr[i].test(uri)) return true;
  43267. }
  43268. }
  43269. function toAssume(uri, extns) {
  43270. let i=0, x, len=uri.length - 1;
  43271. if (uri.charCodeAt(len) === 47) {
  43272. uri = uri.substring(0, len);
  43273. }
  43274. let arr=[], tmp=`${uri}/index`;
  43275. for (; i < extns.length; i++) {
  43276. x = extns[i] ? `.${extns[i]}` : '';
  43277. if (uri) arr.push(uri + x);
  43278. arr.push(tmp + x);
  43279. }
  43280. return arr;
  43281. }
  43282. function viaCache(cache, uri, extns) {
  43283. let i=0, data, arr=toAssume(uri, extns);
  43284. for (; i < arr.length; i++) {
  43285. if (data = cache[arr[i]]) return data;
  43286. }
  43287. }
  43288. function viaLocal(dir, isEtag, uri, extns) {
  43289. let i=0, arr=toAssume(uri, extns);
  43290. let abs, stats, name, headers;
  43291. for (; i < arr.length; i++) {
  43292. abs = path$r.normalize(path$r.join(dir, name=arr[i]));
  43293. if (abs.startsWith(dir) && fs__namespace.existsSync(abs)) {
  43294. stats = fs__namespace.statSync(abs);
  43295. if (stats.isDirectory()) continue;
  43296. headers = toHeaders(name, stats, isEtag);
  43297. headers['Cache-Control'] = isEtag ? 'no-cache' : 'no-store';
  43298. return { abs, stats, headers };
  43299. }
  43300. }
  43301. }
  43302. function is404(req, res) {
  43303. return (res.statusCode=404,res.end());
  43304. }
  43305. function send$1(req, res, file, stats, headers) {
  43306. let code=200, tmp, opts={};
  43307. headers = { ...headers };
  43308. for (let key in headers) {
  43309. tmp = res.getHeader(key);
  43310. if (tmp) headers[key] = tmp;
  43311. }
  43312. if (tmp = res.getHeader('content-type')) {
  43313. headers['Content-Type'] = tmp;
  43314. }
  43315. if (req.headers.range) {
  43316. code = 206;
  43317. let [x, y] = req.headers.range.replace('bytes=', '').split('-');
  43318. let end = opts.end = parseInt(y, 10) || stats.size - 1;
  43319. let start = opts.start = parseInt(x, 10) || 0;
  43320. if (start >= stats.size || end >= stats.size) {
  43321. res.setHeader('Content-Range', `bytes */${stats.size}`);
  43322. res.statusCode = 416;
  43323. return res.end();
  43324. }
  43325. headers['Content-Range'] = `bytes ${start}-${end}/${stats.size}`;
  43326. headers['Content-Length'] = (end - start + 1);
  43327. headers['Accept-Ranges'] = 'bytes';
  43328. }
  43329. res.writeHead(code, headers);
  43330. fs__namespace.createReadStream(file, opts).pipe(res);
  43331. }
  43332. const ENCODING = {
  43333. '.br': 'br',
  43334. '.gz': 'gzip',
  43335. };
  43336. function toHeaders(name, stats, isEtag) {
  43337. let enc = ENCODING[name.slice(-3)];
  43338. let ctype = lookup(name.slice(0, enc && -3)) || '';
  43339. if (ctype === 'text/html') ctype += ';charset=utf-8';
  43340. let headers = {
  43341. 'Content-Length': stats.size,
  43342. 'Content-Type': ctype,
  43343. 'Last-Modified': stats.mtime.toUTCString(),
  43344. };
  43345. if (enc) headers['Content-Encoding'] = enc;
  43346. if (isEtag) headers['ETag'] = `W/"${stats.size}-${stats.mtime.getTime()}"`;
  43347. return headers;
  43348. }
  43349. function sirv (dir, opts={}) {
  43350. dir = path$r.resolve(dir || '.');
  43351. let isNotFound = opts.onNoMatch || is404;
  43352. let setHeaders = opts.setHeaders || noop$2;
  43353. let extensions = opts.extensions || ['html', 'htm'];
  43354. let gzips = opts.gzip && extensions.map(x => `${x}.gz`).concat('gz');
  43355. let brots = opts.brotli && extensions.map(x => `${x}.br`).concat('br');
  43356. const FILES = {};
  43357. let fallback = '/';
  43358. let isEtag = !!opts.etag;
  43359. let isSPA = !!opts.single;
  43360. if (typeof opts.single === 'string') {
  43361. let idx = opts.single.lastIndexOf('.');
  43362. fallback += !!~idx ? opts.single.substring(0, idx) : opts.single;
  43363. }
  43364. let ignores = [];
  43365. if (opts.ignores !== false) {
  43366. ignores.push(/[/]([A-Za-z\s\d~$._-]+\.\w+){1,}$/); // any extn
  43367. if (opts.dotfiles) ignores.push(/\/\.\w/);
  43368. else ignores.push(/\/\.well-known/);
  43369. [].concat(opts.ignores || []).forEach(x => {
  43370. ignores.push(new RegExp(x, 'i'));
  43371. });
  43372. }
  43373. let cc = opts.maxAge != null && `public,max-age=${opts.maxAge}`;
  43374. if (cc && opts.immutable) cc += ',immutable';
  43375. else if (cc && opts.maxAge === 0) cc += ',must-revalidate';
  43376. if (!opts.dev) {
  43377. totalist(dir, (name, abs, stats) => {
  43378. if (/\.well-known[\\+\/]/.test(name)) ; // keep
  43379. else if (!opts.dotfiles && /(^\.|[\\+|\/+]\.)/.test(name)) return;
  43380. let headers = toHeaders(name, stats, isEtag);
  43381. if (cc) headers['Cache-Control'] = cc;
  43382. FILES['/' + name.normalize().replace(/\\+/g, '/')] = { abs, stats, headers };
  43383. });
  43384. }
  43385. let lookup = opts.dev ? viaLocal.bind(0, dir, isEtag) : viaCache.bind(0, FILES);
  43386. return function (req, res, next) {
  43387. let extns = [''];
  43388. let pathname = parse$5(req).pathname;
  43389. let val = req.headers['accept-encoding'] || '';
  43390. if (gzips && val.includes('gzip')) extns.unshift(...gzips);
  43391. if (brots && /(br|brotli)/i.test(val)) extns.unshift(...brots);
  43392. extns.push(...extensions); // [...br, ...gz, orig, ...exts]
  43393. if (pathname.indexOf('%') !== -1) {
  43394. try { pathname = decodeURIComponent(pathname); }
  43395. catch (err) { /* malform uri */ }
  43396. }
  43397. let data = lookup(pathname, extns) || isSPA && !isMatch(pathname, ignores) && lookup(fallback, extns);
  43398. if (!data) return next ? next() : isNotFound(req, res);
  43399. if (isEtag && req.headers['if-none-match'] === data.headers['ETag']) {
  43400. res.writeHead(304);
  43401. return res.end();
  43402. }
  43403. if (gzips || brots) {
  43404. res.setHeader('Vary', 'Accept-Encoding');
  43405. }
  43406. setHeaders(res, pathname, data.stats);
  43407. send$1(req, res, data.abs, data.stats, data.headers);
  43408. };
  43409. }
  43410. const util = require$$0__default$2;
  43411. const braces = braces_1;
  43412. const picomatch = picomatch$6;
  43413. const utils = utils$p;
  43414. const isEmptyString = val => val === '' || val === './';
  43415. /**
  43416. * Returns an array of strings that match one or more glob patterns.
  43417. *
  43418. * ```js
  43419. * const mm = require('micromatch');
  43420. * // mm(list, patterns[, options]);
  43421. *
  43422. * console.log(mm(['a.js', 'a.txt'], ['*.js']));
  43423. * //=> [ 'a.js' ]
  43424. * ```
  43425. * @param {String|Array<string>} `list` List of strings to match.
  43426. * @param {String|Array<string>} `patterns` One or more glob patterns to use for matching.
  43427. * @param {Object} `options` See available [options](#options)
  43428. * @return {Array} Returns an array of matches
  43429. * @summary false
  43430. * @api public
  43431. */
  43432. const micromatch = (list, patterns, options) => {
  43433. patterns = [].concat(patterns);
  43434. list = [].concat(list);
  43435. let omit = new Set();
  43436. let keep = new Set();
  43437. let items = new Set();
  43438. let negatives = 0;
  43439. let onResult = state => {
  43440. items.add(state.output);
  43441. if (options && options.onResult) {
  43442. options.onResult(state);
  43443. }
  43444. };
  43445. for (let i = 0; i < patterns.length; i++) {
  43446. let isMatch = picomatch(String(patterns[i]), { ...options, onResult }, true);
  43447. let negated = isMatch.state.negated || isMatch.state.negatedExtglob;
  43448. if (negated) negatives++;
  43449. for (let item of list) {
  43450. let matched = isMatch(item, true);
  43451. let match = negated ? !matched.isMatch : matched.isMatch;
  43452. if (!match) continue;
  43453. if (negated) {
  43454. omit.add(matched.output);
  43455. } else {
  43456. omit.delete(matched.output);
  43457. keep.add(matched.output);
  43458. }
  43459. }
  43460. }
  43461. let result = negatives === patterns.length ? [...items] : [...keep];
  43462. let matches = result.filter(item => !omit.has(item));
  43463. if (options && matches.length === 0) {
  43464. if (options.failglob === true) {
  43465. throw new Error(`No matches found for "${patterns.join(', ')}"`);
  43466. }
  43467. if (options.nonull === true || options.nullglob === true) {
  43468. return options.unescape ? patterns.map(p => p.replace(/\\/g, '')) : patterns;
  43469. }
  43470. }
  43471. return matches;
  43472. };
  43473. /**
  43474. * Backwards compatibility
  43475. */
  43476. micromatch.match = micromatch;
  43477. /**
  43478. * Returns a matcher function from the given glob `pattern` and `options`.
  43479. * The returned function takes a string to match as its only argument and returns
  43480. * true if the string is a match.
  43481. *
  43482. * ```js
  43483. * const mm = require('micromatch');
  43484. * // mm.matcher(pattern[, options]);
  43485. *
  43486. * const isMatch = mm.matcher('*.!(*a)');
  43487. * console.log(isMatch('a.a')); //=> false
  43488. * console.log(isMatch('a.b')); //=> true
  43489. * ```
  43490. * @param {String} `pattern` Glob pattern
  43491. * @param {Object} `options`
  43492. * @return {Function} Returns a matcher function.
  43493. * @api public
  43494. */
  43495. micromatch.matcher = (pattern, options) => picomatch(pattern, options);
  43496. /**
  43497. * Returns true if **any** of the given glob `patterns` match the specified `string`.
  43498. *
  43499. * ```js
  43500. * const mm = require('micromatch');
  43501. * // mm.isMatch(string, patterns[, options]);
  43502. *
  43503. * console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true
  43504. * console.log(mm.isMatch('a.a', 'b.*')); //=> false
  43505. * ```
  43506. * @param {String} `str` The string to test.
  43507. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  43508. * @param {Object} `[options]` See available [options](#options).
  43509. * @return {Boolean} Returns true if any patterns match `str`
  43510. * @api public
  43511. */
  43512. micromatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
  43513. /**
  43514. * Backwards compatibility
  43515. */
  43516. micromatch.any = micromatch.isMatch;
  43517. /**
  43518. * Returns a list of strings that _**do not match any**_ of the given `patterns`.
  43519. *
  43520. * ```js
  43521. * const mm = require('micromatch');
  43522. * // mm.not(list, patterns[, options]);
  43523. *
  43524. * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a'));
  43525. * //=> ['b.b', 'c.c']
  43526. * ```
  43527. * @param {Array} `list` Array of strings to match.
  43528. * @param {String|Array} `patterns` One or more glob pattern to use for matching.
  43529. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  43530. * @return {Array} Returns an array of strings that **do not match** the given patterns.
  43531. * @api public
  43532. */
  43533. micromatch.not = (list, patterns, options = {}) => {
  43534. patterns = [].concat(patterns).map(String);
  43535. let result = new Set();
  43536. let items = [];
  43537. let onResult = state => {
  43538. if (options.onResult) options.onResult(state);
  43539. items.push(state.output);
  43540. };
  43541. let matches = new Set(micromatch(list, patterns, { ...options, onResult }));
  43542. for (let item of items) {
  43543. if (!matches.has(item)) {
  43544. result.add(item);
  43545. }
  43546. }
  43547. return [...result];
  43548. };
  43549. /**
  43550. * Returns true if the given `string` contains the given pattern. Similar
  43551. * to [.isMatch](#isMatch) but the pattern can match any part of the string.
  43552. *
  43553. * ```js
  43554. * var mm = require('micromatch');
  43555. * // mm.contains(string, pattern[, options]);
  43556. *
  43557. * console.log(mm.contains('aa/bb/cc', '*b'));
  43558. * //=> true
  43559. * console.log(mm.contains('aa/bb/cc', '*d'));
  43560. * //=> false
  43561. * ```
  43562. * @param {String} `str` The string to match.
  43563. * @param {String|Array} `patterns` Glob pattern to use for matching.
  43564. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  43565. * @return {Boolean} Returns true if any of the patterns matches any part of `str`.
  43566. * @api public
  43567. */
  43568. micromatch.contains = (str, pattern, options) => {
  43569. if (typeof str !== 'string') {
  43570. throw new TypeError(`Expected a string: "${util.inspect(str)}"`);
  43571. }
  43572. if (Array.isArray(pattern)) {
  43573. return pattern.some(p => micromatch.contains(str, p, options));
  43574. }
  43575. if (typeof pattern === 'string') {
  43576. if (isEmptyString(str) || isEmptyString(pattern)) {
  43577. return false;
  43578. }
  43579. if (str.includes(pattern) || (str.startsWith('./') && str.slice(2).includes(pattern))) {
  43580. return true;
  43581. }
  43582. }
  43583. return micromatch.isMatch(str, pattern, { ...options, contains: true });
  43584. };
  43585. /**
  43586. * Filter the keys of the given object with the given `glob` pattern
  43587. * and `options`. Does not attempt to match nested keys. If you need this feature,
  43588. * use [glob-object][] instead.
  43589. *
  43590. * ```js
  43591. * const mm = require('micromatch');
  43592. * // mm.matchKeys(object, patterns[, options]);
  43593. *
  43594. * const obj = { aa: 'a', ab: 'b', ac: 'c' };
  43595. * console.log(mm.matchKeys(obj, '*b'));
  43596. * //=> { ab: 'b' }
  43597. * ```
  43598. * @param {Object} `object` The object with keys to filter.
  43599. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  43600. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  43601. * @return {Object} Returns an object with only keys that match the given patterns.
  43602. * @api public
  43603. */
  43604. micromatch.matchKeys = (obj, patterns, options) => {
  43605. if (!utils.isObject(obj)) {
  43606. throw new TypeError('Expected the first argument to be an object');
  43607. }
  43608. let keys = micromatch(Object.keys(obj), patterns, options);
  43609. let res = {};
  43610. for (let key of keys) res[key] = obj[key];
  43611. return res;
  43612. };
  43613. /**
  43614. * Returns true if some of the strings in the given `list` match any of the given glob `patterns`.
  43615. *
  43616. * ```js
  43617. * const mm = require('micromatch');
  43618. * // mm.some(list, patterns[, options]);
  43619. *
  43620. * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
  43621. * // true
  43622. * console.log(mm.some(['foo.js'], ['*.js', '!foo.js']));
  43623. * // false
  43624. * ```
  43625. * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found.
  43626. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  43627. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  43628. * @return {Boolean} Returns true if any `patterns` matches any of the strings in `list`
  43629. * @api public
  43630. */
  43631. micromatch.some = (list, patterns, options) => {
  43632. let items = [].concat(list);
  43633. for (let pattern of [].concat(patterns)) {
  43634. let isMatch = picomatch(String(pattern), options);
  43635. if (items.some(item => isMatch(item))) {
  43636. return true;
  43637. }
  43638. }
  43639. return false;
  43640. };
  43641. /**
  43642. * Returns true if every string in the given `list` matches
  43643. * any of the given glob `patterns`.
  43644. *
  43645. * ```js
  43646. * const mm = require('micromatch');
  43647. * // mm.every(list, patterns[, options]);
  43648. *
  43649. * console.log(mm.every('foo.js', ['foo.js']));
  43650. * // true
  43651. * console.log(mm.every(['foo.js', 'bar.js'], ['*.js']));
  43652. * // true
  43653. * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
  43654. * // false
  43655. * console.log(mm.every(['foo.js'], ['*.js', '!foo.js']));
  43656. * // false
  43657. * ```
  43658. * @param {String|Array} `list` The string or array of strings to test.
  43659. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  43660. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  43661. * @return {Boolean} Returns true if all `patterns` matches all of the strings in `list`
  43662. * @api public
  43663. */
  43664. micromatch.every = (list, patterns, options) => {
  43665. let items = [].concat(list);
  43666. for (let pattern of [].concat(patterns)) {
  43667. let isMatch = picomatch(String(pattern), options);
  43668. if (!items.every(item => isMatch(item))) {
  43669. return false;
  43670. }
  43671. }
  43672. return true;
  43673. };
  43674. /**
  43675. * Returns true if **all** of the given `patterns` match
  43676. * the specified string.
  43677. *
  43678. * ```js
  43679. * const mm = require('micromatch');
  43680. * // mm.all(string, patterns[, options]);
  43681. *
  43682. * console.log(mm.all('foo.js', ['foo.js']));
  43683. * // true
  43684. *
  43685. * console.log(mm.all('foo.js', ['*.js', '!foo.js']));
  43686. * // false
  43687. *
  43688. * console.log(mm.all('foo.js', ['*.js', 'foo.js']));
  43689. * // true
  43690. *
  43691. * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js']));
  43692. * // true
  43693. * ```
  43694. * @param {String|Array} `str` The string to test.
  43695. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  43696. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  43697. * @return {Boolean} Returns true if any patterns match `str`
  43698. * @api public
  43699. */
  43700. micromatch.all = (str, patterns, options) => {
  43701. if (typeof str !== 'string') {
  43702. throw new TypeError(`Expected a string: "${util.inspect(str)}"`);
  43703. }
  43704. return [].concat(patterns).every(p => picomatch(p, options)(str));
  43705. };
  43706. /**
  43707. * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match.
  43708. *
  43709. * ```js
  43710. * const mm = require('micromatch');
  43711. * // mm.capture(pattern, string[, options]);
  43712. *
  43713. * console.log(mm.capture('test/*.js', 'test/foo.js'));
  43714. * //=> ['foo']
  43715. * console.log(mm.capture('test/*.js', 'foo/bar.css'));
  43716. * //=> null
  43717. * ```
  43718. * @param {String} `glob` Glob pattern to use for matching.
  43719. * @param {String} `input` String to match
  43720. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  43721. * @return {Array|null} Returns an array of captures if the input matches the glob pattern, otherwise `null`.
  43722. * @api public
  43723. */
  43724. micromatch.capture = (glob, input, options) => {
  43725. let posix = utils.isWindows(options);
  43726. let regex = picomatch.makeRe(String(glob), { ...options, capture: true });
  43727. let match = regex.exec(posix ? utils.toPosixSlashes(input) : input);
  43728. if (match) {
  43729. return match.slice(1).map(v => v === void 0 ? '' : v);
  43730. }
  43731. };
  43732. /**
  43733. * Create a regular expression from the given glob `pattern`.
  43734. *
  43735. * ```js
  43736. * const mm = require('micromatch');
  43737. * // mm.makeRe(pattern[, options]);
  43738. *
  43739. * console.log(mm.makeRe('*.js'));
  43740. * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/
  43741. * ```
  43742. * @param {String} `pattern` A glob pattern to convert to regex.
  43743. * @param {Object} `options`
  43744. * @return {RegExp} Returns a regex created from the given pattern.
  43745. * @api public
  43746. */
  43747. micromatch.makeRe = (...args) => picomatch.makeRe(...args);
  43748. /**
  43749. * Scan a glob pattern to separate the pattern into segments. Used
  43750. * by the [split](#split) method.
  43751. *
  43752. * ```js
  43753. * const mm = require('micromatch');
  43754. * const state = mm.scan(pattern[, options]);
  43755. * ```
  43756. * @param {String} `pattern`
  43757. * @param {Object} `options`
  43758. * @return {Object} Returns an object with
  43759. * @api public
  43760. */
  43761. micromatch.scan = (...args) => picomatch.scan(...args);
  43762. /**
  43763. * Parse a glob pattern to create the source string for a regular
  43764. * expression.
  43765. *
  43766. * ```js
  43767. * const mm = require('micromatch');
  43768. * const state = mm.parse(pattern[, options]);
  43769. * ```
  43770. * @param {String} `glob`
  43771. * @param {Object} `options`
  43772. * @return {Object} Returns an object with useful properties and output to be used as regex source string.
  43773. * @api public
  43774. */
  43775. micromatch.parse = (patterns, options) => {
  43776. let res = [];
  43777. for (let pattern of [].concat(patterns || [])) {
  43778. for (let str of braces(String(pattern), options)) {
  43779. res.push(picomatch.parse(str, options));
  43780. }
  43781. }
  43782. return res;
  43783. };
  43784. /**
  43785. * Process the given brace `pattern`.
  43786. *
  43787. * ```js
  43788. * const { braces } = require('micromatch');
  43789. * console.log(braces('foo/{a,b,c}/bar'));
  43790. * //=> [ 'foo/(a|b|c)/bar' ]
  43791. *
  43792. * console.log(braces('foo/{a,b,c}/bar', { expand: true }));
  43793. * //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ]
  43794. * ```
  43795. * @param {String} `pattern` String with brace pattern to process.
  43796. * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options.
  43797. * @return {Array}
  43798. * @api public
  43799. */
  43800. micromatch.braces = (pattern, options) => {
  43801. if (typeof pattern !== 'string') throw new TypeError('Expected a string');
  43802. if ((options && options.nobrace === true) || !/\{.*\}/.test(pattern)) {
  43803. return [pattern];
  43804. }
  43805. return braces(pattern, options);
  43806. };
  43807. /**
  43808. * Expand braces
  43809. */
  43810. micromatch.braceExpand = (pattern, options) => {
  43811. if (typeof pattern !== 'string') throw new TypeError('Expected a string');
  43812. return micromatch.braces(pattern, { ...options, expand: true });
  43813. };
  43814. /**
  43815. * Expose micromatch
  43816. */
  43817. var micromatch_1 = micromatch;
  43818. const sirvOptions = (headers) => {
  43819. return {
  43820. dev: true,
  43821. etag: true,
  43822. extensions: [],
  43823. setHeaders(res, pathname) {
  43824. // Matches js, jsx, ts, tsx.
  43825. // The reason this is done, is that the .ts file extension is reserved
  43826. // for the MIME type video/mp2t. In almost all cases, we can expect
  43827. // these files to be TypeScript files, and for Vite to serve them with
  43828. // this Content-Type.
  43829. if (/\.[tj]sx?$/.test(pathname)) {
  43830. res.setHeader('Content-Type', 'application/javascript');
  43831. }
  43832. if (headers) {
  43833. for (const name in headers) {
  43834. res.setHeader(name, headers[name]);
  43835. }
  43836. }
  43837. }
  43838. };
  43839. };
  43840. function servePublicMiddleware(dir, headers) {
  43841. const serve = sirv(dir, sirvOptions(headers));
  43842. // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
  43843. return function viteServePublicMiddleware(req, res, next) {
  43844. // skip import request and internal requests `/@fs/ /@vite-client` etc...
  43845. if (isImportRequest(req.url) || isInternalRequest(req.url)) {
  43846. return next();
  43847. }
  43848. serve(req, res, next);
  43849. };
  43850. }
  43851. function serveStaticMiddleware(dir, server) {
  43852. const serve = sirv(dir, sirvOptions(server.config.server.headers));
  43853. // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
  43854. return function viteServeStaticMiddleware(req, res, next) {
  43855. // only serve the file if it's not an html request or ends with `/`
  43856. // so that html requests can fallthrough to our html middleware for
  43857. // special processing
  43858. // also skip internal requests `/@fs/ /@vite-client` etc...
  43859. const cleanedUrl = cleanUrl(req.url);
  43860. if (cleanedUrl.endsWith('/') ||
  43861. path__default.extname(cleanedUrl) === '.html' ||
  43862. isInternalRequest(req.url)) {
  43863. return next();
  43864. }
  43865. const url = new URL(req.url, 'http://example.com');
  43866. const pathname = decodeURIComponent(url.pathname);
  43867. // apply aliases to static requests as well
  43868. let redirectedPathname;
  43869. for (const { find, replacement } of server.config.resolve.alias) {
  43870. const matches = typeof find === 'string'
  43871. ? pathname.startsWith(find)
  43872. : find.test(pathname);
  43873. if (matches) {
  43874. redirectedPathname = pathname.replace(find, replacement);
  43875. break;
  43876. }
  43877. }
  43878. if (redirectedPathname) {
  43879. // dir is pre-normalized to posix style
  43880. if (redirectedPathname.startsWith(dir)) {
  43881. redirectedPathname = redirectedPathname.slice(dir.length);
  43882. }
  43883. }
  43884. const resolvedPathname = redirectedPathname || pathname;
  43885. let fileUrl = path__default.resolve(dir, resolvedPathname.replace(/^\//, ''));
  43886. if (resolvedPathname.endsWith('/') && !fileUrl.endsWith('/')) {
  43887. fileUrl = fileUrl + '/';
  43888. }
  43889. if (!ensureServingAccess(fileUrl, server, res, next)) {
  43890. return;
  43891. }
  43892. if (redirectedPathname) {
  43893. url.pathname = encodeURIComponent(redirectedPathname);
  43894. req.url = url.href.slice(url.origin.length);
  43895. }
  43896. serve(req, res, next);
  43897. };
  43898. }
  43899. function serveRawFsMiddleware(server) {
  43900. const serveFromRoot = sirv('/', sirvOptions(server.config.server.headers));
  43901. // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
  43902. return function viteServeRawFsMiddleware(req, res, next) {
  43903. const url = new URL(req.url, 'http://example.com');
  43904. // In some cases (e.g. linked monorepos) files outside of root will
  43905. // reference assets that are also out of served root. In such cases
  43906. // the paths are rewritten to `/@fs/` prefixed paths and must be served by
  43907. // searching based from fs root.
  43908. if (url.pathname.startsWith(FS_PREFIX)) {
  43909. const pathname = decodeURIComponent(url.pathname);
  43910. // restrict files outside of `fs.allow`
  43911. if (!ensureServingAccess(slash(path__default.resolve(fsPathFromId(pathname))), server, res, next)) {
  43912. return;
  43913. }
  43914. let newPathname = pathname.slice(FS_PREFIX.length);
  43915. if (isWindows$3)
  43916. newPathname = newPathname.replace(/^[A-Z]:/i, '');
  43917. url.pathname = encodeURIComponent(newPathname);
  43918. req.url = url.href.slice(url.origin.length);
  43919. serveFromRoot(req, res, next);
  43920. }
  43921. else {
  43922. next();
  43923. }
  43924. };
  43925. }
  43926. const _matchOptions = { matchBase: true };
  43927. function isFileServingAllowed(url, server) {
  43928. if (!server.config.server.fs.strict)
  43929. return true;
  43930. const file = fsPathFromUrl(url);
  43931. if (server.config.server.fs.deny.some((i) => micromatch_1.isMatch(file, i, _matchOptions)))
  43932. return false;
  43933. if (server.moduleGraph.safeModulesPath.has(file))
  43934. return true;
  43935. if (server.config.server.fs.allow.some((dir) => isParentDirectory(dir, file)))
  43936. return true;
  43937. return false;
  43938. }
  43939. function ensureServingAccess(url, server, res, next) {
  43940. if (isFileServingAllowed(url, server)) {
  43941. return true;
  43942. }
  43943. if (isFileReadable(cleanUrl(url))) {
  43944. const urlMessage = `The request url "${url}" is outside of Vite serving allow list.`;
  43945. const hintMessage = `
  43946. ${server.config.server.fs.allow.map((i) => `- ${i}`).join('\n')}
  43947. Refer to docs https://vitejs.dev/config/#server-fs-allow for configurations and more details.`;
  43948. server.config.logger.error(urlMessage);
  43949. server.config.logger.warnOnce(hintMessage + '\n');
  43950. res.statusCode = 403;
  43951. res.write(renderRestrictedErrorHTML(urlMessage + '\n' + hintMessage));
  43952. res.end();
  43953. }
  43954. else {
  43955. // if the file doesn't exist, we shouldn't restrict this path as it can
  43956. // be an API call. Middlewares would issue a 404 if the file isn't handled
  43957. next();
  43958. }
  43959. return false;
  43960. }
  43961. function renderRestrictedErrorHTML(msg) {
  43962. // to have syntax highlighting and autocompletion in IDE
  43963. const html = String.raw;
  43964. return html `
  43965. <body>
  43966. <h1>403 Restricted</h1>
  43967. <p>${msg.replace(/\n/g, '<br/>')}</p>
  43968. <style>
  43969. body {
  43970. padding: 1em 2em;
  43971. }
  43972. </style>
  43973. </body>
  43974. `;
  43975. }
  43976. const debugLoad = createDebugger('vite:load');
  43977. const debugTransform = createDebugger('vite:transform');
  43978. const debugCache$1 = createDebugger('vite:cache');
  43979. const isDebug$3 = !!process.env.DEBUG;
  43980. function transformRequest(url, server, options = {}) {
  43981. const cacheKey = (options.ssr ? 'ssr:' : options.html ? 'html:' : '') + url;
  43982. // This module may get invalidated while we are processing it. For example
  43983. // when a full page reload is needed after the re-processing of pre-bundled
  43984. // dependencies when a missing dep is discovered. We save the current time
  43985. // to compare it to the last invalidation performed to know if we should
  43986. // cache the result of the transformation or we should discard it as stale.
  43987. //
  43988. // A module can be invalidated due to:
  43989. // 1. A full reload because of pre-bundling newly discovered deps
  43990. // 2. A full reload after a config change
  43991. // 3. The file that generated the module changed
  43992. // 4. Invalidation for a virtual module
  43993. //
  43994. // For 1 and 2, a new request for this module will be issued after
  43995. // the invalidation as part of the browser reloading the page. For 3 and 4
  43996. // there may not be a new request right away because of HMR handling.
  43997. // In all cases, the next time this module is requested, it should be
  43998. // re-processed.
  43999. //
  44000. // We save the timestamp when we start processing and compare it with the
  44001. // last time this module is invalidated
  44002. const timestamp = Date.now();
  44003. const pending = server._pendingRequests.get(cacheKey);
  44004. if (pending) {
  44005. return server.moduleGraph
  44006. .getModuleByUrl(removeTimestampQuery(url), options.ssr)
  44007. .then((module) => {
  44008. if (!module || pending.timestamp > module.lastInvalidationTimestamp) {
  44009. // The pending request is still valid, we can safely reuse its result
  44010. return pending.request;
  44011. }
  44012. else {
  44013. // Request 1 for module A (pending.timestamp)
  44014. // Invalidate module A (module.lastInvalidationTimestamp)
  44015. // Request 2 for module A (timestamp)
  44016. // First request has been invalidated, abort it to clear the cache,
  44017. // then perform a new doTransform.
  44018. pending.abort();
  44019. return transformRequest(url, server, options);
  44020. }
  44021. });
  44022. }
  44023. const request = doTransform(url, server, options, timestamp);
  44024. // Avoid clearing the cache of future requests if aborted
  44025. let cleared = false;
  44026. const clearCache = () => {
  44027. if (!cleared) {
  44028. server._pendingRequests.delete(cacheKey);
  44029. cleared = true;
  44030. }
  44031. };
  44032. // Cache the request and clear it once processing is done
  44033. server._pendingRequests.set(cacheKey, {
  44034. request,
  44035. timestamp,
  44036. abort: clearCache
  44037. });
  44038. request.then(clearCache, clearCache);
  44039. return request;
  44040. }
  44041. async function doTransform(url, server, options, timestamp) {
  44042. var _a, _b;
  44043. url = removeTimestampQuery(url);
  44044. const { config, pluginContainer, moduleGraph, watcher } = server;
  44045. const { root, logger } = config;
  44046. const prettyUrl = isDebug$3 ? prettifyUrl(url, root) : '';
  44047. const ssr = !!options.ssr;
  44048. const module = await server.moduleGraph.getModuleByUrl(url, ssr);
  44049. // check if we have a fresh cache
  44050. const cached = module && (ssr ? module.ssrTransformResult : module.transformResult);
  44051. if (cached) {
  44052. // TODO: check if the module is "partially invalidated" - i.e. an import
  44053. // down the chain has been fully invalidated, but this current module's
  44054. // content has not changed.
  44055. // in this case, we can reuse its previous cached result and only update
  44056. // its import timestamps.
  44057. isDebug$3 && debugCache$1(`[memory] ${prettyUrl}`);
  44058. return cached;
  44059. }
  44060. // resolve
  44061. const id = ((_a = (await pluginContainer.resolveId(url, undefined, { ssr }))) === null || _a === void 0 ? void 0 : _a.id) || url;
  44062. const file = cleanUrl(id);
  44063. let code = null;
  44064. let map = null;
  44065. // load
  44066. const loadStart = isDebug$3 ? perf_hooks.performance.now() : 0;
  44067. const loadResult = await pluginContainer.load(id, { ssr });
  44068. if (loadResult == null) {
  44069. // if this is an html request and there is no load result, skip ahead to
  44070. // SPA fallback.
  44071. if (options.html && !id.endsWith('.html')) {
  44072. return null;
  44073. }
  44074. // try fallback loading it from fs as string
  44075. // if the file is a binary, there should be a plugin that already loaded it
  44076. // as string
  44077. // only try the fallback if access is allowed, skip for out of root url
  44078. // like /service-worker.js or /api/users
  44079. if (options.ssr || isFileServingAllowed(file, server)) {
  44080. try {
  44081. code = await fs$n.promises.readFile(file, 'utf-8');
  44082. isDebug$3 && debugLoad(`${timeFrom(loadStart)} [fs] ${prettyUrl}`);
  44083. }
  44084. catch (e) {
  44085. if (e.code !== 'ENOENT') {
  44086. throw e;
  44087. }
  44088. }
  44089. }
  44090. if (code) {
  44091. try {
  44092. map = (_b = (convertSourceMap.fromSource(code) ||
  44093. convertSourceMap.fromMapFileSource(code, path__default.dirname(file)))) === null || _b === void 0 ? void 0 : _b.toObject();
  44094. }
  44095. catch (e) {
  44096. logger.warn(`Failed to load source map for ${url}.`, {
  44097. timestamp: true
  44098. });
  44099. }
  44100. }
  44101. }
  44102. else {
  44103. isDebug$3 && debugLoad(`${timeFrom(loadStart)} [plugin] ${prettyUrl}`);
  44104. if (isObject$1(loadResult)) {
  44105. code = loadResult.code;
  44106. map = loadResult.map;
  44107. }
  44108. else {
  44109. code = loadResult;
  44110. }
  44111. }
  44112. if (code == null) {
  44113. if (checkPublicFile(url, config)) {
  44114. throw new Error(`Failed to load url ${url} (resolved id: ${id}). ` +
  44115. `This file is in /public and will be copied as-is during build without ` +
  44116. `going through the plugin transforms, and therefore should not be ` +
  44117. `imported from source code. It can only be referenced via HTML tags.`);
  44118. }
  44119. else {
  44120. return null;
  44121. }
  44122. }
  44123. // ensure module in graph after successful load
  44124. const mod = await moduleGraph.ensureEntryFromUrl(url, ssr);
  44125. ensureWatchedFile(watcher, mod.file, root);
  44126. // transform
  44127. const transformStart = isDebug$3 ? perf_hooks.performance.now() : 0;
  44128. const transformResult = await pluginContainer.transform(code, id, {
  44129. inMap: map,
  44130. ssr
  44131. });
  44132. if (transformResult == null ||
  44133. (isObject$1(transformResult) && transformResult.code == null)) {
  44134. // no transform applied, keep code as-is
  44135. isDebug$3 &&
  44136. debugTransform(timeFrom(transformStart) + colors$1.dim(` [skipped] ${prettyUrl}`));
  44137. }
  44138. else {
  44139. isDebug$3 && debugTransform(`${timeFrom(transformStart)} ${prettyUrl}`);
  44140. code = transformResult.code;
  44141. map = transformResult.map;
  44142. }
  44143. if (map && mod.file) {
  44144. map = (typeof map === 'string' ? JSON.parse(map) : map);
  44145. if (map.mappings && !map.sourcesContent) {
  44146. await injectSourcesContent(map, mod.file, logger);
  44147. }
  44148. }
  44149. const result = ssr
  44150. ? await ssrTransform(code, map, url)
  44151. : {
  44152. code,
  44153. map,
  44154. etag: etag_1(code, { weak: true })
  44155. };
  44156. // Only cache the result if the module wasn't invalidated while it was
  44157. // being processed, so it is re-processed next time if it is stale
  44158. if (timestamp > mod.lastInvalidationTimestamp) {
  44159. if (ssr)
  44160. mod.ssrTransformResult = result;
  44161. else
  44162. mod.transformResult = result;
  44163. }
  44164. return result;
  44165. }
  44166. /**
  44167. * This plugin hooks into Node's module resolution algorithm at runtime,
  44168. * so that SSR builds can benefit from `resolve.dedupe` like they do
  44169. * in development.
  44170. */
  44171. function ssrRequireHookPlugin(config) {
  44172. var _a, _b;
  44173. if (config.command !== 'build' ||
  44174. !((_a = config.resolve.dedupe) === null || _a === void 0 ? void 0 : _a.length) ||
  44175. ((_b = config.ssr) === null || _b === void 0 ? void 0 : _b.noExternal) === true ||
  44176. isBuildOutputEsm(config)) {
  44177. return null;
  44178. }
  44179. return {
  44180. name: 'vite:ssr-require-hook',
  44181. transform(code, id) {
  44182. const moduleInfo = this.getModuleInfo(id);
  44183. if (moduleInfo === null || moduleInfo === void 0 ? void 0 : moduleInfo.isEntry) {
  44184. const s = new MagicString(code);
  44185. s.prepend(`;(${dedupeRequire.toString()})(${JSON.stringify(config.resolve.dedupe)});\n`);
  44186. return {
  44187. code: s.toString(),
  44188. map: s.generateMap({
  44189. source: id,
  44190. hires: true
  44191. })
  44192. };
  44193. }
  44194. }
  44195. };
  44196. }
  44197. /** Respect the `resolve.dedupe` option in production SSR. */
  44198. function dedupeRequire(dedupe) {
  44199. const Module = require('module');
  44200. const resolveFilename = Module._resolveFilename;
  44201. Module._resolveFilename = function (request, parent, isMain, options) {
  44202. if (request[0] !== '.' && request[0] !== '/') {
  44203. const parts = request.split('/');
  44204. const pkgName = parts[0][0] === '@' ? parts[0] + '/' + parts[1] : parts[0];
  44205. if (dedupe.includes(pkgName)) {
  44206. // Use this module as the parent.
  44207. parent = module;
  44208. }
  44209. }
  44210. return resolveFilename(request, parent, isMain, options);
  44211. };
  44212. }
  44213. function hookNodeResolve(getResolver) {
  44214. const Module = require('module');
  44215. const prevResolver = Module._resolveFilename;
  44216. Module._resolveFilename = getResolver(prevResolver);
  44217. return () => {
  44218. Module._resolveFilename = prevResolver;
  44219. };
  44220. }
  44221. function isBuildOutputEsm(config) {
  44222. var _a;
  44223. const outputs = arraify((_a = config.build.rollupOptions) === null || _a === void 0 ? void 0 : _a.output);
  44224. return outputs.some((output) => (output === null || output === void 0 ? void 0 : output.format) === 'es' || (output === null || output === void 0 ? void 0 : output.format) === 'esm');
  44225. }
  44226. let offset;
  44227. try {
  44228. new Function('throw new Error(1)')();
  44229. }
  44230. catch (e) {
  44231. // in Node 12, stack traces account for the function wrapper.
  44232. // in Node 13 and later, the function wrapper adds two lines,
  44233. // which must be subtracted to generate a valid mapping
  44234. const match = /:(\d+):\d+\)$/.exec(e.stack.split('\n')[1]);
  44235. offset = match ? +match[1] - 1 : 0;
  44236. }
  44237. function ssrRewriteStacktrace(stack, moduleGraph) {
  44238. return stack
  44239. .split('\n')
  44240. .map((line) => {
  44241. return line.replace(/^ {4}at (?:(.+?)\s+\()?(?:(.+?):(\d+)(?::(\d+))?)\)?/, (input, varName, url, line, column) => {
  44242. var _a;
  44243. if (!url)
  44244. return input;
  44245. const mod = moduleGraph.urlToModuleMap.get(url);
  44246. const rawSourceMap = (_a = mod === null || mod === void 0 ? void 0 : mod.ssrTransformResult) === null || _a === void 0 ? void 0 : _a.map;
  44247. if (!rawSourceMap) {
  44248. return input;
  44249. }
  44250. const traced = new TraceMap(rawSourceMap);
  44251. const pos = originalPositionFor$1(traced, {
  44252. line: Number(line) - offset,
  44253. column: Number(column)
  44254. });
  44255. if (!pos.source || pos.line == null || pos.column == null) {
  44256. return input;
  44257. }
  44258. const source = `${pos.source}:${pos.line}:${pos.column}`;
  44259. if (!varName || varName === 'eval') {
  44260. return ` at ${source}`;
  44261. }
  44262. else {
  44263. return ` at ${varName} (${source})`;
  44264. }
  44265. });
  44266. })
  44267. .join('\n');
  44268. }
  44269. function rebindErrorStacktrace(e, stacktrace) {
  44270. const { configurable, writable } = Object.getOwnPropertyDescriptor(e, 'stack');
  44271. if (configurable) {
  44272. Object.defineProperty(e, 'stack', {
  44273. value: stacktrace,
  44274. enumerable: true,
  44275. configurable: true,
  44276. writable: true
  44277. });
  44278. }
  44279. else if (writable) {
  44280. e.stack = stacktrace;
  44281. }
  44282. }
  44283. const pendingModules = new Map();
  44284. const pendingImports = new Map();
  44285. async function ssrLoadModule(url, server, context = { global }, urlStack = [], fixStacktrace) {
  44286. url = unwrapId(url).replace(NULL_BYTE_PLACEHOLDER, '\0');
  44287. // when we instantiate multiple dependency modules in parallel, they may
  44288. // point to shared modules. We need to avoid duplicate instantiation attempts
  44289. // by register every module as pending synchronously so that all subsequent
  44290. // request to that module are simply waiting on the same promise.
  44291. const pending = pendingModules.get(url);
  44292. if (pending) {
  44293. return pending;
  44294. }
  44295. const modulePromise = instantiateModule(url, server, context, urlStack, fixStacktrace);
  44296. pendingModules.set(url, modulePromise);
  44297. modulePromise
  44298. .catch(() => {
  44299. pendingImports.delete(url);
  44300. })
  44301. .finally(() => {
  44302. pendingModules.delete(url);
  44303. });
  44304. return modulePromise;
  44305. }
  44306. async function instantiateModule(url, server, context = { global }, urlStack = [], fixStacktrace) {
  44307. const { moduleGraph } = server;
  44308. const mod = await moduleGraph.ensureEntryFromUrl(url, true);
  44309. if (mod.ssrError) {
  44310. throw mod.ssrError;
  44311. }
  44312. if (mod.ssrModule) {
  44313. return mod.ssrModule;
  44314. }
  44315. const result = mod.ssrTransformResult ||
  44316. (await transformRequest(url, server, { ssr: true }));
  44317. if (!result) {
  44318. // TODO more info? is this even necessary?
  44319. throw new Error(`failed to load module for ssr: ${url}`);
  44320. }
  44321. const ssrModule = {
  44322. [Symbol.toStringTag]: 'Module'
  44323. };
  44324. Object.defineProperty(ssrModule, '__esModule', { value: true });
  44325. // Tolerate circular imports by ensuring the module can be
  44326. // referenced before it's been instantiated.
  44327. mod.ssrModule = ssrModule;
  44328. const ssrImportMeta = {
  44329. // The filesystem URL, matching native Node.js modules
  44330. url: require$$0$6.pathToFileURL(mod.file).toString()
  44331. };
  44332. urlStack = urlStack.concat(url);
  44333. const isCircular = (url) => urlStack.includes(url);
  44334. const { isProduction, resolve: { dedupe, preserveSymlinks }, root } = server.config;
  44335. // The `extensions` and `mainFields` options are used to ensure that
  44336. // CommonJS modules are preferred. We want to avoid ESM->ESM imports
  44337. // whenever possible, because `hookNodeResolve` can't intercept them.
  44338. const resolveOptions = {
  44339. dedupe,
  44340. extensions: ['.js', '.cjs', '.json'],
  44341. isBuild: true,
  44342. isProduction,
  44343. isRequire: true,
  44344. mainFields: ['main'],
  44345. preserveSymlinks,
  44346. root
  44347. };
  44348. // Since dynamic imports can happen in parallel, we need to
  44349. // account for multiple pending deps and duplicate imports.
  44350. const pendingDeps = [];
  44351. const ssrImport = async (dep) => {
  44352. var _a, _b;
  44353. if (dep[0] !== '.' && dep[0] !== '/') {
  44354. return nodeImport(dep, mod.file, resolveOptions);
  44355. }
  44356. dep = unwrapId(dep);
  44357. if (!isCircular(dep) && !((_a = pendingImports.get(dep)) === null || _a === void 0 ? void 0 : _a.some(isCircular))) {
  44358. pendingDeps.push(dep);
  44359. if (pendingDeps.length === 1) {
  44360. pendingImports.set(url, pendingDeps);
  44361. }
  44362. const mod = await ssrLoadModule(dep, server, context, urlStack, fixStacktrace);
  44363. if (pendingDeps.length === 1) {
  44364. pendingImports.delete(url);
  44365. }
  44366. else {
  44367. pendingDeps.splice(pendingDeps.indexOf(dep), 1);
  44368. }
  44369. // return local module to avoid race condition #5470
  44370. return mod;
  44371. }
  44372. return (_b = moduleGraph.urlToModuleMap.get(dep)) === null || _b === void 0 ? void 0 : _b.ssrModule;
  44373. };
  44374. const ssrDynamicImport = (dep) => {
  44375. // #3087 dynamic import vars is ignored at rewrite import path,
  44376. // so here need process relative path
  44377. if (dep[0] === '.') {
  44378. dep = path__default.posix.resolve(path__default.dirname(url), dep);
  44379. }
  44380. return ssrImport(dep);
  44381. };
  44382. function ssrExportAll(sourceModule) {
  44383. for (const key in sourceModule) {
  44384. if (key !== 'default') {
  44385. Object.defineProperty(ssrModule, key, {
  44386. enumerable: true,
  44387. configurable: true,
  44388. get() {
  44389. return sourceModule[key];
  44390. }
  44391. });
  44392. }
  44393. }
  44394. }
  44395. try {
  44396. // eslint-disable-next-line @typescript-eslint/no-empty-function
  44397. const AsyncFunction = async function () { }.constructor;
  44398. const initModule = new AsyncFunction(`global`, ssrModuleExportsKey, ssrImportMetaKey, ssrImportKey, ssrDynamicImportKey, ssrExportAllKey, result.code + `\n//# sourceURL=${mod.url}`);
  44399. await initModule(context.global, ssrModule, ssrImportMeta, ssrImport, ssrDynamicImport, ssrExportAll);
  44400. }
  44401. catch (e) {
  44402. mod.ssrError = e;
  44403. if (e.stack && fixStacktrace !== false) {
  44404. const stacktrace = ssrRewriteStacktrace(e.stack, moduleGraph);
  44405. rebindErrorStacktrace(e, stacktrace);
  44406. server.config.logger.error(`Error when evaluating SSR module ${url}:\n${stacktrace}`, {
  44407. timestamp: true,
  44408. clear: server.config.clearScreen,
  44409. error: e
  44410. });
  44411. }
  44412. throw e;
  44413. }
  44414. return Object.freeze(ssrModule);
  44415. }
  44416. // In node@12+ we can use dynamic import to load CJS and ESM
  44417. async function nodeImport(id, importer, resolveOptions) {
  44418. // Node's module resolution is hi-jacked so Vite can ensure the
  44419. // configured `resolve.dedupe` and `mode` options are respected.
  44420. const viteResolve = (id, importer, options = resolveOptions) => {
  44421. const resolved = tryNodeResolve(id, importer, options, false);
  44422. if (!resolved) {
  44423. const err = new Error(`Cannot find module '${id}' imported from '${importer}'`);
  44424. err.code = 'ERR_MODULE_NOT_FOUND';
  44425. throw err;
  44426. }
  44427. return resolved.id;
  44428. };
  44429. // When an ESM module imports an ESM dependency, this hook is *not* used.
  44430. const unhookNodeResolve = hookNodeResolve((nodeResolve) => (id, parent, isMain, options) => {
  44431. // Use the Vite resolver only for bare imports while skipping
  44432. // any absolute paths, built-in modules and binary modules.
  44433. if (!bareImportRE.test(id) ||
  44434. path__default.isAbsolute(id) ||
  44435. isBuiltin(id) ||
  44436. id.endsWith('.node')) {
  44437. return nodeResolve(id, parent, isMain, options);
  44438. }
  44439. if (parent) {
  44440. let resolved = viteResolve(id, parent.id);
  44441. if (resolved) {
  44442. // hookNodeResolve must use platform-specific path.normalize
  44443. // to be compatible with dynamicImport (#6080)
  44444. resolved = path__default.normalize(resolved);
  44445. }
  44446. return resolved;
  44447. }
  44448. // Importing a CJS module from an ESM module. In this case, the import
  44449. // specifier is already an absolute path, so this is a no-op.
  44450. // Options like `resolve.dedupe` and `mode` are not respected.
  44451. return id;
  44452. });
  44453. let url;
  44454. if (id.startsWith('node:') || isBuiltin(id)) {
  44455. url = id;
  44456. }
  44457. else {
  44458. url = viteResolve(id, importer,
  44459. // Non-external modules can import ESM-only modules, but only outside
  44460. // of test runs, because we use Node `require` in Jest to avoid segfault.
  44461. typeof jest === 'undefined'
  44462. ? { ...resolveOptions, tryEsmOnly: true }
  44463. : resolveOptions);
  44464. if (usingDynamicImport) {
  44465. url = require$$0$6.pathToFileURL(url).toString();
  44466. }
  44467. }
  44468. try {
  44469. const mod = await dynamicImport(url);
  44470. return proxyESM(mod);
  44471. }
  44472. finally {
  44473. unhookNodeResolve();
  44474. }
  44475. }
  44476. // rollup-style default import interop for cjs
  44477. function proxyESM(mod) {
  44478. // This is the only sensible option when the exports object is a primitve
  44479. if (isPrimitive(mod))
  44480. return { default: mod };
  44481. let defaultExport = 'default' in mod ? mod.default : mod;
  44482. if (!isPrimitive(defaultExport) && '__esModule' in defaultExport) {
  44483. mod = defaultExport;
  44484. if ('default' in defaultExport) {
  44485. defaultExport = defaultExport.default;
  44486. }
  44487. }
  44488. return new Proxy(mod, {
  44489. get(mod, prop) {
  44490. var _a;
  44491. if (prop === 'default')
  44492. return defaultExport;
  44493. return (_a = mod[prop]) !== null && _a !== void 0 ? _a : defaultExport === null || defaultExport === void 0 ? void 0 : defaultExport[prop];
  44494. }
  44495. });
  44496. }
  44497. function isPrimitive(value) {
  44498. return !value || (typeof value !== 'object' && typeof value !== 'function');
  44499. }
  44500. const isDebugEnabled = _debug('vite:deps').enabled;
  44501. /**
  44502. * The amount to wait for requests to register newly found dependencies before triggering
  44503. * a re-bundle + page reload
  44504. */
  44505. const debounceMs = 100;
  44506. function createOptimizedDeps(server) {
  44507. const { config } = server;
  44508. const { logger } = config;
  44509. const sessionTimestamp = Date.now().toString();
  44510. const cachedMetadata = loadCachedDepOptimizationMetadata(config);
  44511. const optimizedDeps = {
  44512. metadata: cachedMetadata || createOptimizedDepsMetadata(config, sessionTimestamp),
  44513. registerMissingImport
  44514. };
  44515. let handle;
  44516. let newDepsDiscovered = false;
  44517. let newDepsToLog = [];
  44518. let newDepsToLogHandle;
  44519. const logNewlyDiscoveredDeps = () => {
  44520. if (newDepsToLog.length) {
  44521. config.logger.info(colors$1.green(`✨ new dependencies optimized: ${depsLogString(newDepsToLog)}`), {
  44522. timestamp: true
  44523. });
  44524. newDepsToLog = [];
  44525. }
  44526. };
  44527. let depOptimizationProcessing = newDepOptimizationProcessing();
  44528. let depOptimizationProcessingQueue = [];
  44529. const resolveEnqueuedProcessingPromises = () => {
  44530. // Resolve all the processings (including the ones which were delayed)
  44531. for (const processing of depOptimizationProcessingQueue) {
  44532. processing.resolve();
  44533. }
  44534. depOptimizationProcessingQueue = [];
  44535. };
  44536. let enqueuedRerun;
  44537. let currentlyProcessing = false;
  44538. // If there wasn't a cache or it is outdated, perform a fast scan with esbuild
  44539. // to quickly find project dependencies and do a first optimize run
  44540. if (!cachedMetadata) {
  44541. currentlyProcessing = true;
  44542. const scanPhaseProcessing = newDepOptimizationProcessing();
  44543. optimizedDeps.scanProcessing = scanPhaseProcessing.promise;
  44544. const warmUp = async () => {
  44545. try {
  44546. debuggerViteDeps(colors$1.green(`scanning for dependencies...`), {
  44547. timestamp: true
  44548. });
  44549. const { metadata } = optimizedDeps;
  44550. const discovered = await discoverProjectDependencies(config, sessionTimestamp);
  44551. // Respect the scan phase discover order to improve reproducibility
  44552. for (const depInfo of Object.values(discovered)) {
  44553. addOptimizedDepInfo(metadata, 'discovered', {
  44554. ...depInfo,
  44555. processing: depOptimizationProcessing.promise
  44556. });
  44557. }
  44558. debuggerViteDeps(colors$1.green(`dependencies found: ${depsLogString(Object.keys(discovered))}`), {
  44559. timestamp: true
  44560. });
  44561. scanPhaseProcessing.resolve();
  44562. optimizedDeps.scanProcessing = undefined;
  44563. runOptimizer();
  44564. }
  44565. catch (e) {
  44566. logger.error(e.message);
  44567. if (optimizedDeps.scanProcessing) {
  44568. scanPhaseProcessing.resolve();
  44569. optimizedDeps.scanProcessing = undefined;
  44570. }
  44571. }
  44572. };
  44573. setTimeout(warmUp, 0);
  44574. }
  44575. async function runOptimizer(isRerun = false) {
  44576. // Ensure that rerun is called sequentially
  44577. enqueuedRerun = undefined;
  44578. currentlyProcessing = true;
  44579. // Ensure that a rerun will not be issued for current discovered deps
  44580. if (handle)
  44581. clearTimeout(handle);
  44582. // a succesful completion of the optimizeDeps rerun will end up
  44583. // creating new bundled version of all current and discovered deps
  44584. // in the cache dir and a new metadata info object assigned
  44585. // to optimizeDeps.metadata. A fullReload is only issued if
  44586. // the previous bundled dependencies have changed.
  44587. // if the rerun fails, optimizeDeps.metadata remains untouched,
  44588. // current discovered deps are cleaned, and a fullReload is issued
  44589. let { metadata } = optimizedDeps;
  44590. // All deps, previous known and newly discovered are rebundled,
  44591. // respect insertion order to keep the metadata file stable
  44592. const newDeps = {};
  44593. // Clone optimized info objects, fileHash, browserHash may be changed for them
  44594. for (const dep of Object.keys(metadata.optimized)) {
  44595. newDeps[dep] = { ...metadata.optimized[dep] };
  44596. }
  44597. for (const dep of Object.keys(metadata.discovered)) {
  44598. // Clone the discovered info discarding its processing promise
  44599. const { processing, ...info } = metadata.discovered[dep];
  44600. newDeps[dep] = info;
  44601. }
  44602. newDepsDiscovered = false;
  44603. // Add the current depOptimizationProcessing to the queue, these
  44604. // promises are going to be resolved once a rerun is committed
  44605. depOptimizationProcessingQueue.push(depOptimizationProcessing);
  44606. // Create a new promise for the next rerun, discovered missing
  44607. // dependencies will be asigned this promise from this point
  44608. depOptimizationProcessing = newDepOptimizationProcessing();
  44609. try {
  44610. const processingResult = await runOptimizeDeps(config, newDeps);
  44611. const newData = processingResult.metadata;
  44612. // After a re-optimization, if the internal bundled chunks change a full page reload
  44613. // is required. If the files are stable, we can avoid the reload that is expensive
  44614. // for large applications. Comparing their fileHash we can find out if it is safe to
  44615. // keep the current browser state.
  44616. const needsReload = metadata.hash !== newData.hash ||
  44617. Object.keys(metadata.optimized).some((dep) => {
  44618. return (metadata.optimized[dep].fileHash !== newData.optimized[dep].fileHash);
  44619. });
  44620. const commitProcessing = async () => {
  44621. await processingResult.commit();
  44622. // While optimizeDeps is running, new missing deps may be discovered,
  44623. // in which case they will keep being added to metadata.discovered
  44624. for (const id in metadata.discovered) {
  44625. if (!newData.optimized[id]) {
  44626. addOptimizedDepInfo(newData, 'discovered', metadata.discovered[id]);
  44627. }
  44628. }
  44629. // If we don't reload the page, we need to keep browserHash stable
  44630. if (!needsReload) {
  44631. newData.browserHash = metadata.browserHash;
  44632. for (const dep in newData.chunks) {
  44633. newData.chunks[dep].browserHash = metadata.browserHash;
  44634. }
  44635. for (const dep in newData.optimized) {
  44636. newData.optimized[dep].browserHash = (metadata.optimized[dep] || metadata.discovered[dep]).browserHash;
  44637. }
  44638. }
  44639. // Commit hash and needsInterop changes to the discovered deps info
  44640. // object. Allow for code to await for the discovered processing promise
  44641. // and use the information in the same object
  44642. for (const o in newData.optimized) {
  44643. const discovered = metadata.discovered[o];
  44644. if (discovered) {
  44645. const optimized = newData.optimized[o];
  44646. discovered.browserHash = optimized.browserHash;
  44647. discovered.fileHash = optimized.fileHash;
  44648. discovered.needsInterop = optimized.needsInterop;
  44649. discovered.processing = undefined;
  44650. }
  44651. }
  44652. if (isRerun) {
  44653. newDepsToLog.push(...Object.keys(newData.optimized).filter((dep) => !metadata.optimized[dep]));
  44654. }
  44655. metadata = optimizedDeps.metadata = newData;
  44656. resolveEnqueuedProcessingPromises();
  44657. };
  44658. if (!needsReload) {
  44659. await commitProcessing();
  44660. if (!isDebugEnabled) {
  44661. if (newDepsToLogHandle)
  44662. clearTimeout(newDepsToLogHandle);
  44663. newDepsToLogHandle = setTimeout(() => {
  44664. newDepsToLogHandle = undefined;
  44665. logNewlyDiscoveredDeps();
  44666. }, 2 * debounceMs);
  44667. }
  44668. else {
  44669. debuggerViteDeps(colors$1.green(`✨ optimized dependencies unchanged`), {
  44670. timestamp: true
  44671. });
  44672. }
  44673. }
  44674. else {
  44675. if (newDepsDiscovered) {
  44676. // There are newly discovered deps, and another rerun is about to be
  44677. // excecuted. Avoid the current full reload discarding this rerun result
  44678. // We don't resolve the processing promise, as they will be resolved
  44679. // once a rerun is committed
  44680. processingResult.cancel();
  44681. debuggerViteDeps(colors$1.green(`✨ delaying reload as new dependencies have been found...`), {
  44682. timestamp: true
  44683. });
  44684. }
  44685. else {
  44686. await commitProcessing();
  44687. if (!isDebugEnabled) {
  44688. if (newDepsToLogHandle)
  44689. clearTimeout(newDepsToLogHandle);
  44690. newDepsToLogHandle = undefined;
  44691. logNewlyDiscoveredDeps();
  44692. }
  44693. logger.info(colors$1.green(`✨ optimized dependencies changed. reloading`), {
  44694. timestamp: true
  44695. });
  44696. fullReload();
  44697. }
  44698. }
  44699. }
  44700. catch (e) {
  44701. logger.error(colors$1.red(`error while updating dependencies:\n${e.stack}`), { timestamp: true, error: e });
  44702. resolveEnqueuedProcessingPromises();
  44703. // Reset missing deps, let the server rediscover the dependencies
  44704. metadata.discovered = {};
  44705. fullReload();
  44706. }
  44707. currentlyProcessing = false;
  44708. // @ts-ignore
  44709. enqueuedRerun === null || enqueuedRerun === void 0 ? void 0 : enqueuedRerun();
  44710. }
  44711. function fullReload() {
  44712. // Cached transform results have stale imports (resolved to
  44713. // old locations) so they need to be invalidated before the page is
  44714. // reloaded.
  44715. server.moduleGraph.invalidateAll();
  44716. server.ws.send({
  44717. type: 'full-reload',
  44718. path: '*'
  44719. });
  44720. }
  44721. async function rerun() {
  44722. // debounce time to wait for new missing deps finished, issue a new
  44723. // optimization of deps (both old and newly found) once the previous
  44724. // optimizeDeps processing is finished
  44725. const deps = Object.keys(optimizedDeps.metadata.discovered);
  44726. const depsString = depsLogString(deps);
  44727. debuggerViteDeps(colors$1.green(`new dependencies found: ${depsString}`), {
  44728. timestamp: true
  44729. });
  44730. runOptimizer(true);
  44731. }
  44732. function getDiscoveredBrowserHash(hash, deps, missing) {
  44733. return getHash(hash + JSON.stringify(deps) + JSON.stringify(missing) + sessionTimestamp);
  44734. }
  44735. function registerMissingImport(id, resolved, ssr) {
  44736. if (optimizedDeps.scanProcessing) {
  44737. config.logger.error('Vite internal error: registering missing import before initial scanning is over');
  44738. }
  44739. const { metadata } = optimizedDeps;
  44740. const optimized = metadata.optimized[id];
  44741. if (optimized) {
  44742. return optimized;
  44743. }
  44744. const chunk = metadata.chunks[id];
  44745. if (chunk) {
  44746. return chunk;
  44747. }
  44748. let missing = metadata.discovered[id];
  44749. if (missing) {
  44750. // We are already discover this dependency
  44751. // It will be processed in the next rerun call
  44752. return missing;
  44753. }
  44754. newDepsDiscovered = true;
  44755. missing = addOptimizedDepInfo(metadata, 'discovered', {
  44756. id,
  44757. file: getOptimizedDepPath(id, server.config),
  44758. src: resolved,
  44759. // Assing a browserHash to this missing dependency that is unique to
  44760. // the current state of known + missing deps. If its optimizeDeps run
  44761. // doesn't alter the bundled files of previous known dependendencies,
  44762. // we don't need a full reload and this browserHash will be kept
  44763. browserHash: getDiscoveredBrowserHash(metadata.hash, depsFromOptimizedDepInfo(metadata.optimized), depsFromOptimizedDepInfo(metadata.discovered)),
  44764. // loading of this pre-bundled dep needs to await for its processing
  44765. // promise to be resolved
  44766. processing: depOptimizationProcessing.promise
  44767. });
  44768. // Debounced rerun, let other missing dependencies be discovered before
  44769. // the running next optimizeDeps
  44770. enqueuedRerun = undefined;
  44771. if (handle)
  44772. clearTimeout(handle);
  44773. if (newDepsToLogHandle)
  44774. clearTimeout(newDepsToLogHandle);
  44775. newDepsToLogHandle = undefined;
  44776. handle = setTimeout(() => {
  44777. handle = undefined;
  44778. enqueuedRerun = rerun;
  44779. if (!currentlyProcessing) {
  44780. enqueuedRerun();
  44781. }
  44782. }, debounceMs);
  44783. // Return the path for the optimized bundle, this path is known before
  44784. // esbuild is run to generate the pre-bundle
  44785. return missing;
  44786. }
  44787. return optimizedDeps;
  44788. }
  44789. var bufferUtil$1 = {exports: {}};
  44790. var constants = {
  44791. BINARY_TYPES: ['nodebuffer', 'arraybuffer', 'fragments'],
  44792. EMPTY_BUFFER: Buffer.alloc(0),
  44793. GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11',
  44794. kForOnEventAttribute: Symbol('kIsForOnEventAttribute'),
  44795. kListener: Symbol('kListener'),
  44796. kStatusCode: Symbol('status-code'),
  44797. kWebSocket: Symbol('websocket'),
  44798. NOOP: () => {}
  44799. };
  44800. const { EMPTY_BUFFER: EMPTY_BUFFER$3 } = constants;
  44801. /**
  44802. * Merges an array of buffers into a new buffer.
  44803. *
  44804. * @param {Buffer[]} list The array of buffers to concat
  44805. * @param {Number} totalLength The total length of buffers in the list
  44806. * @return {Buffer} The resulting buffer
  44807. * @public
  44808. */
  44809. function concat$1(list, totalLength) {
  44810. if (list.length === 0) return EMPTY_BUFFER$3;
  44811. if (list.length === 1) return list[0];
  44812. const target = Buffer.allocUnsafe(totalLength);
  44813. let offset = 0;
  44814. for (let i = 0; i < list.length; i++) {
  44815. const buf = list[i];
  44816. target.set(buf, offset);
  44817. offset += buf.length;
  44818. }
  44819. if (offset < totalLength) return target.slice(0, offset);
  44820. return target;
  44821. }
  44822. /**
  44823. * Masks a buffer using the given mask.
  44824. *
  44825. * @param {Buffer} source The buffer to mask
  44826. * @param {Buffer} mask The mask to use
  44827. * @param {Buffer} output The buffer where to store the result
  44828. * @param {Number} offset The offset at which to start writing
  44829. * @param {Number} length The number of bytes to mask.
  44830. * @public
  44831. */
  44832. function _mask(source, mask, output, offset, length) {
  44833. for (let i = 0; i < length; i++) {
  44834. output[offset + i] = source[i] ^ mask[i & 3];
  44835. }
  44836. }
  44837. /**
  44838. * Unmasks a buffer using the given mask.
  44839. *
  44840. * @param {Buffer} buffer The buffer to unmask
  44841. * @param {Buffer} mask The mask to use
  44842. * @public
  44843. */
  44844. function _unmask(buffer, mask) {
  44845. for (let i = 0; i < buffer.length; i++) {
  44846. buffer[i] ^= mask[i & 3];
  44847. }
  44848. }
  44849. /**
  44850. * Converts a buffer to an `ArrayBuffer`.
  44851. *
  44852. * @param {Buffer} buf The buffer to convert
  44853. * @return {ArrayBuffer} Converted buffer
  44854. * @public
  44855. */
  44856. function toArrayBuffer$1(buf) {
  44857. if (buf.byteLength === buf.buffer.byteLength) {
  44858. return buf.buffer;
  44859. }
  44860. return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
  44861. }
  44862. /**
  44863. * Converts `data` to a `Buffer`.
  44864. *
  44865. * @param {*} data The data to convert
  44866. * @return {Buffer} The buffer
  44867. * @throws {TypeError}
  44868. * @public
  44869. */
  44870. function toBuffer$2(data) {
  44871. toBuffer$2.readOnly = true;
  44872. if (Buffer.isBuffer(data)) return data;
  44873. let buf;
  44874. if (data instanceof ArrayBuffer) {
  44875. buf = Buffer.from(data);
  44876. } else if (ArrayBuffer.isView(data)) {
  44877. buf = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
  44878. } else {
  44879. buf = Buffer.from(data);
  44880. toBuffer$2.readOnly = false;
  44881. }
  44882. return buf;
  44883. }
  44884. try {
  44885. const bufferUtil = require('bufferutil');
  44886. bufferUtil$1.exports = {
  44887. concat: concat$1,
  44888. mask(source, mask, output, offset, length) {
  44889. if (length < 48) _mask(source, mask, output, offset, length);
  44890. else bufferUtil.mask(source, mask, output, offset, length);
  44891. },
  44892. toArrayBuffer: toArrayBuffer$1,
  44893. toBuffer: toBuffer$2,
  44894. unmask(buffer, mask) {
  44895. if (buffer.length < 32) _unmask(buffer, mask);
  44896. else bufferUtil.unmask(buffer, mask);
  44897. }
  44898. };
  44899. } catch (e) /* istanbul ignore next */ {
  44900. bufferUtil$1.exports = {
  44901. concat: concat$1,
  44902. mask: _mask,
  44903. toArrayBuffer: toArrayBuffer$1,
  44904. toBuffer: toBuffer$2,
  44905. unmask: _unmask
  44906. };
  44907. }
  44908. const kDone = Symbol('kDone');
  44909. const kRun = Symbol('kRun');
  44910. /**
  44911. * A very simple job queue with adjustable concurrency. Adapted from
  44912. * https://github.com/STRML/async-limiter
  44913. */
  44914. class Limiter$1 {
  44915. /**
  44916. * Creates a new `Limiter`.
  44917. *
  44918. * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
  44919. * to run concurrently
  44920. */
  44921. constructor(concurrency) {
  44922. this[kDone] = () => {
  44923. this.pending--;
  44924. this[kRun]();
  44925. };
  44926. this.concurrency = concurrency || Infinity;
  44927. this.jobs = [];
  44928. this.pending = 0;
  44929. }
  44930. /**
  44931. * Adds a job to the queue.
  44932. *
  44933. * @param {Function} job The job to run
  44934. * @public
  44935. */
  44936. add(job) {
  44937. this.jobs.push(job);
  44938. this[kRun]();
  44939. }
  44940. /**
  44941. * Removes a job from the queue and runs it if possible.
  44942. *
  44943. * @private
  44944. */
  44945. [kRun]() {
  44946. if (this.pending === this.concurrency) return;
  44947. if (this.jobs.length) {
  44948. const job = this.jobs.shift();
  44949. this.pending++;
  44950. job(this[kDone]);
  44951. }
  44952. }
  44953. }
  44954. var limiter = Limiter$1;
  44955. const zlib = zlib__default;
  44956. const bufferUtil = bufferUtil$1.exports;
  44957. const Limiter = limiter;
  44958. const { kStatusCode: kStatusCode$2 } = constants;
  44959. const TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]);
  44960. const kPerMessageDeflate = Symbol('permessage-deflate');
  44961. const kTotalLength = Symbol('total-length');
  44962. const kCallback = Symbol('callback');
  44963. const kBuffers = Symbol('buffers');
  44964. const kError$1 = Symbol('error');
  44965. //
  44966. // We limit zlib concurrency, which prevents severe memory fragmentation
  44967. // as documented in https://github.com/nodejs/node/issues/8871#issuecomment-250915913
  44968. // and https://github.com/websockets/ws/issues/1202
  44969. //
  44970. // Intentionally global; it's the global thread pool that's an issue.
  44971. //
  44972. let zlibLimiter;
  44973. /**
  44974. * permessage-deflate implementation.
  44975. */
  44976. class PerMessageDeflate$4 {
  44977. /**
  44978. * Creates a PerMessageDeflate instance.
  44979. *
  44980. * @param {Object} [options] Configuration options
  44981. * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
  44982. * for, or request, a custom client window size
  44983. * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
  44984. * acknowledge disabling of client context takeover
  44985. * @param {Number} [options.concurrencyLimit=10] The number of concurrent
  44986. * calls to zlib
  44987. * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
  44988. * use of a custom server window size
  44989. * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
  44990. * disabling of server context takeover
  44991. * @param {Number} [options.threshold=1024] Size (in bytes) below which
  44992. * messages should not be compressed if context takeover is disabled
  44993. * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
  44994. * deflate
  44995. * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
  44996. * inflate
  44997. * @param {Boolean} [isServer=false] Create the instance in either server or
  44998. * client mode
  44999. * @param {Number} [maxPayload=0] The maximum allowed message length
  45000. */
  45001. constructor(options, isServer, maxPayload) {
  45002. this._maxPayload = maxPayload | 0;
  45003. this._options = options || {};
  45004. this._threshold =
  45005. this._options.threshold !== undefined ? this._options.threshold : 1024;
  45006. this._isServer = !!isServer;
  45007. this._deflate = null;
  45008. this._inflate = null;
  45009. this.params = null;
  45010. if (!zlibLimiter) {
  45011. const concurrency =
  45012. this._options.concurrencyLimit !== undefined
  45013. ? this._options.concurrencyLimit
  45014. : 10;
  45015. zlibLimiter = new Limiter(concurrency);
  45016. }
  45017. }
  45018. /**
  45019. * @type {String}
  45020. */
  45021. static get extensionName() {
  45022. return 'permessage-deflate';
  45023. }
  45024. /**
  45025. * Create an extension negotiation offer.
  45026. *
  45027. * @return {Object} Extension parameters
  45028. * @public
  45029. */
  45030. offer() {
  45031. const params = {};
  45032. if (this._options.serverNoContextTakeover) {
  45033. params.server_no_context_takeover = true;
  45034. }
  45035. if (this._options.clientNoContextTakeover) {
  45036. params.client_no_context_takeover = true;
  45037. }
  45038. if (this._options.serverMaxWindowBits) {
  45039. params.server_max_window_bits = this._options.serverMaxWindowBits;
  45040. }
  45041. if (this._options.clientMaxWindowBits) {
  45042. params.client_max_window_bits = this._options.clientMaxWindowBits;
  45043. } else if (this._options.clientMaxWindowBits == null) {
  45044. params.client_max_window_bits = true;
  45045. }
  45046. return params;
  45047. }
  45048. /**
  45049. * Accept an extension negotiation offer/response.
  45050. *
  45051. * @param {Array} configurations The extension negotiation offers/reponse
  45052. * @return {Object} Accepted configuration
  45053. * @public
  45054. */
  45055. accept(configurations) {
  45056. configurations = this.normalizeParams(configurations);
  45057. this.params = this._isServer
  45058. ? this.acceptAsServer(configurations)
  45059. : this.acceptAsClient(configurations);
  45060. return this.params;
  45061. }
  45062. /**
  45063. * Releases all resources used by the extension.
  45064. *
  45065. * @public
  45066. */
  45067. cleanup() {
  45068. if (this._inflate) {
  45069. this._inflate.close();
  45070. this._inflate = null;
  45071. }
  45072. if (this._deflate) {
  45073. const callback = this._deflate[kCallback];
  45074. this._deflate.close();
  45075. this._deflate = null;
  45076. if (callback) {
  45077. callback(
  45078. new Error(
  45079. 'The deflate stream was closed while data was being processed'
  45080. )
  45081. );
  45082. }
  45083. }
  45084. }
  45085. /**
  45086. * Accept an extension negotiation offer.
  45087. *
  45088. * @param {Array} offers The extension negotiation offers
  45089. * @return {Object} Accepted configuration
  45090. * @private
  45091. */
  45092. acceptAsServer(offers) {
  45093. const opts = this._options;
  45094. const accepted = offers.find((params) => {
  45095. if (
  45096. (opts.serverNoContextTakeover === false &&
  45097. params.server_no_context_takeover) ||
  45098. (params.server_max_window_bits &&
  45099. (opts.serverMaxWindowBits === false ||
  45100. (typeof opts.serverMaxWindowBits === 'number' &&
  45101. opts.serverMaxWindowBits > params.server_max_window_bits))) ||
  45102. (typeof opts.clientMaxWindowBits === 'number' &&
  45103. !params.client_max_window_bits)
  45104. ) {
  45105. return false;
  45106. }
  45107. return true;
  45108. });
  45109. if (!accepted) {
  45110. throw new Error('None of the extension offers can be accepted');
  45111. }
  45112. if (opts.serverNoContextTakeover) {
  45113. accepted.server_no_context_takeover = true;
  45114. }
  45115. if (opts.clientNoContextTakeover) {
  45116. accepted.client_no_context_takeover = true;
  45117. }
  45118. if (typeof opts.serverMaxWindowBits === 'number') {
  45119. accepted.server_max_window_bits = opts.serverMaxWindowBits;
  45120. }
  45121. if (typeof opts.clientMaxWindowBits === 'number') {
  45122. accepted.client_max_window_bits = opts.clientMaxWindowBits;
  45123. } else if (
  45124. accepted.client_max_window_bits === true ||
  45125. opts.clientMaxWindowBits === false
  45126. ) {
  45127. delete accepted.client_max_window_bits;
  45128. }
  45129. return accepted;
  45130. }
  45131. /**
  45132. * Accept the extension negotiation response.
  45133. *
  45134. * @param {Array} response The extension negotiation response
  45135. * @return {Object} Accepted configuration
  45136. * @private
  45137. */
  45138. acceptAsClient(response) {
  45139. const params = response[0];
  45140. if (
  45141. this._options.clientNoContextTakeover === false &&
  45142. params.client_no_context_takeover
  45143. ) {
  45144. throw new Error('Unexpected parameter "client_no_context_takeover"');
  45145. }
  45146. if (!params.client_max_window_bits) {
  45147. if (typeof this._options.clientMaxWindowBits === 'number') {
  45148. params.client_max_window_bits = this._options.clientMaxWindowBits;
  45149. }
  45150. } else if (
  45151. this._options.clientMaxWindowBits === false ||
  45152. (typeof this._options.clientMaxWindowBits === 'number' &&
  45153. params.client_max_window_bits > this._options.clientMaxWindowBits)
  45154. ) {
  45155. throw new Error(
  45156. 'Unexpected or invalid parameter "client_max_window_bits"'
  45157. );
  45158. }
  45159. return params;
  45160. }
  45161. /**
  45162. * Normalize parameters.
  45163. *
  45164. * @param {Array} configurations The extension negotiation offers/reponse
  45165. * @return {Array} The offers/response with normalized parameters
  45166. * @private
  45167. */
  45168. normalizeParams(configurations) {
  45169. configurations.forEach((params) => {
  45170. Object.keys(params).forEach((key) => {
  45171. let value = params[key];
  45172. if (value.length > 1) {
  45173. throw new Error(`Parameter "${key}" must have only a single value`);
  45174. }
  45175. value = value[0];
  45176. if (key === 'client_max_window_bits') {
  45177. if (value !== true) {
  45178. const num = +value;
  45179. if (!Number.isInteger(num) || num < 8 || num > 15) {
  45180. throw new TypeError(
  45181. `Invalid value for parameter "${key}": ${value}`
  45182. );
  45183. }
  45184. value = num;
  45185. } else if (!this._isServer) {
  45186. throw new TypeError(
  45187. `Invalid value for parameter "${key}": ${value}`
  45188. );
  45189. }
  45190. } else if (key === 'server_max_window_bits') {
  45191. const num = +value;
  45192. if (!Number.isInteger(num) || num < 8 || num > 15) {
  45193. throw new TypeError(
  45194. `Invalid value for parameter "${key}": ${value}`
  45195. );
  45196. }
  45197. value = num;
  45198. } else if (
  45199. key === 'client_no_context_takeover' ||
  45200. key === 'server_no_context_takeover'
  45201. ) {
  45202. if (value !== true) {
  45203. throw new TypeError(
  45204. `Invalid value for parameter "${key}": ${value}`
  45205. );
  45206. }
  45207. } else {
  45208. throw new Error(`Unknown parameter "${key}"`);
  45209. }
  45210. params[key] = value;
  45211. });
  45212. });
  45213. return configurations;
  45214. }
  45215. /**
  45216. * Decompress data. Concurrency limited.
  45217. *
  45218. * @param {Buffer} data Compressed data
  45219. * @param {Boolean} fin Specifies whether or not this is the last fragment
  45220. * @param {Function} callback Callback
  45221. * @public
  45222. */
  45223. decompress(data, fin, callback) {
  45224. zlibLimiter.add((done) => {
  45225. this._decompress(data, fin, (err, result) => {
  45226. done();
  45227. callback(err, result);
  45228. });
  45229. });
  45230. }
  45231. /**
  45232. * Compress data. Concurrency limited.
  45233. *
  45234. * @param {(Buffer|String)} data Data to compress
  45235. * @param {Boolean} fin Specifies whether or not this is the last fragment
  45236. * @param {Function} callback Callback
  45237. * @public
  45238. */
  45239. compress(data, fin, callback) {
  45240. zlibLimiter.add((done) => {
  45241. this._compress(data, fin, (err, result) => {
  45242. done();
  45243. callback(err, result);
  45244. });
  45245. });
  45246. }
  45247. /**
  45248. * Decompress data.
  45249. *
  45250. * @param {Buffer} data Compressed data
  45251. * @param {Boolean} fin Specifies whether or not this is the last fragment
  45252. * @param {Function} callback Callback
  45253. * @private
  45254. */
  45255. _decompress(data, fin, callback) {
  45256. const endpoint = this._isServer ? 'client' : 'server';
  45257. if (!this._inflate) {
  45258. const key = `${endpoint}_max_window_bits`;
  45259. const windowBits =
  45260. typeof this.params[key] !== 'number'
  45261. ? zlib.Z_DEFAULT_WINDOWBITS
  45262. : this.params[key];
  45263. this._inflate = zlib.createInflateRaw({
  45264. ...this._options.zlibInflateOptions,
  45265. windowBits
  45266. });
  45267. this._inflate[kPerMessageDeflate] = this;
  45268. this._inflate[kTotalLength] = 0;
  45269. this._inflate[kBuffers] = [];
  45270. this._inflate.on('error', inflateOnError);
  45271. this._inflate.on('data', inflateOnData);
  45272. }
  45273. this._inflate[kCallback] = callback;
  45274. this._inflate.write(data);
  45275. if (fin) this._inflate.write(TRAILER);
  45276. this._inflate.flush(() => {
  45277. const err = this._inflate[kError$1];
  45278. if (err) {
  45279. this._inflate.close();
  45280. this._inflate = null;
  45281. callback(err);
  45282. return;
  45283. }
  45284. const data = bufferUtil.concat(
  45285. this._inflate[kBuffers],
  45286. this._inflate[kTotalLength]
  45287. );
  45288. if (this._inflate._readableState.endEmitted) {
  45289. this._inflate.close();
  45290. this._inflate = null;
  45291. } else {
  45292. this._inflate[kTotalLength] = 0;
  45293. this._inflate[kBuffers] = [];
  45294. if (fin && this.params[`${endpoint}_no_context_takeover`]) {
  45295. this._inflate.reset();
  45296. }
  45297. }
  45298. callback(null, data);
  45299. });
  45300. }
  45301. /**
  45302. * Compress data.
  45303. *
  45304. * @param {(Buffer|String)} data Data to compress
  45305. * @param {Boolean} fin Specifies whether or not this is the last fragment
  45306. * @param {Function} callback Callback
  45307. * @private
  45308. */
  45309. _compress(data, fin, callback) {
  45310. const endpoint = this._isServer ? 'server' : 'client';
  45311. if (!this._deflate) {
  45312. const key = `${endpoint}_max_window_bits`;
  45313. const windowBits =
  45314. typeof this.params[key] !== 'number'
  45315. ? zlib.Z_DEFAULT_WINDOWBITS
  45316. : this.params[key];
  45317. this._deflate = zlib.createDeflateRaw({
  45318. ...this._options.zlibDeflateOptions,
  45319. windowBits
  45320. });
  45321. this._deflate[kTotalLength] = 0;
  45322. this._deflate[kBuffers] = [];
  45323. this._deflate.on('data', deflateOnData);
  45324. }
  45325. this._deflate[kCallback] = callback;
  45326. this._deflate.write(data);
  45327. this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
  45328. if (!this._deflate) {
  45329. //
  45330. // The deflate stream was closed while data was being processed.
  45331. //
  45332. return;
  45333. }
  45334. let data = bufferUtil.concat(
  45335. this._deflate[kBuffers],
  45336. this._deflate[kTotalLength]
  45337. );
  45338. if (fin) data = data.slice(0, data.length - 4);
  45339. //
  45340. // Ensure that the callback will not be called again in
  45341. // `PerMessageDeflate#cleanup()`.
  45342. //
  45343. this._deflate[kCallback] = null;
  45344. this._deflate[kTotalLength] = 0;
  45345. this._deflate[kBuffers] = [];
  45346. if (fin && this.params[`${endpoint}_no_context_takeover`]) {
  45347. this._deflate.reset();
  45348. }
  45349. callback(null, data);
  45350. });
  45351. }
  45352. }
  45353. var permessageDeflate = PerMessageDeflate$4;
  45354. /**
  45355. * The listener of the `zlib.DeflateRaw` stream `'data'` event.
  45356. *
  45357. * @param {Buffer} chunk A chunk of data
  45358. * @private
  45359. */
  45360. function deflateOnData(chunk) {
  45361. this[kBuffers].push(chunk);
  45362. this[kTotalLength] += chunk.length;
  45363. }
  45364. /**
  45365. * The listener of the `zlib.InflateRaw` stream `'data'` event.
  45366. *
  45367. * @param {Buffer} chunk A chunk of data
  45368. * @private
  45369. */
  45370. function inflateOnData(chunk) {
  45371. this[kTotalLength] += chunk.length;
  45372. if (
  45373. this[kPerMessageDeflate]._maxPayload < 1 ||
  45374. this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload
  45375. ) {
  45376. this[kBuffers].push(chunk);
  45377. return;
  45378. }
  45379. this[kError$1] = new RangeError('Max payload size exceeded');
  45380. this[kError$1].code = 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH';
  45381. this[kError$1][kStatusCode$2] = 1009;
  45382. this.removeListener('data', inflateOnData);
  45383. this.reset();
  45384. }
  45385. /**
  45386. * The listener of the `zlib.InflateRaw` stream `'error'` event.
  45387. *
  45388. * @param {Error} err The emitted error
  45389. * @private
  45390. */
  45391. function inflateOnError(err) {
  45392. //
  45393. // There is no need to call `Zlib#close()` as the handle is automatically
  45394. // closed when an error is emitted.
  45395. //
  45396. this[kPerMessageDeflate]._inflate = null;
  45397. err[kStatusCode$2] = 1007;
  45398. this[kCallback](err);
  45399. }
  45400. var validation = {exports: {}};
  45401. //
  45402. // Allowed token characters:
  45403. //
  45404. // '!', '#', '$', '%', '&', ''', '*', '+', '-',
  45405. // '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~'
  45406. //
  45407. // tokenChars[32] === 0 // ' '
  45408. // tokenChars[33] === 1 // '!'
  45409. // tokenChars[34] === 0 // '"'
  45410. // ...
  45411. //
  45412. // prettier-ignore
  45413. const tokenChars$2 = [
  45414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15
  45415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31
  45416. 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47
  45417. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63
  45418. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79
  45419. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95
  45420. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111
  45421. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127
  45422. ];
  45423. /**
  45424. * Checks if a status code is allowed in a close frame.
  45425. *
  45426. * @param {Number} code The status code
  45427. * @return {Boolean} `true` if the status code is valid, else `false`
  45428. * @public
  45429. */
  45430. function isValidStatusCode$2(code) {
  45431. return (
  45432. (code >= 1000 &&
  45433. code <= 1014 &&
  45434. code !== 1004 &&
  45435. code !== 1005 &&
  45436. code !== 1006) ||
  45437. (code >= 3000 && code <= 4999)
  45438. );
  45439. }
  45440. /**
  45441. * Checks if a given buffer contains only correct UTF-8.
  45442. * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by
  45443. * Markus Kuhn.
  45444. *
  45445. * @param {Buffer} buf The buffer to check
  45446. * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false`
  45447. * @public
  45448. */
  45449. function _isValidUTF8(buf) {
  45450. const len = buf.length;
  45451. let i = 0;
  45452. while (i < len) {
  45453. if ((buf[i] & 0x80) === 0) {
  45454. // 0xxxxxxx
  45455. i++;
  45456. } else if ((buf[i] & 0xe0) === 0xc0) {
  45457. // 110xxxxx 10xxxxxx
  45458. if (
  45459. i + 1 === len ||
  45460. (buf[i + 1] & 0xc0) !== 0x80 ||
  45461. (buf[i] & 0xfe) === 0xc0 // Overlong
  45462. ) {
  45463. return false;
  45464. }
  45465. i += 2;
  45466. } else if ((buf[i] & 0xf0) === 0xe0) {
  45467. // 1110xxxx 10xxxxxx 10xxxxxx
  45468. if (
  45469. i + 2 >= len ||
  45470. (buf[i + 1] & 0xc0) !== 0x80 ||
  45471. (buf[i + 2] & 0xc0) !== 0x80 ||
  45472. (buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80) || // Overlong
  45473. (buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0) // Surrogate (U+D800 - U+DFFF)
  45474. ) {
  45475. return false;
  45476. }
  45477. i += 3;
  45478. } else if ((buf[i] & 0xf8) === 0xf0) {
  45479. // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  45480. if (
  45481. i + 3 >= len ||
  45482. (buf[i + 1] & 0xc0) !== 0x80 ||
  45483. (buf[i + 2] & 0xc0) !== 0x80 ||
  45484. (buf[i + 3] & 0xc0) !== 0x80 ||
  45485. (buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80) || // Overlong
  45486. (buf[i] === 0xf4 && buf[i + 1] > 0x8f) ||
  45487. buf[i] > 0xf4 // > U+10FFFF
  45488. ) {
  45489. return false;
  45490. }
  45491. i += 4;
  45492. } else {
  45493. return false;
  45494. }
  45495. }
  45496. return true;
  45497. }
  45498. try {
  45499. const isValidUTF8 = require('utf-8-validate');
  45500. validation.exports = {
  45501. isValidStatusCode: isValidStatusCode$2,
  45502. isValidUTF8(buf) {
  45503. return buf.length < 150 ? _isValidUTF8(buf) : isValidUTF8(buf);
  45504. },
  45505. tokenChars: tokenChars$2
  45506. };
  45507. } catch (e) /* istanbul ignore next */ {
  45508. validation.exports = {
  45509. isValidStatusCode: isValidStatusCode$2,
  45510. isValidUTF8: _isValidUTF8,
  45511. tokenChars: tokenChars$2
  45512. };
  45513. }
  45514. const { Writable: Writable$1 } = require$$0__default$3;
  45515. const PerMessageDeflate$3 = permessageDeflate;
  45516. const {
  45517. BINARY_TYPES: BINARY_TYPES$1,
  45518. EMPTY_BUFFER: EMPTY_BUFFER$2,
  45519. kStatusCode: kStatusCode$1,
  45520. kWebSocket: kWebSocket$2
  45521. } = constants;
  45522. const { concat, toArrayBuffer, unmask } = bufferUtil$1.exports;
  45523. const { isValidStatusCode: isValidStatusCode$1, isValidUTF8 } = validation.exports;
  45524. const GET_INFO = 0;
  45525. const GET_PAYLOAD_LENGTH_16 = 1;
  45526. const GET_PAYLOAD_LENGTH_64 = 2;
  45527. const GET_MASK = 3;
  45528. const GET_DATA = 4;
  45529. const INFLATING = 5;
  45530. /**
  45531. * HyBi Receiver implementation.
  45532. *
  45533. * @extends Writable
  45534. */
  45535. class Receiver$1 extends Writable$1 {
  45536. /**
  45537. * Creates a Receiver instance.
  45538. *
  45539. * @param {Object} [options] Options object
  45540. * @param {String} [options.binaryType=nodebuffer] The type for binary data
  45541. * @param {Object} [options.extensions] An object containing the negotiated
  45542. * extensions
  45543. * @param {Boolean} [options.isServer=false] Specifies whether to operate in
  45544. * client or server mode
  45545. * @param {Number} [options.maxPayload=0] The maximum allowed message length
  45546. * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
  45547. * not to skip UTF-8 validation for text and close messages
  45548. */
  45549. constructor(options = {}) {
  45550. super();
  45551. this._binaryType = options.binaryType || BINARY_TYPES$1[0];
  45552. this._extensions = options.extensions || {};
  45553. this._isServer = !!options.isServer;
  45554. this._maxPayload = options.maxPayload | 0;
  45555. this._skipUTF8Validation = !!options.skipUTF8Validation;
  45556. this[kWebSocket$2] = undefined;
  45557. this._bufferedBytes = 0;
  45558. this._buffers = [];
  45559. this._compressed = false;
  45560. this._payloadLength = 0;
  45561. this._mask = undefined;
  45562. this._fragmented = 0;
  45563. this._masked = false;
  45564. this._fin = false;
  45565. this._opcode = 0;
  45566. this._totalPayloadLength = 0;
  45567. this._messageLength = 0;
  45568. this._fragments = [];
  45569. this._state = GET_INFO;
  45570. this._loop = false;
  45571. }
  45572. /**
  45573. * Implements `Writable.prototype._write()`.
  45574. *
  45575. * @param {Buffer} chunk The chunk of data to write
  45576. * @param {String} encoding The character encoding of `chunk`
  45577. * @param {Function} cb Callback
  45578. * @private
  45579. */
  45580. _write(chunk, encoding, cb) {
  45581. if (this._opcode === 0x08 && this._state == GET_INFO) return cb();
  45582. this._bufferedBytes += chunk.length;
  45583. this._buffers.push(chunk);
  45584. this.startLoop(cb);
  45585. }
  45586. /**
  45587. * Consumes `n` bytes from the buffered data.
  45588. *
  45589. * @param {Number} n The number of bytes to consume
  45590. * @return {Buffer} The consumed bytes
  45591. * @private
  45592. */
  45593. consume(n) {
  45594. this._bufferedBytes -= n;
  45595. if (n === this._buffers[0].length) return this._buffers.shift();
  45596. if (n < this._buffers[0].length) {
  45597. const buf = this._buffers[0];
  45598. this._buffers[0] = buf.slice(n);
  45599. return buf.slice(0, n);
  45600. }
  45601. const dst = Buffer.allocUnsafe(n);
  45602. do {
  45603. const buf = this._buffers[0];
  45604. const offset = dst.length - n;
  45605. if (n >= buf.length) {
  45606. dst.set(this._buffers.shift(), offset);
  45607. } else {
  45608. dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
  45609. this._buffers[0] = buf.slice(n);
  45610. }
  45611. n -= buf.length;
  45612. } while (n > 0);
  45613. return dst;
  45614. }
  45615. /**
  45616. * Starts the parsing loop.
  45617. *
  45618. * @param {Function} cb Callback
  45619. * @private
  45620. */
  45621. startLoop(cb) {
  45622. let err;
  45623. this._loop = true;
  45624. do {
  45625. switch (this._state) {
  45626. case GET_INFO:
  45627. err = this.getInfo();
  45628. break;
  45629. case GET_PAYLOAD_LENGTH_16:
  45630. err = this.getPayloadLength16();
  45631. break;
  45632. case GET_PAYLOAD_LENGTH_64:
  45633. err = this.getPayloadLength64();
  45634. break;
  45635. case GET_MASK:
  45636. this.getMask();
  45637. break;
  45638. case GET_DATA:
  45639. err = this.getData(cb);
  45640. break;
  45641. default:
  45642. // `INFLATING`
  45643. this._loop = false;
  45644. return;
  45645. }
  45646. } while (this._loop);
  45647. cb(err);
  45648. }
  45649. /**
  45650. * Reads the first two bytes of a frame.
  45651. *
  45652. * @return {(RangeError|undefined)} A possible error
  45653. * @private
  45654. */
  45655. getInfo() {
  45656. if (this._bufferedBytes < 2) {
  45657. this._loop = false;
  45658. return;
  45659. }
  45660. const buf = this.consume(2);
  45661. if ((buf[0] & 0x30) !== 0x00) {
  45662. this._loop = false;
  45663. return error$1(
  45664. RangeError,
  45665. 'RSV2 and RSV3 must be clear',
  45666. true,
  45667. 1002,
  45668. 'WS_ERR_UNEXPECTED_RSV_2_3'
  45669. );
  45670. }
  45671. const compressed = (buf[0] & 0x40) === 0x40;
  45672. if (compressed && !this._extensions[PerMessageDeflate$3.extensionName]) {
  45673. this._loop = false;
  45674. return error$1(
  45675. RangeError,
  45676. 'RSV1 must be clear',
  45677. true,
  45678. 1002,
  45679. 'WS_ERR_UNEXPECTED_RSV_1'
  45680. );
  45681. }
  45682. this._fin = (buf[0] & 0x80) === 0x80;
  45683. this._opcode = buf[0] & 0x0f;
  45684. this._payloadLength = buf[1] & 0x7f;
  45685. if (this._opcode === 0x00) {
  45686. if (compressed) {
  45687. this._loop = false;
  45688. return error$1(
  45689. RangeError,
  45690. 'RSV1 must be clear',
  45691. true,
  45692. 1002,
  45693. 'WS_ERR_UNEXPECTED_RSV_1'
  45694. );
  45695. }
  45696. if (!this._fragmented) {
  45697. this._loop = false;
  45698. return error$1(
  45699. RangeError,
  45700. 'invalid opcode 0',
  45701. true,
  45702. 1002,
  45703. 'WS_ERR_INVALID_OPCODE'
  45704. );
  45705. }
  45706. this._opcode = this._fragmented;
  45707. } else if (this._opcode === 0x01 || this._opcode === 0x02) {
  45708. if (this._fragmented) {
  45709. this._loop = false;
  45710. return error$1(
  45711. RangeError,
  45712. `invalid opcode ${this._opcode}`,
  45713. true,
  45714. 1002,
  45715. 'WS_ERR_INVALID_OPCODE'
  45716. );
  45717. }
  45718. this._compressed = compressed;
  45719. } else if (this._opcode > 0x07 && this._opcode < 0x0b) {
  45720. if (!this._fin) {
  45721. this._loop = false;
  45722. return error$1(
  45723. RangeError,
  45724. 'FIN must be set',
  45725. true,
  45726. 1002,
  45727. 'WS_ERR_EXPECTED_FIN'
  45728. );
  45729. }
  45730. if (compressed) {
  45731. this._loop = false;
  45732. return error$1(
  45733. RangeError,
  45734. 'RSV1 must be clear',
  45735. true,
  45736. 1002,
  45737. 'WS_ERR_UNEXPECTED_RSV_1'
  45738. );
  45739. }
  45740. if (this._payloadLength > 0x7d) {
  45741. this._loop = false;
  45742. return error$1(
  45743. RangeError,
  45744. `invalid payload length ${this._payloadLength}`,
  45745. true,
  45746. 1002,
  45747. 'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH'
  45748. );
  45749. }
  45750. } else {
  45751. this._loop = false;
  45752. return error$1(
  45753. RangeError,
  45754. `invalid opcode ${this._opcode}`,
  45755. true,
  45756. 1002,
  45757. 'WS_ERR_INVALID_OPCODE'
  45758. );
  45759. }
  45760. if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
  45761. this._masked = (buf[1] & 0x80) === 0x80;
  45762. if (this._isServer) {
  45763. if (!this._masked) {
  45764. this._loop = false;
  45765. return error$1(
  45766. RangeError,
  45767. 'MASK must be set',
  45768. true,
  45769. 1002,
  45770. 'WS_ERR_EXPECTED_MASK'
  45771. );
  45772. }
  45773. } else if (this._masked) {
  45774. this._loop = false;
  45775. return error$1(
  45776. RangeError,
  45777. 'MASK must be clear',
  45778. true,
  45779. 1002,
  45780. 'WS_ERR_UNEXPECTED_MASK'
  45781. );
  45782. }
  45783. if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
  45784. else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
  45785. else return this.haveLength();
  45786. }
  45787. /**
  45788. * Gets extended payload length (7+16).
  45789. *
  45790. * @return {(RangeError|undefined)} A possible error
  45791. * @private
  45792. */
  45793. getPayloadLength16() {
  45794. if (this._bufferedBytes < 2) {
  45795. this._loop = false;
  45796. return;
  45797. }
  45798. this._payloadLength = this.consume(2).readUInt16BE(0);
  45799. return this.haveLength();
  45800. }
  45801. /**
  45802. * Gets extended payload length (7+64).
  45803. *
  45804. * @return {(RangeError|undefined)} A possible error
  45805. * @private
  45806. */
  45807. getPayloadLength64() {
  45808. if (this._bufferedBytes < 8) {
  45809. this._loop = false;
  45810. return;
  45811. }
  45812. const buf = this.consume(8);
  45813. const num = buf.readUInt32BE(0);
  45814. //
  45815. // The maximum safe integer in JavaScript is 2^53 - 1. An error is returned
  45816. // if payload length is greater than this number.
  45817. //
  45818. if (num > Math.pow(2, 53 - 32) - 1) {
  45819. this._loop = false;
  45820. return error$1(
  45821. RangeError,
  45822. 'Unsupported WebSocket frame: payload length > 2^53 - 1',
  45823. false,
  45824. 1009,
  45825. 'WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH'
  45826. );
  45827. }
  45828. this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
  45829. return this.haveLength();
  45830. }
  45831. /**
  45832. * Payload length has been read.
  45833. *
  45834. * @return {(RangeError|undefined)} A possible error
  45835. * @private
  45836. */
  45837. haveLength() {
  45838. if (this._payloadLength && this._opcode < 0x08) {
  45839. this._totalPayloadLength += this._payloadLength;
  45840. if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
  45841. this._loop = false;
  45842. return error$1(
  45843. RangeError,
  45844. 'Max payload size exceeded',
  45845. false,
  45846. 1009,
  45847. 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'
  45848. );
  45849. }
  45850. }
  45851. if (this._masked) this._state = GET_MASK;
  45852. else this._state = GET_DATA;
  45853. }
  45854. /**
  45855. * Reads mask bytes.
  45856. *
  45857. * @private
  45858. */
  45859. getMask() {
  45860. if (this._bufferedBytes < 4) {
  45861. this._loop = false;
  45862. return;
  45863. }
  45864. this._mask = this.consume(4);
  45865. this._state = GET_DATA;
  45866. }
  45867. /**
  45868. * Reads data bytes.
  45869. *
  45870. * @param {Function} cb Callback
  45871. * @return {(Error|RangeError|undefined)} A possible error
  45872. * @private
  45873. */
  45874. getData(cb) {
  45875. let data = EMPTY_BUFFER$2;
  45876. if (this._payloadLength) {
  45877. if (this._bufferedBytes < this._payloadLength) {
  45878. this._loop = false;
  45879. return;
  45880. }
  45881. data = this.consume(this._payloadLength);
  45882. if (
  45883. this._masked &&
  45884. (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0
  45885. ) {
  45886. unmask(data, this._mask);
  45887. }
  45888. }
  45889. if (this._opcode > 0x07) return this.controlMessage(data);
  45890. if (this._compressed) {
  45891. this._state = INFLATING;
  45892. this.decompress(data, cb);
  45893. return;
  45894. }
  45895. if (data.length) {
  45896. //
  45897. // This message is not compressed so its length is the sum of the payload
  45898. // length of all fragments.
  45899. //
  45900. this._messageLength = this._totalPayloadLength;
  45901. this._fragments.push(data);
  45902. }
  45903. return this.dataMessage();
  45904. }
  45905. /**
  45906. * Decompresses data.
  45907. *
  45908. * @param {Buffer} data Compressed data
  45909. * @param {Function} cb Callback
  45910. * @private
  45911. */
  45912. decompress(data, cb) {
  45913. const perMessageDeflate = this._extensions[PerMessageDeflate$3.extensionName];
  45914. perMessageDeflate.decompress(data, this._fin, (err, buf) => {
  45915. if (err) return cb(err);
  45916. if (buf.length) {
  45917. this._messageLength += buf.length;
  45918. if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
  45919. return cb(
  45920. error$1(
  45921. RangeError,
  45922. 'Max payload size exceeded',
  45923. false,
  45924. 1009,
  45925. 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'
  45926. )
  45927. );
  45928. }
  45929. this._fragments.push(buf);
  45930. }
  45931. const er = this.dataMessage();
  45932. if (er) return cb(er);
  45933. this.startLoop(cb);
  45934. });
  45935. }
  45936. /**
  45937. * Handles a data message.
  45938. *
  45939. * @return {(Error|undefined)} A possible error
  45940. * @private
  45941. */
  45942. dataMessage() {
  45943. if (this._fin) {
  45944. const messageLength = this._messageLength;
  45945. const fragments = this._fragments;
  45946. this._totalPayloadLength = 0;
  45947. this._messageLength = 0;
  45948. this._fragmented = 0;
  45949. this._fragments = [];
  45950. if (this._opcode === 2) {
  45951. let data;
  45952. if (this._binaryType === 'nodebuffer') {
  45953. data = concat(fragments, messageLength);
  45954. } else if (this._binaryType === 'arraybuffer') {
  45955. data = toArrayBuffer(concat(fragments, messageLength));
  45956. } else {
  45957. data = fragments;
  45958. }
  45959. this.emit('message', data, true);
  45960. } else {
  45961. const buf = concat(fragments, messageLength);
  45962. if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
  45963. this._loop = false;
  45964. return error$1(
  45965. Error,
  45966. 'invalid UTF-8 sequence',
  45967. true,
  45968. 1007,
  45969. 'WS_ERR_INVALID_UTF8'
  45970. );
  45971. }
  45972. this.emit('message', buf, false);
  45973. }
  45974. }
  45975. this._state = GET_INFO;
  45976. }
  45977. /**
  45978. * Handles a control message.
  45979. *
  45980. * @param {Buffer} data Data to handle
  45981. * @return {(Error|RangeError|undefined)} A possible error
  45982. * @private
  45983. */
  45984. controlMessage(data) {
  45985. if (this._opcode === 0x08) {
  45986. this._loop = false;
  45987. if (data.length === 0) {
  45988. this.emit('conclude', 1005, EMPTY_BUFFER$2);
  45989. this.end();
  45990. } else if (data.length === 1) {
  45991. return error$1(
  45992. RangeError,
  45993. 'invalid payload length 1',
  45994. true,
  45995. 1002,
  45996. 'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH'
  45997. );
  45998. } else {
  45999. const code = data.readUInt16BE(0);
  46000. if (!isValidStatusCode$1(code)) {
  46001. return error$1(
  46002. RangeError,
  46003. `invalid status code ${code}`,
  46004. true,
  46005. 1002,
  46006. 'WS_ERR_INVALID_CLOSE_CODE'
  46007. );
  46008. }
  46009. const buf = data.slice(2);
  46010. if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
  46011. return error$1(
  46012. Error,
  46013. 'invalid UTF-8 sequence',
  46014. true,
  46015. 1007,
  46016. 'WS_ERR_INVALID_UTF8'
  46017. );
  46018. }
  46019. this.emit('conclude', code, buf);
  46020. this.end();
  46021. }
  46022. } else if (this._opcode === 0x09) {
  46023. this.emit('ping', data);
  46024. } else {
  46025. this.emit('pong', data);
  46026. }
  46027. this._state = GET_INFO;
  46028. }
  46029. }
  46030. var receiver = Receiver$1;
  46031. /**
  46032. * Builds an error object.
  46033. *
  46034. * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
  46035. * @param {String} message The error message
  46036. * @param {Boolean} prefix Specifies whether or not to add a default prefix to
  46037. * `message`
  46038. * @param {Number} statusCode The status code
  46039. * @param {String} errorCode The exposed error code
  46040. * @return {(Error|RangeError)} The error
  46041. * @private
  46042. */
  46043. function error$1(ErrorCtor, message, prefix, statusCode, errorCode) {
  46044. const err = new ErrorCtor(
  46045. prefix ? `Invalid WebSocket frame: ${message}` : message
  46046. );
  46047. Error.captureStackTrace(err, error$1);
  46048. err.code = errorCode;
  46049. err[kStatusCode$1] = statusCode;
  46050. return err;
  46051. }
  46052. /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^net|tls$" }] */
  46053. const { randomFillSync } = require$$1__default$2;
  46054. const PerMessageDeflate$2 = permessageDeflate;
  46055. const { EMPTY_BUFFER: EMPTY_BUFFER$1 } = constants;
  46056. const { isValidStatusCode } = validation.exports;
  46057. const { mask: applyMask, toBuffer: toBuffer$1 } = bufferUtil$1.exports;
  46058. const kByteLength = Symbol('kByteLength');
  46059. const maskBuffer = Buffer.alloc(4);
  46060. /**
  46061. * HyBi Sender implementation.
  46062. */
  46063. class Sender$1 {
  46064. /**
  46065. * Creates a Sender instance.
  46066. *
  46067. * @param {(net.Socket|tls.Socket)} socket The connection socket
  46068. * @param {Object} [extensions] An object containing the negotiated extensions
  46069. * @param {Function} [generateMask] The function used to generate the masking
  46070. * key
  46071. */
  46072. constructor(socket, extensions, generateMask) {
  46073. this._extensions = extensions || {};
  46074. if (generateMask) {
  46075. this._generateMask = generateMask;
  46076. this._maskBuffer = Buffer.alloc(4);
  46077. }
  46078. this._socket = socket;
  46079. this._firstFragment = true;
  46080. this._compress = false;
  46081. this._bufferedBytes = 0;
  46082. this._deflating = false;
  46083. this._queue = [];
  46084. }
  46085. /**
  46086. * Frames a piece of data according to the HyBi WebSocket protocol.
  46087. *
  46088. * @param {(Buffer|String)} data The data to frame
  46089. * @param {Object} options Options object
  46090. * @param {Boolean} [options.fin=false] Specifies whether or not to set the
  46091. * FIN bit
  46092. * @param {Function} [options.generateMask] The function used to generate the
  46093. * masking key
  46094. * @param {Boolean} [options.mask=false] Specifies whether or not to mask
  46095. * `data`
  46096. * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
  46097. * key
  46098. * @param {Number} options.opcode The opcode
  46099. * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
  46100. * modified
  46101. * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
  46102. * RSV1 bit
  46103. * @return {(Buffer|String)[]} The framed data
  46104. * @public
  46105. */
  46106. static frame(data, options) {
  46107. let mask;
  46108. let merge = false;
  46109. let offset = 2;
  46110. let skipMasking = false;
  46111. if (options.mask) {
  46112. mask = options.maskBuffer || maskBuffer;
  46113. if (options.generateMask) {
  46114. options.generateMask(mask);
  46115. } else {
  46116. randomFillSync(mask, 0, 4);
  46117. }
  46118. skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
  46119. offset = 6;
  46120. }
  46121. let dataLength;
  46122. if (typeof data === 'string') {
  46123. if (
  46124. (!options.mask || skipMasking) &&
  46125. options[kByteLength] !== undefined
  46126. ) {
  46127. dataLength = options[kByteLength];
  46128. } else {
  46129. data = Buffer.from(data);
  46130. dataLength = data.length;
  46131. }
  46132. } else {
  46133. dataLength = data.length;
  46134. merge = options.mask && options.readOnly && !skipMasking;
  46135. }
  46136. let payloadLength = dataLength;
  46137. if (dataLength >= 65536) {
  46138. offset += 8;
  46139. payloadLength = 127;
  46140. } else if (dataLength > 125) {
  46141. offset += 2;
  46142. payloadLength = 126;
  46143. }
  46144. const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
  46145. target[0] = options.fin ? options.opcode | 0x80 : options.opcode;
  46146. if (options.rsv1) target[0] |= 0x40;
  46147. target[1] = payloadLength;
  46148. if (payloadLength === 126) {
  46149. target.writeUInt16BE(dataLength, 2);
  46150. } else if (payloadLength === 127) {
  46151. target[2] = target[3] = 0;
  46152. target.writeUIntBE(dataLength, 4, 6);
  46153. }
  46154. if (!options.mask) return [target, data];
  46155. target[1] |= 0x80;
  46156. target[offset - 4] = mask[0];
  46157. target[offset - 3] = mask[1];
  46158. target[offset - 2] = mask[2];
  46159. target[offset - 1] = mask[3];
  46160. if (skipMasking) return [target, data];
  46161. if (merge) {
  46162. applyMask(data, mask, target, offset, dataLength);
  46163. return [target];
  46164. }
  46165. applyMask(data, mask, data, 0, dataLength);
  46166. return [target, data];
  46167. }
  46168. /**
  46169. * Sends a close message to the other peer.
  46170. *
  46171. * @param {Number} [code] The status code component of the body
  46172. * @param {(String|Buffer)} [data] The message component of the body
  46173. * @param {Boolean} [mask=false] Specifies whether or not to mask the message
  46174. * @param {Function} [cb] Callback
  46175. * @public
  46176. */
  46177. close(code, data, mask, cb) {
  46178. let buf;
  46179. if (code === undefined) {
  46180. buf = EMPTY_BUFFER$1;
  46181. } else if (typeof code !== 'number' || !isValidStatusCode(code)) {
  46182. throw new TypeError('First argument must be a valid error code number');
  46183. } else if (data === undefined || !data.length) {
  46184. buf = Buffer.allocUnsafe(2);
  46185. buf.writeUInt16BE(code, 0);
  46186. } else {
  46187. const length = Buffer.byteLength(data);
  46188. if (length > 123) {
  46189. throw new RangeError('The message must not be greater than 123 bytes');
  46190. }
  46191. buf = Buffer.allocUnsafe(2 + length);
  46192. buf.writeUInt16BE(code, 0);
  46193. if (typeof data === 'string') {
  46194. buf.write(data, 2);
  46195. } else {
  46196. buf.set(data, 2);
  46197. }
  46198. }
  46199. const options = {
  46200. [kByteLength]: buf.length,
  46201. fin: true,
  46202. generateMask: this._generateMask,
  46203. mask,
  46204. maskBuffer: this._maskBuffer,
  46205. opcode: 0x08,
  46206. readOnly: false,
  46207. rsv1: false
  46208. };
  46209. if (this._deflating) {
  46210. this.enqueue([this.dispatch, buf, false, options, cb]);
  46211. } else {
  46212. this.sendFrame(Sender$1.frame(buf, options), cb);
  46213. }
  46214. }
  46215. /**
  46216. * Sends a ping message to the other peer.
  46217. *
  46218. * @param {*} data The message to send
  46219. * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
  46220. * @param {Function} [cb] Callback
  46221. * @public
  46222. */
  46223. ping(data, mask, cb) {
  46224. let byteLength;
  46225. let readOnly;
  46226. if (typeof data === 'string') {
  46227. byteLength = Buffer.byteLength(data);
  46228. readOnly = false;
  46229. } else {
  46230. data = toBuffer$1(data);
  46231. byteLength = data.length;
  46232. readOnly = toBuffer$1.readOnly;
  46233. }
  46234. if (byteLength > 125) {
  46235. throw new RangeError('The data size must not be greater than 125 bytes');
  46236. }
  46237. const options = {
  46238. [kByteLength]: byteLength,
  46239. fin: true,
  46240. generateMask: this._generateMask,
  46241. mask,
  46242. maskBuffer: this._maskBuffer,
  46243. opcode: 0x09,
  46244. readOnly,
  46245. rsv1: false
  46246. };
  46247. if (this._deflating) {
  46248. this.enqueue([this.dispatch, data, false, options, cb]);
  46249. } else {
  46250. this.sendFrame(Sender$1.frame(data, options), cb);
  46251. }
  46252. }
  46253. /**
  46254. * Sends a pong message to the other peer.
  46255. *
  46256. * @param {*} data The message to send
  46257. * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
  46258. * @param {Function} [cb] Callback
  46259. * @public
  46260. */
  46261. pong(data, mask, cb) {
  46262. let byteLength;
  46263. let readOnly;
  46264. if (typeof data === 'string') {
  46265. byteLength = Buffer.byteLength(data);
  46266. readOnly = false;
  46267. } else {
  46268. data = toBuffer$1(data);
  46269. byteLength = data.length;
  46270. readOnly = toBuffer$1.readOnly;
  46271. }
  46272. if (byteLength > 125) {
  46273. throw new RangeError('The data size must not be greater than 125 bytes');
  46274. }
  46275. const options = {
  46276. [kByteLength]: byteLength,
  46277. fin: true,
  46278. generateMask: this._generateMask,
  46279. mask,
  46280. maskBuffer: this._maskBuffer,
  46281. opcode: 0x0a,
  46282. readOnly,
  46283. rsv1: false
  46284. };
  46285. if (this._deflating) {
  46286. this.enqueue([this.dispatch, data, false, options, cb]);
  46287. } else {
  46288. this.sendFrame(Sender$1.frame(data, options), cb);
  46289. }
  46290. }
  46291. /**
  46292. * Sends a data message to the other peer.
  46293. *
  46294. * @param {*} data The message to send
  46295. * @param {Object} options Options object
  46296. * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
  46297. * or text
  46298. * @param {Boolean} [options.compress=false] Specifies whether or not to
  46299. * compress `data`
  46300. * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
  46301. * last one
  46302. * @param {Boolean} [options.mask=false] Specifies whether or not to mask
  46303. * `data`
  46304. * @param {Function} [cb] Callback
  46305. * @public
  46306. */
  46307. send(data, options, cb) {
  46308. const perMessageDeflate = this._extensions[PerMessageDeflate$2.extensionName];
  46309. let opcode = options.binary ? 2 : 1;
  46310. let rsv1 = options.compress;
  46311. let byteLength;
  46312. let readOnly;
  46313. if (typeof data === 'string') {
  46314. byteLength = Buffer.byteLength(data);
  46315. readOnly = false;
  46316. } else {
  46317. data = toBuffer$1(data);
  46318. byteLength = data.length;
  46319. readOnly = toBuffer$1.readOnly;
  46320. }
  46321. if (this._firstFragment) {
  46322. this._firstFragment = false;
  46323. if (
  46324. rsv1 &&
  46325. perMessageDeflate &&
  46326. perMessageDeflate.params[
  46327. perMessageDeflate._isServer
  46328. ? 'server_no_context_takeover'
  46329. : 'client_no_context_takeover'
  46330. ]
  46331. ) {
  46332. rsv1 = byteLength >= perMessageDeflate._threshold;
  46333. }
  46334. this._compress = rsv1;
  46335. } else {
  46336. rsv1 = false;
  46337. opcode = 0;
  46338. }
  46339. if (options.fin) this._firstFragment = true;
  46340. if (perMessageDeflate) {
  46341. const opts = {
  46342. [kByteLength]: byteLength,
  46343. fin: options.fin,
  46344. generateMask: this._generateMask,
  46345. mask: options.mask,
  46346. maskBuffer: this._maskBuffer,
  46347. opcode,
  46348. readOnly,
  46349. rsv1
  46350. };
  46351. if (this._deflating) {
  46352. this.enqueue([this.dispatch, data, this._compress, opts, cb]);
  46353. } else {
  46354. this.dispatch(data, this._compress, opts, cb);
  46355. }
  46356. } else {
  46357. this.sendFrame(
  46358. Sender$1.frame(data, {
  46359. [kByteLength]: byteLength,
  46360. fin: options.fin,
  46361. generateMask: this._generateMask,
  46362. mask: options.mask,
  46363. maskBuffer: this._maskBuffer,
  46364. opcode,
  46365. readOnly,
  46366. rsv1: false
  46367. }),
  46368. cb
  46369. );
  46370. }
  46371. }
  46372. /**
  46373. * Dispatches a message.
  46374. *
  46375. * @param {(Buffer|String)} data The message to send
  46376. * @param {Boolean} [compress=false] Specifies whether or not to compress
  46377. * `data`
  46378. * @param {Object} options Options object
  46379. * @param {Boolean} [options.fin=false] Specifies whether or not to set the
  46380. * FIN bit
  46381. * @param {Function} [options.generateMask] The function used to generate the
  46382. * masking key
  46383. * @param {Boolean} [options.mask=false] Specifies whether or not to mask
  46384. * `data`
  46385. * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
  46386. * key
  46387. * @param {Number} options.opcode The opcode
  46388. * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
  46389. * modified
  46390. * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
  46391. * RSV1 bit
  46392. * @param {Function} [cb] Callback
  46393. * @private
  46394. */
  46395. dispatch(data, compress, options, cb) {
  46396. if (!compress) {
  46397. this.sendFrame(Sender$1.frame(data, options), cb);
  46398. return;
  46399. }
  46400. const perMessageDeflate = this._extensions[PerMessageDeflate$2.extensionName];
  46401. this._bufferedBytes += options[kByteLength];
  46402. this._deflating = true;
  46403. perMessageDeflate.compress(data, options.fin, (_, buf) => {
  46404. if (this._socket.destroyed) {
  46405. const err = new Error(
  46406. 'The socket was closed while data was being compressed'
  46407. );
  46408. if (typeof cb === 'function') cb(err);
  46409. for (let i = 0; i < this._queue.length; i++) {
  46410. const params = this._queue[i];
  46411. const callback = params[params.length - 1];
  46412. if (typeof callback === 'function') callback(err);
  46413. }
  46414. return;
  46415. }
  46416. this._bufferedBytes -= options[kByteLength];
  46417. this._deflating = false;
  46418. options.readOnly = false;
  46419. this.sendFrame(Sender$1.frame(buf, options), cb);
  46420. this.dequeue();
  46421. });
  46422. }
  46423. /**
  46424. * Executes queued send operations.
  46425. *
  46426. * @private
  46427. */
  46428. dequeue() {
  46429. while (!this._deflating && this._queue.length) {
  46430. const params = this._queue.shift();
  46431. this._bufferedBytes -= params[3][kByteLength];
  46432. Reflect.apply(params[0], this, params.slice(1));
  46433. }
  46434. }
  46435. /**
  46436. * Enqueues a send operation.
  46437. *
  46438. * @param {Array} params Send operation parameters.
  46439. * @private
  46440. */
  46441. enqueue(params) {
  46442. this._bufferedBytes += params[3][kByteLength];
  46443. this._queue.push(params);
  46444. }
  46445. /**
  46446. * Sends a frame.
  46447. *
  46448. * @param {Buffer[]} list The frame to send
  46449. * @param {Function} [cb] Callback
  46450. * @private
  46451. */
  46452. sendFrame(list, cb) {
  46453. if (list.length === 2) {
  46454. this._socket.cork();
  46455. this._socket.write(list[0]);
  46456. this._socket.write(list[1], cb);
  46457. this._socket.uncork();
  46458. } else {
  46459. this._socket.write(list[0], cb);
  46460. }
  46461. }
  46462. }
  46463. var sender = Sender$1;
  46464. const { kForOnEventAttribute: kForOnEventAttribute$1, kListener: kListener$1 } = constants;
  46465. const kCode = Symbol('kCode');
  46466. const kData = Symbol('kData');
  46467. const kError = Symbol('kError');
  46468. const kMessage = Symbol('kMessage');
  46469. const kReason = Symbol('kReason');
  46470. const kTarget = Symbol('kTarget');
  46471. const kType = Symbol('kType');
  46472. const kWasClean = Symbol('kWasClean');
  46473. /**
  46474. * Class representing an event.
  46475. */
  46476. class Event {
  46477. /**
  46478. * Create a new `Event`.
  46479. *
  46480. * @param {String} type The name of the event
  46481. * @throws {TypeError} If the `type` argument is not specified
  46482. */
  46483. constructor(type) {
  46484. this[kTarget] = null;
  46485. this[kType] = type;
  46486. }
  46487. /**
  46488. * @type {*}
  46489. */
  46490. get target() {
  46491. return this[kTarget];
  46492. }
  46493. /**
  46494. * @type {String}
  46495. */
  46496. get type() {
  46497. return this[kType];
  46498. }
  46499. }
  46500. Object.defineProperty(Event.prototype, 'target', { enumerable: true });
  46501. Object.defineProperty(Event.prototype, 'type', { enumerable: true });
  46502. /**
  46503. * Class representing a close event.
  46504. *
  46505. * @extends Event
  46506. */
  46507. class CloseEvent extends Event {
  46508. /**
  46509. * Create a new `CloseEvent`.
  46510. *
  46511. * @param {String} type The name of the event
  46512. * @param {Object} [options] A dictionary object that allows for setting
  46513. * attributes via object members of the same name
  46514. * @param {Number} [options.code=0] The status code explaining why the
  46515. * connection was closed
  46516. * @param {String} [options.reason=''] A human-readable string explaining why
  46517. * the connection was closed
  46518. * @param {Boolean} [options.wasClean=false] Indicates whether or not the
  46519. * connection was cleanly closed
  46520. */
  46521. constructor(type, options = {}) {
  46522. super(type);
  46523. this[kCode] = options.code === undefined ? 0 : options.code;
  46524. this[kReason] = options.reason === undefined ? '' : options.reason;
  46525. this[kWasClean] = options.wasClean === undefined ? false : options.wasClean;
  46526. }
  46527. /**
  46528. * @type {Number}
  46529. */
  46530. get code() {
  46531. return this[kCode];
  46532. }
  46533. /**
  46534. * @type {String}
  46535. */
  46536. get reason() {
  46537. return this[kReason];
  46538. }
  46539. /**
  46540. * @type {Boolean}
  46541. */
  46542. get wasClean() {
  46543. return this[kWasClean];
  46544. }
  46545. }
  46546. Object.defineProperty(CloseEvent.prototype, 'code', { enumerable: true });
  46547. Object.defineProperty(CloseEvent.prototype, 'reason', { enumerable: true });
  46548. Object.defineProperty(CloseEvent.prototype, 'wasClean', { enumerable: true });
  46549. /**
  46550. * Class representing an error event.
  46551. *
  46552. * @extends Event
  46553. */
  46554. class ErrorEvent extends Event {
  46555. /**
  46556. * Create a new `ErrorEvent`.
  46557. *
  46558. * @param {String} type The name of the event
  46559. * @param {Object} [options] A dictionary object that allows for setting
  46560. * attributes via object members of the same name
  46561. * @param {*} [options.error=null] The error that generated this event
  46562. * @param {String} [options.message=''] The error message
  46563. */
  46564. constructor(type, options = {}) {
  46565. super(type);
  46566. this[kError] = options.error === undefined ? null : options.error;
  46567. this[kMessage] = options.message === undefined ? '' : options.message;
  46568. }
  46569. /**
  46570. * @type {*}
  46571. */
  46572. get error() {
  46573. return this[kError];
  46574. }
  46575. /**
  46576. * @type {String}
  46577. */
  46578. get message() {
  46579. return this[kMessage];
  46580. }
  46581. }
  46582. Object.defineProperty(ErrorEvent.prototype, 'error', { enumerable: true });
  46583. Object.defineProperty(ErrorEvent.prototype, 'message', { enumerable: true });
  46584. /**
  46585. * Class representing a message event.
  46586. *
  46587. * @extends Event
  46588. */
  46589. class MessageEvent extends Event {
  46590. /**
  46591. * Create a new `MessageEvent`.
  46592. *
  46593. * @param {String} type The name of the event
  46594. * @param {Object} [options] A dictionary object that allows for setting
  46595. * attributes via object members of the same name
  46596. * @param {*} [options.data=null] The message content
  46597. */
  46598. constructor(type, options = {}) {
  46599. super(type);
  46600. this[kData] = options.data === undefined ? null : options.data;
  46601. }
  46602. /**
  46603. * @type {*}
  46604. */
  46605. get data() {
  46606. return this[kData];
  46607. }
  46608. }
  46609. Object.defineProperty(MessageEvent.prototype, 'data', { enumerable: true });
  46610. /**
  46611. * This provides methods for emulating the `EventTarget` interface. It's not
  46612. * meant to be used directly.
  46613. *
  46614. * @mixin
  46615. */
  46616. const EventTarget = {
  46617. /**
  46618. * Register an event listener.
  46619. *
  46620. * @param {String} type A string representing the event type to listen for
  46621. * @param {Function} listener The listener to add
  46622. * @param {Object} [options] An options object specifies characteristics about
  46623. * the event listener
  46624. * @param {Boolean} [options.once=false] A `Boolean` indicating that the
  46625. * listener should be invoked at most once after being added. If `true`,
  46626. * the listener would be automatically removed when invoked.
  46627. * @public
  46628. */
  46629. addEventListener(type, listener, options = {}) {
  46630. let wrapper;
  46631. if (type === 'message') {
  46632. wrapper = function onMessage(data, isBinary) {
  46633. const event = new MessageEvent('message', {
  46634. data: isBinary ? data : data.toString()
  46635. });
  46636. event[kTarget] = this;
  46637. listener.call(this, event);
  46638. };
  46639. } else if (type === 'close') {
  46640. wrapper = function onClose(code, message) {
  46641. const event = new CloseEvent('close', {
  46642. code,
  46643. reason: message.toString(),
  46644. wasClean: this._closeFrameReceived && this._closeFrameSent
  46645. });
  46646. event[kTarget] = this;
  46647. listener.call(this, event);
  46648. };
  46649. } else if (type === 'error') {
  46650. wrapper = function onError(error) {
  46651. const event = new ErrorEvent('error', {
  46652. error,
  46653. message: error.message
  46654. });
  46655. event[kTarget] = this;
  46656. listener.call(this, event);
  46657. };
  46658. } else if (type === 'open') {
  46659. wrapper = function onOpen() {
  46660. const event = new Event('open');
  46661. event[kTarget] = this;
  46662. listener.call(this, event);
  46663. };
  46664. } else {
  46665. return;
  46666. }
  46667. wrapper[kForOnEventAttribute$1] = !!options[kForOnEventAttribute$1];
  46668. wrapper[kListener$1] = listener;
  46669. if (options.once) {
  46670. this.once(type, wrapper);
  46671. } else {
  46672. this.on(type, wrapper);
  46673. }
  46674. },
  46675. /**
  46676. * Remove an event listener.
  46677. *
  46678. * @param {String} type A string representing the event type to remove
  46679. * @param {Function} handler The listener to remove
  46680. * @public
  46681. */
  46682. removeEventListener(type, handler) {
  46683. for (const listener of this.listeners(type)) {
  46684. if (listener[kListener$1] === handler && !listener[kForOnEventAttribute$1]) {
  46685. this.removeListener(type, listener);
  46686. break;
  46687. }
  46688. }
  46689. }
  46690. };
  46691. var eventTarget = {
  46692. CloseEvent,
  46693. ErrorEvent,
  46694. Event,
  46695. EventTarget,
  46696. MessageEvent
  46697. };
  46698. const { tokenChars: tokenChars$1 } = validation.exports;
  46699. /**
  46700. * Adds an offer to the map of extension offers or a parameter to the map of
  46701. * parameters.
  46702. *
  46703. * @param {Object} dest The map of extension offers or parameters
  46704. * @param {String} name The extension or parameter name
  46705. * @param {(Object|Boolean|String)} elem The extension parameters or the
  46706. * parameter value
  46707. * @private
  46708. */
  46709. function push(dest, name, elem) {
  46710. if (dest[name] === undefined) dest[name] = [elem];
  46711. else dest[name].push(elem);
  46712. }
  46713. /**
  46714. * Parses the `Sec-WebSocket-Extensions` header into an object.
  46715. *
  46716. * @param {String} header The field value of the header
  46717. * @return {Object} The parsed object
  46718. * @public
  46719. */
  46720. function parse$4(header) {
  46721. const offers = Object.create(null);
  46722. let params = Object.create(null);
  46723. let mustUnescape = false;
  46724. let isEscaping = false;
  46725. let inQuotes = false;
  46726. let extensionName;
  46727. let paramName;
  46728. let start = -1;
  46729. let code = -1;
  46730. let end = -1;
  46731. let i = 0;
  46732. for (; i < header.length; i++) {
  46733. code = header.charCodeAt(i);
  46734. if (extensionName === undefined) {
  46735. if (end === -1 && tokenChars$1[code] === 1) {
  46736. if (start === -1) start = i;
  46737. } else if (
  46738. i !== 0 &&
  46739. (code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */
  46740. ) {
  46741. if (end === -1 && start !== -1) end = i;
  46742. } else if (code === 0x3b /* ';' */ || code === 0x2c /* ',' */) {
  46743. if (start === -1) {
  46744. throw new SyntaxError(`Unexpected character at index ${i}`);
  46745. }
  46746. if (end === -1) end = i;
  46747. const name = header.slice(start, end);
  46748. if (code === 0x2c) {
  46749. push(offers, name, params);
  46750. params = Object.create(null);
  46751. } else {
  46752. extensionName = name;
  46753. }
  46754. start = end = -1;
  46755. } else {
  46756. throw new SyntaxError(`Unexpected character at index ${i}`);
  46757. }
  46758. } else if (paramName === undefined) {
  46759. if (end === -1 && tokenChars$1[code] === 1) {
  46760. if (start === -1) start = i;
  46761. } else if (code === 0x20 || code === 0x09) {
  46762. if (end === -1 && start !== -1) end = i;
  46763. } else if (code === 0x3b || code === 0x2c) {
  46764. if (start === -1) {
  46765. throw new SyntaxError(`Unexpected character at index ${i}`);
  46766. }
  46767. if (end === -1) end = i;
  46768. push(params, header.slice(start, end), true);
  46769. if (code === 0x2c) {
  46770. push(offers, extensionName, params);
  46771. params = Object.create(null);
  46772. extensionName = undefined;
  46773. }
  46774. start = end = -1;
  46775. } else if (code === 0x3d /* '=' */ && start !== -1 && end === -1) {
  46776. paramName = header.slice(start, i);
  46777. start = end = -1;
  46778. } else {
  46779. throw new SyntaxError(`Unexpected character at index ${i}`);
  46780. }
  46781. } else {
  46782. //
  46783. // The value of a quoted-string after unescaping must conform to the
  46784. // token ABNF, so only token characters are valid.
  46785. // Ref: https://tools.ietf.org/html/rfc6455#section-9.1
  46786. //
  46787. if (isEscaping) {
  46788. if (tokenChars$1[code] !== 1) {
  46789. throw new SyntaxError(`Unexpected character at index ${i}`);
  46790. }
  46791. if (start === -1) start = i;
  46792. else if (!mustUnescape) mustUnescape = true;
  46793. isEscaping = false;
  46794. } else if (inQuotes) {
  46795. if (tokenChars$1[code] === 1) {
  46796. if (start === -1) start = i;
  46797. } else if (code === 0x22 /* '"' */ && start !== -1) {
  46798. inQuotes = false;
  46799. end = i;
  46800. } else if (code === 0x5c /* '\' */) {
  46801. isEscaping = true;
  46802. } else {
  46803. throw new SyntaxError(`Unexpected character at index ${i}`);
  46804. }
  46805. } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) {
  46806. inQuotes = true;
  46807. } else if (end === -1 && tokenChars$1[code] === 1) {
  46808. if (start === -1) start = i;
  46809. } else if (start !== -1 && (code === 0x20 || code === 0x09)) {
  46810. if (end === -1) end = i;
  46811. } else if (code === 0x3b || code === 0x2c) {
  46812. if (start === -1) {
  46813. throw new SyntaxError(`Unexpected character at index ${i}`);
  46814. }
  46815. if (end === -1) end = i;
  46816. let value = header.slice(start, end);
  46817. if (mustUnescape) {
  46818. value = value.replace(/\\/g, '');
  46819. mustUnescape = false;
  46820. }
  46821. push(params, paramName, value);
  46822. if (code === 0x2c) {
  46823. push(offers, extensionName, params);
  46824. params = Object.create(null);
  46825. extensionName = undefined;
  46826. }
  46827. paramName = undefined;
  46828. start = end = -1;
  46829. } else {
  46830. throw new SyntaxError(`Unexpected character at index ${i}`);
  46831. }
  46832. }
  46833. }
  46834. if (start === -1 || inQuotes || code === 0x20 || code === 0x09) {
  46835. throw new SyntaxError('Unexpected end of input');
  46836. }
  46837. if (end === -1) end = i;
  46838. const token = header.slice(start, end);
  46839. if (extensionName === undefined) {
  46840. push(offers, token, params);
  46841. } else {
  46842. if (paramName === undefined) {
  46843. push(params, token, true);
  46844. } else if (mustUnescape) {
  46845. push(params, paramName, token.replace(/\\/g, ''));
  46846. } else {
  46847. push(params, paramName, token);
  46848. }
  46849. push(offers, extensionName, params);
  46850. }
  46851. return offers;
  46852. }
  46853. /**
  46854. * Builds the `Sec-WebSocket-Extensions` header field value.
  46855. *
  46856. * @param {Object} extensions The map of extensions and parameters to format
  46857. * @return {String} A string representing the given object
  46858. * @public
  46859. */
  46860. function format$1(extensions) {
  46861. return Object.keys(extensions)
  46862. .map((extension) => {
  46863. let configurations = extensions[extension];
  46864. if (!Array.isArray(configurations)) configurations = [configurations];
  46865. return configurations
  46866. .map((params) => {
  46867. return [extension]
  46868. .concat(
  46869. Object.keys(params).map((k) => {
  46870. let values = params[k];
  46871. if (!Array.isArray(values)) values = [values];
  46872. return values
  46873. .map((v) => (v === true ? k : `${k}=${v}`))
  46874. .join('; ');
  46875. })
  46876. )
  46877. .join('; ');
  46878. })
  46879. .join(', ');
  46880. })
  46881. .join(', ');
  46882. }
  46883. var extension$1 = { format: format$1, parse: parse$4 };
  46884. /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Readable$" }] */
  46885. const EventEmitter$1 = require$$0__default$1;
  46886. const https$2 = require$$1__default$3;
  46887. const http$3 = require$$1__default$1;
  46888. const net = require$$3__default;
  46889. const tls = require$$4__default;
  46890. const { randomBytes, createHash: createHash$1 } = require$$1__default$2;
  46891. const { URL: URL$2 } = require$$0__default$5;
  46892. const PerMessageDeflate$1 = permessageDeflate;
  46893. const Receiver = receiver;
  46894. const Sender = sender;
  46895. const {
  46896. BINARY_TYPES,
  46897. EMPTY_BUFFER,
  46898. GUID: GUID$1,
  46899. kForOnEventAttribute,
  46900. kListener,
  46901. kStatusCode,
  46902. kWebSocket: kWebSocket$1,
  46903. NOOP
  46904. } = constants;
  46905. const {
  46906. EventTarget: { addEventListener, removeEventListener }
  46907. } = eventTarget;
  46908. const { format, parse: parse$3 } = extension$1;
  46909. const { toBuffer } = bufferUtil$1.exports;
  46910. const closeTimeout = 30 * 1000;
  46911. const kAborted = Symbol('kAborted');
  46912. const protocolVersions = [8, 13];
  46913. const readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'];
  46914. const subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
  46915. /**
  46916. * Class representing a WebSocket.
  46917. *
  46918. * @extends EventEmitter
  46919. */
  46920. class WebSocket$1 extends EventEmitter$1 {
  46921. /**
  46922. * Create a new `WebSocket`.
  46923. *
  46924. * @param {(String|URL)} address The URL to which to connect
  46925. * @param {(String|String[])} [protocols] The subprotocols
  46926. * @param {Object} [options] Connection options
  46927. */
  46928. constructor(address, protocols, options) {
  46929. super();
  46930. this._binaryType = BINARY_TYPES[0];
  46931. this._closeCode = 1006;
  46932. this._closeFrameReceived = false;
  46933. this._closeFrameSent = false;
  46934. this._closeMessage = EMPTY_BUFFER;
  46935. this._closeTimer = null;
  46936. this._extensions = {};
  46937. this._paused = false;
  46938. this._protocol = '';
  46939. this._readyState = WebSocket$1.CONNECTING;
  46940. this._receiver = null;
  46941. this._sender = null;
  46942. this._socket = null;
  46943. if (address !== null) {
  46944. this._bufferedAmount = 0;
  46945. this._isServer = false;
  46946. this._redirects = 0;
  46947. if (protocols === undefined) {
  46948. protocols = [];
  46949. } else if (!Array.isArray(protocols)) {
  46950. if (typeof protocols === 'object' && protocols !== null) {
  46951. options = protocols;
  46952. protocols = [];
  46953. } else {
  46954. protocols = [protocols];
  46955. }
  46956. }
  46957. initAsClient(this, address, protocols, options);
  46958. } else {
  46959. this._isServer = true;
  46960. }
  46961. }
  46962. /**
  46963. * This deviates from the WHATWG interface since ws doesn't support the
  46964. * required default "blob" type (instead we define a custom "nodebuffer"
  46965. * type).
  46966. *
  46967. * @type {String}
  46968. */
  46969. get binaryType() {
  46970. return this._binaryType;
  46971. }
  46972. set binaryType(type) {
  46973. if (!BINARY_TYPES.includes(type)) return;
  46974. this._binaryType = type;
  46975. //
  46976. // Allow to change `binaryType` on the fly.
  46977. //
  46978. if (this._receiver) this._receiver._binaryType = type;
  46979. }
  46980. /**
  46981. * @type {Number}
  46982. */
  46983. get bufferedAmount() {
  46984. if (!this._socket) return this._bufferedAmount;
  46985. return this._socket._writableState.length + this._sender._bufferedBytes;
  46986. }
  46987. /**
  46988. * @type {String}
  46989. */
  46990. get extensions() {
  46991. return Object.keys(this._extensions).join();
  46992. }
  46993. /**
  46994. * @type {Boolean}
  46995. */
  46996. get isPaused() {
  46997. return this._paused;
  46998. }
  46999. /**
  47000. * @type {Function}
  47001. */
  47002. /* istanbul ignore next */
  47003. get onclose() {
  47004. return null;
  47005. }
  47006. /**
  47007. * @type {Function}
  47008. */
  47009. /* istanbul ignore next */
  47010. get onerror() {
  47011. return null;
  47012. }
  47013. /**
  47014. * @type {Function}
  47015. */
  47016. /* istanbul ignore next */
  47017. get onopen() {
  47018. return null;
  47019. }
  47020. /**
  47021. * @type {Function}
  47022. */
  47023. /* istanbul ignore next */
  47024. get onmessage() {
  47025. return null;
  47026. }
  47027. /**
  47028. * @type {String}
  47029. */
  47030. get protocol() {
  47031. return this._protocol;
  47032. }
  47033. /**
  47034. * @type {Number}
  47035. */
  47036. get readyState() {
  47037. return this._readyState;
  47038. }
  47039. /**
  47040. * @type {String}
  47041. */
  47042. get url() {
  47043. return this._url;
  47044. }
  47045. /**
  47046. * Set up the socket and the internal resources.
  47047. *
  47048. * @param {(net.Socket|tls.Socket)} socket The network socket between the
  47049. * server and client
  47050. * @param {Buffer} head The first packet of the upgraded stream
  47051. * @param {Object} options Options object
  47052. * @param {Function} [options.generateMask] The function used to generate the
  47053. * masking key
  47054. * @param {Number} [options.maxPayload=0] The maximum allowed message size
  47055. * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
  47056. * not to skip UTF-8 validation for text and close messages
  47057. * @private
  47058. */
  47059. setSocket(socket, head, options) {
  47060. const receiver = new Receiver({
  47061. binaryType: this.binaryType,
  47062. extensions: this._extensions,
  47063. isServer: this._isServer,
  47064. maxPayload: options.maxPayload,
  47065. skipUTF8Validation: options.skipUTF8Validation
  47066. });
  47067. this._sender = new Sender(socket, this._extensions, options.generateMask);
  47068. this._receiver = receiver;
  47069. this._socket = socket;
  47070. receiver[kWebSocket$1] = this;
  47071. socket[kWebSocket$1] = this;
  47072. receiver.on('conclude', receiverOnConclude);
  47073. receiver.on('drain', receiverOnDrain);
  47074. receiver.on('error', receiverOnError);
  47075. receiver.on('message', receiverOnMessage);
  47076. receiver.on('ping', receiverOnPing);
  47077. receiver.on('pong', receiverOnPong);
  47078. socket.setTimeout(0);
  47079. socket.setNoDelay();
  47080. if (head.length > 0) socket.unshift(head);
  47081. socket.on('close', socketOnClose);
  47082. socket.on('data', socketOnData);
  47083. socket.on('end', socketOnEnd);
  47084. socket.on('error', socketOnError$1);
  47085. this._readyState = WebSocket$1.OPEN;
  47086. this.emit('open');
  47087. }
  47088. /**
  47089. * Emit the `'close'` event.
  47090. *
  47091. * @private
  47092. */
  47093. emitClose() {
  47094. if (!this._socket) {
  47095. this._readyState = WebSocket$1.CLOSED;
  47096. this.emit('close', this._closeCode, this._closeMessage);
  47097. return;
  47098. }
  47099. if (this._extensions[PerMessageDeflate$1.extensionName]) {
  47100. this._extensions[PerMessageDeflate$1.extensionName].cleanup();
  47101. }
  47102. this._receiver.removeAllListeners();
  47103. this._readyState = WebSocket$1.CLOSED;
  47104. this.emit('close', this._closeCode, this._closeMessage);
  47105. }
  47106. /**
  47107. * Start a closing handshake.
  47108. *
  47109. * +----------+ +-----------+ +----------+
  47110. * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
  47111. * | +----------+ +-----------+ +----------+ |
  47112. * +----------+ +-----------+ |
  47113. * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
  47114. * +----------+ +-----------+ |
  47115. * | | | +---+ |
  47116. * +------------------------+-->|fin| - - - -
  47117. * | +---+ | +---+
  47118. * - - - - -|fin|<---------------------+
  47119. * +---+
  47120. *
  47121. * @param {Number} [code] Status code explaining why the connection is closing
  47122. * @param {(String|Buffer)} [data] The reason why the connection is
  47123. * closing
  47124. * @public
  47125. */
  47126. close(code, data) {
  47127. if (this.readyState === WebSocket$1.CLOSED) return;
  47128. if (this.readyState === WebSocket$1.CONNECTING) {
  47129. const msg = 'WebSocket was closed before the connection was established';
  47130. return abortHandshake$1(this, this._req, msg);
  47131. }
  47132. if (this.readyState === WebSocket$1.CLOSING) {
  47133. if (
  47134. this._closeFrameSent &&
  47135. (this._closeFrameReceived || this._receiver._writableState.errorEmitted)
  47136. ) {
  47137. this._socket.end();
  47138. }
  47139. return;
  47140. }
  47141. this._readyState = WebSocket$1.CLOSING;
  47142. this._sender.close(code, data, !this._isServer, (err) => {
  47143. //
  47144. // This error is handled by the `'error'` listener on the socket. We only
  47145. // want to know if the close frame has been sent here.
  47146. //
  47147. if (err) return;
  47148. this._closeFrameSent = true;
  47149. if (
  47150. this._closeFrameReceived ||
  47151. this._receiver._writableState.errorEmitted
  47152. ) {
  47153. this._socket.end();
  47154. }
  47155. });
  47156. //
  47157. // Specify a timeout for the closing handshake to complete.
  47158. //
  47159. this._closeTimer = setTimeout(
  47160. this._socket.destroy.bind(this._socket),
  47161. closeTimeout
  47162. );
  47163. }
  47164. /**
  47165. * Pause the socket.
  47166. *
  47167. * @public
  47168. */
  47169. pause() {
  47170. if (
  47171. this.readyState === WebSocket$1.CONNECTING ||
  47172. this.readyState === WebSocket$1.CLOSED
  47173. ) {
  47174. return;
  47175. }
  47176. this._paused = true;
  47177. this._socket.pause();
  47178. }
  47179. /**
  47180. * Send a ping.
  47181. *
  47182. * @param {*} [data] The data to send
  47183. * @param {Boolean} [mask] Indicates whether or not to mask `data`
  47184. * @param {Function} [cb] Callback which is executed when the ping is sent
  47185. * @public
  47186. */
  47187. ping(data, mask, cb) {
  47188. if (this.readyState === WebSocket$1.CONNECTING) {
  47189. throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
  47190. }
  47191. if (typeof data === 'function') {
  47192. cb = data;
  47193. data = mask = undefined;
  47194. } else if (typeof mask === 'function') {
  47195. cb = mask;
  47196. mask = undefined;
  47197. }
  47198. if (typeof data === 'number') data = data.toString();
  47199. if (this.readyState !== WebSocket$1.OPEN) {
  47200. sendAfterClose(this, data, cb);
  47201. return;
  47202. }
  47203. if (mask === undefined) mask = !this._isServer;
  47204. this._sender.ping(data || EMPTY_BUFFER, mask, cb);
  47205. }
  47206. /**
  47207. * Send a pong.
  47208. *
  47209. * @param {*} [data] The data to send
  47210. * @param {Boolean} [mask] Indicates whether or not to mask `data`
  47211. * @param {Function} [cb] Callback which is executed when the pong is sent
  47212. * @public
  47213. */
  47214. pong(data, mask, cb) {
  47215. if (this.readyState === WebSocket$1.CONNECTING) {
  47216. throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
  47217. }
  47218. if (typeof data === 'function') {
  47219. cb = data;
  47220. data = mask = undefined;
  47221. } else if (typeof mask === 'function') {
  47222. cb = mask;
  47223. mask = undefined;
  47224. }
  47225. if (typeof data === 'number') data = data.toString();
  47226. if (this.readyState !== WebSocket$1.OPEN) {
  47227. sendAfterClose(this, data, cb);
  47228. return;
  47229. }
  47230. if (mask === undefined) mask = !this._isServer;
  47231. this._sender.pong(data || EMPTY_BUFFER, mask, cb);
  47232. }
  47233. /**
  47234. * Resume the socket.
  47235. *
  47236. * @public
  47237. */
  47238. resume() {
  47239. if (
  47240. this.readyState === WebSocket$1.CONNECTING ||
  47241. this.readyState === WebSocket$1.CLOSED
  47242. ) {
  47243. return;
  47244. }
  47245. this._paused = false;
  47246. if (!this._receiver._writableState.needDrain) this._socket.resume();
  47247. }
  47248. /**
  47249. * Send a data message.
  47250. *
  47251. * @param {*} data The message to send
  47252. * @param {Object} [options] Options object
  47253. * @param {Boolean} [options.binary] Specifies whether `data` is binary or
  47254. * text
  47255. * @param {Boolean} [options.compress] Specifies whether or not to compress
  47256. * `data`
  47257. * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
  47258. * last one
  47259. * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
  47260. * @param {Function} [cb] Callback which is executed when data is written out
  47261. * @public
  47262. */
  47263. send(data, options, cb) {
  47264. if (this.readyState === WebSocket$1.CONNECTING) {
  47265. throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
  47266. }
  47267. if (typeof options === 'function') {
  47268. cb = options;
  47269. options = {};
  47270. }
  47271. if (typeof data === 'number') data = data.toString();
  47272. if (this.readyState !== WebSocket$1.OPEN) {
  47273. sendAfterClose(this, data, cb);
  47274. return;
  47275. }
  47276. const opts = {
  47277. binary: typeof data !== 'string',
  47278. mask: !this._isServer,
  47279. compress: true,
  47280. fin: true,
  47281. ...options
  47282. };
  47283. if (!this._extensions[PerMessageDeflate$1.extensionName]) {
  47284. opts.compress = false;
  47285. }
  47286. this._sender.send(data || EMPTY_BUFFER, opts, cb);
  47287. }
  47288. /**
  47289. * Forcibly close the connection.
  47290. *
  47291. * @public
  47292. */
  47293. terminate() {
  47294. if (this.readyState === WebSocket$1.CLOSED) return;
  47295. if (this.readyState === WebSocket$1.CONNECTING) {
  47296. const msg = 'WebSocket was closed before the connection was established';
  47297. return abortHandshake$1(this, this._req, msg);
  47298. }
  47299. if (this._socket) {
  47300. this._readyState = WebSocket$1.CLOSING;
  47301. this._socket.destroy();
  47302. }
  47303. }
  47304. }
  47305. /**
  47306. * @constant {Number} CONNECTING
  47307. * @memberof WebSocket
  47308. */
  47309. Object.defineProperty(WebSocket$1, 'CONNECTING', {
  47310. enumerable: true,
  47311. value: readyStates.indexOf('CONNECTING')
  47312. });
  47313. /**
  47314. * @constant {Number} CONNECTING
  47315. * @memberof WebSocket.prototype
  47316. */
  47317. Object.defineProperty(WebSocket$1.prototype, 'CONNECTING', {
  47318. enumerable: true,
  47319. value: readyStates.indexOf('CONNECTING')
  47320. });
  47321. /**
  47322. * @constant {Number} OPEN
  47323. * @memberof WebSocket
  47324. */
  47325. Object.defineProperty(WebSocket$1, 'OPEN', {
  47326. enumerable: true,
  47327. value: readyStates.indexOf('OPEN')
  47328. });
  47329. /**
  47330. * @constant {Number} OPEN
  47331. * @memberof WebSocket.prototype
  47332. */
  47333. Object.defineProperty(WebSocket$1.prototype, 'OPEN', {
  47334. enumerable: true,
  47335. value: readyStates.indexOf('OPEN')
  47336. });
  47337. /**
  47338. * @constant {Number} CLOSING
  47339. * @memberof WebSocket
  47340. */
  47341. Object.defineProperty(WebSocket$1, 'CLOSING', {
  47342. enumerable: true,
  47343. value: readyStates.indexOf('CLOSING')
  47344. });
  47345. /**
  47346. * @constant {Number} CLOSING
  47347. * @memberof WebSocket.prototype
  47348. */
  47349. Object.defineProperty(WebSocket$1.prototype, 'CLOSING', {
  47350. enumerable: true,
  47351. value: readyStates.indexOf('CLOSING')
  47352. });
  47353. /**
  47354. * @constant {Number} CLOSED
  47355. * @memberof WebSocket
  47356. */
  47357. Object.defineProperty(WebSocket$1, 'CLOSED', {
  47358. enumerable: true,
  47359. value: readyStates.indexOf('CLOSED')
  47360. });
  47361. /**
  47362. * @constant {Number} CLOSED
  47363. * @memberof WebSocket.prototype
  47364. */
  47365. Object.defineProperty(WebSocket$1.prototype, 'CLOSED', {
  47366. enumerable: true,
  47367. value: readyStates.indexOf('CLOSED')
  47368. });
  47369. [
  47370. 'binaryType',
  47371. 'bufferedAmount',
  47372. 'extensions',
  47373. 'isPaused',
  47374. 'protocol',
  47375. 'readyState',
  47376. 'url'
  47377. ].forEach((property) => {
  47378. Object.defineProperty(WebSocket$1.prototype, property, { enumerable: true });
  47379. });
  47380. //
  47381. // Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes.
  47382. // See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface
  47383. //
  47384. ['open', 'error', 'close', 'message'].forEach((method) => {
  47385. Object.defineProperty(WebSocket$1.prototype, `on${method}`, {
  47386. enumerable: true,
  47387. get() {
  47388. for (const listener of this.listeners(method)) {
  47389. if (listener[kForOnEventAttribute]) return listener[kListener];
  47390. }
  47391. return null;
  47392. },
  47393. set(handler) {
  47394. for (const listener of this.listeners(method)) {
  47395. if (listener[kForOnEventAttribute]) {
  47396. this.removeListener(method, listener);
  47397. break;
  47398. }
  47399. }
  47400. if (typeof handler !== 'function') return;
  47401. this.addEventListener(method, handler, {
  47402. [kForOnEventAttribute]: true
  47403. });
  47404. }
  47405. });
  47406. });
  47407. WebSocket$1.prototype.addEventListener = addEventListener;
  47408. WebSocket$1.prototype.removeEventListener = removeEventListener;
  47409. var websocket = WebSocket$1;
  47410. /**
  47411. * Initialize a WebSocket client.
  47412. *
  47413. * @param {WebSocket} websocket The client to initialize
  47414. * @param {(String|URL)} address The URL to which to connect
  47415. * @param {Array} protocols The subprotocols
  47416. * @param {Object} [options] Connection options
  47417. * @param {Boolean} [options.followRedirects=false] Whether or not to follow
  47418. * redirects
  47419. * @param {Function} [options.generateMask] The function used to generate the
  47420. * masking key
  47421. * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the
  47422. * handshake request
  47423. * @param {Number} [options.maxPayload=104857600] The maximum allowed message
  47424. * size
  47425. * @param {Number} [options.maxRedirects=10] The maximum number of redirects
  47426. * allowed
  47427. * @param {String} [options.origin] Value of the `Origin` or
  47428. * `Sec-WebSocket-Origin` header
  47429. * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable
  47430. * permessage-deflate
  47431. * @param {Number} [options.protocolVersion=13] Value of the
  47432. * `Sec-WebSocket-Version` header
  47433. * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
  47434. * not to skip UTF-8 validation for text and close messages
  47435. * @private
  47436. */
  47437. function initAsClient(websocket, address, protocols, options) {
  47438. const opts = {
  47439. protocolVersion: protocolVersions[1],
  47440. maxPayload: 100 * 1024 * 1024,
  47441. skipUTF8Validation: false,
  47442. perMessageDeflate: true,
  47443. followRedirects: false,
  47444. maxRedirects: 10,
  47445. ...options,
  47446. createConnection: undefined,
  47447. socketPath: undefined,
  47448. hostname: undefined,
  47449. protocol: undefined,
  47450. timeout: undefined,
  47451. method: 'GET',
  47452. host: undefined,
  47453. path: undefined,
  47454. port: undefined
  47455. };
  47456. if (!protocolVersions.includes(opts.protocolVersion)) {
  47457. throw new RangeError(
  47458. `Unsupported protocol version: ${opts.protocolVersion} ` +
  47459. `(supported versions: ${protocolVersions.join(', ')})`
  47460. );
  47461. }
  47462. let parsedUrl;
  47463. if (address instanceof URL$2) {
  47464. parsedUrl = address;
  47465. websocket._url = address.href;
  47466. } else {
  47467. try {
  47468. parsedUrl = new URL$2(address);
  47469. } catch (e) {
  47470. throw new SyntaxError(`Invalid URL: ${address}`);
  47471. }
  47472. websocket._url = address;
  47473. }
  47474. const isSecure = parsedUrl.protocol === 'wss:';
  47475. const isUnixSocket = parsedUrl.protocol === 'ws+unix:';
  47476. let invalidURLMessage;
  47477. if (parsedUrl.protocol !== 'ws:' && !isSecure && !isUnixSocket) {
  47478. invalidURLMessage =
  47479. 'The URL\'s protocol must be one of "ws:", "wss:", or "ws+unix:"';
  47480. } else if (isUnixSocket && !parsedUrl.pathname) {
  47481. invalidURLMessage = "The URL's pathname is empty";
  47482. } else if (parsedUrl.hash) {
  47483. invalidURLMessage = 'The URL contains a fragment identifier';
  47484. }
  47485. if (invalidURLMessage) {
  47486. const err = new SyntaxError(invalidURLMessage);
  47487. if (websocket._redirects === 0) {
  47488. throw err;
  47489. } else {
  47490. emitErrorAndClose(websocket, err);
  47491. return;
  47492. }
  47493. }
  47494. const defaultPort = isSecure ? 443 : 80;
  47495. const key = randomBytes(16).toString('base64');
  47496. const request = isSecure ? https$2.request : http$3.request;
  47497. const protocolSet = new Set();
  47498. let perMessageDeflate;
  47499. opts.createConnection = isSecure ? tlsConnect : netConnect;
  47500. opts.defaultPort = opts.defaultPort || defaultPort;
  47501. opts.port = parsedUrl.port || defaultPort;
  47502. opts.host = parsedUrl.hostname.startsWith('[')
  47503. ? parsedUrl.hostname.slice(1, -1)
  47504. : parsedUrl.hostname;
  47505. opts.headers = {
  47506. 'Sec-WebSocket-Version': opts.protocolVersion,
  47507. 'Sec-WebSocket-Key': key,
  47508. Connection: 'Upgrade',
  47509. Upgrade: 'websocket',
  47510. ...opts.headers
  47511. };
  47512. opts.path = parsedUrl.pathname + parsedUrl.search;
  47513. opts.timeout = opts.handshakeTimeout;
  47514. if (opts.perMessageDeflate) {
  47515. perMessageDeflate = new PerMessageDeflate$1(
  47516. opts.perMessageDeflate !== true ? opts.perMessageDeflate : {},
  47517. false,
  47518. opts.maxPayload
  47519. );
  47520. opts.headers['Sec-WebSocket-Extensions'] = format({
  47521. [PerMessageDeflate$1.extensionName]: perMessageDeflate.offer()
  47522. });
  47523. }
  47524. if (protocols.length) {
  47525. for (const protocol of protocols) {
  47526. if (
  47527. typeof protocol !== 'string' ||
  47528. !subprotocolRegex.test(protocol) ||
  47529. protocolSet.has(protocol)
  47530. ) {
  47531. throw new SyntaxError(
  47532. 'An invalid or duplicated subprotocol was specified'
  47533. );
  47534. }
  47535. protocolSet.add(protocol);
  47536. }
  47537. opts.headers['Sec-WebSocket-Protocol'] = protocols.join(',');
  47538. }
  47539. if (opts.origin) {
  47540. if (opts.protocolVersion < 13) {
  47541. opts.headers['Sec-WebSocket-Origin'] = opts.origin;
  47542. } else {
  47543. opts.headers.Origin = opts.origin;
  47544. }
  47545. }
  47546. if (parsedUrl.username || parsedUrl.password) {
  47547. opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
  47548. }
  47549. if (isUnixSocket) {
  47550. const parts = opts.path.split(':');
  47551. opts.socketPath = parts[0];
  47552. opts.path = parts[1];
  47553. }
  47554. let req;
  47555. if (opts.followRedirects) {
  47556. if (websocket._redirects === 0) {
  47557. websocket._originalHost = parsedUrl.host;
  47558. const headers = options && options.headers;
  47559. //
  47560. // Shallow copy the user provided options so that headers can be changed
  47561. // without mutating the original object.
  47562. //
  47563. options = { ...options, headers: {} };
  47564. if (headers) {
  47565. for (const [key, value] of Object.entries(headers)) {
  47566. options.headers[key.toLowerCase()] = value;
  47567. }
  47568. }
  47569. } else if (
  47570. websocket.listenerCount('redirect') === 0 &&
  47571. parsedUrl.host !== websocket._originalHost
  47572. ) {
  47573. //
  47574. // Match curl 7.77.0 behavior and drop the following headers. These
  47575. // headers are also dropped when following a redirect to a subdomain.
  47576. //
  47577. delete opts.headers.authorization;
  47578. delete opts.headers.cookie;
  47579. delete opts.headers.host;
  47580. opts.auth = undefined;
  47581. }
  47582. //
  47583. // Match curl 7.77.0 behavior and make the first `Authorization` header win.
  47584. // If the `Authorization` header is set, then there is nothing to do as it
  47585. // will take precedence.
  47586. //
  47587. if (opts.auth && !options.headers.authorization) {
  47588. options.headers.authorization =
  47589. 'Basic ' + Buffer.from(opts.auth).toString('base64');
  47590. }
  47591. req = websocket._req = request(opts);
  47592. if (websocket._redirects) {
  47593. //
  47594. // Unlike what is done for the `'upgrade'` event, no early exit is
  47595. // triggered here if the user calls `websocket.close()` or
  47596. // `websocket.terminate()` from a listener of the `'redirect'` event. This
  47597. // is because the user can also call `request.destroy()` with an error
  47598. // before calling `websocket.close()` or `websocket.terminate()` and this
  47599. // would result in an error being emitted on the `request` object with no
  47600. // `'error'` event listeners attached.
  47601. //
  47602. websocket.emit('redirect', websocket.url, req);
  47603. }
  47604. } else {
  47605. req = websocket._req = request(opts);
  47606. }
  47607. if (opts.timeout) {
  47608. req.on('timeout', () => {
  47609. abortHandshake$1(websocket, req, 'Opening handshake has timed out');
  47610. });
  47611. }
  47612. req.on('error', (err) => {
  47613. if (req === null || req[kAborted]) return;
  47614. req = websocket._req = null;
  47615. emitErrorAndClose(websocket, err);
  47616. });
  47617. req.on('response', (res) => {
  47618. const location = res.headers.location;
  47619. const statusCode = res.statusCode;
  47620. if (
  47621. location &&
  47622. opts.followRedirects &&
  47623. statusCode >= 300 &&
  47624. statusCode < 400
  47625. ) {
  47626. if (++websocket._redirects > opts.maxRedirects) {
  47627. abortHandshake$1(websocket, req, 'Maximum redirects exceeded');
  47628. return;
  47629. }
  47630. req.abort();
  47631. let addr;
  47632. try {
  47633. addr = new URL$2(location, address);
  47634. } catch (e) {
  47635. const err = new SyntaxError(`Invalid URL: ${location}`);
  47636. emitErrorAndClose(websocket, err);
  47637. return;
  47638. }
  47639. initAsClient(websocket, addr, protocols, options);
  47640. } else if (!websocket.emit('unexpected-response', req, res)) {
  47641. abortHandshake$1(
  47642. websocket,
  47643. req,
  47644. `Unexpected server response: ${res.statusCode}`
  47645. );
  47646. }
  47647. });
  47648. req.on('upgrade', (res, socket, head) => {
  47649. websocket.emit('upgrade', res);
  47650. //
  47651. // The user may have closed the connection from a listener of the
  47652. // `'upgrade'` event.
  47653. //
  47654. if (websocket.readyState !== WebSocket$1.CONNECTING) return;
  47655. req = websocket._req = null;
  47656. const digest = createHash$1('sha1')
  47657. .update(key + GUID$1)
  47658. .digest('base64');
  47659. if (res.headers['sec-websocket-accept'] !== digest) {
  47660. abortHandshake$1(websocket, socket, 'Invalid Sec-WebSocket-Accept header');
  47661. return;
  47662. }
  47663. const serverProt = res.headers['sec-websocket-protocol'];
  47664. let protError;
  47665. if (serverProt !== undefined) {
  47666. if (!protocolSet.size) {
  47667. protError = 'Server sent a subprotocol but none was requested';
  47668. } else if (!protocolSet.has(serverProt)) {
  47669. protError = 'Server sent an invalid subprotocol';
  47670. }
  47671. } else if (protocolSet.size) {
  47672. protError = 'Server sent no subprotocol';
  47673. }
  47674. if (protError) {
  47675. abortHandshake$1(websocket, socket, protError);
  47676. return;
  47677. }
  47678. if (serverProt) websocket._protocol = serverProt;
  47679. const secWebSocketExtensions = res.headers['sec-websocket-extensions'];
  47680. if (secWebSocketExtensions !== undefined) {
  47681. if (!perMessageDeflate) {
  47682. const message =
  47683. 'Server sent a Sec-WebSocket-Extensions header but no extension ' +
  47684. 'was requested';
  47685. abortHandshake$1(websocket, socket, message);
  47686. return;
  47687. }
  47688. let extensions;
  47689. try {
  47690. extensions = parse$3(secWebSocketExtensions);
  47691. } catch (err) {
  47692. const message = 'Invalid Sec-WebSocket-Extensions header';
  47693. abortHandshake$1(websocket, socket, message);
  47694. return;
  47695. }
  47696. const extensionNames = Object.keys(extensions);
  47697. if (
  47698. extensionNames.length !== 1 ||
  47699. extensionNames[0] !== PerMessageDeflate$1.extensionName
  47700. ) {
  47701. const message = 'Server indicated an extension that was not requested';
  47702. abortHandshake$1(websocket, socket, message);
  47703. return;
  47704. }
  47705. try {
  47706. perMessageDeflate.accept(extensions[PerMessageDeflate$1.extensionName]);
  47707. } catch (err) {
  47708. const message = 'Invalid Sec-WebSocket-Extensions header';
  47709. abortHandshake$1(websocket, socket, message);
  47710. return;
  47711. }
  47712. websocket._extensions[PerMessageDeflate$1.extensionName] =
  47713. perMessageDeflate;
  47714. }
  47715. websocket.setSocket(socket, head, {
  47716. generateMask: opts.generateMask,
  47717. maxPayload: opts.maxPayload,
  47718. skipUTF8Validation: opts.skipUTF8Validation
  47719. });
  47720. });
  47721. req.end();
  47722. }
  47723. /**
  47724. * Emit the `'error'` and `'close'` events.
  47725. *
  47726. * @param {WebSocket} websocket The WebSocket instance
  47727. * @param {Error} The error to emit
  47728. * @private
  47729. */
  47730. function emitErrorAndClose(websocket, err) {
  47731. websocket._readyState = WebSocket$1.CLOSING;
  47732. websocket.emit('error', err);
  47733. websocket.emitClose();
  47734. }
  47735. /**
  47736. * Create a `net.Socket` and initiate a connection.
  47737. *
  47738. * @param {Object} options Connection options
  47739. * @return {net.Socket} The newly created socket used to start the connection
  47740. * @private
  47741. */
  47742. function netConnect(options) {
  47743. options.path = options.socketPath;
  47744. return net.connect(options);
  47745. }
  47746. /**
  47747. * Create a `tls.TLSSocket` and initiate a connection.
  47748. *
  47749. * @param {Object} options Connection options
  47750. * @return {tls.TLSSocket} The newly created socket used to start the connection
  47751. * @private
  47752. */
  47753. function tlsConnect(options) {
  47754. options.path = undefined;
  47755. if (!options.servername && options.servername !== '') {
  47756. options.servername = net.isIP(options.host) ? '' : options.host;
  47757. }
  47758. return tls.connect(options);
  47759. }
  47760. /**
  47761. * Abort the handshake and emit an error.
  47762. *
  47763. * @param {WebSocket} websocket The WebSocket instance
  47764. * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to
  47765. * abort or the socket to destroy
  47766. * @param {String} message The error message
  47767. * @private
  47768. */
  47769. function abortHandshake$1(websocket, stream, message) {
  47770. websocket._readyState = WebSocket$1.CLOSING;
  47771. const err = new Error(message);
  47772. Error.captureStackTrace(err, abortHandshake$1);
  47773. if (stream.setHeader) {
  47774. stream[kAborted] = true;
  47775. stream.abort();
  47776. if (stream.socket && !stream.socket.destroyed) {
  47777. //
  47778. // On Node.js >= 14.3.0 `request.abort()` does not destroy the socket if
  47779. // called after the request completed. See
  47780. // https://github.com/websockets/ws/issues/1869.
  47781. //
  47782. stream.socket.destroy();
  47783. }
  47784. process.nextTick(emitErrorAndClose, websocket, err);
  47785. } else {
  47786. stream.destroy(err);
  47787. stream.once('error', websocket.emit.bind(websocket, 'error'));
  47788. stream.once('close', websocket.emitClose.bind(websocket));
  47789. }
  47790. }
  47791. /**
  47792. * Handle cases where the `ping()`, `pong()`, or `send()` methods are called
  47793. * when the `readyState` attribute is `CLOSING` or `CLOSED`.
  47794. *
  47795. * @param {WebSocket} websocket The WebSocket instance
  47796. * @param {*} [data] The data to send
  47797. * @param {Function} [cb] Callback
  47798. * @private
  47799. */
  47800. function sendAfterClose(websocket, data, cb) {
  47801. if (data) {
  47802. const length = toBuffer(data).length;
  47803. //
  47804. // The `_bufferedAmount` property is used only when the peer is a client and
  47805. // the opening handshake fails. Under these circumstances, in fact, the
  47806. // `setSocket()` method is not called, so the `_socket` and `_sender`
  47807. // properties are set to `null`.
  47808. //
  47809. if (websocket._socket) websocket._sender._bufferedBytes += length;
  47810. else websocket._bufferedAmount += length;
  47811. }
  47812. if (cb) {
  47813. const err = new Error(
  47814. `WebSocket is not open: readyState ${websocket.readyState} ` +
  47815. `(${readyStates[websocket.readyState]})`
  47816. );
  47817. cb(err);
  47818. }
  47819. }
  47820. /**
  47821. * The listener of the `Receiver` `'conclude'` event.
  47822. *
  47823. * @param {Number} code The status code
  47824. * @param {Buffer} reason The reason for closing
  47825. * @private
  47826. */
  47827. function receiverOnConclude(code, reason) {
  47828. const websocket = this[kWebSocket$1];
  47829. websocket._closeFrameReceived = true;
  47830. websocket._closeMessage = reason;
  47831. websocket._closeCode = code;
  47832. if (websocket._socket[kWebSocket$1] === undefined) return;
  47833. websocket._socket.removeListener('data', socketOnData);
  47834. process.nextTick(resume, websocket._socket);
  47835. if (code === 1005) websocket.close();
  47836. else websocket.close(code, reason);
  47837. }
  47838. /**
  47839. * The listener of the `Receiver` `'drain'` event.
  47840. *
  47841. * @private
  47842. */
  47843. function receiverOnDrain() {
  47844. const websocket = this[kWebSocket$1];
  47845. if (!websocket.isPaused) websocket._socket.resume();
  47846. }
  47847. /**
  47848. * The listener of the `Receiver` `'error'` event.
  47849. *
  47850. * @param {(RangeError|Error)} err The emitted error
  47851. * @private
  47852. */
  47853. function receiverOnError(err) {
  47854. const websocket = this[kWebSocket$1];
  47855. if (websocket._socket[kWebSocket$1] !== undefined) {
  47856. websocket._socket.removeListener('data', socketOnData);
  47857. //
  47858. // On Node.js < 14.0.0 the `'error'` event is emitted synchronously. See
  47859. // https://github.com/websockets/ws/issues/1940.
  47860. //
  47861. process.nextTick(resume, websocket._socket);
  47862. websocket.close(err[kStatusCode]);
  47863. }
  47864. websocket.emit('error', err);
  47865. }
  47866. /**
  47867. * The listener of the `Receiver` `'finish'` event.
  47868. *
  47869. * @private
  47870. */
  47871. function receiverOnFinish() {
  47872. this[kWebSocket$1].emitClose();
  47873. }
  47874. /**
  47875. * The listener of the `Receiver` `'message'` event.
  47876. *
  47877. * @param {Buffer|ArrayBuffer|Buffer[])} data The message
  47878. * @param {Boolean} isBinary Specifies whether the message is binary or not
  47879. * @private
  47880. */
  47881. function receiverOnMessage(data, isBinary) {
  47882. this[kWebSocket$1].emit('message', data, isBinary);
  47883. }
  47884. /**
  47885. * The listener of the `Receiver` `'ping'` event.
  47886. *
  47887. * @param {Buffer} data The data included in the ping frame
  47888. * @private
  47889. */
  47890. function receiverOnPing(data) {
  47891. const websocket = this[kWebSocket$1];
  47892. websocket.pong(data, !websocket._isServer, NOOP);
  47893. websocket.emit('ping', data);
  47894. }
  47895. /**
  47896. * The listener of the `Receiver` `'pong'` event.
  47897. *
  47898. * @param {Buffer} data The data included in the pong frame
  47899. * @private
  47900. */
  47901. function receiverOnPong(data) {
  47902. this[kWebSocket$1].emit('pong', data);
  47903. }
  47904. /**
  47905. * Resume a readable stream
  47906. *
  47907. * @param {Readable} stream The readable stream
  47908. * @private
  47909. */
  47910. function resume(stream) {
  47911. stream.resume();
  47912. }
  47913. /**
  47914. * The listener of the `net.Socket` `'close'` event.
  47915. *
  47916. * @private
  47917. */
  47918. function socketOnClose() {
  47919. const websocket = this[kWebSocket$1];
  47920. this.removeListener('close', socketOnClose);
  47921. this.removeListener('data', socketOnData);
  47922. this.removeListener('end', socketOnEnd);
  47923. websocket._readyState = WebSocket$1.CLOSING;
  47924. let chunk;
  47925. //
  47926. // The close frame might not have been received or the `'end'` event emitted,
  47927. // for example, if the socket was destroyed due to an error. Ensure that the
  47928. // `receiver` stream is closed after writing any remaining buffered data to
  47929. // it. If the readable side of the socket is in flowing mode then there is no
  47930. // buffered data as everything has been already written and `readable.read()`
  47931. // will return `null`. If instead, the socket is paused, any possible buffered
  47932. // data will be read as a single chunk.
  47933. //
  47934. if (
  47935. !this._readableState.endEmitted &&
  47936. !websocket._closeFrameReceived &&
  47937. !websocket._receiver._writableState.errorEmitted &&
  47938. (chunk = websocket._socket.read()) !== null
  47939. ) {
  47940. websocket._receiver.write(chunk);
  47941. }
  47942. websocket._receiver.end();
  47943. this[kWebSocket$1] = undefined;
  47944. clearTimeout(websocket._closeTimer);
  47945. if (
  47946. websocket._receiver._writableState.finished ||
  47947. websocket._receiver._writableState.errorEmitted
  47948. ) {
  47949. websocket.emitClose();
  47950. } else {
  47951. websocket._receiver.on('error', receiverOnFinish);
  47952. websocket._receiver.on('finish', receiverOnFinish);
  47953. }
  47954. }
  47955. /**
  47956. * The listener of the `net.Socket` `'data'` event.
  47957. *
  47958. * @param {Buffer} chunk A chunk of data
  47959. * @private
  47960. */
  47961. function socketOnData(chunk) {
  47962. if (!this[kWebSocket$1]._receiver.write(chunk)) {
  47963. this.pause();
  47964. }
  47965. }
  47966. /**
  47967. * The listener of the `net.Socket` `'end'` event.
  47968. *
  47969. * @private
  47970. */
  47971. function socketOnEnd() {
  47972. const websocket = this[kWebSocket$1];
  47973. websocket._readyState = WebSocket$1.CLOSING;
  47974. websocket._receiver.end();
  47975. this.end();
  47976. }
  47977. /**
  47978. * The listener of the `net.Socket` `'error'` event.
  47979. *
  47980. * @private
  47981. */
  47982. function socketOnError$1() {
  47983. const websocket = this[kWebSocket$1];
  47984. this.removeListener('error', socketOnError$1);
  47985. this.on('error', NOOP);
  47986. if (websocket) {
  47987. websocket._readyState = WebSocket$1.CLOSING;
  47988. this.destroy();
  47989. }
  47990. }
  47991. const { tokenChars } = validation.exports;
  47992. /**
  47993. * Parses the `Sec-WebSocket-Protocol` header into a set of subprotocol names.
  47994. *
  47995. * @param {String} header The field value of the header
  47996. * @return {Set} The subprotocol names
  47997. * @public
  47998. */
  47999. function parse$2(header) {
  48000. const protocols = new Set();
  48001. let start = -1;
  48002. let end = -1;
  48003. let i = 0;
  48004. for (i; i < header.length; i++) {
  48005. const code = header.charCodeAt(i);
  48006. if (end === -1 && tokenChars[code] === 1) {
  48007. if (start === -1) start = i;
  48008. } else if (
  48009. i !== 0 &&
  48010. (code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */
  48011. ) {
  48012. if (end === -1 && start !== -1) end = i;
  48013. } else if (code === 0x2c /* ',' */) {
  48014. if (start === -1) {
  48015. throw new SyntaxError(`Unexpected character at index ${i}`);
  48016. }
  48017. if (end === -1) end = i;
  48018. const protocol = header.slice(start, end);
  48019. if (protocols.has(protocol)) {
  48020. throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
  48021. }
  48022. protocols.add(protocol);
  48023. start = end = -1;
  48024. } else {
  48025. throw new SyntaxError(`Unexpected character at index ${i}`);
  48026. }
  48027. }
  48028. if (start === -1 || end !== -1) {
  48029. throw new SyntaxError('Unexpected end of input');
  48030. }
  48031. const protocol = header.slice(start, i);
  48032. if (protocols.has(protocol)) {
  48033. throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
  48034. }
  48035. protocols.add(protocol);
  48036. return protocols;
  48037. }
  48038. var subprotocol$1 = { parse: parse$2 };
  48039. /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^net|tls|https$" }] */
  48040. const EventEmitter = require$$0__default$1;
  48041. const http$2 = require$$1__default$1;
  48042. const { createHash } = require$$1__default$2;
  48043. const extension = extension$1;
  48044. const PerMessageDeflate = permessageDeflate;
  48045. const subprotocol = subprotocol$1;
  48046. const WebSocket = websocket;
  48047. const { GUID, kWebSocket } = constants;
  48048. const keyRegex = /^[+/0-9A-Za-z]{22}==$/;
  48049. const RUNNING = 0;
  48050. const CLOSING = 1;
  48051. const CLOSED = 2;
  48052. /**
  48053. * Class representing a WebSocket server.
  48054. *
  48055. * @extends EventEmitter
  48056. */
  48057. class WebSocketServer extends EventEmitter {
  48058. /**
  48059. * Create a `WebSocketServer` instance.
  48060. *
  48061. * @param {Object} options Configuration options
  48062. * @param {Number} [options.backlog=511] The maximum length of the queue of
  48063. * pending connections
  48064. * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
  48065. * track clients
  48066. * @param {Function} [options.handleProtocols] A hook to handle protocols
  48067. * @param {String} [options.host] The hostname where to bind the server
  48068. * @param {Number} [options.maxPayload=104857600] The maximum allowed message
  48069. * size
  48070. * @param {Boolean} [options.noServer=false] Enable no server mode
  48071. * @param {String} [options.path] Accept only connections matching this path
  48072. * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
  48073. * permessage-deflate
  48074. * @param {Number} [options.port] The port where to bind the server
  48075. * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
  48076. * server to use
  48077. * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
  48078. * not to skip UTF-8 validation for text and close messages
  48079. * @param {Function} [options.verifyClient] A hook to reject connections
  48080. * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
  48081. * class to use. It must be the `WebSocket` class or class that extends it
  48082. * @param {Function} [callback] A listener for the `listening` event
  48083. */
  48084. constructor(options, callback) {
  48085. super();
  48086. options = {
  48087. maxPayload: 100 * 1024 * 1024,
  48088. skipUTF8Validation: false,
  48089. perMessageDeflate: false,
  48090. handleProtocols: null,
  48091. clientTracking: true,
  48092. verifyClient: null,
  48093. noServer: false,
  48094. backlog: null, // use default (511 as implemented in net.js)
  48095. server: null,
  48096. host: null,
  48097. path: null,
  48098. port: null,
  48099. WebSocket,
  48100. ...options
  48101. };
  48102. if (
  48103. (options.port == null && !options.server && !options.noServer) ||
  48104. (options.port != null && (options.server || options.noServer)) ||
  48105. (options.server && options.noServer)
  48106. ) {
  48107. throw new TypeError(
  48108. 'One and only one of the "port", "server", or "noServer" options ' +
  48109. 'must be specified'
  48110. );
  48111. }
  48112. if (options.port != null) {
  48113. this._server = http$2.createServer((req, res) => {
  48114. const body = http$2.STATUS_CODES[426];
  48115. res.writeHead(426, {
  48116. 'Content-Length': body.length,
  48117. 'Content-Type': 'text/plain'
  48118. });
  48119. res.end(body);
  48120. });
  48121. this._server.listen(
  48122. options.port,
  48123. options.host,
  48124. options.backlog,
  48125. callback
  48126. );
  48127. } else if (options.server) {
  48128. this._server = options.server;
  48129. }
  48130. if (this._server) {
  48131. const emitConnection = this.emit.bind(this, 'connection');
  48132. this._removeListeners = addListeners(this._server, {
  48133. listening: this.emit.bind(this, 'listening'),
  48134. error: this.emit.bind(this, 'error'),
  48135. upgrade: (req, socket, head) => {
  48136. this.handleUpgrade(req, socket, head, emitConnection);
  48137. }
  48138. });
  48139. }
  48140. if (options.perMessageDeflate === true) options.perMessageDeflate = {};
  48141. if (options.clientTracking) {
  48142. this.clients = new Set();
  48143. this._shouldEmitClose = false;
  48144. }
  48145. this.options = options;
  48146. this._state = RUNNING;
  48147. }
  48148. /**
  48149. * Returns the bound address, the address family name, and port of the server
  48150. * as reported by the operating system if listening on an IP socket.
  48151. * If the server is listening on a pipe or UNIX domain socket, the name is
  48152. * returned as a string.
  48153. *
  48154. * @return {(Object|String|null)} The address of the server
  48155. * @public
  48156. */
  48157. address() {
  48158. if (this.options.noServer) {
  48159. throw new Error('The server is operating in "noServer" mode');
  48160. }
  48161. if (!this._server) return null;
  48162. return this._server.address();
  48163. }
  48164. /**
  48165. * Stop the server from accepting new connections and emit the `'close'` event
  48166. * when all existing connections are closed.
  48167. *
  48168. * @param {Function} [cb] A one-time listener for the `'close'` event
  48169. * @public
  48170. */
  48171. close(cb) {
  48172. if (this._state === CLOSED) {
  48173. if (cb) {
  48174. this.once('close', () => {
  48175. cb(new Error('The server is not running'));
  48176. });
  48177. }
  48178. process.nextTick(emitClose, this);
  48179. return;
  48180. }
  48181. if (cb) this.once('close', cb);
  48182. if (this._state === CLOSING) return;
  48183. this._state = CLOSING;
  48184. if (this.options.noServer || this.options.server) {
  48185. if (this._server) {
  48186. this._removeListeners();
  48187. this._removeListeners = this._server = null;
  48188. }
  48189. if (this.clients) {
  48190. if (!this.clients.size) {
  48191. process.nextTick(emitClose, this);
  48192. } else {
  48193. this._shouldEmitClose = true;
  48194. }
  48195. } else {
  48196. process.nextTick(emitClose, this);
  48197. }
  48198. } else {
  48199. const server = this._server;
  48200. this._removeListeners();
  48201. this._removeListeners = this._server = null;
  48202. //
  48203. // The HTTP/S server was created internally. Close it, and rely on its
  48204. // `'close'` event.
  48205. //
  48206. server.close(() => {
  48207. emitClose(this);
  48208. });
  48209. }
  48210. }
  48211. /**
  48212. * See if a given request should be handled by this server instance.
  48213. *
  48214. * @param {http.IncomingMessage} req Request object to inspect
  48215. * @return {Boolean} `true` if the request is valid, else `false`
  48216. * @public
  48217. */
  48218. shouldHandle(req) {
  48219. if (this.options.path) {
  48220. const index = req.url.indexOf('?');
  48221. const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
  48222. if (pathname !== this.options.path) return false;
  48223. }
  48224. return true;
  48225. }
  48226. /**
  48227. * Handle a HTTP Upgrade request.
  48228. *
  48229. * @param {http.IncomingMessage} req The request object
  48230. * @param {(net.Socket|tls.Socket)} socket The network socket between the
  48231. * server and client
  48232. * @param {Buffer} head The first packet of the upgraded stream
  48233. * @param {Function} cb Callback
  48234. * @public
  48235. */
  48236. handleUpgrade(req, socket, head, cb) {
  48237. socket.on('error', socketOnError);
  48238. const key =
  48239. req.headers['sec-websocket-key'] !== undefined
  48240. ? req.headers['sec-websocket-key']
  48241. : false;
  48242. const version = +req.headers['sec-websocket-version'];
  48243. if (
  48244. req.method !== 'GET' ||
  48245. req.headers.upgrade.toLowerCase() !== 'websocket' ||
  48246. !key ||
  48247. !keyRegex.test(key) ||
  48248. (version !== 8 && version !== 13) ||
  48249. !this.shouldHandle(req)
  48250. ) {
  48251. return abortHandshake(socket, 400);
  48252. }
  48253. const secWebSocketProtocol = req.headers['sec-websocket-protocol'];
  48254. let protocols = new Set();
  48255. if (secWebSocketProtocol !== undefined) {
  48256. try {
  48257. protocols = subprotocol.parse(secWebSocketProtocol);
  48258. } catch (err) {
  48259. return abortHandshake(socket, 400);
  48260. }
  48261. }
  48262. const secWebSocketExtensions = req.headers['sec-websocket-extensions'];
  48263. const extensions = {};
  48264. if (
  48265. this.options.perMessageDeflate &&
  48266. secWebSocketExtensions !== undefined
  48267. ) {
  48268. const perMessageDeflate = new PerMessageDeflate(
  48269. this.options.perMessageDeflate,
  48270. true,
  48271. this.options.maxPayload
  48272. );
  48273. try {
  48274. const offers = extension.parse(secWebSocketExtensions);
  48275. if (offers[PerMessageDeflate.extensionName]) {
  48276. perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
  48277. extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
  48278. }
  48279. } catch (err) {
  48280. return abortHandshake(socket, 400);
  48281. }
  48282. }
  48283. //
  48284. // Optionally call external client verification handler.
  48285. //
  48286. if (this.options.verifyClient) {
  48287. const info = {
  48288. origin:
  48289. req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`],
  48290. secure: !!(req.socket.authorized || req.socket.encrypted),
  48291. req
  48292. };
  48293. if (this.options.verifyClient.length === 2) {
  48294. this.options.verifyClient(info, (verified, code, message, headers) => {
  48295. if (!verified) {
  48296. return abortHandshake(socket, code || 401, message, headers);
  48297. }
  48298. this.completeUpgrade(
  48299. extensions,
  48300. key,
  48301. protocols,
  48302. req,
  48303. socket,
  48304. head,
  48305. cb
  48306. );
  48307. });
  48308. return;
  48309. }
  48310. if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
  48311. }
  48312. this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
  48313. }
  48314. /**
  48315. * Upgrade the connection to WebSocket.
  48316. *
  48317. * @param {Object} extensions The accepted extensions
  48318. * @param {String} key The value of the `Sec-WebSocket-Key` header
  48319. * @param {Set} protocols The subprotocols
  48320. * @param {http.IncomingMessage} req The request object
  48321. * @param {(net.Socket|tls.Socket)} socket The network socket between the
  48322. * server and client
  48323. * @param {Buffer} head The first packet of the upgraded stream
  48324. * @param {Function} cb Callback
  48325. * @throws {Error} If called more than once with the same socket
  48326. * @private
  48327. */
  48328. completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
  48329. //
  48330. // Destroy the socket if the client has already sent a FIN packet.
  48331. //
  48332. if (!socket.readable || !socket.writable) return socket.destroy();
  48333. if (socket[kWebSocket]) {
  48334. throw new Error(
  48335. 'server.handleUpgrade() was called more than once with the same ' +
  48336. 'socket, possibly due to a misconfiguration'
  48337. );
  48338. }
  48339. if (this._state > RUNNING) return abortHandshake(socket, 503);
  48340. const digest = createHash('sha1')
  48341. .update(key + GUID)
  48342. .digest('base64');
  48343. const headers = [
  48344. 'HTTP/1.1 101 Switching Protocols',
  48345. 'Upgrade: websocket',
  48346. 'Connection: Upgrade',
  48347. `Sec-WebSocket-Accept: ${digest}`
  48348. ];
  48349. const ws = new this.options.WebSocket(null);
  48350. if (protocols.size) {
  48351. //
  48352. // Optionally call external protocol selection handler.
  48353. //
  48354. const protocol = this.options.handleProtocols
  48355. ? this.options.handleProtocols(protocols, req)
  48356. : protocols.values().next().value;
  48357. if (protocol) {
  48358. headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
  48359. ws._protocol = protocol;
  48360. }
  48361. }
  48362. if (extensions[PerMessageDeflate.extensionName]) {
  48363. const params = extensions[PerMessageDeflate.extensionName].params;
  48364. const value = extension.format({
  48365. [PerMessageDeflate.extensionName]: [params]
  48366. });
  48367. headers.push(`Sec-WebSocket-Extensions: ${value}`);
  48368. ws._extensions = extensions;
  48369. }
  48370. //
  48371. // Allow external modification/inspection of handshake headers.
  48372. //
  48373. this.emit('headers', headers, req);
  48374. socket.write(headers.concat('\r\n').join('\r\n'));
  48375. socket.removeListener('error', socketOnError);
  48376. ws.setSocket(socket, head, {
  48377. maxPayload: this.options.maxPayload,
  48378. skipUTF8Validation: this.options.skipUTF8Validation
  48379. });
  48380. if (this.clients) {
  48381. this.clients.add(ws);
  48382. ws.on('close', () => {
  48383. this.clients.delete(ws);
  48384. if (this._shouldEmitClose && !this.clients.size) {
  48385. process.nextTick(emitClose, this);
  48386. }
  48387. });
  48388. }
  48389. cb(ws, req);
  48390. }
  48391. }
  48392. var websocketServer = WebSocketServer;
  48393. /**
  48394. * Add event listeners on an `EventEmitter` using a map of <event, listener>
  48395. * pairs.
  48396. *
  48397. * @param {EventEmitter} server The event emitter
  48398. * @param {Object.<String, Function>} map The listeners to add
  48399. * @return {Function} A function that will remove the added listeners when
  48400. * called
  48401. * @private
  48402. */
  48403. function addListeners(server, map) {
  48404. for (const event of Object.keys(map)) server.on(event, map[event]);
  48405. return function removeListeners() {
  48406. for (const event of Object.keys(map)) {
  48407. server.removeListener(event, map[event]);
  48408. }
  48409. };
  48410. }
  48411. /**
  48412. * Emit a `'close'` event on an `EventEmitter`.
  48413. *
  48414. * @param {EventEmitter} server The event emitter
  48415. * @private
  48416. */
  48417. function emitClose(server) {
  48418. server._state = CLOSED;
  48419. server.emit('close');
  48420. }
  48421. /**
  48422. * Handle premature socket errors.
  48423. *
  48424. * @private
  48425. */
  48426. function socketOnError() {
  48427. this.destroy();
  48428. }
  48429. /**
  48430. * Close the connection when preconditions are not fulfilled.
  48431. *
  48432. * @param {(net.Socket|tls.Socket)} socket The socket of the upgrade request
  48433. * @param {Number} code The HTTP response status code
  48434. * @param {String} [message] The HTTP response body
  48435. * @param {Object} [headers] Additional HTTP response headers
  48436. * @private
  48437. */
  48438. function abortHandshake(socket, code, message, headers) {
  48439. if (socket.writable) {
  48440. message = message || http$2.STATUS_CODES[code];
  48441. headers = {
  48442. Connection: 'close',
  48443. 'Content-Type': 'text/html',
  48444. 'Content-Length': Buffer.byteLength(message),
  48445. ...headers
  48446. };
  48447. socket.write(
  48448. `HTTP/1.1 ${code} ${http$2.STATUS_CODES[code]}\r\n` +
  48449. Object.keys(headers)
  48450. .map((h) => `${h}: ${headers[h]}`)
  48451. .join('\r\n') +
  48452. '\r\n\r\n' +
  48453. message
  48454. );
  48455. }
  48456. socket.removeListener('error', socketOnError);
  48457. socket.destroy();
  48458. }
  48459. const HMR_HEADER = 'vite-hmr';
  48460. const wsServerEvents = [
  48461. 'connection',
  48462. 'error',
  48463. 'headers',
  48464. 'listening',
  48465. 'message'
  48466. ];
  48467. function createWebSocketServer(server, config, httpsOptions) {
  48468. let wss;
  48469. let httpsServer = undefined;
  48470. const hmr = isObject$1(config.server.hmr) && config.server.hmr;
  48471. const hmrServer = hmr && hmr.server;
  48472. const hmrPort = hmr && hmr.port;
  48473. // TODO: the main server port may not have been chosen yet as it may use the next available
  48474. const portsAreCompatible = !hmrPort || hmrPort === config.server.port;
  48475. const wsServer = hmrServer || (portsAreCompatible && server);
  48476. const customListeners = new Map();
  48477. const clientsMap = new WeakMap();
  48478. if (wsServer) {
  48479. wss = new websocketServer({ noServer: true });
  48480. wsServer.on('upgrade', (req, socket, head) => {
  48481. if (req.headers['sec-websocket-protocol'] === HMR_HEADER) {
  48482. wss.handleUpgrade(req, socket, head, (ws) => {
  48483. wss.emit('connection', ws, req);
  48484. });
  48485. }
  48486. });
  48487. }
  48488. else {
  48489. const websocketServerOptions = {};
  48490. const port = hmrPort || 24678;
  48491. const host = (hmr && hmr.host) || undefined;
  48492. if (httpsOptions) {
  48493. // if we're serving the middlewares over https, the ws library doesn't support automatically creating an https server, so we need to do it ourselves
  48494. // create an inline https server and mount the websocket server to it
  48495. httpsServer = require$$1$3.createServer(httpsOptions, (req, res) => {
  48496. const statusCode = 426;
  48497. const body = require$$1$2.STATUS_CODES[statusCode];
  48498. if (!body)
  48499. throw new Error(`No body text found for the ${statusCode} status code`);
  48500. res.writeHead(statusCode, {
  48501. 'Content-Length': body.length,
  48502. 'Content-Type': 'text/plain'
  48503. });
  48504. res.end(body);
  48505. });
  48506. httpsServer.listen(port, host);
  48507. websocketServerOptions.server = httpsServer;
  48508. }
  48509. else {
  48510. // we don't need to serve over https, just let ws handle its own server
  48511. websocketServerOptions.port = port;
  48512. if (host) {
  48513. websocketServerOptions.host = host;
  48514. }
  48515. }
  48516. // vite dev server in middleware mode
  48517. wss = new websocketServer(websocketServerOptions);
  48518. }
  48519. wss.on('connection', (socket) => {
  48520. socket.on('message', (raw) => {
  48521. if (!customListeners.size)
  48522. return;
  48523. let parsed;
  48524. try {
  48525. parsed = JSON.parse(String(raw));
  48526. }
  48527. catch { }
  48528. if (!parsed || parsed.type !== 'custom' || !parsed.event)
  48529. return;
  48530. const listeners = customListeners.get(parsed.event);
  48531. if (!(listeners === null || listeners === void 0 ? void 0 : listeners.size))
  48532. return;
  48533. const client = getSocketClient(socket);
  48534. listeners.forEach((listener) => listener(parsed.data, client));
  48535. });
  48536. socket.send(JSON.stringify({ type: 'connected' }));
  48537. if (bufferedError) {
  48538. socket.send(JSON.stringify(bufferedError));
  48539. bufferedError = null;
  48540. }
  48541. });
  48542. wss.on('error', (e) => {
  48543. if (e.code !== 'EADDRINUSE') {
  48544. config.logger.error(colors$1.red(`WebSocket server error:\n${e.stack || e.message}`), { error: e });
  48545. }
  48546. });
  48547. // Provide a wrapper to the ws client so we can send messages in JSON format
  48548. // To be consistent with server.ws.send
  48549. function getSocketClient(socket) {
  48550. if (!clientsMap.has(socket)) {
  48551. clientsMap.set(socket, {
  48552. send: (...args) => {
  48553. let payload;
  48554. if (typeof args[0] === 'string') {
  48555. payload = {
  48556. type: 'custom',
  48557. event: args[0],
  48558. data: args[1]
  48559. };
  48560. }
  48561. else {
  48562. payload = args[0];
  48563. }
  48564. socket.send(JSON.stringify(payload));
  48565. },
  48566. socket
  48567. });
  48568. }
  48569. return clientsMap.get(socket);
  48570. }
  48571. // On page reloads, if a file fails to compile and returns 500, the server
  48572. // sends the error payload before the client connection is established.
  48573. // If we have no open clients, buffer the error and send it to the next
  48574. // connected client.
  48575. let bufferedError = null;
  48576. return {
  48577. on: ((event, fn) => {
  48578. if (wsServerEvents.includes(event))
  48579. wss.on(event, fn);
  48580. else {
  48581. if (!customListeners.has(event)) {
  48582. customListeners.set(event, new Set());
  48583. }
  48584. customListeners.get(event).add(fn);
  48585. }
  48586. }),
  48587. off: ((event, fn) => {
  48588. var _a;
  48589. if (wsServerEvents.includes(event)) {
  48590. wss.off(event, fn);
  48591. }
  48592. else {
  48593. (_a = customListeners.get(event)) === null || _a === void 0 ? void 0 : _a.delete(fn);
  48594. }
  48595. }),
  48596. get clients() {
  48597. return new Set(Array.from(wss.clients).map(getSocketClient));
  48598. },
  48599. send(...args) {
  48600. let payload;
  48601. if (typeof args[0] === 'string') {
  48602. payload = {
  48603. type: 'custom',
  48604. event: args[0],
  48605. data: args[1]
  48606. };
  48607. }
  48608. else {
  48609. payload = args[0];
  48610. }
  48611. if (payload.type === 'error' && !wss.clients.size) {
  48612. bufferedError = payload;
  48613. return;
  48614. }
  48615. const stringified = JSON.stringify(payload);
  48616. wss.clients.forEach((client) => {
  48617. // readyState 1 means the connection is open
  48618. if (client.readyState === 1) {
  48619. client.send(stringified);
  48620. }
  48621. });
  48622. },
  48623. close() {
  48624. return new Promise((resolve, reject) => {
  48625. wss.clients.forEach((client) => {
  48626. client.terminate();
  48627. });
  48628. wss.close((err) => {
  48629. if (err) {
  48630. reject(err);
  48631. }
  48632. else {
  48633. if (httpsServer) {
  48634. httpsServer.close((err) => {
  48635. if (err) {
  48636. reject(err);
  48637. }
  48638. else {
  48639. resolve();
  48640. }
  48641. });
  48642. }
  48643. else {
  48644. resolve();
  48645. }
  48646. }
  48647. });
  48648. });
  48649. }
  48650. };
  48651. }
  48652. // this middleware is only active when (config.base !== '/')
  48653. function baseMiddleware({ config }) {
  48654. const base = config.base;
  48655. // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
  48656. return function viteBaseMiddleware(req, res, next) {
  48657. var _a;
  48658. const url = req.url;
  48659. const parsed = require$$0$6.parse(url);
  48660. const path = parsed.pathname || '/';
  48661. if (path.startsWith(base)) {
  48662. // rewrite url to remove base.. this ensures that other middleware does
  48663. // not need to consider base being prepended or not
  48664. req.url = url.replace(base, '/');
  48665. return next();
  48666. }
  48667. // skip redirect and error fallback on middleware mode, #4057
  48668. if (config.server.middlewareMode) {
  48669. return next();
  48670. }
  48671. if (path === '/' || path === '/index.html') {
  48672. // redirect root visit to based url with search and hash
  48673. res.writeHead(302, {
  48674. Location: base + (parsed.search || '') + (parsed.hash || '')
  48675. });
  48676. res.end();
  48677. return;
  48678. }
  48679. else if ((_a = req.headers.accept) === null || _a === void 0 ? void 0 : _a.includes('text/html')) {
  48680. // non-based page visit
  48681. const redirectPath = base + url.slice(1);
  48682. res.writeHead(404, {
  48683. 'Content-Type': 'text/html'
  48684. });
  48685. res.end(`The server is configured with a public base URL of ${base} - ` +
  48686. `did you mean to visit <a href="${redirectPath}">${redirectPath}</a> instead?`);
  48687. return;
  48688. }
  48689. next();
  48690. };
  48691. }
  48692. var httpProxy$2 = {exports: {}};
  48693. var eventemitter3 = {exports: {}};
  48694. (function (module) {
  48695. var has = Object.prototype.hasOwnProperty
  48696. , prefix = '~';
  48697. /**
  48698. * Constructor to create a storage for our `EE` objects.
  48699. * An `Events` instance is a plain object whose properties are event names.
  48700. *
  48701. * @constructor
  48702. * @private
  48703. */
  48704. function Events() {}
  48705. //
  48706. // We try to not inherit from `Object.prototype`. In some engines creating an
  48707. // instance in this way is faster than calling `Object.create(null)` directly.
  48708. // If `Object.create(null)` is not supported we prefix the event names with a
  48709. // character to make sure that the built-in object properties are not
  48710. // overridden or used as an attack vector.
  48711. //
  48712. if (Object.create) {
  48713. Events.prototype = Object.create(null);
  48714. //
  48715. // This hack is needed because the `__proto__` property is still inherited in
  48716. // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
  48717. //
  48718. if (!new Events().__proto__) prefix = false;
  48719. }
  48720. /**
  48721. * Representation of a single event listener.
  48722. *
  48723. * @param {Function} fn The listener function.
  48724. * @param {*} context The context to invoke the listener with.
  48725. * @param {Boolean} [once=false] Specify if the listener is a one-time listener.
  48726. * @constructor
  48727. * @private
  48728. */
  48729. function EE(fn, context, once) {
  48730. this.fn = fn;
  48731. this.context = context;
  48732. this.once = once || false;
  48733. }
  48734. /**
  48735. * Add a listener for a given event.
  48736. *
  48737. * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
  48738. * @param {(String|Symbol)} event The event name.
  48739. * @param {Function} fn The listener function.
  48740. * @param {*} context The context to invoke the listener with.
  48741. * @param {Boolean} once Specify if the listener is a one-time listener.
  48742. * @returns {EventEmitter}
  48743. * @private
  48744. */
  48745. function addListener(emitter, event, fn, context, once) {
  48746. if (typeof fn !== 'function') {
  48747. throw new TypeError('The listener must be a function');
  48748. }
  48749. var listener = new EE(fn, context || emitter, once)
  48750. , evt = prefix ? prefix + event : event;
  48751. if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
  48752. else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
  48753. else emitter._events[evt] = [emitter._events[evt], listener];
  48754. return emitter;
  48755. }
  48756. /**
  48757. * Clear event by name.
  48758. *
  48759. * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
  48760. * @param {(String|Symbol)} evt The Event name.
  48761. * @private
  48762. */
  48763. function clearEvent(emitter, evt) {
  48764. if (--emitter._eventsCount === 0) emitter._events = new Events();
  48765. else delete emitter._events[evt];
  48766. }
  48767. /**
  48768. * Minimal `EventEmitter` interface that is molded against the Node.js
  48769. * `EventEmitter` interface.
  48770. *
  48771. * @constructor
  48772. * @public
  48773. */
  48774. function EventEmitter() {
  48775. this._events = new Events();
  48776. this._eventsCount = 0;
  48777. }
  48778. /**
  48779. * Return an array listing the events for which the emitter has registered
  48780. * listeners.
  48781. *
  48782. * @returns {Array}
  48783. * @public
  48784. */
  48785. EventEmitter.prototype.eventNames = function eventNames() {
  48786. var names = []
  48787. , events
  48788. , name;
  48789. if (this._eventsCount === 0) return names;
  48790. for (name in (events = this._events)) {
  48791. if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
  48792. }
  48793. if (Object.getOwnPropertySymbols) {
  48794. return names.concat(Object.getOwnPropertySymbols(events));
  48795. }
  48796. return names;
  48797. };
  48798. /**
  48799. * Return the listeners registered for a given event.
  48800. *
  48801. * @param {(String|Symbol)} event The event name.
  48802. * @returns {Array} The registered listeners.
  48803. * @public
  48804. */
  48805. EventEmitter.prototype.listeners = function listeners(event) {
  48806. var evt = prefix ? prefix + event : event
  48807. , handlers = this._events[evt];
  48808. if (!handlers) return [];
  48809. if (handlers.fn) return [handlers.fn];
  48810. for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
  48811. ee[i] = handlers[i].fn;
  48812. }
  48813. return ee;
  48814. };
  48815. /**
  48816. * Return the number of listeners listening to a given event.
  48817. *
  48818. * @param {(String|Symbol)} event The event name.
  48819. * @returns {Number} The number of listeners.
  48820. * @public
  48821. */
  48822. EventEmitter.prototype.listenerCount = function listenerCount(event) {
  48823. var evt = prefix ? prefix + event : event
  48824. , listeners = this._events[evt];
  48825. if (!listeners) return 0;
  48826. if (listeners.fn) return 1;
  48827. return listeners.length;
  48828. };
  48829. /**
  48830. * Calls each of the listeners registered for a given event.
  48831. *
  48832. * @param {(String|Symbol)} event The event name.
  48833. * @returns {Boolean} `true` if the event had listeners, else `false`.
  48834. * @public
  48835. */
  48836. EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
  48837. var evt = prefix ? prefix + event : event;
  48838. if (!this._events[evt]) return false;
  48839. var listeners = this._events[evt]
  48840. , len = arguments.length
  48841. , args
  48842. , i;
  48843. if (listeners.fn) {
  48844. if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
  48845. switch (len) {
  48846. case 1: return listeners.fn.call(listeners.context), true;
  48847. case 2: return listeners.fn.call(listeners.context, a1), true;
  48848. case 3: return listeners.fn.call(listeners.context, a1, a2), true;
  48849. case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
  48850. case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
  48851. case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
  48852. }
  48853. for (i = 1, args = new Array(len -1); i < len; i++) {
  48854. args[i - 1] = arguments[i];
  48855. }
  48856. listeners.fn.apply(listeners.context, args);
  48857. } else {
  48858. var length = listeners.length
  48859. , j;
  48860. for (i = 0; i < length; i++) {
  48861. if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
  48862. switch (len) {
  48863. case 1: listeners[i].fn.call(listeners[i].context); break;
  48864. case 2: listeners[i].fn.call(listeners[i].context, a1); break;
  48865. case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
  48866. case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
  48867. default:
  48868. if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
  48869. args[j - 1] = arguments[j];
  48870. }
  48871. listeners[i].fn.apply(listeners[i].context, args);
  48872. }
  48873. }
  48874. }
  48875. return true;
  48876. };
  48877. /**
  48878. * Add a listener for a given event.
  48879. *
  48880. * @param {(String|Symbol)} event The event name.
  48881. * @param {Function} fn The listener function.
  48882. * @param {*} [context=this] The context to invoke the listener with.
  48883. * @returns {EventEmitter} `this`.
  48884. * @public
  48885. */
  48886. EventEmitter.prototype.on = function on(event, fn, context) {
  48887. return addListener(this, event, fn, context, false);
  48888. };
  48889. /**
  48890. * Add a one-time listener for a given event.
  48891. *
  48892. * @param {(String|Symbol)} event The event name.
  48893. * @param {Function} fn The listener function.
  48894. * @param {*} [context=this] The context to invoke the listener with.
  48895. * @returns {EventEmitter} `this`.
  48896. * @public
  48897. */
  48898. EventEmitter.prototype.once = function once(event, fn, context) {
  48899. return addListener(this, event, fn, context, true);
  48900. };
  48901. /**
  48902. * Remove the listeners of a given event.
  48903. *
  48904. * @param {(String|Symbol)} event The event name.
  48905. * @param {Function} fn Only remove the listeners that match this function.
  48906. * @param {*} context Only remove the listeners that have this context.
  48907. * @param {Boolean} once Only remove one-time listeners.
  48908. * @returns {EventEmitter} `this`.
  48909. * @public
  48910. */
  48911. EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
  48912. var evt = prefix ? prefix + event : event;
  48913. if (!this._events[evt]) return this;
  48914. if (!fn) {
  48915. clearEvent(this, evt);
  48916. return this;
  48917. }
  48918. var listeners = this._events[evt];
  48919. if (listeners.fn) {
  48920. if (
  48921. listeners.fn === fn &&
  48922. (!once || listeners.once) &&
  48923. (!context || listeners.context === context)
  48924. ) {
  48925. clearEvent(this, evt);
  48926. }
  48927. } else {
  48928. for (var i = 0, events = [], length = listeners.length; i < length; i++) {
  48929. if (
  48930. listeners[i].fn !== fn ||
  48931. (once && !listeners[i].once) ||
  48932. (context && listeners[i].context !== context)
  48933. ) {
  48934. events.push(listeners[i]);
  48935. }
  48936. }
  48937. //
  48938. // Reset the array, or remove it completely if we have no more listeners.
  48939. //
  48940. if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
  48941. else clearEvent(this, evt);
  48942. }
  48943. return this;
  48944. };
  48945. /**
  48946. * Remove all listeners, or those of the specified event.
  48947. *
  48948. * @param {(String|Symbol)} [event] The event name.
  48949. * @returns {EventEmitter} `this`.
  48950. * @public
  48951. */
  48952. EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
  48953. var evt;
  48954. if (event) {
  48955. evt = prefix ? prefix + event : event;
  48956. if (this._events[evt]) clearEvent(this, evt);
  48957. } else {
  48958. this._events = new Events();
  48959. this._eventsCount = 0;
  48960. }
  48961. return this;
  48962. };
  48963. //
  48964. // Alias methods names because people roll like that.
  48965. //
  48966. EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
  48967. EventEmitter.prototype.addListener = EventEmitter.prototype.on;
  48968. //
  48969. // Expose the prefix.
  48970. //
  48971. EventEmitter.prefixed = prefix;
  48972. //
  48973. // Allow `EventEmitter` to be imported as module namespace.
  48974. //
  48975. EventEmitter.EventEmitter = EventEmitter;
  48976. //
  48977. // Expose the module.
  48978. //
  48979. {
  48980. module.exports = EventEmitter;
  48981. }
  48982. }(eventemitter3));
  48983. var common$3 = {};
  48984. /**
  48985. * Check if we're required to add a port number.
  48986. *
  48987. * @see https://url.spec.whatwg.org/#default-port
  48988. * @param {Number|String} port Port number we need to check
  48989. * @param {String} protocol Protocol we need to check against.
  48990. * @returns {Boolean} Is it a default port for the given protocol
  48991. * @api private
  48992. */
  48993. var requiresPort = function required(port, protocol) {
  48994. protocol = protocol.split(':')[0];
  48995. port = +port;
  48996. if (!port) return false;
  48997. switch (protocol) {
  48998. case 'http':
  48999. case 'ws':
  49000. return port !== 80;
  49001. case 'https':
  49002. case 'wss':
  49003. return port !== 443;
  49004. case 'ftp':
  49005. return port !== 21;
  49006. case 'gopher':
  49007. return port !== 70;
  49008. case 'file':
  49009. return false;
  49010. }
  49011. return port !== 0;
  49012. };
  49013. (function (exports) {
  49014. var common = exports,
  49015. url = require$$0__default$5,
  49016. extend = require$$0__default$2._extend,
  49017. required = requiresPort;
  49018. var upgradeHeader = /(^|,)\s*upgrade\s*($|,)/i,
  49019. isSSL = /^https|wss/;
  49020. /**
  49021. * Simple Regex for testing if protocol is https
  49022. */
  49023. common.isSSL = isSSL;
  49024. /**
  49025. * Copies the right headers from `options` and `req` to
  49026. * `outgoing` which is then used to fire the proxied
  49027. * request.
  49028. *
  49029. * Examples:
  49030. *
  49031. * common.setupOutgoing(outgoing, options, req)
  49032. * // => { host: ..., hostname: ...}
  49033. *
  49034. * @param {Object} Outgoing Base object to be filled with required properties
  49035. * @param {Object} Options Config object passed to the proxy
  49036. * @param {ClientRequest} Req Request Object
  49037. * @param {String} Forward String to select forward or target
  49038. * @return {Object} Outgoing Object with all required properties set
  49039. *
  49040. * @api private
  49041. */
  49042. common.setupOutgoing = function(outgoing, options, req, forward) {
  49043. outgoing.port = options[forward || 'target'].port ||
  49044. (isSSL.test(options[forward || 'target'].protocol) ? 443 : 80);
  49045. ['host', 'hostname', 'socketPath', 'pfx', 'key',
  49046. 'passphrase', 'cert', 'ca', 'ciphers', 'secureProtocol'].forEach(
  49047. function(e) { outgoing[e] = options[forward || 'target'][e]; }
  49048. );
  49049. outgoing.method = options.method || req.method;
  49050. outgoing.headers = extend({}, req.headers);
  49051. if (options.headers){
  49052. extend(outgoing.headers, options.headers);
  49053. }
  49054. if (options.auth) {
  49055. outgoing.auth = options.auth;
  49056. }
  49057. if (options.ca) {
  49058. outgoing.ca = options.ca;
  49059. }
  49060. if (isSSL.test(options[forward || 'target'].protocol)) {
  49061. outgoing.rejectUnauthorized = (typeof options.secure === "undefined") ? true : options.secure;
  49062. }
  49063. outgoing.agent = options.agent || false;
  49064. outgoing.localAddress = options.localAddress;
  49065. //
  49066. // Remark: If we are false and not upgrading, set the connection: close. This is the right thing to do
  49067. // as node core doesn't handle this COMPLETELY properly yet.
  49068. //
  49069. if (!outgoing.agent) {
  49070. outgoing.headers = outgoing.headers || {};
  49071. if (typeof outgoing.headers.connection !== 'string'
  49072. || !upgradeHeader.test(outgoing.headers.connection)
  49073. ) { outgoing.headers.connection = 'close'; }
  49074. }
  49075. // the final path is target path + relative path requested by user:
  49076. var target = options[forward || 'target'];
  49077. var targetPath = target && options.prependPath !== false
  49078. ? (target.path || '')
  49079. : '';
  49080. //
  49081. // Remark: Can we somehow not use url.parse as a perf optimization?
  49082. //
  49083. var outgoingPath = !options.toProxy
  49084. ? (url.parse(req.url).path || '')
  49085. : req.url;
  49086. //
  49087. // Remark: ignorePath will just straight up ignore whatever the request's
  49088. // path is. This can be labeled as FOOT-GUN material if you do not know what
  49089. // you are doing and are using conflicting options.
  49090. //
  49091. outgoingPath = !options.ignorePath ? outgoingPath : '';
  49092. outgoing.path = common.urlJoin(targetPath, outgoingPath);
  49093. if (options.changeOrigin) {
  49094. outgoing.headers.host =
  49095. required(outgoing.port, options[forward || 'target'].protocol) && !hasPort(outgoing.host)
  49096. ? outgoing.host + ':' + outgoing.port
  49097. : outgoing.host;
  49098. }
  49099. return outgoing;
  49100. };
  49101. /**
  49102. * Set the proper configuration for sockets,
  49103. * set no delay and set keep alive, also set
  49104. * the timeout to 0.
  49105. *
  49106. * Examples:
  49107. *
  49108. * common.setupSocket(socket)
  49109. * // => Socket
  49110. *
  49111. * @param {Socket} Socket instance to setup
  49112. * @return {Socket} Return the configured socket.
  49113. *
  49114. * @api private
  49115. */
  49116. common.setupSocket = function(socket) {
  49117. socket.setTimeout(0);
  49118. socket.setNoDelay(true);
  49119. socket.setKeepAlive(true, 0);
  49120. return socket;
  49121. };
  49122. /**
  49123. * Get the port number from the host. Or guess it based on the connection type.
  49124. *
  49125. * @param {Request} req Incoming HTTP request.
  49126. *
  49127. * @return {String} The port number.
  49128. *
  49129. * @api private
  49130. */
  49131. common.getPort = function(req) {
  49132. var res = req.headers.host ? req.headers.host.match(/:(\d+)/) : '';
  49133. return res ?
  49134. res[1] :
  49135. common.hasEncryptedConnection(req) ? '443' : '80';
  49136. };
  49137. /**
  49138. * Check if the request has an encrypted connection.
  49139. *
  49140. * @param {Request} req Incoming HTTP request.
  49141. *
  49142. * @return {Boolean} Whether the connection is encrypted or not.
  49143. *
  49144. * @api private
  49145. */
  49146. common.hasEncryptedConnection = function(req) {
  49147. return Boolean(req.connection.encrypted || req.connection.pair);
  49148. };
  49149. /**
  49150. * OS-agnostic join (doesn't break on URLs like path.join does on Windows)>
  49151. *
  49152. * @return {String} The generated path.
  49153. *
  49154. * @api private
  49155. */
  49156. common.urlJoin = function() {
  49157. //
  49158. // We do not want to mess with the query string. All we want to touch is the path.
  49159. //
  49160. var args = Array.prototype.slice.call(arguments),
  49161. lastIndex = args.length - 1,
  49162. last = args[lastIndex],
  49163. lastSegs = last.split('?'),
  49164. retSegs;
  49165. args[lastIndex] = lastSegs.shift();
  49166. //
  49167. // Join all strings, but remove empty strings so we don't get extra slashes from
  49168. // joining e.g. ['', 'am']
  49169. //
  49170. retSegs = [
  49171. args.filter(Boolean).join('/')
  49172. .replace(/\/+/g, '/')
  49173. .replace('http:/', 'http://')
  49174. .replace('https:/', 'https://')
  49175. ];
  49176. // Only join the query string if it exists so we don't have trailing a '?'
  49177. // on every request
  49178. // Handle case where there could be multiple ? in the URL.
  49179. retSegs.push.apply(retSegs, lastSegs);
  49180. return retSegs.join('?')
  49181. };
  49182. /**
  49183. * Rewrites or removes the domain of a cookie header
  49184. *
  49185. * @param {String|Array} Header
  49186. * @param {Object} Config, mapping of domain to rewritten domain.
  49187. * '*' key to match any domain, null value to remove the domain.
  49188. *
  49189. * @api private
  49190. */
  49191. common.rewriteCookieProperty = function rewriteCookieProperty(header, config, property) {
  49192. if (Array.isArray(header)) {
  49193. return header.map(function (headerElement) {
  49194. return rewriteCookieProperty(headerElement, config, property);
  49195. });
  49196. }
  49197. return header.replace(new RegExp("(;\\s*" + property + "=)([^;]+)", 'i'), function(match, prefix, previousValue) {
  49198. var newValue;
  49199. if (previousValue in config) {
  49200. newValue = config[previousValue];
  49201. } else if ('*' in config) {
  49202. newValue = config['*'];
  49203. } else {
  49204. //no match, return previous value
  49205. return match;
  49206. }
  49207. if (newValue) {
  49208. //replace value
  49209. return prefix + newValue;
  49210. } else {
  49211. //remove value
  49212. return '';
  49213. }
  49214. });
  49215. };
  49216. /**
  49217. * Check the host and see if it potentially has a port in it (keep it simple)
  49218. *
  49219. * @returns {Boolean} Whether we have one or not
  49220. *
  49221. * @api private
  49222. */
  49223. function hasPort(host) {
  49224. return !!~host.indexOf(':');
  49225. }}(common$3));
  49226. var url$1 = require$$0__default$5,
  49227. common$2 = common$3;
  49228. var redirectRegex = /^201|30(1|2|7|8)$/;
  49229. /*!
  49230. * Array of passes.
  49231. *
  49232. * A `pass` is just a function that is executed on `req, res, options`
  49233. * so that you can easily add new checks while still keeping the base
  49234. * flexible.
  49235. */
  49236. var webOutgoing = { // <--
  49237. /**
  49238. * If is a HTTP 1.0 request, remove chunk headers
  49239. *
  49240. * @param {ClientRequest} Req Request object
  49241. * @param {IncomingMessage} Res Response object
  49242. * @param {proxyResponse} Res Response object from the proxy request
  49243. *
  49244. * @api private
  49245. */
  49246. removeChunked: function removeChunked(req, res, proxyRes) {
  49247. if (req.httpVersion === '1.0') {
  49248. delete proxyRes.headers['transfer-encoding'];
  49249. }
  49250. },
  49251. /**
  49252. * If is a HTTP 1.0 request, set the correct connection header
  49253. * or if connection header not present, then use `keep-alive`
  49254. *
  49255. * @param {ClientRequest} Req Request object
  49256. * @param {IncomingMessage} Res Response object
  49257. * @param {proxyResponse} Res Response object from the proxy request
  49258. *
  49259. * @api private
  49260. */
  49261. setConnection: function setConnection(req, res, proxyRes) {
  49262. if (req.httpVersion === '1.0') {
  49263. proxyRes.headers.connection = req.headers.connection || 'close';
  49264. } else if (req.httpVersion !== '2.0' && !proxyRes.headers.connection) {
  49265. proxyRes.headers.connection = req.headers.connection || 'keep-alive';
  49266. }
  49267. },
  49268. setRedirectHostRewrite: function setRedirectHostRewrite(req, res, proxyRes, options) {
  49269. if ((options.hostRewrite || options.autoRewrite || options.protocolRewrite)
  49270. && proxyRes.headers['location']
  49271. && redirectRegex.test(proxyRes.statusCode)) {
  49272. var target = url$1.parse(options.target);
  49273. var u = url$1.parse(proxyRes.headers['location']);
  49274. // make sure the redirected host matches the target host before rewriting
  49275. if (target.host != u.host) {
  49276. return;
  49277. }
  49278. if (options.hostRewrite) {
  49279. u.host = options.hostRewrite;
  49280. } else if (options.autoRewrite) {
  49281. u.host = req.headers['host'];
  49282. }
  49283. if (options.protocolRewrite) {
  49284. u.protocol = options.protocolRewrite;
  49285. }
  49286. proxyRes.headers['location'] = u.format();
  49287. }
  49288. },
  49289. /**
  49290. * Copy headers from proxyResponse to response
  49291. * set each header in response object.
  49292. *
  49293. * @param {ClientRequest} Req Request object
  49294. * @param {IncomingMessage} Res Response object
  49295. * @param {proxyResponse} Res Response object from the proxy request
  49296. * @param {Object} Options options.cookieDomainRewrite: Config to rewrite cookie domain
  49297. *
  49298. * @api private
  49299. */
  49300. writeHeaders: function writeHeaders(req, res, proxyRes, options) {
  49301. var rewriteCookieDomainConfig = options.cookieDomainRewrite,
  49302. rewriteCookiePathConfig = options.cookiePathRewrite,
  49303. preserveHeaderKeyCase = options.preserveHeaderKeyCase,
  49304. rawHeaderKeyMap,
  49305. setHeader = function(key, header) {
  49306. if (header == undefined) return;
  49307. if (rewriteCookieDomainConfig && key.toLowerCase() === 'set-cookie') {
  49308. header = common$2.rewriteCookieProperty(header, rewriteCookieDomainConfig, 'domain');
  49309. }
  49310. if (rewriteCookiePathConfig && key.toLowerCase() === 'set-cookie') {
  49311. header = common$2.rewriteCookieProperty(header, rewriteCookiePathConfig, 'path');
  49312. }
  49313. res.setHeader(String(key).trim(), header);
  49314. };
  49315. if (typeof rewriteCookieDomainConfig === 'string') { //also test for ''
  49316. rewriteCookieDomainConfig = { '*': rewriteCookieDomainConfig };
  49317. }
  49318. if (typeof rewriteCookiePathConfig === 'string') { //also test for ''
  49319. rewriteCookiePathConfig = { '*': rewriteCookiePathConfig };
  49320. }
  49321. // message.rawHeaders is added in: v0.11.6
  49322. // https://nodejs.org/api/http.html#http_message_rawheaders
  49323. if (preserveHeaderKeyCase && proxyRes.rawHeaders != undefined) {
  49324. rawHeaderKeyMap = {};
  49325. for (var i = 0; i < proxyRes.rawHeaders.length; i += 2) {
  49326. var key = proxyRes.rawHeaders[i];
  49327. rawHeaderKeyMap[key.toLowerCase()] = key;
  49328. }
  49329. }
  49330. Object.keys(proxyRes.headers).forEach(function(key) {
  49331. var header = proxyRes.headers[key];
  49332. if (preserveHeaderKeyCase && rawHeaderKeyMap) {
  49333. key = rawHeaderKeyMap[key] || key;
  49334. }
  49335. setHeader(key, header);
  49336. });
  49337. },
  49338. /**
  49339. * Set the statusCode from the proxyResponse
  49340. *
  49341. * @param {ClientRequest} Req Request object
  49342. * @param {IncomingMessage} Res Response object
  49343. * @param {proxyResponse} Res Response object from the proxy request
  49344. *
  49345. * @api private
  49346. */
  49347. writeStatusCode: function writeStatusCode(req, res, proxyRes) {
  49348. // From Node.js docs: response.writeHead(statusCode[, statusMessage][, headers])
  49349. if(proxyRes.statusMessage) {
  49350. res.statusCode = proxyRes.statusCode;
  49351. res.statusMessage = proxyRes.statusMessage;
  49352. } else {
  49353. res.statusCode = proxyRes.statusCode;
  49354. }
  49355. }
  49356. };
  49357. var followRedirects$1 = {exports: {}};
  49358. var debug$5;
  49359. var debug_1 = function () {
  49360. if (!debug$5) {
  49361. try {
  49362. /* eslint global-require: off */
  49363. debug$5 = require("debug")("follow-redirects");
  49364. }
  49365. catch (error) { /* */ }
  49366. if (typeof debug$5 !== "function") {
  49367. debug$5 = function () { /* */ };
  49368. }
  49369. }
  49370. debug$5.apply(null, arguments);
  49371. };
  49372. var url = require$$0__default$5;
  49373. var URL$1 = url.URL;
  49374. var http$1 = require$$1__default$1;
  49375. var https$1 = require$$1__default$3;
  49376. var Writable = require$$0__default$3.Writable;
  49377. var assert = require$$5__default;
  49378. var debug$4 = debug_1;
  49379. // Create handlers that pass events from native requests
  49380. var events = ["abort", "aborted", "connect", "error", "socket", "timeout"];
  49381. var eventHandlers = Object.create(null);
  49382. events.forEach(function (event) {
  49383. eventHandlers[event] = function (arg1, arg2, arg3) {
  49384. this._redirectable.emit(event, arg1, arg2, arg3);
  49385. };
  49386. });
  49387. // Error types with codes
  49388. var RedirectionError = createErrorType(
  49389. "ERR_FR_REDIRECTION_FAILURE",
  49390. "Redirected request failed"
  49391. );
  49392. var TooManyRedirectsError = createErrorType(
  49393. "ERR_FR_TOO_MANY_REDIRECTS",
  49394. "Maximum number of redirects exceeded"
  49395. );
  49396. var MaxBodyLengthExceededError = createErrorType(
  49397. "ERR_FR_MAX_BODY_LENGTH_EXCEEDED",
  49398. "Request body larger than maxBodyLength limit"
  49399. );
  49400. var WriteAfterEndError = createErrorType(
  49401. "ERR_STREAM_WRITE_AFTER_END",
  49402. "write after end"
  49403. );
  49404. // An HTTP(S) request that can be redirected
  49405. function RedirectableRequest(options, responseCallback) {
  49406. // Initialize the request
  49407. Writable.call(this);
  49408. this._sanitizeOptions(options);
  49409. this._options = options;
  49410. this._ended = false;
  49411. this._ending = false;
  49412. this._redirectCount = 0;
  49413. this._redirects = [];
  49414. this._requestBodyLength = 0;
  49415. this._requestBodyBuffers = [];
  49416. // Attach a callback if passed
  49417. if (responseCallback) {
  49418. this.on("response", responseCallback);
  49419. }
  49420. // React to responses of native requests
  49421. var self = this;
  49422. this._onNativeResponse = function (response) {
  49423. self._processResponse(response);
  49424. };
  49425. // Perform the first request
  49426. this._performRequest();
  49427. }
  49428. RedirectableRequest.prototype = Object.create(Writable.prototype);
  49429. RedirectableRequest.prototype.abort = function () {
  49430. abortRequest(this._currentRequest);
  49431. this.emit("abort");
  49432. };
  49433. // Writes buffered data to the current native request
  49434. RedirectableRequest.prototype.write = function (data, encoding, callback) {
  49435. // Writing is not allowed if end has been called
  49436. if (this._ending) {
  49437. throw new WriteAfterEndError();
  49438. }
  49439. // Validate input and shift parameters if necessary
  49440. if (!(typeof data === "string" || typeof data === "object" && ("length" in data))) {
  49441. throw new TypeError("data should be a string, Buffer or Uint8Array");
  49442. }
  49443. if (typeof encoding === "function") {
  49444. callback = encoding;
  49445. encoding = null;
  49446. }
  49447. // Ignore empty buffers, since writing them doesn't invoke the callback
  49448. // https://github.com/nodejs/node/issues/22066
  49449. if (data.length === 0) {
  49450. if (callback) {
  49451. callback();
  49452. }
  49453. return;
  49454. }
  49455. // Only write when we don't exceed the maximum body length
  49456. if (this._requestBodyLength + data.length <= this._options.maxBodyLength) {
  49457. this._requestBodyLength += data.length;
  49458. this._requestBodyBuffers.push({ data: data, encoding: encoding });
  49459. this._currentRequest.write(data, encoding, callback);
  49460. }
  49461. // Error when we exceed the maximum body length
  49462. else {
  49463. this.emit("error", new MaxBodyLengthExceededError());
  49464. this.abort();
  49465. }
  49466. };
  49467. // Ends the current native request
  49468. RedirectableRequest.prototype.end = function (data, encoding, callback) {
  49469. // Shift parameters if necessary
  49470. if (typeof data === "function") {
  49471. callback = data;
  49472. data = encoding = null;
  49473. }
  49474. else if (typeof encoding === "function") {
  49475. callback = encoding;
  49476. encoding = null;
  49477. }
  49478. // Write data if needed and end
  49479. if (!data) {
  49480. this._ended = this._ending = true;
  49481. this._currentRequest.end(null, null, callback);
  49482. }
  49483. else {
  49484. var self = this;
  49485. var currentRequest = this._currentRequest;
  49486. this.write(data, encoding, function () {
  49487. self._ended = true;
  49488. currentRequest.end(null, null, callback);
  49489. });
  49490. this._ending = true;
  49491. }
  49492. };
  49493. // Sets a header value on the current native request
  49494. RedirectableRequest.prototype.setHeader = function (name, value) {
  49495. this._options.headers[name] = value;
  49496. this._currentRequest.setHeader(name, value);
  49497. };
  49498. // Clears a header value on the current native request
  49499. RedirectableRequest.prototype.removeHeader = function (name) {
  49500. delete this._options.headers[name];
  49501. this._currentRequest.removeHeader(name);
  49502. };
  49503. // Global timeout for all underlying requests
  49504. RedirectableRequest.prototype.setTimeout = function (msecs, callback) {
  49505. var self = this;
  49506. // Destroys the socket on timeout
  49507. function destroyOnTimeout(socket) {
  49508. socket.setTimeout(msecs);
  49509. socket.removeListener("timeout", socket.destroy);
  49510. socket.addListener("timeout", socket.destroy);
  49511. }
  49512. // Sets up a timer to trigger a timeout event
  49513. function startTimer(socket) {
  49514. if (self._timeout) {
  49515. clearTimeout(self._timeout);
  49516. }
  49517. self._timeout = setTimeout(function () {
  49518. self.emit("timeout");
  49519. clearTimer();
  49520. }, msecs);
  49521. destroyOnTimeout(socket);
  49522. }
  49523. // Stops a timeout from triggering
  49524. function clearTimer() {
  49525. // Clear the timeout
  49526. if (self._timeout) {
  49527. clearTimeout(self._timeout);
  49528. self._timeout = null;
  49529. }
  49530. // Clean up all attached listeners
  49531. self.removeListener("abort", clearTimer);
  49532. self.removeListener("error", clearTimer);
  49533. self.removeListener("response", clearTimer);
  49534. if (callback) {
  49535. self.removeListener("timeout", callback);
  49536. }
  49537. if (!self.socket) {
  49538. self._currentRequest.removeListener("socket", startTimer);
  49539. }
  49540. }
  49541. // Attach callback if passed
  49542. if (callback) {
  49543. this.on("timeout", callback);
  49544. }
  49545. // Start the timer if or when the socket is opened
  49546. if (this.socket) {
  49547. startTimer(this.socket);
  49548. }
  49549. else {
  49550. this._currentRequest.once("socket", startTimer);
  49551. }
  49552. // Clean up on events
  49553. this.on("socket", destroyOnTimeout);
  49554. this.on("abort", clearTimer);
  49555. this.on("error", clearTimer);
  49556. this.on("response", clearTimer);
  49557. return this;
  49558. };
  49559. // Proxy all other public ClientRequest methods
  49560. [
  49561. "flushHeaders", "getHeader",
  49562. "setNoDelay", "setSocketKeepAlive",
  49563. ].forEach(function (method) {
  49564. RedirectableRequest.prototype[method] = function (a, b) {
  49565. return this._currentRequest[method](a, b);
  49566. };
  49567. });
  49568. // Proxy all public ClientRequest properties
  49569. ["aborted", "connection", "socket"].forEach(function (property) {
  49570. Object.defineProperty(RedirectableRequest.prototype, property, {
  49571. get: function () { return this._currentRequest[property]; },
  49572. });
  49573. });
  49574. RedirectableRequest.prototype._sanitizeOptions = function (options) {
  49575. // Ensure headers are always present
  49576. if (!options.headers) {
  49577. options.headers = {};
  49578. }
  49579. // Since http.request treats host as an alias of hostname,
  49580. // but the url module interprets host as hostname plus port,
  49581. // eliminate the host property to avoid confusion.
  49582. if (options.host) {
  49583. // Use hostname if set, because it has precedence
  49584. if (!options.hostname) {
  49585. options.hostname = options.host;
  49586. }
  49587. delete options.host;
  49588. }
  49589. // Complete the URL object when necessary
  49590. if (!options.pathname && options.path) {
  49591. var searchPos = options.path.indexOf("?");
  49592. if (searchPos < 0) {
  49593. options.pathname = options.path;
  49594. }
  49595. else {
  49596. options.pathname = options.path.substring(0, searchPos);
  49597. options.search = options.path.substring(searchPos);
  49598. }
  49599. }
  49600. };
  49601. // Executes the next native request (initial or redirect)
  49602. RedirectableRequest.prototype._performRequest = function () {
  49603. // Load the native protocol
  49604. var protocol = this._options.protocol;
  49605. var nativeProtocol = this._options.nativeProtocols[protocol];
  49606. if (!nativeProtocol) {
  49607. this.emit("error", new TypeError("Unsupported protocol " + protocol));
  49608. return;
  49609. }
  49610. // If specified, use the agent corresponding to the protocol
  49611. // (HTTP and HTTPS use different types of agents)
  49612. if (this._options.agents) {
  49613. var scheme = protocol.substr(0, protocol.length - 1);
  49614. this._options.agent = this._options.agents[scheme];
  49615. }
  49616. // Create the native request
  49617. var request = this._currentRequest =
  49618. nativeProtocol.request(this._options, this._onNativeResponse);
  49619. this._currentUrl = url.format(this._options);
  49620. // Set up event handlers
  49621. request._redirectable = this;
  49622. for (var e = 0; e < events.length; e++) {
  49623. request.on(events[e], eventHandlers[events[e]]);
  49624. }
  49625. // End a redirected request
  49626. // (The first request must be ended explicitly with RedirectableRequest#end)
  49627. if (this._isRedirect) {
  49628. // Write the request entity and end.
  49629. var i = 0;
  49630. var self = this;
  49631. var buffers = this._requestBodyBuffers;
  49632. (function writeNext(error) {
  49633. // Only write if this request has not been redirected yet
  49634. /* istanbul ignore else */
  49635. if (request === self._currentRequest) {
  49636. // Report any write errors
  49637. /* istanbul ignore if */
  49638. if (error) {
  49639. self.emit("error", error);
  49640. }
  49641. // Write the next buffer if there are still left
  49642. else if (i < buffers.length) {
  49643. var buffer = buffers[i++];
  49644. /* istanbul ignore else */
  49645. if (!request.finished) {
  49646. request.write(buffer.data, buffer.encoding, writeNext);
  49647. }
  49648. }
  49649. // End the request if `end` has been called on us
  49650. else if (self._ended) {
  49651. request.end();
  49652. }
  49653. }
  49654. }());
  49655. }
  49656. };
  49657. // Processes a response from the current native request
  49658. RedirectableRequest.prototype._processResponse = function (response) {
  49659. // Store the redirected response
  49660. var statusCode = response.statusCode;
  49661. if (this._options.trackRedirects) {
  49662. this._redirects.push({
  49663. url: this._currentUrl,
  49664. headers: response.headers,
  49665. statusCode: statusCode,
  49666. });
  49667. }
  49668. // RFC7231§6.4: The 3xx (Redirection) class of status code indicates
  49669. // that further action needs to be taken by the user agent in order to
  49670. // fulfill the request. If a Location header field is provided,
  49671. // the user agent MAY automatically redirect its request to the URI
  49672. // referenced by the Location field value,
  49673. // even if the specific status code is not understood.
  49674. var location = response.headers.location;
  49675. if (location && this._options.followRedirects !== false &&
  49676. statusCode >= 300 && statusCode < 400) {
  49677. // Abort the current request
  49678. abortRequest(this._currentRequest);
  49679. // Discard the remainder of the response to avoid waiting for data
  49680. response.destroy();
  49681. // RFC7231§6.4: A client SHOULD detect and intervene
  49682. // in cyclical redirections (i.e., "infinite" redirection loops).
  49683. if (++this._redirectCount > this._options.maxRedirects) {
  49684. this.emit("error", new TooManyRedirectsError());
  49685. return;
  49686. }
  49687. // RFC7231§6.4: Automatic redirection needs to done with
  49688. // care for methods not known to be safe, […]
  49689. // RFC7231§6.4.2–3: For historical reasons, a user agent MAY change
  49690. // the request method from POST to GET for the subsequent request.
  49691. if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" ||
  49692. // RFC7231§6.4.4: The 303 (See Other) status code indicates that
  49693. // the server is redirecting the user agent to a different resource […]
  49694. // A user agent can perform a retrieval request targeting that URI
  49695. // (a GET or HEAD request if using HTTP) […]
  49696. (statusCode === 303) && !/^(?:GET|HEAD)$/.test(this._options.method)) {
  49697. this._options.method = "GET";
  49698. // Drop a possible entity and headers related to it
  49699. this._requestBodyBuffers = [];
  49700. removeMatchingHeaders(/^content-/i, this._options.headers);
  49701. }
  49702. // Drop the Host header, as the redirect might lead to a different host
  49703. var currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers);
  49704. // If the redirect is relative, carry over the host of the last request
  49705. var currentUrlParts = url.parse(this._currentUrl);
  49706. var currentHost = currentHostHeader || currentUrlParts.host;
  49707. var currentUrl = /^\w+:/.test(location) ? this._currentUrl :
  49708. url.format(Object.assign(currentUrlParts, { host: currentHost }));
  49709. // Determine the URL of the redirection
  49710. var redirectUrl;
  49711. try {
  49712. redirectUrl = url.resolve(currentUrl, location);
  49713. }
  49714. catch (cause) {
  49715. this.emit("error", new RedirectionError(cause));
  49716. return;
  49717. }
  49718. // Create the redirected request
  49719. debug$4("redirecting to", redirectUrl);
  49720. this._isRedirect = true;
  49721. var redirectUrlParts = url.parse(redirectUrl);
  49722. Object.assign(this._options, redirectUrlParts);
  49723. // Drop the Authorization header if redirecting to another domain
  49724. if (!(redirectUrlParts.host === currentHost || isSubdomainOf(redirectUrlParts.host, currentHost))) {
  49725. removeMatchingHeaders(/^authorization$/i, this._options.headers);
  49726. }
  49727. // Evaluate the beforeRedirect callback
  49728. if (typeof this._options.beforeRedirect === "function") {
  49729. var responseDetails = { headers: response.headers };
  49730. try {
  49731. this._options.beforeRedirect.call(null, this._options, responseDetails);
  49732. }
  49733. catch (err) {
  49734. this.emit("error", err);
  49735. return;
  49736. }
  49737. this._sanitizeOptions(this._options);
  49738. }
  49739. // Perform the redirected request
  49740. try {
  49741. this._performRequest();
  49742. }
  49743. catch (cause) {
  49744. this.emit("error", new RedirectionError(cause));
  49745. }
  49746. }
  49747. else {
  49748. // The response is not a redirect; return it as-is
  49749. response.responseUrl = this._currentUrl;
  49750. response.redirects = this._redirects;
  49751. this.emit("response", response);
  49752. // Clean up
  49753. this._requestBodyBuffers = [];
  49754. }
  49755. };
  49756. // Wraps the key/value object of protocols with redirect functionality
  49757. function wrap(protocols) {
  49758. // Default settings
  49759. var exports = {
  49760. maxRedirects: 21,
  49761. maxBodyLength: 10 * 1024 * 1024,
  49762. };
  49763. // Wrap each protocol
  49764. var nativeProtocols = {};
  49765. Object.keys(protocols).forEach(function (scheme) {
  49766. var protocol = scheme + ":";
  49767. var nativeProtocol = nativeProtocols[protocol] = protocols[scheme];
  49768. var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol);
  49769. // Executes a request, following redirects
  49770. function request(input, options, callback) {
  49771. // Parse parameters
  49772. if (typeof input === "string") {
  49773. var urlStr = input;
  49774. try {
  49775. input = urlToOptions(new URL$1(urlStr));
  49776. }
  49777. catch (err) {
  49778. /* istanbul ignore next */
  49779. input = url.parse(urlStr);
  49780. }
  49781. }
  49782. else if (URL$1 && (input instanceof URL$1)) {
  49783. input = urlToOptions(input);
  49784. }
  49785. else {
  49786. callback = options;
  49787. options = input;
  49788. input = { protocol: protocol };
  49789. }
  49790. if (typeof options === "function") {
  49791. callback = options;
  49792. options = null;
  49793. }
  49794. // Set defaults
  49795. options = Object.assign({
  49796. maxRedirects: exports.maxRedirects,
  49797. maxBodyLength: exports.maxBodyLength,
  49798. }, input, options);
  49799. options.nativeProtocols = nativeProtocols;
  49800. assert.equal(options.protocol, protocol, "protocol mismatch");
  49801. debug$4("options", options);
  49802. return new RedirectableRequest(options, callback);
  49803. }
  49804. // Executes a GET request, following redirects
  49805. function get(input, options, callback) {
  49806. var wrappedRequest = wrappedProtocol.request(input, options, callback);
  49807. wrappedRequest.end();
  49808. return wrappedRequest;
  49809. }
  49810. // Expose the properties on the wrapped protocol
  49811. Object.defineProperties(wrappedProtocol, {
  49812. request: { value: request, configurable: true, enumerable: true, writable: true },
  49813. get: { value: get, configurable: true, enumerable: true, writable: true },
  49814. });
  49815. });
  49816. return exports;
  49817. }
  49818. /* istanbul ignore next */
  49819. function noop$1() { /* empty */ }
  49820. // from https://github.com/nodejs/node/blob/master/lib/internal/url.js
  49821. function urlToOptions(urlObject) {
  49822. var options = {
  49823. protocol: urlObject.protocol,
  49824. hostname: urlObject.hostname.startsWith("[") ?
  49825. /* istanbul ignore next */
  49826. urlObject.hostname.slice(1, -1) :
  49827. urlObject.hostname,
  49828. hash: urlObject.hash,
  49829. search: urlObject.search,
  49830. pathname: urlObject.pathname,
  49831. path: urlObject.pathname + urlObject.search,
  49832. href: urlObject.href,
  49833. };
  49834. if (urlObject.port !== "") {
  49835. options.port = Number(urlObject.port);
  49836. }
  49837. return options;
  49838. }
  49839. function removeMatchingHeaders(regex, headers) {
  49840. var lastValue;
  49841. for (var header in headers) {
  49842. if (regex.test(header)) {
  49843. lastValue = headers[header];
  49844. delete headers[header];
  49845. }
  49846. }
  49847. return (lastValue === null || typeof lastValue === "undefined") ?
  49848. undefined : String(lastValue).trim();
  49849. }
  49850. function createErrorType(code, defaultMessage) {
  49851. function CustomError(cause) {
  49852. Error.captureStackTrace(this, this.constructor);
  49853. if (!cause) {
  49854. this.message = defaultMessage;
  49855. }
  49856. else {
  49857. this.message = defaultMessage + ": " + cause.message;
  49858. this.cause = cause;
  49859. }
  49860. }
  49861. CustomError.prototype = new Error();
  49862. CustomError.prototype.constructor = CustomError;
  49863. CustomError.prototype.name = "Error [" + code + "]";
  49864. CustomError.prototype.code = code;
  49865. return CustomError;
  49866. }
  49867. function abortRequest(request) {
  49868. for (var e = 0; e < events.length; e++) {
  49869. request.removeListener(events[e], eventHandlers[events[e]]);
  49870. }
  49871. request.on("error", noop$1);
  49872. request.abort();
  49873. }
  49874. function isSubdomainOf(subdomain, domain) {
  49875. const dot = subdomain.length - domain.length - 1;
  49876. return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain);
  49877. }
  49878. // Exports
  49879. followRedirects$1.exports = wrap({ http: http$1, https: https$1 });
  49880. followRedirects$1.exports.wrap = wrap;
  49881. var httpNative = require$$1__default$1,
  49882. httpsNative = require$$1__default$3,
  49883. web_o = webOutgoing,
  49884. common$1 = common$3,
  49885. followRedirects = followRedirects$1.exports;
  49886. web_o = Object.keys(web_o).map(function(pass) {
  49887. return web_o[pass];
  49888. });
  49889. var nativeAgents = { http: httpNative, https: httpsNative };
  49890. /*!
  49891. * Array of passes.
  49892. *
  49893. * A `pass` is just a function that is executed on `req, res, options`
  49894. * so that you can easily add new checks while still keeping the base
  49895. * flexible.
  49896. */
  49897. var webIncoming = {
  49898. /**
  49899. * Sets `content-length` to '0' if request is of DELETE type.
  49900. *
  49901. * @param {ClientRequest} Req Request object
  49902. * @param {IncomingMessage} Res Response object
  49903. * @param {Object} Options Config object passed to the proxy
  49904. *
  49905. * @api private
  49906. */
  49907. deleteLength: function deleteLength(req, res, options) {
  49908. if((req.method === 'DELETE' || req.method === 'OPTIONS')
  49909. && !req.headers['content-length']) {
  49910. req.headers['content-length'] = '0';
  49911. delete req.headers['transfer-encoding'];
  49912. }
  49913. },
  49914. /**
  49915. * Sets timeout in request socket if it was specified in options.
  49916. *
  49917. * @param {ClientRequest} Req Request object
  49918. * @param {IncomingMessage} Res Response object
  49919. * @param {Object} Options Config object passed to the proxy
  49920. *
  49921. * @api private
  49922. */
  49923. timeout: function timeout(req, res, options) {
  49924. if(options.timeout) {
  49925. req.socket.setTimeout(options.timeout);
  49926. }
  49927. },
  49928. /**
  49929. * Sets `x-forwarded-*` headers if specified in config.
  49930. *
  49931. * @param {ClientRequest} Req Request object
  49932. * @param {IncomingMessage} Res Response object
  49933. * @param {Object} Options Config object passed to the proxy
  49934. *
  49935. * @api private
  49936. */
  49937. XHeaders: function XHeaders(req, res, options) {
  49938. if(!options.xfwd) return;
  49939. var encrypted = req.isSpdy || common$1.hasEncryptedConnection(req);
  49940. var values = {
  49941. for : req.connection.remoteAddress || req.socket.remoteAddress,
  49942. port : common$1.getPort(req),
  49943. proto: encrypted ? 'https' : 'http'
  49944. };
  49945. ['for', 'port', 'proto'].forEach(function(header) {
  49946. req.headers['x-forwarded-' + header] =
  49947. (req.headers['x-forwarded-' + header] || '') +
  49948. (req.headers['x-forwarded-' + header] ? ',' : '') +
  49949. values[header];
  49950. });
  49951. req.headers['x-forwarded-host'] = req.headers['x-forwarded-host'] || req.headers['host'] || '';
  49952. },
  49953. /**
  49954. * Does the actual proxying. If `forward` is enabled fires up
  49955. * a ForwardStream, same happens for ProxyStream. The request
  49956. * just dies otherwise.
  49957. *
  49958. * @param {ClientRequest} Req Request object
  49959. * @param {IncomingMessage} Res Response object
  49960. * @param {Object} Options Config object passed to the proxy
  49961. *
  49962. * @api private
  49963. */
  49964. stream: function stream(req, res, options, _, server, clb) {
  49965. // And we begin!
  49966. server.emit('start', req, res, options.target || options.forward);
  49967. var agents = options.followRedirects ? followRedirects : nativeAgents;
  49968. var http = agents.http;
  49969. var https = agents.https;
  49970. if(options.forward) {
  49971. // If forward enable, so just pipe the request
  49972. var forwardReq = (options.forward.protocol === 'https:' ? https : http).request(
  49973. common$1.setupOutgoing(options.ssl || {}, options, req, 'forward')
  49974. );
  49975. // error handler (e.g. ECONNRESET, ECONNREFUSED)
  49976. // Handle errors on incoming request as well as it makes sense to
  49977. var forwardError = createErrorHandler(forwardReq, options.forward);
  49978. req.on('error', forwardError);
  49979. forwardReq.on('error', forwardError);
  49980. (options.buffer || req).pipe(forwardReq);
  49981. if(!options.target) { return res.end(); }
  49982. }
  49983. // Request initalization
  49984. var proxyReq = (options.target.protocol === 'https:' ? https : http).request(
  49985. common$1.setupOutgoing(options.ssl || {}, options, req)
  49986. );
  49987. // Enable developers to modify the proxyReq before headers are sent
  49988. proxyReq.on('socket', function(socket) {
  49989. if(server && !proxyReq.getHeader('expect')) {
  49990. server.emit('proxyReq', proxyReq, req, res, options);
  49991. }
  49992. });
  49993. // allow outgoing socket to timeout so that we could
  49994. // show an error page at the initial request
  49995. if(options.proxyTimeout) {
  49996. proxyReq.setTimeout(options.proxyTimeout, function() {
  49997. proxyReq.abort();
  49998. });
  49999. }
  50000. // Ensure we abort proxy if request is aborted
  50001. req.on('aborted', function () {
  50002. proxyReq.abort();
  50003. });
  50004. // handle errors in proxy and incoming request, just like for forward proxy
  50005. var proxyError = createErrorHandler(proxyReq, options.target);
  50006. req.on('error', proxyError);
  50007. proxyReq.on('error', proxyError);
  50008. function createErrorHandler(proxyReq, url) {
  50009. return function proxyError(err) {
  50010. if (req.socket.destroyed && err.code === 'ECONNRESET') {
  50011. server.emit('econnreset', err, req, res, url);
  50012. return proxyReq.abort();
  50013. }
  50014. if (clb) {
  50015. clb(err, req, res, url);
  50016. } else {
  50017. server.emit('error', err, req, res, url);
  50018. }
  50019. }
  50020. }
  50021. (options.buffer || req).pipe(proxyReq);
  50022. proxyReq.on('response', function(proxyRes) {
  50023. if(server) { server.emit('proxyRes', proxyRes, req, res); }
  50024. if(!res.headersSent && !options.selfHandleResponse) {
  50025. for(var i=0; i < web_o.length; i++) {
  50026. if(web_o[i](req, res, proxyRes, options)) { break; }
  50027. }
  50028. }
  50029. if (!res.finished) {
  50030. // Allow us to listen when the proxy has completed
  50031. proxyRes.on('end', function () {
  50032. if (server) server.emit('end', req, res, proxyRes);
  50033. });
  50034. // We pipe to the response unless its expected to be handled by the user
  50035. if (!options.selfHandleResponse) proxyRes.pipe(res);
  50036. } else {
  50037. if (server) server.emit('end', req, res, proxyRes);
  50038. }
  50039. });
  50040. }
  50041. };
  50042. var http = require$$1__default$1,
  50043. https = require$$1__default$3,
  50044. common = common$3;
  50045. /*!
  50046. * Array of passes.
  50047. *
  50048. * A `pass` is just a function that is executed on `req, socket, options`
  50049. * so that you can easily add new checks while still keeping the base
  50050. * flexible.
  50051. */
  50052. /*
  50053. * Websockets Passes
  50054. *
  50055. */
  50056. var wsIncoming = {
  50057. /**
  50058. * WebSocket requests must have the `GET` method and
  50059. * the `upgrade:websocket` header
  50060. *
  50061. * @param {ClientRequest} Req Request object
  50062. * @param {Socket} Websocket
  50063. *
  50064. * @api private
  50065. */
  50066. checkMethodAndHeader : function checkMethodAndHeader(req, socket) {
  50067. if (req.method !== 'GET' || !req.headers.upgrade) {
  50068. socket.destroy();
  50069. return true;
  50070. }
  50071. if (req.headers.upgrade.toLowerCase() !== 'websocket') {
  50072. socket.destroy();
  50073. return true;
  50074. }
  50075. },
  50076. /**
  50077. * Sets `x-forwarded-*` headers if specified in config.
  50078. *
  50079. * @param {ClientRequest} Req Request object
  50080. * @param {Socket} Websocket
  50081. * @param {Object} Options Config object passed to the proxy
  50082. *
  50083. * @api private
  50084. */
  50085. XHeaders : function XHeaders(req, socket, options) {
  50086. if(!options.xfwd) return;
  50087. var values = {
  50088. for : req.connection.remoteAddress || req.socket.remoteAddress,
  50089. port : common.getPort(req),
  50090. proto: common.hasEncryptedConnection(req) ? 'wss' : 'ws'
  50091. };
  50092. ['for', 'port', 'proto'].forEach(function(header) {
  50093. req.headers['x-forwarded-' + header] =
  50094. (req.headers['x-forwarded-' + header] || '') +
  50095. (req.headers['x-forwarded-' + header] ? ',' : '') +
  50096. values[header];
  50097. });
  50098. },
  50099. /**
  50100. * Does the actual proxying. Make the request and upgrade it
  50101. * send the Switching Protocols request and pipe the sockets.
  50102. *
  50103. * @param {ClientRequest} Req Request object
  50104. * @param {Socket} Websocket
  50105. * @param {Object} Options Config object passed to the proxy
  50106. *
  50107. * @api private
  50108. */
  50109. stream : function stream(req, socket, options, head, server, clb) {
  50110. var createHttpHeader = function(line, headers) {
  50111. return Object.keys(headers).reduce(function (head, key) {
  50112. var value = headers[key];
  50113. if (!Array.isArray(value)) {
  50114. head.push(key + ': ' + value);
  50115. return head;
  50116. }
  50117. for (var i = 0; i < value.length; i++) {
  50118. head.push(key + ': ' + value[i]);
  50119. }
  50120. return head;
  50121. }, [line])
  50122. .join('\r\n') + '\r\n\r\n';
  50123. };
  50124. common.setupSocket(socket);
  50125. if (head && head.length) socket.unshift(head);
  50126. var proxyReq = (common.isSSL.test(options.target.protocol) ? https : http).request(
  50127. common.setupOutgoing(options.ssl || {}, options, req)
  50128. );
  50129. // Enable developers to modify the proxyReq before headers are sent
  50130. if (server) { server.emit('proxyReqWs', proxyReq, req, socket, options, head); }
  50131. // Error Handler
  50132. proxyReq.on('error', onOutgoingError);
  50133. proxyReq.on('response', function (res) {
  50134. // if upgrade event isn't going to happen, close the socket
  50135. if (!res.upgrade) {
  50136. socket.write(createHttpHeader('HTTP/' + res.httpVersion + ' ' + res.statusCode + ' ' + res.statusMessage, res.headers));
  50137. res.pipe(socket);
  50138. }
  50139. });
  50140. proxyReq.on('upgrade', function(proxyRes, proxySocket, proxyHead) {
  50141. proxySocket.on('error', onOutgoingError);
  50142. // Allow us to listen when the websocket has completed
  50143. proxySocket.on('end', function () {
  50144. server.emit('close', proxyRes, proxySocket, proxyHead);
  50145. });
  50146. // The pipe below will end proxySocket if socket closes cleanly, but not
  50147. // if it errors (eg, vanishes from the net and starts returning
  50148. // EHOSTUNREACH). We need to do that explicitly.
  50149. socket.on('error', function () {
  50150. proxySocket.end();
  50151. });
  50152. common.setupSocket(proxySocket);
  50153. if (proxyHead && proxyHead.length) proxySocket.unshift(proxyHead);
  50154. //
  50155. // Remark: Handle writing the headers to the socket when switching protocols
  50156. // Also handles when a header is an array
  50157. //
  50158. socket.write(createHttpHeader('HTTP/1.1 101 Switching Protocols', proxyRes.headers));
  50159. proxySocket.pipe(socket).pipe(proxySocket);
  50160. server.emit('open', proxySocket);
  50161. server.emit('proxySocket', proxySocket); //DEPRECATED.
  50162. });
  50163. return proxyReq.end(); // XXX: CHECK IF THIS IS THIS CORRECT
  50164. function onOutgoingError(err) {
  50165. if (clb) {
  50166. clb(err, req, socket);
  50167. } else {
  50168. server.emit('error', err, req, socket);
  50169. }
  50170. socket.end();
  50171. }
  50172. }
  50173. };
  50174. (function (module) {
  50175. var httpProxy = module.exports,
  50176. extend = require$$0__default$2._extend,
  50177. parse_url = require$$0__default$5.parse,
  50178. EE3 = eventemitter3.exports,
  50179. http = require$$1__default$1,
  50180. https = require$$1__default$3,
  50181. web = webIncoming,
  50182. ws = wsIncoming;
  50183. httpProxy.Server = ProxyServer;
  50184. /**
  50185. * Returns a function that creates the loader for
  50186. * either `ws` or `web`'s passes.
  50187. *
  50188. * Examples:
  50189. *
  50190. * httpProxy.createRightProxy('ws')
  50191. * // => [Function]
  50192. *
  50193. * @param {String} Type Either 'ws' or 'web'
  50194. * @return {Function} Loader Function that when called returns an iterator for the right passes
  50195. *
  50196. * @api private
  50197. */
  50198. function createRightProxy(type) {
  50199. return function(options) {
  50200. return function(req, res /*, [head], [opts] */) {
  50201. var passes = (type === 'ws') ? this.wsPasses : this.webPasses,
  50202. args = [].slice.call(arguments),
  50203. cntr = args.length - 1,
  50204. head, cbl;
  50205. /* optional args parse begin */
  50206. if(typeof args[cntr] === 'function') {
  50207. cbl = args[cntr];
  50208. cntr--;
  50209. }
  50210. var requestOptions = options;
  50211. if(
  50212. !(args[cntr] instanceof Buffer) &&
  50213. args[cntr] !== res
  50214. ) {
  50215. //Copy global options
  50216. requestOptions = extend({}, options);
  50217. //Overwrite with request options
  50218. extend(requestOptions, args[cntr]);
  50219. cntr--;
  50220. }
  50221. if(args[cntr] instanceof Buffer) {
  50222. head = args[cntr];
  50223. }
  50224. /* optional args parse end */
  50225. ['target', 'forward'].forEach(function(e) {
  50226. if (typeof requestOptions[e] === 'string')
  50227. requestOptions[e] = parse_url(requestOptions[e]);
  50228. });
  50229. if (!requestOptions.target && !requestOptions.forward) {
  50230. return this.emit('error', new Error('Must provide a proper URL as target'));
  50231. }
  50232. for(var i=0; i < passes.length; i++) {
  50233. /**
  50234. * Call of passes functions
  50235. * pass(req, res, options, head)
  50236. *
  50237. * In WebSockets case the `res` variable
  50238. * refer to the connection socket
  50239. * pass(req, socket, options, head)
  50240. */
  50241. if(passes[i](req, res, requestOptions, head, this, cbl)) { // passes can return a truthy value to halt the loop
  50242. break;
  50243. }
  50244. }
  50245. };
  50246. };
  50247. }
  50248. httpProxy.createRightProxy = createRightProxy;
  50249. function ProxyServer(options) {
  50250. EE3.call(this);
  50251. options = options || {};
  50252. options.prependPath = options.prependPath === false ? false : true;
  50253. this.web = this.proxyRequest = createRightProxy('web')(options);
  50254. this.ws = this.proxyWebsocketRequest = createRightProxy('ws')(options);
  50255. this.options = options;
  50256. this.webPasses = Object.keys(web).map(function(pass) {
  50257. return web[pass];
  50258. });
  50259. this.wsPasses = Object.keys(ws).map(function(pass) {
  50260. return ws[pass];
  50261. });
  50262. this.on('error', this.onError, this);
  50263. }
  50264. require$$0__default$2.inherits(ProxyServer, EE3);
  50265. ProxyServer.prototype.onError = function (err) {
  50266. //
  50267. // Remark: Replicate node core behavior using EE3
  50268. // so we force people to handle their own errors
  50269. //
  50270. if(this.listeners('error').length === 1) {
  50271. throw err;
  50272. }
  50273. };
  50274. ProxyServer.prototype.listen = function(port, hostname) {
  50275. var self = this,
  50276. closure = function(req, res) { self.web(req, res); };
  50277. this._server = this.options.ssl ?
  50278. https.createServer(this.options.ssl, closure) :
  50279. http.createServer(closure);
  50280. if(this.options.ws) {
  50281. this._server.on('upgrade', function(req, socket, head) { self.ws(req, socket, head); });
  50282. }
  50283. this._server.listen(port, hostname);
  50284. return this;
  50285. };
  50286. ProxyServer.prototype.close = function(callback) {
  50287. var self = this;
  50288. if (this._server) {
  50289. this._server.close(done);
  50290. }
  50291. // Wrap callback to nullify server after all open connections are closed.
  50292. function done() {
  50293. self._server = null;
  50294. if (callback) {
  50295. callback.apply(null, arguments);
  50296. }
  50297. }};
  50298. ProxyServer.prototype.before = function(type, passName, callback) {
  50299. if (type !== 'ws' && type !== 'web') {
  50300. throw new Error('type must be `web` or `ws`');
  50301. }
  50302. var passes = (type === 'ws') ? this.wsPasses : this.webPasses,
  50303. i = false;
  50304. passes.forEach(function(v, idx) {
  50305. if(v.name === passName) i = idx;
  50306. });
  50307. if(i === false) throw new Error('No such pass');
  50308. passes.splice(i, 0, callback);
  50309. };
  50310. ProxyServer.prototype.after = function(type, passName, callback) {
  50311. if (type !== 'ws' && type !== 'web') {
  50312. throw new Error('type must be `web` or `ws`');
  50313. }
  50314. var passes = (type === 'ws') ? this.wsPasses : this.webPasses,
  50315. i = false;
  50316. passes.forEach(function(v, idx) {
  50317. if(v.name === passName) i = idx;
  50318. });
  50319. if(i === false) throw new Error('No such pass');
  50320. passes.splice(i++, 0, callback);
  50321. };
  50322. }(httpProxy$2));
  50323. // Use explicit /index.js to help browserify negociation in require '/lib/http-proxy' (!)
  50324. var ProxyServer = httpProxy$2.exports.Server;
  50325. /**
  50326. * Creates the proxy server.
  50327. *
  50328. * Examples:
  50329. *
  50330. * httpProxy.createProxyServer({ .. }, 8000)
  50331. * // => '{ web: [Function], ws: [Function] ... }'
  50332. *
  50333. * @param {Object} Options Config object passed to the proxy
  50334. *
  50335. * @return {Object} Proxy Proxy object with handlers for `ws` and `web` requests
  50336. *
  50337. * @api public
  50338. */
  50339. function createProxyServer(options) {
  50340. /*
  50341. * `options` is needed and it must have the following layout:
  50342. *
  50343. * {
  50344. * target : <url string to be parsed with the url module>
  50345. * forward: <url string to be parsed with the url module>
  50346. * agent : <object to be passed to http(s).request>
  50347. * ssl : <object to be passed to https.createServer()>
  50348. * ws : <true/false, if you want to proxy websockets>
  50349. * xfwd : <true/false, adds x-forward headers>
  50350. * secure : <true/false, verify SSL certificate>
  50351. * toProxy: <true/false, explicitly specify if we are proxying to another proxy>
  50352. * prependPath: <true/false, Default: true - specify whether you want to prepend the target's path to the proxy path>
  50353. * ignorePath: <true/false, Default: false - specify whether you want to ignore the proxy path of the incoming request>
  50354. * localAddress : <Local interface string to bind for outgoing connections>
  50355. * changeOrigin: <true/false, Default: false - changes the origin of the host header to the target URL>
  50356. * preserveHeaderKeyCase: <true/false, Default: false - specify whether you want to keep letter case of response header key >
  50357. * auth : Basic authentication i.e. 'user:password' to compute an Authorization header.
  50358. * hostRewrite: rewrites the location hostname on (201/301/302/307/308) redirects, Default: null.
  50359. * autoRewrite: rewrites the location host/port on (201/301/302/307/308) redirects based on requested host/port. Default: false.
  50360. * protocolRewrite: rewrites the location protocol on (201/301/302/307/308) redirects to 'http' or 'https'. Default: null.
  50361. * }
  50362. *
  50363. * NOTE: `options.ws` and `options.ssl` are optional.
  50364. * `options.target and `options.forward` cannot be
  50365. * both missing
  50366. * }
  50367. */
  50368. return new ProxyServer(options);
  50369. }
  50370. ProxyServer.createProxyServer = createProxyServer;
  50371. ProxyServer.createServer = createProxyServer;
  50372. ProxyServer.createProxy = createProxyServer;
  50373. /**
  50374. * Export the proxy "Server" as the main export.
  50375. */
  50376. var httpProxy$1 = ProxyServer;
  50377. /*!
  50378. * Caron dimonio, con occhi di bragia
  50379. * loro accennando, tutte le raccoglie;
  50380. * batte col remo qualunque s’adagia
  50381. *
  50382. * Charon the demon, with the eyes of glede,
  50383. * Beckoning to them, collects them all together,
  50384. * Beats with his oar whoever lags behind
  50385. *
  50386. * Dante - The Divine Comedy (Canto III)
  50387. */
  50388. var httpProxy = httpProxy$1;
  50389. const debug$3 = createDebugger('vite:proxy');
  50390. function proxyMiddleware(httpServer, options, config) {
  50391. // lazy require only when proxy is used
  50392. const proxies = {};
  50393. Object.keys(options).forEach((context) => {
  50394. let opts = options[context];
  50395. if (typeof opts === 'string') {
  50396. opts = { target: opts, changeOrigin: true };
  50397. }
  50398. const proxy = httpProxy.createProxyServer(opts);
  50399. proxy.on('error', (err) => {
  50400. config.logger.error(`${colors$1.red(`http proxy error:`)}\n${err.stack}`, {
  50401. timestamp: true,
  50402. error: err
  50403. });
  50404. });
  50405. if (opts.configure) {
  50406. opts.configure(proxy, opts);
  50407. }
  50408. // clone before saving because http-proxy mutates the options
  50409. proxies[context] = [proxy, { ...opts }];
  50410. });
  50411. if (httpServer) {
  50412. httpServer.on('upgrade', (req, socket, head) => {
  50413. var _a;
  50414. const url = req.url;
  50415. for (const context in proxies) {
  50416. if (doesProxyContextMatchUrl(context, url)) {
  50417. const [proxy, opts] = proxies[context];
  50418. if ((opts.ws || ((_a = opts.target) === null || _a === void 0 ? void 0 : _a.toString().startsWith('ws:'))) &&
  50419. req.headers['sec-websocket-protocol'] !== HMR_HEADER) {
  50420. if (opts.rewrite) {
  50421. req.url = opts.rewrite(url);
  50422. }
  50423. debug$3(`${req.url} -> ws ${opts.target}`);
  50424. proxy.ws(req, socket, head);
  50425. return;
  50426. }
  50427. }
  50428. }
  50429. });
  50430. }
  50431. // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
  50432. return function viteProxyMiddleware(req, res, next) {
  50433. const url = req.url;
  50434. for (const context in proxies) {
  50435. if (doesProxyContextMatchUrl(context, url)) {
  50436. const [proxy, opts] = proxies[context];
  50437. const options = {};
  50438. if (opts.bypass) {
  50439. const bypassResult = opts.bypass(req, res, opts);
  50440. if (typeof bypassResult === 'string') {
  50441. req.url = bypassResult;
  50442. debug$3(`bypass: ${req.url} -> ${bypassResult}`);
  50443. return next();
  50444. }
  50445. else if (isObject$1(bypassResult)) {
  50446. Object.assign(options, bypassResult);
  50447. debug$3(`bypass: ${req.url} use modified options: %O`, options);
  50448. return next();
  50449. }
  50450. else if (bypassResult === false) {
  50451. debug$3(`bypass: ${req.url} -> 404`);
  50452. return res.end(404);
  50453. }
  50454. }
  50455. debug$3(`${req.url} -> ${opts.target || opts.forward}`);
  50456. if (opts.rewrite) {
  50457. req.url = opts.rewrite(req.url);
  50458. }
  50459. proxy.web(req, res, options);
  50460. return;
  50461. }
  50462. }
  50463. next();
  50464. };
  50465. }
  50466. function doesProxyContextMatchUrl(context, url) {
  50467. return ((context.startsWith('^') && new RegExp(context).test(url)) ||
  50468. url.startsWith(context));
  50469. }
  50470. var lib = {exports: {}};
  50471. (function (module, exports) {
  50472. var url = require$$0__default$5;
  50473. module.exports = function historyApiFallback(options) {
  50474. options = options || {};
  50475. var logger = getLogger(options);
  50476. return function(req, res, next) {
  50477. var headers = req.headers;
  50478. if (req.method !== 'GET') {
  50479. logger(
  50480. 'Not rewriting',
  50481. req.method,
  50482. req.url,
  50483. 'because the method is not GET.'
  50484. );
  50485. return next();
  50486. } else if (!headers || typeof headers.accept !== 'string') {
  50487. logger(
  50488. 'Not rewriting',
  50489. req.method,
  50490. req.url,
  50491. 'because the client did not send an HTTP accept header.'
  50492. );
  50493. return next();
  50494. } else if (headers.accept.indexOf('application/json') === 0) {
  50495. logger(
  50496. 'Not rewriting',
  50497. req.method,
  50498. req.url,
  50499. 'because the client prefers JSON.'
  50500. );
  50501. return next();
  50502. } else if (!acceptsHtml(headers.accept, options)) {
  50503. logger(
  50504. 'Not rewriting',
  50505. req.method,
  50506. req.url,
  50507. 'because the client does not accept HTML.'
  50508. );
  50509. return next();
  50510. }
  50511. var parsedUrl = url.parse(req.url);
  50512. var rewriteTarget;
  50513. options.rewrites = options.rewrites || [];
  50514. for (var i = 0; i < options.rewrites.length; i++) {
  50515. var rewrite = options.rewrites[i];
  50516. var match = parsedUrl.pathname.match(rewrite.from);
  50517. if (match !== null) {
  50518. rewriteTarget = evaluateRewriteRule(parsedUrl, match, rewrite.to, req);
  50519. if(rewriteTarget.charAt(0) !== '/') {
  50520. logger(
  50521. 'We recommend using an absolute path for the rewrite target.',
  50522. 'Received a non-absolute rewrite target',
  50523. rewriteTarget,
  50524. 'for URL',
  50525. req.url
  50526. );
  50527. }
  50528. logger('Rewriting', req.method, req.url, 'to', rewriteTarget);
  50529. req.url = rewriteTarget;
  50530. return next();
  50531. }
  50532. }
  50533. var pathname = parsedUrl.pathname;
  50534. if (pathname.lastIndexOf('.') > pathname.lastIndexOf('/') &&
  50535. options.disableDotRule !== true) {
  50536. logger(
  50537. 'Not rewriting',
  50538. req.method,
  50539. req.url,
  50540. 'because the path includes a dot (.) character.'
  50541. );
  50542. return next();
  50543. }
  50544. rewriteTarget = options.index || '/index.html';
  50545. logger('Rewriting', req.method, req.url, 'to', rewriteTarget);
  50546. req.url = rewriteTarget;
  50547. next();
  50548. };
  50549. };
  50550. function evaluateRewriteRule(parsedUrl, match, rule, req) {
  50551. if (typeof rule === 'string') {
  50552. return rule;
  50553. } else if (typeof rule !== 'function') {
  50554. throw new Error('Rewrite rule can only be of type string or function.');
  50555. }
  50556. return rule({
  50557. parsedUrl: parsedUrl,
  50558. match: match,
  50559. request: req
  50560. });
  50561. }
  50562. function acceptsHtml(header, options) {
  50563. options.htmlAcceptHeaders = options.htmlAcceptHeaders || ['text/html', '*/*'];
  50564. for (var i = 0; i < options.htmlAcceptHeaders.length; i++) {
  50565. if (header.indexOf(options.htmlAcceptHeaders[i]) !== -1) {
  50566. return true;
  50567. }
  50568. }
  50569. return false;
  50570. }
  50571. function getLogger(options) {
  50572. if (options && options.logger) {
  50573. return options.logger;
  50574. } else if (options && options.verbose) {
  50575. return console.log.bind(console);
  50576. }
  50577. return function(){};
  50578. }
  50579. }(lib));
  50580. var history = lib.exports;
  50581. function spaFallbackMiddleware(root) {
  50582. const historySpaFallbackMiddleware = history({
  50583. logger: createDebugger('vite:spa-fallback'),
  50584. // support /dir/ without explicit index.html
  50585. rewrites: [
  50586. {
  50587. from: /\/$/,
  50588. to({ parsedUrl }) {
  50589. const rewritten = decodeURIComponent(parsedUrl.pathname) + 'index.html';
  50590. if (fs__default.existsSync(path__default.join(root, rewritten))) {
  50591. return rewritten;
  50592. }
  50593. else {
  50594. return `/index.html`;
  50595. }
  50596. }
  50597. }
  50598. ]
  50599. });
  50600. // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
  50601. return function viteSpaFallbackMiddleware(req, res, next) {
  50602. return historySpaFallbackMiddleware(req, res, next);
  50603. };
  50604. }
  50605. const alias = {
  50606. js: 'application/javascript',
  50607. css: 'text/css',
  50608. html: 'text/html',
  50609. json: 'application/json'
  50610. };
  50611. function send(req, res, content, type, options) {
  50612. const { etag = etag_1(content, { weak: true }), cacheControl = 'no-cache', headers, map } = options;
  50613. if (res.writableEnded) {
  50614. return;
  50615. }
  50616. if (req.headers['if-none-match'] === etag) {
  50617. res.statusCode = 304;
  50618. res.end();
  50619. return;
  50620. }
  50621. res.setHeader('Content-Type', alias[type] || type);
  50622. res.setHeader('Cache-Control', cacheControl);
  50623. res.setHeader('Etag', etag);
  50624. if (headers) {
  50625. for (const name in headers) {
  50626. res.setHeader(name, headers[name]);
  50627. }
  50628. }
  50629. // inject source map reference
  50630. if (map && map.mappings) {
  50631. if (type === 'js' || type === 'css') {
  50632. content = getCodeWithSourcemap(type, content.toString(), map);
  50633. }
  50634. }
  50635. res.statusCode = 200;
  50636. res.end(content);
  50637. return;
  50638. }
  50639. const ERR_OPTIMIZE_DEPS_PROCESSING_ERROR = 'ERR_OPTIMIZE_DEPS_PROCESSING_ERROR';
  50640. const ERR_OUTDATED_OPTIMIZED_DEP = 'ERR_OUTDATED_OPTIMIZED_DEP';
  50641. const isDebug$2 = process.env.DEBUG;
  50642. const debug$2 = createDebugger('vite:optimize-deps');
  50643. function optimizedDepsPlugin() {
  50644. let server;
  50645. return {
  50646. name: 'vite:optimized-deps',
  50647. configureServer(_server) {
  50648. server = _server;
  50649. },
  50650. async load(id) {
  50651. var _a, _b;
  50652. if (server && isOptimizedDepFile(id, server.config)) {
  50653. const metadata = (_a = server === null || server === void 0 ? void 0 : server._optimizedDeps) === null || _a === void 0 ? void 0 : _a.metadata;
  50654. if (metadata) {
  50655. const file = cleanUrl(id);
  50656. const versionMatch = id.match(DEP_VERSION_RE);
  50657. const browserHash = versionMatch
  50658. ? versionMatch[1].split('=')[1]
  50659. : undefined;
  50660. // Search in both the currently optimized and newly discovered deps
  50661. const info = optimizedDepInfoFromFile(metadata, file);
  50662. if (info) {
  50663. if (browserHash && info.browserHash !== browserHash) {
  50664. throwOutdatedRequest(id);
  50665. }
  50666. try {
  50667. // This is an entry point, it may still not be bundled
  50668. await info.processing;
  50669. }
  50670. catch {
  50671. // If the refresh has not happened after timeout, Vite considers
  50672. // something unexpected has happened. In this case, Vite
  50673. // returns an empty response that will error.
  50674. throwProcessingError(id);
  50675. return;
  50676. }
  50677. const newMetadata = (_b = server._optimizedDeps) === null || _b === void 0 ? void 0 : _b.metadata;
  50678. if (metadata !== newMetadata) {
  50679. const currentInfo = optimizedDepInfoFromFile(newMetadata, file);
  50680. if (info.browserHash !== (currentInfo === null || currentInfo === void 0 ? void 0 : currentInfo.browserHash)) {
  50681. throwOutdatedRequest(id);
  50682. }
  50683. }
  50684. }
  50685. isDebug$2 && debug$2(`load ${colors$1.cyan(file)}`);
  50686. // Load the file from the cache instead of waiting for other plugin
  50687. // load hooks to avoid race conditions, once processing is resolved,
  50688. // we are sure that the file has been properly save to disk
  50689. try {
  50690. return await fs$n.promises.readFile(file, 'utf-8');
  50691. }
  50692. catch (e) {
  50693. // Outdated non-entry points (CHUNK), loaded after a rerun
  50694. throwOutdatedRequest(id);
  50695. }
  50696. }
  50697. }
  50698. }
  50699. };
  50700. }
  50701. function throwProcessingError(id) {
  50702. const err = new Error(`Something unexpected happened while optimizing "${id}". ` +
  50703. `The current page should have reloaded by now`);
  50704. err.code = ERR_OPTIMIZE_DEPS_PROCESSING_ERROR;
  50705. // This error will be caught by the transform middleware that will
  50706. // send a 504 status code request timeout
  50707. throw err;
  50708. }
  50709. function throwOutdatedRequest(id) {
  50710. const err = new Error(`There is a new version of the pre-bundle for "${id}", ` +
  50711. `a page reload is going to ask for it.`);
  50712. err.code = ERR_OUTDATED_OPTIMIZED_DEP;
  50713. // This error will be caught by the transform middleware that will
  50714. // send a 504 status code request timeout
  50715. throw err;
  50716. }
  50717. const debugCache = createDebugger('vite:cache');
  50718. const isDebug$1 = !!process.env.DEBUG;
  50719. const knownIgnoreList = new Set(['/', '/favicon.ico']);
  50720. function transformMiddleware(server) {
  50721. const { config: { root, logger }, moduleGraph } = server;
  50722. const isOptimizedDepUrl = createIsOptimizedDepUrl(server.config);
  50723. // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
  50724. return async function viteTransformMiddleware(req, res, next) {
  50725. var _a, _b, _c, _d, _e, _f;
  50726. if (req.method !== 'GET' || knownIgnoreList.has(req.url)) {
  50727. return next();
  50728. }
  50729. let url;
  50730. try {
  50731. url = decodeURI(removeTimestampQuery(req.url)).replace(NULL_BYTE_PLACEHOLDER, '\0');
  50732. }
  50733. catch (e) {
  50734. return next(e);
  50735. }
  50736. const withoutQuery = cleanUrl(url);
  50737. try {
  50738. const isSourceMap = withoutQuery.endsWith('.map');
  50739. // since we generate source map references, handle those requests here
  50740. if (isSourceMap) {
  50741. if (isOptimizedDepUrl(url)) {
  50742. // If the browser is requesting a source map for an optimized dep, it
  50743. // means that the dependency has already been pre-bundled and loaded
  50744. const mapFile = url.startsWith(FS_PREFIX)
  50745. ? fsPathFromId(url)
  50746. : normalizePath$3(ensureVolumeInPath(path__default.resolve(root, url.slice(1))));
  50747. try {
  50748. const map = await fs$n.promises.readFile(mapFile, 'utf-8');
  50749. return send(req, res, map, 'json', {
  50750. headers: server.config.server.headers
  50751. });
  50752. }
  50753. catch (e) {
  50754. // Outdated source map request for optimized deps, this isn't an error
  50755. // but part of the normal flow when re-optimizing after missing deps
  50756. // Send back an empty source map so the browser doesn't issue warnings
  50757. const dummySourceMap = {
  50758. version: 3,
  50759. file: mapFile.replace(/\.map$/, ''),
  50760. sources: [],
  50761. sourcesContent: [],
  50762. names: [],
  50763. mappings: ';;;;;;;;;'
  50764. };
  50765. return send(req, res, JSON.stringify(dummySourceMap), 'json', {
  50766. cacheControl: 'no-cache',
  50767. headers: server.config.server.headers
  50768. });
  50769. }
  50770. }
  50771. else {
  50772. const originalUrl = url.replace(/\.map($|\?)/, '$1');
  50773. const map = (_b = (_a = (await moduleGraph.getModuleByUrl(originalUrl, false))) === null || _a === void 0 ? void 0 : _a.transformResult) === null || _b === void 0 ? void 0 : _b.map;
  50774. if (map) {
  50775. return send(req, res, JSON.stringify(map), 'json', {
  50776. headers: server.config.server.headers
  50777. });
  50778. }
  50779. else {
  50780. return next();
  50781. }
  50782. }
  50783. }
  50784. // check if public dir is inside root dir
  50785. const publicDir = normalizePath$3(server.config.publicDir);
  50786. const rootDir = normalizePath$3(server.config.root);
  50787. if (publicDir.startsWith(rootDir)) {
  50788. const publicPath = `${publicDir.slice(rootDir.length)}/`;
  50789. // warn explicit public paths
  50790. if (url.startsWith(publicPath)) {
  50791. logger.warn(colors$1.yellow(`files in the public directory are served at the root path.\n` +
  50792. `Instead of ${colors$1.cyan(url)}, use ${colors$1.cyan(url.replace(publicPath, '/'))}.`));
  50793. }
  50794. }
  50795. if (isJSRequest(url) ||
  50796. isImportRequest(url) ||
  50797. isCSSRequest(url) ||
  50798. isHTMLProxy(url)) {
  50799. // strip ?import
  50800. url = removeImportQuery(url);
  50801. // Strip valid id prefix. This is prepended to resolved Ids that are
  50802. // not valid browser import specifiers by the importAnalysis plugin.
  50803. url = unwrapId(url);
  50804. // for CSS, we need to differentiate between normal CSS requests and
  50805. // imports
  50806. if (isCSSRequest(url) &&
  50807. !isDirectRequest(url) &&
  50808. ((_c = req.headers.accept) === null || _c === void 0 ? void 0 : _c.includes('text/css'))) {
  50809. url = injectQuery(url, 'direct');
  50810. }
  50811. // check if we can return 304 early
  50812. const ifNoneMatch = req.headers['if-none-match'];
  50813. if (ifNoneMatch &&
  50814. ((_e = (_d = (await moduleGraph.getModuleByUrl(url, false))) === null || _d === void 0 ? void 0 : _d.transformResult) === null || _e === void 0 ? void 0 : _e.etag) === ifNoneMatch) {
  50815. isDebug$1 && debugCache(`[304] ${prettifyUrl(url, root)}`);
  50816. res.statusCode = 304;
  50817. return res.end();
  50818. }
  50819. // resolve, load and transform using the plugin container
  50820. const result = await transformRequest(url, server, {
  50821. html: (_f = req.headers.accept) === null || _f === void 0 ? void 0 : _f.includes('text/html')
  50822. });
  50823. if (result) {
  50824. const type = isDirectCSSRequest(url) ? 'css' : 'js';
  50825. const isDep = DEP_VERSION_RE.test(url) || isOptimizedDepUrl(url);
  50826. return send(req, res, result.code, type, {
  50827. etag: result.etag,
  50828. // allow browser to cache npm deps!
  50829. cacheControl: isDep ? 'max-age=31536000,immutable' : 'no-cache',
  50830. headers: server.config.server.headers,
  50831. map: result.map
  50832. });
  50833. }
  50834. }
  50835. }
  50836. catch (e) {
  50837. if ((e === null || e === void 0 ? void 0 : e.code) === ERR_OPTIMIZE_DEPS_PROCESSING_ERROR) {
  50838. // Skip if response has already been sent
  50839. if (!res.writableEnded) {
  50840. res.statusCode = 504; // status code request timeout
  50841. res.end();
  50842. }
  50843. // This timeout is unexpected
  50844. logger.error(e.message);
  50845. return;
  50846. }
  50847. if ((e === null || e === void 0 ? void 0 : e.code) === ERR_OUTDATED_OPTIMIZED_DEP) {
  50848. // Skip if response has already been sent
  50849. if (!res.writableEnded) {
  50850. res.statusCode = 504; // status code request timeout
  50851. res.end();
  50852. }
  50853. // We don't need to log an error in this case, the request
  50854. // is outdated because new dependencies were discovered and
  50855. // the new pre-bundle dependendencies have changed.
  50856. // A full-page reload has been issued, and these old requests
  50857. // can't be properly fullfilled. This isn't an unexpected
  50858. // error but a normal part of the missing deps discovery flow
  50859. return;
  50860. }
  50861. return next(e);
  50862. }
  50863. next();
  50864. };
  50865. }
  50866. function createDevHtmlTransformFn(server) {
  50867. const [preHooks, postHooks] = resolveHtmlTransforms(server.config.plugins);
  50868. return (url, html, originalUrl) => {
  50869. return applyHtmlTransforms(html, [...preHooks, devHtmlHook, ...postHooks], {
  50870. path: url,
  50871. filename: getHtmlFilename(url, server),
  50872. server,
  50873. originalUrl
  50874. });
  50875. };
  50876. }
  50877. function getHtmlFilename(url, server) {
  50878. if (url.startsWith(FS_PREFIX)) {
  50879. return decodeURIComponent(fsPathFromId(url));
  50880. }
  50881. else {
  50882. return decodeURIComponent(normalizePath$3(path__default.join(server.config.root, url.slice(1))));
  50883. }
  50884. }
  50885. const startsWithSingleSlashRE = /^\/(?!\/)/;
  50886. const processNodeUrl = (node, s, config, htmlPath, originalUrl, moduleGraph) => {
  50887. var _a;
  50888. let url = ((_a = node.value) === null || _a === void 0 ? void 0 : _a.content) || '';
  50889. if (moduleGraph) {
  50890. const mod = moduleGraph.urlToModuleMap.get(url);
  50891. if (mod && mod.lastHMRTimestamp > 0) {
  50892. url = injectQuery(url, `t=${mod.lastHMRTimestamp}`);
  50893. }
  50894. }
  50895. if (startsWithSingleSlashRE.test(url)) {
  50896. // prefix with base
  50897. s.overwrite(node.value.loc.start.offset, node.value.loc.end.offset, `"${config.base + url.slice(1)}"`, { contentOnly: true });
  50898. }
  50899. else if (url.startsWith('.') &&
  50900. originalUrl &&
  50901. originalUrl !== '/' &&
  50902. htmlPath === '/index.html') {
  50903. // #3230 if some request url (localhost:3000/a/b) return to fallback html, the relative assets
  50904. // path will add `/a/` prefix, it will caused 404.
  50905. // rewrite before `./index.js` -> `localhost:3000/a/index.js`.
  50906. // rewrite after `../index.js` -> `localhost:3000/index.js`.
  50907. s.overwrite(node.value.loc.start.offset, node.value.loc.end.offset, `"${path__default.posix.join(path__default.posix.relative(originalUrl, '/'), url.slice(1))}"`, { contentOnly: true });
  50908. }
  50909. };
  50910. const devHtmlHook = async (html, { path: htmlPath, filename, server, originalUrl }) => {
  50911. const { config, moduleGraph, watcher } = server;
  50912. const base = config.base || '/';
  50913. let proxyModulePath;
  50914. let proxyModuleUrl;
  50915. const trailingSlash = htmlPath.endsWith('/');
  50916. if (!trailingSlash && fs__default.existsSync(filename)) {
  50917. proxyModulePath = htmlPath;
  50918. proxyModuleUrl = base + htmlPath.slice(1);
  50919. }
  50920. else {
  50921. // There are users of vite.transformIndexHtml calling it with url '/'
  50922. // for SSR integrations #7993, filename is root for this case
  50923. // A user may also use a valid name for a virtual html file
  50924. // Mark the path as virtual in both cases so sourcemaps aren't processed
  50925. // and ids are properly handled
  50926. const validPath = `${htmlPath}${trailingSlash ? 'index.html' : ''}`;
  50927. proxyModulePath = `\0${validPath}`;
  50928. proxyModuleUrl = `${VALID_ID_PREFIX}${NULL_BYTE_PLACEHOLDER}${validPath}`;
  50929. }
  50930. const s = new MagicString(html);
  50931. let inlineModuleIndex = -1;
  50932. const proxyCacheUrl = cleanUrl(proxyModulePath).replace(normalizePath$3(config.root), '');
  50933. const styleUrl = [];
  50934. const addInlineModule = (node, ext) => {
  50935. inlineModuleIndex++;
  50936. const contentNode = node.children[0];
  50937. const code = contentNode.content;
  50938. let map;
  50939. if (!proxyModulePath.startsWith('\0')) {
  50940. map = new MagicString(html)
  50941. .snip(contentNode.loc.start.offset, contentNode.loc.end.offset)
  50942. .generateMap({ hires: true });
  50943. map.sources = [filename];
  50944. map.file = filename;
  50945. }
  50946. // add HTML Proxy to Map
  50947. addToHTMLProxyCache(config, proxyCacheUrl, inlineModuleIndex, { code, map });
  50948. // inline js module. convert to src="proxy"
  50949. const modulePath = `${proxyModuleUrl}?html-proxy&index=${inlineModuleIndex}.${ext}`;
  50950. // invalidate the module so the newly cached contents will be served
  50951. const module = server === null || server === void 0 ? void 0 : server.moduleGraph.getModuleById(modulePath);
  50952. if (module) {
  50953. server === null || server === void 0 ? void 0 : server.moduleGraph.invalidateModule(module);
  50954. }
  50955. s.overwrite(node.loc.start.offset, node.loc.end.offset, `<script type="module" src="${modulePath}"></script>`, { contentOnly: true });
  50956. };
  50957. await traverseHtml(html, htmlPath, (node) => {
  50958. if (node.type !== 1 /* ELEMENT */) {
  50959. return;
  50960. }
  50961. // script tags
  50962. if (node.tag === 'script') {
  50963. const { src, isModule } = getScriptInfo(node);
  50964. if (src) {
  50965. processNodeUrl(src, s, config, htmlPath, originalUrl, moduleGraph);
  50966. }
  50967. else if (isModule && node.children.length) {
  50968. addInlineModule(node, 'js');
  50969. }
  50970. }
  50971. if (node.tag === 'style' && node.children.length) {
  50972. const children = node.children[0];
  50973. styleUrl.push({
  50974. start: children.loc.start.offset,
  50975. end: children.loc.end.offset,
  50976. code: children.content
  50977. });
  50978. }
  50979. // elements with [href/src] attrs
  50980. const assetAttrs = assetAttrsConfig[node.tag];
  50981. if (assetAttrs) {
  50982. for (const p of node.props) {
  50983. if (p.type === 6 /* ATTRIBUTE */ &&
  50984. p.value &&
  50985. assetAttrs.includes(p.name)) {
  50986. processNodeUrl(p, s, config, htmlPath, originalUrl);
  50987. }
  50988. }
  50989. }
  50990. });
  50991. await Promise.all(styleUrl.map(async ({ start, end, code }, index) => {
  50992. const url = `${proxyModulePath}?html-proxy&direct&index=${index}.css`;
  50993. // ensure module in graph after successful load
  50994. const mod = await moduleGraph.ensureEntryFromUrl(url, false);
  50995. ensureWatchedFile(watcher, mod.file, config.root);
  50996. const result = await server.pluginContainer.transform(code, mod.id);
  50997. s.overwrite(start, end, (result === null || result === void 0 ? void 0 : result.code) || '');
  50998. }));
  50999. html = s.toString();
  51000. return {
  51001. html,
  51002. tags: [
  51003. {
  51004. tag: 'script',
  51005. attrs: {
  51006. type: 'module',
  51007. src: path__default.posix.join(base, CLIENT_PUBLIC_PATH)
  51008. },
  51009. injectTo: 'head-prepend'
  51010. }
  51011. ]
  51012. };
  51013. };
  51014. function indexHtmlMiddleware(server) {
  51015. // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
  51016. return async function viteIndexHtmlMiddleware(req, res, next) {
  51017. if (res.writableEnded) {
  51018. return next();
  51019. }
  51020. const url = req.url && cleanUrl(req.url);
  51021. // spa-fallback always redirects to /index.html
  51022. if ((url === null || url === void 0 ? void 0 : url.endsWith('.html')) && req.headers['sec-fetch-dest'] !== 'script') {
  51023. const filename = getHtmlFilename(url, server);
  51024. if (fs__default.existsSync(filename)) {
  51025. try {
  51026. let html = fs__default.readFileSync(filename, 'utf-8');
  51027. html = await server.transformIndexHtml(url, html, req.originalUrl);
  51028. return send(req, res, html, 'html', {
  51029. headers: server.config.server.headers
  51030. });
  51031. }
  51032. catch (e) {
  51033. return next(e);
  51034. }
  51035. }
  51036. }
  51037. next();
  51038. };
  51039. }
  51040. const logTime = createDebugger('vite:time');
  51041. function timeMiddleware(root) {
  51042. // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
  51043. return function viteTimeMiddleware(req, res, next) {
  51044. const start = perf_hooks.performance.now();
  51045. const end = res.end;
  51046. res.end = (...args) => {
  51047. logTime(`${timeFrom(start)} ${prettifyUrl(req.url, root)}`);
  51048. // @ts-ignore
  51049. return end.call(res, ...args);
  51050. };
  51051. next();
  51052. };
  51053. }
  51054. const debugHmr = createDebugger('vite:hmr');
  51055. const normalizedClientDir = normalizePath$3(CLIENT_DIR);
  51056. function getShortName(file, root) {
  51057. return file.startsWith(root + '/') ? path__default.posix.relative(root, file) : file;
  51058. }
  51059. async function handleHMRUpdate(file, server) {
  51060. const { ws, config, moduleGraph } = server;
  51061. const shortFile = getShortName(file, config.root);
  51062. const fileName = path__default.basename(file);
  51063. const isConfig = file === config.configFile;
  51064. const isConfigDependency = config.configFileDependencies.some((name) => file === name);
  51065. const isEnv = config.inlineConfig.envFile !== false &&
  51066. (fileName === '.env' || fileName.startsWith('.env.'));
  51067. if (isConfig || isConfigDependency || isEnv) {
  51068. // auto restart server
  51069. debugHmr(`[config change] ${colors$1.dim(shortFile)}`);
  51070. config.logger.info(colors$1.green(`${path__default.relative(process.cwd(), file)} changed, restarting server...`), { clear: true, timestamp: true });
  51071. try {
  51072. await server.restart();
  51073. }
  51074. catch (e) {
  51075. config.logger.error(colors$1.red(e));
  51076. }
  51077. return;
  51078. }
  51079. debugHmr(`[file change] ${colors$1.dim(shortFile)}`);
  51080. // (dev only) the client itself cannot be hot updated.
  51081. if (file.startsWith(normalizedClientDir)) {
  51082. ws.send({
  51083. type: 'full-reload',
  51084. path: '*'
  51085. });
  51086. return;
  51087. }
  51088. const mods = moduleGraph.getModulesByFile(file);
  51089. // check if any plugin wants to perform custom HMR handling
  51090. const timestamp = Date.now();
  51091. const hmrContext = {
  51092. file,
  51093. timestamp,
  51094. modules: mods ? [...mods] : [],
  51095. read: () => readModifiedFile(file),
  51096. server
  51097. };
  51098. for (const plugin of config.plugins) {
  51099. if (plugin.handleHotUpdate) {
  51100. const filteredModules = await plugin.handleHotUpdate(hmrContext);
  51101. if (filteredModules) {
  51102. hmrContext.modules = filteredModules;
  51103. }
  51104. }
  51105. }
  51106. if (!hmrContext.modules.length) {
  51107. // html file cannot be hot updated
  51108. if (file.endsWith('.html')) {
  51109. config.logger.info(colors$1.green(`page reload `) + colors$1.dim(shortFile), {
  51110. clear: true,
  51111. timestamp: true
  51112. });
  51113. ws.send({
  51114. type: 'full-reload',
  51115. path: config.server.middlewareMode
  51116. ? '*'
  51117. : '/' + normalizePath$3(path__default.relative(config.root, file))
  51118. });
  51119. }
  51120. else {
  51121. // loaded but not in the module graph, probably not js
  51122. debugHmr(`[no modules matched] ${colors$1.dim(shortFile)}`);
  51123. }
  51124. return;
  51125. }
  51126. updateModules(shortFile, hmrContext.modules, timestamp, server);
  51127. }
  51128. function updateModules(file, modules, timestamp, { config, ws }) {
  51129. const updates = [];
  51130. const invalidatedModules = new Set();
  51131. let needFullReload = false;
  51132. for (const mod of modules) {
  51133. invalidate(mod, timestamp, invalidatedModules);
  51134. if (needFullReload) {
  51135. continue;
  51136. }
  51137. const boundaries = new Set();
  51138. const hasDeadEnd = propagateUpdate(mod, boundaries);
  51139. if (hasDeadEnd) {
  51140. needFullReload = true;
  51141. continue;
  51142. }
  51143. updates.push(...[...boundaries].map(({ boundary, acceptedVia }) => ({
  51144. type: `${boundary.type}-update`,
  51145. timestamp,
  51146. path: boundary.url,
  51147. acceptedPath: acceptedVia.url
  51148. })));
  51149. }
  51150. if (needFullReload) {
  51151. config.logger.info(colors$1.green(`page reload `) + colors$1.dim(file), {
  51152. clear: true,
  51153. timestamp: true
  51154. });
  51155. ws.send({
  51156. type: 'full-reload'
  51157. });
  51158. }
  51159. else {
  51160. config.logger.info(updates
  51161. .map(({ path }) => colors$1.green(`hmr update `) + colors$1.dim(path))
  51162. .join('\n'), { clear: true, timestamp: true });
  51163. ws.send({
  51164. type: 'update',
  51165. updates
  51166. });
  51167. }
  51168. }
  51169. async function handleFileAddUnlink(file, server, isUnlink = false) {
  51170. var _a;
  51171. const modules = [...((_a = server.moduleGraph.getModulesByFile(file)) !== null && _a !== void 0 ? _a : [])];
  51172. if (isUnlink && file in server._globImporters) {
  51173. delete server._globImporters[file];
  51174. }
  51175. else {
  51176. for (const i in server._globImporters) {
  51177. const { module, importGlobs } = server._globImporters[i];
  51178. for (const { base, pattern } of importGlobs) {
  51179. if (micromatch_1.isMatch(file, pattern) ||
  51180. micromatch_1.isMatch(path__default.relative(base, file), pattern)) {
  51181. modules.push(module);
  51182. // We use `onFileChange` to invalidate `module.file` so that subsequent `ssrLoadModule()`
  51183. // calls get fresh glob import results with(out) the newly added(/removed) `file`.
  51184. server.moduleGraph.onFileChange(module.file);
  51185. break;
  51186. }
  51187. }
  51188. }
  51189. }
  51190. if (modules.length > 0) {
  51191. updateModules(getShortName(file, server.config.root), modules, Date.now(), server);
  51192. }
  51193. }
  51194. function propagateUpdate(node, boundaries, currentChain = [node]) {
  51195. // #7561
  51196. // if the imports of `node` have not been analyzed, then `node` has not
  51197. // been loaded in the browser and we should stop propagation.
  51198. if (node.id && node.isSelfAccepting === undefined) {
  51199. return false;
  51200. }
  51201. if (node.isSelfAccepting) {
  51202. boundaries.add({
  51203. boundary: node,
  51204. acceptedVia: node
  51205. });
  51206. // additionally check for CSS importers, since a PostCSS plugin like
  51207. // Tailwind JIT may register any file as a dependency to a CSS file.
  51208. for (const importer of node.importers) {
  51209. if (isCSSRequest(importer.url) && !currentChain.includes(importer)) {
  51210. propagateUpdate(importer, boundaries, currentChain.concat(importer));
  51211. }
  51212. }
  51213. return false;
  51214. }
  51215. if (!node.importers.size) {
  51216. return true;
  51217. }
  51218. // #3716, #3913
  51219. // For a non-CSS file, if all of its importers are CSS files (registered via
  51220. // PostCSS plugins) it should be considered a dead end and force full reload.
  51221. if (!isCSSRequest(node.url) &&
  51222. [...node.importers].every((i) => isCSSRequest(i.url))) {
  51223. return true;
  51224. }
  51225. for (const importer of node.importers) {
  51226. const subChain = currentChain.concat(importer);
  51227. if (importer.acceptedHmrDeps.has(node)) {
  51228. boundaries.add({
  51229. boundary: importer,
  51230. acceptedVia: node
  51231. });
  51232. continue;
  51233. }
  51234. if (currentChain.includes(importer)) {
  51235. // circular deps is considered dead end
  51236. return true;
  51237. }
  51238. if (propagateUpdate(importer, boundaries, subChain)) {
  51239. return true;
  51240. }
  51241. }
  51242. return false;
  51243. }
  51244. function invalidate(mod, timestamp, seen) {
  51245. if (seen.has(mod)) {
  51246. return;
  51247. }
  51248. seen.add(mod);
  51249. mod.lastHMRTimestamp = timestamp;
  51250. mod.transformResult = null;
  51251. mod.ssrModule = null;
  51252. mod.ssrError = null;
  51253. mod.ssrTransformResult = null;
  51254. mod.importers.forEach((importer) => {
  51255. if (!importer.acceptedHmrDeps.has(mod)) {
  51256. invalidate(importer, timestamp, seen);
  51257. }
  51258. });
  51259. }
  51260. function handlePrunedModules(mods, { ws }) {
  51261. // update the disposed modules' hmr timestamp
  51262. // since if it's re-imported, it should re-apply side effects
  51263. // and without the timestamp the browser will not re-import it!
  51264. const t = Date.now();
  51265. mods.forEach((mod) => {
  51266. mod.lastHMRTimestamp = t;
  51267. debugHmr(`[dispose] ${colors$1.dim(mod.file)}`);
  51268. });
  51269. ws.send({
  51270. type: 'prune',
  51271. paths: [...mods].map((m) => m.url)
  51272. });
  51273. }
  51274. /**
  51275. * Lex import.meta.hot.accept() for accepted deps.
  51276. * Since hot.accept() can only accept string literals or array of string
  51277. * literals, we don't really need a heavy @babel/parse call on the entire source.
  51278. *
  51279. * @returns selfAccepts
  51280. */
  51281. function lexAcceptedHmrDeps(code, start, urls) {
  51282. let state = 0 /* inCall */;
  51283. // the state can only be 2 levels deep so no need for a stack
  51284. let prevState = 0 /* inCall */;
  51285. let currentDep = '';
  51286. function addDep(index) {
  51287. urls.add({
  51288. url: currentDep,
  51289. start: index - currentDep.length - 1,
  51290. end: index + 1
  51291. });
  51292. currentDep = '';
  51293. }
  51294. for (let i = start; i < code.length; i++) {
  51295. const char = code.charAt(i);
  51296. switch (state) {
  51297. case 0 /* inCall */:
  51298. case 4 /* inArray */:
  51299. if (char === `'`) {
  51300. prevState = state;
  51301. state = 1 /* inSingleQuoteString */;
  51302. }
  51303. else if (char === `"`) {
  51304. prevState = state;
  51305. state = 2 /* inDoubleQuoteString */;
  51306. }
  51307. else if (char === '`') {
  51308. prevState = state;
  51309. state = 3 /* inTemplateString */;
  51310. }
  51311. else if (/\s/.test(char)) {
  51312. continue;
  51313. }
  51314. else {
  51315. if (state === 0 /* inCall */) {
  51316. if (char === `[`) {
  51317. state = 4 /* inArray */;
  51318. }
  51319. else {
  51320. // reaching here means the first arg is neither a string literal
  51321. // nor an Array literal (direct callback) or there is no arg
  51322. // in both case this indicates a self-accepting module
  51323. return true; // done
  51324. }
  51325. }
  51326. else if (state === 4 /* inArray */) {
  51327. if (char === `]`) {
  51328. return false; // done
  51329. }
  51330. else if (char === ',') {
  51331. continue;
  51332. }
  51333. else {
  51334. error(i);
  51335. }
  51336. }
  51337. }
  51338. break;
  51339. case 1 /* inSingleQuoteString */:
  51340. if (char === `'`) {
  51341. addDep(i);
  51342. if (prevState === 0 /* inCall */) {
  51343. // accept('foo', ...)
  51344. return false;
  51345. }
  51346. else {
  51347. state = prevState;
  51348. }
  51349. }
  51350. else {
  51351. currentDep += char;
  51352. }
  51353. break;
  51354. case 2 /* inDoubleQuoteString */:
  51355. if (char === `"`) {
  51356. addDep(i);
  51357. if (prevState === 0 /* inCall */) {
  51358. // accept('foo', ...)
  51359. return false;
  51360. }
  51361. else {
  51362. state = prevState;
  51363. }
  51364. }
  51365. else {
  51366. currentDep += char;
  51367. }
  51368. break;
  51369. case 3 /* inTemplateString */:
  51370. if (char === '`') {
  51371. addDep(i);
  51372. if (prevState === 0 /* inCall */) {
  51373. // accept('foo', ...)
  51374. return false;
  51375. }
  51376. else {
  51377. state = prevState;
  51378. }
  51379. }
  51380. else if (char === '$' && code.charAt(i + 1) === '{') {
  51381. error(i);
  51382. }
  51383. else {
  51384. currentDep += char;
  51385. }
  51386. break;
  51387. default:
  51388. throw new Error('unknown import.meta.hot lexer state');
  51389. }
  51390. }
  51391. return false;
  51392. }
  51393. function error(pos) {
  51394. const err = new Error(`import.meta.accept() can only accept string literals or an ` +
  51395. `Array of string literals.`);
  51396. err.pos = pos;
  51397. throw err;
  51398. }
  51399. // vitejs/vite#610 when hot-reloading Vue files, we read immediately on file
  51400. // change event and sometimes this can be too early and get an empty buffer.
  51401. // Poll until the file's modified time has changed before reading again.
  51402. async function readModifiedFile(file) {
  51403. const content = fs__default.readFileSync(file, 'utf-8');
  51404. if (!content) {
  51405. const mtime = fs__default.statSync(file).mtimeMs;
  51406. await new Promise((r) => {
  51407. let n = 0;
  51408. const poll = async () => {
  51409. n++;
  51410. const newMtime = fs__default.statSync(file).mtimeMs;
  51411. if (newMtime !== mtime || n > 10) {
  51412. r(0);
  51413. }
  51414. else {
  51415. setTimeout(poll, 10);
  51416. }
  51417. };
  51418. setTimeout(poll, 10);
  51419. });
  51420. return fs__default.readFileSync(file, 'utf-8');
  51421. }
  51422. else {
  51423. return content;
  51424. }
  51425. }
  51426. const isDebug = !!process.env.DEBUG;
  51427. const debug$1 = createDebugger('vite:import-analysis');
  51428. const clientDir = normalizePath$3(CLIENT_DIR);
  51429. const skipRE = /\.(map|json)$/;
  51430. const canSkipImportAnalysis = (id) => skipRE.test(id) || isDirectCSSRequest(id);
  51431. const optimizedDepChunkRE = /\/chunk-[A-Z0-9]{8}\.js/;
  51432. const optimizedDepDynamicRE = /-[A-Z0-9]{8}\.js/;
  51433. function isExplicitImportRequired(url) {
  51434. return !isJSRequest(cleanUrl(url)) && !isCSSRequest(url);
  51435. }
  51436. function markExplicitImport(url) {
  51437. if (isExplicitImportRequired(url)) {
  51438. return injectQuery(url, 'import');
  51439. }
  51440. return url;
  51441. }
  51442. /**
  51443. * Server-only plugin that lexes, resolves, rewrites and analyzes url imports.
  51444. *
  51445. * - Imports are resolved to ensure they exist on disk
  51446. *
  51447. * - Lexes HMR accept calls and updates import relationships in the module graph
  51448. *
  51449. * - Bare module imports are resolved (by @rollup-plugin/node-resolve) to
  51450. * absolute file paths, e.g.
  51451. *
  51452. * ```js
  51453. * import 'foo'
  51454. * ```
  51455. * is rewritten to
  51456. * ```js
  51457. * import '/@fs//project/node_modules/foo/dist/foo.js'
  51458. * ```
  51459. *
  51460. * - CSS imports are appended with `.js` since both the js module and the actual
  51461. * css (referenced via <link>) may go through the transform pipeline:
  51462. *
  51463. * ```js
  51464. * import './style.css'
  51465. * ```
  51466. * is rewritten to
  51467. * ```js
  51468. * import './style.css.js'
  51469. * ```
  51470. */
  51471. function importAnalysisPlugin(config) {
  51472. const { root, base } = config;
  51473. const clientPublicPath = path__default.posix.join(base, CLIENT_PUBLIC_PATH);
  51474. const resolve = config.createResolver({
  51475. preferRelative: true,
  51476. tryIndex: false,
  51477. extensions: []
  51478. });
  51479. let server;
  51480. return {
  51481. name: 'vite:import-analysis',
  51482. configureServer(_server) {
  51483. server = _server;
  51484. },
  51485. async transform(source, importer, options) {
  51486. // In a real app `server` is always defined, but it is undefined when
  51487. // running src/node/server/__tests__/pluginContainer.spec.ts
  51488. if (!server) {
  51489. return null;
  51490. }
  51491. const ssr = (options === null || options === void 0 ? void 0 : options.ssr) === true;
  51492. const prettyImporter = prettifyUrl(importer, root);
  51493. if (canSkipImportAnalysis(importer)) {
  51494. isDebug && debug$1(colors$1.dim(`[skipped] ${prettyImporter}`));
  51495. return null;
  51496. }
  51497. const start = perf_hooks.performance.now();
  51498. await init;
  51499. let imports = [];
  51500. // strip UTF-8 BOM
  51501. if (source.charCodeAt(0) === 0xfeff) {
  51502. source = source.slice(1);
  51503. }
  51504. try {
  51505. imports = parse$e(source)[0];
  51506. }
  51507. catch (e) {
  51508. const isVue = importer.endsWith('.vue');
  51509. const maybeJSX = !isVue && isJSRequest(importer);
  51510. const msg = isVue
  51511. ? `Install @vitejs/plugin-vue to handle .vue files.`
  51512. : maybeJSX
  51513. ? `If you are using JSX, make sure to name the file with the .jsx or .tsx extension.`
  51514. : `You may need to install appropriate plugins to handle the ${path__default.extname(importer)} file format.`;
  51515. this.error(`Failed to parse source for import analysis because the content ` +
  51516. `contains invalid JS syntax. ` +
  51517. msg, e.idx);
  51518. }
  51519. const { moduleGraph } = server;
  51520. // since we are already in the transform phase of the importer, it must
  51521. // have been loaded so its entry is guaranteed in the module graph.
  51522. const importerModule = moduleGraph.getModuleById(importer);
  51523. if (!importerModule && isOptimizedDepFile(importer, config)) {
  51524. // Ids of optimized deps could be invalidated and removed from the graph
  51525. // Return without transforming, this request is no longer valid, a full reload
  51526. // is going to request this id again. Throwing an outdated error so we
  51527. // properly finish the request with a 504 sent to the browser.
  51528. throwOutdatedRequest(importer);
  51529. }
  51530. if (!imports.length) {
  51531. importerModule.isSelfAccepting = false;
  51532. isDebug &&
  51533. debug$1(`${timeFrom(start)} ${colors$1.dim(`[no imports] ${prettyImporter}`)}`);
  51534. return source;
  51535. }
  51536. let hasHMR = false;
  51537. let isSelfAccepting = false;
  51538. let hasEnv = false;
  51539. let needQueryInjectHelper = false;
  51540. let s;
  51541. const str = () => s || (s = new MagicString(source));
  51542. const importedUrls = new Set();
  51543. const staticImportedUrls = new Set();
  51544. const acceptedUrls = new Set();
  51545. const toAbsoluteUrl = (url) => path__default.posix.resolve(path__default.posix.dirname(importerModule.url), url);
  51546. const normalizeUrl = async (url, pos) => {
  51547. var _a;
  51548. if (base !== '/' && url.startsWith(base)) {
  51549. url = url.replace(base, '/');
  51550. }
  51551. let importerFile = importer;
  51552. if (moduleListContains((_a = config.optimizeDeps) === null || _a === void 0 ? void 0 : _a.exclude, url)) {
  51553. const optimizedDeps = server._optimizedDeps;
  51554. if (optimizedDeps) {
  51555. await optimizedDeps.scanProcessing;
  51556. // if the dependency encountered in the optimized file was excluded from the optimization
  51557. // the dependency needs to be resolved starting from the original source location of the optimized file
  51558. // because starting from node_modules/.vite will not find the dependency if it was not hoisted
  51559. // (that is, if it is under node_modules directory in the package source of the optimized file)
  51560. for (const optimizedModule of optimizedDeps.metadata.depInfoList) {
  51561. if (!optimizedModule.src)
  51562. continue; // Ignore chunks
  51563. if (optimizedModule.file === importerModule.file) {
  51564. importerFile = optimizedModule.src;
  51565. }
  51566. }
  51567. }
  51568. }
  51569. const resolved = await this.resolve(url, importerFile);
  51570. if (!resolved) {
  51571. // in ssr, we should let node handle the missing modules
  51572. if (ssr) {
  51573. return [url, url];
  51574. }
  51575. this.error(`Failed to resolve import "${url}" from "${path__default.relative(process.cwd(), importerFile)}". Does the file exist?`, pos);
  51576. }
  51577. const isRelative = url.startsWith('.');
  51578. const isSelfImport = !isRelative && cleanUrl(url) === cleanUrl(importer);
  51579. // normalize all imports into resolved URLs
  51580. // e.g. `import 'foo'` -> `import '/@fs/.../node_modules/foo/index.js'`
  51581. if (resolved.id.startsWith(root + '/')) {
  51582. // in root: infer short absolute path from root
  51583. url = resolved.id.slice(root.length);
  51584. }
  51585. else if (resolved.id.startsWith(getDepsCacheDir(config)) ||
  51586. fs__default.existsSync(cleanUrl(resolved.id))) {
  51587. // an optimized deps may not yet exists in the filesystem, or
  51588. // a regular file exists but is out of root: rewrite to absolute /@fs/ paths
  51589. url = path__default.posix.join(FS_PREFIX + resolved.id);
  51590. }
  51591. else {
  51592. url = resolved.id;
  51593. }
  51594. if (isExternalUrl(url)) {
  51595. return [url, url];
  51596. }
  51597. // if the resolved id is not a valid browser import specifier,
  51598. // prefix it to make it valid. We will strip this before feeding it
  51599. // back into the transform pipeline
  51600. if (!url.startsWith('.') && !url.startsWith('/')) {
  51601. url =
  51602. VALID_ID_PREFIX + resolved.id.replace('\0', NULL_BYTE_PLACEHOLDER);
  51603. }
  51604. // make the URL browser-valid if not SSR
  51605. if (!ssr) {
  51606. // mark non-js/css imports with `?import`
  51607. url = markExplicitImport(url);
  51608. // If the url isn't a request for a pre-bundled common chunk,
  51609. // for relative js/css imports, or self-module virtual imports
  51610. // (e.g. vue blocks), inherit importer's version query
  51611. // do not do this for unknown type imports, otherwise the appended
  51612. // query can break 3rd party plugin's extension checks.
  51613. if ((isRelative || isSelfImport) &&
  51614. !/[\?&]import=?\b/.test(url) &&
  51615. !url.match(DEP_VERSION_RE)) {
  51616. const versionMatch = importer.match(DEP_VERSION_RE);
  51617. if (versionMatch) {
  51618. url = injectQuery(url, versionMatch[1]);
  51619. }
  51620. }
  51621. // check if the dep has been hmr updated. If yes, we need to attach
  51622. // its last updated timestamp to force the browser to fetch the most
  51623. // up-to-date version of this module.
  51624. try {
  51625. const depModule = await moduleGraph.ensureEntryFromUrl(url, ssr);
  51626. if (depModule.lastHMRTimestamp > 0) {
  51627. url = injectQuery(url, `t=${depModule.lastHMRTimestamp}`);
  51628. }
  51629. }
  51630. catch (e) {
  51631. // it's possible that the dep fails to resolve (non-existent import)
  51632. // attach location to the missing import
  51633. e.pos = pos;
  51634. throw e;
  51635. }
  51636. // prepend base (dev base is guaranteed to have ending slash)
  51637. url = base + url.replace(/^\//, '');
  51638. }
  51639. return [url, resolved.id];
  51640. };
  51641. // Import rewrites, we do them after all the URLs have been resolved
  51642. // to help with the discovery of new dependencies. If we need to wait
  51643. // for each dependency there could be one reload per import
  51644. const importRewrites = [];
  51645. for (let index = 0; index < imports.length; index++) {
  51646. const { s: start, e: end, ss: expStart, se: expEnd, d: dynamicIndex,
  51647. // #2083 User may use escape path,
  51648. // so use imports[index].n to get the unescaped string
  51649. // @ts-ignore
  51650. n: specifier } = imports[index];
  51651. const rawUrl = source.slice(start, end);
  51652. // check import.meta usage
  51653. if (rawUrl === 'import.meta') {
  51654. const prop = source.slice(end, end + 4);
  51655. if (prop === '.hot') {
  51656. hasHMR = true;
  51657. if (source.slice(end + 4, end + 11) === '.accept') {
  51658. // further analyze accepted modules
  51659. if (lexAcceptedHmrDeps(source, source.indexOf('(', end + 11) + 1, acceptedUrls)) {
  51660. isSelfAccepting = true;
  51661. }
  51662. }
  51663. }
  51664. else if (prop === '.env') {
  51665. hasEnv = true;
  51666. }
  51667. else if (prop === '.glo' && source[end + 4] === 'b') {
  51668. // transform import.meta.glob()
  51669. // e.g. `import.meta.glob('glob:./dir/*.js')`
  51670. const { imports, importsString, exp, endIndex, base, pattern, isEager } = await transformImportGlob(source, start, importer, index, root, config.logger, normalizeUrl, resolve);
  51671. str().prepend(importsString);
  51672. str().overwrite(expStart, endIndex, exp, { contentOnly: true });
  51673. imports.forEach((url) => {
  51674. url = url.replace(base, '/');
  51675. importedUrls.add(url);
  51676. if (isEager)
  51677. staticImportedUrls.add(url);
  51678. });
  51679. if (!(importerModule.file in server._globImporters)) {
  51680. server._globImporters[importerModule.file] = {
  51681. module: importerModule,
  51682. importGlobs: []
  51683. };
  51684. }
  51685. server._globImporters[importerModule.file].importGlobs.push({
  51686. base,
  51687. pattern
  51688. });
  51689. }
  51690. continue;
  51691. }
  51692. const isDynamicImport = dynamicIndex > -1;
  51693. // static import or valid string in dynamic import
  51694. // If resolvable, let's resolve it
  51695. if (specifier) {
  51696. // skip external / data uri
  51697. if (isExternalUrl(specifier) || isDataUrl(specifier)) {
  51698. continue;
  51699. }
  51700. // skip ssr external
  51701. if (ssr) {
  51702. if (server._ssrExternals &&
  51703. shouldExternalizeForSSR(specifier, server._ssrExternals)) {
  51704. continue;
  51705. }
  51706. if (isBuiltin(specifier)) {
  51707. continue;
  51708. }
  51709. }
  51710. // skip client
  51711. if (specifier === clientPublicPath) {
  51712. continue;
  51713. }
  51714. // warn imports to non-asset /public files
  51715. if (specifier.startsWith('/') &&
  51716. !config.assetsInclude(cleanUrl(specifier)) &&
  51717. !specifier.endsWith('.json') &&
  51718. checkPublicFile(specifier, config)) {
  51719. throw new Error(`Cannot import non-asset file ${specifier} which is inside /public.` +
  51720. `JS/CSS files inside /public are copied as-is on build and ` +
  51721. `can only be referenced via <script src> or <link href> in html.`);
  51722. }
  51723. // normalize
  51724. const [normalizedUrl, resolvedId] = await normalizeUrl(specifier, start);
  51725. const url = normalizedUrl;
  51726. // record as safe modules
  51727. server === null || server === void 0 ? void 0 : server.moduleGraph.safeModulesPath.add(fsPathFromUrl(url));
  51728. if (url !== specifier) {
  51729. importRewrites.push(async () => {
  51730. let rewriteDone = false;
  51731. if ((server === null || server === void 0 ? void 0 : server._optimizedDeps) &&
  51732. isOptimizedDepFile(resolvedId, config) &&
  51733. !resolvedId.match(optimizedDepChunkRE)) {
  51734. // for optimized cjs deps, support named imports by rewriting named imports to const assignments.
  51735. // internal optimized chunks don't need es interop and are excluded
  51736. // The browserHash in resolvedId could be stale in which case there will be a full
  51737. // page reload. We could return a 404 in that case but it is safe to return the request
  51738. const file = cleanUrl(resolvedId); // Remove ?v={hash}
  51739. const needsInterop = await optimizedDepNeedsInterop(server._optimizedDeps.metadata, file);
  51740. if (needsInterop === undefined) {
  51741. // Non-entry dynamic imports from dependencies will reach here as there isn't
  51742. // optimize info for them, but they don't need es interop. If the request isn't
  51743. // a dynamic import, then it is an internal Vite error
  51744. if (!file.match(optimizedDepDynamicRE)) {
  51745. config.logger.error(colors$1.red(`Vite Error, ${url} optimized info should be defined`));
  51746. }
  51747. }
  51748. else if (needsInterop) {
  51749. debug$1(`${url} needs interop`);
  51750. if (isDynamicImport) {
  51751. // rewrite `import('package')` to expose the default directly
  51752. str().overwrite(expStart, expEnd, `import('${url}').then(m => m.default && m.default.__esModule ? m.default : ({ ...m.default, default: m.default }))`, { contentOnly: true });
  51753. }
  51754. else {
  51755. const exp = source.slice(expStart, expEnd);
  51756. const rewritten = transformCjsImport(exp, url, rawUrl, index);
  51757. if (rewritten) {
  51758. str().overwrite(expStart, expEnd, rewritten, {
  51759. contentOnly: true
  51760. });
  51761. }
  51762. else {
  51763. // #1439 export * from '...'
  51764. str().overwrite(start, end, url, { contentOnly: true });
  51765. }
  51766. }
  51767. rewriteDone = true;
  51768. }
  51769. }
  51770. if (!rewriteDone) {
  51771. str().overwrite(start, end, isDynamicImport ? `'${url}'` : url, { contentOnly: true });
  51772. }
  51773. });
  51774. }
  51775. // record for HMR import chain analysis
  51776. // make sure to normalize away base
  51777. const urlWithoutBase = url.replace(base, '/');
  51778. importedUrls.add(urlWithoutBase);
  51779. if (!isDynamicImport) {
  51780. // for pre-transforming
  51781. staticImportedUrls.add(urlWithoutBase);
  51782. }
  51783. }
  51784. else if (!importer.startsWith(clientDir) && !ssr) {
  51785. // check @vite-ignore which suppresses dynamic import warning
  51786. const hasViteIgnore = /\/\*\s*@vite-ignore\s*\*\//.test(
  51787. // complete expression inside parens
  51788. source.slice(dynamicIndex + 1, end));
  51789. const url = rawUrl
  51790. .replace(/\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/gm, '')
  51791. .trim();
  51792. if (!hasViteIgnore && !isSupportedDynamicImport(url)) {
  51793. this.warn(`\n` +
  51794. colors$1.cyan(importerModule.file) +
  51795. `\n` +
  51796. generateCodeFrame(source, start) +
  51797. `\nThe above dynamic import cannot be analyzed by vite.\n` +
  51798. `See ${colors$1.blue(`https://github.com/rollup/plugins/tree/master/packages/dynamic-import-vars#limitations`)} ` +
  51799. `for supported dynamic import formats. ` +
  51800. `If this is intended to be left as-is, you can use the ` +
  51801. `/* @vite-ignore */ comment inside the import() call to suppress this warning.\n`);
  51802. }
  51803. if (!/^('.*'|".*"|`.*`)$/.test(url) ||
  51804. isExplicitImportRequired(url.slice(1, -1))) {
  51805. needQueryInjectHelper = true;
  51806. str().overwrite(start, end, `__vite__injectQuery(${url}, 'import')`, { contentOnly: true });
  51807. }
  51808. }
  51809. }
  51810. if (hasEnv) {
  51811. // inject import.meta.env
  51812. let env = `import.meta.env = ${JSON.stringify({
  51813. ...config.env,
  51814. SSR: !!ssr
  51815. })};`;
  51816. // account for user env defines
  51817. for (const key in config.define) {
  51818. if (key.startsWith(`import.meta.env.`)) {
  51819. const val = config.define[key];
  51820. env += `${key} = ${typeof val === 'string' ? val : JSON.stringify(val)};`;
  51821. }
  51822. }
  51823. str().prepend(env);
  51824. }
  51825. if (hasHMR && !ssr) {
  51826. debugHmr(`${isSelfAccepting
  51827. ? `[self-accepts]`
  51828. : acceptedUrls.size
  51829. ? `[accepts-deps]`
  51830. : `[detected api usage]`} ${prettyImporter}`);
  51831. // inject hot context
  51832. str().prepend(`import { createHotContext as __vite__createHotContext } from "${clientPublicPath}";` +
  51833. `import.meta.hot = __vite__createHotContext(${JSON.stringify(importerModule.url)});`);
  51834. }
  51835. if (needQueryInjectHelper) {
  51836. str().prepend(`import { injectQuery as __vite__injectQuery } from "${clientPublicPath}";`);
  51837. }
  51838. // normalize and rewrite accepted urls
  51839. const normalizedAcceptedUrls = new Set();
  51840. for (const { url, start, end } of acceptedUrls) {
  51841. const [normalized] = await moduleGraph.resolveUrl(toAbsoluteUrl(markExplicitImport(url)), ssr);
  51842. normalizedAcceptedUrls.add(normalized);
  51843. str().overwrite(start, end, JSON.stringify(normalized), {
  51844. contentOnly: true
  51845. });
  51846. }
  51847. // update the module graph for HMR analysis.
  51848. // node CSS imports does its own graph update in the css plugin so we
  51849. // only handle js graph updates here.
  51850. if (!isCSSRequest(importer)) {
  51851. // attached by pluginContainer.addWatchFile
  51852. const pluginImports = this._addedImports;
  51853. if (pluginImports) {
  51854. (await Promise.all([...pluginImports].map((id) => normalizeUrl(id, 0)))).forEach(([url]) => importedUrls.add(url));
  51855. }
  51856. // HMR transforms are no-ops in SSR, so an `accept` call will
  51857. // never be injected. Avoid updating the `isSelfAccepting`
  51858. // property for our module node in that case.
  51859. if (ssr && importerModule.isSelfAccepting) {
  51860. isSelfAccepting = true;
  51861. }
  51862. const prunedImports = await moduleGraph.updateModuleInfo(importerModule, importedUrls, normalizedAcceptedUrls, isSelfAccepting, ssr);
  51863. if (hasHMR && prunedImports) {
  51864. handlePrunedModules(prunedImports, server);
  51865. }
  51866. }
  51867. isDebug &&
  51868. debug$1(`${timeFrom(start)} ${colors$1.dim(`[${importedUrls.size} imports rewritten] ${prettyImporter}`)}`);
  51869. // pre-transform known direct imports
  51870. if (config.server.preTransformRequests && staticImportedUrls.size) {
  51871. staticImportedUrls.forEach((url) => {
  51872. url = unwrapId(removeImportQuery(url)).replace(NULL_BYTE_PLACEHOLDER, '\0');
  51873. transformRequest(url, server, { ssr }).catch((e) => {
  51874. if ((e === null || e === void 0 ? void 0 : e.code) === ERR_OUTDATED_OPTIMIZED_DEP) {
  51875. // This are expected errors
  51876. return;
  51877. }
  51878. // Unexpected error, log the issue but avoid an unhandled exception
  51879. config.logger.error(e.message);
  51880. });
  51881. });
  51882. }
  51883. // Await for import rewrites that requires dependencies to be pre-bundled to
  51884. // know if es interop is needed after starting further transformRequest calls
  51885. // This will let Vite process deeper into the user code and find more missing
  51886. // dependencies before the next page reload
  51887. for (const rewrite of importRewrites) {
  51888. await rewrite();
  51889. }
  51890. if (s) {
  51891. return s.toString();
  51892. }
  51893. else {
  51894. return source;
  51895. }
  51896. }
  51897. };
  51898. }
  51899. /**
  51900. * https://github.com/rollup/plugins/tree/master/packages/dynamic-import-vars#limitations
  51901. * This is probably less accurate but is much cheaper than a full AST parse.
  51902. */
  51903. function isSupportedDynamicImport(url) {
  51904. url = url.trim().slice(1, -1);
  51905. // must be relative
  51906. if (!url.startsWith('./') && !url.startsWith('../')) {
  51907. return false;
  51908. }
  51909. // must have extension
  51910. if (!path__default.extname(url)) {
  51911. return false;
  51912. }
  51913. // must be more specific if importing from same dir
  51914. if (url.startsWith('./${') && url.indexOf('/') === url.lastIndexOf('/')) {
  51915. return false;
  51916. }
  51917. return true;
  51918. }
  51919. /**
  51920. * Detect import statements to a known optimized CJS dependency and provide
  51921. * ES named imports interop. We do this by rewriting named imports to a variable
  51922. * assignment to the corresponding property on the `module.exports` of the cjs
  51923. * module. Note this doesn't support dynamic re-assignments from within the cjs
  51924. * module.
  51925. *
  51926. * Note that es-module-lexer treats `export * from '...'` as an import as well,
  51927. * so, we may encounter ExportAllDeclaration here, in which case `undefined`
  51928. * will be returned.
  51929. *
  51930. * Credits \@csr632 via #837
  51931. */
  51932. function transformCjsImport(importExp, url, rawUrl, importIndex) {
  51933. const node = parse$a(importExp, {
  51934. ecmaVersion: 'latest',
  51935. sourceType: 'module'
  51936. }).body[0];
  51937. if (node.type === 'ImportDeclaration' ||
  51938. node.type === 'ExportNamedDeclaration') {
  51939. if (!node.specifiers.length) {
  51940. return `import "${url}"`;
  51941. }
  51942. const importNames = [];
  51943. const exportNames = [];
  51944. let defaultExports = '';
  51945. for (const spec of node.specifiers) {
  51946. if (spec.type === 'ImportSpecifier' &&
  51947. spec.imported.type === 'Identifier') {
  51948. const importedName = spec.imported.name;
  51949. const localName = spec.local.name;
  51950. importNames.push({ importedName, localName });
  51951. }
  51952. else if (spec.type === 'ImportDefaultSpecifier') {
  51953. importNames.push({
  51954. importedName: 'default',
  51955. localName: spec.local.name
  51956. });
  51957. }
  51958. else if (spec.type === 'ImportNamespaceSpecifier') {
  51959. importNames.push({ importedName: '*', localName: spec.local.name });
  51960. }
  51961. else if (spec.type === 'ExportSpecifier' &&
  51962. spec.exported.type === 'Identifier') {
  51963. // for ExportSpecifier, local name is same as imported name
  51964. const importedName = spec.local.name;
  51965. // we want to specify exported name as variable and re-export it
  51966. const exportedName = spec.exported.name;
  51967. if (exportedName === 'default') {
  51968. defaultExports = makeLegalIdentifier$1(`__vite__cjsExportDefault_${importIndex}`);
  51969. importNames.push({ importedName, localName: defaultExports });
  51970. }
  51971. else {
  51972. importNames.push({ importedName, localName: exportedName });
  51973. exportNames.push(exportedName);
  51974. }
  51975. }
  51976. }
  51977. // If there is multiple import for same id in one file,
  51978. // importIndex will prevent the cjsModuleName to be duplicate
  51979. const cjsModuleName = makeLegalIdentifier$1(`__vite__cjsImport${importIndex}_${rawUrl}`);
  51980. const lines = [`import ${cjsModuleName} from "${url}"`];
  51981. importNames.forEach(({ importedName, localName }) => {
  51982. if (importedName === '*') {
  51983. lines.push(`const ${localName} = ${cjsModuleName}`);
  51984. }
  51985. else if (importedName === 'default') {
  51986. lines.push(`const ${localName} = ${cjsModuleName}.__esModule ? ${cjsModuleName}.default : ${cjsModuleName}`);
  51987. }
  51988. else {
  51989. lines.push(`const ${localName} = ${cjsModuleName}["${importedName}"]`);
  51990. }
  51991. });
  51992. if (defaultExports) {
  51993. lines.push(`export default ${defaultExports}`);
  51994. }
  51995. if (exportNames.length) {
  51996. lines.push(`export { ${exportNames.join(', ')} }`);
  51997. }
  51998. return lines.join('; ');
  51999. }
  52000. }
  52001. class ModuleNode {
  52002. constructor(url) {
  52003. /**
  52004. * Resolved file system path + query
  52005. */
  52006. this.id = null;
  52007. this.file = null;
  52008. this.importers = new Set();
  52009. this.importedModules = new Set();
  52010. this.acceptedHmrDeps = new Set();
  52011. this.transformResult = null;
  52012. this.ssrTransformResult = null;
  52013. this.ssrModule = null;
  52014. this.ssrError = null;
  52015. this.lastHMRTimestamp = 0;
  52016. this.lastInvalidationTimestamp = 0;
  52017. this.url = url;
  52018. this.type = isDirectCSSRequest(url) ? 'css' : 'js';
  52019. // #7870
  52020. // The `isSelfAccepting` value is set by importAnalysis, but some
  52021. // assets don't go through importAnalysis.
  52022. if (isHTMLRequest(url) || canSkipImportAnalysis(url)) {
  52023. this.isSelfAccepting = false;
  52024. }
  52025. }
  52026. }
  52027. function invalidateSSRModule(mod, seen) {
  52028. if (seen.has(mod)) {
  52029. return;
  52030. }
  52031. seen.add(mod);
  52032. mod.ssrModule = null;
  52033. mod.importers.forEach((importer) => invalidateSSRModule(importer, seen));
  52034. }
  52035. class ModuleGraph {
  52036. constructor(resolveId) {
  52037. this.resolveId = resolveId;
  52038. this.urlToModuleMap = new Map();
  52039. this.idToModuleMap = new Map();
  52040. // a single file may corresponds to multiple modules with different queries
  52041. this.fileToModulesMap = new Map();
  52042. this.safeModulesPath = new Set();
  52043. }
  52044. async getModuleByUrl(rawUrl, ssr) {
  52045. const [url] = await this.resolveUrl(rawUrl, ssr);
  52046. return this.urlToModuleMap.get(url);
  52047. }
  52048. getModuleById(id) {
  52049. return this.idToModuleMap.get(removeTimestampQuery(id));
  52050. }
  52051. getModulesByFile(file) {
  52052. return this.fileToModulesMap.get(file);
  52053. }
  52054. onFileChange(file) {
  52055. const mods = this.getModulesByFile(file);
  52056. if (mods) {
  52057. const seen = new Set();
  52058. mods.forEach((mod) => {
  52059. this.invalidateModule(mod, seen);
  52060. });
  52061. }
  52062. }
  52063. invalidateModule(mod, seen = new Set(), timestamp = Date.now()) {
  52064. // Save the timestamp for this invalidation, so we can avoid caching the result of possible already started
  52065. // processing being done for this module
  52066. mod.lastInvalidationTimestamp = timestamp;
  52067. // Don't invalidate mod.info and mod.meta, as they are part of the processing pipeline
  52068. // Invalidating the transform result is enough to ensure this module is re-processed next time it is requested
  52069. mod.transformResult = null;
  52070. mod.ssrTransformResult = null;
  52071. invalidateSSRModule(mod, seen);
  52072. }
  52073. invalidateAll() {
  52074. const timestamp = Date.now();
  52075. const seen = new Set();
  52076. this.idToModuleMap.forEach((mod) => {
  52077. this.invalidateModule(mod, seen, timestamp);
  52078. });
  52079. }
  52080. /**
  52081. * Update the module graph based on a module's updated imports information
  52082. * If there are dependencies that no longer have any importers, they are
  52083. * returned as a Set.
  52084. */
  52085. async updateModuleInfo(mod, importedModules, acceptedModules, isSelfAccepting, ssr) {
  52086. mod.isSelfAccepting = isSelfAccepting;
  52087. const prevImports = mod.importedModules;
  52088. const nextImports = (mod.importedModules = new Set());
  52089. let noLongerImported;
  52090. // update import graph
  52091. for (const imported of importedModules) {
  52092. const dep = typeof imported === 'string'
  52093. ? await this.ensureEntryFromUrl(imported, ssr)
  52094. : imported;
  52095. dep.importers.add(mod);
  52096. nextImports.add(dep);
  52097. }
  52098. // remove the importer from deps that were imported but no longer are.
  52099. prevImports.forEach((dep) => {
  52100. if (!nextImports.has(dep)) {
  52101. dep.importers.delete(mod);
  52102. if (!dep.importers.size) {
  52103. (noLongerImported || (noLongerImported = new Set())).add(dep);
  52104. }
  52105. }
  52106. });
  52107. // update accepted hmr deps
  52108. const deps = (mod.acceptedHmrDeps = new Set());
  52109. for (const accepted of acceptedModules) {
  52110. const dep = typeof accepted === 'string'
  52111. ? await this.ensureEntryFromUrl(accepted, ssr)
  52112. : accepted;
  52113. deps.add(dep);
  52114. }
  52115. return noLongerImported;
  52116. }
  52117. async ensureEntryFromUrl(rawUrl, ssr) {
  52118. const [url, resolvedId, meta] = await this.resolveUrl(rawUrl, ssr);
  52119. let mod = this.urlToModuleMap.get(url);
  52120. if (!mod) {
  52121. mod = new ModuleNode(url);
  52122. if (meta)
  52123. mod.meta = meta;
  52124. this.urlToModuleMap.set(url, mod);
  52125. mod.id = resolvedId;
  52126. this.idToModuleMap.set(resolvedId, mod);
  52127. const file = (mod.file = cleanUrl(resolvedId));
  52128. let fileMappedModules = this.fileToModulesMap.get(file);
  52129. if (!fileMappedModules) {
  52130. fileMappedModules = new Set();
  52131. this.fileToModulesMap.set(file, fileMappedModules);
  52132. }
  52133. fileMappedModules.add(mod);
  52134. }
  52135. return mod;
  52136. }
  52137. // some deps, like a css file referenced via @import, don't have its own
  52138. // url because they are inlined into the main css import. But they still
  52139. // need to be represented in the module graph so that they can trigger
  52140. // hmr in the importing css file.
  52141. createFileOnlyEntry(file) {
  52142. file = normalizePath$3(file);
  52143. let fileMappedModules = this.fileToModulesMap.get(file);
  52144. if (!fileMappedModules) {
  52145. fileMappedModules = new Set();
  52146. this.fileToModulesMap.set(file, fileMappedModules);
  52147. }
  52148. const url = `${FS_PREFIX}${file}`;
  52149. for (const m of fileMappedModules) {
  52150. if (m.url === url || m.id === file) {
  52151. return m;
  52152. }
  52153. }
  52154. const mod = new ModuleNode(url);
  52155. mod.file = file;
  52156. fileMappedModules.add(mod);
  52157. return mod;
  52158. }
  52159. // for incoming urls, it is important to:
  52160. // 1. remove the HMR timestamp query (?t=xxxx)
  52161. // 2. resolve its extension so that urls with or without extension all map to
  52162. // the same module
  52163. async resolveUrl(url, ssr) {
  52164. url = removeImportQuery(removeTimestampQuery(url));
  52165. const resolved = await this.resolveId(url, !!ssr);
  52166. const resolvedId = (resolved === null || resolved === void 0 ? void 0 : resolved.id) || url;
  52167. const ext = path$r.extname(cleanUrl(resolvedId));
  52168. const { pathname, search, hash } = require$$0$6.parse(url);
  52169. if (ext && !pathname.endsWith(ext)) {
  52170. url = pathname + ext + (search || '') + (hash || '');
  52171. }
  52172. return [url, resolvedId, resolved === null || resolved === void 0 ? void 0 : resolved.meta];
  52173. }
  52174. }
  52175. var isWsl$2 = {exports: {}};
  52176. const fs$5 = fs__default;
  52177. let isDocker$2;
  52178. function hasDockerEnv() {
  52179. try {
  52180. fs$5.statSync('/.dockerenv');
  52181. return true;
  52182. } catch (_) {
  52183. return false;
  52184. }
  52185. }
  52186. function hasDockerCGroup() {
  52187. try {
  52188. return fs$5.readFileSync('/proc/self/cgroup', 'utf8').includes('docker');
  52189. } catch (_) {
  52190. return false;
  52191. }
  52192. }
  52193. var isDocker_1 = () => {
  52194. if (isDocker$2 === undefined) {
  52195. isDocker$2 = hasDockerEnv() || hasDockerCGroup();
  52196. }
  52197. return isDocker$2;
  52198. };
  52199. const os = require$$2__default;
  52200. const fs$4 = fs__default;
  52201. const isDocker$1 = isDocker_1;
  52202. const isWsl$1 = () => {
  52203. if (process.platform !== 'linux') {
  52204. return false;
  52205. }
  52206. if (os.release().toLowerCase().includes('microsoft')) {
  52207. if (isDocker$1()) {
  52208. return false;
  52209. }
  52210. return true;
  52211. }
  52212. try {
  52213. return fs$4.readFileSync('/proc/version', 'utf8').toLowerCase().includes('microsoft') ?
  52214. !isDocker$1() : false;
  52215. } catch (_) {
  52216. return false;
  52217. }
  52218. };
  52219. if (process.env.__IS_WSL_TEST__) {
  52220. isWsl$2.exports = isWsl$1;
  52221. } else {
  52222. isWsl$2.exports = isWsl$1();
  52223. }
  52224. var defineLazyProp = (object, propertyName, fn) => {
  52225. const define = value => Object.defineProperty(object, propertyName, {value, enumerable: true, writable: true});
  52226. Object.defineProperty(object, propertyName, {
  52227. configurable: true,
  52228. enumerable: true,
  52229. get() {
  52230. const result = fn();
  52231. define(result);
  52232. return result;
  52233. },
  52234. set(value) {
  52235. define(value);
  52236. }
  52237. });
  52238. return object;
  52239. };
  52240. const path$3 = path__default;
  52241. const childProcess = require$$2__default$1;
  52242. const {promises: fs$3, constants: fsConstants} = fs__default;
  52243. const isWsl = isWsl$2.exports;
  52244. const isDocker = isDocker_1;
  52245. const defineLazyProperty = defineLazyProp;
  52246. // Path to included `xdg-open`.
  52247. const localXdgOpenPath = path$3.join(__dirname, 'xdg-open');
  52248. const {platform, arch} = process;
  52249. /**
  52250. Get the mount point for fixed drives in WSL.
  52251. @inner
  52252. @returns {string} The mount point.
  52253. */
  52254. const getWslDrivesMountPoint = (() => {
  52255. // Default value for "root" param
  52256. // according to https://docs.microsoft.com/en-us/windows/wsl/wsl-config
  52257. const defaultMountPoint = '/mnt/';
  52258. let mountPoint;
  52259. return async function () {
  52260. if (mountPoint) {
  52261. // Return memoized mount point value
  52262. return mountPoint;
  52263. }
  52264. const configFilePath = '/etc/wsl.conf';
  52265. let isConfigFileExists = false;
  52266. try {
  52267. await fs$3.access(configFilePath, fsConstants.F_OK);
  52268. isConfigFileExists = true;
  52269. } catch {}
  52270. if (!isConfigFileExists) {
  52271. return defaultMountPoint;
  52272. }
  52273. const configContent = await fs$3.readFile(configFilePath, {encoding: 'utf8'});
  52274. const configMountPoint = /(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(configContent);
  52275. if (!configMountPoint) {
  52276. return defaultMountPoint;
  52277. }
  52278. mountPoint = configMountPoint.groups.mountPoint.trim();
  52279. mountPoint = mountPoint.endsWith('/') ? mountPoint : `${mountPoint}/`;
  52280. return mountPoint;
  52281. };
  52282. })();
  52283. const pTryEach = async (array, mapper) => {
  52284. let latestError;
  52285. for (const item of array) {
  52286. try {
  52287. return await mapper(item); // eslint-disable-line no-await-in-loop
  52288. } catch (error) {
  52289. latestError = error;
  52290. }
  52291. }
  52292. throw latestError;
  52293. };
  52294. const baseOpen = async options => {
  52295. options = {
  52296. wait: false,
  52297. background: false,
  52298. newInstance: false,
  52299. allowNonzeroExitCode: false,
  52300. ...options
  52301. };
  52302. if (Array.isArray(options.app)) {
  52303. return pTryEach(options.app, singleApp => baseOpen({
  52304. ...options,
  52305. app: singleApp
  52306. }));
  52307. }
  52308. let {name: app, arguments: appArguments = []} = options.app || {};
  52309. appArguments = [...appArguments];
  52310. if (Array.isArray(app)) {
  52311. return pTryEach(app, appName => baseOpen({
  52312. ...options,
  52313. app: {
  52314. name: appName,
  52315. arguments: appArguments
  52316. }
  52317. }));
  52318. }
  52319. let command;
  52320. const cliArguments = [];
  52321. const childProcessOptions = {};
  52322. if (platform === 'darwin') {
  52323. command = 'open';
  52324. if (options.wait) {
  52325. cliArguments.push('--wait-apps');
  52326. }
  52327. if (options.background) {
  52328. cliArguments.push('--background');
  52329. }
  52330. if (options.newInstance) {
  52331. cliArguments.push('--new');
  52332. }
  52333. if (app) {
  52334. cliArguments.push('-a', app);
  52335. }
  52336. } else if (platform === 'win32' || (isWsl && !isDocker())) {
  52337. const mountPoint = await getWslDrivesMountPoint();
  52338. command = isWsl ?
  52339. `${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe` :
  52340. `${process.env.SYSTEMROOT}\\System32\\WindowsPowerShell\\v1.0\\powershell`;
  52341. cliArguments.push(
  52342. '-NoProfile',
  52343. '-NonInteractive',
  52344. '–ExecutionPolicy',
  52345. 'Bypass',
  52346. '-EncodedCommand'
  52347. );
  52348. if (!isWsl) {
  52349. childProcessOptions.windowsVerbatimArguments = true;
  52350. }
  52351. const encodedArguments = ['Start'];
  52352. if (options.wait) {
  52353. encodedArguments.push('-Wait');
  52354. }
  52355. if (app) {
  52356. // Double quote with double quotes to ensure the inner quotes are passed through.
  52357. // Inner quotes are delimited for PowerShell interpretation with backticks.
  52358. encodedArguments.push(`"\`"${app}\`""`, '-ArgumentList');
  52359. if (options.target) {
  52360. appArguments.unshift(options.target);
  52361. }
  52362. } else if (options.target) {
  52363. encodedArguments.push(`"${options.target}"`);
  52364. }
  52365. if (appArguments.length > 0) {
  52366. appArguments = appArguments.map(arg => `"\`"${arg}\`""`);
  52367. encodedArguments.push(appArguments.join(','));
  52368. }
  52369. // Using Base64-encoded command, accepted by PowerShell, to allow special characters.
  52370. options.target = Buffer.from(encodedArguments.join(' '), 'utf16le').toString('base64');
  52371. } else {
  52372. if (app) {
  52373. command = app;
  52374. } else {
  52375. // When bundled by Webpack, there's no actual package file path and no local `xdg-open`.
  52376. const isBundled = !__dirname || __dirname === '/';
  52377. // Check if local `xdg-open` exists and is executable.
  52378. let exeLocalXdgOpen = false;
  52379. try {
  52380. await fs$3.access(localXdgOpenPath, fsConstants.X_OK);
  52381. exeLocalXdgOpen = true;
  52382. } catch {}
  52383. const useSystemXdgOpen = process.versions.electron ||
  52384. platform === 'android' || isBundled || !exeLocalXdgOpen;
  52385. command = useSystemXdgOpen ? 'xdg-open' : localXdgOpenPath;
  52386. }
  52387. if (appArguments.length > 0) {
  52388. cliArguments.push(...appArguments);
  52389. }
  52390. if (!options.wait) {
  52391. // `xdg-open` will block the process unless stdio is ignored
  52392. // and it's detached from the parent even if it's unref'd.
  52393. childProcessOptions.stdio = 'ignore';
  52394. childProcessOptions.detached = true;
  52395. }
  52396. }
  52397. if (options.target) {
  52398. cliArguments.push(options.target);
  52399. }
  52400. if (platform === 'darwin' && appArguments.length > 0) {
  52401. cliArguments.push('--args', ...appArguments);
  52402. }
  52403. const subprocess = childProcess.spawn(command, cliArguments, childProcessOptions);
  52404. if (options.wait) {
  52405. return new Promise((resolve, reject) => {
  52406. subprocess.once('error', reject);
  52407. subprocess.once('close', exitCode => {
  52408. if (options.allowNonzeroExitCode && exitCode > 0) {
  52409. reject(new Error(`Exited with code ${exitCode}`));
  52410. return;
  52411. }
  52412. resolve(subprocess);
  52413. });
  52414. });
  52415. }
  52416. subprocess.unref();
  52417. return subprocess;
  52418. };
  52419. const open = (target, options) => {
  52420. if (typeof target !== 'string') {
  52421. throw new TypeError('Expected a `target`');
  52422. }
  52423. return baseOpen({
  52424. ...options,
  52425. target
  52426. });
  52427. };
  52428. const openApp = (name, options) => {
  52429. if (typeof name !== 'string') {
  52430. throw new TypeError('Expected a `name`');
  52431. }
  52432. const {arguments: appArguments = []} = options || {};
  52433. if (appArguments !== undefined && appArguments !== null && !Array.isArray(appArguments)) {
  52434. throw new TypeError('Expected `appArguments` as Array type');
  52435. }
  52436. return baseOpen({
  52437. ...options,
  52438. app: {
  52439. name,
  52440. arguments: appArguments
  52441. }
  52442. });
  52443. };
  52444. function detectArchBinary(binary) {
  52445. if (typeof binary === 'string' || Array.isArray(binary)) {
  52446. return binary;
  52447. }
  52448. const {[arch]: archBinary} = binary;
  52449. if (!archBinary) {
  52450. throw new Error(`${arch} is not supported`);
  52451. }
  52452. return archBinary;
  52453. }
  52454. function detectPlatformBinary({[platform]: platformBinary}, {wsl}) {
  52455. if (wsl && isWsl) {
  52456. return detectArchBinary(wsl);
  52457. }
  52458. if (!platformBinary) {
  52459. throw new Error(`${platform} is not supported`);
  52460. }
  52461. return detectArchBinary(platformBinary);
  52462. }
  52463. const apps = {};
  52464. defineLazyProperty(apps, 'chrome', () => detectPlatformBinary({
  52465. darwin: 'google chrome',
  52466. win32: 'chrome',
  52467. linux: ['google-chrome', 'google-chrome-stable', 'chromium']
  52468. }, {
  52469. wsl: {
  52470. ia32: '/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe',
  52471. x64: ['/mnt/c/Program Files/Google/Chrome/Application/chrome.exe', '/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe']
  52472. }
  52473. }));
  52474. defineLazyProperty(apps, 'firefox', () => detectPlatformBinary({
  52475. darwin: 'firefox',
  52476. win32: 'C:\\Program Files\\Mozilla Firefox\\firefox.exe',
  52477. linux: 'firefox'
  52478. }, {
  52479. wsl: '/mnt/c/Program Files/Mozilla Firefox/firefox.exe'
  52480. }));
  52481. defineLazyProperty(apps, 'edge', () => detectPlatformBinary({
  52482. darwin: 'microsoft edge',
  52483. win32: 'msedge',
  52484. linux: ['microsoft-edge', 'microsoft-edge-dev']
  52485. }, {
  52486. wsl: '/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe'
  52487. }));
  52488. open.apps = apps;
  52489. open.openApp = openApp;
  52490. var open_1 = open;
  52491. var crossSpawn = {exports: {}};
  52492. var windows = isexe$3;
  52493. isexe$3.sync = sync$2;
  52494. var fs$2 = fs__default;
  52495. function checkPathExt (path, options) {
  52496. var pathext = options.pathExt !== undefined ?
  52497. options.pathExt : process.env.PATHEXT;
  52498. if (!pathext) {
  52499. return true
  52500. }
  52501. pathext = pathext.split(';');
  52502. if (pathext.indexOf('') !== -1) {
  52503. return true
  52504. }
  52505. for (var i = 0; i < pathext.length; i++) {
  52506. var p = pathext[i].toLowerCase();
  52507. if (p && path.substr(-p.length).toLowerCase() === p) {
  52508. return true
  52509. }
  52510. }
  52511. return false
  52512. }
  52513. function checkStat$1 (stat, path, options) {
  52514. if (!stat.isSymbolicLink() && !stat.isFile()) {
  52515. return false
  52516. }
  52517. return checkPathExt(path, options)
  52518. }
  52519. function isexe$3 (path, options, cb) {
  52520. fs$2.stat(path, function (er, stat) {
  52521. cb(er, er ? false : checkStat$1(stat, path, options));
  52522. });
  52523. }
  52524. function sync$2 (path, options) {
  52525. return checkStat$1(fs$2.statSync(path), path, options)
  52526. }
  52527. var mode = isexe$2;
  52528. isexe$2.sync = sync$1;
  52529. var fs$1 = fs__default;
  52530. function isexe$2 (path, options, cb) {
  52531. fs$1.stat(path, function (er, stat) {
  52532. cb(er, er ? false : checkStat(stat, options));
  52533. });
  52534. }
  52535. function sync$1 (path, options) {
  52536. return checkStat(fs$1.statSync(path), options)
  52537. }
  52538. function checkStat (stat, options) {
  52539. return stat.isFile() && checkMode(stat, options)
  52540. }
  52541. function checkMode (stat, options) {
  52542. var mod = stat.mode;
  52543. var uid = stat.uid;
  52544. var gid = stat.gid;
  52545. var myUid = options.uid !== undefined ?
  52546. options.uid : process.getuid && process.getuid();
  52547. var myGid = options.gid !== undefined ?
  52548. options.gid : process.getgid && process.getgid();
  52549. var u = parseInt('100', 8);
  52550. var g = parseInt('010', 8);
  52551. var o = parseInt('001', 8);
  52552. var ug = u | g;
  52553. var ret = (mod & o) ||
  52554. (mod & g) && gid === myGid ||
  52555. (mod & u) && uid === myUid ||
  52556. (mod & ug) && myUid === 0;
  52557. return ret
  52558. }
  52559. var core;
  52560. if (process.platform === 'win32' || commonjsGlobal.TESTING_WINDOWS) {
  52561. core = windows;
  52562. } else {
  52563. core = mode;
  52564. }
  52565. var isexe_1 = isexe$1;
  52566. isexe$1.sync = sync;
  52567. function isexe$1 (path, options, cb) {
  52568. if (typeof options === 'function') {
  52569. cb = options;
  52570. options = {};
  52571. }
  52572. if (!cb) {
  52573. if (typeof Promise !== 'function') {
  52574. throw new TypeError('callback not provided')
  52575. }
  52576. return new Promise(function (resolve, reject) {
  52577. isexe$1(path, options || {}, function (er, is) {
  52578. if (er) {
  52579. reject(er);
  52580. } else {
  52581. resolve(is);
  52582. }
  52583. });
  52584. })
  52585. }
  52586. core(path, options || {}, function (er, is) {
  52587. // ignore EACCES because that just means we aren't allowed to run it
  52588. if (er) {
  52589. if (er.code === 'EACCES' || options && options.ignoreErrors) {
  52590. er = null;
  52591. is = false;
  52592. }
  52593. }
  52594. cb(er, is);
  52595. });
  52596. }
  52597. function sync (path, options) {
  52598. // my kingdom for a filtered catch
  52599. try {
  52600. return core.sync(path, options || {})
  52601. } catch (er) {
  52602. if (options && options.ignoreErrors || er.code === 'EACCES') {
  52603. return false
  52604. } else {
  52605. throw er
  52606. }
  52607. }
  52608. }
  52609. const isWindows = process.platform === 'win32' ||
  52610. process.env.OSTYPE === 'cygwin' ||
  52611. process.env.OSTYPE === 'msys';
  52612. const path$2 = path__default;
  52613. const COLON = isWindows ? ';' : ':';
  52614. const isexe = isexe_1;
  52615. const getNotFoundError = (cmd) =>
  52616. Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' });
  52617. const getPathInfo = (cmd, opt) => {
  52618. const colon = opt.colon || COLON;
  52619. // If it has a slash, then we don't bother searching the pathenv.
  52620. // just check the file itself, and that's it.
  52621. const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? ['']
  52622. : (
  52623. [
  52624. // windows always checks the cwd first
  52625. ...(isWindows ? [process.cwd()] : []),
  52626. ...(opt.path || process.env.PATH ||
  52627. /* istanbul ignore next: very unusual */ '').split(colon),
  52628. ]
  52629. );
  52630. const pathExtExe = isWindows
  52631. ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM'
  52632. : '';
  52633. const pathExt = isWindows ? pathExtExe.split(colon) : [''];
  52634. if (isWindows) {
  52635. if (cmd.indexOf('.') !== -1 && pathExt[0] !== '')
  52636. pathExt.unshift('');
  52637. }
  52638. return {
  52639. pathEnv,
  52640. pathExt,
  52641. pathExtExe,
  52642. }
  52643. };
  52644. const which$1 = (cmd, opt, cb) => {
  52645. if (typeof opt === 'function') {
  52646. cb = opt;
  52647. opt = {};
  52648. }
  52649. if (!opt)
  52650. opt = {};
  52651. const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
  52652. const found = [];
  52653. const step = i => new Promise((resolve, reject) => {
  52654. if (i === pathEnv.length)
  52655. return opt.all && found.length ? resolve(found)
  52656. : reject(getNotFoundError(cmd))
  52657. const ppRaw = pathEnv[i];
  52658. const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
  52659. const pCmd = path$2.join(pathPart, cmd);
  52660. const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd
  52661. : pCmd;
  52662. resolve(subStep(p, i, 0));
  52663. });
  52664. const subStep = (p, i, ii) => new Promise((resolve, reject) => {
  52665. if (ii === pathExt.length)
  52666. return resolve(step(i + 1))
  52667. const ext = pathExt[ii];
  52668. isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {
  52669. if (!er && is) {
  52670. if (opt.all)
  52671. found.push(p + ext);
  52672. else
  52673. return resolve(p + ext)
  52674. }
  52675. return resolve(subStep(p, i, ii + 1))
  52676. });
  52677. });
  52678. return cb ? step(0).then(res => cb(null, res), cb) : step(0)
  52679. };
  52680. const whichSync = (cmd, opt) => {
  52681. opt = opt || {};
  52682. const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
  52683. const found = [];
  52684. for (let i = 0; i < pathEnv.length; i ++) {
  52685. const ppRaw = pathEnv[i];
  52686. const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
  52687. const pCmd = path$2.join(pathPart, cmd);
  52688. const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd
  52689. : pCmd;
  52690. for (let j = 0; j < pathExt.length; j ++) {
  52691. const cur = p + pathExt[j];
  52692. try {
  52693. const is = isexe.sync(cur, { pathExt: pathExtExe });
  52694. if (is) {
  52695. if (opt.all)
  52696. found.push(cur);
  52697. else
  52698. return cur
  52699. }
  52700. } catch (ex) {}
  52701. }
  52702. }
  52703. if (opt.all && found.length)
  52704. return found
  52705. if (opt.nothrow)
  52706. return null
  52707. throw getNotFoundError(cmd)
  52708. };
  52709. var which_1 = which$1;
  52710. which$1.sync = whichSync;
  52711. var pathKey$1 = {exports: {}};
  52712. const pathKey = (options = {}) => {
  52713. const environment = options.env || process.env;
  52714. const platform = options.platform || process.platform;
  52715. if (platform !== 'win32') {
  52716. return 'PATH';
  52717. }
  52718. return Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path';
  52719. };
  52720. pathKey$1.exports = pathKey;
  52721. // TODO: Remove this for the next major release
  52722. pathKey$1.exports.default = pathKey;
  52723. const path$1 = path__default;
  52724. const which = which_1;
  52725. const getPathKey = pathKey$1.exports;
  52726. function resolveCommandAttempt(parsed, withoutPathExt) {
  52727. const env = parsed.options.env || process.env;
  52728. const cwd = process.cwd();
  52729. const hasCustomCwd = parsed.options.cwd != null;
  52730. // Worker threads do not have process.chdir()
  52731. const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled;
  52732. // If a custom `cwd` was specified, we need to change the process cwd
  52733. // because `which` will do stat calls but does not support a custom cwd
  52734. if (shouldSwitchCwd) {
  52735. try {
  52736. process.chdir(parsed.options.cwd);
  52737. } catch (err) {
  52738. /* Empty */
  52739. }
  52740. }
  52741. let resolved;
  52742. try {
  52743. resolved = which.sync(parsed.command, {
  52744. path: env[getPathKey({ env })],
  52745. pathExt: withoutPathExt ? path$1.delimiter : undefined,
  52746. });
  52747. } catch (e) {
  52748. /* Empty */
  52749. } finally {
  52750. if (shouldSwitchCwd) {
  52751. process.chdir(cwd);
  52752. }
  52753. }
  52754. // If we successfully resolved, ensure that an absolute path is returned
  52755. // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it
  52756. if (resolved) {
  52757. resolved = path$1.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved);
  52758. }
  52759. return resolved;
  52760. }
  52761. function resolveCommand$1(parsed) {
  52762. return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);
  52763. }
  52764. var resolveCommand_1 = resolveCommand$1;
  52765. var _escape = {};
  52766. // See http://www.robvanderwoude.com/escapechars.php
  52767. const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g;
  52768. function escapeCommand(arg) {
  52769. // Escape meta chars
  52770. arg = arg.replace(metaCharsRegExp, '^$1');
  52771. return arg;
  52772. }
  52773. function escapeArgument(arg, doubleEscapeMetaChars) {
  52774. // Convert to string
  52775. arg = `${arg}`;
  52776. // Algorithm below is based on https://qntm.org/cmd
  52777. // Sequence of backslashes followed by a double quote:
  52778. // double up all the backslashes and escape the double quote
  52779. arg = arg.replace(/(\\*)"/g, '$1$1\\"');
  52780. // Sequence of backslashes followed by the end of the string
  52781. // (which will become a double quote later):
  52782. // double up all the backslashes
  52783. arg = arg.replace(/(\\*)$/, '$1$1');
  52784. // All other backslashes occur literally
  52785. // Quote the whole thing:
  52786. arg = `"${arg}"`;
  52787. // Escape meta chars
  52788. arg = arg.replace(metaCharsRegExp, '^$1');
  52789. // Double escape meta chars if necessary
  52790. if (doubleEscapeMetaChars) {
  52791. arg = arg.replace(metaCharsRegExp, '^$1');
  52792. }
  52793. return arg;
  52794. }
  52795. _escape.command = escapeCommand;
  52796. _escape.argument = escapeArgument;
  52797. var shebangRegex$1 = /^#!(.*)/;
  52798. const shebangRegex = shebangRegex$1;
  52799. var shebangCommand$1 = (string = '') => {
  52800. const match = string.match(shebangRegex);
  52801. if (!match) {
  52802. return null;
  52803. }
  52804. const [path, argument] = match[0].replace(/#! ?/, '').split(' ');
  52805. const binary = path.split('/').pop();
  52806. if (binary === 'env') {
  52807. return argument;
  52808. }
  52809. return argument ? `${binary} ${argument}` : binary;
  52810. };
  52811. const fs = fs__default;
  52812. const shebangCommand = shebangCommand$1;
  52813. function readShebang$1(command) {
  52814. // Read the first 150 bytes from the file
  52815. const size = 150;
  52816. const buffer = Buffer.alloc(size);
  52817. let fd;
  52818. try {
  52819. fd = fs.openSync(command, 'r');
  52820. fs.readSync(fd, buffer, 0, size, 0);
  52821. fs.closeSync(fd);
  52822. } catch (e) { /* Empty */ }
  52823. // Attempt to extract shebang (null is returned if not a shebang)
  52824. return shebangCommand(buffer.toString());
  52825. }
  52826. var readShebang_1 = readShebang$1;
  52827. const path = path__default;
  52828. const resolveCommand = resolveCommand_1;
  52829. const escape = _escape;
  52830. const readShebang = readShebang_1;
  52831. const isWin$1 = process.platform === 'win32';
  52832. const isExecutableRegExp = /\.(?:com|exe)$/i;
  52833. const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;
  52834. function detectShebang(parsed) {
  52835. parsed.file = resolveCommand(parsed);
  52836. const shebang = parsed.file && readShebang(parsed.file);
  52837. if (shebang) {
  52838. parsed.args.unshift(parsed.file);
  52839. parsed.command = shebang;
  52840. return resolveCommand(parsed);
  52841. }
  52842. return parsed.file;
  52843. }
  52844. function parseNonShell(parsed) {
  52845. if (!isWin$1) {
  52846. return parsed;
  52847. }
  52848. // Detect & add support for shebangs
  52849. const commandFile = detectShebang(parsed);
  52850. // We don't need a shell if the command filename is an executable
  52851. const needsShell = !isExecutableRegExp.test(commandFile);
  52852. // If a shell is required, use cmd.exe and take care of escaping everything correctly
  52853. // Note that `forceShell` is an hidden option used only in tests
  52854. if (parsed.options.forceShell || needsShell) {
  52855. // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/`
  52856. // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument
  52857. // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called,
  52858. // we need to double escape them
  52859. const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
  52860. // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\bar)
  52861. // This is necessary otherwise it will always fail with ENOENT in those cases
  52862. parsed.command = path.normalize(parsed.command);
  52863. // Escape command & arguments
  52864. parsed.command = escape.command(parsed.command);
  52865. parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars));
  52866. const shellCommand = [parsed.command].concat(parsed.args).join(' ');
  52867. parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`];
  52868. parsed.command = process.env.comspec || 'cmd.exe';
  52869. parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped
  52870. }
  52871. return parsed;
  52872. }
  52873. function parse$1(command, args, options) {
  52874. // Normalize arguments, similar to nodejs
  52875. if (args && !Array.isArray(args)) {
  52876. options = args;
  52877. args = null;
  52878. }
  52879. args = args ? args.slice(0) : []; // Clone array to avoid changing the original
  52880. options = Object.assign({}, options); // Clone object to avoid changing the original
  52881. // Build our parsed object
  52882. const parsed = {
  52883. command,
  52884. args,
  52885. options,
  52886. file: undefined,
  52887. original: {
  52888. command,
  52889. args,
  52890. },
  52891. };
  52892. // Delegate further parsing to shell or non-shell
  52893. return options.shell ? parsed : parseNonShell(parsed);
  52894. }
  52895. var parse_1 = parse$1;
  52896. const isWin = process.platform === 'win32';
  52897. function notFoundError(original, syscall) {
  52898. return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), {
  52899. code: 'ENOENT',
  52900. errno: 'ENOENT',
  52901. syscall: `${syscall} ${original.command}`,
  52902. path: original.command,
  52903. spawnargs: original.args,
  52904. });
  52905. }
  52906. function hookChildProcess(cp, parsed) {
  52907. if (!isWin) {
  52908. return;
  52909. }
  52910. const originalEmit = cp.emit;
  52911. cp.emit = function (name, arg1) {
  52912. // If emitting "exit" event and exit code is 1, we need to check if
  52913. // the command exists and emit an "error" instead
  52914. // See https://github.com/IndigoUnited/node-cross-spawn/issues/16
  52915. if (name === 'exit') {
  52916. const err = verifyENOENT(arg1, parsed);
  52917. if (err) {
  52918. return originalEmit.call(cp, 'error', err);
  52919. }
  52920. }
  52921. return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params
  52922. };
  52923. }
  52924. function verifyENOENT(status, parsed) {
  52925. if (isWin && status === 1 && !parsed.file) {
  52926. return notFoundError(parsed.original, 'spawn');
  52927. }
  52928. return null;
  52929. }
  52930. function verifyENOENTSync(status, parsed) {
  52931. if (isWin && status === 1 && !parsed.file) {
  52932. return notFoundError(parsed.original, 'spawnSync');
  52933. }
  52934. return null;
  52935. }
  52936. var enoent$1 = {
  52937. hookChildProcess,
  52938. verifyENOENT,
  52939. verifyENOENTSync,
  52940. notFoundError,
  52941. };
  52942. const cp = require$$2__default$1;
  52943. const parse = parse_1;
  52944. const enoent = enoent$1;
  52945. function spawn(command, args, options) {
  52946. // Parse the arguments
  52947. const parsed = parse(command, args, options);
  52948. // Spawn the child process
  52949. const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);
  52950. // Hook into child process "exit" event to emit an error if the command
  52951. // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16
  52952. enoent.hookChildProcess(spawned, parsed);
  52953. return spawned;
  52954. }
  52955. function spawnSync(command, args, options) {
  52956. // Parse the arguments
  52957. const parsed = parse(command, args, options);
  52958. // Spawn the child process
  52959. const result = cp.spawnSync(parsed.command, parsed.args, parsed.options);
  52960. // Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16
  52961. result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
  52962. return result;
  52963. }
  52964. crossSpawn.exports = spawn;
  52965. crossSpawn.exports.spawn = spawn;
  52966. crossSpawn.exports.sync = spawnSync;
  52967. crossSpawn.exports._parse = parse;
  52968. crossSpawn.exports._enoent = enoent;
  52969. var spawn$1 = crossSpawn.exports;
  52970. /**
  52971. * The following is modified based on source found in
  52972. * https://github.com/facebook/create-react-app
  52973. *
  52974. * MIT Licensed
  52975. * Copyright (c) 2015-present, Facebook, Inc.
  52976. * https://github.com/facebook/create-react-app/blob/master/LICENSE
  52977. *
  52978. */
  52979. // https://github.com/sindresorhus/open#app
  52980. const OSX_CHROME = 'google chrome';
  52981. /**
  52982. * Reads the BROWSER environment variable and decides what to do with it.
  52983. * Returns true if it opened a browser or ran a node.js script, otherwise false.
  52984. */
  52985. function openBrowser(url, opt, logger) {
  52986. // The browser executable to open.
  52987. // See https://github.com/sindresorhus/open#app for documentation.
  52988. const browser = typeof opt === 'string' ? opt : process.env.BROWSER || '';
  52989. if (browser.toLowerCase().endsWith('.js')) {
  52990. return executeNodeScript(browser, url, logger);
  52991. }
  52992. else if (browser.toLowerCase() !== 'none') {
  52993. return startBrowserProcess(browser, url);
  52994. }
  52995. return false;
  52996. }
  52997. function executeNodeScript(scriptPath, url, logger) {
  52998. const extraArgs = process.argv.slice(2);
  52999. const child = spawn$1(process.execPath, [scriptPath, ...extraArgs, url], {
  53000. stdio: 'inherit'
  53001. });
  53002. child.on('close', (code) => {
  53003. if (code !== 0) {
  53004. logger.error(colors$1.red(`\nThe script specified as BROWSER environment variable failed.\n\n${colors$1.cyan(scriptPath)} exited with code ${code}.`), { error: null });
  53005. }
  53006. });
  53007. return true;
  53008. }
  53009. function startBrowserProcess(browser, url) {
  53010. // If we're on OS X, the user hasn't specifically
  53011. // requested a different browser, we can try opening
  53012. // Chrome with AppleScript. This lets us reuse an
  53013. // existing tab when possible instead of creating a new one.
  53014. const shouldTryOpenChromeWithAppleScript = process.platform === 'darwin' && (browser === '' || browser === OSX_CHROME);
  53015. if (shouldTryOpenChromeWithAppleScript) {
  53016. try {
  53017. // Try our best to reuse existing tab
  53018. // on OS X Google Chrome with AppleScript
  53019. require$$2$1.execSync('ps cax | grep "Google Chrome"');
  53020. require$$2$1.execSync('osascript openChrome.applescript "' + encodeURI(url) + '"', {
  53021. cwd: path__default.dirname(require.resolve('vite/bin/openChrome.applescript')),
  53022. stdio: 'ignore'
  53023. });
  53024. return true;
  53025. }
  53026. catch (err) {
  53027. // Ignore errors
  53028. }
  53029. }
  53030. // Another special case: on OS X, check if BROWSER has been set to "open".
  53031. // In this case, instead of passing the string `open` to `open` function (which won't work),
  53032. // just ignore it (thus ensuring the intended behavior, i.e. opening the system browser):
  53033. // https://github.com/facebook/create-react-app/pull/1690#issuecomment-283518768
  53034. if (process.platform === 'darwin' && browser === 'open') {
  53035. browser = undefined;
  53036. }
  53037. // Fallback to open
  53038. // (It will always open new tab)
  53039. try {
  53040. const options = browser ? { app: { name: browser } } : {};
  53041. open_1(url, options).catch(() => { }); // Prevent `unhandledRejection` error.
  53042. return true;
  53043. }
  53044. catch (err) {
  53045. return false;
  53046. }
  53047. }
  53048. // https://github.com/vitejs/vite/issues/2820#issuecomment-812495079
  53049. const ROOT_FILES = [
  53050. // '.git',
  53051. // https://pnpm.js.org/workspaces/
  53052. 'pnpm-workspace.yaml',
  53053. // https://rushjs.io/pages/advanced/config_files/
  53054. // 'rush.json',
  53055. // https://nx.dev/latest/react/getting-started/nx-setup
  53056. // 'workspace.json',
  53057. // 'nx.json',
  53058. // https://github.com/lerna/lerna#lernajson
  53059. 'lerna.json'
  53060. ];
  53061. // npm: https://docs.npmjs.com/cli/v7/using-npm/workspaces#installing-workspaces
  53062. // yarn: https://classic.yarnpkg.com/en/docs/workspaces/#toc-how-to-use-it
  53063. function hasWorkspacePackageJSON(root) {
  53064. const path = path$r.join(root, 'package.json');
  53065. if (!isFileReadable(path)) {
  53066. return false;
  53067. }
  53068. const content = JSON.parse(fs__default.readFileSync(path, 'utf-8')) || {};
  53069. return !!content.workspaces;
  53070. }
  53071. function hasRootFile(root) {
  53072. return ROOT_FILES.some((file) => fs__default.existsSync(path$r.join(root, file)));
  53073. }
  53074. function hasPackageJSON(root) {
  53075. const path = path$r.join(root, 'package.json');
  53076. return fs__default.existsSync(path);
  53077. }
  53078. /**
  53079. * Search up for the nearest `package.json`
  53080. */
  53081. function searchForPackageRoot(current, root = current) {
  53082. if (hasPackageJSON(current))
  53083. return current;
  53084. const dir = path$r.dirname(current);
  53085. // reach the fs root
  53086. if (!dir || dir === current)
  53087. return root;
  53088. return searchForPackageRoot(dir, root);
  53089. }
  53090. /**
  53091. * Search up for the nearest workspace root
  53092. */
  53093. function searchForWorkspaceRoot(current, root = searchForPackageRoot(current)) {
  53094. if (hasRootFile(current))
  53095. return current;
  53096. if (hasWorkspacePackageJSON(current))
  53097. return current;
  53098. const dir = path$r.dirname(current);
  53099. // reach the fs root
  53100. if (!dir || dir === current)
  53101. return root;
  53102. return searchForWorkspaceRoot(dir, root);
  53103. }
  53104. async function createServer(inlineConfig = {}) {
  53105. const config = await resolveConfig(inlineConfig, 'serve', 'development');
  53106. const { root, server: serverConfig } = config;
  53107. const httpsOptions = await resolveHttpsConfig(config.server.https, config.cacheDir);
  53108. let { middlewareMode } = serverConfig;
  53109. if (middlewareMode === true) {
  53110. middlewareMode = 'ssr';
  53111. }
  53112. const middlewares = connect();
  53113. const httpServer = middlewareMode
  53114. ? null
  53115. : await resolveHttpServer(serverConfig, middlewares, httpsOptions);
  53116. const ws = createWebSocketServer(httpServer, config, httpsOptions);
  53117. const { ignored = [], ...watchOptions } = serverConfig.watch || {};
  53118. const watcher = chokidar.watch(path__default.resolve(root), {
  53119. ignored: [
  53120. '**/node_modules/**',
  53121. '**/.git/**',
  53122. ...(Array.isArray(ignored) ? ignored : [ignored])
  53123. ],
  53124. ignoreInitial: true,
  53125. ignorePermissionErrors: true,
  53126. disableGlobbing: true,
  53127. ...watchOptions
  53128. });
  53129. const moduleGraph = new ModuleGraph((url, ssr) => container.resolveId(url, undefined, { ssr }));
  53130. const container = await createPluginContainer(config, moduleGraph, watcher);
  53131. const closeHttpServer = createServerCloseFn(httpServer);
  53132. // eslint-disable-next-line prefer-const
  53133. let exitProcess;
  53134. const server = {
  53135. config,
  53136. middlewares,
  53137. get app() {
  53138. config.logger.warn(`ViteDevServer.app is deprecated. Use ViteDevServer.middlewares instead.`);
  53139. return middlewares;
  53140. },
  53141. httpServer,
  53142. watcher,
  53143. pluginContainer: container,
  53144. ws,
  53145. moduleGraph,
  53146. ssrTransform,
  53147. transformWithEsbuild,
  53148. transformRequest(url, options) {
  53149. return transformRequest(url, server, options);
  53150. },
  53151. transformIndexHtml: null,
  53152. async ssrLoadModule(url, opts) {
  53153. if (!server._ssrExternals) {
  53154. let knownImports = [];
  53155. const optimizedDeps = server._optimizedDeps;
  53156. if (optimizedDeps) {
  53157. await optimizedDeps.scanProcessing;
  53158. knownImports = [
  53159. ...Object.keys(optimizedDeps.metadata.optimized),
  53160. ...Object.keys(optimizedDeps.metadata.discovered)
  53161. ];
  53162. }
  53163. server._ssrExternals = resolveSSRExternal(config, knownImports);
  53164. }
  53165. return ssrLoadModule(url, server, undefined, undefined, opts === null || opts === void 0 ? void 0 : opts.fixStacktrace);
  53166. },
  53167. ssrFixStacktrace(e) {
  53168. if (e.stack) {
  53169. const stacktrace = ssrRewriteStacktrace(e.stack, moduleGraph);
  53170. rebindErrorStacktrace(e, stacktrace);
  53171. }
  53172. },
  53173. ssrRewriteStacktrace(stack) {
  53174. return ssrRewriteStacktrace(stack, moduleGraph);
  53175. },
  53176. listen(port, isRestart) {
  53177. return startServer(server, port, isRestart);
  53178. },
  53179. async close() {
  53180. process.off('SIGTERM', exitProcess);
  53181. if (!middlewareMode && process.env.CI !== 'true') {
  53182. process.stdin.off('end', exitProcess);
  53183. }
  53184. await Promise.all([
  53185. watcher.close(),
  53186. ws.close(),
  53187. container.close(),
  53188. closeHttpServer()
  53189. ]);
  53190. },
  53191. printUrls() {
  53192. if (httpServer) {
  53193. printCommonServerUrls(httpServer, config.server, config);
  53194. }
  53195. else {
  53196. throw new Error('cannot print server URLs in middleware mode.');
  53197. }
  53198. },
  53199. async restart(forceOptimize) {
  53200. if (!server._restartPromise) {
  53201. server._forceOptimizeOnRestart = !!forceOptimize;
  53202. server._restartPromise = restartServer(server).finally(() => {
  53203. server._restartPromise = null;
  53204. server._forceOptimizeOnRestart = false;
  53205. });
  53206. }
  53207. return server._restartPromise;
  53208. },
  53209. _optimizedDeps: null,
  53210. _ssrExternals: null,
  53211. _globImporters: Object.create(null),
  53212. _restartPromise: null,
  53213. _forceOptimizeOnRestart: false,
  53214. _pendingRequests: new Map()
  53215. };
  53216. server.transformIndexHtml = createDevHtmlTransformFn(server);
  53217. exitProcess = async () => {
  53218. try {
  53219. await server.close();
  53220. }
  53221. finally {
  53222. process.exit(0);
  53223. }
  53224. };
  53225. process.once('SIGTERM', exitProcess);
  53226. if (!middlewareMode && process.env.CI !== 'true') {
  53227. process.stdin.on('end', exitProcess);
  53228. }
  53229. const { packageCache } = config;
  53230. const setPackageData = packageCache.set.bind(packageCache);
  53231. packageCache.set = (id, pkg) => {
  53232. if (id.endsWith('.json')) {
  53233. watcher.add(id);
  53234. }
  53235. return setPackageData(id, pkg);
  53236. };
  53237. watcher.on('change', async (file) => {
  53238. file = normalizePath$3(file);
  53239. if (file.endsWith('/package.json')) {
  53240. return invalidatePackageData(packageCache, file);
  53241. }
  53242. // invalidate module graph cache on file change
  53243. moduleGraph.onFileChange(file);
  53244. if (serverConfig.hmr !== false) {
  53245. try {
  53246. await handleHMRUpdate(file, server);
  53247. }
  53248. catch (err) {
  53249. ws.send({
  53250. type: 'error',
  53251. err: prepareError(err)
  53252. });
  53253. }
  53254. }
  53255. });
  53256. watcher.on('add', (file) => {
  53257. handleFileAddUnlink(normalizePath$3(file), server);
  53258. });
  53259. watcher.on('unlink', (file) => {
  53260. handleFileAddUnlink(normalizePath$3(file), server, true);
  53261. });
  53262. if (!middlewareMode && httpServer) {
  53263. httpServer.once('listening', () => {
  53264. // update actual port since this may be different from initial value
  53265. serverConfig.port = httpServer.address().port;
  53266. });
  53267. }
  53268. // apply server configuration hooks from plugins
  53269. const postHooks = [];
  53270. for (const plugin of config.plugins) {
  53271. if (plugin.configureServer) {
  53272. postHooks.push(await plugin.configureServer(server));
  53273. }
  53274. }
  53275. // Internal middlewares ------------------------------------------------------
  53276. // request timer
  53277. if (process.env.DEBUG) {
  53278. middlewares.use(timeMiddleware(root));
  53279. }
  53280. // cors (enabled by default)
  53281. const { cors } = serverConfig;
  53282. if (cors !== false) {
  53283. middlewares.use(corsMiddleware(typeof cors === 'boolean' ? {} : cors));
  53284. }
  53285. // proxy
  53286. const { proxy } = serverConfig;
  53287. if (proxy) {
  53288. middlewares.use(proxyMiddleware(httpServer, proxy, config));
  53289. }
  53290. // base
  53291. if (config.base !== '/') {
  53292. middlewares.use(baseMiddleware(server));
  53293. }
  53294. // open in editor support
  53295. middlewares.use('/__open-in-editor', launchEditorMiddleware());
  53296. // hmr reconnect ping
  53297. // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
  53298. middlewares.use('/__vite_ping', function viteHMRPingMiddleware(_, res) {
  53299. res.end('pong');
  53300. });
  53301. // serve static files under /public
  53302. // this applies before the transform middleware so that these files are served
  53303. // as-is without transforms.
  53304. if (config.publicDir) {
  53305. middlewares.use(servePublicMiddleware(config.publicDir, config.server.headers));
  53306. }
  53307. // main transform middleware
  53308. middlewares.use(transformMiddleware(server));
  53309. // serve static files
  53310. middlewares.use(serveRawFsMiddleware(server));
  53311. middlewares.use(serveStaticMiddleware(root, server));
  53312. // spa fallback
  53313. if (!middlewareMode || middlewareMode === 'html') {
  53314. middlewares.use(spaFallbackMiddleware(root));
  53315. }
  53316. // run post config hooks
  53317. // This is applied before the html middleware so that user middleware can
  53318. // serve custom content instead of index.html.
  53319. postHooks.forEach((fn) => fn && fn());
  53320. if (!middlewareMode || middlewareMode === 'html') {
  53321. // transform index.html
  53322. middlewares.use(indexHtmlMiddleware(server));
  53323. // handle 404s
  53324. // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
  53325. middlewares.use(function vite404Middleware(_, res) {
  53326. res.statusCode = 404;
  53327. res.end();
  53328. });
  53329. }
  53330. // error handler
  53331. middlewares.use(errorMiddleware(server, !!middlewareMode));
  53332. const initOptimizer = () => {
  53333. if (!config.optimizeDeps.disabled) {
  53334. server._optimizedDeps = createOptimizedDeps(server);
  53335. }
  53336. };
  53337. if (!middlewareMode && httpServer) {
  53338. let isOptimized = false;
  53339. // overwrite listen to init optimizer before server start
  53340. const listen = httpServer.listen.bind(httpServer);
  53341. httpServer.listen = (async (port, ...args) => {
  53342. if (!isOptimized) {
  53343. try {
  53344. await container.buildStart({});
  53345. initOptimizer();
  53346. isOptimized = true;
  53347. }
  53348. catch (e) {
  53349. httpServer.emit('error', e);
  53350. return;
  53351. }
  53352. }
  53353. return listen(port, ...args);
  53354. });
  53355. }
  53356. else {
  53357. await container.buildStart({});
  53358. initOptimizer();
  53359. }
  53360. return server;
  53361. }
  53362. async function startServer(server, inlinePort, isRestart = false) {
  53363. var _a;
  53364. const httpServer = server.httpServer;
  53365. if (!httpServer) {
  53366. throw new Error('Cannot call server.listen in middleware mode.');
  53367. }
  53368. const options = server.config.server;
  53369. const port = (_a = inlinePort !== null && inlinePort !== void 0 ? inlinePort : options.port) !== null && _a !== void 0 ? _a : 3000;
  53370. const hostname = resolveHostname(options.host);
  53371. const protocol = options.https ? 'https' : 'http';
  53372. const info = server.config.logger.info;
  53373. const base = server.config.base;
  53374. const serverPort = await httpServerStart(httpServer, {
  53375. port,
  53376. strictPort: options.strictPort,
  53377. host: hostname.host,
  53378. logger: server.config.logger
  53379. });
  53380. // @ts-ignore
  53381. const profileSession = global.__vite_profile_session;
  53382. if (profileSession) {
  53383. profileSession.post('Profiler.stop', (err, { profile }) => {
  53384. // Write profile to disk, upload, etc.
  53385. if (!err) {
  53386. const outPath = path__default.resolve('./vite-profile.cpuprofile');
  53387. fs__default.writeFileSync(outPath, JSON.stringify(profile));
  53388. info(colors$1.yellow(` CPU profile written to ${colors$1.white(colors$1.dim(outPath))}\n`));
  53389. }
  53390. else {
  53391. throw err;
  53392. }
  53393. });
  53394. }
  53395. if (options.open && !isRestart) {
  53396. const path = typeof options.open === 'string' ? options.open : base;
  53397. openBrowser(path.startsWith('http')
  53398. ? path
  53399. : `${protocol}://${hostname.name}:${serverPort}${path}`, true, server.config.logger);
  53400. }
  53401. return server;
  53402. }
  53403. function createServerCloseFn(server) {
  53404. if (!server) {
  53405. return () => { };
  53406. }
  53407. let hasListened = false;
  53408. const openSockets = new Set();
  53409. server.on('connection', (socket) => {
  53410. openSockets.add(socket);
  53411. socket.on('close', () => {
  53412. openSockets.delete(socket);
  53413. });
  53414. });
  53415. server.once('listening', () => {
  53416. hasListened = true;
  53417. });
  53418. return () => new Promise((resolve, reject) => {
  53419. openSockets.forEach((s) => s.destroy());
  53420. if (hasListened) {
  53421. server.close((err) => {
  53422. if (err) {
  53423. reject(err);
  53424. }
  53425. else {
  53426. resolve();
  53427. }
  53428. });
  53429. }
  53430. else {
  53431. resolve();
  53432. }
  53433. });
  53434. }
  53435. function resolvedAllowDir(root, dir) {
  53436. return normalizePath$3(path__default.resolve(root, dir));
  53437. }
  53438. function resolveServerOptions(root, raw, logger) {
  53439. var _a, _b, _c, _d, _e;
  53440. const server = {
  53441. preTransformRequests: true,
  53442. ...raw
  53443. };
  53444. let allowDirs = (_a = server.fs) === null || _a === void 0 ? void 0 : _a.allow;
  53445. const deny = ((_b = server.fs) === null || _b === void 0 ? void 0 : _b.deny) || ['.env', '.env.*', '*.{crt,pem}'];
  53446. if (!allowDirs) {
  53447. allowDirs = [searchForWorkspaceRoot(root)];
  53448. }
  53449. allowDirs = allowDirs.map((i) => resolvedAllowDir(root, i));
  53450. // only push client dir when vite itself is outside-of-root
  53451. const resolvedClientDir = resolvedAllowDir(root, CLIENT_DIR);
  53452. if (!allowDirs.some((dir) => isParentDirectory(dir, resolvedClientDir))) {
  53453. allowDirs.push(resolvedClientDir);
  53454. }
  53455. server.fs = {
  53456. strict: (_d = (_c = server.fs) === null || _c === void 0 ? void 0 : _c.strict) !== null && _d !== void 0 ? _d : true,
  53457. allow: allowDirs,
  53458. deny
  53459. };
  53460. if ((_e = server.origin) === null || _e === void 0 ? void 0 : _e.endsWith('/')) {
  53461. server.origin = server.origin.slice(0, -1);
  53462. logger.warn(colors$1.yellow(`${colors$1.bold('(!)')} server.origin should not end with "/". Using "${server.origin}" instead.`));
  53463. }
  53464. return server;
  53465. }
  53466. async function restartServer(server) {
  53467. // @ts-ignore
  53468. global.__vite_start_time = perf_hooks.performance.now();
  53469. const { port: prevPort, host: prevHost } = server.config.server;
  53470. await server.close();
  53471. let inlineConfig = server.config.inlineConfig;
  53472. if (server._forceOptimizeOnRestart) {
  53473. inlineConfig = mergeConfig(inlineConfig, {
  53474. server: {
  53475. force: true
  53476. }
  53477. });
  53478. }
  53479. let newServer = null;
  53480. try {
  53481. newServer = await createServer(inlineConfig);
  53482. }
  53483. catch (err) {
  53484. server.config.logger.error(err.message, {
  53485. timestamp: true
  53486. });
  53487. return;
  53488. }
  53489. for (const key in newServer) {
  53490. if (key === '_restartPromise') {
  53491. // prevent new server `restart` function from calling
  53492. // @ts-ignore
  53493. newServer[key] = server[key];
  53494. }
  53495. else if (key !== 'app') {
  53496. // @ts-ignore
  53497. server[key] = newServer[key];
  53498. }
  53499. }
  53500. const { logger, server: { port, host, middlewareMode } } = server.config;
  53501. if (!middlewareMode) {
  53502. await server.listen(port, true);
  53503. logger.info('server restarted.', { timestamp: true });
  53504. if (port !== prevPort || host !== prevHost) {
  53505. logger.info('');
  53506. server.printUrls();
  53507. }
  53508. }
  53509. else {
  53510. logger.info('server restarted.', { timestamp: true });
  53511. }
  53512. // new server (the current server) can restart now
  53513. newServer._restartPromise = null;
  53514. }
  53515. var index = {
  53516. __proto__: null,
  53517. createServer: createServer,
  53518. resolveServerOptions: resolveServerOptions,
  53519. searchForWorkspaceRoot: searchForWorkspaceRoot
  53520. };
  53521. //@ts-nocheck
  53522. /* global Buffer */
  53523. const noop = () => { };
  53524. const mimes = /text|javascript|\/json|xml/i;
  53525. const threshold = 1024;
  53526. const level = -1;
  53527. let brotli = false;
  53528. const getChunkSize = (chunk, enc) => (chunk ? Buffer.byteLength(chunk, enc) : 0);
  53529. function compression() {
  53530. const brotliOpts = (typeof brotli === 'object' && brotli) || {};
  53531. const gzipOpts = {};
  53532. // disable Brotli on Node<12.7 where it is unsupported:
  53533. if (!zlib__default.createBrotliCompress)
  53534. brotli = false;
  53535. return (req, res, next = noop) => {
  53536. const accept = req.headers['accept-encoding'] + '';
  53537. const encoding = ((brotli && accept.match(/\bbr\b/)) ||
  53538. (accept.match(/\bgzip\b/)) ||
  53539. [])[0];
  53540. // skip if no response body or no supported encoding:
  53541. if (req.method === 'HEAD' || !encoding)
  53542. return next();
  53543. /** @type {zlib.Gzip | zlib.BrotliCompress} */
  53544. let compress;
  53545. let pendingStatus;
  53546. /** @type {[string, function][]?} */
  53547. let pendingListeners = [];
  53548. let started = false;
  53549. let size = 0;
  53550. function start() {
  53551. started = true;
  53552. // @ts-ignore
  53553. size = res.getHeader('Content-Length') | 0 || size;
  53554. const compressible = mimes.test(String(res.getHeader('Content-Type') || 'text/plain'));
  53555. const cleartext = !res.getHeader('Content-Encoding');
  53556. const listeners = pendingListeners || [];
  53557. if (compressible && cleartext && size >= threshold) {
  53558. res.setHeader('Content-Encoding', encoding);
  53559. res.removeHeader('Content-Length');
  53560. if (encoding === 'br') {
  53561. const params = {
  53562. [zlib__default.constants.BROTLI_PARAM_QUALITY]: level,
  53563. [zlib__default.constants.BROTLI_PARAM_SIZE_HINT]: size
  53564. };
  53565. compress = zlib__default.createBrotliCompress({
  53566. params: Object.assign(params, brotliOpts)
  53567. });
  53568. }
  53569. else {
  53570. compress = zlib__default.createGzip(Object.assign({ level }, gzipOpts));
  53571. }
  53572. // backpressure
  53573. compress.on('data', (chunk) => write.call(res, chunk) === false && compress.pause());
  53574. on.call(res, 'drain', () => compress.resume());
  53575. compress.on('end', () => end.call(res));
  53576. listeners.forEach((p) => compress.on.apply(compress, p));
  53577. }
  53578. else {
  53579. pendingListeners = null;
  53580. listeners.forEach((p) => on.apply(res, p));
  53581. }
  53582. writeHead.call(res, pendingStatus || res.statusCode);
  53583. }
  53584. const { end, write, on, writeHead } = res;
  53585. res.writeHead = function (status, reason, headers) {
  53586. if (typeof reason !== 'string')
  53587. [headers, reason] = [reason, headers];
  53588. if (headers)
  53589. for (let i in headers)
  53590. res.setHeader(i, headers[i]);
  53591. pendingStatus = status;
  53592. return this;
  53593. };
  53594. res.write = function (chunk, enc, cb) {
  53595. size += getChunkSize(chunk, enc);
  53596. if (!started)
  53597. start();
  53598. if (!compress)
  53599. return write.apply(this, arguments);
  53600. return compress.write.apply(compress, arguments);
  53601. };
  53602. res.end = function (chunk, enc, cb) {
  53603. if (arguments.length > 0 && typeof chunk !== 'function') {
  53604. size += getChunkSize(chunk, enc);
  53605. }
  53606. if (!started)
  53607. start();
  53608. if (!compress)
  53609. return end.apply(this, arguments);
  53610. return compress.end.apply(compress, arguments);
  53611. };
  53612. res.on = function (type, listener) {
  53613. if (!pendingListeners || type !== 'drain')
  53614. on.call(this, type, listener);
  53615. else if (compress)
  53616. compress.on(type, listener);
  53617. else
  53618. pendingListeners.push([type, listener]);
  53619. return this;
  53620. };
  53621. next();
  53622. };
  53623. }
  53624. function resolvePreviewOptions(preview, server) {
  53625. var _a, _b, _c, _d, _e, _f, _g;
  53626. // The preview server inherits every CommonServerOption from the `server` config
  53627. // except for the port to enable having both the dev and preview servers running
  53628. // at the same time without extra configuration
  53629. return {
  53630. port: preview === null || preview === void 0 ? void 0 : preview.port,
  53631. strictPort: (_a = preview === null || preview === void 0 ? void 0 : preview.strictPort) !== null && _a !== void 0 ? _a : server.strictPort,
  53632. host: (_b = preview === null || preview === void 0 ? void 0 : preview.host) !== null && _b !== void 0 ? _b : server.host,
  53633. https: (_c = preview === null || preview === void 0 ? void 0 : preview.https) !== null && _c !== void 0 ? _c : server.https,
  53634. open: (_d = preview === null || preview === void 0 ? void 0 : preview.open) !== null && _d !== void 0 ? _d : server.open,
  53635. proxy: (_e = preview === null || preview === void 0 ? void 0 : preview.proxy) !== null && _e !== void 0 ? _e : server.proxy,
  53636. cors: (_f = preview === null || preview === void 0 ? void 0 : preview.cors) !== null && _f !== void 0 ? _f : server.cors,
  53637. headers: (_g = preview === null || preview === void 0 ? void 0 : preview.headers) !== null && _g !== void 0 ? _g : server.headers
  53638. };
  53639. }
  53640. /**
  53641. * Starts the Vite server in preview mode, to simulate a production deployment
  53642. * @experimental
  53643. */
  53644. async function preview(inlineConfig) {
  53645. var _a, _b;
  53646. const config = await resolveConfig(inlineConfig, 'serve', 'production');
  53647. const app = connect();
  53648. const httpServer = await resolveHttpServer(config.preview, app, await resolveHttpsConfig((_a = config.preview) === null || _a === void 0 ? void 0 : _a.https, config.cacheDir));
  53649. // apply server hooks from plugins
  53650. const postHooks = [];
  53651. for (const plugin of config.plugins) {
  53652. if (plugin.configurePreviewServer) {
  53653. postHooks.push(await plugin.configurePreviewServer({ middlewares: app, httpServer }));
  53654. }
  53655. }
  53656. // cors
  53657. const { cors } = config.preview;
  53658. if (cors !== false) {
  53659. app.use(corsMiddleware(typeof cors === 'boolean' ? {} : cors));
  53660. }
  53661. // proxy
  53662. const { proxy } = config.preview;
  53663. if (proxy) {
  53664. app.use(proxyMiddleware(httpServer, proxy, config));
  53665. }
  53666. app.use(compression());
  53667. // static assets
  53668. const distDir = path__default.resolve(config.root, config.build.outDir);
  53669. app.use(config.base, sirv(distDir, {
  53670. etag: true,
  53671. dev: true,
  53672. single: true
  53673. }));
  53674. // apply post server hooks from plugins
  53675. postHooks.forEach((fn) => fn && fn());
  53676. const options = config.preview;
  53677. const hostname = resolveHostname(options.host);
  53678. const port = (_b = options.port) !== null && _b !== void 0 ? _b : 4173;
  53679. const protocol = options.https ? 'https' : 'http';
  53680. const logger = config.logger;
  53681. const base = config.base;
  53682. const serverPort = await httpServerStart(httpServer, {
  53683. port,
  53684. strictPort: options.strictPort,
  53685. host: hostname.host,
  53686. logger
  53687. });
  53688. if (options.open) {
  53689. const path = typeof options.open === 'string' ? options.open : base;
  53690. openBrowser(path.startsWith('http')
  53691. ? path
  53692. : `${protocol}://${hostname.name}:${serverPort}${path}`, true, logger);
  53693. }
  53694. return {
  53695. config,
  53696. httpServer,
  53697. printUrls() {
  53698. printCommonServerUrls(httpServer, config.preview, config);
  53699. }
  53700. };
  53701. }
  53702. var preview$1 = {
  53703. __proto__: null,
  53704. resolvePreviewOptions: resolvePreviewOptions,
  53705. preview: preview
  53706. };
  53707. /**
  53708. * https://github.com/rollup/plugins/blob/master/packages/json/src/index.js
  53709. *
  53710. * This source code is licensed under the MIT license found in the
  53711. * LICENSE file at
  53712. * https://github.com/rollup/plugins/blob/master/LICENSE
  53713. */
  53714. // Custom json filter for vite
  53715. const jsonExtRE = /\.json($|\?)(?!commonjs-(proxy|external))/;
  53716. function jsonPlugin(options = {}, isBuild) {
  53717. return {
  53718. name: 'vite:json',
  53719. transform(json, id) {
  53720. if (!jsonExtRE.test(id))
  53721. return null;
  53722. if (SPECIAL_QUERY_RE.test(id))
  53723. return null;
  53724. try {
  53725. if (options.stringify) {
  53726. if (isBuild) {
  53727. return {
  53728. // during build, parse then double-stringify to remove all
  53729. // unnecessary whitespaces to reduce bundle size.
  53730. code: `export default JSON.parse(${JSON.stringify(JSON.stringify(JSON.parse(json)))})`,
  53731. map: { mappings: '' }
  53732. };
  53733. }
  53734. else {
  53735. return `export default JSON.parse(${JSON.stringify(json)})`;
  53736. }
  53737. }
  53738. const parsed = JSON.parse(json);
  53739. return {
  53740. code: dataToEsm(parsed, {
  53741. preferConst: true,
  53742. namedExports: options.namedExports
  53743. }),
  53744. map: { mappings: '' }
  53745. };
  53746. }
  53747. catch (e) {
  53748. const errorMessageList = /[\d]+/.exec(e.message);
  53749. const position = errorMessageList && parseInt(errorMessageList[0], 10);
  53750. const msg = position
  53751. ? `, invalid JSON syntax found at line ${position}`
  53752. : `.`;
  53753. this.error(`Failed to parse JSON file` + msg, e.idx);
  53754. }
  53755. }
  53756. };
  53757. }
  53758. // ids in transform are normalized to unix style
  53759. const normalizedClientEntry = normalizePath$3(CLIENT_ENTRY);
  53760. const normalizedEnvEntry = normalizePath$3(ENV_ENTRY);
  53761. /**
  53762. * some values used by the client needs to be dynamically injected by the server
  53763. * @server-only
  53764. */
  53765. function clientInjectionsPlugin(config) {
  53766. return {
  53767. name: 'vite:client-inject',
  53768. transform(code, id, options) {
  53769. if (id === normalizedClientEntry || id === normalizedEnvEntry) {
  53770. let options = config.server.hmr;
  53771. options = options && typeof options !== 'boolean' ? options : {};
  53772. const host = options.host || null;
  53773. const protocol = options.protocol || null;
  53774. const timeout = options.timeout || 30000;
  53775. const overlay = options.overlay !== false;
  53776. let port;
  53777. if (isObject$1(config.server.hmr)) {
  53778. port = config.server.hmr.clientPort || config.server.hmr.port;
  53779. }
  53780. if (config.server.middlewareMode) {
  53781. port = String(port || 24678);
  53782. }
  53783. else {
  53784. port = String(port || options.port || config.server.port);
  53785. }
  53786. let hmrBase = config.base;
  53787. if (options.path) {
  53788. hmrBase = path__default.posix.join(hmrBase, options.path);
  53789. }
  53790. if (hmrBase !== '/') {
  53791. port = path__default.posix.normalize(`${port}${hmrBase}`);
  53792. }
  53793. return code
  53794. .replace(`__MODE__`, JSON.stringify(config.mode))
  53795. .replace(`__BASE__`, JSON.stringify(config.base))
  53796. .replace(`__DEFINES__`, serializeDefine(config.define || {}))
  53797. .replace(`__HMR_PROTOCOL__`, JSON.stringify(protocol))
  53798. .replace(`__HMR_HOSTNAME__`, JSON.stringify(host))
  53799. .replace(`__HMR_PORT__`, JSON.stringify(port))
  53800. .replace(`__HMR_TIMEOUT__`, JSON.stringify(timeout))
  53801. .replace(`__HMR_ENABLE_OVERLAY__`, JSON.stringify(overlay));
  53802. }
  53803. else if (!(options === null || options === void 0 ? void 0 : options.ssr) && code.includes('process.env.NODE_ENV')) {
  53804. // replace process.env.NODE_ENV instead of defining a global
  53805. // for it to avoid shimming a `process` object during dev,
  53806. // avoiding inconsistencies between dev and build
  53807. return code.replace(/\bprocess\.env\.NODE_ENV\b/g, JSON.stringify(config.mode));
  53808. }
  53809. }
  53810. };
  53811. }
  53812. function serializeDefine(define) {
  53813. let res = `{`;
  53814. for (const key in define) {
  53815. const val = define[key];
  53816. res += `${JSON.stringify(key)}: ${typeof val === 'string' ? `(${val})` : JSON.stringify(val)}, `;
  53817. }
  53818. return res + `}`;
  53819. }
  53820. const wasmHelperId = '/__vite-wasm-helper';
  53821. const wasmHelper = async (opts = {}, url) => {
  53822. let result;
  53823. if (url.startsWith('data:')) {
  53824. const urlContent = url.replace(/^data:.*?base64,/, '');
  53825. let bytes;
  53826. if (typeof Buffer === 'function' && typeof Buffer.from === 'function') {
  53827. bytes = Buffer.from(urlContent, 'base64');
  53828. }
  53829. else if (typeof atob === 'function') {
  53830. // @ts-ignore
  53831. const binaryString = atob(urlContent);
  53832. bytes = new Uint8Array(binaryString.length);
  53833. for (let i = 0; i < binaryString.length; i++) {
  53834. bytes[i] = binaryString.charCodeAt(i);
  53835. }
  53836. }
  53837. else {
  53838. throw new Error('Failed to decode base64-encoded data URL, Buffer and atob are not supported');
  53839. }
  53840. // @ts-ignore
  53841. result = await WebAssembly.instantiate(bytes, opts);
  53842. }
  53843. else {
  53844. // https://github.com/mdn/webassembly-examples/issues/5
  53845. // WebAssembly.instantiateStreaming requires the server to provide the
  53846. // correct MIME type for .wasm files, which unfortunately doesn't work for
  53847. // a lot of static file servers, so we just work around it by getting the
  53848. // raw buffer.
  53849. // @ts-ignore
  53850. const response = await fetch(url);
  53851. const contentType = response.headers.get('Content-Type') || '';
  53852. if (
  53853. // @ts-ignore
  53854. 'instantiateStreaming' in WebAssembly &&
  53855. contentType.startsWith('application/wasm')) {
  53856. // @ts-ignore
  53857. result = await WebAssembly.instantiateStreaming(response, opts);
  53858. }
  53859. else {
  53860. const buffer = await response.arrayBuffer();
  53861. // @ts-ignore
  53862. result = await WebAssembly.instantiate(buffer, opts);
  53863. }
  53864. }
  53865. return result.instance.exports;
  53866. };
  53867. const wasmHelperCode = wasmHelper.toString();
  53868. const wasmPlugin = (config) => {
  53869. return {
  53870. name: 'vite:wasm',
  53871. resolveId(id) {
  53872. if (id === wasmHelperId) {
  53873. return id;
  53874. }
  53875. },
  53876. async load(id) {
  53877. if (id === wasmHelperId) {
  53878. return `export default ${wasmHelperCode}`;
  53879. }
  53880. if (!id.endsWith('.wasm')) {
  53881. return;
  53882. }
  53883. const url = await fileToUrl(id, config, this);
  53884. return `
  53885. import initWasm from "${wasmHelperId}"
  53886. export default opts => initWasm(opts, ${JSON.stringify(url)})
  53887. `;
  53888. }
  53889. };
  53890. };
  53891. const WorkerFileId = 'worker_file';
  53892. const workerCache = new WeakMap();
  53893. function emitWorkerFile(ctx, config, asset, type) {
  53894. const fileName = asset.fileName;
  53895. const workerMap = workerCache.get(config);
  53896. if (workerMap[type].has(fileName)) {
  53897. return workerMap[type].get(fileName);
  53898. }
  53899. const hash = ctx.emitFile(asset);
  53900. workerMap[type].set(fileName, hash);
  53901. workerMap.emitted.set(hash, fileName);
  53902. return hash;
  53903. }
  53904. function emitWorkerAssets(ctx, config, asset) {
  53905. const { format } = config.worker;
  53906. return emitWorkerFile(ctx, config, asset, format === 'es' ? 'chunks' : 'assets');
  53907. }
  53908. function emitWorkerSourcemap(ctx, config, asset) {
  53909. return emitWorkerFile(ctx, config, asset, 'assets');
  53910. }
  53911. function emitWorkerChunks(ctx, config, asset) {
  53912. return emitWorkerFile(ctx, config, asset, 'chunks');
  53913. }
  53914. async function bundleWorkerEntry(ctx, config, id, query) {
  53915. // bundle the file as entry to support imports
  53916. const rollup = require('rollup');
  53917. const { plugins, rollupOptions, format } = config.worker;
  53918. const bundle = await rollup.rollup({
  53919. ...rollupOptions,
  53920. input: cleanUrl(id),
  53921. plugins,
  53922. onwarn(warning, warn) {
  53923. onRollupWarning(warning, warn, config);
  53924. },
  53925. preserveEntrySignatures: false
  53926. });
  53927. let chunk;
  53928. try {
  53929. const { output: [outputChunk, ...outputChunks] } = await bundle.generate({
  53930. format,
  53931. sourcemap: config.build.sourcemap
  53932. });
  53933. chunk = outputChunk;
  53934. outputChunks.forEach((outputChunk) => {
  53935. if (outputChunk.type === 'asset') {
  53936. emitWorkerAssets(ctx, config, outputChunk);
  53937. }
  53938. else if (outputChunk.type === 'chunk') {
  53939. emitWorkerChunks(ctx, config, {
  53940. fileName: path__default.posix.join(config.build.assetsDir, outputChunk.fileName),
  53941. source: outputChunk.code,
  53942. type: 'asset'
  53943. });
  53944. }
  53945. });
  53946. }
  53947. finally {
  53948. await bundle.close();
  53949. }
  53950. return emitSourcemapForWorkerEntry(ctx, config, id, query, chunk);
  53951. }
  53952. function emitSourcemapForWorkerEntry(context, config, id, query, chunk) {
  53953. let { code, map: sourcemap } = chunk;
  53954. if (sourcemap) {
  53955. if (config.build.sourcemap === 'inline') {
  53956. // Manually add the sourcemap to the code if configured for inline sourcemaps.
  53957. // TODO: Remove when https://github.com/rollup/rollup/issues/3913 is resolved
  53958. // Currently seems that it won't be resolved until Rollup 3
  53959. const dataUrl = sourcemap.toUrl();
  53960. code += `//# sourceMappingURL=${dataUrl}`;
  53961. }
  53962. else if (config.build.sourcemap === 'hidden' ||
  53963. config.build.sourcemap === true) {
  53964. const basename = path__default.parse(cleanUrl(id)).name;
  53965. const data = sourcemap.toString();
  53966. const content = Buffer.from(data);
  53967. const contentHash = getAssetHash(content);
  53968. const fileName = `${basename}.${contentHash}.js.map`;
  53969. const filePath = path__default.posix.join(config.build.assetsDir, fileName);
  53970. emitWorkerSourcemap(context, config, {
  53971. fileName: filePath,
  53972. type: 'asset',
  53973. source: data
  53974. });
  53975. // Emit the comment that tells the JS debugger where it can find the
  53976. // sourcemap file.
  53977. // 'hidden' causes the sourcemap file to be created but
  53978. // the comment in the file to be omitted.
  53979. if (config.build.sourcemap === true) {
  53980. // inline web workers need to use the full sourcemap path
  53981. // non-inline web workers can use a relative path
  53982. const sourceMapUrl = (query === null || query === void 0 ? void 0 : query.inline) != null
  53983. ? path__default.posix.join(config.base, filePath)
  53984. : fileName;
  53985. code += `//# sourceMappingURL=${sourceMapUrl}`;
  53986. }
  53987. }
  53988. }
  53989. return Buffer.from(code);
  53990. }
  53991. async function workerFileToUrl(ctx, config, id, query) {
  53992. const workerMap = workerCache.get(config);
  53993. let hash = workerMap.bundle.get(id);
  53994. if (hash) {
  53995. // rewrite truth id, no need to replace by asset plugin
  53996. return config.base + workerMap.emitted.get(hash);
  53997. }
  53998. const code = await bundleWorkerEntry(ctx, config, id, query);
  53999. const basename = path__default.parse(cleanUrl(id)).name;
  54000. const contentHash = getAssetHash(code);
  54001. const fileName = path__default.posix.join(config.build.assetsDir, `${basename}.${contentHash}.js`);
  54002. hash = emitWorkerAssets(ctx, config, {
  54003. fileName,
  54004. type: 'asset',
  54005. source: code
  54006. });
  54007. workerMap.bundle.set(id, hash);
  54008. return `__VITE_ASSET__${hash}__`;
  54009. }
  54010. function webWorkerPlugin(config) {
  54011. const isBuild = config.command === 'build';
  54012. return {
  54013. name: 'vite:worker',
  54014. buildStart() {
  54015. workerCache.set(config, {
  54016. assets: new Map(),
  54017. chunks: new Map(),
  54018. bundle: new Map(),
  54019. emitted: new Map()
  54020. });
  54021. },
  54022. load(id) {
  54023. var _a;
  54024. if (isBuild) {
  54025. const parsedQuery = parseRequest(id);
  54026. if (parsedQuery &&
  54027. ((_a = parsedQuery.worker) !== null && _a !== void 0 ? _a : parsedQuery.sharedworker) != null) {
  54028. return '';
  54029. }
  54030. }
  54031. },
  54032. async transform(_, id) {
  54033. var _a;
  54034. const query = parseRequest(id);
  54035. if (query && query[WorkerFileId] != null) {
  54036. return {
  54037. code: `import '${ENV_PUBLIC_PATH}'\n` + _
  54038. };
  54039. }
  54040. if (query == null ||
  54041. (query && ((_a = query.worker) !== null && _a !== void 0 ? _a : query.sharedworker) == null)) {
  54042. return;
  54043. }
  54044. let url;
  54045. if (isBuild) {
  54046. if (query.inline != null) {
  54047. const code = await bundleWorkerEntry(this, config, id, query);
  54048. const { format } = config.worker;
  54049. const workerOptions = format === 'es' ? '{type: "module"}' : '{}';
  54050. // inline as blob data url
  54051. return {
  54052. code: `const encodedJs = "${code.toString('base64')}";
  54053. const blob = typeof window !== "undefined" && window.Blob && new Blob([atob(encodedJs)], { type: "text/javascript;charset=utf-8" });
  54054. export default function WorkerWrapper() {
  54055. const objURL = blob && (window.URL || window.webkitURL).createObjectURL(blob);
  54056. try {
  54057. return objURL ? new Worker(objURL, ${workerOptions}) : new Worker("data:application/javascript;base64," + encodedJs, {type: "module"});
  54058. } finally {
  54059. objURL && (window.URL || window.webkitURL).revokeObjectURL(objURL);
  54060. }
  54061. }`,
  54062. // Empty sourcemap to supress Rollup warning
  54063. map: { mappings: '' }
  54064. };
  54065. }
  54066. else {
  54067. url = await workerFileToUrl(this, config, id, query);
  54068. }
  54069. }
  54070. else {
  54071. url = await fileToUrl(cleanUrl(id), config, this);
  54072. url = injectQuery(url, WorkerFileId);
  54073. }
  54074. const workerConstructor = query.sharedworker != null ? 'SharedWorker' : 'Worker';
  54075. const workerOptions = { type: 'module' };
  54076. return {
  54077. code: `export default function WorkerWrapper() {
  54078. return new ${workerConstructor}(${JSON.stringify(url)}, ${JSON.stringify(workerOptions, null, 2)})
  54079. }`,
  54080. map: { mappings: '' } // Empty sourcemap to supress Rolup warning
  54081. };
  54082. },
  54083. renderChunk(code) {
  54084. if (config.isWorker && code.includes('import.meta.url')) {
  54085. return code.replace('import.meta.url', 'self.location.href');
  54086. }
  54087. }
  54088. };
  54089. }
  54090. /**
  54091. * A plugin to avoid an aliased AND optimized dep from being aliased in src
  54092. */
  54093. function preAliasPlugin() {
  54094. let server;
  54095. return {
  54096. name: 'vite:pre-alias',
  54097. configureServer(_server) {
  54098. server = _server;
  54099. },
  54100. async resolveId(id, importer, options) {
  54101. if (!(options === null || options === void 0 ? void 0 : options.ssr) && bareImportRE.test(id) && !(options === null || options === void 0 ? void 0 : options.scan)) {
  54102. return await tryOptimizedResolve(id, server, importer);
  54103. }
  54104. }
  54105. };
  54106. }
  54107. const nonJsRe = /\.(json)($|\?)/;
  54108. const isNonJsRequest = (request) => nonJsRe.test(request);
  54109. function definePlugin(config) {
  54110. const isBuild = config.command === 'build';
  54111. const processNodeEnv = {
  54112. 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || config.mode),
  54113. 'global.process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || config.mode),
  54114. 'globalThis.process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || config.mode)
  54115. };
  54116. const userDefine = {};
  54117. for (const key in config.define) {
  54118. const val = config.define[key];
  54119. userDefine[key] = typeof val === 'string' ? val : JSON.stringify(val);
  54120. }
  54121. // during dev, import.meta properties are handled by importAnalysis plugin
  54122. const importMetaKeys = {};
  54123. if (isBuild) {
  54124. const env = {
  54125. ...config.env,
  54126. SSR: !!config.build.ssr
  54127. };
  54128. for (const key in env) {
  54129. importMetaKeys[`import.meta.env.${key}`] = JSON.stringify(env[key]);
  54130. }
  54131. Object.assign(importMetaKeys, {
  54132. 'import.meta.env.': `({}).`,
  54133. 'import.meta.env': JSON.stringify(config.env),
  54134. 'import.meta.hot': `false`
  54135. });
  54136. }
  54137. function generatePattern(ssr) {
  54138. var _a;
  54139. const processEnv = {};
  54140. const isNeedProcessEnv = !ssr || ((_a = config.ssr) === null || _a === void 0 ? void 0 : _a.target) === 'webworker';
  54141. if (isNeedProcessEnv) {
  54142. Object.assign(processEnv, {
  54143. 'process.env.': `({}).`,
  54144. 'global.process.env.': `({}).`,
  54145. 'globalThis.process.env.': `({}).`
  54146. });
  54147. }
  54148. const replacements = {
  54149. ...(isNeedProcessEnv ? processNodeEnv : {}),
  54150. ...userDefine,
  54151. ...importMetaKeys,
  54152. ...processEnv
  54153. };
  54154. const replacementsKeys = Object.keys(replacements);
  54155. const pattern = replacementsKeys.length
  54156. ? new RegExp(
  54157. // Do not allow preceding '.', but do allow preceding '...' for spread operations
  54158. '(?<!(?<!\\.\\.)\\.)\\b(' +
  54159. replacementsKeys
  54160. .map((str) => {
  54161. return str.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&');
  54162. })
  54163. .join('|') +
  54164. // prevent trailing assignments
  54165. ')\\b(?!\\s*?=[^=])', 'g')
  54166. : null;
  54167. return [replacements, pattern];
  54168. }
  54169. const defaultPattern = generatePattern(false);
  54170. const ssrPattern = generatePattern(true);
  54171. return {
  54172. name: 'vite:define',
  54173. transform(code, id, options) {
  54174. const ssr = (options === null || options === void 0 ? void 0 : options.ssr) === true;
  54175. if (!ssr && !isBuild) {
  54176. // for dev we inject actual global defines in the vite client to
  54177. // avoid the transform cost.
  54178. return;
  54179. }
  54180. if (
  54181. // exclude html, css and static assets for performance
  54182. isHTMLRequest(id) ||
  54183. isCSSRequest(id) ||
  54184. isNonJsRequest(id) ||
  54185. config.assetsInclude(id)) {
  54186. return;
  54187. }
  54188. const [replacements, pattern] = ssr ? ssrPattern : defaultPattern;
  54189. if (!pattern) {
  54190. return null;
  54191. }
  54192. if (ssr && !isBuild) {
  54193. // ssr + dev, simple replace
  54194. return code.replace(pattern, (_, match) => {
  54195. return '' + replacements[match];
  54196. });
  54197. }
  54198. const s = new MagicString(code);
  54199. let hasReplaced = false;
  54200. let match;
  54201. while ((match = pattern.exec(code))) {
  54202. hasReplaced = true;
  54203. const start = match.index;
  54204. const end = start + match[0].length;
  54205. const replacement = '' + replacements[match[1]];
  54206. s.overwrite(start, end, replacement, { contentOnly: true });
  54207. }
  54208. if (!hasReplaced) {
  54209. return null;
  54210. }
  54211. const result = { code: s.toString() };
  54212. if (config.build.sourcemap) {
  54213. result.map = s.generateMap({ hires: true });
  54214. }
  54215. return result;
  54216. }
  54217. };
  54218. }
  54219. const ignoreFlagRE = /\/\*\s*@vite-ignore\s*\*\//;
  54220. const WORKER_FILE_ID = 'worker_url_file';
  54221. function getWorkerType(raw, clean, i) {
  54222. function err(e, pos) {
  54223. const error = new Error(e);
  54224. error.pos = pos;
  54225. throw error;
  54226. }
  54227. const commaIndex = clean.indexOf(',', i);
  54228. if (commaIndex === -1) {
  54229. return 'classic';
  54230. }
  54231. const endIndex = clean.indexOf(')', i);
  54232. // case: ') ... ,' mean no worker options params
  54233. if (commaIndex > endIndex) {
  54234. return 'classic';
  54235. }
  54236. // need to find in comment code
  54237. const workerOptString = raw.substring(commaIndex + 1, endIndex);
  54238. const hasViteIgnore = ignoreFlagRE.test(workerOptString);
  54239. if (hasViteIgnore) {
  54240. return 'ignore';
  54241. }
  54242. // need to find in no comment code
  54243. const cleanWorkerOptString = clean.substring(commaIndex + 1, endIndex);
  54244. if (!cleanWorkerOptString.trim().length) {
  54245. return 'classic';
  54246. }
  54247. let workerOpts = { type: 'classic' };
  54248. try {
  54249. workerOpts = lib$2.parse(workerOptString);
  54250. }
  54251. catch (e) {
  54252. // can't parse by JSON5, so the worker options had unexpect char.
  54253. err('Vite is unable to parse the worker options as the value is not static.' +
  54254. 'To ignore this error, please use /* @vite-ignore */ in the worker options.', commaIndex + 1);
  54255. }
  54256. if (['classic', 'module'].includes(workerOpts.type)) {
  54257. return workerOpts.type;
  54258. }
  54259. return 'classic';
  54260. }
  54261. function workerImportMetaUrlPlugin(config) {
  54262. const isBuild = config.command === 'build';
  54263. let server;
  54264. return {
  54265. name: 'vite:worker-import-meta-url',
  54266. configureServer(_server) {
  54267. server = _server;
  54268. },
  54269. async transform(code, id, options) {
  54270. var _a;
  54271. const query = parseRequest(id);
  54272. if (query && query[WORKER_FILE_ID] != null && query['type'] != null) {
  54273. const workerType = query['type'];
  54274. let injectEnv = '';
  54275. if (workerType === 'classic') {
  54276. injectEnv = `importScripts('${ENV_PUBLIC_PATH}')\n`;
  54277. }
  54278. else if (workerType === 'module') {
  54279. injectEnv = `import '${ENV_PUBLIC_PATH}'\n`;
  54280. }
  54281. else if (workerType === 'ignore') {
  54282. if (isBuild) {
  54283. injectEnv = '';
  54284. }
  54285. else if (server) {
  54286. // dynamic worker type we can't know how import the env
  54287. // so we copy /@vite/env code of server transform result into file header
  54288. const { moduleGraph } = server;
  54289. const module = moduleGraph.getModuleById(ENV_ENTRY);
  54290. injectEnv = ((_a = module === null || module === void 0 ? void 0 : module.transformResult) === null || _a === void 0 ? void 0 : _a.code) || '';
  54291. }
  54292. }
  54293. return {
  54294. code: injectEnv + code
  54295. };
  54296. }
  54297. let s;
  54298. if ((code.includes('new Worker') || code.includes('new SharedWorker')) &&
  54299. code.includes('new URL') &&
  54300. code.includes(`import.meta.url`)) {
  54301. const cleanString = stripLiteral(code);
  54302. const workerImportMetaUrlRE = /\bnew\s+(Worker|SharedWorker)\s*\(\s*(new\s+URL\s*\(\s*('[^']+'|"[^"]+"|`[^`]+`)\s*,\s*import\.meta\.url\s*\))/g;
  54303. let match;
  54304. while ((match = workerImportMetaUrlRE.exec(cleanString))) {
  54305. const { 0: allExp, 2: exp, 3: emptyUrl, index } = match;
  54306. const urlIndex = allExp.indexOf(exp) + index;
  54307. const urlStart = cleanString.indexOf(emptyUrl, index);
  54308. const urlEnd = urlStart + emptyUrl.length;
  54309. const rawUrl = code.slice(urlStart, urlEnd);
  54310. if (options === null || options === void 0 ? void 0 : options.ssr) {
  54311. this.error(`\`new URL(url, import.meta.url)\` is not supported in SSR.`, urlIndex);
  54312. }
  54313. // potential dynamic template string
  54314. if (rawUrl[0] === '`' && /\$\{/.test(rawUrl)) {
  54315. this.error(`\`new URL(url, import.meta.url)\` is not supported in dynamic template string.`, urlIndex);
  54316. }
  54317. s || (s = new MagicString(code));
  54318. const workerType = getWorkerType(code, cleanString, index + allExp.length);
  54319. const file = path__default.resolve(path__default.dirname(id), rawUrl.slice(1, -1));
  54320. let url;
  54321. if (isBuild) {
  54322. url = await workerFileToUrl(this, config, file, query);
  54323. }
  54324. else {
  54325. url = await fileToUrl(cleanUrl(file), config, this);
  54326. url = injectQuery(url, WORKER_FILE_ID);
  54327. url = injectQuery(url, `type=${workerType}`);
  54328. }
  54329. s.overwrite(urlIndex, urlIndex + exp.length, JSON.stringify(url), {
  54330. contentOnly: true
  54331. });
  54332. }
  54333. if (s) {
  54334. return {
  54335. code: s.toString(),
  54336. map: config.build.sourcemap ? s.generateMap({ hires: true }) : null
  54337. };
  54338. }
  54339. return null;
  54340. }
  54341. }
  54342. };
  54343. }
  54344. /**
  54345. * Prepares the rendered chunks to contain additional metadata during build.
  54346. */
  54347. function metadataPlugin() {
  54348. return {
  54349. name: 'vite:build-metadata',
  54350. async renderChunk(_code, chunk) {
  54351. chunk.viteMetadata = {
  54352. importedAssets: new Set(),
  54353. importedCss: new Set()
  54354. };
  54355. return null;
  54356. }
  54357. };
  54358. }
  54359. async function resolvePlugins(config, prePlugins, normalPlugins, postPlugins) {
  54360. const isBuild = config.command === 'build';
  54361. const isWatch = isBuild && !!config.build.watch;
  54362. const buildPlugins = isBuild
  54363. ? (await Promise.resolve().then(function () { return build$1; })).resolveBuildPlugins(config)
  54364. : { pre: [], post: [] };
  54365. return [
  54366. isWatch ? ensureWatchPlugin() : null,
  54367. isBuild ? metadataPlugin() : null,
  54368. isBuild ? null : preAliasPlugin(),
  54369. alias$1({ entries: config.resolve.alias }),
  54370. ...prePlugins,
  54371. config.build.polyfillModulePreload
  54372. ? modulePreloadPolyfillPlugin(config)
  54373. : null,
  54374. resolvePlugin({
  54375. ...config.resolve,
  54376. root: config.root,
  54377. isProduction: config.isProduction,
  54378. isBuild,
  54379. packageCache: config.packageCache,
  54380. ssrConfig: config.ssr,
  54381. asSrc: true
  54382. }),
  54383. isBuild ? null : optimizedDepsPlugin(),
  54384. htmlInlineProxyPlugin(config),
  54385. cssPlugin(config),
  54386. config.esbuild !== false ? esbuildPlugin(config.esbuild) : null,
  54387. jsonPlugin({
  54388. namedExports: true,
  54389. ...config.json
  54390. }, isBuild),
  54391. wasmPlugin(config),
  54392. webWorkerPlugin(config),
  54393. assetPlugin(config),
  54394. ...normalPlugins,
  54395. definePlugin(config),
  54396. cssPostPlugin(config),
  54397. config.build.ssr ? ssrRequireHookPlugin(config) : null,
  54398. isBuild && buildHtmlPlugin(config),
  54399. workerImportMetaUrlPlugin(config),
  54400. ...buildPlugins.pre,
  54401. ...postPlugins,
  54402. ...buildPlugins.post,
  54403. // internal server-only plugins are always applied after everything else
  54404. ...(isBuild
  54405. ? []
  54406. : [clientInjectionsPlugin(config), importAnalysisPlugin(config)])
  54407. ].filter(Boolean);
  54408. }
  54409. const debug = createDebugger('vite:config');
  54410. /**
  54411. * Type helper to make it easier to use vite.config.ts
  54412. * accepts a direct {@link UserConfig} object, or a function that returns it.
  54413. * The function receives a {@link ConfigEnv} object that exposes two properties:
  54414. * `command` (either `'build'` or `'serve'`), and `mode`.
  54415. */
  54416. function defineConfig(config) {
  54417. return config;
  54418. }
  54419. async function resolveConfig(inlineConfig, command, defaultMode = 'development') {
  54420. var _a, _b, _c, _d, _e, _f, _g, _h, _j;
  54421. let config = inlineConfig;
  54422. let configFileDependencies = [];
  54423. let mode = inlineConfig.mode || defaultMode;
  54424. // some dependencies e.g. @vue/compiler-* relies on NODE_ENV for getting
  54425. // production-specific behavior, so set it here even though we haven't
  54426. // resolve the final mode yet
  54427. if (mode === 'production') {
  54428. process.env.NODE_ENV = 'production';
  54429. }
  54430. const configEnv = {
  54431. mode,
  54432. command
  54433. };
  54434. let { configFile } = config;
  54435. if (configFile !== false) {
  54436. const loadResult = await loadConfigFromFile(configEnv, configFile, config.root, config.logLevel);
  54437. if (loadResult) {
  54438. config = mergeConfig(loadResult.config, config);
  54439. configFile = loadResult.path;
  54440. configFileDependencies = loadResult.dependencies;
  54441. }
  54442. }
  54443. // Define logger
  54444. const logger = createLogger(config.logLevel, {
  54445. allowClearScreen: config.clearScreen,
  54446. customLogger: config.customLogger
  54447. });
  54448. // user config may provide an alternative mode. But --mode has a higher priority
  54449. mode = inlineConfig.mode || config.mode || mode;
  54450. configEnv.mode = mode;
  54451. // resolve plugins
  54452. const rawUserPlugins = (config.plugins || []).flat(Infinity).filter((p) => {
  54453. if (!p) {
  54454. return false;
  54455. }
  54456. else if (!p.apply) {
  54457. return true;
  54458. }
  54459. else if (typeof p.apply === 'function') {
  54460. return p.apply({ ...config, mode }, configEnv);
  54461. }
  54462. else {
  54463. return p.apply === command;
  54464. }
  54465. });
  54466. const [prePlugins, normalPlugins, postPlugins] = sortUserPlugins(rawUserPlugins);
  54467. // resolve worker
  54468. const resolvedWorkerOptions = {
  54469. format: ((_a = config.worker) === null || _a === void 0 ? void 0 : _a.format) || 'iife',
  54470. plugins: [],
  54471. rollupOptions: ((_b = config.worker) === null || _b === void 0 ? void 0 : _b.rollupOptions) || {}
  54472. };
  54473. // run config hooks
  54474. const userPlugins = [...prePlugins, ...normalPlugins, ...postPlugins];
  54475. for (const p of userPlugins) {
  54476. if (p.config) {
  54477. const res = await p.config(config, configEnv);
  54478. if (res) {
  54479. config = mergeConfig(config, res);
  54480. }
  54481. }
  54482. }
  54483. // resolve root
  54484. const resolvedRoot = normalizePath$3(config.root ? path__default.resolve(config.root) : process.cwd());
  54485. const clientAlias = [
  54486. { find: /^[\/]?@vite\/env/, replacement: () => ENV_ENTRY },
  54487. { find: /^[\/]?@vite\/client/, replacement: () => CLIENT_ENTRY }
  54488. ];
  54489. // resolve alias with internal client alias
  54490. const resolvedAlias = normalizeAlias(mergeAlias(
  54491. // @ts-ignore because @rollup/plugin-alias' type doesn't allow function
  54492. // replacement, but its implementation does work with function values.
  54493. clientAlias, ((_c = config.resolve) === null || _c === void 0 ? void 0 : _c.alias) || config.alias || []));
  54494. const resolveOptions = {
  54495. dedupe: config.dedupe,
  54496. ...config.resolve,
  54497. alias: resolvedAlias
  54498. };
  54499. // load .env files
  54500. const envDir = config.envDir
  54501. ? normalizePath$3(path__default.resolve(resolvedRoot, config.envDir))
  54502. : resolvedRoot;
  54503. const userEnv = inlineConfig.envFile !== false &&
  54504. loadEnv(mode, envDir, resolveEnvPrefix(config));
  54505. // Note it is possible for user to have a custom mode, e.g. `staging` where
  54506. // production-like behavior is expected. This is indicated by NODE_ENV=production
  54507. // loaded from `.staging.env` and set by us as VITE_USER_NODE_ENV
  54508. const isProduction = (process.env.VITE_USER_NODE_ENV || mode) === 'production';
  54509. if (isProduction) {
  54510. // in case default mode was not production and is overwritten
  54511. process.env.NODE_ENV = 'production';
  54512. }
  54513. // resolve public base url
  54514. const BASE_URL = resolveBaseUrl(config.base, command === 'build', logger);
  54515. const resolvedBuildOptions = resolveBuildOptions(config.build);
  54516. // resolve cache directory
  54517. const pkgPath = lookupFile(resolvedRoot, [`package.json`], { pathOnly: true });
  54518. const cacheDir = config.cacheDir
  54519. ? path__default.resolve(resolvedRoot, config.cacheDir)
  54520. : pkgPath
  54521. ? path__default.join(path__default.dirname(pkgPath), `node_modules/.vite`)
  54522. : path__default.join(resolvedRoot, `.vite`);
  54523. const assetsFilter = config.assetsInclude
  54524. ? createFilter$1(config.assetsInclude)
  54525. : () => false;
  54526. // create an internal resolver to be used in special scenarios, e.g.
  54527. // optimizer & handling css @imports
  54528. const createResolver = (options) => {
  54529. let aliasContainer;
  54530. let resolverContainer;
  54531. return async (id, importer, aliasOnly, ssr) => {
  54532. var _a;
  54533. let container;
  54534. if (aliasOnly) {
  54535. container =
  54536. aliasContainer ||
  54537. (aliasContainer = await createPluginContainer({
  54538. ...resolved,
  54539. plugins: [alias$1({ entries: resolved.resolve.alias })]
  54540. }));
  54541. }
  54542. else {
  54543. container =
  54544. resolverContainer ||
  54545. (resolverContainer = await createPluginContainer({
  54546. ...resolved,
  54547. plugins: [
  54548. alias$1({ entries: resolved.resolve.alias }),
  54549. resolvePlugin({
  54550. ...resolved.resolve,
  54551. root: resolvedRoot,
  54552. isProduction,
  54553. isBuild: command === 'build',
  54554. ssrConfig: resolved.ssr,
  54555. asSrc: true,
  54556. preferRelative: false,
  54557. tryIndex: true,
  54558. ...options
  54559. })
  54560. ]
  54561. }));
  54562. }
  54563. return (_a = (await container.resolveId(id, importer, { ssr }))) === null || _a === void 0 ? void 0 : _a.id;
  54564. };
  54565. };
  54566. const { publicDir } = config;
  54567. const resolvedPublicDir = publicDir !== false && publicDir !== ''
  54568. ? path__default.resolve(resolvedRoot, typeof publicDir === 'string' ? publicDir : 'public')
  54569. : '';
  54570. const server = resolveServerOptions(resolvedRoot, config.server, logger);
  54571. const optimizeDeps = config.optimizeDeps || {};
  54572. const resolved = {
  54573. ...config,
  54574. configFile: configFile ? normalizePath$3(configFile) : undefined,
  54575. configFileDependencies: configFileDependencies.map((name) => normalizePath$3(path__default.resolve(name))),
  54576. inlineConfig,
  54577. root: resolvedRoot,
  54578. base: BASE_URL,
  54579. resolve: resolveOptions,
  54580. publicDir: resolvedPublicDir,
  54581. cacheDir,
  54582. command,
  54583. mode,
  54584. isWorker: false,
  54585. isProduction,
  54586. plugins: userPlugins,
  54587. server,
  54588. build: resolvedBuildOptions,
  54589. preview: resolvePreviewOptions(config.preview, server),
  54590. env: {
  54591. ...userEnv,
  54592. BASE_URL,
  54593. MODE: mode,
  54594. DEV: !isProduction,
  54595. PROD: isProduction
  54596. },
  54597. assetsInclude(file) {
  54598. return DEFAULT_ASSETS_RE.test(file) || assetsFilter(file);
  54599. },
  54600. logger,
  54601. packageCache: new Map(),
  54602. createResolver,
  54603. optimizeDeps: {
  54604. ...optimizeDeps,
  54605. esbuildOptions: {
  54606. keepNames: optimizeDeps.keepNames,
  54607. preserveSymlinks: (_d = config.resolve) === null || _d === void 0 ? void 0 : _d.preserveSymlinks,
  54608. ...optimizeDeps.esbuildOptions
  54609. }
  54610. },
  54611. worker: resolvedWorkerOptions
  54612. };
  54613. // flat config.worker.plugin
  54614. const [workerPrePlugins, workerNormalPlugins, workerPostPlugins] = sortUserPlugins((_e = config.worker) === null || _e === void 0 ? void 0 : _e.plugins);
  54615. const workerResolved = { ...resolved, isWorker: true };
  54616. resolved.worker.plugins = await resolvePlugins(workerResolved, workerPrePlugins, workerNormalPlugins, workerPostPlugins);
  54617. // call configResolved worker plugins hooks
  54618. await Promise.all(resolved.worker.plugins.map((p) => { var _a; return (_a = p.configResolved) === null || _a === void 0 ? void 0 : _a.call(p, workerResolved); }));
  54619. resolved.plugins = await resolvePlugins(resolved, prePlugins, normalPlugins, postPlugins);
  54620. // call configResolved hooks
  54621. await Promise.all(userPlugins.map((p) => { var _a; return (_a = p.configResolved) === null || _a === void 0 ? void 0 : _a.call(p, resolved); }));
  54622. if (process.env.DEBUG) {
  54623. debug(`using resolved config: %O`, {
  54624. ...resolved,
  54625. plugins: resolved.plugins.map((p) => p.name)
  54626. });
  54627. }
  54628. // TODO Deprecation warnings - remove when out of beta
  54629. const logDeprecationWarning = (deprecatedOption, hint, error) => {
  54630. logger.warn(colors$1.yellow(colors$1.bold(`(!) "${deprecatedOption}" option is deprecated. ${hint}${error ? `\n${error.stack}` : ''}`)));
  54631. };
  54632. if ((_f = config.build) === null || _f === void 0 ? void 0 : _f.base) {
  54633. logDeprecationWarning('build.base', '"base" is now a root-level config option.');
  54634. config.base = config.build.base;
  54635. }
  54636. Object.defineProperty(resolvedBuildOptions, 'base', {
  54637. enumerable: false,
  54638. get() {
  54639. logDeprecationWarning('build.base', '"base" is now a root-level config option.', new Error());
  54640. return resolved.base;
  54641. }
  54642. });
  54643. if (config.alias) {
  54644. logDeprecationWarning('alias', 'Use "resolve.alias" instead.');
  54645. }
  54646. Object.defineProperty(resolved, 'alias', {
  54647. enumerable: false,
  54648. get() {
  54649. logDeprecationWarning('alias', 'Use "resolve.alias" instead.', new Error());
  54650. return resolved.resolve.alias;
  54651. }
  54652. });
  54653. if (config.dedupe) {
  54654. logDeprecationWarning('dedupe', 'Use "resolve.dedupe" instead.');
  54655. }
  54656. Object.defineProperty(resolved, 'dedupe', {
  54657. enumerable: false,
  54658. get() {
  54659. logDeprecationWarning('dedupe', 'Use "resolve.dedupe" instead.', new Error());
  54660. return resolved.resolve.dedupe;
  54661. }
  54662. });
  54663. if (optimizeDeps.keepNames) {
  54664. logDeprecationWarning('optimizeDeps.keepNames', 'Use "optimizeDeps.esbuildOptions.keepNames" instead.');
  54665. }
  54666. Object.defineProperty(resolved.optimizeDeps, 'keepNames', {
  54667. enumerable: false,
  54668. get() {
  54669. var _a;
  54670. logDeprecationWarning('optimizeDeps.keepNames', 'Use "optimizeDeps.esbuildOptions.keepNames" instead.', new Error());
  54671. return (_a = resolved.optimizeDeps.esbuildOptions) === null || _a === void 0 ? void 0 : _a.keepNames;
  54672. }
  54673. });
  54674. if ((_g = config.build) === null || _g === void 0 ? void 0 : _g.polyfillDynamicImport) {
  54675. logDeprecationWarning('build.polyfillDynamicImport', '"polyfillDynamicImport" has been removed. Please use @vitejs/plugin-legacy if your target browsers do not support dynamic imports.');
  54676. }
  54677. Object.defineProperty(resolvedBuildOptions, 'polyfillDynamicImport', {
  54678. enumerable: false,
  54679. get() {
  54680. logDeprecationWarning('build.polyfillDynamicImport', '"polyfillDynamicImport" has been removed. Please use @vitejs/plugin-legacy if your target browsers do not support dynamic imports.', new Error());
  54681. return false;
  54682. }
  54683. });
  54684. if ((_h = config.build) === null || _h === void 0 ? void 0 : _h.cleanCssOptions) {
  54685. logDeprecationWarning('build.cleanCssOptions', 'Vite now uses esbuild for CSS minification.');
  54686. }
  54687. if (((_j = config.build) === null || _j === void 0 ? void 0 : _j.terserOptions) && config.build.minify !== 'terser') {
  54688. logger.warn(colors$1.yellow(`build.terserOptions is specified but build.minify is not set to use Terser. ` +
  54689. `Note Vite now defaults to use esbuild for minification. If you still ` +
  54690. `prefer Terser, set build.minify to "terser".`));
  54691. }
  54692. return resolved;
  54693. }
  54694. /**
  54695. * Resolve base. Note that some users use Vite to build for non-web targets like
  54696. * electron or expects to deploy
  54697. */
  54698. function resolveBaseUrl(base = '/', isBuild, logger) {
  54699. // #1669 special treatment for empty for same dir relative base
  54700. if (base === '' || base === './') {
  54701. return isBuild ? base : '/';
  54702. }
  54703. if (base.startsWith('.')) {
  54704. logger.warn(colors$1.yellow(colors$1.bold(`(!) invalid "base" option: ${base}. The value can only be an absolute ` +
  54705. `URL, ./, or an empty string.`)));
  54706. base = '/';
  54707. }
  54708. // external URL
  54709. if (isExternalUrl(base)) {
  54710. if (!isBuild) {
  54711. // get base from full url during dev
  54712. const parsed = require$$0$6.parse(base);
  54713. base = parsed.pathname || '/';
  54714. }
  54715. }
  54716. else {
  54717. // ensure leading slash
  54718. if (!base.startsWith('/')) {
  54719. logger.warn(colors$1.yellow(colors$1.bold(`(!) "base" option should start with a slash.`)));
  54720. base = '/' + base;
  54721. }
  54722. }
  54723. // ensure ending slash
  54724. if (!base.endsWith('/')) {
  54725. logger.warn(colors$1.yellow(colors$1.bold(`(!) "base" option should end with a slash.`)));
  54726. base += '/';
  54727. }
  54728. return base;
  54729. }
  54730. function mergeConfigRecursively(defaults, overrides, rootPath) {
  54731. const merged = { ...defaults };
  54732. for (const key in overrides) {
  54733. const value = overrides[key];
  54734. if (value == null) {
  54735. continue;
  54736. }
  54737. const existing = merged[key];
  54738. if (existing == null) {
  54739. merged[key] = value;
  54740. continue;
  54741. }
  54742. // fields that require special handling
  54743. if (key === 'alias' && (rootPath === 'resolve' || rootPath === '')) {
  54744. merged[key] = mergeAlias(existing, value);
  54745. continue;
  54746. }
  54747. else if (key === 'assetsInclude' && rootPath === '') {
  54748. merged[key] = [].concat(existing, value);
  54749. continue;
  54750. }
  54751. else if (key === 'noExternal' &&
  54752. rootPath === 'ssr' &&
  54753. (existing === true || value === true)) {
  54754. merged[key] = true;
  54755. continue;
  54756. }
  54757. if (Array.isArray(existing) || Array.isArray(value)) {
  54758. merged[key] = [...arraify(existing !== null && existing !== void 0 ? existing : []), ...arraify(value !== null && value !== void 0 ? value : [])];
  54759. continue;
  54760. }
  54761. if (isObject$1(existing) && isObject$1(value)) {
  54762. merged[key] = mergeConfigRecursively(existing, value, rootPath ? `${rootPath}.${key}` : key);
  54763. continue;
  54764. }
  54765. merged[key] = value;
  54766. }
  54767. return merged;
  54768. }
  54769. function mergeConfig(defaults, overrides, isRoot = true) {
  54770. return mergeConfigRecursively(defaults, overrides, isRoot ? '' : '.');
  54771. }
  54772. function mergeAlias(a, b) {
  54773. if (!a)
  54774. return b;
  54775. if (!b)
  54776. return a;
  54777. if (isObject$1(a) && isObject$1(b)) {
  54778. return { ...a, ...b };
  54779. }
  54780. // the order is flipped because the alias is resolved from top-down,
  54781. // where the later should have higher priority
  54782. return [...normalizeAlias(b), ...normalizeAlias(a)];
  54783. }
  54784. function normalizeAlias(o = []) {
  54785. return Array.isArray(o)
  54786. ? o.map(normalizeSingleAlias)
  54787. : Object.keys(o).map((find) => normalizeSingleAlias({
  54788. find,
  54789. replacement: o[find]
  54790. }));
  54791. }
  54792. // https://github.com/vitejs/vite/issues/1363
  54793. // work around https://github.com/rollup/plugins/issues/759
  54794. function normalizeSingleAlias({ find, replacement, customResolver }) {
  54795. if (typeof find === 'string' &&
  54796. find.endsWith('/') &&
  54797. replacement.endsWith('/')) {
  54798. find = find.slice(0, find.length - 1);
  54799. replacement = replacement.slice(0, replacement.length - 1);
  54800. }
  54801. const alias = {
  54802. find,
  54803. replacement
  54804. };
  54805. if (customResolver) {
  54806. alias.customResolver = customResolver;
  54807. }
  54808. return alias;
  54809. }
  54810. function sortUserPlugins(plugins) {
  54811. const prePlugins = [];
  54812. const postPlugins = [];
  54813. const normalPlugins = [];
  54814. if (plugins) {
  54815. plugins.flat().forEach((p) => {
  54816. if (p.enforce === 'pre')
  54817. prePlugins.push(p);
  54818. else if (p.enforce === 'post')
  54819. postPlugins.push(p);
  54820. else
  54821. normalPlugins.push(p);
  54822. });
  54823. }
  54824. return [prePlugins, normalPlugins, postPlugins];
  54825. }
  54826. async function loadConfigFromFile(configEnv, configFile, configRoot = process.cwd(), logLevel) {
  54827. const start = perf_hooks.performance.now();
  54828. const getTime = () => `${(perf_hooks.performance.now() - start).toFixed(2)}ms`;
  54829. let resolvedPath;
  54830. let isTS = false;
  54831. let isESM = false;
  54832. let dependencies = [];
  54833. // check package.json for type: "module" and set `isMjs` to true
  54834. try {
  54835. const pkg = lookupFile(configRoot, ['package.json']);
  54836. if (pkg && JSON.parse(pkg).type === 'module') {
  54837. isESM = true;
  54838. }
  54839. }
  54840. catch (e) { }
  54841. if (configFile) {
  54842. // explicit config path is always resolved from cwd
  54843. resolvedPath = path__default.resolve(configFile);
  54844. isTS = configFile.endsWith('.ts');
  54845. if (configFile.endsWith('.mjs')) {
  54846. isESM = true;
  54847. }
  54848. }
  54849. else {
  54850. // implicit config file loaded from inline root (if present)
  54851. // otherwise from cwd
  54852. const jsconfigFile = path__default.resolve(configRoot, 'vite.config.js');
  54853. if (fs__default.existsSync(jsconfigFile)) {
  54854. resolvedPath = jsconfigFile;
  54855. }
  54856. if (!resolvedPath) {
  54857. const mjsconfigFile = path__default.resolve(configRoot, 'vite.config.mjs');
  54858. if (fs__default.existsSync(mjsconfigFile)) {
  54859. resolvedPath = mjsconfigFile;
  54860. isESM = true;
  54861. }
  54862. }
  54863. if (!resolvedPath) {
  54864. const tsconfigFile = path__default.resolve(configRoot, 'vite.config.ts');
  54865. if (fs__default.existsSync(tsconfigFile)) {
  54866. resolvedPath = tsconfigFile;
  54867. isTS = true;
  54868. }
  54869. }
  54870. if (!resolvedPath) {
  54871. const cjsConfigFile = path__default.resolve(configRoot, 'vite.config.cjs');
  54872. if (fs__default.existsSync(cjsConfigFile)) {
  54873. resolvedPath = cjsConfigFile;
  54874. isESM = false;
  54875. }
  54876. }
  54877. }
  54878. if (!resolvedPath) {
  54879. debug('no config file found.');
  54880. return null;
  54881. }
  54882. try {
  54883. let userConfig;
  54884. if (isESM) {
  54885. const bundled = await bundleConfigFile(resolvedPath, true);
  54886. dependencies = bundled.dependencies;
  54887. if (isTS) {
  54888. // before we can register loaders without requiring users to run node
  54889. // with --experimental-loader themselves, we have to do a hack here:
  54890. // bundle the config file w/ ts transforms first, write it to disk,
  54891. // load it with native Node ESM, then delete the file.
  54892. const fileBase = `${resolvedPath}.timestamp-${Date.now()}`;
  54893. const fileNameTmp = `${fileBase}.js`;
  54894. const fileUrl = `${require('url').pathToFileURL(fileBase)}.js`;
  54895. fs__default.writeFileSync(fileNameTmp, bundled.code);
  54896. userConfig = (await dynamicImport(fileUrl)).default;
  54897. fs__default.unlinkSync(fileNameTmp);
  54898. debug(`TS + native esm config loaded in ${getTime()}`, fileUrl);
  54899. }
  54900. else {
  54901. const fileUrl = require('url').pathToFileURL(resolvedPath);
  54902. // using Function to avoid this from being compiled away by TS/Rollup
  54903. // append a query so that we force reload fresh config in case of
  54904. // server restart
  54905. userConfig = (await dynamicImport(`${fileUrl}?t=${Date.now()}`)).default;
  54906. debug(`native esm config loaded in ${getTime()}`, fileUrl);
  54907. }
  54908. }
  54909. if (!userConfig) {
  54910. // Bundle config file and transpile it to cjs using esbuild.
  54911. const bundled = await bundleConfigFile(resolvedPath);
  54912. dependencies = bundled.dependencies;
  54913. userConfig = await loadConfigFromBundledFile(resolvedPath, bundled.code);
  54914. debug(`bundled config file loaded in ${getTime()}`);
  54915. }
  54916. const config = await (typeof userConfig === 'function'
  54917. ? userConfig(configEnv)
  54918. : userConfig);
  54919. if (!isObject$1(config)) {
  54920. throw new Error(`config must export or return an object.`);
  54921. }
  54922. return {
  54923. path: normalizePath$3(resolvedPath),
  54924. config,
  54925. dependencies
  54926. };
  54927. }
  54928. catch (e) {
  54929. createLogger(logLevel).error(colors$1.red(`failed to load config from ${resolvedPath}`), { error: e });
  54930. throw e;
  54931. }
  54932. }
  54933. async function bundleConfigFile(fileName, isESM = false) {
  54934. const result = await esbuild.build({
  54935. absWorkingDir: process.cwd(),
  54936. entryPoints: [fileName],
  54937. outfile: 'out.js',
  54938. write: false,
  54939. platform: 'node',
  54940. bundle: true,
  54941. format: isESM ? 'esm' : 'cjs',
  54942. sourcemap: 'inline',
  54943. metafile: true,
  54944. plugins: [
  54945. {
  54946. name: 'externalize-deps',
  54947. setup(build) {
  54948. build.onResolve({ filter: /.*/ }, (args) => {
  54949. const id = args.path;
  54950. if (id[0] !== '.' && !path__default.isAbsolute(id)) {
  54951. return {
  54952. external: true
  54953. };
  54954. }
  54955. });
  54956. }
  54957. },
  54958. {
  54959. name: 'replace-import-meta',
  54960. setup(build) {
  54961. build.onLoad({ filter: /\.[jt]s$/ }, async (args) => {
  54962. const contents = await fs__default.promises.readFile(args.path, 'utf8');
  54963. return {
  54964. loader: args.path.endsWith('.ts') ? 'ts' : 'js',
  54965. contents: contents
  54966. .replace(/\bimport\.meta\.url\b/g, JSON.stringify(require$$0$6.pathToFileURL(args.path).href))
  54967. .replace(/\b__dirname\b/g, JSON.stringify(path__default.dirname(args.path)))
  54968. .replace(/\b__filename\b/g, JSON.stringify(args.path))
  54969. };
  54970. });
  54971. }
  54972. }
  54973. ]
  54974. });
  54975. const { text } = result.outputFiles[0];
  54976. return {
  54977. code: text,
  54978. dependencies: result.metafile ? Object.keys(result.metafile.inputs) : []
  54979. };
  54980. }
  54981. async function loadConfigFromBundledFile(fileName, bundledCode) {
  54982. const extension = path__default.extname(fileName);
  54983. const defaultLoader = require.extensions[extension];
  54984. require.extensions[extension] = (module, filename) => {
  54985. if (filename === fileName) {
  54986. module._compile(bundledCode, filename);
  54987. }
  54988. else {
  54989. defaultLoader(module, filename);
  54990. }
  54991. };
  54992. // clear cache in case of server restart
  54993. delete require.cache[require.resolve(fileName)];
  54994. const raw = require(fileName);
  54995. const config = raw.__esModule ? raw.default : raw;
  54996. require.extensions[extension] = defaultLoader;
  54997. return config;
  54998. }
  54999. function loadEnv(mode, envDir, prefixes = 'VITE_') {
  55000. var _a;
  55001. if (mode === 'local') {
  55002. throw new Error(`"local" cannot be used as a mode name because it conflicts with ` +
  55003. `the .local postfix for .env files.`);
  55004. }
  55005. prefixes = arraify(prefixes);
  55006. const env = {};
  55007. const envFiles = [
  55008. /** mode local file */ `.env.${mode}.local`,
  55009. /** mode file */ `.env.${mode}`,
  55010. /** local file */ `.env.local`,
  55011. /** default file */ `.env`
  55012. ];
  55013. // check if there are actual env variables starting with VITE_*
  55014. // these are typically provided inline and should be prioritized
  55015. for (const key in process.env) {
  55016. if (prefixes.some((prefix) => key.startsWith(prefix)) &&
  55017. env[key] === undefined) {
  55018. env[key] = process.env[key];
  55019. }
  55020. }
  55021. for (const file of envFiles) {
  55022. const path = lookupFile(envDir, [file], { pathOnly: true, rootDir: envDir });
  55023. if (path) {
  55024. const parsed = dotenv.parse(fs__default.readFileSync(path), {
  55025. debug: ((_a = process.env.DEBUG) === null || _a === void 0 ? void 0 : _a.includes('vite:dotenv')) || undefined
  55026. });
  55027. // let environment variables use each other
  55028. main({
  55029. parsed,
  55030. // prevent process.env mutation
  55031. ignoreProcessEnv: true
  55032. });
  55033. // only keys that start with prefix are exposed to client
  55034. for (const [key, value] of Object.entries(parsed)) {
  55035. if (prefixes.some((prefix) => key.startsWith(prefix)) &&
  55036. env[key] === undefined) {
  55037. env[key] = value;
  55038. }
  55039. else if (key === 'NODE_ENV' &&
  55040. process.env.VITE_USER_NODE_ENV === undefined) {
  55041. // NODE_ENV override in .env file
  55042. process.env.VITE_USER_NODE_ENV = value;
  55043. }
  55044. }
  55045. }
  55046. }
  55047. return env;
  55048. }
  55049. function resolveEnvPrefix({ envPrefix = 'VITE_' }) {
  55050. envPrefix = arraify(envPrefix);
  55051. if (envPrefix.some((prefix) => prefix === '')) {
  55052. throw new Error(`envPrefix option contains value '', which could lead unexpected exposure of sensitive information.`);
  55053. }
  55054. return envPrefix;
  55055. }
  55056. exports.build = build;
  55057. exports.build$1 = build$1;
  55058. exports.colors = colors$1;
  55059. exports.commonjsGlobal = commonjsGlobal;
  55060. exports.createLogger = createLogger;
  55061. exports.createServer = createServer;
  55062. exports.defineConfig = defineConfig;
  55063. exports.formatPostcssSourceMap = formatPostcssSourceMap;
  55064. exports.getAugmentedNamespace = getAugmentedNamespace;
  55065. exports.getDefaultExportFromCjs = getDefaultExportFromCjs;
  55066. exports.index = index$1;
  55067. exports.index$1 = index;
  55068. exports.isCSSRequest = isCSSRequest;
  55069. exports.loadConfigFromFile = loadConfigFromFile;
  55070. exports.loadEnv = loadEnv;
  55071. exports.mergeConfig = mergeConfig;
  55072. exports.normalizePath = normalizePath$3;
  55073. exports.optimizeDeps = optimizeDeps;
  55074. exports.preview = preview;
  55075. exports.preview$1 = preview$1;
  55076. exports.printHttpServerUrls = printHttpServerUrls;
  55077. exports.resolveConfig = resolveConfig;
  55078. exports.resolveEnvPrefix = resolveEnvPrefix;
  55079. exports.resolvePackageData = resolvePackageData;
  55080. exports.resolvePackageEntry = resolvePackageEntry;
  55081. exports.searchForWorkspaceRoot = searchForWorkspaceRoot;
  55082. exports.send = send;
  55083. exports.sortUserPlugins = sortUserPlugins;
  55084. exports.transformWithEsbuild = transformWithEsbuild;