f35f383c0176ccf654843401697bd3b337e1c1072ec6254c8ef50bbff8219e4c1a62a16afe44aec30581a91e98b83a94182355af617769f364a3ce672d7eb7 1000 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273
  1. /*
  2. @license
  3. Rollup.js v3.29.4
  4. Sat, 21 Sep 2024 06:29:06 GMT - commit 2ef77c00ec2635d42697cff2c0567ccc8db34fb4
  5. https://github.com/rollup/rollup
  6. Released under the MIT License.
  7. */
  8. import { resolve, basename, extname, dirname, relative as relative$1 } from 'node:path';
  9. import require$$0$1, { win32, posix, isAbsolute as isAbsolute$1, resolve as resolve$1 } from 'path';
  10. import process$1, { env as env$1 } from 'node:process';
  11. import { performance } from 'node:perf_hooks';
  12. import { createHash as createHash$1 } from 'node:crypto';
  13. import { lstat, realpath, readdir, readFile, mkdir, writeFile } from 'node:fs/promises';
  14. import * as tty from 'tty';
  15. var version$1 = "3.29.4";
  16. const comma = ','.charCodeAt(0);
  17. const semicolon = ';'.charCodeAt(0);
  18. const chars$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  19. const intToChar = new Uint8Array(64); // 64 possible chars.
  20. const charToInt = new Uint8Array(128); // z is 122 in ASCII
  21. for (let i = 0; i < chars$1.length; i++) {
  22. const c = chars$1.charCodeAt(i);
  23. intToChar[i] = c;
  24. charToInt[c] = i;
  25. }
  26. // Provide a fallback for older environments.
  27. const td = typeof TextDecoder !== 'undefined'
  28. ? /* #__PURE__ */ new TextDecoder()
  29. : typeof Buffer !== 'undefined'
  30. ? {
  31. decode(buf) {
  32. const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
  33. return out.toString();
  34. },
  35. }
  36. : {
  37. decode(buf) {
  38. let out = '';
  39. for (let i = 0; i < buf.length; i++) {
  40. out += String.fromCharCode(buf[i]);
  41. }
  42. return out;
  43. },
  44. };
  45. function decode(mappings) {
  46. const state = new Int32Array(5);
  47. const decoded = [];
  48. let index = 0;
  49. do {
  50. const semi = indexOf(mappings, index);
  51. const line = [];
  52. let sorted = true;
  53. let lastCol = 0;
  54. state[0] = 0;
  55. for (let i = index; i < semi; i++) {
  56. let seg;
  57. i = decodeInteger(mappings, i, state, 0); // genColumn
  58. const col = state[0];
  59. if (col < lastCol)
  60. sorted = false;
  61. lastCol = col;
  62. if (hasMoreVlq(mappings, i, semi)) {
  63. i = decodeInteger(mappings, i, state, 1); // sourcesIndex
  64. i = decodeInteger(mappings, i, state, 2); // sourceLine
  65. i = decodeInteger(mappings, i, state, 3); // sourceColumn
  66. if (hasMoreVlq(mappings, i, semi)) {
  67. i = decodeInteger(mappings, i, state, 4); // namesIndex
  68. seg = [col, state[1], state[2], state[3], state[4]];
  69. }
  70. else {
  71. seg = [col, state[1], state[2], state[3]];
  72. }
  73. }
  74. else {
  75. seg = [col];
  76. }
  77. line.push(seg);
  78. }
  79. if (!sorted)
  80. sort(line);
  81. decoded.push(line);
  82. index = semi + 1;
  83. } while (index <= mappings.length);
  84. return decoded;
  85. }
  86. function indexOf(mappings, index) {
  87. const idx = mappings.indexOf(';', index);
  88. return idx === -1 ? mappings.length : idx;
  89. }
  90. function decodeInteger(mappings, pos, state, j) {
  91. let value = 0;
  92. let shift = 0;
  93. let integer = 0;
  94. do {
  95. const c = mappings.charCodeAt(pos++);
  96. integer = charToInt[c];
  97. value |= (integer & 31) << shift;
  98. shift += 5;
  99. } while (integer & 32);
  100. const shouldNegate = value & 1;
  101. value >>>= 1;
  102. if (shouldNegate) {
  103. value = -0x80000000 | -value;
  104. }
  105. state[j] += value;
  106. return pos;
  107. }
  108. function hasMoreVlq(mappings, i, length) {
  109. if (i >= length)
  110. return false;
  111. return mappings.charCodeAt(i) !== comma;
  112. }
  113. function sort(line) {
  114. line.sort(sortComparator);
  115. }
  116. function sortComparator(a, b) {
  117. return a[0] - b[0];
  118. }
  119. function encode(decoded) {
  120. const state = new Int32Array(5);
  121. const bufLength = 1024 * 16;
  122. const subLength = bufLength - 36;
  123. const buf = new Uint8Array(bufLength);
  124. const sub = buf.subarray(0, subLength);
  125. let pos = 0;
  126. let out = '';
  127. for (let i = 0; i < decoded.length; i++) {
  128. const line = decoded[i];
  129. if (i > 0) {
  130. if (pos === bufLength) {
  131. out += td.decode(buf);
  132. pos = 0;
  133. }
  134. buf[pos++] = semicolon;
  135. }
  136. if (line.length === 0)
  137. continue;
  138. state[0] = 0;
  139. for (let j = 0; j < line.length; j++) {
  140. const segment = line[j];
  141. // We can push up to 5 ints, each int can take at most 7 chars, and we
  142. // may push a comma.
  143. if (pos > subLength) {
  144. out += td.decode(sub);
  145. buf.copyWithin(0, subLength, pos);
  146. pos -= subLength;
  147. }
  148. if (j > 0)
  149. buf[pos++] = comma;
  150. pos = encodeInteger(buf, pos, state, segment, 0); // genColumn
  151. if (segment.length === 1)
  152. continue;
  153. pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex
  154. pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine
  155. pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn
  156. if (segment.length === 4)
  157. continue;
  158. pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex
  159. }
  160. }
  161. return out + td.decode(buf.subarray(0, pos));
  162. }
  163. function encodeInteger(buf, pos, state, segment, j) {
  164. const next = segment[j];
  165. let num = next - state[j];
  166. state[j] = next;
  167. num = num < 0 ? (-num << 1) | 1 : num << 1;
  168. do {
  169. let clamped = num & 0b011111;
  170. num >>>= 5;
  171. if (num > 0)
  172. clamped |= 0b100000;
  173. buf[pos++] = intToChar[clamped];
  174. } while (num > 0);
  175. return pos;
  176. }
  177. class BitSet {
  178. constructor(arg) {
  179. this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
  180. }
  181. add(n) {
  182. this.bits[n >> 5] |= 1 << (n & 31);
  183. }
  184. has(n) {
  185. return !!(this.bits[n >> 5] & (1 << (n & 31)));
  186. }
  187. }
  188. let Chunk$1 = class Chunk {
  189. constructor(start, end, content) {
  190. this.start = start;
  191. this.end = end;
  192. this.original = content;
  193. this.intro = '';
  194. this.outro = '';
  195. this.content = content;
  196. this.storeName = false;
  197. this.edited = false;
  198. {
  199. this.previous = null;
  200. this.next = null;
  201. }
  202. }
  203. appendLeft(content) {
  204. this.outro += content;
  205. }
  206. appendRight(content) {
  207. this.intro = this.intro + content;
  208. }
  209. clone() {
  210. const chunk = new Chunk(this.start, this.end, this.original);
  211. chunk.intro = this.intro;
  212. chunk.outro = this.outro;
  213. chunk.content = this.content;
  214. chunk.storeName = this.storeName;
  215. chunk.edited = this.edited;
  216. return chunk;
  217. }
  218. contains(index) {
  219. return this.start < index && index < this.end;
  220. }
  221. eachNext(fn) {
  222. let chunk = this;
  223. while (chunk) {
  224. fn(chunk);
  225. chunk = chunk.next;
  226. }
  227. }
  228. eachPrevious(fn) {
  229. let chunk = this;
  230. while (chunk) {
  231. fn(chunk);
  232. chunk = chunk.previous;
  233. }
  234. }
  235. edit(content, storeName, contentOnly) {
  236. this.content = content;
  237. if (!contentOnly) {
  238. this.intro = '';
  239. this.outro = '';
  240. }
  241. this.storeName = storeName;
  242. this.edited = true;
  243. return this;
  244. }
  245. prependLeft(content) {
  246. this.outro = content + this.outro;
  247. }
  248. prependRight(content) {
  249. this.intro = content + this.intro;
  250. }
  251. split(index) {
  252. const sliceIndex = index - this.start;
  253. const originalBefore = this.original.slice(0, sliceIndex);
  254. const originalAfter = this.original.slice(sliceIndex);
  255. this.original = originalBefore;
  256. const newChunk = new Chunk(index, this.end, originalAfter);
  257. newChunk.outro = this.outro;
  258. this.outro = '';
  259. this.end = index;
  260. if (this.edited) {
  261. // after split we should save the edit content record into the correct chunk
  262. // to make sure sourcemap correct
  263. // For example:
  264. // ' test'.trim()
  265. // split -> ' ' + 'test'
  266. // ✔️ edit -> '' + 'test'
  267. // ✖️ edit -> 'test' + ''
  268. // TODO is this block necessary?...
  269. newChunk.edit('', false);
  270. this.content = '';
  271. } else {
  272. this.content = originalBefore;
  273. }
  274. newChunk.next = this.next;
  275. if (newChunk.next) newChunk.next.previous = newChunk;
  276. newChunk.previous = this;
  277. this.next = newChunk;
  278. return newChunk;
  279. }
  280. toString() {
  281. return this.intro + this.content + this.outro;
  282. }
  283. trimEnd(rx) {
  284. this.outro = this.outro.replace(rx, '');
  285. if (this.outro.length) return true;
  286. const trimmed = this.content.replace(rx, '');
  287. if (trimmed.length) {
  288. if (trimmed !== this.content) {
  289. this.split(this.start + trimmed.length).edit('', undefined, true);
  290. if (this.edited) {
  291. // save the change, if it has been edited
  292. this.edit(trimmed, this.storeName, true);
  293. }
  294. }
  295. return true;
  296. } else {
  297. this.edit('', undefined, true);
  298. this.intro = this.intro.replace(rx, '');
  299. if (this.intro.length) return true;
  300. }
  301. }
  302. trimStart(rx) {
  303. this.intro = this.intro.replace(rx, '');
  304. if (this.intro.length) return true;
  305. const trimmed = this.content.replace(rx, '');
  306. if (trimmed.length) {
  307. if (trimmed !== this.content) {
  308. const newChunk = this.split(this.end - trimmed.length);
  309. if (this.edited) {
  310. // save the change, if it has been edited
  311. newChunk.edit(trimmed, this.storeName, true);
  312. }
  313. this.edit('', undefined, true);
  314. }
  315. return true;
  316. } else {
  317. this.edit('', undefined, true);
  318. this.outro = this.outro.replace(rx, '');
  319. if (this.outro.length) return true;
  320. }
  321. }
  322. };
  323. function getBtoa() {
  324. if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
  325. return (str) => window.btoa(unescape(encodeURIComponent(str)));
  326. } else if (typeof Buffer === 'function') {
  327. return (str) => Buffer.from(str, 'utf-8').toString('base64');
  328. } else {
  329. return () => {
  330. throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
  331. };
  332. }
  333. }
  334. const btoa = /*#__PURE__*/ getBtoa();
  335. class SourceMap {
  336. constructor(properties) {
  337. this.version = 3;
  338. this.file = properties.file;
  339. this.sources = properties.sources;
  340. this.sourcesContent = properties.sourcesContent;
  341. this.names = properties.names;
  342. this.mappings = encode(properties.mappings);
  343. if (typeof properties.x_google_ignoreList !== 'undefined') {
  344. this.x_google_ignoreList = properties.x_google_ignoreList;
  345. }
  346. }
  347. toString() {
  348. return JSON.stringify(this);
  349. }
  350. toUrl() {
  351. return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
  352. }
  353. }
  354. function guessIndent(code) {
  355. const lines = code.split('\n');
  356. const tabbed = lines.filter((line) => /^\t+/.test(line));
  357. const spaced = lines.filter((line) => /^ {2,}/.test(line));
  358. if (tabbed.length === 0 && spaced.length === 0) {
  359. return null;
  360. }
  361. // More lines tabbed than spaced? Assume tabs, and
  362. // default to tabs in the case of a tie (or nothing
  363. // to go on)
  364. if (tabbed.length >= spaced.length) {
  365. return '\t';
  366. }
  367. // Otherwise, we need to guess the multiple
  368. const min = spaced.reduce((previous, current) => {
  369. const numSpaces = /^ +/.exec(current)[0].length;
  370. return Math.min(numSpaces, previous);
  371. }, Infinity);
  372. return new Array(min + 1).join(' ');
  373. }
  374. function getRelativePath(from, to) {
  375. const fromParts = from.split(/[/\\]/);
  376. const toParts = to.split(/[/\\]/);
  377. fromParts.pop(); // get dirname
  378. while (fromParts[0] === toParts[0]) {
  379. fromParts.shift();
  380. toParts.shift();
  381. }
  382. if (fromParts.length) {
  383. let i = fromParts.length;
  384. while (i--) fromParts[i] = '..';
  385. }
  386. return fromParts.concat(toParts).join('/');
  387. }
  388. const toString$1 = Object.prototype.toString;
  389. function isObject$1(thing) {
  390. return toString$1.call(thing) === '[object Object]';
  391. }
  392. function getLocator$1(source) {
  393. const originalLines = source.split('\n');
  394. const lineOffsets = [];
  395. for (let i = 0, pos = 0; i < originalLines.length; i++) {
  396. lineOffsets.push(pos);
  397. pos += originalLines[i].length + 1;
  398. }
  399. return function locate(index) {
  400. let i = 0;
  401. let j = lineOffsets.length;
  402. while (i < j) {
  403. const m = (i + j) >> 1;
  404. if (index < lineOffsets[m]) {
  405. j = m;
  406. } else {
  407. i = m + 1;
  408. }
  409. }
  410. const line = i - 1;
  411. const column = index - lineOffsets[line];
  412. return { line, column };
  413. };
  414. }
  415. const wordRegex = /\w/;
  416. class Mappings {
  417. constructor(hires) {
  418. this.hires = hires;
  419. this.generatedCodeLine = 0;
  420. this.generatedCodeColumn = 0;
  421. this.raw = [];
  422. this.rawSegments = this.raw[this.generatedCodeLine] = [];
  423. this.pending = null;
  424. }
  425. addEdit(sourceIndex, content, loc, nameIndex) {
  426. if (content.length) {
  427. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  428. if (nameIndex >= 0) {
  429. segment.push(nameIndex);
  430. }
  431. this.rawSegments.push(segment);
  432. } else if (this.pending) {
  433. this.rawSegments.push(this.pending);
  434. }
  435. this.advance(content);
  436. this.pending = null;
  437. }
  438. addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
  439. let originalCharIndex = chunk.start;
  440. let first = true;
  441. // when iterating each char, check if it's in a word boundary
  442. let charInHiresBoundary = false;
  443. while (originalCharIndex < chunk.end) {
  444. if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
  445. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  446. if (this.hires === 'boundary') {
  447. // in hires "boundary", group segments per word boundary than per char
  448. if (wordRegex.test(original[originalCharIndex])) {
  449. // for first char in the boundary found, start the boundary by pushing a segment
  450. if (!charInHiresBoundary) {
  451. this.rawSegments.push(segment);
  452. charInHiresBoundary = true;
  453. }
  454. } else {
  455. // for non-word char, end the boundary by pushing a segment
  456. this.rawSegments.push(segment);
  457. charInHiresBoundary = false;
  458. }
  459. } else {
  460. this.rawSegments.push(segment);
  461. }
  462. }
  463. if (original[originalCharIndex] === '\n') {
  464. loc.line += 1;
  465. loc.column = 0;
  466. this.generatedCodeLine += 1;
  467. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  468. this.generatedCodeColumn = 0;
  469. first = true;
  470. } else {
  471. loc.column += 1;
  472. this.generatedCodeColumn += 1;
  473. first = false;
  474. }
  475. originalCharIndex += 1;
  476. }
  477. this.pending = null;
  478. }
  479. advance(str) {
  480. if (!str) return;
  481. const lines = str.split('\n');
  482. if (lines.length > 1) {
  483. for (let i = 0; i < lines.length - 1; i++) {
  484. this.generatedCodeLine++;
  485. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  486. }
  487. this.generatedCodeColumn = 0;
  488. }
  489. this.generatedCodeColumn += lines[lines.length - 1].length;
  490. }
  491. }
  492. const n = '\n';
  493. const warned = {
  494. insertLeft: false,
  495. insertRight: false,
  496. storeName: false,
  497. };
  498. class MagicString {
  499. constructor(string, options = {}) {
  500. const chunk = new Chunk$1(0, string.length, string);
  501. Object.defineProperties(this, {
  502. original: { writable: true, value: string },
  503. outro: { writable: true, value: '' },
  504. intro: { writable: true, value: '' },
  505. firstChunk: { writable: true, value: chunk },
  506. lastChunk: { writable: true, value: chunk },
  507. lastSearchedChunk: { writable: true, value: chunk },
  508. byStart: { writable: true, value: {} },
  509. byEnd: { writable: true, value: {} },
  510. filename: { writable: true, value: options.filename },
  511. indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
  512. sourcemapLocations: { writable: true, value: new BitSet() },
  513. storedNames: { writable: true, value: {} },
  514. indentStr: { writable: true, value: undefined },
  515. ignoreList: { writable: true, value: options.ignoreList },
  516. });
  517. this.byStart[0] = chunk;
  518. this.byEnd[string.length] = chunk;
  519. }
  520. addSourcemapLocation(char) {
  521. this.sourcemapLocations.add(char);
  522. }
  523. append(content) {
  524. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  525. this.outro += content;
  526. return this;
  527. }
  528. appendLeft(index, content) {
  529. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  530. this._split(index);
  531. const chunk = this.byEnd[index];
  532. if (chunk) {
  533. chunk.appendLeft(content);
  534. } else {
  535. this.intro += content;
  536. }
  537. return this;
  538. }
  539. appendRight(index, content) {
  540. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  541. this._split(index);
  542. const chunk = this.byStart[index];
  543. if (chunk) {
  544. chunk.appendRight(content);
  545. } else {
  546. this.outro += content;
  547. }
  548. return this;
  549. }
  550. clone() {
  551. const cloned = new MagicString(this.original, { filename: this.filename });
  552. let originalChunk = this.firstChunk;
  553. let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
  554. while (originalChunk) {
  555. cloned.byStart[clonedChunk.start] = clonedChunk;
  556. cloned.byEnd[clonedChunk.end] = clonedChunk;
  557. const nextOriginalChunk = originalChunk.next;
  558. const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
  559. if (nextClonedChunk) {
  560. clonedChunk.next = nextClonedChunk;
  561. nextClonedChunk.previous = clonedChunk;
  562. clonedChunk = nextClonedChunk;
  563. }
  564. originalChunk = nextOriginalChunk;
  565. }
  566. cloned.lastChunk = clonedChunk;
  567. if (this.indentExclusionRanges) {
  568. cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
  569. }
  570. cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
  571. cloned.intro = this.intro;
  572. cloned.outro = this.outro;
  573. return cloned;
  574. }
  575. generateDecodedMap(options) {
  576. options = options || {};
  577. const sourceIndex = 0;
  578. const names = Object.keys(this.storedNames);
  579. const mappings = new Mappings(options.hires);
  580. const locate = getLocator$1(this.original);
  581. if (this.intro) {
  582. mappings.advance(this.intro);
  583. }
  584. this.firstChunk.eachNext((chunk) => {
  585. const loc = locate(chunk.start);
  586. if (chunk.intro.length) mappings.advance(chunk.intro);
  587. if (chunk.edited) {
  588. mappings.addEdit(
  589. sourceIndex,
  590. chunk.content,
  591. loc,
  592. chunk.storeName ? names.indexOf(chunk.original) : -1,
  593. );
  594. } else {
  595. mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
  596. }
  597. if (chunk.outro.length) mappings.advance(chunk.outro);
  598. });
  599. return {
  600. file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
  601. sources: [
  602. options.source ? getRelativePath(options.file || '', options.source) : options.file || '',
  603. ],
  604. sourcesContent: options.includeContent ? [this.original] : undefined,
  605. names,
  606. mappings: mappings.raw,
  607. x_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined,
  608. };
  609. }
  610. generateMap(options) {
  611. return new SourceMap(this.generateDecodedMap(options));
  612. }
  613. _ensureindentStr() {
  614. if (this.indentStr === undefined) {
  615. this.indentStr = guessIndent(this.original);
  616. }
  617. }
  618. _getRawIndentString() {
  619. this._ensureindentStr();
  620. return this.indentStr;
  621. }
  622. getIndentString() {
  623. this._ensureindentStr();
  624. return this.indentStr === null ? '\t' : this.indentStr;
  625. }
  626. indent(indentStr, options) {
  627. const pattern = /^[^\r\n]/gm;
  628. if (isObject$1(indentStr)) {
  629. options = indentStr;
  630. indentStr = undefined;
  631. }
  632. if (indentStr === undefined) {
  633. this._ensureindentStr();
  634. indentStr = this.indentStr || '\t';
  635. }
  636. if (indentStr === '') return this; // noop
  637. options = options || {};
  638. // Process exclusion ranges
  639. const isExcluded = {};
  640. if (options.exclude) {
  641. const exclusions =
  642. typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
  643. exclusions.forEach((exclusion) => {
  644. for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
  645. isExcluded[i] = true;
  646. }
  647. });
  648. }
  649. let shouldIndentNextCharacter = options.indentStart !== false;
  650. const replacer = (match) => {
  651. if (shouldIndentNextCharacter) return `${indentStr}${match}`;
  652. shouldIndentNextCharacter = true;
  653. return match;
  654. };
  655. this.intro = this.intro.replace(pattern, replacer);
  656. let charIndex = 0;
  657. let chunk = this.firstChunk;
  658. while (chunk) {
  659. const end = chunk.end;
  660. if (chunk.edited) {
  661. if (!isExcluded[charIndex]) {
  662. chunk.content = chunk.content.replace(pattern, replacer);
  663. if (chunk.content.length) {
  664. shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
  665. }
  666. }
  667. } else {
  668. charIndex = chunk.start;
  669. while (charIndex < end) {
  670. if (!isExcluded[charIndex]) {
  671. const char = this.original[charIndex];
  672. if (char === '\n') {
  673. shouldIndentNextCharacter = true;
  674. } else if (char !== '\r' && shouldIndentNextCharacter) {
  675. shouldIndentNextCharacter = false;
  676. if (charIndex === chunk.start) {
  677. chunk.prependRight(indentStr);
  678. } else {
  679. this._splitChunk(chunk, charIndex);
  680. chunk = chunk.next;
  681. chunk.prependRight(indentStr);
  682. }
  683. }
  684. }
  685. charIndex += 1;
  686. }
  687. }
  688. charIndex = chunk.end;
  689. chunk = chunk.next;
  690. }
  691. this.outro = this.outro.replace(pattern, replacer);
  692. return this;
  693. }
  694. insert() {
  695. throw new Error(
  696. 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)',
  697. );
  698. }
  699. insertLeft(index, content) {
  700. if (!warned.insertLeft) {
  701. console.warn(
  702. 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead',
  703. ); // eslint-disable-line no-console
  704. warned.insertLeft = true;
  705. }
  706. return this.appendLeft(index, content);
  707. }
  708. insertRight(index, content) {
  709. if (!warned.insertRight) {
  710. console.warn(
  711. 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead',
  712. ); // eslint-disable-line no-console
  713. warned.insertRight = true;
  714. }
  715. return this.prependRight(index, content);
  716. }
  717. move(start, end, index) {
  718. if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself');
  719. this._split(start);
  720. this._split(end);
  721. this._split(index);
  722. const first = this.byStart[start];
  723. const last = this.byEnd[end];
  724. const oldLeft = first.previous;
  725. const oldRight = last.next;
  726. const newRight = this.byStart[index];
  727. if (!newRight && last === this.lastChunk) return this;
  728. const newLeft = newRight ? newRight.previous : this.lastChunk;
  729. if (oldLeft) oldLeft.next = oldRight;
  730. if (oldRight) oldRight.previous = oldLeft;
  731. if (newLeft) newLeft.next = first;
  732. if (newRight) newRight.previous = last;
  733. if (!first.previous) this.firstChunk = last.next;
  734. if (!last.next) {
  735. this.lastChunk = first.previous;
  736. this.lastChunk.next = null;
  737. }
  738. first.previous = newLeft;
  739. last.next = newRight || null;
  740. if (!newLeft) this.firstChunk = first;
  741. if (!newRight) this.lastChunk = last;
  742. return this;
  743. }
  744. overwrite(start, end, content, options) {
  745. options = options || {};
  746. return this.update(start, end, content, { ...options, overwrite: !options.contentOnly });
  747. }
  748. update(start, end, content, options) {
  749. if (typeof content !== 'string') throw new TypeError('replacement content must be a string');
  750. while (start < 0) start += this.original.length;
  751. while (end < 0) end += this.original.length;
  752. if (end > this.original.length) throw new Error('end is out of bounds');
  753. if (start === end)
  754. throw new Error(
  755. 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead',
  756. );
  757. this._split(start);
  758. this._split(end);
  759. if (options === true) {
  760. if (!warned.storeName) {
  761. console.warn(
  762. 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string',
  763. ); // eslint-disable-line no-console
  764. warned.storeName = true;
  765. }
  766. options = { storeName: true };
  767. }
  768. const storeName = options !== undefined ? options.storeName : false;
  769. const overwrite = options !== undefined ? options.overwrite : false;
  770. if (storeName) {
  771. const original = this.original.slice(start, end);
  772. Object.defineProperty(this.storedNames, original, {
  773. writable: true,
  774. value: true,
  775. enumerable: true,
  776. });
  777. }
  778. const first = this.byStart[start];
  779. const last = this.byEnd[end];
  780. if (first) {
  781. let chunk = first;
  782. while (chunk !== last) {
  783. if (chunk.next !== this.byStart[chunk.end]) {
  784. throw new Error('Cannot overwrite across a split point');
  785. }
  786. chunk = chunk.next;
  787. chunk.edit('', false);
  788. }
  789. first.edit(content, storeName, !overwrite);
  790. } else {
  791. // must be inserting at the end
  792. const newChunk = new Chunk$1(start, end, '').edit(content, storeName);
  793. // TODO last chunk in the array may not be the last chunk, if it's moved...
  794. last.next = newChunk;
  795. newChunk.previous = last;
  796. }
  797. return this;
  798. }
  799. prepend(content) {
  800. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  801. this.intro = content + this.intro;
  802. return this;
  803. }
  804. prependLeft(index, content) {
  805. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  806. this._split(index);
  807. const chunk = this.byEnd[index];
  808. if (chunk) {
  809. chunk.prependLeft(content);
  810. } else {
  811. this.intro = content + this.intro;
  812. }
  813. return this;
  814. }
  815. prependRight(index, content) {
  816. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  817. this._split(index);
  818. const chunk = this.byStart[index];
  819. if (chunk) {
  820. chunk.prependRight(content);
  821. } else {
  822. this.outro = content + this.outro;
  823. }
  824. return this;
  825. }
  826. remove(start, end) {
  827. while (start < 0) start += this.original.length;
  828. while (end < 0) end += this.original.length;
  829. if (start === end) return this;
  830. if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
  831. if (start > end) throw new Error('end must be greater than start');
  832. this._split(start);
  833. this._split(end);
  834. let chunk = this.byStart[start];
  835. while (chunk) {
  836. chunk.intro = '';
  837. chunk.outro = '';
  838. chunk.edit('');
  839. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  840. }
  841. return this;
  842. }
  843. lastChar() {
  844. if (this.outro.length) return this.outro[this.outro.length - 1];
  845. let chunk = this.lastChunk;
  846. do {
  847. if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
  848. if (chunk.content.length) return chunk.content[chunk.content.length - 1];
  849. if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
  850. } while ((chunk = chunk.previous));
  851. if (this.intro.length) return this.intro[this.intro.length - 1];
  852. return '';
  853. }
  854. lastLine() {
  855. let lineIndex = this.outro.lastIndexOf(n);
  856. if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
  857. let lineStr = this.outro;
  858. let chunk = this.lastChunk;
  859. do {
  860. if (chunk.outro.length > 0) {
  861. lineIndex = chunk.outro.lastIndexOf(n);
  862. if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
  863. lineStr = chunk.outro + lineStr;
  864. }
  865. if (chunk.content.length > 0) {
  866. lineIndex = chunk.content.lastIndexOf(n);
  867. if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
  868. lineStr = chunk.content + lineStr;
  869. }
  870. if (chunk.intro.length > 0) {
  871. lineIndex = chunk.intro.lastIndexOf(n);
  872. if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
  873. lineStr = chunk.intro + lineStr;
  874. }
  875. } while ((chunk = chunk.previous));
  876. lineIndex = this.intro.lastIndexOf(n);
  877. if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
  878. return this.intro + lineStr;
  879. }
  880. slice(start = 0, end = this.original.length) {
  881. while (start < 0) start += this.original.length;
  882. while (end < 0) end += this.original.length;
  883. let result = '';
  884. // find start chunk
  885. let chunk = this.firstChunk;
  886. while (chunk && (chunk.start > start || chunk.end <= start)) {
  887. // found end chunk before start
  888. if (chunk.start < end && chunk.end >= end) {
  889. return result;
  890. }
  891. chunk = chunk.next;
  892. }
  893. if (chunk && chunk.edited && chunk.start !== start)
  894. throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
  895. const startChunk = chunk;
  896. while (chunk) {
  897. if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
  898. result += chunk.intro;
  899. }
  900. const containsEnd = chunk.start < end && chunk.end >= end;
  901. if (containsEnd && chunk.edited && chunk.end !== end)
  902. throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
  903. const sliceStart = startChunk === chunk ? start - chunk.start : 0;
  904. const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
  905. result += chunk.content.slice(sliceStart, sliceEnd);
  906. if (chunk.outro && (!containsEnd || chunk.end === end)) {
  907. result += chunk.outro;
  908. }
  909. if (containsEnd) {
  910. break;
  911. }
  912. chunk = chunk.next;
  913. }
  914. return result;
  915. }
  916. // TODO deprecate this? not really very useful
  917. snip(start, end) {
  918. const clone = this.clone();
  919. clone.remove(0, start);
  920. clone.remove(end, clone.original.length);
  921. return clone;
  922. }
  923. _split(index) {
  924. if (this.byStart[index] || this.byEnd[index]) return;
  925. let chunk = this.lastSearchedChunk;
  926. const searchForward = index > chunk.end;
  927. while (chunk) {
  928. if (chunk.contains(index)) return this._splitChunk(chunk, index);
  929. chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
  930. }
  931. }
  932. _splitChunk(chunk, index) {
  933. if (chunk.edited && chunk.content.length) {
  934. // zero-length edited chunks are a special case (overlapping replacements)
  935. const loc = getLocator$1(this.original)(index);
  936. throw new Error(
  937. `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`,
  938. );
  939. }
  940. const newChunk = chunk.split(index);
  941. this.byEnd[index] = chunk;
  942. this.byStart[index] = newChunk;
  943. this.byEnd[newChunk.end] = newChunk;
  944. if (chunk === this.lastChunk) this.lastChunk = newChunk;
  945. this.lastSearchedChunk = chunk;
  946. return true;
  947. }
  948. toString() {
  949. let str = this.intro;
  950. let chunk = this.firstChunk;
  951. while (chunk) {
  952. str += chunk.toString();
  953. chunk = chunk.next;
  954. }
  955. return str + this.outro;
  956. }
  957. isEmpty() {
  958. let chunk = this.firstChunk;
  959. do {
  960. if (
  961. (chunk.intro.length && chunk.intro.trim()) ||
  962. (chunk.content.length && chunk.content.trim()) ||
  963. (chunk.outro.length && chunk.outro.trim())
  964. )
  965. return false;
  966. } while ((chunk = chunk.next));
  967. return true;
  968. }
  969. length() {
  970. let chunk = this.firstChunk;
  971. let length = 0;
  972. do {
  973. length += chunk.intro.length + chunk.content.length + chunk.outro.length;
  974. } while ((chunk = chunk.next));
  975. return length;
  976. }
  977. trimLines() {
  978. return this.trim('[\\r\\n]');
  979. }
  980. trim(charType) {
  981. return this.trimStart(charType).trimEnd(charType);
  982. }
  983. trimEndAborted(charType) {
  984. const rx = new RegExp((charType || '\\s') + '+$');
  985. this.outro = this.outro.replace(rx, '');
  986. if (this.outro.length) return true;
  987. let chunk = this.lastChunk;
  988. do {
  989. const end = chunk.end;
  990. const aborted = chunk.trimEnd(rx);
  991. // if chunk was trimmed, we have a new lastChunk
  992. if (chunk.end !== end) {
  993. if (this.lastChunk === chunk) {
  994. this.lastChunk = chunk.next;
  995. }
  996. this.byEnd[chunk.end] = chunk;
  997. this.byStart[chunk.next.start] = chunk.next;
  998. this.byEnd[chunk.next.end] = chunk.next;
  999. }
  1000. if (aborted) return true;
  1001. chunk = chunk.previous;
  1002. } while (chunk);
  1003. return false;
  1004. }
  1005. trimEnd(charType) {
  1006. this.trimEndAborted(charType);
  1007. return this;
  1008. }
  1009. trimStartAborted(charType) {
  1010. const rx = new RegExp('^' + (charType || '\\s') + '+');
  1011. this.intro = this.intro.replace(rx, '');
  1012. if (this.intro.length) return true;
  1013. let chunk = this.firstChunk;
  1014. do {
  1015. const end = chunk.end;
  1016. const aborted = chunk.trimStart(rx);
  1017. if (chunk.end !== end) {
  1018. // special case...
  1019. if (chunk === this.lastChunk) this.lastChunk = chunk.next;
  1020. this.byEnd[chunk.end] = chunk;
  1021. this.byStart[chunk.next.start] = chunk.next;
  1022. this.byEnd[chunk.next.end] = chunk.next;
  1023. }
  1024. if (aborted) return true;
  1025. chunk = chunk.next;
  1026. } while (chunk);
  1027. return false;
  1028. }
  1029. trimStart(charType) {
  1030. this.trimStartAborted(charType);
  1031. return this;
  1032. }
  1033. hasChanged() {
  1034. return this.original !== this.toString();
  1035. }
  1036. _replaceRegexp(searchValue, replacement) {
  1037. function getReplacement(match, str) {
  1038. if (typeof replacement === 'string') {
  1039. return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
  1040. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
  1041. if (i === '$') return '$';
  1042. if (i === '&') return match[0];
  1043. const num = +i;
  1044. if (num < match.length) return match[+i];
  1045. return `$${i}`;
  1046. });
  1047. } else {
  1048. return replacement(...match, match.index, str, match.groups);
  1049. }
  1050. }
  1051. function matchAll(re, str) {
  1052. let match;
  1053. const matches = [];
  1054. while ((match = re.exec(str))) {
  1055. matches.push(match);
  1056. }
  1057. return matches;
  1058. }
  1059. if (searchValue.global) {
  1060. const matches = matchAll(searchValue, this.original);
  1061. matches.forEach((match) => {
  1062. if (match.index != null)
  1063. this.overwrite(
  1064. match.index,
  1065. match.index + match[0].length,
  1066. getReplacement(match, this.original),
  1067. );
  1068. });
  1069. } else {
  1070. const match = this.original.match(searchValue);
  1071. if (match && match.index != null)
  1072. this.overwrite(
  1073. match.index,
  1074. match.index + match[0].length,
  1075. getReplacement(match, this.original),
  1076. );
  1077. }
  1078. return this;
  1079. }
  1080. _replaceString(string, replacement) {
  1081. const { original } = this;
  1082. const index = original.indexOf(string);
  1083. if (index !== -1) {
  1084. this.overwrite(index, index + string.length, replacement);
  1085. }
  1086. return this;
  1087. }
  1088. replace(searchValue, replacement) {
  1089. if (typeof searchValue === 'string') {
  1090. return this._replaceString(searchValue, replacement);
  1091. }
  1092. return this._replaceRegexp(searchValue, replacement);
  1093. }
  1094. _replaceAllString(string, replacement) {
  1095. const { original } = this;
  1096. const stringLength = string.length;
  1097. for (
  1098. let index = original.indexOf(string);
  1099. index !== -1;
  1100. index = original.indexOf(string, index + stringLength)
  1101. ) {
  1102. this.overwrite(index, index + stringLength, replacement);
  1103. }
  1104. return this;
  1105. }
  1106. replaceAll(searchValue, replacement) {
  1107. if (typeof searchValue === 'string') {
  1108. return this._replaceAllString(searchValue, replacement);
  1109. }
  1110. if (!searchValue.global) {
  1111. throw new TypeError(
  1112. 'MagicString.prototype.replaceAll called with a non-global RegExp argument',
  1113. );
  1114. }
  1115. return this._replaceRegexp(searchValue, replacement);
  1116. }
  1117. }
  1118. const hasOwnProp = Object.prototype.hasOwnProperty;
  1119. let Bundle$1 = class Bundle {
  1120. constructor(options = {}) {
  1121. this.intro = options.intro || '';
  1122. this.separator = options.separator !== undefined ? options.separator : '\n';
  1123. this.sources = [];
  1124. this.uniqueSources = [];
  1125. this.uniqueSourceIndexByFilename = {};
  1126. }
  1127. addSource(source) {
  1128. if (source instanceof MagicString) {
  1129. return this.addSource({
  1130. content: source,
  1131. filename: source.filename,
  1132. separator: this.separator,
  1133. });
  1134. }
  1135. if (!isObject$1(source) || !source.content) {
  1136. throw new Error(
  1137. 'bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`',
  1138. );
  1139. }
  1140. ['filename', 'ignoreList', 'indentExclusionRanges', 'separator'].forEach((option) => {
  1141. if (!hasOwnProp.call(source, option)) source[option] = source.content[option];
  1142. });
  1143. if (source.separator === undefined) {
  1144. // TODO there's a bunch of this sort of thing, needs cleaning up
  1145. source.separator = this.separator;
  1146. }
  1147. if (source.filename) {
  1148. if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {
  1149. this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;
  1150. this.uniqueSources.push({ filename: source.filename, content: source.content.original });
  1151. } else {
  1152. const uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];
  1153. if (source.content.original !== uniqueSource.content) {
  1154. throw new Error(`Illegal source: same filename (${source.filename}), different contents`);
  1155. }
  1156. }
  1157. }
  1158. this.sources.push(source);
  1159. return this;
  1160. }
  1161. append(str, options) {
  1162. this.addSource({
  1163. content: new MagicString(str),
  1164. separator: (options && options.separator) || '',
  1165. });
  1166. return this;
  1167. }
  1168. clone() {
  1169. const bundle = new Bundle({
  1170. intro: this.intro,
  1171. separator: this.separator,
  1172. });
  1173. this.sources.forEach((source) => {
  1174. bundle.addSource({
  1175. filename: source.filename,
  1176. content: source.content.clone(),
  1177. separator: source.separator,
  1178. });
  1179. });
  1180. return bundle;
  1181. }
  1182. generateDecodedMap(options = {}) {
  1183. const names = [];
  1184. let x_google_ignoreList = undefined;
  1185. this.sources.forEach((source) => {
  1186. Object.keys(source.content.storedNames).forEach((name) => {
  1187. if (!~names.indexOf(name)) names.push(name);
  1188. });
  1189. });
  1190. const mappings = new Mappings(options.hires);
  1191. if (this.intro) {
  1192. mappings.advance(this.intro);
  1193. }
  1194. this.sources.forEach((source, i) => {
  1195. if (i > 0) {
  1196. mappings.advance(this.separator);
  1197. }
  1198. const sourceIndex = source.filename ? this.uniqueSourceIndexByFilename[source.filename] : -1;
  1199. const magicString = source.content;
  1200. const locate = getLocator$1(magicString.original);
  1201. if (magicString.intro) {
  1202. mappings.advance(magicString.intro);
  1203. }
  1204. magicString.firstChunk.eachNext((chunk) => {
  1205. const loc = locate(chunk.start);
  1206. if (chunk.intro.length) mappings.advance(chunk.intro);
  1207. if (source.filename) {
  1208. if (chunk.edited) {
  1209. mappings.addEdit(
  1210. sourceIndex,
  1211. chunk.content,
  1212. loc,
  1213. chunk.storeName ? names.indexOf(chunk.original) : -1,
  1214. );
  1215. } else {
  1216. mappings.addUneditedChunk(
  1217. sourceIndex,
  1218. chunk,
  1219. magicString.original,
  1220. loc,
  1221. magicString.sourcemapLocations,
  1222. );
  1223. }
  1224. } else {
  1225. mappings.advance(chunk.content);
  1226. }
  1227. if (chunk.outro.length) mappings.advance(chunk.outro);
  1228. });
  1229. if (magicString.outro) {
  1230. mappings.advance(magicString.outro);
  1231. }
  1232. if (source.ignoreList && sourceIndex !== -1) {
  1233. if (x_google_ignoreList === undefined) {
  1234. x_google_ignoreList = [];
  1235. }
  1236. x_google_ignoreList.push(sourceIndex);
  1237. }
  1238. });
  1239. return {
  1240. file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
  1241. sources: this.uniqueSources.map((source) => {
  1242. return options.file ? getRelativePath(options.file, source.filename) : source.filename;
  1243. }),
  1244. sourcesContent: this.uniqueSources.map((source) => {
  1245. return options.includeContent ? source.content : null;
  1246. }),
  1247. names,
  1248. mappings: mappings.raw,
  1249. x_google_ignoreList,
  1250. };
  1251. }
  1252. generateMap(options) {
  1253. return new SourceMap(this.generateDecodedMap(options));
  1254. }
  1255. getIndentString() {
  1256. const indentStringCounts = {};
  1257. this.sources.forEach((source) => {
  1258. const indentStr = source.content._getRawIndentString();
  1259. if (indentStr === null) return;
  1260. if (!indentStringCounts[indentStr]) indentStringCounts[indentStr] = 0;
  1261. indentStringCounts[indentStr] += 1;
  1262. });
  1263. return (
  1264. Object.keys(indentStringCounts).sort((a, b) => {
  1265. return indentStringCounts[a] - indentStringCounts[b];
  1266. })[0] || '\t'
  1267. );
  1268. }
  1269. indent(indentStr) {
  1270. if (!arguments.length) {
  1271. indentStr = this.getIndentString();
  1272. }
  1273. if (indentStr === '') return this; // noop
  1274. let trailingNewline = !this.intro || this.intro.slice(-1) === '\n';
  1275. this.sources.forEach((source, i) => {
  1276. const separator = source.separator !== undefined ? source.separator : this.separator;
  1277. const indentStart = trailingNewline || (i > 0 && /\r?\n$/.test(separator));
  1278. source.content.indent(indentStr, {
  1279. exclude: source.indentExclusionRanges,
  1280. indentStart, //: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator )
  1281. });
  1282. trailingNewline = source.content.lastChar() === '\n';
  1283. });
  1284. if (this.intro) {
  1285. this.intro =
  1286. indentStr +
  1287. this.intro.replace(/^[^\n]/gm, (match, index) => {
  1288. return index > 0 ? indentStr + match : match;
  1289. });
  1290. }
  1291. return this;
  1292. }
  1293. prepend(str) {
  1294. this.intro = str + this.intro;
  1295. return this;
  1296. }
  1297. toString() {
  1298. const body = this.sources
  1299. .map((source, i) => {
  1300. const separator = source.separator !== undefined ? source.separator : this.separator;
  1301. const str = (i > 0 ? separator : '') + source.content.toString();
  1302. return str;
  1303. })
  1304. .join('');
  1305. return this.intro + body;
  1306. }
  1307. isEmpty() {
  1308. if (this.intro.length && this.intro.trim()) return false;
  1309. if (this.sources.some((source) => !source.content.isEmpty())) return false;
  1310. return true;
  1311. }
  1312. length() {
  1313. return this.sources.reduce(
  1314. (length, source) => length + source.content.length(),
  1315. this.intro.length,
  1316. );
  1317. }
  1318. trimLines() {
  1319. return this.trim('[\\r\\n]');
  1320. }
  1321. trim(charType) {
  1322. return this.trimStart(charType).trimEnd(charType);
  1323. }
  1324. trimStart(charType) {
  1325. const rx = new RegExp('^' + (charType || '\\s') + '+');
  1326. this.intro = this.intro.replace(rx, '');
  1327. if (!this.intro) {
  1328. let source;
  1329. let i = 0;
  1330. do {
  1331. source = this.sources[i++];
  1332. if (!source) {
  1333. break;
  1334. }
  1335. } while (!source.content.trimStartAborted(charType));
  1336. }
  1337. return this;
  1338. }
  1339. trimEnd(charType) {
  1340. const rx = new RegExp((charType || '\\s') + '+$');
  1341. let source;
  1342. let i = this.sources.length - 1;
  1343. do {
  1344. source = this.sources[i--];
  1345. if (!source) {
  1346. this.intro = this.intro.replace(rx, '');
  1347. break;
  1348. }
  1349. } while (!source.content.trimEndAborted(charType));
  1350. return this;
  1351. }
  1352. };
  1353. const ANY_SLASH_REGEX = /[/\\]/;
  1354. function relative(from, to) {
  1355. const fromParts = from.split(ANY_SLASH_REGEX).filter(Boolean);
  1356. const toParts = to.split(ANY_SLASH_REGEX).filter(Boolean);
  1357. if (fromParts[0] === '.')
  1358. fromParts.shift();
  1359. if (toParts[0] === '.')
  1360. toParts.shift();
  1361. while (fromParts[0] && toParts[0] && fromParts[0] === toParts[0]) {
  1362. fromParts.shift();
  1363. toParts.shift();
  1364. }
  1365. while (toParts[0] === '..' && fromParts.length > 0) {
  1366. toParts.shift();
  1367. fromParts.pop();
  1368. }
  1369. while (fromParts.pop()) {
  1370. toParts.unshift('..');
  1371. }
  1372. return toParts.join('/');
  1373. }
  1374. const needsEscapeRegEx = /[\n\r'\\\u2028\u2029]/;
  1375. const quoteNewlineRegEx = /([\n\r'\u2028\u2029])/g;
  1376. const backSlashRegEx = /\\/g;
  1377. function escapeId(id) {
  1378. if (!needsEscapeRegEx.test(id))
  1379. return id;
  1380. return id.replace(backSlashRegEx, '\\\\').replace(quoteNewlineRegEx, '\\$1');
  1381. }
  1382. const ABSOLUTE_PATH_REGEX = /^(?:\/|(?:[A-Za-z]:)?[/\\|])/;
  1383. const RELATIVE_PATH_REGEX = /^\.?\.(\/|$)/;
  1384. function isAbsolute(path) {
  1385. return ABSOLUTE_PATH_REGEX.test(path);
  1386. }
  1387. function isRelative(path) {
  1388. return RELATIVE_PATH_REGEX.test(path);
  1389. }
  1390. const BACKSLASH_REGEX = /\\/g;
  1391. function normalize(path) {
  1392. return path.replace(BACKSLASH_REGEX, '/');
  1393. }
  1394. function getAliasName(id) {
  1395. const base = basename(id);
  1396. return base.slice(0, Math.max(0, base.length - extname(id).length));
  1397. }
  1398. function relativeId(id) {
  1399. if (!isAbsolute(id))
  1400. return id;
  1401. return relative(resolve(), id);
  1402. }
  1403. function isPathFragment(name) {
  1404. // starting with "/", "./", "../", "C:/"
  1405. return (name[0] === '/' || (name[0] === '.' && (name[1] === '/' || name[1] === '.')) || isAbsolute(name));
  1406. }
  1407. const UPPER_DIR_REGEX = /^(\.\.\/)*\.\.$/;
  1408. function getImportPath(importerId, targetPath, stripJsExtension, ensureFileName) {
  1409. while (targetPath.startsWith('../')) {
  1410. targetPath = targetPath.slice(3);
  1411. importerId = '_/' + importerId;
  1412. }
  1413. let relativePath = normalize(relative(dirname(importerId), targetPath));
  1414. if (stripJsExtension && relativePath.endsWith('.js')) {
  1415. relativePath = relativePath.slice(0, -3);
  1416. }
  1417. if (ensureFileName) {
  1418. if (relativePath === '')
  1419. return '../' + basename(targetPath);
  1420. if (UPPER_DIR_REGEX.test(relativePath)) {
  1421. return [...relativePath.split('/'), '..', basename(targetPath)].join('/');
  1422. }
  1423. }
  1424. return relativePath ? (relativePath.startsWith('..') ? relativePath : './' + relativePath) : '.';
  1425. }
  1426. class ExternalChunk {
  1427. constructor(module, options, inputBase) {
  1428. this.options = options;
  1429. this.inputBase = inputBase;
  1430. this.defaultVariableName = '';
  1431. this.namespaceVariableName = '';
  1432. this.variableName = '';
  1433. this.fileName = null;
  1434. this.importAssertions = null;
  1435. this.id = module.id;
  1436. this.moduleInfo = module.info;
  1437. this.renormalizeRenderPath = module.renormalizeRenderPath;
  1438. this.suggestedVariableName = module.suggestedVariableName;
  1439. }
  1440. getFileName() {
  1441. if (this.fileName) {
  1442. return this.fileName;
  1443. }
  1444. const { paths } = this.options;
  1445. return (this.fileName =
  1446. (typeof paths === 'function' ? paths(this.id) : paths[this.id]) ||
  1447. (this.renormalizeRenderPath ? normalize(relative$1(this.inputBase, this.id)) : this.id));
  1448. }
  1449. getImportAssertions(snippets) {
  1450. return (this.importAssertions || (this.importAssertions = formatAssertions$1(this.options.format === 'es' &&
  1451. this.options.externalImportAssertions &&
  1452. this.moduleInfo.assertions, snippets)));
  1453. }
  1454. getImportPath(importer) {
  1455. return escapeId(this.renormalizeRenderPath
  1456. ? getImportPath(importer, this.getFileName(), this.options.format === 'amd', false)
  1457. : this.getFileName());
  1458. }
  1459. }
  1460. function formatAssertions$1(assertions, { getObject }) {
  1461. if (!assertions) {
  1462. return null;
  1463. }
  1464. const assertionEntries = Object.entries(assertions).map(([key, value]) => [key, `'${value}'`]);
  1465. if (assertionEntries.length > 0) {
  1466. return getObject(assertionEntries, { lineBreakIndent: null });
  1467. }
  1468. return null;
  1469. }
  1470. function getOrCreate(map, key, init) {
  1471. const existing = map.get(key);
  1472. if (existing !== undefined) {
  1473. return existing;
  1474. }
  1475. const value = init();
  1476. map.set(key, value);
  1477. return value;
  1478. }
  1479. function getNewSet() {
  1480. return new Set();
  1481. }
  1482. function getNewArray() {
  1483. return [];
  1484. }
  1485. const UnknownKey = Symbol('Unknown Key');
  1486. const UnknownNonAccessorKey = Symbol('Unknown Non-Accessor Key');
  1487. const UnknownInteger = Symbol('Unknown Integer');
  1488. const SymbolToStringTag = Symbol('Symbol.toStringTag');
  1489. const EMPTY_PATH = [];
  1490. const UNKNOWN_PATH = [UnknownKey];
  1491. // For deoptimizations, this means we are modifying an unknown property but did
  1492. // not lose track of the object or are creating a setter/getter;
  1493. // For assignment effects it means we do not check for setter/getter effects
  1494. // but only if something is mutated that is included, which is relevant for
  1495. // Object.defineProperty
  1496. const UNKNOWN_NON_ACCESSOR_PATH = [UnknownNonAccessorKey];
  1497. const UNKNOWN_INTEGER_PATH = [UnknownInteger];
  1498. const EntitiesKey = Symbol('Entities');
  1499. class PathTracker {
  1500. constructor() {
  1501. this.entityPaths = Object.create(null, {
  1502. [EntitiesKey]: { value: new Set() }
  1503. });
  1504. }
  1505. trackEntityAtPathAndGetIfTracked(path, entity) {
  1506. const trackedEntities = this.getEntities(path);
  1507. if (trackedEntities.has(entity))
  1508. return true;
  1509. trackedEntities.add(entity);
  1510. return false;
  1511. }
  1512. withTrackedEntityAtPath(path, entity, onUntracked, returnIfTracked) {
  1513. const trackedEntities = this.getEntities(path);
  1514. if (trackedEntities.has(entity))
  1515. return returnIfTracked;
  1516. trackedEntities.add(entity);
  1517. const result = onUntracked();
  1518. trackedEntities.delete(entity);
  1519. return result;
  1520. }
  1521. getEntities(path) {
  1522. let currentPaths = this.entityPaths;
  1523. for (const pathSegment of path) {
  1524. currentPaths = currentPaths[pathSegment] =
  1525. currentPaths[pathSegment] ||
  1526. Object.create(null, { [EntitiesKey]: { value: new Set() } });
  1527. }
  1528. return currentPaths[EntitiesKey];
  1529. }
  1530. }
  1531. const SHARED_RECURSION_TRACKER = new PathTracker();
  1532. class DiscriminatedPathTracker {
  1533. constructor() {
  1534. this.entityPaths = Object.create(null, {
  1535. [EntitiesKey]: { value: new Map() }
  1536. });
  1537. }
  1538. trackEntityAtPathAndGetIfTracked(path, discriminator, entity) {
  1539. let currentPaths = this.entityPaths;
  1540. for (const pathSegment of path) {
  1541. currentPaths = currentPaths[pathSegment] =
  1542. currentPaths[pathSegment] ||
  1543. Object.create(null, { [EntitiesKey]: { value: new Map() } });
  1544. }
  1545. const trackedEntities = getOrCreate(currentPaths[EntitiesKey], discriminator, (getNewSet));
  1546. if (trackedEntities.has(entity))
  1547. return true;
  1548. trackedEntities.add(entity);
  1549. return false;
  1550. }
  1551. }
  1552. const UnknownValue = Symbol('Unknown Value');
  1553. const UnknownTruthyValue = Symbol('Unknown Truthy Value');
  1554. class ExpressionEntity {
  1555. constructor() {
  1556. this.included = false;
  1557. }
  1558. deoptimizeArgumentsOnInteractionAtPath(interaction, _path, _recursionTracker) {
  1559. deoptimizeInteraction(interaction);
  1560. }
  1561. deoptimizePath(_path) { }
  1562. /**
  1563. * If possible it returns a stringifyable literal value for this node that
  1564. * can be used for inlining or comparing values. Otherwise, it should return
  1565. * UnknownValue.
  1566. */
  1567. getLiteralValueAtPath(_path, _recursionTracker, _origin) {
  1568. return UnknownValue;
  1569. }
  1570. getReturnExpressionWhenCalledAtPath(_path, _interaction, _recursionTracker, _origin) {
  1571. return UNKNOWN_RETURN_EXPRESSION;
  1572. }
  1573. hasEffectsOnInteractionAtPath(_path, _interaction, _context) {
  1574. return true;
  1575. }
  1576. include(_context, _includeChildrenRecursively, _options) {
  1577. this.included = true;
  1578. }
  1579. includeCallArguments(context, parameters) {
  1580. for (const argument of parameters) {
  1581. argument.include(context, false);
  1582. }
  1583. }
  1584. shouldBeIncluded(_context) {
  1585. return true;
  1586. }
  1587. }
  1588. const UNKNOWN_EXPRESSION = new (class UnknownExpression extends ExpressionEntity {
  1589. })();
  1590. const UNKNOWN_RETURN_EXPRESSION = [
  1591. UNKNOWN_EXPRESSION,
  1592. false
  1593. ];
  1594. const deoptimizeInteraction = (interaction) => {
  1595. for (const argument of interaction.args) {
  1596. argument?.deoptimizePath(UNKNOWN_PATH);
  1597. }
  1598. };
  1599. const INTERACTION_ACCESSED = 0;
  1600. const INTERACTION_ASSIGNED = 1;
  1601. const INTERACTION_CALLED = 2;
  1602. const NODE_INTERACTION_UNKNOWN_ACCESS = {
  1603. args: [null],
  1604. type: INTERACTION_ACCESSED
  1605. };
  1606. const NODE_INTERACTION_UNKNOWN_ASSIGNMENT = {
  1607. args: [null, UNKNOWN_EXPRESSION],
  1608. type: INTERACTION_ASSIGNED
  1609. };
  1610. // While this is technically a call without arguments, we can compare against
  1611. // this reference in places where precise values or this argument would make a
  1612. // difference
  1613. const NODE_INTERACTION_UNKNOWN_CALL = {
  1614. args: [null],
  1615. type: INTERACTION_CALLED,
  1616. withNew: false
  1617. };
  1618. class Variable extends ExpressionEntity {
  1619. constructor(name) {
  1620. super();
  1621. this.name = name;
  1622. this.alwaysRendered = false;
  1623. this.forbiddenNames = null;
  1624. this.initReached = false;
  1625. this.isId = false;
  1626. this.isReassigned = false;
  1627. this.kind = null;
  1628. this.renderBaseName = null;
  1629. this.renderName = null;
  1630. }
  1631. /**
  1632. * Binds identifiers that reference this variable to this variable.
  1633. * Necessary to be able to change variable names.
  1634. */
  1635. addReference(_identifier) { }
  1636. /**
  1637. * Prevent this variable from being renamed to this name to avoid name
  1638. * collisions
  1639. */
  1640. forbidName(name) {
  1641. (this.forbiddenNames || (this.forbiddenNames = new Set())).add(name);
  1642. }
  1643. getBaseVariableName() {
  1644. return this.renderBaseName || this.renderName || this.name;
  1645. }
  1646. getName(getPropertyAccess, useOriginalName) {
  1647. if (useOriginalName?.(this)) {
  1648. return this.name;
  1649. }
  1650. const name = this.renderName || this.name;
  1651. return this.renderBaseName ? `${this.renderBaseName}${getPropertyAccess(name)}` : name;
  1652. }
  1653. hasEffectsOnInteractionAtPath(path, { type }, _context) {
  1654. return type !== INTERACTION_ACCESSED || path.length > 0;
  1655. }
  1656. /**
  1657. * Marks this variable as being part of the bundle, which is usually the case when one of
  1658. * its identifiers becomes part of the bundle. Returns true if it has not been included
  1659. * previously.
  1660. * Once a variable is included, it should take care all its declarations are included.
  1661. */
  1662. include() {
  1663. this.included = true;
  1664. }
  1665. markCalledFromTryStatement() { }
  1666. setRenderNames(baseName, name) {
  1667. this.renderBaseName = baseName;
  1668. this.renderName = name;
  1669. }
  1670. }
  1671. class ExternalVariable extends Variable {
  1672. constructor(module, name) {
  1673. super(name);
  1674. this.referenced = false;
  1675. this.module = module;
  1676. this.isNamespace = name === '*';
  1677. }
  1678. addReference(identifier) {
  1679. this.referenced = true;
  1680. if (this.name === 'default' || this.name === '*') {
  1681. this.module.suggestName(identifier.name);
  1682. }
  1683. }
  1684. hasEffectsOnInteractionAtPath(path, { type }) {
  1685. return type !== INTERACTION_ACCESSED || path.length > (this.isNamespace ? 1 : 0);
  1686. }
  1687. include() {
  1688. if (!this.included) {
  1689. this.included = true;
  1690. this.module.used = true;
  1691. }
  1692. }
  1693. }
  1694. const BLANK = Object.freeze(Object.create(null));
  1695. const EMPTY_OBJECT = Object.freeze({});
  1696. const EMPTY_ARRAY = Object.freeze([]);
  1697. const EMPTY_SET = Object.freeze(new (class extends Set {
  1698. add() {
  1699. throw new Error('Cannot add to empty set');
  1700. }
  1701. })());
  1702. const RESERVED_NAMES = new Set([
  1703. 'await',
  1704. 'break',
  1705. 'case',
  1706. 'catch',
  1707. 'class',
  1708. 'const',
  1709. 'continue',
  1710. 'debugger',
  1711. 'default',
  1712. 'delete',
  1713. 'do',
  1714. 'else',
  1715. 'enum',
  1716. 'eval',
  1717. 'export',
  1718. 'extends',
  1719. 'false',
  1720. 'finally',
  1721. 'for',
  1722. 'function',
  1723. 'if',
  1724. 'implements',
  1725. 'import',
  1726. 'in',
  1727. 'instanceof',
  1728. 'interface',
  1729. 'let',
  1730. 'NaN',
  1731. 'new',
  1732. 'null',
  1733. 'package',
  1734. 'private',
  1735. 'protected',
  1736. 'public',
  1737. 'return',
  1738. 'static',
  1739. 'super',
  1740. 'switch',
  1741. 'this',
  1742. 'throw',
  1743. 'true',
  1744. 'try',
  1745. 'typeof',
  1746. 'undefined',
  1747. 'var',
  1748. 'void',
  1749. 'while',
  1750. 'with',
  1751. 'yield'
  1752. ]);
  1753. const RESERVED_NAMES$1 = RESERVED_NAMES;
  1754. const illegalCharacters = /[^\w$]/g;
  1755. const startsWithDigit = (value) => /\d/.test(value[0]);
  1756. const needsEscape = (value) => startsWithDigit(value) || RESERVED_NAMES$1.has(value) || value === 'arguments';
  1757. function isLegal(value) {
  1758. if (needsEscape(value)) {
  1759. return false;
  1760. }
  1761. return !illegalCharacters.test(value);
  1762. }
  1763. function makeLegal(value) {
  1764. value = value
  1765. .replace(/-(\w)/g, (_, letter) => letter.toUpperCase())
  1766. .replace(illegalCharacters, '_');
  1767. if (needsEscape(value))
  1768. value = `_${value}`;
  1769. return value || '_';
  1770. }
  1771. const LOGLEVEL_SILENT = 'silent';
  1772. const LOGLEVEL_ERROR = 'error';
  1773. const LOGLEVEL_WARN = 'warn';
  1774. const LOGLEVEL_INFO = 'info';
  1775. const LOGLEVEL_DEBUG = 'debug';
  1776. const logLevelPriority = {
  1777. [LOGLEVEL_DEBUG]: 0,
  1778. [LOGLEVEL_INFO]: 1,
  1779. [LOGLEVEL_SILENT]: 3,
  1780. [LOGLEVEL_WARN]: 2
  1781. };
  1782. /** @typedef {import('./types').Location} Location */
  1783. /**
  1784. * @param {import('./types').Range} range
  1785. * @param {number} index
  1786. */
  1787. function rangeContains(range, index) {
  1788. return range.start <= index && index < range.end;
  1789. }
  1790. /**
  1791. * @param {string} source
  1792. * @param {import('./types').Options} [options]
  1793. */
  1794. function getLocator(source, options = {}) {
  1795. const { offsetLine = 0, offsetColumn = 0 } = options;
  1796. let start = 0;
  1797. const ranges = source.split('\n').map((line, i) => {
  1798. const end = start + line.length + 1;
  1799. /** @type {import('./types').Range} */
  1800. const range = { start, end, line: i };
  1801. start = end;
  1802. return range;
  1803. });
  1804. let i = 0;
  1805. /**
  1806. * @param {string | number} search
  1807. * @param {number} [index]
  1808. * @returns {Location | undefined}
  1809. */
  1810. function locator(search, index) {
  1811. if (typeof search === 'string') {
  1812. search = source.indexOf(search, index ?? 0);
  1813. }
  1814. if (search === -1) return undefined;
  1815. let range = ranges[i];
  1816. const d = search >= range.end ? 1 : -1;
  1817. while (range) {
  1818. if (rangeContains(range, search)) {
  1819. return {
  1820. line: offsetLine + range.line,
  1821. column: offsetColumn + search - range.start,
  1822. character: search
  1823. };
  1824. }
  1825. i += d;
  1826. range = ranges[i];
  1827. }
  1828. }
  1829. return locator;
  1830. }
  1831. /**
  1832. * @param {string} source
  1833. * @param {string | number} search
  1834. * @param {import('./types').Options} [options]
  1835. * @returns {Location | undefined}
  1836. */
  1837. function locate(source, search, options) {
  1838. return getLocator(source, options)(search, options && options.startIndex);
  1839. }
  1840. function spaces(index) {
  1841. let result = '';
  1842. while (index--)
  1843. result += ' ';
  1844. return result;
  1845. }
  1846. function tabsToSpaces(value) {
  1847. return value.replace(/^\t+/, match => match.split('\t').join(' '));
  1848. }
  1849. const LINE_TRUNCATE_LENGTH = 120;
  1850. const MIN_CHARACTERS_SHOWN_AFTER_LOCATION = 10;
  1851. const ELLIPSIS = '...';
  1852. function getCodeFrame(source, line, column) {
  1853. let lines = source.split('\n');
  1854. // Needed if a plugin did not generate correct sourcemaps
  1855. if (line > lines.length)
  1856. return '';
  1857. const maxLineLength = Math.max(tabsToSpaces(lines[line - 1].slice(0, column)).length +
  1858. MIN_CHARACTERS_SHOWN_AFTER_LOCATION +
  1859. ELLIPSIS.length, LINE_TRUNCATE_LENGTH);
  1860. const frameStart = Math.max(0, line - 3);
  1861. let frameEnd = Math.min(line + 2, lines.length);
  1862. lines = lines.slice(frameStart, frameEnd);
  1863. while (!/\S/.test(lines[lines.length - 1])) {
  1864. lines.pop();
  1865. frameEnd -= 1;
  1866. }
  1867. const digits = String(frameEnd).length;
  1868. return lines
  1869. .map((sourceLine, index) => {
  1870. const isErrorLine = frameStart + index + 1 === line;
  1871. let lineNumber = String(index + frameStart + 1);
  1872. while (lineNumber.length < digits)
  1873. lineNumber = ` ${lineNumber}`;
  1874. let displayedLine = tabsToSpaces(sourceLine);
  1875. if (displayedLine.length > maxLineLength) {
  1876. displayedLine = `${displayedLine.slice(0, maxLineLength - ELLIPSIS.length)}${ELLIPSIS}`;
  1877. }
  1878. if (isErrorLine) {
  1879. const indicator = spaces(digits + 2 + tabsToSpaces(sourceLine.slice(0, column)).length) + '^';
  1880. return `${lineNumber}: ${displayedLine}\n${indicator}`;
  1881. }
  1882. return `${lineNumber}: ${displayedLine}`;
  1883. })
  1884. .join('\n');
  1885. }
  1886. function printQuotedStringList(list, verbs) {
  1887. const isSingleItem = list.length <= 1;
  1888. const quotedList = list.map(item => `"${item}"`);
  1889. let output = isSingleItem
  1890. ? quotedList[0]
  1891. : `${quotedList.slice(0, -1).join(', ')} and ${quotedList.slice(-1)[0]}`;
  1892. if (verbs) {
  1893. output += ` ${isSingleItem ? verbs[0] : verbs[1]}`;
  1894. }
  1895. return output;
  1896. }
  1897. function isValidUrl(url) {
  1898. try {
  1899. new URL(url);
  1900. }
  1901. catch {
  1902. return false;
  1903. }
  1904. return true;
  1905. }
  1906. function getRollupUrl(snippet) {
  1907. return `https://rollupjs.org/${snippet}`;
  1908. }
  1909. function addTrailingSlashIfMissed(url) {
  1910. if (!url.endsWith('/')) {
  1911. return url + '/';
  1912. }
  1913. return url;
  1914. }
  1915. // troubleshooting
  1916. const URL_AVOIDING_EVAL = 'troubleshooting/#avoiding-eval';
  1917. const URL_NAME_IS_NOT_EXPORTED = 'troubleshooting/#error-name-is-not-exported-by-module';
  1918. const URL_THIS_IS_UNDEFINED = 'troubleshooting/#error-this-is-undefined';
  1919. const URL_TREATING_MODULE_AS_EXTERNAL_DEPENDENCY = 'troubleshooting/#warning-treating-module-as-external-dependency';
  1920. const URL_SOURCEMAP_IS_LIKELY_TO_BE_INCORRECT = 'troubleshooting/#warning-sourcemap-is-likely-to-be-incorrect';
  1921. // configuration-options
  1922. const URL_MAXPARALLELFILEOPS = 'configuration-options/#maxparallelfileops';
  1923. const URL_OUTPUT_AMD_ID = 'configuration-options/#output-amd-id';
  1924. const URL_OUTPUT_AMD_BASEPATH = 'configuration-options/#output-amd-basepath';
  1925. const URL_OUTPUT_DIR = 'configuration-options/#output-dir';
  1926. const URL_OUTPUT_DYNAMICIMPORTFUNCTION = 'configuration-options/#output-dynamicimportfunction';
  1927. const URL_OUTPUT_EXPORTS = 'configuration-options/#output-exports';
  1928. const URL_OUTPUT_EXTEND = 'configuration-options/#output-extend';
  1929. const URL_OUTPUT_FORMAT = 'configuration-options/#output-format';
  1930. const URL_OUTPUT_GENERATEDCODE = 'configuration-options/#output-generatedcode';
  1931. const URL_OUTPUT_EXPERIMENTALDEEPCHUNKOPTIMIZATION = 'configuration-options/#output-experimentaldeepdynamicchunkoptimization';
  1932. const URL_OUTPUT_GENERATEDCODE_CONSTBINDINGS = 'configuration-options/#output-generatedcode-constbindings';
  1933. const URL_OUTPUT_GENERATEDCODE_SYMBOLS = 'configuration-options/#output-generatedcode-symbols';
  1934. const URL_OUTPUT_GLOBALS = 'configuration-options/#output-globals';
  1935. const URL_OUTPUT_INLINEDYNAMICIMPORTS = 'configuration-options/#output-inlinedynamicimports';
  1936. const URL_OUTPUT_INTEROP = 'configuration-options/#output-interop';
  1937. const URL_OUTPUT_MANUALCHUNKS = 'configuration-options/#output-manualchunks';
  1938. const URL_OUTPUT_NAME = 'configuration-options/#output-name';
  1939. const URL_OUTPUT_PRESERVEMODULES = 'configuration-options/#output-preservemodules';
  1940. const URL_OUTPUT_SOURCEMAPBASEURL = 'configuration-options/#output-sourcemapbaseurl';
  1941. const URL_OUTPUT_SOURCEMAPFILE = 'configuration-options/#output-sourcemapfile';
  1942. const URL_PRESERVEENTRYSIGNATURES = 'configuration-options/#preserveentrysignatures';
  1943. const URL_TREESHAKE = 'configuration-options/#treeshake';
  1944. const URL_TREESHAKE_MODULESIDEEFFECTS = 'configuration-options/#treeshake-modulesideeffects';
  1945. const URL_WATCH = 'configuration-options/#watch';
  1946. const URL_RENDERDYNAMICIMPORT = 'plugin-development/#renderdynamicimport';
  1947. const URL_THIS_GETMODULEIDS = 'plugin-development/#this-getmoduleids';
  1948. const URL_THIS_GETMODULEINFO = 'plugin-development/#this-getmoduleinfo';
  1949. function error(base) {
  1950. if (!(base instanceof Error)) {
  1951. base = Object.assign(new Error(base.message), base);
  1952. Object.defineProperty(base, 'name', { value: 'RollupError' });
  1953. }
  1954. throw base;
  1955. }
  1956. function augmentCodeLocation(properties, pos, source, id) {
  1957. if (typeof pos === 'object') {
  1958. const { line, column } = pos;
  1959. properties.loc = { column, file: id, line };
  1960. }
  1961. else {
  1962. properties.pos = pos;
  1963. const { line, column } = locate(source, pos, { offsetLine: 1 });
  1964. properties.loc = { column, file: id, line };
  1965. }
  1966. if (properties.frame === undefined) {
  1967. const { line, column } = properties.loc;
  1968. properties.frame = getCodeFrame(source, line, column);
  1969. }
  1970. }
  1971. // Error codes should be sorted alphabetically while errors should be sorted by
  1972. // error code below
  1973. const ADDON_ERROR = 'ADDON_ERROR', ALREADY_CLOSED = 'ALREADY_CLOSED', AMBIGUOUS_EXTERNAL_NAMESPACES = 'AMBIGUOUS_EXTERNAL_NAMESPACES', ANONYMOUS_PLUGIN_CACHE = 'ANONYMOUS_PLUGIN_CACHE', ASSET_NOT_FINALISED = 'ASSET_NOT_FINALISED', ASSET_NOT_FOUND = 'ASSET_NOT_FOUND', ASSET_SOURCE_ALREADY_SET = 'ASSET_SOURCE_ALREADY_SET', ASSET_SOURCE_MISSING = 'ASSET_SOURCE_MISSING', BAD_LOADER = 'BAD_LOADER', CANNOT_CALL_NAMESPACE = 'CANNOT_CALL_NAMESPACE', CANNOT_EMIT_FROM_OPTIONS_HOOK = 'CANNOT_EMIT_FROM_OPTIONS_HOOK', CHUNK_NOT_GENERATED = 'CHUNK_NOT_GENERATED', CHUNK_INVALID = 'CHUNK_INVALID', CIRCULAR_DEPENDENCY = 'CIRCULAR_DEPENDENCY', CIRCULAR_REEXPORT = 'CIRCULAR_REEXPORT', CYCLIC_CROSS_CHUNK_REEXPORT = 'CYCLIC_CROSS_CHUNK_REEXPORT', DEPRECATED_FEATURE = 'DEPRECATED_FEATURE', DUPLICATE_PLUGIN_NAME = 'DUPLICATE_PLUGIN_NAME', EMPTY_BUNDLE = 'EMPTY_BUNDLE', EVAL = 'EVAL', EXTERNAL_MODULES_CANNOT_BE_INCLUDED_IN_MANUAL_CHUNKS = 'EXTERNAL_MODULES_CANNOT_BE_INCLUDED_IN_MANUAL_CHUNKS', EXTERNAL_MODULES_CANNOT_BE_TRANSFORMED_TO_MODULES = 'EXTERNAL_MODULES_CANNOT_BE_TRANSFORMED_TO_MODULES', EXTERNAL_SYNTHETIC_EXPORTS = 'EXTERNAL_SYNTHETIC_EXPORTS', FILE_NAME_CONFLICT = 'FILE_NAME_CONFLICT', FILE_NOT_FOUND = 'FILE_NOT_FOUND', FIRST_SIDE_EFFECT = 'FIRST_SIDE_EFFECT', ILLEGAL_IDENTIFIER_AS_NAME = 'ILLEGAL_IDENTIFIER_AS_NAME', ILLEGAL_REASSIGNMENT = 'ILLEGAL_REASSIGNMENT', INCONSISTENT_IMPORT_ASSERTIONS = 'INCONSISTENT_IMPORT_ASSERTIONS', INPUT_HOOK_IN_OUTPUT_PLUGIN = 'INPUT_HOOK_IN_OUTPUT_PLUGIN', INVALID_CHUNK = 'INVALID_CHUNK', INVALID_EXPORT_OPTION = 'INVALID_EXPORT_OPTION', INVALID_EXTERNAL_ID = 'INVALID_EXTERNAL_ID', INVALID_LOG_POSITION = 'INVALID_LOG_POSITION', INVALID_OPTION = 'INVALID_OPTION', INVALID_PLUGIN_HOOK = 'INVALID_PLUGIN_HOOK', INVALID_ROLLUP_PHASE = 'INVALID_ROLLUP_PHASE', INVALID_SETASSETSOURCE = 'INVALID_SETASSETSOURCE', INVALID_TLA_FORMAT = 'INVALID_TLA_FORMAT', MISSING_EXPORT = 'MISSING_EXPORT', MISSING_GLOBAL_NAME = 'MISSING_GLOBAL_NAME', MISSING_IMPLICIT_DEPENDANT = 'MISSING_IMPLICIT_DEPENDANT', MISSING_NAME_OPTION_FOR_IIFE_EXPORT = 'MISSING_NAME_OPTION_FOR_IIFE_EXPORT', MISSING_NODE_BUILTINS = 'MISSING_NODE_BUILTINS', MISSING_OPTION = 'MISSING_OPTION', MIXED_EXPORTS = 'MIXED_EXPORTS', MODULE_LEVEL_DIRECTIVE = 'MODULE_LEVEL_DIRECTIVE', NAMESPACE_CONFLICT = 'NAMESPACE_CONFLICT', NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE = 'NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE', OPTIMIZE_CHUNK_STATUS = 'OPTIMIZE_CHUNK_STATUS', PARSE_ERROR = 'PARSE_ERROR', PLUGIN_ERROR = 'PLUGIN_ERROR', SHIMMED_EXPORT = 'SHIMMED_EXPORT', SOURCEMAP_BROKEN = 'SOURCEMAP_BROKEN', SOURCEMAP_ERROR = 'SOURCEMAP_ERROR', SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT = 'SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT', THIS_IS_UNDEFINED = 'THIS_IS_UNDEFINED', UNEXPECTED_NAMED_IMPORT = 'UNEXPECTED_NAMED_IMPORT', UNKNOWN_OPTION = 'UNKNOWN_OPTION', UNRESOLVED_ENTRY = 'UNRESOLVED_ENTRY', UNRESOLVED_IMPORT = 'UNRESOLVED_IMPORT', UNUSED_EXTERNAL_IMPORT = 'UNUSED_EXTERNAL_IMPORT', VALIDATION_ERROR = 'VALIDATION_ERROR';
  1974. function logAddonNotGenerated(message, hook, plugin) {
  1975. return {
  1976. code: ADDON_ERROR,
  1977. message: `Could not retrieve "${hook}". Check configuration of plugin "${plugin}".
  1978. \tError Message: ${message}`
  1979. };
  1980. }
  1981. function logAlreadyClosed() {
  1982. return {
  1983. code: ALREADY_CLOSED,
  1984. message: 'Bundle is already closed, no more calls to "generate" or "write" are allowed.'
  1985. };
  1986. }
  1987. function logAmbiguousExternalNamespaces(binding, reexportingModule, usedModule, sources) {
  1988. return {
  1989. binding,
  1990. code: AMBIGUOUS_EXTERNAL_NAMESPACES,
  1991. ids: sources,
  1992. message: `Ambiguous external namespace resolution: "${relativeId(reexportingModule)}" re-exports "${binding}" from one of the external modules ${printQuotedStringList(sources.map(module => relativeId(module)))}, guessing "${relativeId(usedModule)}".`,
  1993. reexporter: reexportingModule
  1994. };
  1995. }
  1996. function logAnonymousPluginCache() {
  1997. return {
  1998. code: ANONYMOUS_PLUGIN_CACHE,
  1999. message: 'A plugin is trying to use the Rollup cache but is not declaring a plugin name or cacheKey.'
  2000. };
  2001. }
  2002. function logAssetNotFinalisedForFileName(name) {
  2003. return {
  2004. code: ASSET_NOT_FINALISED,
  2005. message: `Plugin error - Unable to get file name for asset "${name}". Ensure that the source is set and that generate is called first. If you reference assets via import.meta.ROLLUP_FILE_URL_<referenceId>, you need to either have set their source after "renderStart" or need to provide an explicit "fileName" when emitting them.`
  2006. };
  2007. }
  2008. function logAssetReferenceIdNotFoundForSetSource(assetReferenceId) {
  2009. return {
  2010. code: ASSET_NOT_FOUND,
  2011. message: `Plugin error - Unable to set the source for unknown asset "${assetReferenceId}".`
  2012. };
  2013. }
  2014. function logAssetSourceAlreadySet(name) {
  2015. return {
  2016. code: ASSET_SOURCE_ALREADY_SET,
  2017. message: `Unable to set the source for asset "${name}", source already set.`
  2018. };
  2019. }
  2020. function logNoAssetSourceSet(assetName) {
  2021. return {
  2022. code: ASSET_SOURCE_MISSING,
  2023. message: `Plugin error creating asset "${assetName}" - no asset source set.`
  2024. };
  2025. }
  2026. function logBadLoader(id) {
  2027. return {
  2028. code: BAD_LOADER,
  2029. message: `Error loading "${relativeId(id)}": plugin load hook should return a string, a { code, map } object, or nothing/null.`
  2030. };
  2031. }
  2032. function logCannotCallNamespace(name) {
  2033. return {
  2034. code: CANNOT_CALL_NAMESPACE,
  2035. message: `Cannot call a namespace ("${name}").`
  2036. };
  2037. }
  2038. function logCannotEmitFromOptionsHook() {
  2039. return {
  2040. code: CANNOT_EMIT_FROM_OPTIONS_HOOK,
  2041. message: `Cannot emit files or set asset sources in the "outputOptions" hook, use the "renderStart" hook instead.`
  2042. };
  2043. }
  2044. function logChunkNotGeneratedForFileName(name) {
  2045. return {
  2046. code: CHUNK_NOT_GENERATED,
  2047. message: `Plugin error - Unable to get file name for emitted chunk "${name}". You can only get file names once chunks have been generated after the "renderStart" hook.`
  2048. };
  2049. }
  2050. function logChunkInvalid({ fileName, code }, exception) {
  2051. const errorProperties = {
  2052. code: CHUNK_INVALID,
  2053. message: `Chunk "${fileName}" is not valid JavaScript: ${exception.message}.`
  2054. };
  2055. augmentCodeLocation(errorProperties, exception.loc, code, fileName);
  2056. return errorProperties;
  2057. }
  2058. function logCircularDependency(cyclePath) {
  2059. return {
  2060. code: CIRCULAR_DEPENDENCY,
  2061. ids: cyclePath,
  2062. message: `Circular dependency: ${cyclePath.map(relativeId).join(' -> ')}`
  2063. };
  2064. }
  2065. function logCircularReexport(exportName, exporter) {
  2066. return {
  2067. code: CIRCULAR_REEXPORT,
  2068. exporter,
  2069. message: `"${exportName}" cannot be exported from "${relativeId(exporter)}" as it is a reexport that references itself.`
  2070. };
  2071. }
  2072. function logCyclicCrossChunkReexport(exportName, exporter, reexporter, importer, preserveModules) {
  2073. return {
  2074. code: CYCLIC_CROSS_CHUNK_REEXPORT,
  2075. exporter,
  2076. id: importer,
  2077. message: `Export "${exportName}" of module "${relativeId(exporter)}" was reexported through module "${relativeId(reexporter)}" while both modules are dependencies of each other and will end up in different chunks by current Rollup settings. This scenario is not well supported at the moment as it will produce a circular dependency between chunks and will likely lead to broken execution order.\nEither change the import in "${relativeId(importer)}" to point directly to the exporting module or ${preserveModules ? 'do not use "output.preserveModules"' : 'reconfigure "output.manualChunks"'} to ensure these modules end up in the same chunk.`,
  2078. reexporter
  2079. };
  2080. }
  2081. function logDeprecation(deprecation, urlSnippet, plugin) {
  2082. return {
  2083. code: DEPRECATED_FEATURE,
  2084. message: deprecation,
  2085. url: getRollupUrl(urlSnippet),
  2086. ...(plugin ? { plugin } : {})
  2087. };
  2088. }
  2089. function logDuplicatePluginName(plugin) {
  2090. return {
  2091. code: DUPLICATE_PLUGIN_NAME,
  2092. message: `The plugin name ${plugin} is being used twice in the same build. Plugin names must be distinct or provide a cacheKey (please post an issue to the plugin if you are a plugin user).`
  2093. };
  2094. }
  2095. function logEmptyChunk(chunkName) {
  2096. return {
  2097. code: EMPTY_BUNDLE,
  2098. message: `Generated an empty chunk: "${chunkName}".`,
  2099. names: [chunkName]
  2100. };
  2101. }
  2102. function logEval(id) {
  2103. return {
  2104. code: EVAL,
  2105. id,
  2106. message: `Use of eval in "${relativeId(id)}" is strongly discouraged as it poses security risks and may cause issues with minification.`,
  2107. url: getRollupUrl(URL_AVOIDING_EVAL)
  2108. };
  2109. }
  2110. function logExternalSyntheticExports(id, importer) {
  2111. return {
  2112. code: EXTERNAL_SYNTHETIC_EXPORTS,
  2113. exporter: id,
  2114. message: `External "${id}" cannot have "syntheticNamedExports" enabled (imported by "${relativeId(importer)}").`
  2115. };
  2116. }
  2117. function logFileNameConflict(fileName) {
  2118. return {
  2119. code: FILE_NAME_CONFLICT,
  2120. message: `The emitted file "${fileName}" overwrites a previously emitted file of the same name.`
  2121. };
  2122. }
  2123. function logFileReferenceIdNotFoundForFilename(assetReferenceId) {
  2124. return {
  2125. code: FILE_NOT_FOUND,
  2126. message: `Plugin error - Unable to get file name for unknown file "${assetReferenceId}".`
  2127. };
  2128. }
  2129. function logFirstSideEffect(source, id, { line, column }) {
  2130. return {
  2131. code: FIRST_SIDE_EFFECT,
  2132. message: `First side effect in ${relativeId(id)} is at (${line}:${column})\n${getCodeFrame(source, line, column)}`
  2133. };
  2134. }
  2135. function logIllegalIdentifierAsName(name) {
  2136. return {
  2137. code: ILLEGAL_IDENTIFIER_AS_NAME,
  2138. message: `Given name "${name}" is not a legal JS identifier. If you need this, you can try "output.extend: true".`,
  2139. url: getRollupUrl(URL_OUTPUT_EXTEND)
  2140. };
  2141. }
  2142. function logIllegalImportReassignment(name, importingId) {
  2143. return {
  2144. code: ILLEGAL_REASSIGNMENT,
  2145. message: `Illegal reassignment of import "${name}" in "${relativeId(importingId)}".`
  2146. };
  2147. }
  2148. function logInconsistentImportAssertions(existingAssertions, newAssertions, source, importer) {
  2149. return {
  2150. code: INCONSISTENT_IMPORT_ASSERTIONS,
  2151. message: `Module "${relativeId(importer)}" tried to import "${relativeId(source)}" with ${formatAssertions(newAssertions)} assertions, but it was already imported elsewhere with ${formatAssertions(existingAssertions)} assertions. Please ensure that import assertions for the same module are always consistent.`
  2152. };
  2153. }
  2154. const formatAssertions = (assertions) => {
  2155. const entries = Object.entries(assertions);
  2156. if (entries.length === 0)
  2157. return 'no';
  2158. return entries.map(([key, value]) => `"${key}": "${value}"`).join(', ');
  2159. };
  2160. function logInputHookInOutputPlugin(pluginName, hookName) {
  2161. return {
  2162. code: INPUT_HOOK_IN_OUTPUT_PLUGIN,
  2163. message: `The "${hookName}" hook used by the output plugin ${pluginName} is a build time hook and will not be run for that plugin. Either this plugin cannot be used as an output plugin, or it should have an option to configure it as an output plugin.`
  2164. };
  2165. }
  2166. function logCannotAssignModuleToChunk(moduleId, assignToAlias, currentAlias) {
  2167. return {
  2168. code: INVALID_CHUNK,
  2169. message: `Cannot assign "${relativeId(moduleId)}" to the "${assignToAlias}" chunk as it is already in the "${currentAlias}" chunk.`
  2170. };
  2171. }
  2172. function logInvalidExportOptionValue(optionValue) {
  2173. return {
  2174. code: INVALID_EXPORT_OPTION,
  2175. message: `"output.exports" must be "default", "named", "none", "auto", or left unspecified (defaults to "auto"), received "${optionValue}".`,
  2176. url: getRollupUrl(URL_OUTPUT_EXPORTS)
  2177. };
  2178. }
  2179. function logIncompatibleExportOptionValue(optionValue, keys, entryModule) {
  2180. return {
  2181. code: INVALID_EXPORT_OPTION,
  2182. message: `"${optionValue}" was specified for "output.exports", but entry module "${relativeId(entryModule)}" has the following exports: ${printQuotedStringList(keys)}`,
  2183. url: getRollupUrl(URL_OUTPUT_EXPORTS)
  2184. };
  2185. }
  2186. function logInternalIdCannotBeExternal(source, importer) {
  2187. return {
  2188. code: INVALID_EXTERNAL_ID,
  2189. message: `"${source}" is imported as an external by "${relativeId(importer)}", but is already an existing non-external module id.`
  2190. };
  2191. }
  2192. function logInvalidLogPosition(plugin) {
  2193. return {
  2194. code: INVALID_LOG_POSITION,
  2195. message: `Plugin "${plugin}" tried to add a file position to a log or warning. This is only supported in the "transform" hook at the moment and will be ignored.`
  2196. };
  2197. }
  2198. function logInvalidOption(option, urlSnippet, explanation, value) {
  2199. return {
  2200. code: INVALID_OPTION,
  2201. message: `Invalid value ${value === undefined ? '' : `${JSON.stringify(value)} `}for option "${option}" - ${explanation}.`,
  2202. url: getRollupUrl(urlSnippet)
  2203. };
  2204. }
  2205. function logInvalidAddonPluginHook(hook, plugin) {
  2206. return {
  2207. code: INVALID_PLUGIN_HOOK,
  2208. hook,
  2209. message: `Error running plugin hook "${hook}" for plugin "${plugin}", expected a string, a function hook or an object with a "handler" string or function.`,
  2210. plugin
  2211. };
  2212. }
  2213. function logInvalidFunctionPluginHook(hook, plugin) {
  2214. return {
  2215. code: INVALID_PLUGIN_HOOK,
  2216. hook,
  2217. message: `Error running plugin hook "${hook}" for plugin "${plugin}", expected a function hook or an object with a "handler" function.`,
  2218. plugin
  2219. };
  2220. }
  2221. function logInvalidRollupPhaseForAddWatchFile() {
  2222. return {
  2223. code: INVALID_ROLLUP_PHASE,
  2224. message: `Cannot call "addWatchFile" after the build has finished.`
  2225. };
  2226. }
  2227. function logInvalidRollupPhaseForChunkEmission() {
  2228. return {
  2229. code: INVALID_ROLLUP_PHASE,
  2230. message: `Cannot emit chunks after module loading has finished.`
  2231. };
  2232. }
  2233. function logInvalidSetAssetSourceCall() {
  2234. return {
  2235. code: INVALID_SETASSETSOURCE,
  2236. message: `setAssetSource cannot be called in transform for caching reasons. Use emitFile with a source, or call setAssetSource in another hook.`
  2237. };
  2238. }
  2239. function logInvalidFormatForTopLevelAwait(id, format) {
  2240. return {
  2241. code: INVALID_TLA_FORMAT,
  2242. id,
  2243. message: `Module format "${format}" does not support top-level await. Use the "es" or "system" output formats rather.`
  2244. };
  2245. }
  2246. function logMissingExport(binding, importingModule, exporter) {
  2247. const isJson = extname(exporter) === '.json';
  2248. return {
  2249. binding,
  2250. code: MISSING_EXPORT,
  2251. exporter,
  2252. id: importingModule,
  2253. message: `"${binding}" is not exported by "${relativeId(exporter)}", imported by "${relativeId(importingModule)}".${isJson ? ' (Note that you need @rollup/plugin-json to import JSON files)' : ''}`,
  2254. url: getRollupUrl(URL_NAME_IS_NOT_EXPORTED)
  2255. };
  2256. }
  2257. function logMissingGlobalName(externalId, guess) {
  2258. return {
  2259. code: MISSING_GLOBAL_NAME,
  2260. id: externalId,
  2261. message: `No name was provided for external module "${externalId}" in "output.globals" – guessing "${guess}".`,
  2262. names: [guess],
  2263. url: getRollupUrl(URL_OUTPUT_GLOBALS)
  2264. };
  2265. }
  2266. function logImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore) {
  2267. return {
  2268. code: MISSING_IMPLICIT_DEPENDANT,
  2269. message: `Module "${relativeId(unresolvedId)}" that should be implicitly loaded before "${relativeId(implicitlyLoadedBefore)}" cannot be external.`
  2270. };
  2271. }
  2272. function logUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore) {
  2273. return {
  2274. code: MISSING_IMPLICIT_DEPENDANT,
  2275. message: `Module "${relativeId(unresolvedId)}" that should be implicitly loaded before "${relativeId(implicitlyLoadedBefore)}" could not be resolved.`
  2276. };
  2277. }
  2278. function logImplicitDependantIsNotIncluded(module) {
  2279. const implicitDependencies = [...module.implicitlyLoadedBefore]
  2280. .map(dependency => relativeId(dependency.id))
  2281. .sort();
  2282. return {
  2283. code: MISSING_IMPLICIT_DEPENDANT,
  2284. message: `Module "${relativeId(module.id)}" that should be implicitly loaded before ${printQuotedStringList(implicitDependencies)} is not included in the module graph. Either it was not imported by an included module or only via a tree-shaken dynamic import, or no imported bindings were used and it had otherwise no side-effects.`
  2285. };
  2286. }
  2287. function logMissingNameOptionForIifeExport() {
  2288. return {
  2289. code: MISSING_NAME_OPTION_FOR_IIFE_EXPORT,
  2290. message: `If you do not supply "output.name", you may not be able to access the exports of an IIFE bundle.`,
  2291. url: getRollupUrl(URL_OUTPUT_NAME)
  2292. };
  2293. }
  2294. function logMissingNameOptionForUmdExport() {
  2295. return {
  2296. code: MISSING_NAME_OPTION_FOR_IIFE_EXPORT,
  2297. message: 'You must supply "output.name" for UMD bundles that have exports so that the exports are accessible in environments without a module loader.',
  2298. url: getRollupUrl(URL_OUTPUT_NAME)
  2299. };
  2300. }
  2301. function logMissingNodeBuiltins(externalBuiltins) {
  2302. return {
  2303. code: MISSING_NODE_BUILTINS,
  2304. ids: externalBuiltins,
  2305. message: `Creating a browser bundle that depends on Node.js built-in modules (${printQuotedStringList(externalBuiltins)}). You might need to include https://github.com/FredKSchott/rollup-plugin-polyfill-node`
  2306. };
  2307. }
  2308. // eslint-disable-next-line unicorn/prevent-abbreviations
  2309. function logMissingFileOrDirOption() {
  2310. return {
  2311. code: MISSING_OPTION,
  2312. message: 'You must specify "output.file" or "output.dir" for the build.',
  2313. url: getRollupUrl(URL_OUTPUT_DIR)
  2314. };
  2315. }
  2316. function logMixedExport(facadeModuleId, name) {
  2317. return {
  2318. code: MIXED_EXPORTS,
  2319. id: facadeModuleId,
  2320. message: `Entry module "${relativeId(facadeModuleId)}" is using named and default exports together. Consumers of your bundle will have to use \`${name || 'chunk'}.default\` to access the default export, which may not be what you want. Use \`output.exports: "named"\` to disable this warning.`,
  2321. url: getRollupUrl(URL_OUTPUT_EXPORTS)
  2322. };
  2323. }
  2324. function logModuleLevelDirective(directive, id) {
  2325. return {
  2326. code: MODULE_LEVEL_DIRECTIVE,
  2327. id,
  2328. message: `Module level directives cause errors when bundled, "${directive}" in "${relativeId(id)}" was ignored.`
  2329. };
  2330. }
  2331. function logNamespaceConflict(binding, reexportingModuleId, sources) {
  2332. return {
  2333. binding,
  2334. code: NAMESPACE_CONFLICT,
  2335. ids: sources,
  2336. message: `Conflicting namespaces: "${relativeId(reexportingModuleId)}" re-exports "${binding}" from one of the modules ${printQuotedStringList(sources.map(moduleId => relativeId(moduleId)))} (will be ignored).`,
  2337. reexporter: reexportingModuleId
  2338. };
  2339. }
  2340. function logNoTransformMapOrAstWithoutCode(pluginName) {
  2341. return {
  2342. code: NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE,
  2343. message: `The plugin "${pluginName}" returned a "map" or "ast" without returning ` +
  2344. 'a "code". This will be ignored.'
  2345. };
  2346. }
  2347. function logOptimizeChunkStatus(chunks, smallChunks, pointInTime) {
  2348. return {
  2349. code: OPTIMIZE_CHUNK_STATUS,
  2350. message: `${pointInTime}, there are\n` +
  2351. `${chunks} chunks, of which\n` +
  2352. `${smallChunks} are below minChunkSize.`
  2353. };
  2354. }
  2355. function logParseError(error, moduleId) {
  2356. let message = error.message.replace(/ \(\d+:\d+\)$/, '');
  2357. if (moduleId.endsWith('.json')) {
  2358. message += ' (Note that you need @rollup/plugin-json to import JSON files)';
  2359. }
  2360. else if (!moduleId.endsWith('.js')) {
  2361. message += ' (Note that you need plugins to import files that are not JavaScript)';
  2362. }
  2363. return {
  2364. cause: error,
  2365. code: PARSE_ERROR,
  2366. id: moduleId,
  2367. message
  2368. };
  2369. }
  2370. function logPluginError(error, plugin, { hook, id } = {}) {
  2371. const code = error.code;
  2372. if (!error.pluginCode &&
  2373. code != null &&
  2374. (typeof code !== 'string' || (typeof code === 'string' && !code.startsWith('PLUGIN_')))) {
  2375. error.pluginCode = code;
  2376. }
  2377. error.code = PLUGIN_ERROR;
  2378. error.plugin = plugin;
  2379. if (hook) {
  2380. error.hook = hook;
  2381. }
  2382. if (id) {
  2383. error.id = id;
  2384. }
  2385. return error;
  2386. }
  2387. function logShimmedExport(id, binding) {
  2388. return {
  2389. binding,
  2390. code: SHIMMED_EXPORT,
  2391. exporter: id,
  2392. message: `Missing export "${binding}" has been shimmed in module "${relativeId(id)}".`
  2393. };
  2394. }
  2395. function logSourcemapBroken(plugin) {
  2396. return {
  2397. code: SOURCEMAP_BROKEN,
  2398. message: `Sourcemap is likely to be incorrect: a plugin (${plugin}) was used to transform files, but didn't generate a sourcemap for the transformation. Consult the plugin documentation for help`,
  2399. plugin,
  2400. url: getRollupUrl(URL_SOURCEMAP_IS_LIKELY_TO_BE_INCORRECT)
  2401. };
  2402. }
  2403. function logConflictingSourcemapSources(filename) {
  2404. return {
  2405. code: SOURCEMAP_BROKEN,
  2406. message: `Multiple conflicting contents for sourcemap source ${filename}`
  2407. };
  2408. }
  2409. function logInvalidSourcemapForError(error, id, column, line, pos) {
  2410. return {
  2411. cause: error,
  2412. code: SOURCEMAP_ERROR,
  2413. id,
  2414. loc: {
  2415. column,
  2416. file: id,
  2417. line
  2418. },
  2419. message: `Error when using sourcemap for reporting an error: ${error.message}`,
  2420. pos
  2421. };
  2422. }
  2423. function logSyntheticNamedExportsNeedNamespaceExport(id, syntheticNamedExportsOption) {
  2424. return {
  2425. code: SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT,
  2426. exporter: id,
  2427. message: `Module "${relativeId(id)}" that is marked with \`syntheticNamedExports: ${JSON.stringify(syntheticNamedExportsOption)}\` needs ${typeof syntheticNamedExportsOption === 'string' && syntheticNamedExportsOption !== 'default'
  2428. ? `an explicit export named "${syntheticNamedExportsOption}"`
  2429. : 'a default export'} that does not reexport an unresolved named export of the same module.`
  2430. };
  2431. }
  2432. function logThisIsUndefined() {
  2433. return {
  2434. code: THIS_IS_UNDEFINED,
  2435. message: `The 'this' keyword is equivalent to 'undefined' at the top level of an ES module, and has been rewritten`,
  2436. url: getRollupUrl(URL_THIS_IS_UNDEFINED)
  2437. };
  2438. }
  2439. function logUnexpectedNamedImport(id, imported, isReexport) {
  2440. const importType = isReexport ? 'reexport' : 'import';
  2441. return {
  2442. code: UNEXPECTED_NAMED_IMPORT,
  2443. exporter: id,
  2444. message: `The named export "${imported}" was ${importType}ed from the external module "${relativeId(id)}" even though its interop type is "defaultOnly". Either remove or change this ${importType} or change the value of the "output.interop" option.`,
  2445. url: getRollupUrl(URL_OUTPUT_INTEROP)
  2446. };
  2447. }
  2448. function logUnexpectedNamespaceReexport(id) {
  2449. return {
  2450. code: UNEXPECTED_NAMED_IMPORT,
  2451. exporter: id,
  2452. message: `There was a namespace "*" reexport from the external module "${relativeId(id)}" even though its interop type is "defaultOnly". This will be ignored as namespace reexports only reexport named exports. If this is not intended, either remove or change this reexport or change the value of the "output.interop" option.`,
  2453. url: getRollupUrl(URL_OUTPUT_INTEROP)
  2454. };
  2455. }
  2456. function logUnknownOption(optionType, unknownOptions, validOptions) {
  2457. return {
  2458. code: UNKNOWN_OPTION,
  2459. message: `Unknown ${optionType}: ${unknownOptions.join(', ')}. Allowed options: ${validOptions.join(', ')}`
  2460. };
  2461. }
  2462. function logEntryCannotBeExternal(unresolvedId) {
  2463. return {
  2464. code: UNRESOLVED_ENTRY,
  2465. message: `Entry module "${relativeId(unresolvedId)}" cannot be external.`
  2466. };
  2467. }
  2468. function logExternalModulesCannotBeIncludedInManualChunks(source) {
  2469. return {
  2470. code: EXTERNAL_MODULES_CANNOT_BE_INCLUDED_IN_MANUAL_CHUNKS,
  2471. message: `"${source}" cannot be included in manualChunks because it is resolved as an external module by the "external" option or plugins.`
  2472. };
  2473. }
  2474. function logExternalModulesCannotBeTransformedToModules(source) {
  2475. return {
  2476. code: EXTERNAL_MODULES_CANNOT_BE_TRANSFORMED_TO_MODULES,
  2477. message: `${source} is resolved as a module now, but it was an external module before. Please check whether there are conflicts in your Rollup options "external" and "manualChunks", manualChunks cannot include external modules.`
  2478. };
  2479. }
  2480. function logUnresolvedEntry(unresolvedId) {
  2481. return {
  2482. code: UNRESOLVED_ENTRY,
  2483. message: `Could not resolve entry module "${relativeId(unresolvedId)}".`
  2484. };
  2485. }
  2486. function logUnresolvedImport(source, importer) {
  2487. return {
  2488. code: UNRESOLVED_IMPORT,
  2489. exporter: source,
  2490. id: importer,
  2491. message: `Could not resolve "${source}" from "${relativeId(importer)}"`
  2492. };
  2493. }
  2494. function logUnresolvedImportTreatedAsExternal(source, importer) {
  2495. return {
  2496. code: UNRESOLVED_IMPORT,
  2497. exporter: source,
  2498. id: importer,
  2499. message: `"${source}" is imported by "${relativeId(importer)}", but could not be resolved – treating it as an external dependency.`,
  2500. url: getRollupUrl(URL_TREATING_MODULE_AS_EXTERNAL_DEPENDENCY)
  2501. };
  2502. }
  2503. function logUnusedExternalImports(externalId, names, importers) {
  2504. return {
  2505. code: UNUSED_EXTERNAL_IMPORT,
  2506. exporter: externalId,
  2507. ids: importers,
  2508. message: `${printQuotedStringList(names, [
  2509. 'is',
  2510. 'are'
  2511. ])} imported from external module "${externalId}" but never used in ${printQuotedStringList(importers.map(importer => relativeId(importer)))}.`,
  2512. names
  2513. };
  2514. }
  2515. function logFailedValidation(message) {
  2516. return {
  2517. code: VALIDATION_ERROR,
  2518. message
  2519. };
  2520. }
  2521. function warnDeprecation(deprecation, urlSnippet, activeDeprecation, options, plugin) {
  2522. warnDeprecationWithOptions(deprecation, urlSnippet, activeDeprecation, options.onLog, options.strictDeprecations, plugin);
  2523. }
  2524. function warnDeprecationWithOptions(deprecation, urlSnippet, activeDeprecation, log, strictDeprecations, plugin) {
  2525. if (activeDeprecation || strictDeprecations) {
  2526. const warning = logDeprecation(deprecation, urlSnippet, plugin);
  2527. if (strictDeprecations) {
  2528. return error(warning);
  2529. }
  2530. log(LOGLEVEL_WARN, warning);
  2531. }
  2532. }
  2533. class ExternalModule {
  2534. constructor(options, id, moduleSideEffects, meta, renormalizeRenderPath, assertions) {
  2535. this.options = options;
  2536. this.id = id;
  2537. this.renormalizeRenderPath = renormalizeRenderPath;
  2538. this.dynamicImporters = [];
  2539. this.execIndex = Infinity;
  2540. this.exportedVariables = new Map();
  2541. this.importers = [];
  2542. this.reexported = false;
  2543. this.used = false;
  2544. this.declarations = new Map();
  2545. this.mostCommonSuggestion = 0;
  2546. this.nameSuggestions = new Map();
  2547. this.suggestedVariableName = makeLegal(id.split(/[/\\]/).pop());
  2548. const { importers, dynamicImporters } = this;
  2549. const info = (this.info = {
  2550. assertions,
  2551. ast: null,
  2552. code: null,
  2553. dynamicallyImportedIdResolutions: EMPTY_ARRAY,
  2554. dynamicallyImportedIds: EMPTY_ARRAY,
  2555. get dynamicImporters() {
  2556. return dynamicImporters.sort();
  2557. },
  2558. exportedBindings: null,
  2559. exports: null,
  2560. hasDefaultExport: null,
  2561. get hasModuleSideEffects() {
  2562. warnDeprecation('Accessing ModuleInfo.hasModuleSideEffects from plugins is deprecated. Please use ModuleInfo.moduleSideEffects instead.', URL_THIS_GETMODULEINFO, true, options);
  2563. return info.moduleSideEffects;
  2564. },
  2565. id,
  2566. implicitlyLoadedAfterOneOf: EMPTY_ARRAY,
  2567. implicitlyLoadedBefore: EMPTY_ARRAY,
  2568. importedIdResolutions: EMPTY_ARRAY,
  2569. importedIds: EMPTY_ARRAY,
  2570. get importers() {
  2571. return importers.sort();
  2572. },
  2573. isEntry: false,
  2574. isExternal: true,
  2575. isIncluded: null,
  2576. meta,
  2577. moduleSideEffects,
  2578. syntheticNamedExports: false
  2579. });
  2580. // Hide the deprecated key so that it only warns when accessed explicitly
  2581. Object.defineProperty(this.info, 'hasModuleSideEffects', {
  2582. enumerable: false
  2583. });
  2584. }
  2585. getVariableForExportName(name) {
  2586. const declaration = this.declarations.get(name);
  2587. if (declaration)
  2588. return [declaration];
  2589. const externalVariable = new ExternalVariable(this, name);
  2590. this.declarations.set(name, externalVariable);
  2591. this.exportedVariables.set(externalVariable, name);
  2592. return [externalVariable];
  2593. }
  2594. suggestName(name) {
  2595. const value = (this.nameSuggestions.get(name) ?? 0) + 1;
  2596. this.nameSuggestions.set(name, value);
  2597. if (value > this.mostCommonSuggestion) {
  2598. this.mostCommonSuggestion = value;
  2599. this.suggestedVariableName = name;
  2600. }
  2601. }
  2602. warnUnusedImports() {
  2603. const unused = [...this.declarations]
  2604. .filter(([name, declaration]) => name !== '*' && !declaration.included && !this.reexported && !declaration.referenced)
  2605. .map(([name]) => name);
  2606. if (unused.length === 0)
  2607. return;
  2608. const importersSet = new Set();
  2609. for (const name of unused) {
  2610. for (const importer of this.declarations.get(name).module.importers) {
  2611. importersSet.add(importer);
  2612. }
  2613. }
  2614. const importersArray = [...importersSet];
  2615. this.options.onLog(LOGLEVEL_WARN, logUnusedExternalImports(this.id, unused, importersArray));
  2616. }
  2617. }
  2618. function getDefaultExportFromCjs (x) {
  2619. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  2620. }
  2621. function getAugmentedNamespace(n) {
  2622. if (n.__esModule) return n;
  2623. var f = n.default;
  2624. if (typeof f == "function") {
  2625. var a = function a () {
  2626. if (this instanceof a) {
  2627. return Reflect.construct(f, arguments, this.constructor);
  2628. }
  2629. return f.apply(this, arguments);
  2630. };
  2631. a.prototype = f.prototype;
  2632. } else a = {};
  2633. Object.defineProperty(a, '__esModule', {value: true});
  2634. Object.keys(n).forEach(function (k) {
  2635. var d = Object.getOwnPropertyDescriptor(n, k);
  2636. Object.defineProperty(a, k, d.get ? d : {
  2637. enumerable: true,
  2638. get: function () {
  2639. return n[k];
  2640. }
  2641. });
  2642. });
  2643. return a;
  2644. }
  2645. var utils$3 = {};
  2646. const path$1 = require$$0$1;
  2647. const WIN_SLASH = '\\\\/';
  2648. const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
  2649. /**
  2650. * Posix glob regex
  2651. */
  2652. const DOT_LITERAL = '\\.';
  2653. const PLUS_LITERAL = '\\+';
  2654. const QMARK_LITERAL = '\\?';
  2655. const SLASH_LITERAL = '\\/';
  2656. const ONE_CHAR = '(?=.)';
  2657. const QMARK = '[^/]';
  2658. const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
  2659. const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
  2660. const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
  2661. const NO_DOT = `(?!${DOT_LITERAL})`;
  2662. const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
  2663. const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
  2664. const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
  2665. const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
  2666. const STAR = `${QMARK}*?`;
  2667. const POSIX_CHARS = {
  2668. DOT_LITERAL,
  2669. PLUS_LITERAL,
  2670. QMARK_LITERAL,
  2671. SLASH_LITERAL,
  2672. ONE_CHAR,
  2673. QMARK,
  2674. END_ANCHOR,
  2675. DOTS_SLASH,
  2676. NO_DOT,
  2677. NO_DOTS,
  2678. NO_DOT_SLASH,
  2679. NO_DOTS_SLASH,
  2680. QMARK_NO_DOT,
  2681. STAR,
  2682. START_ANCHOR
  2683. };
  2684. /**
  2685. * Windows glob regex
  2686. */
  2687. const WINDOWS_CHARS = {
  2688. ...POSIX_CHARS,
  2689. SLASH_LITERAL: `[${WIN_SLASH}]`,
  2690. QMARK: WIN_NO_SLASH,
  2691. STAR: `${WIN_NO_SLASH}*?`,
  2692. DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
  2693. NO_DOT: `(?!${DOT_LITERAL})`,
  2694. NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  2695. NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
  2696. NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  2697. QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
  2698. START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
  2699. END_ANCHOR: `(?:[${WIN_SLASH}]|$)`
  2700. };
  2701. /**
  2702. * POSIX Bracket Regex
  2703. */
  2704. const POSIX_REGEX_SOURCE$1 = {
  2705. alnum: 'a-zA-Z0-9',
  2706. alpha: 'a-zA-Z',
  2707. ascii: '\\x00-\\x7F',
  2708. blank: ' \\t',
  2709. cntrl: '\\x00-\\x1F\\x7F',
  2710. digit: '0-9',
  2711. graph: '\\x21-\\x7E',
  2712. lower: 'a-z',
  2713. print: '\\x20-\\x7E ',
  2714. punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
  2715. space: ' \\t\\r\\n\\v\\f',
  2716. upper: 'A-Z',
  2717. word: 'A-Za-z0-9_',
  2718. xdigit: 'A-Fa-f0-9'
  2719. };
  2720. var constants$2 = {
  2721. MAX_LENGTH: 1024 * 64,
  2722. POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1,
  2723. // regular expressions
  2724. REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
  2725. REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
  2726. REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
  2727. REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
  2728. REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
  2729. REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
  2730. // Replace globs with equivalent patterns to reduce parsing time.
  2731. REPLACEMENTS: {
  2732. '***': '*',
  2733. '**/**': '**',
  2734. '**/**/**': '**'
  2735. },
  2736. // Digits
  2737. CHAR_0: 48, /* 0 */
  2738. CHAR_9: 57, /* 9 */
  2739. // Alphabet chars.
  2740. CHAR_UPPERCASE_A: 65, /* A */
  2741. CHAR_LOWERCASE_A: 97, /* a */
  2742. CHAR_UPPERCASE_Z: 90, /* Z */
  2743. CHAR_LOWERCASE_Z: 122, /* z */
  2744. CHAR_LEFT_PARENTHESES: 40, /* ( */
  2745. CHAR_RIGHT_PARENTHESES: 41, /* ) */
  2746. CHAR_ASTERISK: 42, /* * */
  2747. // Non-alphabetic chars.
  2748. CHAR_AMPERSAND: 38, /* & */
  2749. CHAR_AT: 64, /* @ */
  2750. CHAR_BACKWARD_SLASH: 92, /* \ */
  2751. CHAR_CARRIAGE_RETURN: 13, /* \r */
  2752. CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */
  2753. CHAR_COLON: 58, /* : */
  2754. CHAR_COMMA: 44, /* , */
  2755. CHAR_DOT: 46, /* . */
  2756. CHAR_DOUBLE_QUOTE: 34, /* " */
  2757. CHAR_EQUAL: 61, /* = */
  2758. CHAR_EXCLAMATION_MARK: 33, /* ! */
  2759. CHAR_FORM_FEED: 12, /* \f */
  2760. CHAR_FORWARD_SLASH: 47, /* / */
  2761. CHAR_GRAVE_ACCENT: 96, /* ` */
  2762. CHAR_HASH: 35, /* # */
  2763. CHAR_HYPHEN_MINUS: 45, /* - */
  2764. CHAR_LEFT_ANGLE_BRACKET: 60, /* < */
  2765. CHAR_LEFT_CURLY_BRACE: 123, /* { */
  2766. CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */
  2767. CHAR_LINE_FEED: 10, /* \n */
  2768. CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
  2769. CHAR_PERCENT: 37, /* % */
  2770. CHAR_PLUS: 43, /* + */
  2771. CHAR_QUESTION_MARK: 63, /* ? */
  2772. CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */
  2773. CHAR_RIGHT_CURLY_BRACE: 125, /* } */
  2774. CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */
  2775. CHAR_SEMICOLON: 59, /* ; */
  2776. CHAR_SINGLE_QUOTE: 39, /* ' */
  2777. CHAR_SPACE: 32, /* */
  2778. CHAR_TAB: 9, /* \t */
  2779. CHAR_UNDERSCORE: 95, /* _ */
  2780. CHAR_VERTICAL_LINE: 124, /* | */
  2781. CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
  2782. SEP: path$1.sep,
  2783. /**
  2784. * Create EXTGLOB_CHARS
  2785. */
  2786. extglobChars(chars) {
  2787. return {
  2788. '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
  2789. '?': { type: 'qmark', open: '(?:', close: ')?' },
  2790. '+': { type: 'plus', open: '(?:', close: ')+' },
  2791. '*': { type: 'star', open: '(?:', close: ')*' },
  2792. '@': { type: 'at', open: '(?:', close: ')' }
  2793. };
  2794. },
  2795. /**
  2796. * Create GLOB_CHARS
  2797. */
  2798. globChars(win32) {
  2799. return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
  2800. }
  2801. };
  2802. (function (exports) {
  2803. const path = require$$0$1;
  2804. const win32 = process.platform === 'win32';
  2805. const {
  2806. REGEX_BACKSLASH,
  2807. REGEX_REMOVE_BACKSLASH,
  2808. REGEX_SPECIAL_CHARS,
  2809. REGEX_SPECIAL_CHARS_GLOBAL
  2810. } = constants$2;
  2811. exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  2812. exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
  2813. exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
  2814. exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
  2815. exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
  2816. exports.removeBackslashes = str => {
  2817. return str.replace(REGEX_REMOVE_BACKSLASH, match => {
  2818. return match === '\\' ? '' : match;
  2819. });
  2820. };
  2821. exports.supportsLookbehinds = () => {
  2822. const segs = process.version.slice(1).split('.').map(Number);
  2823. if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) {
  2824. return true;
  2825. }
  2826. return false;
  2827. };
  2828. exports.isWindows = options => {
  2829. if (options && typeof options.windows === 'boolean') {
  2830. return options.windows;
  2831. }
  2832. return win32 === true || path.sep === '\\';
  2833. };
  2834. exports.escapeLast = (input, char, lastIdx) => {
  2835. const idx = input.lastIndexOf(char, lastIdx);
  2836. if (idx === -1) return input;
  2837. if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
  2838. return `${input.slice(0, idx)}\\${input.slice(idx)}`;
  2839. };
  2840. exports.removePrefix = (input, state = {}) => {
  2841. let output = input;
  2842. if (output.startsWith('./')) {
  2843. output = output.slice(2);
  2844. state.prefix = './';
  2845. }
  2846. return output;
  2847. };
  2848. exports.wrapOutput = (input, state = {}, options = {}) => {
  2849. const prepend = options.contains ? '' : '^';
  2850. const append = options.contains ? '' : '$';
  2851. let output = `${prepend}(?:${input})${append}`;
  2852. if (state.negated === true) {
  2853. output = `(?:^(?!${output}).*$)`;
  2854. }
  2855. return output;
  2856. };
  2857. } (utils$3));
  2858. const utils$2 = utils$3;
  2859. const {
  2860. CHAR_ASTERISK, /* * */
  2861. CHAR_AT, /* @ */
  2862. CHAR_BACKWARD_SLASH, /* \ */
  2863. CHAR_COMMA, /* , */
  2864. CHAR_DOT, /* . */
  2865. CHAR_EXCLAMATION_MARK, /* ! */
  2866. CHAR_FORWARD_SLASH, /* / */
  2867. CHAR_LEFT_CURLY_BRACE, /* { */
  2868. CHAR_LEFT_PARENTHESES, /* ( */
  2869. CHAR_LEFT_SQUARE_BRACKET, /* [ */
  2870. CHAR_PLUS, /* + */
  2871. CHAR_QUESTION_MARK, /* ? */
  2872. CHAR_RIGHT_CURLY_BRACE, /* } */
  2873. CHAR_RIGHT_PARENTHESES, /* ) */
  2874. CHAR_RIGHT_SQUARE_BRACKET /* ] */
  2875. } = constants$2;
  2876. const isPathSeparator = code => {
  2877. return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
  2878. };
  2879. const depth = token => {
  2880. if (token.isPrefix !== true) {
  2881. token.depth = token.isGlobstar ? Infinity : 1;
  2882. }
  2883. };
  2884. /**
  2885. * Quickly scans a glob pattern and returns an object with a handful of
  2886. * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
  2887. * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
  2888. * with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
  2889. *
  2890. * ```js
  2891. * const pm = require('picomatch');
  2892. * console.log(pm.scan('foo/bar/*.js'));
  2893. * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
  2894. * ```
  2895. * @param {String} `str`
  2896. * @param {Object} `options`
  2897. * @return {Object} Returns an object with tokens and regex source string.
  2898. * @api public
  2899. */
  2900. const scan$1 = (input, options) => {
  2901. const opts = options || {};
  2902. const length = input.length - 1;
  2903. const scanToEnd = opts.parts === true || opts.scanToEnd === true;
  2904. const slashes = [];
  2905. const tokens = [];
  2906. const parts = [];
  2907. let str = input;
  2908. let index = -1;
  2909. let start = 0;
  2910. let lastIndex = 0;
  2911. let isBrace = false;
  2912. let isBracket = false;
  2913. let isGlob = false;
  2914. let isExtglob = false;
  2915. let isGlobstar = false;
  2916. let braceEscaped = false;
  2917. let backslashes = false;
  2918. let negated = false;
  2919. let negatedExtglob = false;
  2920. let finished = false;
  2921. let braces = 0;
  2922. let prev;
  2923. let code;
  2924. let token = { value: '', depth: 0, isGlob: false };
  2925. const eos = () => index >= length;
  2926. const peek = () => str.charCodeAt(index + 1);
  2927. const advance = () => {
  2928. prev = code;
  2929. return str.charCodeAt(++index);
  2930. };
  2931. while (index < length) {
  2932. code = advance();
  2933. let next;
  2934. if (code === CHAR_BACKWARD_SLASH) {
  2935. backslashes = token.backslashes = true;
  2936. code = advance();
  2937. if (code === CHAR_LEFT_CURLY_BRACE) {
  2938. braceEscaped = true;
  2939. }
  2940. continue;
  2941. }
  2942. if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
  2943. braces++;
  2944. while (eos() !== true && (code = advance())) {
  2945. if (code === CHAR_BACKWARD_SLASH) {
  2946. backslashes = token.backslashes = true;
  2947. advance();
  2948. continue;
  2949. }
  2950. if (code === CHAR_LEFT_CURLY_BRACE) {
  2951. braces++;
  2952. continue;
  2953. }
  2954. if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
  2955. isBrace = token.isBrace = true;
  2956. isGlob = token.isGlob = true;
  2957. finished = true;
  2958. if (scanToEnd === true) {
  2959. continue;
  2960. }
  2961. break;
  2962. }
  2963. if (braceEscaped !== true && code === CHAR_COMMA) {
  2964. isBrace = token.isBrace = true;
  2965. isGlob = token.isGlob = true;
  2966. finished = true;
  2967. if (scanToEnd === true) {
  2968. continue;
  2969. }
  2970. break;
  2971. }
  2972. if (code === CHAR_RIGHT_CURLY_BRACE) {
  2973. braces--;
  2974. if (braces === 0) {
  2975. braceEscaped = false;
  2976. isBrace = token.isBrace = true;
  2977. finished = true;
  2978. break;
  2979. }
  2980. }
  2981. }
  2982. if (scanToEnd === true) {
  2983. continue;
  2984. }
  2985. break;
  2986. }
  2987. if (code === CHAR_FORWARD_SLASH) {
  2988. slashes.push(index);
  2989. tokens.push(token);
  2990. token = { value: '', depth: 0, isGlob: false };
  2991. if (finished === true) continue;
  2992. if (prev === CHAR_DOT && index === (start + 1)) {
  2993. start += 2;
  2994. continue;
  2995. }
  2996. lastIndex = index + 1;
  2997. continue;
  2998. }
  2999. if (opts.noext !== true) {
  3000. const isExtglobChar = code === CHAR_PLUS
  3001. || code === CHAR_AT
  3002. || code === CHAR_ASTERISK
  3003. || code === CHAR_QUESTION_MARK
  3004. || code === CHAR_EXCLAMATION_MARK;
  3005. if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
  3006. isGlob = token.isGlob = true;
  3007. isExtglob = token.isExtglob = true;
  3008. finished = true;
  3009. if (code === CHAR_EXCLAMATION_MARK && index === start) {
  3010. negatedExtglob = true;
  3011. }
  3012. if (scanToEnd === true) {
  3013. while (eos() !== true && (code = advance())) {
  3014. if (code === CHAR_BACKWARD_SLASH) {
  3015. backslashes = token.backslashes = true;
  3016. code = advance();
  3017. continue;
  3018. }
  3019. if (code === CHAR_RIGHT_PARENTHESES) {
  3020. isGlob = token.isGlob = true;
  3021. finished = true;
  3022. break;
  3023. }
  3024. }
  3025. continue;
  3026. }
  3027. break;
  3028. }
  3029. }
  3030. if (code === CHAR_ASTERISK) {
  3031. if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
  3032. isGlob = token.isGlob = true;
  3033. finished = true;
  3034. if (scanToEnd === true) {
  3035. continue;
  3036. }
  3037. break;
  3038. }
  3039. if (code === CHAR_QUESTION_MARK) {
  3040. isGlob = token.isGlob = true;
  3041. finished = true;
  3042. if (scanToEnd === true) {
  3043. continue;
  3044. }
  3045. break;
  3046. }
  3047. if (code === CHAR_LEFT_SQUARE_BRACKET) {
  3048. while (eos() !== true && (next = advance())) {
  3049. if (next === CHAR_BACKWARD_SLASH) {
  3050. backslashes = token.backslashes = true;
  3051. advance();
  3052. continue;
  3053. }
  3054. if (next === CHAR_RIGHT_SQUARE_BRACKET) {
  3055. isBracket = token.isBracket = true;
  3056. isGlob = token.isGlob = true;
  3057. finished = true;
  3058. break;
  3059. }
  3060. }
  3061. if (scanToEnd === true) {
  3062. continue;
  3063. }
  3064. break;
  3065. }
  3066. if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
  3067. negated = token.negated = true;
  3068. start++;
  3069. continue;
  3070. }
  3071. if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
  3072. isGlob = token.isGlob = true;
  3073. if (scanToEnd === true) {
  3074. while (eos() !== true && (code = advance())) {
  3075. if (code === CHAR_LEFT_PARENTHESES) {
  3076. backslashes = token.backslashes = true;
  3077. code = advance();
  3078. continue;
  3079. }
  3080. if (code === CHAR_RIGHT_PARENTHESES) {
  3081. finished = true;
  3082. break;
  3083. }
  3084. }
  3085. continue;
  3086. }
  3087. break;
  3088. }
  3089. if (isGlob === true) {
  3090. finished = true;
  3091. if (scanToEnd === true) {
  3092. continue;
  3093. }
  3094. break;
  3095. }
  3096. }
  3097. if (opts.noext === true) {
  3098. isExtglob = false;
  3099. isGlob = false;
  3100. }
  3101. let base = str;
  3102. let prefix = '';
  3103. let glob = '';
  3104. if (start > 0) {
  3105. prefix = str.slice(0, start);
  3106. str = str.slice(start);
  3107. lastIndex -= start;
  3108. }
  3109. if (base && isGlob === true && lastIndex > 0) {
  3110. base = str.slice(0, lastIndex);
  3111. glob = str.slice(lastIndex);
  3112. } else if (isGlob === true) {
  3113. base = '';
  3114. glob = str;
  3115. } else {
  3116. base = str;
  3117. }
  3118. if (base && base !== '' && base !== '/' && base !== str) {
  3119. if (isPathSeparator(base.charCodeAt(base.length - 1))) {
  3120. base = base.slice(0, -1);
  3121. }
  3122. }
  3123. if (opts.unescape === true) {
  3124. if (glob) glob = utils$2.removeBackslashes(glob);
  3125. if (base && backslashes === true) {
  3126. base = utils$2.removeBackslashes(base);
  3127. }
  3128. }
  3129. const state = {
  3130. prefix,
  3131. input,
  3132. start,
  3133. base,
  3134. glob,
  3135. isBrace,
  3136. isBracket,
  3137. isGlob,
  3138. isExtglob,
  3139. isGlobstar,
  3140. negated,
  3141. negatedExtglob
  3142. };
  3143. if (opts.tokens === true) {
  3144. state.maxDepth = 0;
  3145. if (!isPathSeparator(code)) {
  3146. tokens.push(token);
  3147. }
  3148. state.tokens = tokens;
  3149. }
  3150. if (opts.parts === true || opts.tokens === true) {
  3151. let prevIndex;
  3152. for (let idx = 0; idx < slashes.length; idx++) {
  3153. const n = prevIndex ? prevIndex + 1 : start;
  3154. const i = slashes[idx];
  3155. const value = input.slice(n, i);
  3156. if (opts.tokens) {
  3157. if (idx === 0 && start !== 0) {
  3158. tokens[idx].isPrefix = true;
  3159. tokens[idx].value = prefix;
  3160. } else {
  3161. tokens[idx].value = value;
  3162. }
  3163. depth(tokens[idx]);
  3164. state.maxDepth += tokens[idx].depth;
  3165. }
  3166. if (idx !== 0 || value !== '') {
  3167. parts.push(value);
  3168. }
  3169. prevIndex = i;
  3170. }
  3171. if (prevIndex && prevIndex + 1 < input.length) {
  3172. const value = input.slice(prevIndex + 1);
  3173. parts.push(value);
  3174. if (opts.tokens) {
  3175. tokens[tokens.length - 1].value = value;
  3176. depth(tokens[tokens.length - 1]);
  3177. state.maxDepth += tokens[tokens.length - 1].depth;
  3178. }
  3179. }
  3180. state.slashes = slashes;
  3181. state.parts = parts;
  3182. }
  3183. return state;
  3184. };
  3185. var scan_1 = scan$1;
  3186. const constants$1 = constants$2;
  3187. const utils$1 = utils$3;
  3188. /**
  3189. * Constants
  3190. */
  3191. const {
  3192. MAX_LENGTH,
  3193. POSIX_REGEX_SOURCE,
  3194. REGEX_NON_SPECIAL_CHARS,
  3195. REGEX_SPECIAL_CHARS_BACKREF,
  3196. REPLACEMENTS
  3197. } = constants$1;
  3198. /**
  3199. * Helpers
  3200. */
  3201. const expandRange = (args, options) => {
  3202. if (typeof options.expandRange === 'function') {
  3203. return options.expandRange(...args, options);
  3204. }
  3205. args.sort();
  3206. const value = `[${args.join('-')}]`;
  3207. return value;
  3208. };
  3209. /**
  3210. * Create the message for a syntax error
  3211. */
  3212. const syntaxError = (type, char) => {
  3213. return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
  3214. };
  3215. /**
  3216. * Parse the given input string.
  3217. * @param {String} input
  3218. * @param {Object} options
  3219. * @return {Object}
  3220. */
  3221. const parse$2 = (input, options) => {
  3222. if (typeof input !== 'string') {
  3223. throw new TypeError('Expected a string');
  3224. }
  3225. input = REPLACEMENTS[input] || input;
  3226. const opts = { ...options };
  3227. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  3228. let len = input.length;
  3229. if (len > max) {
  3230. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  3231. }
  3232. const bos = { type: 'bos', value: '', output: opts.prepend || '' };
  3233. const tokens = [bos];
  3234. const capture = opts.capture ? '' : '?:';
  3235. const win32 = utils$1.isWindows(options);
  3236. // create constants based on platform, for windows or posix
  3237. const PLATFORM_CHARS = constants$1.globChars(win32);
  3238. const EXTGLOB_CHARS = constants$1.extglobChars(PLATFORM_CHARS);
  3239. const {
  3240. DOT_LITERAL,
  3241. PLUS_LITERAL,
  3242. SLASH_LITERAL,
  3243. ONE_CHAR,
  3244. DOTS_SLASH,
  3245. NO_DOT,
  3246. NO_DOT_SLASH,
  3247. NO_DOTS_SLASH,
  3248. QMARK,
  3249. QMARK_NO_DOT,
  3250. STAR,
  3251. START_ANCHOR
  3252. } = PLATFORM_CHARS;
  3253. const globstar = opts => {
  3254. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  3255. };
  3256. const nodot = opts.dot ? '' : NO_DOT;
  3257. const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
  3258. let star = opts.bash === true ? globstar(opts) : STAR;
  3259. if (opts.capture) {
  3260. star = `(${star})`;
  3261. }
  3262. // minimatch options support
  3263. if (typeof opts.noext === 'boolean') {
  3264. opts.noextglob = opts.noext;
  3265. }
  3266. const state = {
  3267. input,
  3268. index: -1,
  3269. start: 0,
  3270. dot: opts.dot === true,
  3271. consumed: '',
  3272. output: '',
  3273. prefix: '',
  3274. backtrack: false,
  3275. negated: false,
  3276. brackets: 0,
  3277. braces: 0,
  3278. parens: 0,
  3279. quotes: 0,
  3280. globstar: false,
  3281. tokens
  3282. };
  3283. input = utils$1.removePrefix(input, state);
  3284. len = input.length;
  3285. const extglobs = [];
  3286. const braces = [];
  3287. const stack = [];
  3288. let prev = bos;
  3289. let value;
  3290. /**
  3291. * Tokenizing helpers
  3292. */
  3293. const eos = () => state.index === len - 1;
  3294. const peek = state.peek = (n = 1) => input[state.index + n];
  3295. const advance = state.advance = () => input[++state.index] || '';
  3296. const remaining = () => input.slice(state.index + 1);
  3297. const consume = (value = '', num = 0) => {
  3298. state.consumed += value;
  3299. state.index += num;
  3300. };
  3301. const append = token => {
  3302. state.output += token.output != null ? token.output : token.value;
  3303. consume(token.value);
  3304. };
  3305. const negate = () => {
  3306. let count = 1;
  3307. while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
  3308. advance();
  3309. state.start++;
  3310. count++;
  3311. }
  3312. if (count % 2 === 0) {
  3313. return false;
  3314. }
  3315. state.negated = true;
  3316. state.start++;
  3317. return true;
  3318. };
  3319. const increment = type => {
  3320. state[type]++;
  3321. stack.push(type);
  3322. };
  3323. const decrement = type => {
  3324. state[type]--;
  3325. stack.pop();
  3326. };
  3327. /**
  3328. * Push tokens onto the tokens array. This helper speeds up
  3329. * tokenizing by 1) helping us avoid backtracking as much as possible,
  3330. * and 2) helping us avoid creating extra tokens when consecutive
  3331. * characters are plain text. This improves performance and simplifies
  3332. * lookbehinds.
  3333. */
  3334. const push = tok => {
  3335. if (prev.type === 'globstar') {
  3336. const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
  3337. const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));
  3338. if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
  3339. state.output = state.output.slice(0, -prev.output.length);
  3340. prev.type = 'star';
  3341. prev.value = '*';
  3342. prev.output = star;
  3343. state.output += prev.output;
  3344. }
  3345. }
  3346. if (extglobs.length && tok.type !== 'paren') {
  3347. extglobs[extglobs.length - 1].inner += tok.value;
  3348. }
  3349. if (tok.value || tok.output) append(tok);
  3350. if (prev && prev.type === 'text' && tok.type === 'text') {
  3351. prev.value += tok.value;
  3352. prev.output = (prev.output || '') + tok.value;
  3353. return;
  3354. }
  3355. tok.prev = prev;
  3356. tokens.push(tok);
  3357. prev = tok;
  3358. };
  3359. const extglobOpen = (type, value) => {
  3360. const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };
  3361. token.prev = prev;
  3362. token.parens = state.parens;
  3363. token.output = state.output;
  3364. const output = (opts.capture ? '(' : '') + token.open;
  3365. increment('parens');
  3366. push({ type, value, output: state.output ? '' : ONE_CHAR });
  3367. push({ type: 'paren', extglob: true, value: advance(), output });
  3368. extglobs.push(token);
  3369. };
  3370. const extglobClose = token => {
  3371. let output = token.close + (opts.capture ? ')' : '');
  3372. let rest;
  3373. if (token.type === 'negate') {
  3374. let extglobStar = star;
  3375. if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
  3376. extglobStar = globstar(opts);
  3377. }
  3378. if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
  3379. output = token.close = `)$))${extglobStar}`;
  3380. }
  3381. if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
  3382. // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis.
  3383. // In this case, we need to parse the string and use it in the output of the original pattern.
  3384. // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`.
  3385. //
  3386. // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`.
  3387. const expression = parse$2(rest, { ...options, fastpaths: false }).output;
  3388. output = token.close = `)${expression})${extglobStar})`;
  3389. }
  3390. if (token.prev.type === 'bos') {
  3391. state.negatedExtglob = true;
  3392. }
  3393. }
  3394. push({ type: 'paren', extglob: true, value, output });
  3395. decrement('parens');
  3396. };
  3397. /**
  3398. * Fast paths
  3399. */
  3400. if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
  3401. let backslashes = false;
  3402. let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
  3403. if (first === '\\') {
  3404. backslashes = true;
  3405. return m;
  3406. }
  3407. if (first === '?') {
  3408. if (esc) {
  3409. return esc + first + (rest ? QMARK.repeat(rest.length) : '');
  3410. }
  3411. if (index === 0) {
  3412. return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
  3413. }
  3414. return QMARK.repeat(chars.length);
  3415. }
  3416. if (first === '.') {
  3417. return DOT_LITERAL.repeat(chars.length);
  3418. }
  3419. if (first === '*') {
  3420. if (esc) {
  3421. return esc + first + (rest ? star : '');
  3422. }
  3423. return star;
  3424. }
  3425. return esc ? m : `\\${m}`;
  3426. });
  3427. if (backslashes === true) {
  3428. if (opts.unescape === true) {
  3429. output = output.replace(/\\/g, '');
  3430. } else {
  3431. output = output.replace(/\\+/g, m => {
  3432. return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
  3433. });
  3434. }
  3435. }
  3436. if (output === input && opts.contains === true) {
  3437. state.output = input;
  3438. return state;
  3439. }
  3440. state.output = utils$1.wrapOutput(output, state, options);
  3441. return state;
  3442. }
  3443. /**
  3444. * Tokenize input until we reach end-of-string
  3445. */
  3446. while (!eos()) {
  3447. value = advance();
  3448. if (value === '\u0000') {
  3449. continue;
  3450. }
  3451. /**
  3452. * Escaped characters
  3453. */
  3454. if (value === '\\') {
  3455. const next = peek();
  3456. if (next === '/' && opts.bash !== true) {
  3457. continue;
  3458. }
  3459. if (next === '.' || next === ';') {
  3460. continue;
  3461. }
  3462. if (!next) {
  3463. value += '\\';
  3464. push({ type: 'text', value });
  3465. continue;
  3466. }
  3467. // collapse slashes to reduce potential for exploits
  3468. const match = /^\\+/.exec(remaining());
  3469. let slashes = 0;
  3470. if (match && match[0].length > 2) {
  3471. slashes = match[0].length;
  3472. state.index += slashes;
  3473. if (slashes % 2 !== 0) {
  3474. value += '\\';
  3475. }
  3476. }
  3477. if (opts.unescape === true) {
  3478. value = advance();
  3479. } else {
  3480. value += advance();
  3481. }
  3482. if (state.brackets === 0) {
  3483. push({ type: 'text', value });
  3484. continue;
  3485. }
  3486. }
  3487. /**
  3488. * If we're inside a regex character class, continue
  3489. * until we reach the closing bracket.
  3490. */
  3491. if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
  3492. if (opts.posix !== false && value === ':') {
  3493. const inner = prev.value.slice(1);
  3494. if (inner.includes('[')) {
  3495. prev.posix = true;
  3496. if (inner.includes(':')) {
  3497. const idx = prev.value.lastIndexOf('[');
  3498. const pre = prev.value.slice(0, idx);
  3499. const rest = prev.value.slice(idx + 2);
  3500. const posix = POSIX_REGEX_SOURCE[rest];
  3501. if (posix) {
  3502. prev.value = pre + posix;
  3503. state.backtrack = true;
  3504. advance();
  3505. if (!bos.output && tokens.indexOf(prev) === 1) {
  3506. bos.output = ONE_CHAR;
  3507. }
  3508. continue;
  3509. }
  3510. }
  3511. }
  3512. }
  3513. if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
  3514. value = `\\${value}`;
  3515. }
  3516. if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
  3517. value = `\\${value}`;
  3518. }
  3519. if (opts.posix === true && value === '!' && prev.value === '[') {
  3520. value = '^';
  3521. }
  3522. prev.value += value;
  3523. append({ value });
  3524. continue;
  3525. }
  3526. /**
  3527. * If we're inside a quoted string, continue
  3528. * until we reach the closing double quote.
  3529. */
  3530. if (state.quotes === 1 && value !== '"') {
  3531. value = utils$1.escapeRegex(value);
  3532. prev.value += value;
  3533. append({ value });
  3534. continue;
  3535. }
  3536. /**
  3537. * Double quotes
  3538. */
  3539. if (value === '"') {
  3540. state.quotes = state.quotes === 1 ? 0 : 1;
  3541. if (opts.keepQuotes === true) {
  3542. push({ type: 'text', value });
  3543. }
  3544. continue;
  3545. }
  3546. /**
  3547. * Parentheses
  3548. */
  3549. if (value === '(') {
  3550. increment('parens');
  3551. push({ type: 'paren', value });
  3552. continue;
  3553. }
  3554. if (value === ')') {
  3555. if (state.parens === 0 && opts.strictBrackets === true) {
  3556. throw new SyntaxError(syntaxError('opening', '('));
  3557. }
  3558. const extglob = extglobs[extglobs.length - 1];
  3559. if (extglob && state.parens === extglob.parens + 1) {
  3560. extglobClose(extglobs.pop());
  3561. continue;
  3562. }
  3563. push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
  3564. decrement('parens');
  3565. continue;
  3566. }
  3567. /**
  3568. * Square brackets
  3569. */
  3570. if (value === '[') {
  3571. if (opts.nobracket === true || !remaining().includes(']')) {
  3572. if (opts.nobracket !== true && opts.strictBrackets === true) {
  3573. throw new SyntaxError(syntaxError('closing', ']'));
  3574. }
  3575. value = `\\${value}`;
  3576. } else {
  3577. increment('brackets');
  3578. }
  3579. push({ type: 'bracket', value });
  3580. continue;
  3581. }
  3582. if (value === ']') {
  3583. if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
  3584. push({ type: 'text', value, output: `\\${value}` });
  3585. continue;
  3586. }
  3587. if (state.brackets === 0) {
  3588. if (opts.strictBrackets === true) {
  3589. throw new SyntaxError(syntaxError('opening', '['));
  3590. }
  3591. push({ type: 'text', value, output: `\\${value}` });
  3592. continue;
  3593. }
  3594. decrement('brackets');
  3595. const prevValue = prev.value.slice(1);
  3596. if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
  3597. value = `/${value}`;
  3598. }
  3599. prev.value += value;
  3600. append({ value });
  3601. // when literal brackets are explicitly disabled
  3602. // assume we should match with a regex character class
  3603. if (opts.literalBrackets === false || utils$1.hasRegexChars(prevValue)) {
  3604. continue;
  3605. }
  3606. const escaped = utils$1.escapeRegex(prev.value);
  3607. state.output = state.output.slice(0, -prev.value.length);
  3608. // when literal brackets are explicitly enabled
  3609. // assume we should escape the brackets to match literal characters
  3610. if (opts.literalBrackets === true) {
  3611. state.output += escaped;
  3612. prev.value = escaped;
  3613. continue;
  3614. }
  3615. // when the user specifies nothing, try to match both
  3616. prev.value = `(${capture}${escaped}|${prev.value})`;
  3617. state.output += prev.value;
  3618. continue;
  3619. }
  3620. /**
  3621. * Braces
  3622. */
  3623. if (value === '{' && opts.nobrace !== true) {
  3624. increment('braces');
  3625. const open = {
  3626. type: 'brace',
  3627. value,
  3628. output: '(',
  3629. outputIndex: state.output.length,
  3630. tokensIndex: state.tokens.length
  3631. };
  3632. braces.push(open);
  3633. push(open);
  3634. continue;
  3635. }
  3636. if (value === '}') {
  3637. const brace = braces[braces.length - 1];
  3638. if (opts.nobrace === true || !brace) {
  3639. push({ type: 'text', value, output: value });
  3640. continue;
  3641. }
  3642. let output = ')';
  3643. if (brace.dots === true) {
  3644. const arr = tokens.slice();
  3645. const range = [];
  3646. for (let i = arr.length - 1; i >= 0; i--) {
  3647. tokens.pop();
  3648. if (arr[i].type === 'brace') {
  3649. break;
  3650. }
  3651. if (arr[i].type !== 'dots') {
  3652. range.unshift(arr[i].value);
  3653. }
  3654. }
  3655. output = expandRange(range, opts);
  3656. state.backtrack = true;
  3657. }
  3658. if (brace.comma !== true && brace.dots !== true) {
  3659. const out = state.output.slice(0, brace.outputIndex);
  3660. const toks = state.tokens.slice(brace.tokensIndex);
  3661. brace.value = brace.output = '\\{';
  3662. value = output = '\\}';
  3663. state.output = out;
  3664. for (const t of toks) {
  3665. state.output += (t.output || t.value);
  3666. }
  3667. }
  3668. push({ type: 'brace', value, output });
  3669. decrement('braces');
  3670. braces.pop();
  3671. continue;
  3672. }
  3673. /**
  3674. * Pipes
  3675. */
  3676. if (value === '|') {
  3677. if (extglobs.length > 0) {
  3678. extglobs[extglobs.length - 1].conditions++;
  3679. }
  3680. push({ type: 'text', value });
  3681. continue;
  3682. }
  3683. /**
  3684. * Commas
  3685. */
  3686. if (value === ',') {
  3687. let output = value;
  3688. const brace = braces[braces.length - 1];
  3689. if (brace && stack[stack.length - 1] === 'braces') {
  3690. brace.comma = true;
  3691. output = '|';
  3692. }
  3693. push({ type: 'comma', value, output });
  3694. continue;
  3695. }
  3696. /**
  3697. * Slashes
  3698. */
  3699. if (value === '/') {
  3700. // if the beginning of the glob is "./", advance the start
  3701. // to the current index, and don't add the "./" characters
  3702. // to the state. This greatly simplifies lookbehinds when
  3703. // checking for BOS characters like "!" and "." (not "./")
  3704. if (prev.type === 'dot' && state.index === state.start + 1) {
  3705. state.start = state.index + 1;
  3706. state.consumed = '';
  3707. state.output = '';
  3708. tokens.pop();
  3709. prev = bos; // reset "prev" to the first token
  3710. continue;
  3711. }
  3712. push({ type: 'slash', value, output: SLASH_LITERAL });
  3713. continue;
  3714. }
  3715. /**
  3716. * Dots
  3717. */
  3718. if (value === '.') {
  3719. if (state.braces > 0 && prev.type === 'dot') {
  3720. if (prev.value === '.') prev.output = DOT_LITERAL;
  3721. const brace = braces[braces.length - 1];
  3722. prev.type = 'dots';
  3723. prev.output += value;
  3724. prev.value += value;
  3725. brace.dots = true;
  3726. continue;
  3727. }
  3728. if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
  3729. push({ type: 'text', value, output: DOT_LITERAL });
  3730. continue;
  3731. }
  3732. push({ type: 'dot', value, output: DOT_LITERAL });
  3733. continue;
  3734. }
  3735. /**
  3736. * Question marks
  3737. */
  3738. if (value === '?') {
  3739. const isGroup = prev && prev.value === '(';
  3740. if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  3741. extglobOpen('qmark', value);
  3742. continue;
  3743. }
  3744. if (prev && prev.type === 'paren') {
  3745. const next = peek();
  3746. let output = value;
  3747. if (next === '<' && !utils$1.supportsLookbehinds()) {
  3748. throw new Error('Node.js v10 or higher is required for regex lookbehinds');
  3749. }
  3750. if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {
  3751. output = `\\${value}`;
  3752. }
  3753. push({ type: 'text', value, output });
  3754. continue;
  3755. }
  3756. if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
  3757. push({ type: 'qmark', value, output: QMARK_NO_DOT });
  3758. continue;
  3759. }
  3760. push({ type: 'qmark', value, output: QMARK });
  3761. continue;
  3762. }
  3763. /**
  3764. * Exclamation
  3765. */
  3766. if (value === '!') {
  3767. if (opts.noextglob !== true && peek() === '(') {
  3768. if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
  3769. extglobOpen('negate', value);
  3770. continue;
  3771. }
  3772. }
  3773. if (opts.nonegate !== true && state.index === 0) {
  3774. negate();
  3775. continue;
  3776. }
  3777. }
  3778. /**
  3779. * Plus
  3780. */
  3781. if (value === '+') {
  3782. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  3783. extglobOpen('plus', value);
  3784. continue;
  3785. }
  3786. if ((prev && prev.value === '(') || opts.regex === false) {
  3787. push({ type: 'plus', value, output: PLUS_LITERAL });
  3788. continue;
  3789. }
  3790. if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {
  3791. push({ type: 'plus', value });
  3792. continue;
  3793. }
  3794. push({ type: 'plus', value: PLUS_LITERAL });
  3795. continue;
  3796. }
  3797. /**
  3798. * Plain text
  3799. */
  3800. if (value === '@') {
  3801. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  3802. push({ type: 'at', extglob: true, value, output: '' });
  3803. continue;
  3804. }
  3805. push({ type: 'text', value });
  3806. continue;
  3807. }
  3808. /**
  3809. * Plain text
  3810. */
  3811. if (value !== '*') {
  3812. if (value === '$' || value === '^') {
  3813. value = `\\${value}`;
  3814. }
  3815. const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
  3816. if (match) {
  3817. value += match[0];
  3818. state.index += match[0].length;
  3819. }
  3820. push({ type: 'text', value });
  3821. continue;
  3822. }
  3823. /**
  3824. * Stars
  3825. */
  3826. if (prev && (prev.type === 'globstar' || prev.star === true)) {
  3827. prev.type = 'star';
  3828. prev.star = true;
  3829. prev.value += value;
  3830. prev.output = star;
  3831. state.backtrack = true;
  3832. state.globstar = true;
  3833. consume(value);
  3834. continue;
  3835. }
  3836. let rest = remaining();
  3837. if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
  3838. extglobOpen('star', value);
  3839. continue;
  3840. }
  3841. if (prev.type === 'star') {
  3842. if (opts.noglobstar === true) {
  3843. consume(value);
  3844. continue;
  3845. }
  3846. const prior = prev.prev;
  3847. const before = prior.prev;
  3848. const isStart = prior.type === 'slash' || prior.type === 'bos';
  3849. const afterStar = before && (before.type === 'star' || before.type === 'globstar');
  3850. if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {
  3851. push({ type: 'star', value, output: '' });
  3852. continue;
  3853. }
  3854. const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
  3855. const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
  3856. if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
  3857. push({ type: 'star', value, output: '' });
  3858. continue;
  3859. }
  3860. // strip consecutive `/**/`
  3861. while (rest.slice(0, 3) === '/**') {
  3862. const after = input[state.index + 4];
  3863. if (after && after !== '/') {
  3864. break;
  3865. }
  3866. rest = rest.slice(3);
  3867. consume('/**', 3);
  3868. }
  3869. if (prior.type === 'bos' && eos()) {
  3870. prev.type = 'globstar';
  3871. prev.value += value;
  3872. prev.output = globstar(opts);
  3873. state.output = prev.output;
  3874. state.globstar = true;
  3875. consume(value);
  3876. continue;
  3877. }
  3878. if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
  3879. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  3880. prior.output = `(?:${prior.output}`;
  3881. prev.type = 'globstar';
  3882. prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
  3883. prev.value += value;
  3884. state.globstar = true;
  3885. state.output += prior.output + prev.output;
  3886. consume(value);
  3887. continue;
  3888. }
  3889. if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
  3890. const end = rest[1] !== void 0 ? '|$' : '';
  3891. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  3892. prior.output = `(?:${prior.output}`;
  3893. prev.type = 'globstar';
  3894. prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
  3895. prev.value += value;
  3896. state.output += prior.output + prev.output;
  3897. state.globstar = true;
  3898. consume(value + advance());
  3899. push({ type: 'slash', value: '/', output: '' });
  3900. continue;
  3901. }
  3902. if (prior.type === 'bos' && rest[0] === '/') {
  3903. prev.type = 'globstar';
  3904. prev.value += value;
  3905. prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
  3906. state.output = prev.output;
  3907. state.globstar = true;
  3908. consume(value + advance());
  3909. push({ type: 'slash', value: '/', output: '' });
  3910. continue;
  3911. }
  3912. // remove single star from output
  3913. state.output = state.output.slice(0, -prev.output.length);
  3914. // reset previous token to globstar
  3915. prev.type = 'globstar';
  3916. prev.output = globstar(opts);
  3917. prev.value += value;
  3918. // reset output with globstar
  3919. state.output += prev.output;
  3920. state.globstar = true;
  3921. consume(value);
  3922. continue;
  3923. }
  3924. const token = { type: 'star', value, output: star };
  3925. if (opts.bash === true) {
  3926. token.output = '.*?';
  3927. if (prev.type === 'bos' || prev.type === 'slash') {
  3928. token.output = nodot + token.output;
  3929. }
  3930. push(token);
  3931. continue;
  3932. }
  3933. if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
  3934. token.output = value;
  3935. push(token);
  3936. continue;
  3937. }
  3938. if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
  3939. if (prev.type === 'dot') {
  3940. state.output += NO_DOT_SLASH;
  3941. prev.output += NO_DOT_SLASH;
  3942. } else if (opts.dot === true) {
  3943. state.output += NO_DOTS_SLASH;
  3944. prev.output += NO_DOTS_SLASH;
  3945. } else {
  3946. state.output += nodot;
  3947. prev.output += nodot;
  3948. }
  3949. if (peek() !== '*') {
  3950. state.output += ONE_CHAR;
  3951. prev.output += ONE_CHAR;
  3952. }
  3953. }
  3954. push(token);
  3955. }
  3956. while (state.brackets > 0) {
  3957. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
  3958. state.output = utils$1.escapeLast(state.output, '[');
  3959. decrement('brackets');
  3960. }
  3961. while (state.parens > 0) {
  3962. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
  3963. state.output = utils$1.escapeLast(state.output, '(');
  3964. decrement('parens');
  3965. }
  3966. while (state.braces > 0) {
  3967. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
  3968. state.output = utils$1.escapeLast(state.output, '{');
  3969. decrement('braces');
  3970. }
  3971. if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
  3972. push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
  3973. }
  3974. // rebuild the output if we had to backtrack at any point
  3975. if (state.backtrack === true) {
  3976. state.output = '';
  3977. for (const token of state.tokens) {
  3978. state.output += token.output != null ? token.output : token.value;
  3979. if (token.suffix) {
  3980. state.output += token.suffix;
  3981. }
  3982. }
  3983. }
  3984. return state;
  3985. };
  3986. /**
  3987. * Fast paths for creating regular expressions for common glob patterns.
  3988. * This can significantly speed up processing and has very little downside
  3989. * impact when none of the fast paths match.
  3990. */
  3991. parse$2.fastpaths = (input, options) => {
  3992. const opts = { ...options };
  3993. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  3994. const len = input.length;
  3995. if (len > max) {
  3996. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  3997. }
  3998. input = REPLACEMENTS[input] || input;
  3999. const win32 = utils$1.isWindows(options);
  4000. // create constants based on platform, for windows or posix
  4001. const {
  4002. DOT_LITERAL,
  4003. SLASH_LITERAL,
  4004. ONE_CHAR,
  4005. DOTS_SLASH,
  4006. NO_DOT,
  4007. NO_DOTS,
  4008. NO_DOTS_SLASH,
  4009. STAR,
  4010. START_ANCHOR
  4011. } = constants$1.globChars(win32);
  4012. const nodot = opts.dot ? NO_DOTS : NO_DOT;
  4013. const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
  4014. const capture = opts.capture ? '' : '?:';
  4015. const state = { negated: false, prefix: '' };
  4016. let star = opts.bash === true ? '.*?' : STAR;
  4017. if (opts.capture) {
  4018. star = `(${star})`;
  4019. }
  4020. const globstar = opts => {
  4021. if (opts.noglobstar === true) return star;
  4022. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  4023. };
  4024. const create = str => {
  4025. switch (str) {
  4026. case '*':
  4027. return `${nodot}${ONE_CHAR}${star}`;
  4028. case '.*':
  4029. return `${DOT_LITERAL}${ONE_CHAR}${star}`;
  4030. case '*.*':
  4031. return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  4032. case '*/*':
  4033. return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
  4034. case '**':
  4035. return nodot + globstar(opts);
  4036. case '**/*':
  4037. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
  4038. case '**/*.*':
  4039. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  4040. case '**/.*':
  4041. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
  4042. default: {
  4043. const match = /^(.*?)\.(\w+)$/.exec(str);
  4044. if (!match) return;
  4045. const source = create(match[1]);
  4046. if (!source) return;
  4047. return source + DOT_LITERAL + match[2];
  4048. }
  4049. }
  4050. };
  4051. const output = utils$1.removePrefix(input, state);
  4052. let source = create(output);
  4053. if (source && opts.strictSlashes !== true) {
  4054. source += `${SLASH_LITERAL}?`;
  4055. }
  4056. return source;
  4057. };
  4058. var parse_1 = parse$2;
  4059. const path = require$$0$1;
  4060. const scan = scan_1;
  4061. const parse$1 = parse_1;
  4062. const utils = utils$3;
  4063. const constants = constants$2;
  4064. const isObject = val => val && typeof val === 'object' && !Array.isArray(val);
  4065. /**
  4066. * Creates a matcher function from one or more glob patterns. The
  4067. * returned function takes a string to match as its first argument,
  4068. * and returns true if the string is a match. The returned matcher
  4069. * function also takes a boolean as the second argument that, when true,
  4070. * returns an object with additional information.
  4071. *
  4072. * ```js
  4073. * const picomatch = require('picomatch');
  4074. * // picomatch(glob[, options]);
  4075. *
  4076. * const isMatch = picomatch('*.!(*a)');
  4077. * console.log(isMatch('a.a')); //=> false
  4078. * console.log(isMatch('a.b')); //=> true
  4079. * ```
  4080. * @name picomatch
  4081. * @param {String|Array} `globs` One or more glob patterns.
  4082. * @param {Object=} `options`
  4083. * @return {Function=} Returns a matcher function.
  4084. * @api public
  4085. */
  4086. const picomatch$1 = (glob, options, returnState = false) => {
  4087. if (Array.isArray(glob)) {
  4088. const fns = glob.map(input => picomatch$1(input, options, returnState));
  4089. const arrayMatcher = str => {
  4090. for (const isMatch of fns) {
  4091. const state = isMatch(str);
  4092. if (state) return state;
  4093. }
  4094. return false;
  4095. };
  4096. return arrayMatcher;
  4097. }
  4098. const isState = isObject(glob) && glob.tokens && glob.input;
  4099. if (glob === '' || (typeof glob !== 'string' && !isState)) {
  4100. throw new TypeError('Expected pattern to be a non-empty string');
  4101. }
  4102. const opts = options || {};
  4103. const posix = utils.isWindows(options);
  4104. const regex = isState
  4105. ? picomatch$1.compileRe(glob, options)
  4106. : picomatch$1.makeRe(glob, options, false, true);
  4107. const state = regex.state;
  4108. delete regex.state;
  4109. let isIgnored = () => false;
  4110. if (opts.ignore) {
  4111. const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
  4112. isIgnored = picomatch$1(opts.ignore, ignoreOpts, returnState);
  4113. }
  4114. const matcher = (input, returnObject = false) => {
  4115. const { isMatch, match, output } = picomatch$1.test(input, regex, options, { glob, posix });
  4116. const result = { glob, state, regex, posix, input, output, match, isMatch };
  4117. if (typeof opts.onResult === 'function') {
  4118. opts.onResult(result);
  4119. }
  4120. if (isMatch === false) {
  4121. result.isMatch = false;
  4122. return returnObject ? result : false;
  4123. }
  4124. if (isIgnored(input)) {
  4125. if (typeof opts.onIgnore === 'function') {
  4126. opts.onIgnore(result);
  4127. }
  4128. result.isMatch = false;
  4129. return returnObject ? result : false;
  4130. }
  4131. if (typeof opts.onMatch === 'function') {
  4132. opts.onMatch(result);
  4133. }
  4134. return returnObject ? result : true;
  4135. };
  4136. if (returnState) {
  4137. matcher.state = state;
  4138. }
  4139. return matcher;
  4140. };
  4141. /**
  4142. * Test `input` with the given `regex`. This is used by the main
  4143. * `picomatch()` function to test the input string.
  4144. *
  4145. * ```js
  4146. * const picomatch = require('picomatch');
  4147. * // picomatch.test(input, regex[, options]);
  4148. *
  4149. * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
  4150. * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
  4151. * ```
  4152. * @param {String} `input` String to test.
  4153. * @param {RegExp} `regex`
  4154. * @return {Object} Returns an object with matching info.
  4155. * @api public
  4156. */
  4157. picomatch$1.test = (input, regex, options, { glob, posix } = {}) => {
  4158. if (typeof input !== 'string') {
  4159. throw new TypeError('Expected input to be a string');
  4160. }
  4161. if (input === '') {
  4162. return { isMatch: false, output: '' };
  4163. }
  4164. const opts = options || {};
  4165. const format = opts.format || (posix ? utils.toPosixSlashes : null);
  4166. let match = input === glob;
  4167. let output = (match && format) ? format(input) : input;
  4168. if (match === false) {
  4169. output = format ? format(input) : input;
  4170. match = output === glob;
  4171. }
  4172. if (match === false || opts.capture === true) {
  4173. if (opts.matchBase === true || opts.basename === true) {
  4174. match = picomatch$1.matchBase(input, regex, options, posix);
  4175. } else {
  4176. match = regex.exec(output);
  4177. }
  4178. }
  4179. return { isMatch: Boolean(match), match, output };
  4180. };
  4181. /**
  4182. * Match the basename of a filepath.
  4183. *
  4184. * ```js
  4185. * const picomatch = require('picomatch');
  4186. * // picomatch.matchBase(input, glob[, options]);
  4187. * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
  4188. * ```
  4189. * @param {String} `input` String to test.
  4190. * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
  4191. * @return {Boolean}
  4192. * @api public
  4193. */
  4194. picomatch$1.matchBase = (input, glob, options, posix = utils.isWindows(options)) => {
  4195. const regex = glob instanceof RegExp ? glob : picomatch$1.makeRe(glob, options);
  4196. return regex.test(path.basename(input));
  4197. };
  4198. /**
  4199. * Returns true if **any** of the given glob `patterns` match the specified `string`.
  4200. *
  4201. * ```js
  4202. * const picomatch = require('picomatch');
  4203. * // picomatch.isMatch(string, patterns[, options]);
  4204. *
  4205. * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
  4206. * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
  4207. * ```
  4208. * @param {String|Array} str The string to test.
  4209. * @param {String|Array} patterns One or more glob patterns to use for matching.
  4210. * @param {Object} [options] See available [options](#options).
  4211. * @return {Boolean} Returns true if any patterns match `str`
  4212. * @api public
  4213. */
  4214. picomatch$1.isMatch = (str, patterns, options) => picomatch$1(patterns, options)(str);
  4215. /**
  4216. * Parse a glob pattern to create the source string for a regular
  4217. * expression.
  4218. *
  4219. * ```js
  4220. * const picomatch = require('picomatch');
  4221. * const result = picomatch.parse(pattern[, options]);
  4222. * ```
  4223. * @param {String} `pattern`
  4224. * @param {Object} `options`
  4225. * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
  4226. * @api public
  4227. */
  4228. picomatch$1.parse = (pattern, options) => {
  4229. if (Array.isArray(pattern)) return pattern.map(p => picomatch$1.parse(p, options));
  4230. return parse$1(pattern, { ...options, fastpaths: false });
  4231. };
  4232. /**
  4233. * Scan a glob pattern to separate the pattern into segments.
  4234. *
  4235. * ```js
  4236. * const picomatch = require('picomatch');
  4237. * // picomatch.scan(input[, options]);
  4238. *
  4239. * const result = picomatch.scan('!./foo/*.js');
  4240. * console.log(result);
  4241. * { prefix: '!./',
  4242. * input: '!./foo/*.js',
  4243. * start: 3,
  4244. * base: 'foo',
  4245. * glob: '*.js',
  4246. * isBrace: false,
  4247. * isBracket: false,
  4248. * isGlob: true,
  4249. * isExtglob: false,
  4250. * isGlobstar: false,
  4251. * negated: true }
  4252. * ```
  4253. * @param {String} `input` Glob pattern to scan.
  4254. * @param {Object} `options`
  4255. * @return {Object} Returns an object with
  4256. * @api public
  4257. */
  4258. picomatch$1.scan = (input, options) => scan(input, options);
  4259. /**
  4260. * Compile a regular expression from the `state` object returned by the
  4261. * [parse()](#parse) method.
  4262. *
  4263. * @param {Object} `state`
  4264. * @param {Object} `options`
  4265. * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
  4266. * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
  4267. * @return {RegExp}
  4268. * @api public
  4269. */
  4270. picomatch$1.compileRe = (state, options, returnOutput = false, returnState = false) => {
  4271. if (returnOutput === true) {
  4272. return state.output;
  4273. }
  4274. const opts = options || {};
  4275. const prepend = opts.contains ? '' : '^';
  4276. const append = opts.contains ? '' : '$';
  4277. let source = `${prepend}(?:${state.output})${append}`;
  4278. if (state && state.negated === true) {
  4279. source = `^(?!${source}).*$`;
  4280. }
  4281. const regex = picomatch$1.toRegex(source, options);
  4282. if (returnState === true) {
  4283. regex.state = state;
  4284. }
  4285. return regex;
  4286. };
  4287. /**
  4288. * Create a regular expression from a parsed glob pattern.
  4289. *
  4290. * ```js
  4291. * const picomatch = require('picomatch');
  4292. * const state = picomatch.parse('*.js');
  4293. * // picomatch.compileRe(state[, options]);
  4294. *
  4295. * console.log(picomatch.compileRe(state));
  4296. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  4297. * ```
  4298. * @param {String} `state` The object returned from the `.parse` method.
  4299. * @param {Object} `options`
  4300. * @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.
  4301. * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
  4302. * @return {RegExp} Returns a regex created from the given pattern.
  4303. * @api public
  4304. */
  4305. picomatch$1.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
  4306. if (!input || typeof input !== 'string') {
  4307. throw new TypeError('Expected a non-empty string');
  4308. }
  4309. let parsed = { negated: false, fastpaths: true };
  4310. if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
  4311. parsed.output = parse$1.fastpaths(input, options);
  4312. }
  4313. if (!parsed.output) {
  4314. parsed = parse$1(input, options);
  4315. }
  4316. return picomatch$1.compileRe(parsed, options, returnOutput, returnState);
  4317. };
  4318. /**
  4319. * Create a regular expression from the given regex source string.
  4320. *
  4321. * ```js
  4322. * const picomatch = require('picomatch');
  4323. * // picomatch.toRegex(source[, options]);
  4324. *
  4325. * const { output } = picomatch.parse('*.js');
  4326. * console.log(picomatch.toRegex(output));
  4327. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  4328. * ```
  4329. * @param {String} `source` Regular expression source string.
  4330. * @param {Object} `options`
  4331. * @return {RegExp}
  4332. * @api public
  4333. */
  4334. picomatch$1.toRegex = (source, options) => {
  4335. try {
  4336. const opts = options || {};
  4337. return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
  4338. } catch (err) {
  4339. if (options && options.debug === true) throw err;
  4340. return /$^/;
  4341. }
  4342. };
  4343. /**
  4344. * Picomatch constants.
  4345. * @return {Object}
  4346. */
  4347. picomatch$1.constants = constants;
  4348. /**
  4349. * Expose "picomatch"
  4350. */
  4351. var picomatch_1 = picomatch$1;
  4352. var picomatch = picomatch_1;
  4353. const pm = /*@__PURE__*/getDefaultExportFromCjs(picomatch);
  4354. const extractors = {
  4355. ArrayPattern(names, param) {
  4356. for (const element of param.elements) {
  4357. if (element)
  4358. extractors[element.type](names, element);
  4359. }
  4360. },
  4361. AssignmentPattern(names, param) {
  4362. extractors[param.left.type](names, param.left);
  4363. },
  4364. Identifier(names, param) {
  4365. names.push(param.name);
  4366. },
  4367. MemberExpression() { },
  4368. ObjectPattern(names, param) {
  4369. for (const prop of param.properties) {
  4370. // @ts-ignore Typescript reports that this is not a valid type
  4371. if (prop.type === 'RestElement') {
  4372. extractors.RestElement(names, prop);
  4373. }
  4374. else {
  4375. extractors[prop.value.type](names, prop.value);
  4376. }
  4377. }
  4378. },
  4379. RestElement(names, param) {
  4380. extractors[param.argument.type](names, param.argument);
  4381. }
  4382. };
  4383. const extractAssignedNames = function extractAssignedNames(param) {
  4384. const names = [];
  4385. extractors[param.type](names, param);
  4386. return names;
  4387. };
  4388. // Helper since Typescript can't detect readonly arrays with Array.isArray
  4389. function isArray$1(arg) {
  4390. return Array.isArray(arg);
  4391. }
  4392. function ensureArray$1(thing) {
  4393. if (isArray$1(thing))
  4394. return thing;
  4395. if (thing == null)
  4396. return [];
  4397. return [thing];
  4398. }
  4399. const normalizePath = function normalizePath(filename) {
  4400. return filename.split(win32.sep).join(posix.sep);
  4401. };
  4402. function getMatcherString(id, resolutionBase) {
  4403. if (resolutionBase === false || isAbsolute$1(id) || id.startsWith('**')) {
  4404. return normalizePath(id);
  4405. }
  4406. // resolve('') is valid and will default to process.cwd()
  4407. const basePath = normalizePath(resolve$1(resolutionBase || ''))
  4408. // escape all possible (posix + win) path characters that might interfere with regex
  4409. .replace(/[-^$*+?.()|[\]{}]/g, '\\$&');
  4410. // Note that we use posix.join because:
  4411. // 1. the basePath has been normalized to use /
  4412. // 2. the incoming glob (id) matcher, also uses /
  4413. // otherwise Node will force backslash (\) on windows
  4414. return posix.join(basePath, normalizePath(id));
  4415. }
  4416. const createFilter = function createFilter(include, exclude, options) {
  4417. const resolutionBase = options && options.resolve;
  4418. const getMatcher = (id) => id instanceof RegExp
  4419. ? id
  4420. : {
  4421. test: (what) => {
  4422. // this refactor is a tad overly verbose but makes for easy debugging
  4423. const pattern = getMatcherString(id, resolutionBase);
  4424. const fn = pm(pattern, { dot: true });
  4425. const result = fn(what);
  4426. return result;
  4427. }
  4428. };
  4429. const includeMatchers = ensureArray$1(include).map(getMatcher);
  4430. const excludeMatchers = ensureArray$1(exclude).map(getMatcher);
  4431. return function result(id) {
  4432. if (typeof id !== 'string')
  4433. return false;
  4434. if (/\0/.test(id))
  4435. return false;
  4436. const pathId = normalizePath(id);
  4437. for (let i = 0; i < excludeMatchers.length; ++i) {
  4438. const matcher = excludeMatchers[i];
  4439. if (matcher.test(pathId))
  4440. return false;
  4441. }
  4442. for (let i = 0; i < includeMatchers.length; ++i) {
  4443. const matcher = includeMatchers[i];
  4444. if (matcher.test(pathId))
  4445. return true;
  4446. }
  4447. return !includeMatchers.length;
  4448. };
  4449. };
  4450. 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';
  4451. const builtins = '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';
  4452. const forbiddenIdentifiers = new Set(`${reservedWords$1} ${builtins}`.split(' '));
  4453. forbiddenIdentifiers.add('');
  4454. function createInclusionContext() {
  4455. return {
  4456. brokenFlow: false,
  4457. hasBreak: false,
  4458. hasContinue: false,
  4459. includedCallArguments: new Set(),
  4460. includedLabels: new Set()
  4461. };
  4462. }
  4463. function createHasEffectsContext() {
  4464. return {
  4465. accessed: new PathTracker(),
  4466. assigned: new PathTracker(),
  4467. brokenFlow: false,
  4468. called: new DiscriminatedPathTracker(),
  4469. hasBreak: false,
  4470. hasContinue: false,
  4471. ignore: {
  4472. breaks: false,
  4473. continues: false,
  4474. labels: new Set(),
  4475. returnYield: false,
  4476. this: false
  4477. },
  4478. includedLabels: new Set(),
  4479. instantiated: new DiscriminatedPathTracker(),
  4480. replacedVariableInits: new Map()
  4481. };
  4482. }
  4483. function assembleMemberDescriptions(memberDescriptions, inheritedDescriptions = null) {
  4484. return Object.create(inheritedDescriptions, memberDescriptions);
  4485. }
  4486. const UNDEFINED_EXPRESSION = new (class UndefinedExpression extends ExpressionEntity {
  4487. getLiteralValueAtPath() {
  4488. return undefined;
  4489. }
  4490. })();
  4491. const returnsUnknown = {
  4492. value: {
  4493. hasEffectsWhenCalled: null,
  4494. returns: UNKNOWN_EXPRESSION
  4495. }
  4496. };
  4497. const UNKNOWN_LITERAL_BOOLEAN = new (class UnknownBoolean extends ExpressionEntity {
  4498. getReturnExpressionWhenCalledAtPath(path) {
  4499. if (path.length === 1) {
  4500. return getMemberReturnExpressionWhenCalled(literalBooleanMembers, path[0]);
  4501. }
  4502. return UNKNOWN_RETURN_EXPRESSION;
  4503. }
  4504. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4505. if (interaction.type === INTERACTION_ACCESSED) {
  4506. return path.length > 1;
  4507. }
  4508. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  4509. return hasMemberEffectWhenCalled(literalBooleanMembers, path[0], interaction, context);
  4510. }
  4511. return true;
  4512. }
  4513. })();
  4514. const returnsBoolean = {
  4515. value: {
  4516. hasEffectsWhenCalled: null,
  4517. returns: UNKNOWN_LITERAL_BOOLEAN
  4518. }
  4519. };
  4520. const UNKNOWN_LITERAL_NUMBER = new (class UnknownNumber extends ExpressionEntity {
  4521. getReturnExpressionWhenCalledAtPath(path) {
  4522. if (path.length === 1) {
  4523. return getMemberReturnExpressionWhenCalled(literalNumberMembers, path[0]);
  4524. }
  4525. return UNKNOWN_RETURN_EXPRESSION;
  4526. }
  4527. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4528. if (interaction.type === INTERACTION_ACCESSED) {
  4529. return path.length > 1;
  4530. }
  4531. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  4532. return hasMemberEffectWhenCalled(literalNumberMembers, path[0], interaction, context);
  4533. }
  4534. return true;
  4535. }
  4536. })();
  4537. const returnsNumber = {
  4538. value: {
  4539. hasEffectsWhenCalled: null,
  4540. returns: UNKNOWN_LITERAL_NUMBER
  4541. }
  4542. };
  4543. const UNKNOWN_LITERAL_STRING = new (class UnknownString extends ExpressionEntity {
  4544. getReturnExpressionWhenCalledAtPath(path) {
  4545. if (path.length === 1) {
  4546. return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
  4547. }
  4548. return UNKNOWN_RETURN_EXPRESSION;
  4549. }
  4550. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4551. if (interaction.type === INTERACTION_ACCESSED) {
  4552. return path.length > 1;
  4553. }
  4554. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  4555. return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
  4556. }
  4557. return true;
  4558. }
  4559. })();
  4560. const returnsString = {
  4561. value: {
  4562. hasEffectsWhenCalled: null,
  4563. returns: UNKNOWN_LITERAL_STRING
  4564. }
  4565. };
  4566. const stringReplace = {
  4567. value: {
  4568. hasEffectsWhenCalled({ args }, context) {
  4569. const argument1 = args[2];
  4570. return (args.length < 3 ||
  4571. (typeof argument1.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, {
  4572. deoptimizeCache() { }
  4573. }) === 'symbol' &&
  4574. argument1.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)));
  4575. },
  4576. returns: UNKNOWN_LITERAL_STRING
  4577. }
  4578. };
  4579. const objectMembers = assembleMemberDescriptions({
  4580. hasOwnProperty: returnsBoolean,
  4581. isPrototypeOf: returnsBoolean,
  4582. propertyIsEnumerable: returnsBoolean,
  4583. toLocaleString: returnsString,
  4584. toString: returnsString,
  4585. valueOf: returnsUnknown
  4586. });
  4587. const literalBooleanMembers = assembleMemberDescriptions({
  4588. valueOf: returnsBoolean
  4589. }, objectMembers);
  4590. const literalNumberMembers = assembleMemberDescriptions({
  4591. toExponential: returnsString,
  4592. toFixed: returnsString,
  4593. toLocaleString: returnsString,
  4594. toPrecision: returnsString,
  4595. valueOf: returnsNumber
  4596. }, objectMembers);
  4597. /**
  4598. * RegExp are stateful when they have the global or sticky flags set.
  4599. * But if we actually don't use them, the side effect does not matter.
  4600. * the check logic in `hasEffectsOnInteractionAtPath`.
  4601. */
  4602. const literalRegExpMembers = assembleMemberDescriptions({
  4603. exec: returnsUnknown,
  4604. test: returnsBoolean
  4605. }, objectMembers);
  4606. const literalStringMembers = assembleMemberDescriptions({
  4607. anchor: returnsString,
  4608. at: returnsUnknown,
  4609. big: returnsString,
  4610. blink: returnsString,
  4611. bold: returnsString,
  4612. charAt: returnsString,
  4613. charCodeAt: returnsNumber,
  4614. codePointAt: returnsUnknown,
  4615. concat: returnsString,
  4616. endsWith: returnsBoolean,
  4617. fixed: returnsString,
  4618. fontcolor: returnsString,
  4619. fontsize: returnsString,
  4620. includes: returnsBoolean,
  4621. indexOf: returnsNumber,
  4622. italics: returnsString,
  4623. lastIndexOf: returnsNumber,
  4624. link: returnsString,
  4625. localeCompare: returnsNumber,
  4626. match: returnsUnknown,
  4627. matchAll: returnsUnknown,
  4628. normalize: returnsString,
  4629. padEnd: returnsString,
  4630. padStart: returnsString,
  4631. repeat: returnsString,
  4632. replace: stringReplace,
  4633. replaceAll: stringReplace,
  4634. search: returnsNumber,
  4635. slice: returnsString,
  4636. small: returnsString,
  4637. split: returnsUnknown,
  4638. startsWith: returnsBoolean,
  4639. strike: returnsString,
  4640. sub: returnsString,
  4641. substr: returnsString,
  4642. substring: returnsString,
  4643. sup: returnsString,
  4644. toLocaleLowerCase: returnsString,
  4645. toLocaleUpperCase: returnsString,
  4646. toLowerCase: returnsString,
  4647. toString: returnsString,
  4648. toUpperCase: returnsString,
  4649. trim: returnsString,
  4650. trimEnd: returnsString,
  4651. trimLeft: returnsString,
  4652. trimRight: returnsString,
  4653. trimStart: returnsString,
  4654. valueOf: returnsString
  4655. }, objectMembers);
  4656. function getLiteralMembersForValue(value) {
  4657. if (value instanceof RegExp) {
  4658. return literalRegExpMembers;
  4659. }
  4660. switch (typeof value) {
  4661. case 'boolean': {
  4662. return literalBooleanMembers;
  4663. }
  4664. case 'number': {
  4665. return literalNumberMembers;
  4666. }
  4667. case 'string': {
  4668. return literalStringMembers;
  4669. }
  4670. }
  4671. return Object.create(null);
  4672. }
  4673. function hasMemberEffectWhenCalled(members, memberName, interaction, context) {
  4674. if (typeof memberName !== 'string' || !members[memberName]) {
  4675. return true;
  4676. }
  4677. return members[memberName].hasEffectsWhenCalled?.(interaction, context) || false;
  4678. }
  4679. function getMemberReturnExpressionWhenCalled(members, memberName) {
  4680. if (typeof memberName !== 'string' || !members[memberName])
  4681. return UNKNOWN_RETURN_EXPRESSION;
  4682. return [members[memberName].returns, false];
  4683. }
  4684. // AST walker module for Mozilla Parser API compatible trees
  4685. function skipThrough(node, st, c) { c(node, st); }
  4686. function ignore(_node, _st, _c) {}
  4687. // Node walkers.
  4688. var base$1 = {};
  4689. base$1.Program = base$1.BlockStatement = base$1.StaticBlock = function (node, st, c) {
  4690. for (var i = 0, list = node.body; i < list.length; i += 1)
  4691. {
  4692. var stmt = list[i];
  4693. c(stmt, st, "Statement");
  4694. }
  4695. };
  4696. base$1.Statement = skipThrough;
  4697. base$1.EmptyStatement = ignore;
  4698. base$1.ExpressionStatement = base$1.ParenthesizedExpression = base$1.ChainExpression =
  4699. function (node, st, c) { return c(node.expression, st, "Expression"); };
  4700. base$1.IfStatement = function (node, st, c) {
  4701. c(node.test, st, "Expression");
  4702. c(node.consequent, st, "Statement");
  4703. if (node.alternate) { c(node.alternate, st, "Statement"); }
  4704. };
  4705. base$1.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); };
  4706. base$1.BreakStatement = base$1.ContinueStatement = ignore;
  4707. base$1.WithStatement = function (node, st, c) {
  4708. c(node.object, st, "Expression");
  4709. c(node.body, st, "Statement");
  4710. };
  4711. base$1.SwitchStatement = function (node, st, c) {
  4712. c(node.discriminant, st, "Expression");
  4713. for (var i$1 = 0, list$1 = node.cases; i$1 < list$1.length; i$1 += 1) {
  4714. var cs = list$1[i$1];
  4715. if (cs.test) { c(cs.test, st, "Expression"); }
  4716. for (var i = 0, list = cs.consequent; i < list.length; i += 1)
  4717. {
  4718. var cons = list[i];
  4719. c(cons, st, "Statement");
  4720. }
  4721. }
  4722. };
  4723. base$1.SwitchCase = function (node, st, c) {
  4724. if (node.test) { c(node.test, st, "Expression"); }
  4725. for (var i = 0, list = node.consequent; i < list.length; i += 1)
  4726. {
  4727. var cons = list[i];
  4728. c(cons, st, "Statement");
  4729. }
  4730. };
  4731. base$1.ReturnStatement = base$1.YieldExpression = base$1.AwaitExpression = function (node, st, c) {
  4732. if (node.argument) { c(node.argument, st, "Expression"); }
  4733. };
  4734. base$1.ThrowStatement = base$1.SpreadElement =
  4735. function (node, st, c) { return c(node.argument, st, "Expression"); };
  4736. base$1.TryStatement = function (node, st, c) {
  4737. c(node.block, st, "Statement");
  4738. if (node.handler) { c(node.handler, st); }
  4739. if (node.finalizer) { c(node.finalizer, st, "Statement"); }
  4740. };
  4741. base$1.CatchClause = function (node, st, c) {
  4742. if (node.param) { c(node.param, st, "Pattern"); }
  4743. c(node.body, st, "Statement");
  4744. };
  4745. base$1.WhileStatement = base$1.DoWhileStatement = function (node, st, c) {
  4746. c(node.test, st, "Expression");
  4747. c(node.body, st, "Statement");
  4748. };
  4749. base$1.ForStatement = function (node, st, c) {
  4750. if (node.init) { c(node.init, st, "ForInit"); }
  4751. if (node.test) { c(node.test, st, "Expression"); }
  4752. if (node.update) { c(node.update, st, "Expression"); }
  4753. c(node.body, st, "Statement");
  4754. };
  4755. base$1.ForInStatement = base$1.ForOfStatement = function (node, st, c) {
  4756. c(node.left, st, "ForInit");
  4757. c(node.right, st, "Expression");
  4758. c(node.body, st, "Statement");
  4759. };
  4760. base$1.ForInit = function (node, st, c) {
  4761. if (node.type === "VariableDeclaration") { c(node, st); }
  4762. else { c(node, st, "Expression"); }
  4763. };
  4764. base$1.DebuggerStatement = ignore;
  4765. base$1.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); };
  4766. base$1.VariableDeclaration = function (node, st, c) {
  4767. for (var i = 0, list = node.declarations; i < list.length; i += 1)
  4768. {
  4769. var decl = list[i];
  4770. c(decl, st);
  4771. }
  4772. };
  4773. base$1.VariableDeclarator = function (node, st, c) {
  4774. c(node.id, st, "Pattern");
  4775. if (node.init) { c(node.init, st, "Expression"); }
  4776. };
  4777. base$1.Function = function (node, st, c) {
  4778. if (node.id) { c(node.id, st, "Pattern"); }
  4779. for (var i = 0, list = node.params; i < list.length; i += 1)
  4780. {
  4781. var param = list[i];
  4782. c(param, st, "Pattern");
  4783. }
  4784. c(node.body, st, node.expression ? "Expression" : "Statement");
  4785. };
  4786. base$1.Pattern = function (node, st, c) {
  4787. if (node.type === "Identifier")
  4788. { c(node, st, "VariablePattern"); }
  4789. else if (node.type === "MemberExpression")
  4790. { c(node, st, "MemberPattern"); }
  4791. else
  4792. { c(node, st); }
  4793. };
  4794. base$1.VariablePattern = ignore;
  4795. base$1.MemberPattern = skipThrough;
  4796. base$1.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); };
  4797. base$1.ArrayPattern = function (node, st, c) {
  4798. for (var i = 0, list = node.elements; i < list.length; i += 1) {
  4799. var elt = list[i];
  4800. if (elt) { c(elt, st, "Pattern"); }
  4801. }
  4802. };
  4803. base$1.ObjectPattern = function (node, st, c) {
  4804. for (var i = 0, list = node.properties; i < list.length; i += 1) {
  4805. var prop = list[i];
  4806. if (prop.type === "Property") {
  4807. if (prop.computed) { c(prop.key, st, "Expression"); }
  4808. c(prop.value, st, "Pattern");
  4809. } else if (prop.type === "RestElement") {
  4810. c(prop.argument, st, "Pattern");
  4811. }
  4812. }
  4813. };
  4814. base$1.Expression = skipThrough;
  4815. base$1.ThisExpression = base$1.Super = base$1.MetaProperty = ignore;
  4816. base$1.ArrayExpression = function (node, st, c) {
  4817. for (var i = 0, list = node.elements; i < list.length; i += 1) {
  4818. var elt = list[i];
  4819. if (elt) { c(elt, st, "Expression"); }
  4820. }
  4821. };
  4822. base$1.ObjectExpression = function (node, st, c) {
  4823. for (var i = 0, list = node.properties; i < list.length; i += 1)
  4824. {
  4825. var prop = list[i];
  4826. c(prop, st);
  4827. }
  4828. };
  4829. base$1.FunctionExpression = base$1.ArrowFunctionExpression = base$1.FunctionDeclaration;
  4830. base$1.SequenceExpression = function (node, st, c) {
  4831. for (var i = 0, list = node.expressions; i < list.length; i += 1)
  4832. {
  4833. var expr = list[i];
  4834. c(expr, st, "Expression");
  4835. }
  4836. };
  4837. base$1.TemplateLiteral = function (node, st, c) {
  4838. for (var i = 0, list = node.quasis; i < list.length; i += 1)
  4839. {
  4840. var quasi = list[i];
  4841. c(quasi, st);
  4842. }
  4843. for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1)
  4844. {
  4845. var expr = list$1[i$1];
  4846. c(expr, st, "Expression");
  4847. }
  4848. };
  4849. base$1.TemplateElement = ignore;
  4850. base$1.UnaryExpression = base$1.UpdateExpression = function (node, st, c) {
  4851. c(node.argument, st, "Expression");
  4852. };
  4853. base$1.BinaryExpression = base$1.LogicalExpression = function (node, st, c) {
  4854. c(node.left, st, "Expression");
  4855. c(node.right, st, "Expression");
  4856. };
  4857. base$1.AssignmentExpression = base$1.AssignmentPattern = function (node, st, c) {
  4858. c(node.left, st, "Pattern");
  4859. c(node.right, st, "Expression");
  4860. };
  4861. base$1.ConditionalExpression = function (node, st, c) {
  4862. c(node.test, st, "Expression");
  4863. c(node.consequent, st, "Expression");
  4864. c(node.alternate, st, "Expression");
  4865. };
  4866. base$1.NewExpression = base$1.CallExpression = function (node, st, c) {
  4867. c(node.callee, st, "Expression");
  4868. if (node.arguments)
  4869. { for (var i = 0, list = node.arguments; i < list.length; i += 1)
  4870. {
  4871. var arg = list[i];
  4872. c(arg, st, "Expression");
  4873. } }
  4874. };
  4875. base$1.MemberExpression = function (node, st, c) {
  4876. c(node.object, st, "Expression");
  4877. if (node.computed) { c(node.property, st, "Expression"); }
  4878. };
  4879. base$1.ExportNamedDeclaration = base$1.ExportDefaultDeclaration = function (node, st, c) {
  4880. if (node.declaration)
  4881. { c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); }
  4882. if (node.source) { c(node.source, st, "Expression"); }
  4883. };
  4884. base$1.ExportAllDeclaration = function (node, st, c) {
  4885. if (node.exported)
  4886. { c(node.exported, st); }
  4887. c(node.source, st, "Expression");
  4888. };
  4889. base$1.ImportDeclaration = function (node, st, c) {
  4890. for (var i = 0, list = node.specifiers; i < list.length; i += 1)
  4891. {
  4892. var spec = list[i];
  4893. c(spec, st);
  4894. }
  4895. c(node.source, st, "Expression");
  4896. };
  4897. base$1.ImportExpression = function (node, st, c) {
  4898. c(node.source, st, "Expression");
  4899. };
  4900. base$1.ImportSpecifier = base$1.ImportDefaultSpecifier = base$1.ImportNamespaceSpecifier = base$1.Identifier = base$1.PrivateIdentifier = base$1.Literal = ignore;
  4901. base$1.TaggedTemplateExpression = function (node, st, c) {
  4902. c(node.tag, st, "Expression");
  4903. c(node.quasi, st, "Expression");
  4904. };
  4905. base$1.ClassDeclaration = base$1.ClassExpression = function (node, st, c) { return c(node, st, "Class"); };
  4906. base$1.Class = function (node, st, c) {
  4907. if (node.id) { c(node.id, st, "Pattern"); }
  4908. if (node.superClass) { c(node.superClass, st, "Expression"); }
  4909. c(node.body, st);
  4910. };
  4911. base$1.ClassBody = function (node, st, c) {
  4912. for (var i = 0, list = node.body; i < list.length; i += 1)
  4913. {
  4914. var elt = list[i];
  4915. c(elt, st);
  4916. }
  4917. };
  4918. base$1.MethodDefinition = base$1.PropertyDefinition = base$1.Property = function (node, st, c) {
  4919. if (node.computed) { c(node.key, st, "Expression"); }
  4920. if (node.value) { c(node.value, st, "Expression"); }
  4921. };
  4922. const ArrowFunctionExpression$1 = 'ArrowFunctionExpression';
  4923. const BinaryExpression$1 = 'BinaryExpression';
  4924. const BlockStatement$1 = 'BlockStatement';
  4925. const CallExpression$1 = 'CallExpression';
  4926. const ChainExpression$1 = 'ChainExpression';
  4927. const ConditionalExpression$1 = 'ConditionalExpression';
  4928. const ExportDefaultDeclaration$1 = 'ExportDefaultDeclaration';
  4929. const ExportNamedDeclaration$1 = 'ExportNamedDeclaration';
  4930. const ExpressionStatement$1 = 'ExpressionStatement';
  4931. const FunctionDeclaration$1 = 'FunctionDeclaration';
  4932. const Identifier$1 = 'Identifier';
  4933. const LogicalExpression$1 = 'LogicalExpression';
  4934. const NewExpression$1 = 'NewExpression';
  4935. const Program$1 = 'Program';
  4936. const Property$1 = 'Property';
  4937. const ReturnStatement$1 = 'ReturnStatement';
  4938. const SequenceExpression$1 = 'SequenceExpression';
  4939. const VariableDeclarator$1 = 'VariableDeclarator';
  4940. const VariableDeclaration$1 = 'VariableDeclaration';
  4941. // this looks ridiculous, but it prevents sourcemap tooling from mistaking
  4942. // this for an actual sourceMappingURL
  4943. let SOURCEMAPPING_URL = 'sourceMa';
  4944. SOURCEMAPPING_URL += 'ppingURL';
  4945. const whiteSpaceNoNewline = '[ \\f\\r\\t\\v\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]';
  4946. const SOURCEMAPPING_URL_RE = new RegExp(`^#${whiteSpaceNoNewline}+${SOURCEMAPPING_URL}=.+`);
  4947. const ANNOTATION_KEY = '_rollupAnnotations';
  4948. const INVALID_COMMENT_KEY = '_rollupRemoved';
  4949. function handlePureAnnotationsOfNode(node, state, type = node.type) {
  4950. const { annotations, code } = state;
  4951. // eslint-disable-next-line unicorn/consistent-destructuring
  4952. let comment = annotations[state.annotationIndex];
  4953. while (comment && node.start >= comment.end) {
  4954. markPureNode(node, comment, code);
  4955. comment = annotations[++state.annotationIndex];
  4956. }
  4957. if (comment && comment.end <= node.end) {
  4958. base$1[type](node, state, handlePureAnnotationsOfNode);
  4959. // eslint-disable-next-line unicorn/consistent-destructuring
  4960. while ((comment = annotations[state.annotationIndex]) && comment.end <= node.end) {
  4961. ++state.annotationIndex;
  4962. annotateNode(node, comment, false);
  4963. }
  4964. }
  4965. }
  4966. const neitherWithespaceNorBrackets = /[^\s(]/g;
  4967. const noWhitespace = /\S/g;
  4968. function markPureNode(node, comment, code) {
  4969. const annotatedNodes = [];
  4970. let invalidAnnotation;
  4971. const codeInBetween = code.slice(comment.end, node.start);
  4972. if (doesNotMatchOutsideComment(codeInBetween, neitherWithespaceNorBrackets)) {
  4973. const parentStart = node.start;
  4974. while (true) {
  4975. annotatedNodes.push(node);
  4976. switch (node.type) {
  4977. case ExpressionStatement$1:
  4978. case ChainExpression$1: {
  4979. node = node.expression;
  4980. continue;
  4981. }
  4982. case SequenceExpression$1: {
  4983. // if there are parentheses, the annotation would apply to the entire expression
  4984. if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) {
  4985. node = node.expressions[0];
  4986. continue;
  4987. }
  4988. invalidAnnotation = true;
  4989. break;
  4990. }
  4991. case ConditionalExpression$1: {
  4992. // if there are parentheses, the annotation would apply to the entire expression
  4993. if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) {
  4994. node = node.test;
  4995. continue;
  4996. }
  4997. invalidAnnotation = true;
  4998. break;
  4999. }
  5000. case LogicalExpression$1:
  5001. case BinaryExpression$1: {
  5002. // if there are parentheses, the annotation would apply to the entire expression
  5003. if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) {
  5004. node = node.left;
  5005. continue;
  5006. }
  5007. invalidAnnotation = true;
  5008. break;
  5009. }
  5010. case ExportNamedDeclaration$1:
  5011. case ExportDefaultDeclaration$1: {
  5012. node = node.declaration;
  5013. continue;
  5014. }
  5015. case VariableDeclaration$1: {
  5016. const declaration = node;
  5017. if (declaration.kind === 'const') {
  5018. // jsdoc only applies to the first declaration
  5019. node = declaration.declarations[0].init;
  5020. continue;
  5021. }
  5022. invalidAnnotation = true;
  5023. break;
  5024. }
  5025. case VariableDeclarator$1: {
  5026. node = node.init;
  5027. continue;
  5028. }
  5029. case FunctionDeclaration$1:
  5030. case ArrowFunctionExpression$1:
  5031. case CallExpression$1:
  5032. case NewExpression$1: {
  5033. break;
  5034. }
  5035. default: {
  5036. invalidAnnotation = true;
  5037. }
  5038. }
  5039. break;
  5040. }
  5041. }
  5042. else {
  5043. invalidAnnotation = true;
  5044. }
  5045. if (invalidAnnotation) {
  5046. annotateNode(node, comment, false);
  5047. }
  5048. else {
  5049. for (const node of annotatedNodes) {
  5050. annotateNode(node, comment, true);
  5051. }
  5052. }
  5053. }
  5054. function doesNotMatchOutsideComment(code, forbiddenChars) {
  5055. let nextMatch;
  5056. while ((nextMatch = forbiddenChars.exec(code)) !== null) {
  5057. if (nextMatch[0] === '/') {
  5058. const charCodeAfterSlash = code.charCodeAt(forbiddenChars.lastIndex);
  5059. if (charCodeAfterSlash === 42 /*"*"*/) {
  5060. forbiddenChars.lastIndex = code.indexOf('*/', forbiddenChars.lastIndex + 1) + 2;
  5061. continue;
  5062. }
  5063. else if (charCodeAfterSlash === 47 /*"/"*/) {
  5064. forbiddenChars.lastIndex = code.indexOf('\n', forbiddenChars.lastIndex + 1) + 1;
  5065. continue;
  5066. }
  5067. }
  5068. forbiddenChars.lastIndex = 0;
  5069. return false;
  5070. }
  5071. return true;
  5072. }
  5073. const annotationsRegexes = [
  5074. ['pure', /[#@]__PURE__/],
  5075. ['noSideEffects', /[#@]__NO_SIDE_EFFECTS__/]
  5076. ];
  5077. function addAnnotations(comments, esTreeAst, code) {
  5078. const annotations = [];
  5079. const sourceMappingComments = [];
  5080. for (const comment of comments) {
  5081. for (const [annotationType, regex] of annotationsRegexes) {
  5082. if (regex.test(comment.value)) {
  5083. annotations.push({ ...comment, annotationType });
  5084. }
  5085. }
  5086. if (SOURCEMAPPING_URL_RE.test(comment.value)) {
  5087. sourceMappingComments.push(comment);
  5088. }
  5089. }
  5090. for (const comment of sourceMappingComments) {
  5091. annotateNode(esTreeAst, comment, false);
  5092. }
  5093. handlePureAnnotationsOfNode(esTreeAst, {
  5094. annotationIndex: 0,
  5095. annotations,
  5096. code
  5097. });
  5098. }
  5099. function annotateNode(node, comment, valid) {
  5100. const key = valid ? ANNOTATION_KEY : INVALID_COMMENT_KEY;
  5101. const property = node[key];
  5102. if (property) {
  5103. property.push(comment);
  5104. }
  5105. else {
  5106. node[key] = [comment];
  5107. }
  5108. }
  5109. const keys = {
  5110. // TODO this should be removed once ImportExpression follows official ESTree
  5111. // specs with "null" as default
  5112. ImportExpression: ['arguments'],
  5113. Literal: [],
  5114. Program: ['body']
  5115. };
  5116. function getAndCreateKeys(esTreeNode) {
  5117. keys[esTreeNode.type] = Object.keys(esTreeNode).filter(key => typeof esTreeNode[key] === 'object' && key.charCodeAt(0) !== 95 /* _ */);
  5118. return keys[esTreeNode.type];
  5119. }
  5120. const INCLUDE_PARAMETERS = 'variables';
  5121. class NodeBase extends ExpressionEntity {
  5122. constructor(esTreeNode, parent, parentScope, keepEsTreeNode = false) {
  5123. super();
  5124. /**
  5125. * Nodes can apply custom deoptimizations once they become part of the
  5126. * executed code. To do this, they must initialize this as false, implement
  5127. * applyDeoptimizations and call this from include and hasEffects if they have
  5128. * custom handlers
  5129. */
  5130. this.deoptimized = false;
  5131. // Nodes can opt-in to keep the AST if needed during the build pipeline.
  5132. // Avoid true when possible as large AST takes up memory.
  5133. this.esTreeNode = keepEsTreeNode ? esTreeNode : null;
  5134. this.keys = keys[esTreeNode.type] || getAndCreateKeys(esTreeNode);
  5135. this.parent = parent;
  5136. this.context = parent.context;
  5137. this.createScope(parentScope);
  5138. this.parseNode(esTreeNode);
  5139. this.initialise();
  5140. this.context.magicString.addSourcemapLocation(this.start);
  5141. this.context.magicString.addSourcemapLocation(this.end);
  5142. }
  5143. addExportedVariables(_variables, _exportNamesByVariable) { }
  5144. /**
  5145. * Override this to bind assignments to variables and do any initialisations
  5146. * that require the scopes to be populated with variables.
  5147. */
  5148. bind() {
  5149. for (const key of this.keys) {
  5150. const value = this[key];
  5151. if (Array.isArray(value)) {
  5152. for (const child of value) {
  5153. child?.bind();
  5154. }
  5155. }
  5156. else if (value) {
  5157. value.bind();
  5158. }
  5159. }
  5160. }
  5161. /**
  5162. * Override if this node should receive a different scope than the parent
  5163. * scope.
  5164. */
  5165. createScope(parentScope) {
  5166. this.scope = parentScope;
  5167. }
  5168. hasEffects(context) {
  5169. if (!this.deoptimized)
  5170. this.applyDeoptimizations();
  5171. for (const key of this.keys) {
  5172. const value = this[key];
  5173. if (value === null)
  5174. continue;
  5175. if (Array.isArray(value)) {
  5176. for (const child of value) {
  5177. if (child?.hasEffects(context))
  5178. return true;
  5179. }
  5180. }
  5181. else if (value.hasEffects(context))
  5182. return true;
  5183. }
  5184. return false;
  5185. }
  5186. hasEffectsAsAssignmentTarget(context, _checkAccess) {
  5187. return (this.hasEffects(context) ||
  5188. this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
  5189. }
  5190. include(context, includeChildrenRecursively, _options) {
  5191. if (!this.deoptimized)
  5192. this.applyDeoptimizations();
  5193. this.included = true;
  5194. for (const key of this.keys) {
  5195. const value = this[key];
  5196. if (value === null)
  5197. continue;
  5198. if (Array.isArray(value)) {
  5199. for (const child of value) {
  5200. child?.include(context, includeChildrenRecursively);
  5201. }
  5202. }
  5203. else {
  5204. value.include(context, includeChildrenRecursively);
  5205. }
  5206. }
  5207. }
  5208. includeAsAssignmentTarget(context, includeChildrenRecursively, _deoptimizeAccess) {
  5209. this.include(context, includeChildrenRecursively);
  5210. }
  5211. /**
  5212. * Override to perform special initialisation steps after the scope is
  5213. * initialised
  5214. */
  5215. initialise() { }
  5216. insertSemicolon(code) {
  5217. if (code.original[this.end - 1] !== ';') {
  5218. code.appendLeft(this.end, ';');
  5219. }
  5220. }
  5221. parseNode(esTreeNode, keepEsTreeNodeKeys) {
  5222. for (const [key, value] of Object.entries(esTreeNode)) {
  5223. // That way, we can override this function to add custom initialisation and then call super.parseNode
  5224. if (this.hasOwnProperty(key))
  5225. continue;
  5226. if (key.charCodeAt(0) === 95 /* _ */) {
  5227. if (key === ANNOTATION_KEY) {
  5228. const annotations = value;
  5229. this.annotations = annotations;
  5230. if (this.context.options.treeshake.annotations) {
  5231. this.annotationNoSideEffects = annotations.some(comment => comment.annotationType === 'noSideEffects');
  5232. this.annotationPure = annotations.some(comment => comment.annotationType === 'pure');
  5233. }
  5234. }
  5235. else if (key === INVALID_COMMENT_KEY) {
  5236. for (const { start, end } of value)
  5237. this.context.magicString.remove(start, end);
  5238. }
  5239. }
  5240. else if (typeof value !== 'object' || value === null) {
  5241. this[key] = value;
  5242. }
  5243. else if (Array.isArray(value)) {
  5244. this[key] = [];
  5245. for (const child of value) {
  5246. this[key].push(child === null
  5247. ? null
  5248. : new (this.context.getNodeConstructor(child.type))(child, this, this.scope, keepEsTreeNodeKeys?.includes(key)));
  5249. }
  5250. }
  5251. else {
  5252. this[key] = new (this.context.getNodeConstructor(value.type))(value, this, this.scope, keepEsTreeNodeKeys?.includes(key));
  5253. }
  5254. }
  5255. }
  5256. render(code, options) {
  5257. for (const key of this.keys) {
  5258. const value = this[key];
  5259. if (value === null)
  5260. continue;
  5261. if (Array.isArray(value)) {
  5262. for (const child of value) {
  5263. child?.render(code, options);
  5264. }
  5265. }
  5266. else {
  5267. value.render(code, options);
  5268. }
  5269. }
  5270. }
  5271. setAssignedValue(value) {
  5272. this.assignmentInteraction = { args: [null, value], type: INTERACTION_ASSIGNED };
  5273. }
  5274. shouldBeIncluded(context) {
  5275. return this.included || (!context.brokenFlow && this.hasEffects(createHasEffectsContext()));
  5276. }
  5277. /**
  5278. * Just deoptimize everything by default so that when e.g. we do not track
  5279. * something properly, it is deoptimized.
  5280. * @protected
  5281. */
  5282. applyDeoptimizations() {
  5283. this.deoptimized = true;
  5284. for (const key of this.keys) {
  5285. const value = this[key];
  5286. if (value === null)
  5287. continue;
  5288. if (Array.isArray(value)) {
  5289. for (const child of value) {
  5290. child?.deoptimizePath(UNKNOWN_PATH);
  5291. }
  5292. }
  5293. else {
  5294. value.deoptimizePath(UNKNOWN_PATH);
  5295. }
  5296. }
  5297. this.context.requestTreeshakingPass();
  5298. }
  5299. }
  5300. class SpreadElement extends NodeBase {
  5301. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  5302. if (path.length > 0) {
  5303. this.argument.deoptimizeArgumentsOnInteractionAtPath(interaction, [UnknownKey, ...path], recursionTracker);
  5304. }
  5305. }
  5306. hasEffects(context) {
  5307. if (!this.deoptimized)
  5308. this.applyDeoptimizations();
  5309. const { propertyReadSideEffects } = this.context.options
  5310. .treeshake;
  5311. return (this.argument.hasEffects(context) ||
  5312. (propertyReadSideEffects &&
  5313. (propertyReadSideEffects === 'always' ||
  5314. this.argument.hasEffectsOnInteractionAtPath(UNKNOWN_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context))));
  5315. }
  5316. applyDeoptimizations() {
  5317. this.deoptimized = true;
  5318. // Only properties of properties of the argument could become subject to reassignment
  5319. // This will also reassign the return values of iterators
  5320. this.argument.deoptimizePath([UnknownKey, UnknownKey]);
  5321. this.context.requestTreeshakingPass();
  5322. }
  5323. }
  5324. class Method extends ExpressionEntity {
  5325. constructor(description) {
  5326. super();
  5327. this.description = description;
  5328. }
  5329. deoptimizeArgumentsOnInteractionAtPath({ args, type }, path) {
  5330. if (type === INTERACTION_CALLED && path.length === 0 && this.description.mutatesSelfAsArray) {
  5331. args[0]?.deoptimizePath(UNKNOWN_INTEGER_PATH);
  5332. }
  5333. }
  5334. getReturnExpressionWhenCalledAtPath(path, { args }) {
  5335. if (path.length > 0) {
  5336. return UNKNOWN_RETURN_EXPRESSION;
  5337. }
  5338. return [
  5339. this.description.returnsPrimitive ||
  5340. (this.description.returns === 'self'
  5341. ? args[0] || UNKNOWN_EXPRESSION
  5342. : this.description.returns()),
  5343. false
  5344. ];
  5345. }
  5346. hasEffectsOnInteractionAtPath(path, interaction, context) {
  5347. const { type } = interaction;
  5348. if (path.length > (type === INTERACTION_ACCESSED ? 1 : 0)) {
  5349. return true;
  5350. }
  5351. if (type === INTERACTION_CALLED) {
  5352. const { args } = interaction;
  5353. if (this.description.mutatesSelfAsArray === true &&
  5354. args[0]?.hasEffectsOnInteractionAtPath(UNKNOWN_INTEGER_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context)) {
  5355. return true;
  5356. }
  5357. if (this.description.callsArgs) {
  5358. for (const argumentIndex of this.description.callsArgs) {
  5359. if (args[argumentIndex + 1]?.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)) {
  5360. return true;
  5361. }
  5362. }
  5363. }
  5364. }
  5365. return false;
  5366. }
  5367. }
  5368. const METHOD_RETURNS_BOOLEAN = [
  5369. new Method({
  5370. callsArgs: null,
  5371. mutatesSelfAsArray: false,
  5372. returns: null,
  5373. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  5374. })
  5375. ];
  5376. const METHOD_RETURNS_STRING = [
  5377. new Method({
  5378. callsArgs: null,
  5379. mutatesSelfAsArray: false,
  5380. returns: null,
  5381. returnsPrimitive: UNKNOWN_LITERAL_STRING
  5382. })
  5383. ];
  5384. const METHOD_RETURNS_NUMBER = [
  5385. new Method({
  5386. callsArgs: null,
  5387. mutatesSelfAsArray: false,
  5388. returns: null,
  5389. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  5390. })
  5391. ];
  5392. const METHOD_RETURNS_UNKNOWN = [
  5393. new Method({
  5394. callsArgs: null,
  5395. mutatesSelfAsArray: false,
  5396. returns: null,
  5397. returnsPrimitive: UNKNOWN_EXPRESSION
  5398. })
  5399. ];
  5400. const INTEGER_REG_EXP = /^\d+$/;
  5401. class ObjectEntity extends ExpressionEntity {
  5402. // If a PropertyMap is used, this will be taken as propertiesAndGettersByKey
  5403. // and we assume there are no setters or getters
  5404. constructor(properties, prototypeExpression, immutable = false) {
  5405. super();
  5406. this.prototypeExpression = prototypeExpression;
  5407. this.immutable = immutable;
  5408. this.additionalExpressionsToBeDeoptimized = new Set();
  5409. this.allProperties = [];
  5410. this.deoptimizedPaths = Object.create(null);
  5411. this.expressionsToBeDeoptimizedByKey = Object.create(null);
  5412. this.gettersByKey = Object.create(null);
  5413. this.hasLostTrack = false;
  5414. this.hasUnknownDeoptimizedInteger = false;
  5415. this.hasUnknownDeoptimizedProperty = false;
  5416. this.propertiesAndGettersByKey = Object.create(null);
  5417. this.propertiesAndSettersByKey = Object.create(null);
  5418. this.settersByKey = Object.create(null);
  5419. this.unknownIntegerProps = [];
  5420. this.unmatchableGetters = [];
  5421. this.unmatchablePropertiesAndGetters = [];
  5422. this.unmatchableSetters = [];
  5423. if (Array.isArray(properties)) {
  5424. this.buildPropertyMaps(properties);
  5425. }
  5426. else {
  5427. this.propertiesAndGettersByKey = this.propertiesAndSettersByKey = properties;
  5428. for (const propertiesForKey of Object.values(properties)) {
  5429. this.allProperties.push(...propertiesForKey);
  5430. }
  5431. }
  5432. }
  5433. deoptimizeAllProperties(noAccessors) {
  5434. const isDeoptimized = this.hasLostTrack || this.hasUnknownDeoptimizedProperty;
  5435. if (noAccessors) {
  5436. this.hasUnknownDeoptimizedProperty = true;
  5437. }
  5438. else {
  5439. this.hasLostTrack = true;
  5440. }
  5441. if (isDeoptimized) {
  5442. return;
  5443. }
  5444. for (const properties of [
  5445. ...Object.values(this.propertiesAndGettersByKey),
  5446. ...Object.values(this.settersByKey)
  5447. ]) {
  5448. for (const property of properties) {
  5449. property.deoptimizePath(UNKNOWN_PATH);
  5450. }
  5451. }
  5452. // While the prototype itself cannot be mutated, each property can
  5453. this.prototypeExpression?.deoptimizePath([UnknownKey, UnknownKey]);
  5454. this.deoptimizeCachedEntities();
  5455. }
  5456. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  5457. const [key, ...subPath] = path;
  5458. const { args, type } = interaction;
  5459. if (this.hasLostTrack ||
  5460. // single paths that are deoptimized will not become getters or setters
  5461. ((type === INTERACTION_CALLED || path.length > 1) &&
  5462. (this.hasUnknownDeoptimizedProperty ||
  5463. (typeof key === 'string' && this.deoptimizedPaths[key])))) {
  5464. deoptimizeInteraction(interaction);
  5465. return;
  5466. }
  5467. const [propertiesForExactMatchByKey, relevantPropertiesByKey, relevantUnmatchableProperties] = type === INTERACTION_CALLED || path.length > 1
  5468. ? [
  5469. this.propertiesAndGettersByKey,
  5470. this.propertiesAndGettersByKey,
  5471. this.unmatchablePropertiesAndGetters
  5472. ]
  5473. : type === INTERACTION_ACCESSED
  5474. ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters]
  5475. : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters];
  5476. if (typeof key === 'string') {
  5477. if (propertiesForExactMatchByKey[key]) {
  5478. const properties = relevantPropertiesByKey[key];
  5479. if (properties) {
  5480. for (const property of properties) {
  5481. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  5482. }
  5483. }
  5484. if (!this.immutable) {
  5485. for (const argument of args) {
  5486. if (argument) {
  5487. this.additionalExpressionsToBeDeoptimized.add(argument);
  5488. }
  5489. }
  5490. }
  5491. return;
  5492. }
  5493. for (const property of relevantUnmatchableProperties) {
  5494. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  5495. }
  5496. if (INTEGER_REG_EXP.test(key)) {
  5497. for (const property of this.unknownIntegerProps) {
  5498. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  5499. }
  5500. }
  5501. }
  5502. else {
  5503. for (const properties of [
  5504. ...Object.values(relevantPropertiesByKey),
  5505. relevantUnmatchableProperties
  5506. ]) {
  5507. for (const property of properties) {
  5508. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  5509. }
  5510. }
  5511. for (const property of this.unknownIntegerProps) {
  5512. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  5513. }
  5514. }
  5515. if (!this.immutable) {
  5516. for (const argument of args) {
  5517. if (argument) {
  5518. this.additionalExpressionsToBeDeoptimized.add(argument);
  5519. }
  5520. }
  5521. }
  5522. this.prototypeExpression?.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  5523. }
  5524. deoptimizeIntegerProperties() {
  5525. if (this.hasLostTrack ||
  5526. this.hasUnknownDeoptimizedProperty ||
  5527. this.hasUnknownDeoptimizedInteger) {
  5528. return;
  5529. }
  5530. this.hasUnknownDeoptimizedInteger = true;
  5531. for (const [key, propertiesAndGetters] of Object.entries(this.propertiesAndGettersByKey)) {
  5532. if (INTEGER_REG_EXP.test(key)) {
  5533. for (const property of propertiesAndGetters) {
  5534. property.deoptimizePath(UNKNOWN_PATH);
  5535. }
  5536. }
  5537. }
  5538. this.deoptimizeCachedIntegerEntities();
  5539. }
  5540. // Assumption: If only a specific path is deoptimized, no accessors are created
  5541. deoptimizePath(path) {
  5542. if (this.hasLostTrack || this.immutable) {
  5543. return;
  5544. }
  5545. const key = path[0];
  5546. if (path.length === 1) {
  5547. if (typeof key !== 'string') {
  5548. if (key === UnknownInteger) {
  5549. return this.deoptimizeIntegerProperties();
  5550. }
  5551. return this.deoptimizeAllProperties(key === UnknownNonAccessorKey);
  5552. }
  5553. if (!this.deoptimizedPaths[key]) {
  5554. this.deoptimizedPaths[key] = true;
  5555. // we only deoptimizeCache exact matches as in all other cases,
  5556. // we do not return a literal value or return expression
  5557. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimizedByKey[key];
  5558. if (expressionsToBeDeoptimized) {
  5559. for (const expression of expressionsToBeDeoptimized) {
  5560. expression.deoptimizeCache();
  5561. }
  5562. }
  5563. }
  5564. }
  5565. const subPath = path.length === 1 ? UNKNOWN_PATH : path.slice(1);
  5566. for (const property of typeof key === 'string'
  5567. ? [
  5568. ...(this.propertiesAndGettersByKey[key] || this.unmatchablePropertiesAndGetters),
  5569. ...(this.settersByKey[key] || this.unmatchableSetters)
  5570. ]
  5571. : this.allProperties) {
  5572. property.deoptimizePath(subPath);
  5573. }
  5574. this.prototypeExpression?.deoptimizePath(path.length === 1 ? [...path, UnknownKey] : path);
  5575. }
  5576. getLiteralValueAtPath(path, recursionTracker, origin) {
  5577. if (path.length === 0) {
  5578. return UnknownTruthyValue;
  5579. }
  5580. const key = path[0];
  5581. const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
  5582. if (expressionAtPath) {
  5583. return expressionAtPath.getLiteralValueAtPath(path.slice(1), recursionTracker, origin);
  5584. }
  5585. if (this.prototypeExpression) {
  5586. return this.prototypeExpression.getLiteralValueAtPath(path, recursionTracker, origin);
  5587. }
  5588. if (path.length === 1) {
  5589. return undefined;
  5590. }
  5591. return UnknownValue;
  5592. }
  5593. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  5594. if (path.length === 0) {
  5595. return UNKNOWN_RETURN_EXPRESSION;
  5596. }
  5597. const [key, ...subPath] = path;
  5598. const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
  5599. if (expressionAtPath) {
  5600. return expressionAtPath.getReturnExpressionWhenCalledAtPath(subPath, interaction, recursionTracker, origin);
  5601. }
  5602. if (this.prototypeExpression) {
  5603. return this.prototypeExpression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  5604. }
  5605. return UNKNOWN_RETURN_EXPRESSION;
  5606. }
  5607. hasEffectsOnInteractionAtPath(path, interaction, context) {
  5608. const [key, ...subPath] = path;
  5609. if (subPath.length > 0 || interaction.type === INTERACTION_CALLED) {
  5610. const expressionAtPath = this.getMemberExpression(key);
  5611. if (expressionAtPath) {
  5612. return expressionAtPath.hasEffectsOnInteractionAtPath(subPath, interaction, context);
  5613. }
  5614. if (this.prototypeExpression) {
  5615. return this.prototypeExpression.hasEffectsOnInteractionAtPath(path, interaction, context);
  5616. }
  5617. return true;
  5618. }
  5619. if (key === UnknownNonAccessorKey)
  5620. return false;
  5621. if (this.hasLostTrack)
  5622. return true;
  5623. const [propertiesAndAccessorsByKey, accessorsByKey, unmatchableAccessors] = interaction.type === INTERACTION_ACCESSED
  5624. ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters]
  5625. : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters];
  5626. if (typeof key === 'string') {
  5627. if (propertiesAndAccessorsByKey[key]) {
  5628. const accessors = accessorsByKey[key];
  5629. if (accessors) {
  5630. for (const accessor of accessors) {
  5631. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context))
  5632. return true;
  5633. }
  5634. }
  5635. return false;
  5636. }
  5637. for (const accessor of unmatchableAccessors) {
  5638. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context)) {
  5639. return true;
  5640. }
  5641. }
  5642. }
  5643. else {
  5644. for (const accessors of [...Object.values(accessorsByKey), unmatchableAccessors]) {
  5645. for (const accessor of accessors) {
  5646. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context))
  5647. return true;
  5648. }
  5649. }
  5650. }
  5651. if (this.prototypeExpression) {
  5652. return this.prototypeExpression.hasEffectsOnInteractionAtPath(path, interaction, context);
  5653. }
  5654. return false;
  5655. }
  5656. buildPropertyMaps(properties) {
  5657. const { allProperties, propertiesAndGettersByKey, propertiesAndSettersByKey, settersByKey, gettersByKey, unknownIntegerProps, unmatchablePropertiesAndGetters, unmatchableGetters, unmatchableSetters } = this;
  5658. const unmatchablePropertiesAndSetters = [];
  5659. for (let index = properties.length - 1; index >= 0; index--) {
  5660. const { key, kind, property } = properties[index];
  5661. allProperties.push(property);
  5662. if (typeof key === 'string') {
  5663. if (kind === 'set') {
  5664. if (!propertiesAndSettersByKey[key]) {
  5665. propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters];
  5666. settersByKey[key] = [property, ...unmatchableSetters];
  5667. }
  5668. }
  5669. else if (kind === 'get') {
  5670. if (!propertiesAndGettersByKey[key]) {
  5671. propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters];
  5672. gettersByKey[key] = [property, ...unmatchableGetters];
  5673. }
  5674. }
  5675. else {
  5676. if (!propertiesAndSettersByKey[key]) {
  5677. propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters];
  5678. }
  5679. if (!propertiesAndGettersByKey[key]) {
  5680. propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters];
  5681. }
  5682. }
  5683. }
  5684. else {
  5685. if (key === UnknownInteger) {
  5686. unknownIntegerProps.push(property);
  5687. continue;
  5688. }
  5689. if (kind === 'set')
  5690. unmatchableSetters.push(property);
  5691. if (kind === 'get')
  5692. unmatchableGetters.push(property);
  5693. if (kind !== 'get')
  5694. unmatchablePropertiesAndSetters.push(property);
  5695. if (kind !== 'set')
  5696. unmatchablePropertiesAndGetters.push(property);
  5697. }
  5698. }
  5699. }
  5700. deoptimizeCachedEntities() {
  5701. for (const expressionsToBeDeoptimized of Object.values(this.expressionsToBeDeoptimizedByKey)) {
  5702. for (const expression of expressionsToBeDeoptimized) {
  5703. expression.deoptimizeCache();
  5704. }
  5705. }
  5706. for (const expression of this.additionalExpressionsToBeDeoptimized) {
  5707. expression.deoptimizePath(UNKNOWN_PATH);
  5708. }
  5709. }
  5710. deoptimizeCachedIntegerEntities() {
  5711. for (const [key, expressionsToBeDeoptimized] of Object.entries(this.expressionsToBeDeoptimizedByKey)) {
  5712. if (INTEGER_REG_EXP.test(key)) {
  5713. for (const expression of expressionsToBeDeoptimized) {
  5714. expression.deoptimizeCache();
  5715. }
  5716. }
  5717. }
  5718. for (const expression of this.additionalExpressionsToBeDeoptimized) {
  5719. expression.deoptimizePath(UNKNOWN_INTEGER_PATH);
  5720. }
  5721. }
  5722. getMemberExpression(key) {
  5723. if (this.hasLostTrack ||
  5724. this.hasUnknownDeoptimizedProperty ||
  5725. typeof key !== 'string' ||
  5726. (this.hasUnknownDeoptimizedInteger && INTEGER_REG_EXP.test(key)) ||
  5727. this.deoptimizedPaths[key]) {
  5728. return UNKNOWN_EXPRESSION;
  5729. }
  5730. const properties = this.propertiesAndGettersByKey[key];
  5731. if (properties?.length === 1) {
  5732. return properties[0];
  5733. }
  5734. if (properties ||
  5735. this.unmatchablePropertiesAndGetters.length > 0 ||
  5736. (this.unknownIntegerProps.length > 0 && INTEGER_REG_EXP.test(key))) {
  5737. return UNKNOWN_EXPRESSION;
  5738. }
  5739. return null;
  5740. }
  5741. getMemberExpressionAndTrackDeopt(key, origin) {
  5742. if (typeof key !== 'string') {
  5743. return UNKNOWN_EXPRESSION;
  5744. }
  5745. const expression = this.getMemberExpression(key);
  5746. if (!(expression === UNKNOWN_EXPRESSION || this.immutable)) {
  5747. const expressionsToBeDeoptimized = (this.expressionsToBeDeoptimizedByKey[key] =
  5748. this.expressionsToBeDeoptimizedByKey[key] || []);
  5749. expressionsToBeDeoptimized.push(origin);
  5750. }
  5751. return expression;
  5752. }
  5753. }
  5754. const isInteger = (property) => typeof property === 'string' && /^\d+$/.test(property);
  5755. // This makes sure unknown properties are not handled as "undefined" but as
  5756. // "unknown" but without access side effects. An exception is done for numeric
  5757. // properties as we do not expect new builtin properties to be numbers, this
  5758. // will improve tree-shaking for out-of-bounds array properties
  5759. const OBJECT_PROTOTYPE_FALLBACK = new (class ObjectPrototypeFallbackExpression extends ExpressionEntity {
  5760. deoptimizeArgumentsOnInteractionAtPath(interaction, path) {
  5761. if (interaction.type === INTERACTION_CALLED && path.length === 1 && !isInteger(path[0])) {
  5762. deoptimizeInteraction(interaction);
  5763. }
  5764. }
  5765. getLiteralValueAtPath(path) {
  5766. // We ignore number properties as we do not expect new properties to be
  5767. // numbers and also want to keep handling out-of-bound array elements as
  5768. // "undefined"
  5769. return path.length === 1 && isInteger(path[0]) ? undefined : UnknownValue;
  5770. }
  5771. hasEffectsOnInteractionAtPath(path, { type }) {
  5772. return path.length > 1 || type === INTERACTION_CALLED;
  5773. }
  5774. })();
  5775. const OBJECT_PROTOTYPE = new ObjectEntity({
  5776. __proto__: null,
  5777. hasOwnProperty: METHOD_RETURNS_BOOLEAN,
  5778. isPrototypeOf: METHOD_RETURNS_BOOLEAN,
  5779. propertyIsEnumerable: METHOD_RETURNS_BOOLEAN,
  5780. toLocaleString: METHOD_RETURNS_STRING,
  5781. toString: METHOD_RETURNS_STRING,
  5782. valueOf: METHOD_RETURNS_UNKNOWN
  5783. }, OBJECT_PROTOTYPE_FALLBACK, true);
  5784. const NEW_ARRAY_PROPERTIES = [
  5785. { key: UnknownInteger, kind: 'init', property: UNKNOWN_EXPRESSION },
  5786. { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
  5787. ];
  5788. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN = [
  5789. new Method({
  5790. callsArgs: [0],
  5791. mutatesSelfAsArray: 'deopt-only',
  5792. returns: null,
  5793. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  5794. })
  5795. ];
  5796. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER = [
  5797. new Method({
  5798. callsArgs: [0],
  5799. mutatesSelfAsArray: 'deopt-only',
  5800. returns: null,
  5801. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  5802. })
  5803. ];
  5804. const METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY = [
  5805. new Method({
  5806. callsArgs: null,
  5807. mutatesSelfAsArray: true,
  5808. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  5809. returnsPrimitive: null
  5810. })
  5811. ];
  5812. const METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
  5813. new Method({
  5814. callsArgs: null,
  5815. mutatesSelfAsArray: 'deopt-only',
  5816. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  5817. returnsPrimitive: null
  5818. })
  5819. ];
  5820. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
  5821. new Method({
  5822. callsArgs: [0],
  5823. mutatesSelfAsArray: 'deopt-only',
  5824. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  5825. returnsPrimitive: null
  5826. })
  5827. ];
  5828. const METHOD_MUTATES_SELF_RETURNS_NUMBER = [
  5829. new Method({
  5830. callsArgs: null,
  5831. mutatesSelfAsArray: true,
  5832. returns: null,
  5833. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  5834. })
  5835. ];
  5836. const METHOD_MUTATES_SELF_RETURNS_UNKNOWN = [
  5837. new Method({
  5838. callsArgs: null,
  5839. mutatesSelfAsArray: true,
  5840. returns: null,
  5841. returnsPrimitive: UNKNOWN_EXPRESSION
  5842. })
  5843. ];
  5844. const METHOD_DEOPTS_SELF_RETURNS_UNKNOWN = [
  5845. new Method({
  5846. callsArgs: null,
  5847. mutatesSelfAsArray: 'deopt-only',
  5848. returns: null,
  5849. returnsPrimitive: UNKNOWN_EXPRESSION
  5850. })
  5851. ];
  5852. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN = [
  5853. new Method({
  5854. callsArgs: [0],
  5855. mutatesSelfAsArray: 'deopt-only',
  5856. returns: null,
  5857. returnsPrimitive: UNKNOWN_EXPRESSION
  5858. })
  5859. ];
  5860. const METHOD_MUTATES_SELF_RETURNS_SELF = [
  5861. new Method({
  5862. callsArgs: null,
  5863. mutatesSelfAsArray: true,
  5864. returns: 'self',
  5865. returnsPrimitive: null
  5866. })
  5867. ];
  5868. const METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF = [
  5869. new Method({
  5870. callsArgs: [0],
  5871. mutatesSelfAsArray: true,
  5872. returns: 'self',
  5873. returnsPrimitive: null
  5874. })
  5875. ];
  5876. const ARRAY_PROTOTYPE = new ObjectEntity({
  5877. __proto__: null,
  5878. // We assume that accessors have effects as we do not track the accessed value afterwards
  5879. at: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN,
  5880. concat: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5881. copyWithin: METHOD_MUTATES_SELF_RETURNS_SELF,
  5882. entries: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5883. every: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN,
  5884. fill: METHOD_MUTATES_SELF_RETURNS_SELF,
  5885. filter: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5886. find: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  5887. findIndex: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER,
  5888. findLast: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  5889. findLastIndex: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER,
  5890. flat: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5891. flatMap: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5892. forEach: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  5893. includes: METHOD_RETURNS_BOOLEAN,
  5894. indexOf: METHOD_RETURNS_NUMBER,
  5895. join: METHOD_RETURNS_STRING,
  5896. keys: METHOD_RETURNS_UNKNOWN,
  5897. lastIndexOf: METHOD_RETURNS_NUMBER,
  5898. map: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5899. pop: METHOD_MUTATES_SELF_RETURNS_UNKNOWN,
  5900. push: METHOD_MUTATES_SELF_RETURNS_NUMBER,
  5901. reduce: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  5902. reduceRight: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  5903. reverse: METHOD_MUTATES_SELF_RETURNS_SELF,
  5904. shift: METHOD_MUTATES_SELF_RETURNS_UNKNOWN,
  5905. slice: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5906. some: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN,
  5907. sort: METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF,
  5908. splice: METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY,
  5909. toLocaleString: METHOD_RETURNS_STRING,
  5910. toString: METHOD_RETURNS_STRING,
  5911. unshift: METHOD_MUTATES_SELF_RETURNS_NUMBER,
  5912. values: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN
  5913. }, OBJECT_PROTOTYPE, true);
  5914. class ArrayExpression extends NodeBase {
  5915. constructor() {
  5916. super(...arguments);
  5917. this.objectEntity = null;
  5918. }
  5919. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  5920. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  5921. }
  5922. deoptimizePath(path) {
  5923. this.getObjectEntity().deoptimizePath(path);
  5924. }
  5925. getLiteralValueAtPath(path, recursionTracker, origin) {
  5926. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  5927. }
  5928. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  5929. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  5930. }
  5931. hasEffectsOnInteractionAtPath(path, interaction, context) {
  5932. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  5933. }
  5934. applyDeoptimizations() {
  5935. this.deoptimized = true;
  5936. let hasSpread = false;
  5937. for (let index = 0; index < this.elements.length; index++) {
  5938. const element = this.elements[index];
  5939. if (element && (hasSpread || element instanceof SpreadElement)) {
  5940. hasSpread = true;
  5941. element.deoptimizePath(UNKNOWN_PATH);
  5942. }
  5943. }
  5944. this.context.requestTreeshakingPass();
  5945. }
  5946. getObjectEntity() {
  5947. if (this.objectEntity !== null) {
  5948. return this.objectEntity;
  5949. }
  5950. const properties = [
  5951. { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
  5952. ];
  5953. let hasSpread = false;
  5954. for (let index = 0; index < this.elements.length; index++) {
  5955. const element = this.elements[index];
  5956. if (hasSpread || element instanceof SpreadElement) {
  5957. if (element) {
  5958. hasSpread = true;
  5959. properties.unshift({ key: UnknownInteger, kind: 'init', property: element });
  5960. }
  5961. }
  5962. else if (element) {
  5963. properties.push({ key: String(index), kind: 'init', property: element });
  5964. }
  5965. else {
  5966. properties.push({ key: String(index), kind: 'init', property: UNDEFINED_EXPRESSION });
  5967. }
  5968. }
  5969. return (this.objectEntity = new ObjectEntity(properties, ARRAY_PROTOTYPE));
  5970. }
  5971. }
  5972. class ArrayPattern extends NodeBase {
  5973. addExportedVariables(variables, exportNamesByVariable) {
  5974. for (const element of this.elements) {
  5975. element?.addExportedVariables(variables, exportNamesByVariable);
  5976. }
  5977. }
  5978. declare(kind) {
  5979. const variables = [];
  5980. for (const element of this.elements) {
  5981. if (element !== null) {
  5982. variables.push(...element.declare(kind, UNKNOWN_EXPRESSION));
  5983. }
  5984. }
  5985. return variables;
  5986. }
  5987. // Patterns can only be deoptimized at the empty path at the moment
  5988. deoptimizePath() {
  5989. for (const element of this.elements) {
  5990. element?.deoptimizePath(EMPTY_PATH);
  5991. }
  5992. }
  5993. // Patterns are only checked at the emtpy path at the moment
  5994. hasEffectsOnInteractionAtPath(_path, interaction, context) {
  5995. for (const element of this.elements) {
  5996. if (element?.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context))
  5997. return true;
  5998. }
  5999. return false;
  6000. }
  6001. markDeclarationReached() {
  6002. for (const element of this.elements) {
  6003. element?.markDeclarationReached();
  6004. }
  6005. }
  6006. }
  6007. class LocalVariable extends Variable {
  6008. constructor(name, declarator, init, context) {
  6009. super(name);
  6010. this.init = init;
  6011. this.calledFromTryStatement = false;
  6012. this.additionalInitializers = null;
  6013. this.expressionsToBeDeoptimized = [];
  6014. this.declarations = declarator ? [declarator] : [];
  6015. this.deoptimizationTracker = context.deoptimizationTracker;
  6016. this.module = context.module;
  6017. }
  6018. addDeclaration(identifier, init) {
  6019. this.declarations.push(identifier);
  6020. this.markInitializersForDeoptimization().push(init);
  6021. }
  6022. consolidateInitializers() {
  6023. if (this.additionalInitializers) {
  6024. for (const initializer of this.additionalInitializers) {
  6025. initializer.deoptimizePath(UNKNOWN_PATH);
  6026. }
  6027. this.additionalInitializers = null;
  6028. }
  6029. }
  6030. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  6031. if (this.isReassigned) {
  6032. deoptimizeInteraction(interaction);
  6033. return;
  6034. }
  6035. recursionTracker.withTrackedEntityAtPath(path, this.init, () => this.init.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker), undefined);
  6036. }
  6037. deoptimizePath(path) {
  6038. if (this.isReassigned ||
  6039. this.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  6040. return;
  6041. }
  6042. if (path.length === 0) {
  6043. if (!this.isReassigned) {
  6044. this.isReassigned = true;
  6045. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
  6046. this.expressionsToBeDeoptimized = EMPTY_ARRAY;
  6047. for (const expression of expressionsToBeDeoptimized) {
  6048. expression.deoptimizeCache();
  6049. }
  6050. this.init.deoptimizePath(UNKNOWN_PATH);
  6051. }
  6052. }
  6053. else {
  6054. this.init.deoptimizePath(path);
  6055. }
  6056. }
  6057. getLiteralValueAtPath(path, recursionTracker, origin) {
  6058. if (this.isReassigned) {
  6059. return UnknownValue;
  6060. }
  6061. return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  6062. this.expressionsToBeDeoptimized.push(origin);
  6063. return this.init.getLiteralValueAtPath(path, recursionTracker, origin);
  6064. }, UnknownValue);
  6065. }
  6066. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  6067. if (this.isReassigned) {
  6068. return UNKNOWN_RETURN_EXPRESSION;
  6069. }
  6070. return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  6071. this.expressionsToBeDeoptimized.push(origin);
  6072. return this.init.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  6073. }, UNKNOWN_RETURN_EXPRESSION);
  6074. }
  6075. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6076. switch (interaction.type) {
  6077. case INTERACTION_ACCESSED: {
  6078. if (this.isReassigned)
  6079. return true;
  6080. return (!context.accessed.trackEntityAtPathAndGetIfTracked(path, this) &&
  6081. this.init.hasEffectsOnInteractionAtPath(path, interaction, context));
  6082. }
  6083. case INTERACTION_ASSIGNED: {
  6084. if (this.included)
  6085. return true;
  6086. if (path.length === 0)
  6087. return false;
  6088. if (this.isReassigned)
  6089. return true;
  6090. return (!context.assigned.trackEntityAtPathAndGetIfTracked(path, this) &&
  6091. this.init.hasEffectsOnInteractionAtPath(path, interaction, context));
  6092. }
  6093. case INTERACTION_CALLED: {
  6094. if (this.isReassigned)
  6095. return true;
  6096. return (!(interaction.withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, interaction.args, this) &&
  6097. this.init.hasEffectsOnInteractionAtPath(path, interaction, context));
  6098. }
  6099. }
  6100. }
  6101. include() {
  6102. if (!this.included) {
  6103. this.included = true;
  6104. for (const declaration of this.declarations) {
  6105. // If node is a default export, it can save a tree-shaking run to include the full declaration now
  6106. if (!declaration.included)
  6107. declaration.include(createInclusionContext(), false);
  6108. let node = declaration.parent;
  6109. while (!node.included) {
  6110. // We do not want to properly include parents in case they are part of a dead branch
  6111. // in which case .include() might pull in more dead code
  6112. node.included = true;
  6113. if (node.type === Program$1)
  6114. break;
  6115. node = node.parent;
  6116. }
  6117. }
  6118. }
  6119. }
  6120. includeCallArguments(context, parameters) {
  6121. if (this.isReassigned || context.includedCallArguments.has(this.init)) {
  6122. for (const argument of parameters) {
  6123. argument.include(context, false);
  6124. }
  6125. }
  6126. else {
  6127. context.includedCallArguments.add(this.init);
  6128. this.init.includeCallArguments(context, parameters);
  6129. context.includedCallArguments.delete(this.init);
  6130. }
  6131. }
  6132. markCalledFromTryStatement() {
  6133. this.calledFromTryStatement = true;
  6134. }
  6135. markInitializersForDeoptimization() {
  6136. if (this.additionalInitializers === null) {
  6137. this.additionalInitializers = [this.init];
  6138. this.init = UNKNOWN_EXPRESSION;
  6139. this.isReassigned = true;
  6140. }
  6141. return this.additionalInitializers;
  6142. }
  6143. mergeDeclarations(variable) {
  6144. const { declarations } = this;
  6145. for (const declaration of variable.declarations) {
  6146. declarations.push(declaration);
  6147. }
  6148. const additionalInitializers = this.markInitializersForDeoptimization();
  6149. additionalInitializers.push(variable.init);
  6150. if (variable.additionalInitializers) {
  6151. for (const initializer of variable.additionalInitializers) {
  6152. additionalInitializers.push(initializer);
  6153. }
  6154. }
  6155. }
  6156. }
  6157. const MAX_TRACKED_INTERACTIONS = 20;
  6158. const NO_INTERACTIONS = EMPTY_ARRAY;
  6159. const UNKNOWN_DEOPTIMIZED_FIELD = new Set([UnknownKey]);
  6160. const EMPTY_PATH_TRACKER = new PathTracker();
  6161. const UNKNOWN_DEOPTIMIZED_ENTITY = new Set([UNKNOWN_EXPRESSION]);
  6162. class ParameterVariable extends LocalVariable {
  6163. constructor(name, declarator, context) {
  6164. super(name, declarator, UNKNOWN_EXPRESSION, context);
  6165. this.deoptimizationInteractions = [];
  6166. this.deoptimizations = new PathTracker();
  6167. this.deoptimizedFields = new Set();
  6168. this.entitiesToBeDeoptimized = new Set();
  6169. }
  6170. addEntityToBeDeoptimized(entity) {
  6171. if (entity === UNKNOWN_EXPRESSION) {
  6172. // As unknown expressions fully deoptimize all interactions, we can clear
  6173. // the interaction cache at this point provided we keep this optimization
  6174. // in mind when adding new interactions
  6175. if (!this.entitiesToBeDeoptimized.has(UNKNOWN_EXPRESSION)) {
  6176. this.entitiesToBeDeoptimized.add(UNKNOWN_EXPRESSION);
  6177. for (const { interaction } of this.deoptimizationInteractions) {
  6178. deoptimizeInteraction(interaction);
  6179. }
  6180. this.deoptimizationInteractions = NO_INTERACTIONS;
  6181. }
  6182. }
  6183. else if (this.deoptimizedFields.has(UnknownKey)) {
  6184. // This means that we already deoptimized all interactions and no longer
  6185. // track them
  6186. entity.deoptimizePath(UNKNOWN_PATH);
  6187. }
  6188. else if (!this.entitiesToBeDeoptimized.has(entity)) {
  6189. this.entitiesToBeDeoptimized.add(entity);
  6190. for (const field of this.deoptimizedFields) {
  6191. entity.deoptimizePath([field]);
  6192. }
  6193. for (const { interaction, path } of this.deoptimizationInteractions) {
  6194. entity.deoptimizeArgumentsOnInteractionAtPath(interaction, path, SHARED_RECURSION_TRACKER);
  6195. }
  6196. }
  6197. }
  6198. deoptimizeArgumentsOnInteractionAtPath(interaction, path) {
  6199. // For performance reasons, we fully deoptimize all deeper interactions
  6200. if (path.length >= 2 ||
  6201. this.entitiesToBeDeoptimized.has(UNKNOWN_EXPRESSION) ||
  6202. this.deoptimizationInteractions.length >= MAX_TRACKED_INTERACTIONS ||
  6203. (path.length === 1 &&
  6204. (this.deoptimizedFields.has(UnknownKey) ||
  6205. (interaction.type === INTERACTION_CALLED && this.deoptimizedFields.has(path[0]))))) {
  6206. deoptimizeInteraction(interaction);
  6207. return;
  6208. }
  6209. if (!this.deoptimizations.trackEntityAtPathAndGetIfTracked(path, interaction.args)) {
  6210. for (const entity of this.entitiesToBeDeoptimized) {
  6211. entity.deoptimizeArgumentsOnInteractionAtPath(interaction, path, SHARED_RECURSION_TRACKER);
  6212. }
  6213. if (!this.entitiesToBeDeoptimized.has(UNKNOWN_EXPRESSION)) {
  6214. this.deoptimizationInteractions.push({
  6215. interaction,
  6216. path
  6217. });
  6218. }
  6219. }
  6220. }
  6221. deoptimizePath(path) {
  6222. if (path.length === 0 || this.deoptimizedFields.has(UnknownKey)) {
  6223. return;
  6224. }
  6225. const key = path[0];
  6226. if (this.deoptimizedFields.has(key)) {
  6227. return;
  6228. }
  6229. this.deoptimizedFields.add(key);
  6230. for (const entity of this.entitiesToBeDeoptimized) {
  6231. // We do not need a recursion tracker here as we already track whether
  6232. // this field is deoptimized
  6233. entity.deoptimizePath([key]);
  6234. }
  6235. if (key === UnknownKey) {
  6236. // save some memory
  6237. this.deoptimizationInteractions = NO_INTERACTIONS;
  6238. this.deoptimizations = EMPTY_PATH_TRACKER;
  6239. this.deoptimizedFields = UNKNOWN_DEOPTIMIZED_FIELD;
  6240. this.entitiesToBeDeoptimized = UNKNOWN_DEOPTIMIZED_ENTITY;
  6241. }
  6242. }
  6243. getReturnExpressionWhenCalledAtPath(path) {
  6244. // We deoptimize everything that is called as that will trivially deoptimize
  6245. // the corresponding return expressions as well and avoid badly performing
  6246. // and complicated alternatives
  6247. if (path.length === 0) {
  6248. this.deoptimizePath(UNKNOWN_PATH);
  6249. }
  6250. else if (!this.deoptimizedFields.has(path[0])) {
  6251. this.deoptimizePath([path[0]]);
  6252. }
  6253. return UNKNOWN_RETURN_EXPRESSION;
  6254. }
  6255. }
  6256. const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
  6257. const base = 64;
  6258. function toBase64(value) {
  6259. let outString = '';
  6260. do {
  6261. const currentDigit = value % base;
  6262. value = (value / base) | 0;
  6263. outString = chars[currentDigit] + outString;
  6264. } while (value !== 0);
  6265. return outString;
  6266. }
  6267. function getSafeName(baseName, usedNames, forbiddenNames) {
  6268. let safeName = baseName;
  6269. let count = 1;
  6270. while (usedNames.has(safeName) || RESERVED_NAMES$1.has(safeName) || forbiddenNames?.has(safeName)) {
  6271. safeName = `${baseName}$${toBase64(count++)}`;
  6272. }
  6273. usedNames.add(safeName);
  6274. return safeName;
  6275. }
  6276. let Scope$1 = class Scope {
  6277. constructor() {
  6278. this.children = [];
  6279. this.variables = new Map();
  6280. }
  6281. addDeclaration(identifier, context, init, _isHoisted) {
  6282. const name = identifier.name;
  6283. let variable = this.variables.get(name);
  6284. if (variable) {
  6285. variable.addDeclaration(identifier, init);
  6286. }
  6287. else {
  6288. variable = new LocalVariable(identifier.name, identifier, init || UNDEFINED_EXPRESSION, context);
  6289. this.variables.set(name, variable);
  6290. }
  6291. return variable;
  6292. }
  6293. contains(name) {
  6294. return this.variables.has(name);
  6295. }
  6296. findVariable(_name) {
  6297. throw new Error('Internal Error: findVariable needs to be implemented by a subclass');
  6298. }
  6299. };
  6300. class ChildScope extends Scope$1 {
  6301. constructor(parent) {
  6302. super();
  6303. this.accessedOutsideVariables = new Map();
  6304. this.parent = parent;
  6305. parent.children.push(this);
  6306. }
  6307. addAccessedDynamicImport(importExpression) {
  6308. (this.accessedDynamicImports || (this.accessedDynamicImports = new Set())).add(importExpression);
  6309. if (this.parent instanceof ChildScope) {
  6310. this.parent.addAccessedDynamicImport(importExpression);
  6311. }
  6312. }
  6313. addAccessedGlobals(globals, accessedGlobalsByScope) {
  6314. const accessedGlobals = accessedGlobalsByScope.get(this) || new Set();
  6315. for (const name of globals) {
  6316. accessedGlobals.add(name);
  6317. }
  6318. accessedGlobalsByScope.set(this, accessedGlobals);
  6319. if (this.parent instanceof ChildScope) {
  6320. this.parent.addAccessedGlobals(globals, accessedGlobalsByScope);
  6321. }
  6322. }
  6323. addNamespaceMemberAccess(name, variable) {
  6324. this.accessedOutsideVariables.set(name, variable);
  6325. this.parent.addNamespaceMemberAccess(name, variable);
  6326. }
  6327. addReturnExpression(expression) {
  6328. this.parent instanceof ChildScope && this.parent.addReturnExpression(expression);
  6329. }
  6330. addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope) {
  6331. for (const variable of this.accessedOutsideVariables.values()) {
  6332. if (variable.included) {
  6333. usedNames.add(variable.getBaseVariableName());
  6334. if (format === 'system' && exportNamesByVariable.has(variable)) {
  6335. usedNames.add('exports');
  6336. }
  6337. }
  6338. }
  6339. const accessedGlobals = accessedGlobalsByScope.get(this);
  6340. if (accessedGlobals) {
  6341. for (const name of accessedGlobals) {
  6342. usedNames.add(name);
  6343. }
  6344. }
  6345. }
  6346. contains(name) {
  6347. return this.variables.has(name) || this.parent.contains(name);
  6348. }
  6349. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  6350. const usedNames = new Set();
  6351. this.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
  6352. if (this.accessedDynamicImports) {
  6353. for (const importExpression of this.accessedDynamicImports) {
  6354. if (importExpression.inlineNamespace) {
  6355. usedNames.add(importExpression.inlineNamespace.getBaseVariableName());
  6356. }
  6357. }
  6358. }
  6359. for (const [name, variable] of this.variables) {
  6360. if (variable.included || variable.alwaysRendered) {
  6361. variable.setRenderNames(null, getSafeName(name, usedNames, variable.forbiddenNames));
  6362. }
  6363. }
  6364. for (const scope of this.children) {
  6365. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  6366. }
  6367. }
  6368. findLexicalBoundary() {
  6369. return this.parent.findLexicalBoundary();
  6370. }
  6371. findVariable(name) {
  6372. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  6373. if (knownVariable) {
  6374. return knownVariable;
  6375. }
  6376. const variable = this.parent.findVariable(name);
  6377. this.accessedOutsideVariables.set(name, variable);
  6378. return variable;
  6379. }
  6380. }
  6381. class ParameterScope extends ChildScope {
  6382. constructor(parent, context) {
  6383. super(parent);
  6384. this.parameters = [];
  6385. this.hasRest = false;
  6386. this.context = context;
  6387. this.hoistedBodyVarScope = new ChildScope(this);
  6388. }
  6389. /**
  6390. * Adds a parameter to this scope. Parameters must be added in the correct
  6391. * order, i.e. from left to right.
  6392. */
  6393. addParameterDeclaration(identifier) {
  6394. const { name } = identifier;
  6395. const variable = new ParameterVariable(name, identifier, this.context);
  6396. const localVariable = this.hoistedBodyVarScope.variables.get(name);
  6397. if (localVariable) {
  6398. this.hoistedBodyVarScope.variables.set(name, variable);
  6399. variable.mergeDeclarations(localVariable);
  6400. }
  6401. this.variables.set(name, variable);
  6402. return variable;
  6403. }
  6404. addParameterVariables(parameters, hasRest) {
  6405. this.parameters = parameters;
  6406. for (const parameterList of parameters) {
  6407. for (const parameter of parameterList) {
  6408. parameter.alwaysRendered = true;
  6409. }
  6410. }
  6411. this.hasRest = hasRest;
  6412. }
  6413. includeCallArguments(context, parameters) {
  6414. let calledFromTryStatement = false;
  6415. let argumentIncluded = false;
  6416. const restParameter = this.hasRest && this.parameters[this.parameters.length - 1];
  6417. for (const checkedArgument of parameters) {
  6418. if (checkedArgument instanceof SpreadElement) {
  6419. for (const argument of parameters) {
  6420. argument.include(context, false);
  6421. }
  6422. break;
  6423. }
  6424. }
  6425. for (let index = parameters.length - 1; index >= 0; index--) {
  6426. const parameterVariables = this.parameters[index] || restParameter;
  6427. const argument = parameters[index];
  6428. if (parameterVariables) {
  6429. calledFromTryStatement = false;
  6430. if (parameterVariables.length === 0) {
  6431. // handle empty destructuring
  6432. argumentIncluded = true;
  6433. }
  6434. else {
  6435. for (const variable of parameterVariables) {
  6436. if (variable.included) {
  6437. argumentIncluded = true;
  6438. }
  6439. if (variable.calledFromTryStatement) {
  6440. calledFromTryStatement = true;
  6441. }
  6442. }
  6443. }
  6444. }
  6445. if (!argumentIncluded && argument.shouldBeIncluded(context)) {
  6446. argumentIncluded = true;
  6447. }
  6448. if (argumentIncluded) {
  6449. argument.include(context, calledFromTryStatement);
  6450. }
  6451. }
  6452. }
  6453. }
  6454. class ReturnValueScope extends ParameterScope {
  6455. constructor() {
  6456. super(...arguments);
  6457. this.returnExpression = null;
  6458. this.returnExpressions = [];
  6459. }
  6460. addReturnExpression(expression) {
  6461. this.returnExpressions.push(expression);
  6462. }
  6463. getReturnExpression() {
  6464. if (this.returnExpression === null)
  6465. this.updateReturnExpression();
  6466. return this.returnExpression;
  6467. }
  6468. updateReturnExpression() {
  6469. if (this.returnExpressions.length === 1) {
  6470. this.returnExpression = this.returnExpressions[0];
  6471. }
  6472. else {
  6473. this.returnExpression = UNKNOWN_EXPRESSION;
  6474. for (const expression of this.returnExpressions) {
  6475. expression.deoptimizePath(UNKNOWN_PATH);
  6476. }
  6477. }
  6478. }
  6479. }
  6480. /** @typedef { import('estree').Node} Node */
  6481. /** @typedef {Node | {
  6482. * type: 'PropertyDefinition';
  6483. * computed: boolean;
  6484. * value: Node
  6485. * }} NodeWithPropertyDefinition */
  6486. /**
  6487. *
  6488. * @param {NodeWithPropertyDefinition} node
  6489. * @param {NodeWithPropertyDefinition} parent
  6490. * @returns {boolean}
  6491. */
  6492. function is_reference (node, parent) {
  6493. if (node.type === 'MemberExpression') {
  6494. return !node.computed && is_reference(node.object, node);
  6495. }
  6496. if (node.type === 'Identifier') {
  6497. if (!parent) return true;
  6498. switch (parent.type) {
  6499. // disregard `bar` in `foo.bar`
  6500. case 'MemberExpression': return parent.computed || node === parent.object;
  6501. // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}`
  6502. case 'MethodDefinition': return parent.computed;
  6503. // disregard the `foo` in `class {foo=bar}` but keep it in `class {[foo]=bar}` and `class {bar=foo}`
  6504. case 'PropertyDefinition': return parent.computed || node === parent.value;
  6505. // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
  6506. case 'Property': return parent.computed || node === parent.value;
  6507. // disregard the `bar` in `export { foo as bar }` or
  6508. // the foo in `import { foo as bar }`
  6509. case 'ExportSpecifier':
  6510. case 'ImportSpecifier': return node === parent.local;
  6511. // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}`
  6512. case 'LabeledStatement':
  6513. case 'BreakStatement':
  6514. case 'ContinueStatement': return false;
  6515. default: return true;
  6516. }
  6517. }
  6518. return false;
  6519. }
  6520. const PureFunctionKey = Symbol('PureFunction');
  6521. const getPureFunctions = ({ treeshake }) => {
  6522. const pureFunctions = Object.create(null);
  6523. for (const functionName of treeshake ? treeshake.manualPureFunctions : []) {
  6524. let currentFunctions = pureFunctions;
  6525. for (const pathSegment of functionName.split('.')) {
  6526. currentFunctions = currentFunctions[pathSegment] || (currentFunctions[pathSegment] = Object.create(null));
  6527. }
  6528. currentFunctions[PureFunctionKey] = true;
  6529. }
  6530. return pureFunctions;
  6531. };
  6532. const doNothing = () => { };
  6533. /* eslint sort-keys: "off" */
  6534. const ValueProperties = Symbol('Value Properties');
  6535. const getTruthyLiteralValue = () => UnknownTruthyValue;
  6536. const returnFalse = () => false;
  6537. const returnTrue = () => true;
  6538. const PURE = {
  6539. deoptimizeArgumentsOnCall: doNothing,
  6540. getLiteralValue: getTruthyLiteralValue,
  6541. hasEffectsWhenCalled: returnFalse
  6542. };
  6543. const IMPURE = {
  6544. deoptimizeArgumentsOnCall: doNothing,
  6545. getLiteralValue: getTruthyLiteralValue,
  6546. hasEffectsWhenCalled: returnTrue
  6547. };
  6548. const PURE_WITH_ARRAY = {
  6549. deoptimizeArgumentsOnCall: doNothing,
  6550. getLiteralValue: getTruthyLiteralValue,
  6551. hasEffectsWhenCalled({ args }) {
  6552. return args.length > 1 && !(args[1] instanceof ArrayExpression);
  6553. }
  6554. };
  6555. const GETTER_ACCESS = {
  6556. deoptimizeArgumentsOnCall: doNothing,
  6557. getLiteralValue: getTruthyLiteralValue,
  6558. hasEffectsWhenCalled({ args }, context) {
  6559. const [_thisArgument, firstArgument] = args;
  6560. return (!(firstArgument instanceof ExpressionEntity) ||
  6561. firstArgument.hasEffectsOnInteractionAtPath(UNKNOWN_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context));
  6562. }
  6563. };
  6564. // We use shortened variables to reduce file size here
  6565. /* OBJECT */
  6566. const O = {
  6567. __proto__: null,
  6568. [ValueProperties]: IMPURE
  6569. };
  6570. /* PURE FUNCTION */
  6571. const PF = {
  6572. __proto__: null,
  6573. [ValueProperties]: PURE
  6574. };
  6575. /* PURE FUNCTION IF FIRST ARG DOES NOT CONTAIN A GETTER */
  6576. const PF_NO_GETTER = {
  6577. __proto__: null,
  6578. [ValueProperties]: GETTER_ACCESS
  6579. };
  6580. /* FUNCTION THAT MUTATES FIRST ARG WITHOUT TRIGGERING ACCESSORS */
  6581. const MUTATES_ARG_WITHOUT_ACCESSOR = {
  6582. __proto__: null,
  6583. [ValueProperties]: {
  6584. deoptimizeArgumentsOnCall({ args: [, firstArgument] }) {
  6585. firstArgument?.deoptimizePath(UNKNOWN_PATH);
  6586. },
  6587. getLiteralValue: getTruthyLiteralValue,
  6588. hasEffectsWhenCalled({ args }, context) {
  6589. return (args.length <= 1 ||
  6590. args[1].hasEffectsOnInteractionAtPath(UNKNOWN_NON_ACCESSOR_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context));
  6591. }
  6592. }
  6593. };
  6594. /* CONSTRUCTOR */
  6595. const C = {
  6596. __proto__: null,
  6597. [ValueProperties]: IMPURE,
  6598. prototype: O
  6599. };
  6600. /* PURE CONSTRUCTOR */
  6601. const PC = {
  6602. __proto__: null,
  6603. [ValueProperties]: PURE,
  6604. prototype: O
  6605. };
  6606. const PC_WITH_ARRAY = {
  6607. __proto__: null,
  6608. [ValueProperties]: PURE_WITH_ARRAY,
  6609. prototype: O
  6610. };
  6611. const ARRAY_TYPE = {
  6612. __proto__: null,
  6613. [ValueProperties]: PURE,
  6614. from: O,
  6615. of: PF,
  6616. prototype: O
  6617. };
  6618. const INTL_MEMBER = {
  6619. __proto__: null,
  6620. [ValueProperties]: PURE,
  6621. supportedLocalesOf: PC
  6622. };
  6623. const knownGlobals = {
  6624. // Placeholders for global objects to avoid shape mutations
  6625. global: O,
  6626. globalThis: O,
  6627. self: O,
  6628. window: O,
  6629. // Common globals
  6630. __proto__: null,
  6631. [ValueProperties]: IMPURE,
  6632. Array: {
  6633. __proto__: null,
  6634. [ValueProperties]: IMPURE,
  6635. from: O,
  6636. isArray: PF,
  6637. of: PF,
  6638. prototype: O
  6639. },
  6640. ArrayBuffer: {
  6641. __proto__: null,
  6642. [ValueProperties]: PURE,
  6643. isView: PF,
  6644. prototype: O
  6645. },
  6646. Atomics: O,
  6647. BigInt: C,
  6648. BigInt64Array: C,
  6649. BigUint64Array: C,
  6650. Boolean: PC,
  6651. constructor: C,
  6652. DataView: PC,
  6653. Date: {
  6654. __proto__: null,
  6655. [ValueProperties]: PURE,
  6656. now: PF,
  6657. parse: PF,
  6658. prototype: O,
  6659. UTC: PF
  6660. },
  6661. decodeURI: PF,
  6662. decodeURIComponent: PF,
  6663. encodeURI: PF,
  6664. encodeURIComponent: PF,
  6665. Error: PC,
  6666. escape: PF,
  6667. eval: O,
  6668. EvalError: PC,
  6669. Float32Array: ARRAY_TYPE,
  6670. Float64Array: ARRAY_TYPE,
  6671. Function: C,
  6672. hasOwnProperty: O,
  6673. Infinity: O,
  6674. Int16Array: ARRAY_TYPE,
  6675. Int32Array: ARRAY_TYPE,
  6676. Int8Array: ARRAY_TYPE,
  6677. isFinite: PF,
  6678. isNaN: PF,
  6679. isPrototypeOf: O,
  6680. JSON: O,
  6681. Map: PC_WITH_ARRAY,
  6682. Math: {
  6683. __proto__: null,
  6684. [ValueProperties]: IMPURE,
  6685. abs: PF,
  6686. acos: PF,
  6687. acosh: PF,
  6688. asin: PF,
  6689. asinh: PF,
  6690. atan: PF,
  6691. atan2: PF,
  6692. atanh: PF,
  6693. cbrt: PF,
  6694. ceil: PF,
  6695. clz32: PF,
  6696. cos: PF,
  6697. cosh: PF,
  6698. exp: PF,
  6699. expm1: PF,
  6700. floor: PF,
  6701. fround: PF,
  6702. hypot: PF,
  6703. imul: PF,
  6704. log: PF,
  6705. log10: PF,
  6706. log1p: PF,
  6707. log2: PF,
  6708. max: PF,
  6709. min: PF,
  6710. pow: PF,
  6711. random: PF,
  6712. round: PF,
  6713. sign: PF,
  6714. sin: PF,
  6715. sinh: PF,
  6716. sqrt: PF,
  6717. tan: PF,
  6718. tanh: PF,
  6719. trunc: PF
  6720. },
  6721. NaN: O,
  6722. Number: {
  6723. __proto__: null,
  6724. [ValueProperties]: PURE,
  6725. isFinite: PF,
  6726. isInteger: PF,
  6727. isNaN: PF,
  6728. isSafeInteger: PF,
  6729. parseFloat: PF,
  6730. parseInt: PF,
  6731. prototype: O
  6732. },
  6733. Object: {
  6734. __proto__: null,
  6735. [ValueProperties]: PURE,
  6736. create: PF,
  6737. // Technically those can throw in certain situations, but we ignore this as
  6738. // code that relies on this will hopefully wrap this in a try-catch, which
  6739. // deoptimizes everything anyway
  6740. defineProperty: MUTATES_ARG_WITHOUT_ACCESSOR,
  6741. defineProperties: MUTATES_ARG_WITHOUT_ACCESSOR,
  6742. freeze: MUTATES_ARG_WITHOUT_ACCESSOR,
  6743. getOwnPropertyDescriptor: PF,
  6744. getOwnPropertyDescriptors: PF,
  6745. getOwnPropertyNames: PF,
  6746. getOwnPropertySymbols: PF,
  6747. getPrototypeOf: PF,
  6748. hasOwn: PF,
  6749. is: PF,
  6750. isExtensible: PF,
  6751. isFrozen: PF,
  6752. isSealed: PF,
  6753. keys: PF,
  6754. fromEntries: O,
  6755. entries: PF_NO_GETTER,
  6756. values: PF_NO_GETTER,
  6757. prototype: O
  6758. },
  6759. parseFloat: PF,
  6760. parseInt: PF,
  6761. Promise: {
  6762. __proto__: null,
  6763. [ValueProperties]: IMPURE,
  6764. all: O,
  6765. allSettled: O,
  6766. any: O,
  6767. prototype: O,
  6768. race: O,
  6769. reject: O,
  6770. resolve: O
  6771. },
  6772. propertyIsEnumerable: O,
  6773. Proxy: O,
  6774. RangeError: PC,
  6775. ReferenceError: PC,
  6776. Reflect: O,
  6777. RegExp: PC,
  6778. Set: PC_WITH_ARRAY,
  6779. SharedArrayBuffer: C,
  6780. String: {
  6781. __proto__: null,
  6782. [ValueProperties]: PURE,
  6783. fromCharCode: PF,
  6784. fromCodePoint: PF,
  6785. prototype: O,
  6786. raw: PF
  6787. },
  6788. Symbol: {
  6789. __proto__: null,
  6790. [ValueProperties]: PURE,
  6791. for: PF,
  6792. keyFor: PF,
  6793. prototype: O,
  6794. toStringTag: {
  6795. __proto__: null,
  6796. [ValueProperties]: {
  6797. deoptimizeArgumentsOnCall: doNothing,
  6798. getLiteralValue() {
  6799. return SymbolToStringTag;
  6800. },
  6801. hasEffectsWhenCalled: returnTrue
  6802. }
  6803. }
  6804. },
  6805. SyntaxError: PC,
  6806. toLocaleString: O,
  6807. toString: O,
  6808. TypeError: PC,
  6809. Uint16Array: ARRAY_TYPE,
  6810. Uint32Array: ARRAY_TYPE,
  6811. Uint8Array: ARRAY_TYPE,
  6812. Uint8ClampedArray: ARRAY_TYPE,
  6813. // Technically, this is a global, but it needs special handling
  6814. // undefined: ?,
  6815. unescape: PF,
  6816. URIError: PC,
  6817. valueOf: O,
  6818. WeakMap: PC_WITH_ARRAY,
  6819. WeakSet: PC_WITH_ARRAY,
  6820. // Additional globals shared by Node and Browser that are not strictly part of the language
  6821. clearInterval: C,
  6822. clearTimeout: C,
  6823. console: {
  6824. __proto__: null,
  6825. [ValueProperties]: IMPURE,
  6826. assert: C,
  6827. clear: C,
  6828. count: C,
  6829. countReset: C,
  6830. debug: C,
  6831. dir: C,
  6832. dirxml: C,
  6833. error: C,
  6834. exception: C,
  6835. group: C,
  6836. groupCollapsed: C,
  6837. groupEnd: C,
  6838. info: C,
  6839. log: C,
  6840. table: C,
  6841. time: C,
  6842. timeEnd: C,
  6843. timeLog: C,
  6844. trace: C,
  6845. warn: C
  6846. },
  6847. Intl: {
  6848. __proto__: null,
  6849. [ValueProperties]: IMPURE,
  6850. Collator: INTL_MEMBER,
  6851. DateTimeFormat: INTL_MEMBER,
  6852. DisplayNames: INTL_MEMBER,
  6853. ListFormat: INTL_MEMBER,
  6854. Locale: INTL_MEMBER,
  6855. NumberFormat: INTL_MEMBER,
  6856. PluralRules: INTL_MEMBER,
  6857. RelativeTimeFormat: INTL_MEMBER,
  6858. Segmenter: INTL_MEMBER
  6859. },
  6860. setInterval: C,
  6861. setTimeout: C,
  6862. TextDecoder: C,
  6863. TextEncoder: C,
  6864. URL: {
  6865. __proto__: null,
  6866. [ValueProperties]: IMPURE,
  6867. prototype: O,
  6868. canParse: PF
  6869. },
  6870. URLSearchParams: C,
  6871. // Browser specific globals
  6872. AbortController: C,
  6873. AbortSignal: C,
  6874. addEventListener: O,
  6875. alert: O,
  6876. AnalyserNode: C,
  6877. Animation: C,
  6878. AnimationEvent: C,
  6879. applicationCache: O,
  6880. ApplicationCache: C,
  6881. ApplicationCacheErrorEvent: C,
  6882. atob: O,
  6883. Attr: C,
  6884. Audio: C,
  6885. AudioBuffer: C,
  6886. AudioBufferSourceNode: C,
  6887. AudioContext: C,
  6888. AudioDestinationNode: C,
  6889. AudioListener: C,
  6890. AudioNode: C,
  6891. AudioParam: C,
  6892. AudioProcessingEvent: C,
  6893. AudioScheduledSourceNode: C,
  6894. AudioWorkletNode: C,
  6895. BarProp: C,
  6896. BaseAudioContext: C,
  6897. BatteryManager: C,
  6898. BeforeUnloadEvent: C,
  6899. BiquadFilterNode: C,
  6900. Blob: C,
  6901. BlobEvent: C,
  6902. blur: O,
  6903. BroadcastChannel: C,
  6904. btoa: O,
  6905. ByteLengthQueuingStrategy: C,
  6906. Cache: C,
  6907. caches: O,
  6908. CacheStorage: C,
  6909. cancelAnimationFrame: O,
  6910. cancelIdleCallback: O,
  6911. CanvasCaptureMediaStreamTrack: C,
  6912. CanvasGradient: C,
  6913. CanvasPattern: C,
  6914. CanvasRenderingContext2D: C,
  6915. ChannelMergerNode: C,
  6916. ChannelSplitterNode: C,
  6917. CharacterData: C,
  6918. clientInformation: O,
  6919. ClipboardEvent: C,
  6920. close: O,
  6921. closed: O,
  6922. CloseEvent: C,
  6923. Comment: C,
  6924. CompositionEvent: C,
  6925. confirm: O,
  6926. ConstantSourceNode: C,
  6927. ConvolverNode: C,
  6928. CountQueuingStrategy: C,
  6929. createImageBitmap: O,
  6930. Credential: C,
  6931. CredentialsContainer: C,
  6932. crypto: O,
  6933. Crypto: C,
  6934. CryptoKey: C,
  6935. CSS: C,
  6936. CSSConditionRule: C,
  6937. CSSFontFaceRule: C,
  6938. CSSGroupingRule: C,
  6939. CSSImportRule: C,
  6940. CSSKeyframeRule: C,
  6941. CSSKeyframesRule: C,
  6942. CSSMediaRule: C,
  6943. CSSNamespaceRule: C,
  6944. CSSPageRule: C,
  6945. CSSRule: C,
  6946. CSSRuleList: C,
  6947. CSSStyleDeclaration: C,
  6948. CSSStyleRule: C,
  6949. CSSStyleSheet: C,
  6950. CSSSupportsRule: C,
  6951. CustomElementRegistry: C,
  6952. customElements: O,
  6953. CustomEvent: {
  6954. __proto__: null,
  6955. [ValueProperties]: {
  6956. deoptimizeArgumentsOnCall({ args }) {
  6957. args[2]?.deoptimizePath(['detail']);
  6958. },
  6959. getLiteralValue: getTruthyLiteralValue,
  6960. hasEffectsWhenCalled: returnFalse
  6961. },
  6962. prototype: O
  6963. },
  6964. DataTransfer: C,
  6965. DataTransferItem: C,
  6966. DataTransferItemList: C,
  6967. defaultstatus: O,
  6968. defaultStatus: O,
  6969. DelayNode: C,
  6970. DeviceMotionEvent: C,
  6971. DeviceOrientationEvent: C,
  6972. devicePixelRatio: O,
  6973. dispatchEvent: O,
  6974. document: O,
  6975. Document: C,
  6976. DocumentFragment: C,
  6977. DocumentType: C,
  6978. DOMError: C,
  6979. DOMException: C,
  6980. DOMImplementation: C,
  6981. DOMMatrix: C,
  6982. DOMMatrixReadOnly: C,
  6983. DOMParser: C,
  6984. DOMPoint: C,
  6985. DOMPointReadOnly: C,
  6986. DOMQuad: C,
  6987. DOMRect: C,
  6988. DOMRectReadOnly: C,
  6989. DOMStringList: C,
  6990. DOMStringMap: C,
  6991. DOMTokenList: C,
  6992. DragEvent: C,
  6993. DynamicsCompressorNode: C,
  6994. Element: C,
  6995. ErrorEvent: C,
  6996. Event: C,
  6997. EventSource: C,
  6998. EventTarget: C,
  6999. external: O,
  7000. fetch: O,
  7001. File: C,
  7002. FileList: C,
  7003. FileReader: C,
  7004. find: O,
  7005. focus: O,
  7006. FocusEvent: C,
  7007. FontFace: C,
  7008. FontFaceSetLoadEvent: C,
  7009. FormData: C,
  7010. frames: O,
  7011. GainNode: C,
  7012. Gamepad: C,
  7013. GamepadButton: C,
  7014. GamepadEvent: C,
  7015. getComputedStyle: O,
  7016. getSelection: O,
  7017. HashChangeEvent: C,
  7018. Headers: C,
  7019. history: O,
  7020. History: C,
  7021. HTMLAllCollection: C,
  7022. HTMLAnchorElement: C,
  7023. HTMLAreaElement: C,
  7024. HTMLAudioElement: C,
  7025. HTMLBaseElement: C,
  7026. HTMLBodyElement: C,
  7027. HTMLBRElement: C,
  7028. HTMLButtonElement: C,
  7029. HTMLCanvasElement: C,
  7030. HTMLCollection: C,
  7031. HTMLContentElement: C,
  7032. HTMLDataElement: C,
  7033. HTMLDataListElement: C,
  7034. HTMLDetailsElement: C,
  7035. HTMLDialogElement: C,
  7036. HTMLDirectoryElement: C,
  7037. HTMLDivElement: C,
  7038. HTMLDListElement: C,
  7039. HTMLDocument: C,
  7040. HTMLElement: C,
  7041. HTMLEmbedElement: C,
  7042. HTMLFieldSetElement: C,
  7043. HTMLFontElement: C,
  7044. HTMLFormControlsCollection: C,
  7045. HTMLFormElement: C,
  7046. HTMLFrameElement: C,
  7047. HTMLFrameSetElement: C,
  7048. HTMLHeadElement: C,
  7049. HTMLHeadingElement: C,
  7050. HTMLHRElement: C,
  7051. HTMLHtmlElement: C,
  7052. HTMLIFrameElement: C,
  7053. HTMLImageElement: C,
  7054. HTMLInputElement: C,
  7055. HTMLLabelElement: C,
  7056. HTMLLegendElement: C,
  7057. HTMLLIElement: C,
  7058. HTMLLinkElement: C,
  7059. HTMLMapElement: C,
  7060. HTMLMarqueeElement: C,
  7061. HTMLMediaElement: C,
  7062. HTMLMenuElement: C,
  7063. HTMLMetaElement: C,
  7064. HTMLMeterElement: C,
  7065. HTMLModElement: C,
  7066. HTMLObjectElement: C,
  7067. HTMLOListElement: C,
  7068. HTMLOptGroupElement: C,
  7069. HTMLOptionElement: C,
  7070. HTMLOptionsCollection: C,
  7071. HTMLOutputElement: C,
  7072. HTMLParagraphElement: C,
  7073. HTMLParamElement: C,
  7074. HTMLPictureElement: C,
  7075. HTMLPreElement: C,
  7076. HTMLProgressElement: C,
  7077. HTMLQuoteElement: C,
  7078. HTMLScriptElement: C,
  7079. HTMLSelectElement: C,
  7080. HTMLShadowElement: C,
  7081. HTMLSlotElement: C,
  7082. HTMLSourceElement: C,
  7083. HTMLSpanElement: C,
  7084. HTMLStyleElement: C,
  7085. HTMLTableCaptionElement: C,
  7086. HTMLTableCellElement: C,
  7087. HTMLTableColElement: C,
  7088. HTMLTableElement: C,
  7089. HTMLTableRowElement: C,
  7090. HTMLTableSectionElement: C,
  7091. HTMLTemplateElement: C,
  7092. HTMLTextAreaElement: C,
  7093. HTMLTimeElement: C,
  7094. HTMLTitleElement: C,
  7095. HTMLTrackElement: C,
  7096. HTMLUListElement: C,
  7097. HTMLUnknownElement: C,
  7098. HTMLVideoElement: C,
  7099. IDBCursor: C,
  7100. IDBCursorWithValue: C,
  7101. IDBDatabase: C,
  7102. IDBFactory: C,
  7103. IDBIndex: C,
  7104. IDBKeyRange: C,
  7105. IDBObjectStore: C,
  7106. IDBOpenDBRequest: C,
  7107. IDBRequest: C,
  7108. IDBTransaction: C,
  7109. IDBVersionChangeEvent: C,
  7110. IdleDeadline: C,
  7111. IIRFilterNode: C,
  7112. Image: C,
  7113. ImageBitmap: C,
  7114. ImageBitmapRenderingContext: C,
  7115. ImageCapture: C,
  7116. ImageData: C,
  7117. indexedDB: O,
  7118. innerHeight: O,
  7119. innerWidth: O,
  7120. InputEvent: C,
  7121. IntersectionObserver: C,
  7122. IntersectionObserverEntry: C,
  7123. isSecureContext: O,
  7124. KeyboardEvent: C,
  7125. KeyframeEffect: C,
  7126. length: O,
  7127. localStorage: O,
  7128. location: O,
  7129. Location: C,
  7130. locationbar: O,
  7131. matchMedia: O,
  7132. MediaDeviceInfo: C,
  7133. MediaDevices: C,
  7134. MediaElementAudioSourceNode: C,
  7135. MediaEncryptedEvent: C,
  7136. MediaError: C,
  7137. MediaKeyMessageEvent: C,
  7138. MediaKeySession: C,
  7139. MediaKeyStatusMap: C,
  7140. MediaKeySystemAccess: C,
  7141. MediaList: C,
  7142. MediaQueryList: C,
  7143. MediaQueryListEvent: C,
  7144. MediaRecorder: C,
  7145. MediaSettingsRange: C,
  7146. MediaSource: C,
  7147. MediaStream: C,
  7148. MediaStreamAudioDestinationNode: C,
  7149. MediaStreamAudioSourceNode: C,
  7150. MediaStreamEvent: C,
  7151. MediaStreamTrack: C,
  7152. MediaStreamTrackEvent: C,
  7153. menubar: O,
  7154. MessageChannel: C,
  7155. MessageEvent: C,
  7156. MessagePort: C,
  7157. MIDIAccess: C,
  7158. MIDIConnectionEvent: C,
  7159. MIDIInput: C,
  7160. MIDIInputMap: C,
  7161. MIDIMessageEvent: C,
  7162. MIDIOutput: C,
  7163. MIDIOutputMap: C,
  7164. MIDIPort: C,
  7165. MimeType: C,
  7166. MimeTypeArray: C,
  7167. MouseEvent: C,
  7168. moveBy: O,
  7169. moveTo: O,
  7170. MutationEvent: C,
  7171. MutationObserver: C,
  7172. MutationRecord: C,
  7173. name: O,
  7174. NamedNodeMap: C,
  7175. NavigationPreloadManager: C,
  7176. navigator: O,
  7177. Navigator: C,
  7178. NetworkInformation: C,
  7179. Node: C,
  7180. NodeFilter: O,
  7181. NodeIterator: C,
  7182. NodeList: C,
  7183. Notification: C,
  7184. OfflineAudioCompletionEvent: C,
  7185. OfflineAudioContext: C,
  7186. offscreenBuffering: O,
  7187. OffscreenCanvas: C,
  7188. open: O,
  7189. openDatabase: O,
  7190. Option: C,
  7191. origin: O,
  7192. OscillatorNode: C,
  7193. outerHeight: O,
  7194. outerWidth: O,
  7195. PageTransitionEvent: C,
  7196. pageXOffset: O,
  7197. pageYOffset: O,
  7198. PannerNode: C,
  7199. parent: O,
  7200. Path2D: C,
  7201. PaymentAddress: C,
  7202. PaymentRequest: C,
  7203. PaymentRequestUpdateEvent: C,
  7204. PaymentResponse: C,
  7205. performance: O,
  7206. Performance: C,
  7207. PerformanceEntry: C,
  7208. PerformanceLongTaskTiming: C,
  7209. PerformanceMark: C,
  7210. PerformanceMeasure: C,
  7211. PerformanceNavigation: C,
  7212. PerformanceNavigationTiming: C,
  7213. PerformanceObserver: C,
  7214. PerformanceObserverEntryList: C,
  7215. PerformancePaintTiming: C,
  7216. PerformanceResourceTiming: C,
  7217. PerformanceTiming: C,
  7218. PeriodicWave: C,
  7219. Permissions: C,
  7220. PermissionStatus: C,
  7221. personalbar: O,
  7222. PhotoCapabilities: C,
  7223. Plugin: C,
  7224. PluginArray: C,
  7225. PointerEvent: C,
  7226. PopStateEvent: C,
  7227. postMessage: O,
  7228. Presentation: C,
  7229. PresentationAvailability: C,
  7230. PresentationConnection: C,
  7231. PresentationConnectionAvailableEvent: C,
  7232. PresentationConnectionCloseEvent: C,
  7233. PresentationConnectionList: C,
  7234. PresentationReceiver: C,
  7235. PresentationRequest: C,
  7236. print: O,
  7237. ProcessingInstruction: C,
  7238. ProgressEvent: C,
  7239. PromiseRejectionEvent: C,
  7240. prompt: O,
  7241. PushManager: C,
  7242. PushSubscription: C,
  7243. PushSubscriptionOptions: C,
  7244. queueMicrotask: O,
  7245. RadioNodeList: C,
  7246. Range: C,
  7247. ReadableStream: C,
  7248. RemotePlayback: C,
  7249. removeEventListener: O,
  7250. Request: C,
  7251. requestAnimationFrame: O,
  7252. requestIdleCallback: O,
  7253. resizeBy: O,
  7254. ResizeObserver: C,
  7255. ResizeObserverEntry: C,
  7256. resizeTo: O,
  7257. Response: C,
  7258. RTCCertificate: C,
  7259. RTCDataChannel: C,
  7260. RTCDataChannelEvent: C,
  7261. RTCDtlsTransport: C,
  7262. RTCIceCandidate: C,
  7263. RTCIceTransport: C,
  7264. RTCPeerConnection: C,
  7265. RTCPeerConnectionIceEvent: C,
  7266. RTCRtpReceiver: C,
  7267. RTCRtpSender: C,
  7268. RTCSctpTransport: C,
  7269. RTCSessionDescription: C,
  7270. RTCStatsReport: C,
  7271. RTCTrackEvent: C,
  7272. screen: O,
  7273. Screen: C,
  7274. screenLeft: O,
  7275. ScreenOrientation: C,
  7276. screenTop: O,
  7277. screenX: O,
  7278. screenY: O,
  7279. ScriptProcessorNode: C,
  7280. scroll: O,
  7281. scrollbars: O,
  7282. scrollBy: O,
  7283. scrollTo: O,
  7284. scrollX: O,
  7285. scrollY: O,
  7286. SecurityPolicyViolationEvent: C,
  7287. Selection: C,
  7288. ServiceWorker: C,
  7289. ServiceWorkerContainer: C,
  7290. ServiceWorkerRegistration: C,
  7291. sessionStorage: O,
  7292. ShadowRoot: C,
  7293. SharedWorker: C,
  7294. SourceBuffer: C,
  7295. SourceBufferList: C,
  7296. speechSynthesis: O,
  7297. SpeechSynthesisEvent: C,
  7298. SpeechSynthesisUtterance: C,
  7299. StaticRange: C,
  7300. status: O,
  7301. statusbar: O,
  7302. StereoPannerNode: C,
  7303. stop: O,
  7304. Storage: C,
  7305. StorageEvent: C,
  7306. StorageManager: C,
  7307. styleMedia: O,
  7308. StyleSheet: C,
  7309. StyleSheetList: C,
  7310. SubtleCrypto: C,
  7311. SVGAElement: C,
  7312. SVGAngle: C,
  7313. SVGAnimatedAngle: C,
  7314. SVGAnimatedBoolean: C,
  7315. SVGAnimatedEnumeration: C,
  7316. SVGAnimatedInteger: C,
  7317. SVGAnimatedLength: C,
  7318. SVGAnimatedLengthList: C,
  7319. SVGAnimatedNumber: C,
  7320. SVGAnimatedNumberList: C,
  7321. SVGAnimatedPreserveAspectRatio: C,
  7322. SVGAnimatedRect: C,
  7323. SVGAnimatedString: C,
  7324. SVGAnimatedTransformList: C,
  7325. SVGAnimateElement: C,
  7326. SVGAnimateMotionElement: C,
  7327. SVGAnimateTransformElement: C,
  7328. SVGAnimationElement: C,
  7329. SVGCircleElement: C,
  7330. SVGClipPathElement: C,
  7331. SVGComponentTransferFunctionElement: C,
  7332. SVGDefsElement: C,
  7333. SVGDescElement: C,
  7334. SVGDiscardElement: C,
  7335. SVGElement: C,
  7336. SVGEllipseElement: C,
  7337. SVGFEBlendElement: C,
  7338. SVGFEColorMatrixElement: C,
  7339. SVGFEComponentTransferElement: C,
  7340. SVGFECompositeElement: C,
  7341. SVGFEConvolveMatrixElement: C,
  7342. SVGFEDiffuseLightingElement: C,
  7343. SVGFEDisplacementMapElement: C,
  7344. SVGFEDistantLightElement: C,
  7345. SVGFEDropShadowElement: C,
  7346. SVGFEFloodElement: C,
  7347. SVGFEFuncAElement: C,
  7348. SVGFEFuncBElement: C,
  7349. SVGFEFuncGElement: C,
  7350. SVGFEFuncRElement: C,
  7351. SVGFEGaussianBlurElement: C,
  7352. SVGFEImageElement: C,
  7353. SVGFEMergeElement: C,
  7354. SVGFEMergeNodeElement: C,
  7355. SVGFEMorphologyElement: C,
  7356. SVGFEOffsetElement: C,
  7357. SVGFEPointLightElement: C,
  7358. SVGFESpecularLightingElement: C,
  7359. SVGFESpotLightElement: C,
  7360. SVGFETileElement: C,
  7361. SVGFETurbulenceElement: C,
  7362. SVGFilterElement: C,
  7363. SVGForeignObjectElement: C,
  7364. SVGGElement: C,
  7365. SVGGeometryElement: C,
  7366. SVGGradientElement: C,
  7367. SVGGraphicsElement: C,
  7368. SVGImageElement: C,
  7369. SVGLength: C,
  7370. SVGLengthList: C,
  7371. SVGLinearGradientElement: C,
  7372. SVGLineElement: C,
  7373. SVGMarkerElement: C,
  7374. SVGMaskElement: C,
  7375. SVGMatrix: C,
  7376. SVGMetadataElement: C,
  7377. SVGMPathElement: C,
  7378. SVGNumber: C,
  7379. SVGNumberList: C,
  7380. SVGPathElement: C,
  7381. SVGPatternElement: C,
  7382. SVGPoint: C,
  7383. SVGPointList: C,
  7384. SVGPolygonElement: C,
  7385. SVGPolylineElement: C,
  7386. SVGPreserveAspectRatio: C,
  7387. SVGRadialGradientElement: C,
  7388. SVGRect: C,
  7389. SVGRectElement: C,
  7390. SVGScriptElement: C,
  7391. SVGSetElement: C,
  7392. SVGStopElement: C,
  7393. SVGStringList: C,
  7394. SVGStyleElement: C,
  7395. SVGSVGElement: C,
  7396. SVGSwitchElement: C,
  7397. SVGSymbolElement: C,
  7398. SVGTextContentElement: C,
  7399. SVGTextElement: C,
  7400. SVGTextPathElement: C,
  7401. SVGTextPositioningElement: C,
  7402. SVGTitleElement: C,
  7403. SVGTransform: C,
  7404. SVGTransformList: C,
  7405. SVGTSpanElement: C,
  7406. SVGUnitTypes: C,
  7407. SVGUseElement: C,
  7408. SVGViewElement: C,
  7409. TaskAttributionTiming: C,
  7410. Text: C,
  7411. TextEvent: C,
  7412. TextMetrics: C,
  7413. TextTrack: C,
  7414. TextTrackCue: C,
  7415. TextTrackCueList: C,
  7416. TextTrackList: C,
  7417. TimeRanges: C,
  7418. toolbar: O,
  7419. top: O,
  7420. Touch: C,
  7421. TouchEvent: C,
  7422. TouchList: C,
  7423. TrackEvent: C,
  7424. TransitionEvent: C,
  7425. TreeWalker: C,
  7426. UIEvent: C,
  7427. ValidityState: C,
  7428. visualViewport: O,
  7429. VisualViewport: C,
  7430. VTTCue: C,
  7431. WaveShaperNode: C,
  7432. WebAssembly: O,
  7433. WebGL2RenderingContext: C,
  7434. WebGLActiveInfo: C,
  7435. WebGLBuffer: C,
  7436. WebGLContextEvent: C,
  7437. WebGLFramebuffer: C,
  7438. WebGLProgram: C,
  7439. WebGLQuery: C,
  7440. WebGLRenderbuffer: C,
  7441. WebGLRenderingContext: C,
  7442. WebGLSampler: C,
  7443. WebGLShader: C,
  7444. WebGLShaderPrecisionFormat: C,
  7445. WebGLSync: C,
  7446. WebGLTexture: C,
  7447. WebGLTransformFeedback: C,
  7448. WebGLUniformLocation: C,
  7449. WebGLVertexArrayObject: C,
  7450. WebSocket: C,
  7451. WheelEvent: C,
  7452. Window: C,
  7453. Worker: C,
  7454. WritableStream: C,
  7455. XMLDocument: C,
  7456. XMLHttpRequest: C,
  7457. XMLHttpRequestEventTarget: C,
  7458. XMLHttpRequestUpload: C,
  7459. XMLSerializer: C,
  7460. XPathEvaluator: C,
  7461. XPathExpression: C,
  7462. XPathResult: C,
  7463. XSLTProcessor: C
  7464. };
  7465. for (const global of ['window', 'global', 'self', 'globalThis']) {
  7466. knownGlobals[global] = knownGlobals;
  7467. }
  7468. function getGlobalAtPath(path) {
  7469. let currentGlobal = knownGlobals;
  7470. for (const pathSegment of path) {
  7471. if (typeof pathSegment !== 'string') {
  7472. return null;
  7473. }
  7474. currentGlobal = currentGlobal[pathSegment];
  7475. if (!currentGlobal) {
  7476. return null;
  7477. }
  7478. }
  7479. return currentGlobal[ValueProperties];
  7480. }
  7481. class GlobalVariable extends Variable {
  7482. constructor() {
  7483. super(...arguments);
  7484. // Ensure we use live-bindings for globals as we do not know if they have
  7485. // been reassigned
  7486. this.isReassigned = true;
  7487. }
  7488. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  7489. switch (interaction.type) {
  7490. // While there is no point in testing these cases as at the moment, they
  7491. // are also covered via other means, we keep them for completeness
  7492. case INTERACTION_ACCESSED:
  7493. case INTERACTION_ASSIGNED: {
  7494. if (!getGlobalAtPath([this.name, ...path].slice(0, -1))) {
  7495. super.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  7496. }
  7497. return;
  7498. }
  7499. case INTERACTION_CALLED: {
  7500. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  7501. if (globalAtPath) {
  7502. globalAtPath.deoptimizeArgumentsOnCall(interaction);
  7503. }
  7504. else {
  7505. super.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  7506. }
  7507. return;
  7508. }
  7509. }
  7510. }
  7511. getLiteralValueAtPath(path, _recursionTracker, _origin) {
  7512. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  7513. return globalAtPath ? globalAtPath.getLiteralValue() : UnknownValue;
  7514. }
  7515. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7516. switch (interaction.type) {
  7517. case INTERACTION_ACCESSED: {
  7518. if (path.length === 0) {
  7519. // Technically, "undefined" is a global variable of sorts
  7520. return this.name !== 'undefined' && !getGlobalAtPath([this.name]);
  7521. }
  7522. return !getGlobalAtPath([this.name, ...path].slice(0, -1));
  7523. }
  7524. case INTERACTION_ASSIGNED: {
  7525. return true;
  7526. }
  7527. case INTERACTION_CALLED: {
  7528. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  7529. return !globalAtPath || globalAtPath.hasEffectsWhenCalled(interaction, context);
  7530. }
  7531. }
  7532. }
  7533. }
  7534. const tdzVariableKinds = {
  7535. __proto__: null,
  7536. class: true,
  7537. const: true,
  7538. let: true,
  7539. var: true
  7540. };
  7541. class Identifier extends NodeBase {
  7542. constructor() {
  7543. super(...arguments);
  7544. this.variable = null;
  7545. this.isTDZAccess = null;
  7546. }
  7547. addExportedVariables(variables, exportNamesByVariable) {
  7548. if (exportNamesByVariable.has(this.variable)) {
  7549. variables.push(this.variable);
  7550. }
  7551. }
  7552. bind() {
  7553. if (!this.variable && is_reference(this, this.parent)) {
  7554. this.variable = this.scope.findVariable(this.name);
  7555. this.variable.addReference(this);
  7556. }
  7557. }
  7558. declare(kind, init) {
  7559. let variable;
  7560. const { treeshake } = this.context.options;
  7561. switch (kind) {
  7562. case 'var': {
  7563. variable = this.scope.addDeclaration(this, this.context, init, true);
  7564. if (treeshake && treeshake.correctVarValueBeforeDeclaration) {
  7565. // Necessary to make sure the init is deoptimized. We cannot call deoptimizePath here.
  7566. variable.markInitializersForDeoptimization();
  7567. }
  7568. break;
  7569. }
  7570. case 'function': {
  7571. // in strict mode, functions are only hoisted within a scope but not across block scopes
  7572. variable = this.scope.addDeclaration(this, this.context, init, false);
  7573. break;
  7574. }
  7575. case 'let':
  7576. case 'const':
  7577. case 'class': {
  7578. variable = this.scope.addDeclaration(this, this.context, init, false);
  7579. break;
  7580. }
  7581. case 'parameter': {
  7582. variable = this.scope.addParameterDeclaration(this);
  7583. break;
  7584. }
  7585. /* istanbul ignore next */
  7586. default: {
  7587. /* istanbul ignore next */
  7588. throw new Error(`Internal Error: Unexpected identifier kind ${kind}.`);
  7589. }
  7590. }
  7591. variable.kind = kind;
  7592. return [(this.variable = variable)];
  7593. }
  7594. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  7595. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  7596. }
  7597. deoptimizePath(path) {
  7598. if (path.length === 0 && !this.scope.contains(this.name)) {
  7599. this.disallowImportReassignment();
  7600. }
  7601. // We keep conditional chaining because an unknown Node could have an
  7602. // Identifier as property that might be deoptimized by default
  7603. this.variable?.deoptimizePath(path);
  7604. }
  7605. getLiteralValueAtPath(path, recursionTracker, origin) {
  7606. return this.getVariableRespectingTDZ().getLiteralValueAtPath(path, recursionTracker, origin);
  7607. }
  7608. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  7609. const [expression, isPure] = this.getVariableRespectingTDZ().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  7610. return [expression, isPure || this.isPureFunction(path)];
  7611. }
  7612. hasEffects(context) {
  7613. if (!this.deoptimized)
  7614. this.applyDeoptimizations();
  7615. if (this.isPossibleTDZ() && this.variable.kind !== 'var') {
  7616. return true;
  7617. }
  7618. return (this.context.options.treeshake.unknownGlobalSideEffects &&
  7619. this.variable instanceof GlobalVariable &&
  7620. !this.isPureFunction(EMPTY_PATH) &&
  7621. this.variable.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context));
  7622. }
  7623. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7624. switch (interaction.type) {
  7625. case INTERACTION_ACCESSED: {
  7626. return (this.variable !== null &&
  7627. !this.isPureFunction(path) &&
  7628. this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context));
  7629. }
  7630. case INTERACTION_ASSIGNED: {
  7631. return (path.length > 0 ? this.getVariableRespectingTDZ() : this.variable).hasEffectsOnInteractionAtPath(path, interaction, context);
  7632. }
  7633. case INTERACTION_CALLED: {
  7634. return (!this.isPureFunction(path) &&
  7635. this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context));
  7636. }
  7637. }
  7638. }
  7639. include() {
  7640. if (!this.deoptimized)
  7641. this.applyDeoptimizations();
  7642. if (!this.included) {
  7643. this.included = true;
  7644. if (this.variable !== null) {
  7645. this.context.includeVariableInModule(this.variable);
  7646. }
  7647. }
  7648. }
  7649. includeCallArguments(context, parameters) {
  7650. this.variable.includeCallArguments(context, parameters);
  7651. }
  7652. isPossibleTDZ() {
  7653. // return cached value to avoid issues with the next tree-shaking pass
  7654. if (this.isTDZAccess !== null)
  7655. return this.isTDZAccess;
  7656. if (!(this.variable instanceof LocalVariable &&
  7657. this.variable.kind &&
  7658. this.variable.kind in tdzVariableKinds &&
  7659. // we ignore possible TDZs due to circular module dependencies as
  7660. // otherwise we get many false positives
  7661. this.variable.module === this.context.module)) {
  7662. return (this.isTDZAccess = false);
  7663. }
  7664. let decl_id;
  7665. if (this.variable.declarations &&
  7666. this.variable.declarations.length === 1 &&
  7667. (decl_id = this.variable.declarations[0]) &&
  7668. this.start < decl_id.start &&
  7669. closestParentFunctionOrProgram(this) === closestParentFunctionOrProgram(decl_id)) {
  7670. // a variable accessed before its declaration
  7671. // in the same function or at top level of module
  7672. return (this.isTDZAccess = true);
  7673. }
  7674. if (!this.variable.initReached) {
  7675. // Either a const/let TDZ violation or
  7676. // var use before declaration was encountered.
  7677. return (this.isTDZAccess = true);
  7678. }
  7679. return (this.isTDZAccess = false);
  7680. }
  7681. markDeclarationReached() {
  7682. this.variable.initReached = true;
  7683. }
  7684. render(code, { snippets: { getPropertyAccess }, useOriginalName }, { renderedParentType, isCalleeOfRenderedParent, isShorthandProperty } = BLANK) {
  7685. if (this.variable) {
  7686. const name = this.variable.getName(getPropertyAccess, useOriginalName);
  7687. if (name !== this.name) {
  7688. code.overwrite(this.start, this.end, name, {
  7689. contentOnly: true,
  7690. storeName: true
  7691. });
  7692. if (isShorthandProperty) {
  7693. code.prependRight(this.start, `${this.name}: `);
  7694. }
  7695. }
  7696. // In strict mode, any variable named "eval" must be the actual "eval" function
  7697. if (name === 'eval' &&
  7698. renderedParentType === CallExpression$1 &&
  7699. isCalleeOfRenderedParent) {
  7700. code.appendRight(this.start, '0, ');
  7701. }
  7702. }
  7703. }
  7704. applyDeoptimizations() {
  7705. this.deoptimized = true;
  7706. if (this.variable instanceof LocalVariable) {
  7707. this.variable.consolidateInitializers();
  7708. this.context.requestTreeshakingPass();
  7709. }
  7710. }
  7711. disallowImportReassignment() {
  7712. return this.context.error(logIllegalImportReassignment(this.name, this.context.module.id), this.start);
  7713. }
  7714. getVariableRespectingTDZ() {
  7715. if (this.isPossibleTDZ()) {
  7716. return UNKNOWN_EXPRESSION;
  7717. }
  7718. return this.variable;
  7719. }
  7720. isPureFunction(path) {
  7721. let currentPureFunction = this.context.manualPureFunctions[this.name];
  7722. for (const segment of path) {
  7723. if (currentPureFunction) {
  7724. if (currentPureFunction[PureFunctionKey]) {
  7725. return true;
  7726. }
  7727. currentPureFunction = currentPureFunction[segment];
  7728. }
  7729. else {
  7730. return false;
  7731. }
  7732. }
  7733. return currentPureFunction?.[PureFunctionKey];
  7734. }
  7735. }
  7736. function closestParentFunctionOrProgram(node) {
  7737. while (node && !/^Program|Function/.test(node.type)) {
  7738. node = node.parent;
  7739. }
  7740. // one of: ArrowFunctionExpression, FunctionDeclaration, FunctionExpression or Program
  7741. return node;
  7742. }
  7743. function treeshakeNode(node, code, start, end) {
  7744. code.remove(start, end);
  7745. if (node.annotations) {
  7746. for (const annotation of node.annotations) {
  7747. if (annotation.start < start) {
  7748. code.remove(annotation.start, annotation.end);
  7749. }
  7750. else {
  7751. return;
  7752. }
  7753. }
  7754. }
  7755. }
  7756. function removeAnnotations(node, code) {
  7757. if (!node.annotations && node.parent.type === ExpressionStatement$1) {
  7758. node = node.parent;
  7759. }
  7760. if (node.annotations) {
  7761. for (const annotation of node.annotations) {
  7762. code.remove(annotation.start, annotation.end);
  7763. }
  7764. }
  7765. }
  7766. const NO_SEMICOLON = { isNoStatement: true };
  7767. // This assumes there are only white-space and comments between start and the string we are looking for
  7768. function findFirstOccurrenceOutsideComment(code, searchString, start = 0) {
  7769. let searchPos, charCodeAfterSlash;
  7770. searchPos = code.indexOf(searchString, start);
  7771. while (true) {
  7772. start = code.indexOf('/', start);
  7773. if (start === -1 || start >= searchPos)
  7774. return searchPos;
  7775. charCodeAfterSlash = code.charCodeAt(++start);
  7776. ++start;
  7777. // With our assumption, '/' always starts a comment. Determine comment type:
  7778. start =
  7779. charCodeAfterSlash === 47 /*"/"*/
  7780. ? code.indexOf('\n', start) + 1
  7781. : code.indexOf('*/', start) + 2;
  7782. if (start > searchPos) {
  7783. searchPos = code.indexOf(searchString, start);
  7784. }
  7785. }
  7786. }
  7787. const NON_WHITESPACE = /\S/g;
  7788. function findNonWhiteSpace(code, index) {
  7789. NON_WHITESPACE.lastIndex = index;
  7790. const result = NON_WHITESPACE.exec(code);
  7791. return result.index;
  7792. }
  7793. // This assumes "code" only contains white-space and comments
  7794. // Returns position of line-comment if applicable
  7795. function findFirstLineBreakOutsideComment(code) {
  7796. let lineBreakPos, charCodeAfterSlash, start = 0;
  7797. lineBreakPos = code.indexOf('\n', start);
  7798. while (true) {
  7799. start = code.indexOf('/', start);
  7800. if (start === -1 || start > lineBreakPos)
  7801. return [lineBreakPos, lineBreakPos + 1];
  7802. // With our assumption, '/' always starts a comment. Determine comment type:
  7803. charCodeAfterSlash = code.charCodeAt(start + 1);
  7804. if (charCodeAfterSlash === 47 /*"/"*/)
  7805. return [start, lineBreakPos + 1];
  7806. start = code.indexOf('*/', start + 3) + 2;
  7807. if (start > lineBreakPos) {
  7808. lineBreakPos = code.indexOf('\n', start);
  7809. }
  7810. }
  7811. }
  7812. function renderStatementList(statements, code, start, end, options) {
  7813. let currentNode, currentNodeStart, currentNodeNeedsBoundaries, nextNodeStart;
  7814. let nextNode = statements[0];
  7815. let nextNodeNeedsBoundaries = !nextNode.included || nextNode.needsBoundaries;
  7816. if (nextNodeNeedsBoundaries) {
  7817. nextNodeStart =
  7818. start + findFirstLineBreakOutsideComment(code.original.slice(start, nextNode.start))[1];
  7819. }
  7820. for (let nextIndex = 1; nextIndex <= statements.length; nextIndex++) {
  7821. currentNode = nextNode;
  7822. currentNodeStart = nextNodeStart;
  7823. currentNodeNeedsBoundaries = nextNodeNeedsBoundaries;
  7824. nextNode = statements[nextIndex];
  7825. nextNodeNeedsBoundaries =
  7826. nextNode === undefined ? false : !nextNode.included || nextNode.needsBoundaries;
  7827. if (currentNodeNeedsBoundaries || nextNodeNeedsBoundaries) {
  7828. nextNodeStart =
  7829. currentNode.end +
  7830. findFirstLineBreakOutsideComment(code.original.slice(currentNode.end, nextNode === undefined ? end : nextNode.start))[1];
  7831. if (currentNode.included) {
  7832. currentNodeNeedsBoundaries
  7833. ? currentNode.render(code, options, {
  7834. end: nextNodeStart,
  7835. start: currentNodeStart
  7836. })
  7837. : currentNode.render(code, options);
  7838. }
  7839. else {
  7840. treeshakeNode(currentNode, code, currentNodeStart, nextNodeStart);
  7841. }
  7842. }
  7843. else {
  7844. currentNode.render(code, options);
  7845. }
  7846. }
  7847. }
  7848. // This assumes that the first character is not part of the first node
  7849. function getCommaSeparatedNodesWithBoundaries(nodes, code, start, end) {
  7850. const splitUpNodes = [];
  7851. let node, nextNodeStart, contentEnd, char;
  7852. let separator = start - 1;
  7853. for (const nextNode of nodes) {
  7854. if (node !== undefined) {
  7855. separator =
  7856. node.end +
  7857. findFirstOccurrenceOutsideComment(code.original.slice(node.end, nextNode.start), ',');
  7858. }
  7859. nextNodeStart = contentEnd =
  7860. separator +
  7861. 1 +
  7862. findFirstLineBreakOutsideComment(code.original.slice(separator + 1, nextNode.start))[1];
  7863. while (((char = code.original.charCodeAt(nextNodeStart)),
  7864. char === 32 /*" "*/ || char === 9 /*"\t"*/ || char === 10 /*"\n"*/ || char === 13) /*"\r"*/)
  7865. nextNodeStart++;
  7866. if (node !== undefined) {
  7867. splitUpNodes.push({
  7868. contentEnd,
  7869. end: nextNodeStart,
  7870. node,
  7871. separator,
  7872. start
  7873. });
  7874. }
  7875. node = nextNode;
  7876. start = nextNodeStart;
  7877. }
  7878. splitUpNodes.push({
  7879. contentEnd: end,
  7880. end,
  7881. node: node,
  7882. separator: null,
  7883. start
  7884. });
  7885. return splitUpNodes;
  7886. }
  7887. // This assumes there are only white-space and comments between start and end
  7888. function removeLineBreaks(code, start, end) {
  7889. while (true) {
  7890. const [removeStart, removeEnd] = findFirstLineBreakOutsideComment(code.original.slice(start, end));
  7891. if (removeStart === -1) {
  7892. break;
  7893. }
  7894. code.remove(start + removeStart, (start += removeEnd));
  7895. }
  7896. }
  7897. class BlockScope extends ChildScope {
  7898. addDeclaration(identifier, context, init, isHoisted) {
  7899. if (isHoisted) {
  7900. const variable = this.parent.addDeclaration(identifier, context, init, isHoisted);
  7901. // Necessary to make sure the init is deoptimized for conditional declarations.
  7902. // We cannot call deoptimizePath here.
  7903. variable.markInitializersForDeoptimization();
  7904. return variable;
  7905. }
  7906. else {
  7907. return super.addDeclaration(identifier, context, init, false);
  7908. }
  7909. }
  7910. }
  7911. class ExpressionStatement extends NodeBase {
  7912. initialise() {
  7913. if (this.directive &&
  7914. this.directive !== 'use strict' &&
  7915. this.parent.type === Program$1) {
  7916. this.context.log(LOGLEVEL_WARN,
  7917. // This is necessary, because either way (deleting or not) can lead to errors.
  7918. logModuleLevelDirective(this.directive, this.context.module.id), this.start);
  7919. }
  7920. }
  7921. render(code, options) {
  7922. super.render(code, options);
  7923. if (this.included)
  7924. this.insertSemicolon(code);
  7925. }
  7926. shouldBeIncluded(context) {
  7927. if (this.directive && this.directive !== 'use strict')
  7928. return this.parent.type !== Program$1;
  7929. return super.shouldBeIncluded(context);
  7930. }
  7931. applyDeoptimizations() { }
  7932. }
  7933. class BlockStatement extends NodeBase {
  7934. constructor() {
  7935. super(...arguments);
  7936. this.directlyIncluded = false;
  7937. }
  7938. addImplicitReturnExpressionToScope() {
  7939. const lastStatement = this.body[this.body.length - 1];
  7940. if (!lastStatement || lastStatement.type !== ReturnStatement$1) {
  7941. this.scope.addReturnExpression(UNKNOWN_EXPRESSION);
  7942. }
  7943. }
  7944. createScope(parentScope) {
  7945. this.scope = this.parent.preventChildBlockScope
  7946. ? parentScope
  7947. : new BlockScope(parentScope);
  7948. }
  7949. hasEffects(context) {
  7950. if (this.deoptimizeBody)
  7951. return true;
  7952. for (const node of this.body) {
  7953. if (context.brokenFlow)
  7954. break;
  7955. if (node.hasEffects(context))
  7956. return true;
  7957. }
  7958. return false;
  7959. }
  7960. include(context, includeChildrenRecursively) {
  7961. if (!(this.deoptimizeBody && this.directlyIncluded)) {
  7962. this.included = true;
  7963. this.directlyIncluded = true;
  7964. if (this.deoptimizeBody)
  7965. includeChildrenRecursively = true;
  7966. for (const node of this.body) {
  7967. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  7968. node.include(context, includeChildrenRecursively);
  7969. }
  7970. }
  7971. }
  7972. initialise() {
  7973. const firstBodyStatement = this.body[0];
  7974. this.deoptimizeBody =
  7975. firstBodyStatement instanceof ExpressionStatement &&
  7976. firstBodyStatement.directive === 'use asm';
  7977. }
  7978. render(code, options) {
  7979. if (this.body.length > 0) {
  7980. renderStatementList(this.body, code, this.start + 1, this.end - 1, options);
  7981. }
  7982. else {
  7983. super.render(code, options);
  7984. }
  7985. }
  7986. }
  7987. class RestElement extends NodeBase {
  7988. constructor() {
  7989. super(...arguments);
  7990. this.declarationInit = null;
  7991. }
  7992. addExportedVariables(variables, exportNamesByVariable) {
  7993. this.argument.addExportedVariables(variables, exportNamesByVariable);
  7994. }
  7995. declare(kind, init) {
  7996. this.declarationInit = init;
  7997. return this.argument.declare(kind, UNKNOWN_EXPRESSION);
  7998. }
  7999. deoptimizePath(path) {
  8000. path.length === 0 && this.argument.deoptimizePath(EMPTY_PATH);
  8001. }
  8002. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8003. return (path.length > 0 ||
  8004. this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context));
  8005. }
  8006. markDeclarationReached() {
  8007. this.argument.markDeclarationReached();
  8008. }
  8009. applyDeoptimizations() {
  8010. this.deoptimized = true;
  8011. if (this.declarationInit !== null) {
  8012. this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
  8013. this.context.requestTreeshakingPass();
  8014. }
  8015. }
  8016. }
  8017. class FunctionBase extends NodeBase {
  8018. constructor() {
  8019. super(...arguments);
  8020. this.objectEntity = null;
  8021. this.deoptimizedReturn = false;
  8022. }
  8023. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  8024. if (interaction.type === INTERACTION_CALLED) {
  8025. const { parameters } = this.scope;
  8026. const { args } = interaction;
  8027. let hasRest = false;
  8028. for (let position = 0; position < args.length - 1; position++) {
  8029. const parameter = this.params[position];
  8030. // Only the "this" argument arg[0] can be null
  8031. const argument = args[position + 1];
  8032. if (hasRest || parameter instanceof RestElement) {
  8033. hasRest = true;
  8034. argument.deoptimizePath(UNKNOWN_PATH);
  8035. }
  8036. else if (parameter instanceof Identifier) {
  8037. parameters[position][0].addEntityToBeDeoptimized(argument);
  8038. this.addArgumentToBeDeoptimized(argument);
  8039. }
  8040. else if (parameter) {
  8041. argument.deoptimizePath(UNKNOWN_PATH);
  8042. }
  8043. else {
  8044. this.addArgumentToBeDeoptimized(argument);
  8045. }
  8046. }
  8047. }
  8048. else {
  8049. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  8050. }
  8051. }
  8052. deoptimizePath(path) {
  8053. this.getObjectEntity().deoptimizePath(path);
  8054. if (path.length === 1 && path[0] === UnknownKey) {
  8055. // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
  8056. // which means the return expression and parameters need to be reassigned
  8057. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  8058. for (const parameterList of this.scope.parameters) {
  8059. for (const parameter of parameterList) {
  8060. parameter.deoptimizePath(UNKNOWN_PATH);
  8061. }
  8062. }
  8063. }
  8064. }
  8065. getLiteralValueAtPath(path, recursionTracker, origin) {
  8066. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  8067. }
  8068. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8069. if (path.length > 0) {
  8070. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  8071. }
  8072. if (this.async) {
  8073. if (!this.deoptimizedReturn) {
  8074. this.deoptimizedReturn = true;
  8075. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  8076. this.context.requestTreeshakingPass();
  8077. }
  8078. return UNKNOWN_RETURN_EXPRESSION;
  8079. }
  8080. return [this.scope.getReturnExpression(), false];
  8081. }
  8082. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8083. if (path.length > 0 || interaction.type !== INTERACTION_CALLED) {
  8084. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  8085. }
  8086. if (this.annotationNoSideEffects) {
  8087. return false;
  8088. }
  8089. if (this.async) {
  8090. const { propertyReadSideEffects } = this.context.options
  8091. .treeshake;
  8092. const returnExpression = this.scope.getReturnExpression();
  8093. if (returnExpression.hasEffectsOnInteractionAtPath(['then'], NODE_INTERACTION_UNKNOWN_CALL, context) ||
  8094. (propertyReadSideEffects &&
  8095. (propertyReadSideEffects === 'always' ||
  8096. returnExpression.hasEffectsOnInteractionAtPath(['then'], NODE_INTERACTION_UNKNOWN_ACCESS, context)))) {
  8097. return true;
  8098. }
  8099. }
  8100. for (const parameter of this.params) {
  8101. if (parameter.hasEffects(context))
  8102. return true;
  8103. }
  8104. return false;
  8105. }
  8106. include(context, includeChildrenRecursively) {
  8107. if (!this.deoptimized)
  8108. this.applyDeoptimizations();
  8109. this.included = true;
  8110. const { brokenFlow } = context;
  8111. context.brokenFlow = false;
  8112. this.body.include(context, includeChildrenRecursively);
  8113. context.brokenFlow = brokenFlow;
  8114. }
  8115. includeCallArguments(context, parameters) {
  8116. this.scope.includeCallArguments(context, parameters);
  8117. }
  8118. initialise() {
  8119. this.scope.addParameterVariables(this.params.map(parameter => parameter.declare('parameter', UNKNOWN_EXPRESSION)), this.params[this.params.length - 1] instanceof RestElement);
  8120. if (this.body instanceof BlockStatement) {
  8121. this.body.addImplicitReturnExpressionToScope();
  8122. }
  8123. else {
  8124. this.scope.addReturnExpression(this.body);
  8125. }
  8126. }
  8127. parseNode(esTreeNode) {
  8128. if (esTreeNode.body.type === BlockStatement$1) {
  8129. this.body = new BlockStatement(esTreeNode.body, this, this.scope.hoistedBodyVarScope);
  8130. }
  8131. super.parseNode(esTreeNode);
  8132. }
  8133. addArgumentToBeDeoptimized(_argument) { }
  8134. applyDeoptimizations() { }
  8135. }
  8136. FunctionBase.prototype.preventChildBlockScope = true;
  8137. class ArrowFunctionExpression extends FunctionBase {
  8138. constructor() {
  8139. super(...arguments);
  8140. this.objectEntity = null;
  8141. }
  8142. createScope(parentScope) {
  8143. this.scope = new ReturnValueScope(parentScope, this.context);
  8144. }
  8145. hasEffects() {
  8146. if (!this.deoptimized)
  8147. this.applyDeoptimizations();
  8148. return false;
  8149. }
  8150. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8151. if (super.hasEffectsOnInteractionAtPath(path, interaction, context)) {
  8152. return true;
  8153. }
  8154. if (this.annotationNoSideEffects) {
  8155. return false;
  8156. }
  8157. if (interaction.type === INTERACTION_CALLED) {
  8158. const { ignore, brokenFlow } = context;
  8159. context.ignore = {
  8160. breaks: false,
  8161. continues: false,
  8162. labels: new Set(),
  8163. returnYield: true,
  8164. this: false
  8165. };
  8166. if (this.body.hasEffects(context))
  8167. return true;
  8168. context.ignore = ignore;
  8169. context.brokenFlow = brokenFlow;
  8170. }
  8171. return false;
  8172. }
  8173. include(context, includeChildrenRecursively) {
  8174. super.include(context, includeChildrenRecursively);
  8175. for (const parameter of this.params) {
  8176. if (!(parameter instanceof Identifier)) {
  8177. parameter.include(context, includeChildrenRecursively);
  8178. }
  8179. }
  8180. }
  8181. getObjectEntity() {
  8182. if (this.objectEntity !== null) {
  8183. return this.objectEntity;
  8184. }
  8185. return (this.objectEntity = new ObjectEntity([], OBJECT_PROTOTYPE));
  8186. }
  8187. }
  8188. function getSystemExportStatement(exportedVariables, { exportNamesByVariable, snippets: { _, getObject, getPropertyAccess } }, modifier = '') {
  8189. if (exportedVariables.length === 1 &&
  8190. exportNamesByVariable.get(exportedVariables[0]).length === 1) {
  8191. const variable = exportedVariables[0];
  8192. return `exports('${exportNamesByVariable.get(variable)}',${_}${variable.getName(getPropertyAccess)}${modifier})`;
  8193. }
  8194. else {
  8195. const fields = [];
  8196. for (const variable of exportedVariables) {
  8197. for (const exportName of exportNamesByVariable.get(variable)) {
  8198. fields.push([exportName, variable.getName(getPropertyAccess) + modifier]);
  8199. }
  8200. }
  8201. return `exports(${getObject(fields, { lineBreakIndent: null })})`;
  8202. }
  8203. }
  8204. function renderSystemExportExpression(exportedVariable, expressionStart, expressionEnd, code, { exportNamesByVariable, snippets: { _ } }) {
  8205. code.prependRight(expressionStart, `exports('${exportNamesByVariable.get(exportedVariable)}',${_}`);
  8206. code.appendLeft(expressionEnd, ')');
  8207. }
  8208. function renderSystemExportFunction(exportedVariables, expressionStart, expressionEnd, needsParens, code, options) {
  8209. const { _, getDirectReturnIifeLeft } = options.snippets;
  8210. code.prependRight(expressionStart, getDirectReturnIifeLeft(['v'], `${getSystemExportStatement(exportedVariables, options)},${_}v`, { needsArrowReturnParens: true, needsWrappedFunction: needsParens }));
  8211. code.appendLeft(expressionEnd, ')');
  8212. }
  8213. function renderSystemExportSequenceAfterExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options) {
  8214. const { _, getPropertyAccess } = options.snippets;
  8215. code.appendLeft(expressionEnd, `,${_}${getSystemExportStatement([exportedVariable], options)},${_}${exportedVariable.getName(getPropertyAccess)}`);
  8216. if (needsParens) {
  8217. code.prependRight(expressionStart, '(');
  8218. code.appendLeft(expressionEnd, ')');
  8219. }
  8220. }
  8221. function renderSystemExportSequenceBeforeExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options, modifier) {
  8222. const { _ } = options.snippets;
  8223. code.prependRight(expressionStart, `${getSystemExportStatement([exportedVariable], options, modifier)},${_}`);
  8224. if (needsParens) {
  8225. code.prependRight(expressionStart, '(');
  8226. code.appendLeft(expressionEnd, ')');
  8227. }
  8228. }
  8229. class ObjectPattern extends NodeBase {
  8230. addExportedVariables(variables, exportNamesByVariable) {
  8231. for (const property of this.properties) {
  8232. if (property.type === Property$1) {
  8233. property.value.addExportedVariables(variables, exportNamesByVariable);
  8234. }
  8235. else {
  8236. property.argument.addExportedVariables(variables, exportNamesByVariable);
  8237. }
  8238. }
  8239. }
  8240. declare(kind, init) {
  8241. const variables = [];
  8242. for (const property of this.properties) {
  8243. variables.push(...property.declare(kind, init));
  8244. }
  8245. return variables;
  8246. }
  8247. deoptimizePath(path) {
  8248. if (path.length === 0) {
  8249. for (const property of this.properties) {
  8250. property.deoptimizePath(path);
  8251. }
  8252. }
  8253. }
  8254. hasEffectsOnInteractionAtPath(
  8255. // At the moment, this is only triggered for assignment left-hand sides,
  8256. // where the path is empty
  8257. _path, interaction, context) {
  8258. for (const property of this.properties) {
  8259. if (property.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context))
  8260. return true;
  8261. }
  8262. return false;
  8263. }
  8264. markDeclarationReached() {
  8265. for (const property of this.properties) {
  8266. property.markDeclarationReached();
  8267. }
  8268. }
  8269. }
  8270. class AssignmentExpression extends NodeBase {
  8271. hasEffects(context) {
  8272. const { deoptimized, left, operator, right } = this;
  8273. if (!deoptimized)
  8274. this.applyDeoptimizations();
  8275. // MemberExpressions do not access the property before assignments if the
  8276. // operator is '='.
  8277. return (right.hasEffects(context) || left.hasEffectsAsAssignmentTarget(context, operator !== '='));
  8278. }
  8279. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8280. return this.right.hasEffectsOnInteractionAtPath(path, interaction, context);
  8281. }
  8282. include(context, includeChildrenRecursively) {
  8283. const { deoptimized, left, right, operator } = this;
  8284. if (!deoptimized)
  8285. this.applyDeoptimizations();
  8286. this.included = true;
  8287. if (includeChildrenRecursively ||
  8288. operator !== '=' ||
  8289. left.included ||
  8290. left.hasEffectsAsAssignmentTarget(createHasEffectsContext(), false)) {
  8291. left.includeAsAssignmentTarget(context, includeChildrenRecursively, operator !== '=');
  8292. }
  8293. right.include(context, includeChildrenRecursively);
  8294. }
  8295. initialise() {
  8296. this.left.setAssignedValue(this.right);
  8297. }
  8298. render(code, options, { preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  8299. const { left, right, start, end, parent } = this;
  8300. if (left.included) {
  8301. left.render(code, options);
  8302. right.render(code, options);
  8303. }
  8304. else {
  8305. const inclusionStart = findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, '=', left.end) + 1);
  8306. code.remove(start, inclusionStart);
  8307. if (preventASI) {
  8308. removeLineBreaks(code, inclusionStart, right.start);
  8309. }
  8310. right.render(code, options, {
  8311. renderedParentType: renderedParentType || parent.type,
  8312. renderedSurroundingElement: renderedSurroundingElement || parent.type
  8313. });
  8314. }
  8315. if (options.format === 'system') {
  8316. if (left instanceof Identifier) {
  8317. const variable = left.variable;
  8318. const exportNames = options.exportNamesByVariable.get(variable);
  8319. if (exportNames) {
  8320. if (exportNames.length === 1) {
  8321. renderSystemExportExpression(variable, start, end, code, options);
  8322. }
  8323. else {
  8324. renderSystemExportSequenceAfterExpression(variable, start, end, parent.type !== ExpressionStatement$1, code, options);
  8325. }
  8326. return;
  8327. }
  8328. }
  8329. else {
  8330. const systemPatternExports = [];
  8331. left.addExportedVariables(systemPatternExports, options.exportNamesByVariable);
  8332. if (systemPatternExports.length > 0) {
  8333. renderSystemExportFunction(systemPatternExports, start, end, renderedSurroundingElement === ExpressionStatement$1, code, options);
  8334. return;
  8335. }
  8336. }
  8337. }
  8338. if (left.included &&
  8339. left instanceof ObjectPattern &&
  8340. (renderedSurroundingElement === ExpressionStatement$1 ||
  8341. renderedSurroundingElement === ArrowFunctionExpression$1)) {
  8342. code.appendRight(start, '(');
  8343. code.prependLeft(end, ')');
  8344. }
  8345. }
  8346. applyDeoptimizations() {
  8347. this.deoptimized = true;
  8348. this.left.deoptimizePath(EMPTY_PATH);
  8349. this.right.deoptimizePath(UNKNOWN_PATH);
  8350. this.context.requestTreeshakingPass();
  8351. }
  8352. }
  8353. class AssignmentPattern extends NodeBase {
  8354. addExportedVariables(variables, exportNamesByVariable) {
  8355. this.left.addExportedVariables(variables, exportNamesByVariable);
  8356. }
  8357. declare(kind, init) {
  8358. return this.left.declare(kind, init);
  8359. }
  8360. deoptimizePath(path) {
  8361. path.length === 0 && this.left.deoptimizePath(path);
  8362. }
  8363. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8364. return (path.length > 0 || this.left.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context));
  8365. }
  8366. markDeclarationReached() {
  8367. this.left.markDeclarationReached();
  8368. }
  8369. render(code, options, { isShorthandProperty } = BLANK) {
  8370. this.left.render(code, options, { isShorthandProperty });
  8371. this.right.render(code, options);
  8372. }
  8373. applyDeoptimizations() {
  8374. this.deoptimized = true;
  8375. this.left.deoptimizePath(EMPTY_PATH);
  8376. this.right.deoptimizePath(UNKNOWN_PATH);
  8377. this.context.requestTreeshakingPass();
  8378. }
  8379. }
  8380. class ArgumentsVariable extends LocalVariable {
  8381. constructor(context) {
  8382. super('arguments', null, UNKNOWN_EXPRESSION, context);
  8383. this.deoptimizedArguments = [];
  8384. }
  8385. addArgumentToBeDeoptimized(argument) {
  8386. if (this.included) {
  8387. argument.deoptimizePath(UNKNOWN_PATH);
  8388. }
  8389. else {
  8390. this.deoptimizedArguments.push(argument);
  8391. }
  8392. }
  8393. hasEffectsOnInteractionAtPath(path, { type }) {
  8394. return type !== INTERACTION_ACCESSED || path.length > 1;
  8395. }
  8396. include() {
  8397. super.include();
  8398. for (const argument of this.deoptimizedArguments) {
  8399. argument.deoptimizePath(UNKNOWN_PATH);
  8400. }
  8401. this.deoptimizedArguments.length = 0;
  8402. }
  8403. }
  8404. class ThisVariable extends ParameterVariable {
  8405. constructor(context) {
  8406. super('this', null, context);
  8407. }
  8408. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8409. return (context.replacedVariableInits.get(this) || UNKNOWN_EXPRESSION).hasEffectsOnInteractionAtPath(path, interaction, context);
  8410. }
  8411. }
  8412. class FunctionScope extends ReturnValueScope {
  8413. constructor(parent, context) {
  8414. super(parent, context);
  8415. this.variables.set('arguments', (this.argumentsVariable = new ArgumentsVariable(context)));
  8416. this.variables.set('this', (this.thisVariable = new ThisVariable(context)));
  8417. }
  8418. findLexicalBoundary() {
  8419. return this;
  8420. }
  8421. includeCallArguments(context, parameters) {
  8422. super.includeCallArguments(context, parameters);
  8423. if (this.argumentsVariable.included) {
  8424. for (const argument of parameters) {
  8425. if (!argument.included) {
  8426. argument.include(context, false);
  8427. }
  8428. }
  8429. }
  8430. }
  8431. }
  8432. class FunctionNode extends FunctionBase {
  8433. constructor() {
  8434. super(...arguments);
  8435. this.objectEntity = null;
  8436. }
  8437. createScope(parentScope) {
  8438. this.scope = new FunctionScope(parentScope, this.context);
  8439. this.constructedEntity = new ObjectEntity(Object.create(null), OBJECT_PROTOTYPE);
  8440. // This makes sure that all deoptimizations of "this" are applied to the
  8441. // constructed entity.
  8442. this.scope.thisVariable.addEntityToBeDeoptimized(this.constructedEntity);
  8443. }
  8444. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  8445. super.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  8446. if (interaction.type === INTERACTION_CALLED && path.length === 0 && interaction.args[0]) {
  8447. // args[0] is the "this" argument
  8448. this.scope.thisVariable.addEntityToBeDeoptimized(interaction.args[0]);
  8449. }
  8450. }
  8451. hasEffects(context) {
  8452. if (!this.deoptimized)
  8453. this.applyDeoptimizations();
  8454. if (this.annotationNoSideEffects) {
  8455. return false;
  8456. }
  8457. return !!this.id?.hasEffects(context);
  8458. }
  8459. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8460. if (super.hasEffectsOnInteractionAtPath(path, interaction, context))
  8461. return true;
  8462. if (this.annotationNoSideEffects) {
  8463. return false;
  8464. }
  8465. if (interaction.type === INTERACTION_CALLED) {
  8466. const thisInit = context.replacedVariableInits.get(this.scope.thisVariable);
  8467. context.replacedVariableInits.set(this.scope.thisVariable, interaction.withNew ? this.constructedEntity : UNKNOWN_EXPRESSION);
  8468. const { brokenFlow, ignore, replacedVariableInits } = context;
  8469. context.ignore = {
  8470. breaks: false,
  8471. continues: false,
  8472. labels: new Set(),
  8473. returnYield: true,
  8474. this: interaction.withNew
  8475. };
  8476. if (this.body.hasEffects(context))
  8477. return true;
  8478. context.brokenFlow = brokenFlow;
  8479. if (thisInit) {
  8480. replacedVariableInits.set(this.scope.thisVariable, thisInit);
  8481. }
  8482. else {
  8483. replacedVariableInits.delete(this.scope.thisVariable);
  8484. }
  8485. context.ignore = ignore;
  8486. }
  8487. return false;
  8488. }
  8489. include(context, includeChildrenRecursively) {
  8490. super.include(context, includeChildrenRecursively);
  8491. this.id?.include();
  8492. const hasArguments = this.scope.argumentsVariable.included;
  8493. for (const parameter of this.params) {
  8494. if (!(parameter instanceof Identifier) || hasArguments) {
  8495. parameter.include(context, includeChildrenRecursively);
  8496. }
  8497. }
  8498. }
  8499. initialise() {
  8500. super.initialise();
  8501. this.id?.declare('function', this);
  8502. }
  8503. addArgumentToBeDeoptimized(argument) {
  8504. this.scope.argumentsVariable.addArgumentToBeDeoptimized(argument);
  8505. }
  8506. getObjectEntity() {
  8507. if (this.objectEntity !== null) {
  8508. return this.objectEntity;
  8509. }
  8510. return (this.objectEntity = new ObjectEntity([
  8511. {
  8512. key: 'prototype',
  8513. kind: 'init',
  8514. property: new ObjectEntity([], OBJECT_PROTOTYPE)
  8515. }
  8516. ], OBJECT_PROTOTYPE));
  8517. }
  8518. }
  8519. class AwaitExpression extends NodeBase {
  8520. hasEffects() {
  8521. if (!this.deoptimized)
  8522. this.applyDeoptimizations();
  8523. return true;
  8524. }
  8525. include(context, includeChildrenRecursively) {
  8526. if (!this.deoptimized)
  8527. this.applyDeoptimizations();
  8528. if (!this.included) {
  8529. this.included = true;
  8530. checkTopLevelAwait: if (!this.context.usesTopLevelAwait) {
  8531. let parent = this.parent;
  8532. do {
  8533. if (parent instanceof FunctionNode || parent instanceof ArrowFunctionExpression)
  8534. break checkTopLevelAwait;
  8535. } while ((parent = parent.parent));
  8536. this.context.usesTopLevelAwait = true;
  8537. }
  8538. }
  8539. this.argument.include(context, includeChildrenRecursively);
  8540. }
  8541. }
  8542. const binaryOperators = {
  8543. '!=': (left, right) => left != right,
  8544. '!==': (left, right) => left !== right,
  8545. '%': (left, right) => left % right,
  8546. '&': (left, right) => left & right,
  8547. '*': (left, right) => left * right,
  8548. // At the moment, "**" will be transpiled to Math.pow
  8549. '**': (left, right) => left ** right,
  8550. '+': (left, right) => left + right,
  8551. '-': (left, right) => left - right,
  8552. '/': (left, right) => left / right,
  8553. '<': (left, right) => left < right,
  8554. '<<': (left, right) => left << right,
  8555. '<=': (left, right) => left <= right,
  8556. '==': (left, right) => left == right,
  8557. '===': (left, right) => left === right,
  8558. '>': (left, right) => left > right,
  8559. '>=': (left, right) => left >= right,
  8560. '>>': (left, right) => left >> right,
  8561. '>>>': (left, right) => left >>> right,
  8562. '^': (left, right) => left ^ right,
  8563. '|': (left, right) => left | right
  8564. // We use the fallback for cases where we return something unknown
  8565. // in: () => UnknownValue,
  8566. // instanceof: () => UnknownValue,
  8567. };
  8568. class BinaryExpression extends NodeBase {
  8569. deoptimizeCache() { }
  8570. getLiteralValueAtPath(path, recursionTracker, origin) {
  8571. if (path.length > 0)
  8572. return UnknownValue;
  8573. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  8574. if (typeof leftValue === 'symbol')
  8575. return UnknownValue;
  8576. const rightValue = this.right.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  8577. if (typeof rightValue === 'symbol')
  8578. return UnknownValue;
  8579. const operatorFunction = binaryOperators[this.operator];
  8580. if (!operatorFunction)
  8581. return UnknownValue;
  8582. return operatorFunction(leftValue, rightValue);
  8583. }
  8584. hasEffects(context) {
  8585. // support some implicit type coercion runtime errors
  8586. if (this.operator === '+' &&
  8587. this.parent instanceof ExpressionStatement &&
  8588. this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) === '') {
  8589. return true;
  8590. }
  8591. return super.hasEffects(context);
  8592. }
  8593. hasEffectsOnInteractionAtPath(path, { type }) {
  8594. return type !== INTERACTION_ACCESSED || path.length > 1;
  8595. }
  8596. render(code, options, { renderedSurroundingElement } = BLANK) {
  8597. this.left.render(code, options, { renderedSurroundingElement });
  8598. this.right.render(code, options);
  8599. }
  8600. }
  8601. class BreakStatement extends NodeBase {
  8602. hasEffects(context) {
  8603. if (this.label) {
  8604. if (!context.ignore.labels.has(this.label.name))
  8605. return true;
  8606. context.includedLabels.add(this.label.name);
  8607. }
  8608. else {
  8609. if (!context.ignore.breaks)
  8610. return true;
  8611. context.hasBreak = true;
  8612. }
  8613. context.brokenFlow = true;
  8614. return false;
  8615. }
  8616. include(context) {
  8617. this.included = true;
  8618. if (this.label) {
  8619. this.label.include();
  8620. context.includedLabels.add(this.label.name);
  8621. }
  8622. else {
  8623. context.hasBreak = true;
  8624. }
  8625. context.brokenFlow = true;
  8626. }
  8627. }
  8628. function renderCallArguments(code, options, node) {
  8629. if (node.arguments.length > 0) {
  8630. if (node.arguments[node.arguments.length - 1].included) {
  8631. for (const argument of node.arguments) {
  8632. argument.render(code, options);
  8633. }
  8634. }
  8635. else {
  8636. let lastIncludedIndex = node.arguments.length - 2;
  8637. while (lastIncludedIndex >= 0 && !node.arguments[lastIncludedIndex].included) {
  8638. lastIncludedIndex--;
  8639. }
  8640. if (lastIncludedIndex >= 0) {
  8641. for (let index = 0; index <= lastIncludedIndex; index++) {
  8642. node.arguments[index].render(code, options);
  8643. }
  8644. code.remove(findFirstOccurrenceOutsideComment(code.original, ',', node.arguments[lastIncludedIndex].end), node.end - 1);
  8645. }
  8646. else {
  8647. code.remove(findFirstOccurrenceOutsideComment(code.original, '(', node.callee.end) + 1, node.end - 1);
  8648. }
  8649. }
  8650. }
  8651. }
  8652. class Literal extends NodeBase {
  8653. deoptimizeArgumentsOnInteractionAtPath() { }
  8654. getLiteralValueAtPath(path) {
  8655. if (path.length > 0 ||
  8656. // unknown literals can also be null but do not start with an "n"
  8657. (this.value === null && this.context.code.charCodeAt(this.start) !== 110) ||
  8658. typeof this.value === 'bigint' ||
  8659. // to support shims for regular expressions
  8660. this.context.code.charCodeAt(this.start) === 47) {
  8661. return UnknownValue;
  8662. }
  8663. return this.value;
  8664. }
  8665. getReturnExpressionWhenCalledAtPath(path) {
  8666. if (path.length !== 1)
  8667. return UNKNOWN_RETURN_EXPRESSION;
  8668. return getMemberReturnExpressionWhenCalled(this.members, path[0]);
  8669. }
  8670. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8671. switch (interaction.type) {
  8672. case INTERACTION_ACCESSED: {
  8673. return path.length > (this.value === null ? 0 : 1);
  8674. }
  8675. case INTERACTION_ASSIGNED: {
  8676. return true;
  8677. }
  8678. case INTERACTION_CALLED: {
  8679. if (this.included &&
  8680. this.value instanceof RegExp &&
  8681. (this.value.global || this.value.sticky)) {
  8682. return true;
  8683. }
  8684. return (path.length !== 1 ||
  8685. hasMemberEffectWhenCalled(this.members, path[0], interaction, context));
  8686. }
  8687. }
  8688. }
  8689. initialise() {
  8690. this.members = getLiteralMembersForValue(this.value);
  8691. }
  8692. parseNode(esTreeNode) {
  8693. this.value = esTreeNode.value;
  8694. this.regex = esTreeNode.regex;
  8695. super.parseNode(esTreeNode);
  8696. }
  8697. render(code) {
  8698. if (typeof this.value === 'string') {
  8699. code.indentExclusionRanges.push([this.start + 1, this.end - 1]);
  8700. }
  8701. }
  8702. }
  8703. // To avoid infinite recursions
  8704. const MAX_PATH_DEPTH = 7;
  8705. function getResolvablePropertyKey(memberExpression) {
  8706. return memberExpression.computed
  8707. ? getResolvableComputedPropertyKey(memberExpression.property)
  8708. : memberExpression.property.name;
  8709. }
  8710. function getResolvableComputedPropertyKey(propertyKey) {
  8711. if (propertyKey instanceof Literal) {
  8712. return String(propertyKey.value);
  8713. }
  8714. return null;
  8715. }
  8716. function getPathIfNotComputed(memberExpression) {
  8717. const nextPathKey = memberExpression.propertyKey;
  8718. const object = memberExpression.object;
  8719. if (typeof nextPathKey === 'string') {
  8720. if (object instanceof Identifier) {
  8721. return [
  8722. { key: object.name, pos: object.start },
  8723. { key: nextPathKey, pos: memberExpression.property.start }
  8724. ];
  8725. }
  8726. if (object instanceof MemberExpression) {
  8727. const parentPath = getPathIfNotComputed(object);
  8728. return (parentPath && [...parentPath, { key: nextPathKey, pos: memberExpression.property.start }]);
  8729. }
  8730. }
  8731. return null;
  8732. }
  8733. function getStringFromPath(path) {
  8734. let pathString = path[0].key;
  8735. for (let index = 1; index < path.length; index++) {
  8736. pathString += '.' + path[index].key;
  8737. }
  8738. return pathString;
  8739. }
  8740. class MemberExpression extends NodeBase {
  8741. constructor() {
  8742. super(...arguments);
  8743. this.variable = null;
  8744. this.assignmentDeoptimized = false;
  8745. this.bound = false;
  8746. this.expressionsToBeDeoptimized = [];
  8747. this.isUndefined = false;
  8748. }
  8749. bind() {
  8750. this.bound = true;
  8751. const path = getPathIfNotComputed(this);
  8752. const baseVariable = path && this.scope.findVariable(path[0].key);
  8753. if (baseVariable?.isNamespace) {
  8754. const resolvedVariable = resolveNamespaceVariables(baseVariable, path.slice(1), this.context);
  8755. if (!resolvedVariable) {
  8756. super.bind();
  8757. }
  8758. else if (resolvedVariable === 'undefined') {
  8759. this.isUndefined = true;
  8760. }
  8761. else {
  8762. this.variable = resolvedVariable;
  8763. this.scope.addNamespaceMemberAccess(getStringFromPath(path), resolvedVariable);
  8764. }
  8765. }
  8766. else {
  8767. super.bind();
  8768. }
  8769. }
  8770. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  8771. if (this.variable) {
  8772. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  8773. }
  8774. else if (!this.isUndefined) {
  8775. if (path.length < MAX_PATH_DEPTH) {
  8776. this.object.deoptimizeArgumentsOnInteractionAtPath(interaction, [this.getPropertyKey(), ...path], recursionTracker);
  8777. }
  8778. else {
  8779. deoptimizeInteraction(interaction);
  8780. }
  8781. }
  8782. }
  8783. deoptimizeCache() {
  8784. const { expressionsToBeDeoptimized, object } = this;
  8785. this.expressionsToBeDeoptimized = EMPTY_ARRAY;
  8786. this.propertyKey = UnknownKey;
  8787. object.deoptimizePath(UNKNOWN_PATH);
  8788. for (const expression of expressionsToBeDeoptimized) {
  8789. expression.deoptimizeCache();
  8790. }
  8791. }
  8792. deoptimizePath(path) {
  8793. if (path.length === 0)
  8794. this.disallowNamespaceReassignment();
  8795. if (this.variable) {
  8796. this.variable.deoptimizePath(path);
  8797. }
  8798. else if (!this.isUndefined && path.length < MAX_PATH_DEPTH) {
  8799. const propertyKey = this.getPropertyKey();
  8800. this.object.deoptimizePath([
  8801. propertyKey === UnknownKey ? UnknownNonAccessorKey : propertyKey,
  8802. ...path
  8803. ]);
  8804. }
  8805. }
  8806. getLiteralValueAtPath(path, recursionTracker, origin) {
  8807. if (this.variable) {
  8808. return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
  8809. }
  8810. if (this.isUndefined) {
  8811. return undefined;
  8812. }
  8813. if (this.propertyKey !== UnknownKey && path.length < MAX_PATH_DEPTH) {
  8814. this.expressionsToBeDeoptimized.push(origin);
  8815. return this.object.getLiteralValueAtPath([this.getPropertyKey(), ...path], recursionTracker, origin);
  8816. }
  8817. return UnknownValue;
  8818. }
  8819. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  8820. if (this.variable) {
  8821. return this.variable.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  8822. }
  8823. if (this.isUndefined) {
  8824. return [UNDEFINED_EXPRESSION, false];
  8825. }
  8826. if (this.propertyKey !== UnknownKey && path.length < MAX_PATH_DEPTH) {
  8827. this.expressionsToBeDeoptimized.push(origin);
  8828. return this.object.getReturnExpressionWhenCalledAtPath([this.getPropertyKey(), ...path], interaction, recursionTracker, origin);
  8829. }
  8830. return UNKNOWN_RETURN_EXPRESSION;
  8831. }
  8832. hasEffects(context) {
  8833. if (!this.deoptimized)
  8834. this.applyDeoptimizations();
  8835. return (this.property.hasEffects(context) ||
  8836. this.object.hasEffects(context) ||
  8837. this.hasAccessEffect(context));
  8838. }
  8839. hasEffectsAsAssignmentTarget(context, checkAccess) {
  8840. if (checkAccess && !this.deoptimized)
  8841. this.applyDeoptimizations();
  8842. if (!this.assignmentDeoptimized)
  8843. this.applyAssignmentDeoptimization();
  8844. return (this.property.hasEffects(context) ||
  8845. this.object.hasEffects(context) ||
  8846. (checkAccess && this.hasAccessEffect(context)) ||
  8847. this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
  8848. }
  8849. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8850. if (this.variable) {
  8851. return this.variable.hasEffectsOnInteractionAtPath(path, interaction, context);
  8852. }
  8853. if (this.isUndefined) {
  8854. return true;
  8855. }
  8856. if (path.length < MAX_PATH_DEPTH) {
  8857. return this.object.hasEffectsOnInteractionAtPath([this.getPropertyKey(), ...path], interaction, context);
  8858. }
  8859. return true;
  8860. }
  8861. include(context, includeChildrenRecursively) {
  8862. if (!this.deoptimized)
  8863. this.applyDeoptimizations();
  8864. this.includeProperties(context, includeChildrenRecursively);
  8865. }
  8866. includeAsAssignmentTarget(context, includeChildrenRecursively, deoptimizeAccess) {
  8867. if (!this.assignmentDeoptimized)
  8868. this.applyAssignmentDeoptimization();
  8869. if (deoptimizeAccess) {
  8870. this.include(context, includeChildrenRecursively);
  8871. }
  8872. else {
  8873. this.includeProperties(context, includeChildrenRecursively);
  8874. }
  8875. }
  8876. includeCallArguments(context, parameters) {
  8877. if (this.variable) {
  8878. this.variable.includeCallArguments(context, parameters);
  8879. }
  8880. else {
  8881. super.includeCallArguments(context, parameters);
  8882. }
  8883. }
  8884. initialise() {
  8885. this.propertyKey = getResolvablePropertyKey(this);
  8886. this.accessInteraction = { args: [this.object], type: INTERACTION_ACCESSED };
  8887. }
  8888. isSkippedAsOptional(origin) {
  8889. return (!this.variable &&
  8890. !this.isUndefined &&
  8891. (this.object.isSkippedAsOptional?.(origin) ||
  8892. (this.optional &&
  8893. this.object.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, origin) == null)));
  8894. }
  8895. render(code, options, { renderedParentType, isCalleeOfRenderedParent, renderedSurroundingElement } = BLANK) {
  8896. if (this.variable || this.isUndefined) {
  8897. const { snippets: { getPropertyAccess } } = options;
  8898. let replacement = this.variable ? this.variable.getName(getPropertyAccess) : 'undefined';
  8899. if (renderedParentType && isCalleeOfRenderedParent)
  8900. replacement = '0, ' + replacement;
  8901. code.overwrite(this.start, this.end, replacement, {
  8902. contentOnly: true,
  8903. storeName: true
  8904. });
  8905. }
  8906. else {
  8907. if (renderedParentType && isCalleeOfRenderedParent) {
  8908. code.appendRight(this.start, '0, ');
  8909. }
  8910. this.object.render(code, options, { renderedSurroundingElement });
  8911. this.property.render(code, options);
  8912. }
  8913. }
  8914. setAssignedValue(value) {
  8915. this.assignmentInteraction = {
  8916. args: [this.object, value],
  8917. type: INTERACTION_ASSIGNED
  8918. };
  8919. }
  8920. applyDeoptimizations() {
  8921. this.deoptimized = true;
  8922. const { propertyReadSideEffects } = this.context.options
  8923. .treeshake;
  8924. if (
  8925. // Namespaces are not bound and should not be deoptimized
  8926. this.bound &&
  8927. propertyReadSideEffects &&
  8928. !(this.variable || this.isUndefined)) {
  8929. const propertyKey = this.getPropertyKey();
  8930. this.object.deoptimizeArgumentsOnInteractionAtPath(this.accessInteraction, [propertyKey], SHARED_RECURSION_TRACKER);
  8931. this.context.requestTreeshakingPass();
  8932. }
  8933. }
  8934. applyAssignmentDeoptimization() {
  8935. this.assignmentDeoptimized = true;
  8936. const { propertyReadSideEffects } = this.context.options
  8937. .treeshake;
  8938. if (
  8939. // Namespaces are not bound and should not be deoptimized
  8940. this.bound &&
  8941. propertyReadSideEffects &&
  8942. !(this.variable || this.isUndefined)) {
  8943. this.object.deoptimizeArgumentsOnInteractionAtPath(this.assignmentInteraction, [this.getPropertyKey()], SHARED_RECURSION_TRACKER);
  8944. this.context.requestTreeshakingPass();
  8945. }
  8946. }
  8947. disallowNamespaceReassignment() {
  8948. if (this.object instanceof Identifier) {
  8949. const variable = this.scope.findVariable(this.object.name);
  8950. if (variable.isNamespace) {
  8951. if (this.variable) {
  8952. this.context.includeVariableInModule(this.variable);
  8953. }
  8954. this.context.log(LOGLEVEL_WARN, logIllegalImportReassignment(this.object.name, this.context.module.id), this.start);
  8955. }
  8956. }
  8957. }
  8958. getPropertyKey() {
  8959. if (this.propertyKey === null) {
  8960. this.propertyKey = UnknownKey;
  8961. const value = this.property.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  8962. return (this.propertyKey =
  8963. value === SymbolToStringTag
  8964. ? value
  8965. : typeof value === 'symbol'
  8966. ? UnknownKey
  8967. : String(value));
  8968. }
  8969. return this.propertyKey;
  8970. }
  8971. hasAccessEffect(context) {
  8972. const { propertyReadSideEffects } = this.context.options
  8973. .treeshake;
  8974. return (!(this.variable || this.isUndefined) &&
  8975. propertyReadSideEffects &&
  8976. (propertyReadSideEffects === 'always' ||
  8977. this.object.hasEffectsOnInteractionAtPath([this.getPropertyKey()], this.accessInteraction, context)));
  8978. }
  8979. includeProperties(context, includeChildrenRecursively) {
  8980. if (!this.included) {
  8981. this.included = true;
  8982. if (this.variable) {
  8983. this.context.includeVariableInModule(this.variable);
  8984. }
  8985. }
  8986. this.object.include(context, includeChildrenRecursively);
  8987. this.property.include(context, includeChildrenRecursively);
  8988. }
  8989. }
  8990. function resolveNamespaceVariables(baseVariable, path, astContext) {
  8991. if (path.length === 0)
  8992. return baseVariable;
  8993. if (!baseVariable.isNamespace || baseVariable instanceof ExternalVariable)
  8994. return null;
  8995. const exportName = path[0].key;
  8996. const variable = baseVariable.context.traceExport(exportName);
  8997. if (!variable) {
  8998. if (path.length === 1) {
  8999. const fileName = baseVariable.context.fileName;
  9000. astContext.log(LOGLEVEL_WARN, logMissingExport(exportName, astContext.module.id, fileName), path[0].pos);
  9001. return 'undefined';
  9002. }
  9003. return null;
  9004. }
  9005. return resolveNamespaceVariables(variable, path.slice(1), astContext);
  9006. }
  9007. class CallExpressionBase extends NodeBase {
  9008. constructor() {
  9009. super(...arguments);
  9010. this.returnExpression = null;
  9011. this.deoptimizableDependentExpressions = [];
  9012. this.expressionsToBeDeoptimized = new Set();
  9013. }
  9014. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  9015. const { args } = interaction;
  9016. const [returnExpression, isPure] = this.getReturnExpression(recursionTracker);
  9017. if (isPure)
  9018. return;
  9019. const deoptimizedExpressions = args.filter(expression => !!expression && expression !== UNKNOWN_EXPRESSION);
  9020. if (deoptimizedExpressions.length === 0)
  9021. return;
  9022. if (returnExpression === UNKNOWN_EXPRESSION) {
  9023. for (const expression of deoptimizedExpressions) {
  9024. expression.deoptimizePath(UNKNOWN_PATH);
  9025. }
  9026. }
  9027. else {
  9028. recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  9029. for (const expression of deoptimizedExpressions) {
  9030. this.expressionsToBeDeoptimized.add(expression);
  9031. }
  9032. returnExpression.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  9033. }, null);
  9034. }
  9035. }
  9036. deoptimizeCache() {
  9037. if (this.returnExpression?.[0] !== UNKNOWN_EXPRESSION) {
  9038. this.returnExpression = UNKNOWN_RETURN_EXPRESSION;
  9039. const { deoptimizableDependentExpressions, expressionsToBeDeoptimized } = this;
  9040. this.expressionsToBeDeoptimized = EMPTY_SET;
  9041. this.deoptimizableDependentExpressions = EMPTY_ARRAY;
  9042. for (const expression of deoptimizableDependentExpressions) {
  9043. expression.deoptimizeCache();
  9044. }
  9045. for (const expression of expressionsToBeDeoptimized) {
  9046. expression.deoptimizePath(UNKNOWN_PATH);
  9047. }
  9048. }
  9049. }
  9050. deoptimizePath(path) {
  9051. if (path.length === 0 ||
  9052. this.context.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  9053. return;
  9054. }
  9055. const [returnExpression] = this.getReturnExpression();
  9056. if (returnExpression !== UNKNOWN_EXPRESSION) {
  9057. returnExpression.deoptimizePath(path);
  9058. }
  9059. }
  9060. getLiteralValueAtPath(path, recursionTracker, origin) {
  9061. const [returnExpression] = this.getReturnExpression(recursionTracker);
  9062. if (returnExpression === UNKNOWN_EXPRESSION) {
  9063. return UnknownValue;
  9064. }
  9065. return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  9066. this.deoptimizableDependentExpressions.push(origin);
  9067. return returnExpression.getLiteralValueAtPath(path, recursionTracker, origin);
  9068. }, UnknownValue);
  9069. }
  9070. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  9071. const returnExpression = this.getReturnExpression(recursionTracker);
  9072. if (returnExpression[0] === UNKNOWN_EXPRESSION) {
  9073. return returnExpression;
  9074. }
  9075. return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  9076. this.deoptimizableDependentExpressions.push(origin);
  9077. const [expression, isPure] = returnExpression[0].getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  9078. return [expression, isPure || returnExpression[1]];
  9079. }, UNKNOWN_RETURN_EXPRESSION);
  9080. }
  9081. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9082. const { type } = interaction;
  9083. if (type === INTERACTION_CALLED) {
  9084. const { args, withNew } = interaction;
  9085. if ((withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, args, this)) {
  9086. return false;
  9087. }
  9088. }
  9089. else if ((type === INTERACTION_ASSIGNED
  9090. ? context.assigned
  9091. : context.accessed).trackEntityAtPathAndGetIfTracked(path, this)) {
  9092. return false;
  9093. }
  9094. const [returnExpression, isPure] = this.getReturnExpression();
  9095. return ((type === INTERACTION_ASSIGNED || !isPure) &&
  9096. returnExpression.hasEffectsOnInteractionAtPath(path, interaction, context));
  9097. }
  9098. }
  9099. class CallExpression extends CallExpressionBase {
  9100. bind() {
  9101. super.bind();
  9102. if (this.callee instanceof Identifier) {
  9103. const variable = this.scope.findVariable(this.callee.name);
  9104. if (variable.isNamespace) {
  9105. this.context.log(LOGLEVEL_WARN, logCannotCallNamespace(this.callee.name), this.start);
  9106. }
  9107. if (this.callee.name === 'eval') {
  9108. this.context.log(LOGLEVEL_WARN, logEval(this.context.module.id), this.start);
  9109. }
  9110. }
  9111. this.interaction = {
  9112. args: [
  9113. this.callee instanceof MemberExpression && !this.callee.variable
  9114. ? this.callee.object
  9115. : null,
  9116. ...this.arguments
  9117. ],
  9118. type: INTERACTION_CALLED,
  9119. withNew: false
  9120. };
  9121. }
  9122. hasEffects(context) {
  9123. try {
  9124. for (const argument of this.arguments) {
  9125. if (argument.hasEffects(context))
  9126. return true;
  9127. }
  9128. if (this.annotationPure) {
  9129. return false;
  9130. }
  9131. return (this.callee.hasEffects(context) ||
  9132. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  9133. }
  9134. finally {
  9135. if (!this.deoptimized)
  9136. this.applyDeoptimizations();
  9137. }
  9138. }
  9139. include(context, includeChildrenRecursively) {
  9140. if (!this.deoptimized)
  9141. this.applyDeoptimizations();
  9142. if (includeChildrenRecursively) {
  9143. super.include(context, includeChildrenRecursively);
  9144. if (includeChildrenRecursively === INCLUDE_PARAMETERS &&
  9145. this.callee instanceof Identifier &&
  9146. this.callee.variable) {
  9147. this.callee.variable.markCalledFromTryStatement();
  9148. }
  9149. }
  9150. else {
  9151. this.included = true;
  9152. this.callee.include(context, false);
  9153. }
  9154. this.callee.includeCallArguments(context, this.arguments);
  9155. }
  9156. isSkippedAsOptional(origin) {
  9157. return (this.callee.isSkippedAsOptional?.(origin) ||
  9158. (this.optional &&
  9159. this.callee.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, origin) == null));
  9160. }
  9161. render(code, options, { renderedSurroundingElement } = BLANK) {
  9162. this.callee.render(code, options, {
  9163. isCalleeOfRenderedParent: true,
  9164. renderedSurroundingElement
  9165. });
  9166. renderCallArguments(code, options, this);
  9167. }
  9168. applyDeoptimizations() {
  9169. this.deoptimized = true;
  9170. this.callee.deoptimizeArgumentsOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  9171. this.context.requestTreeshakingPass();
  9172. }
  9173. getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) {
  9174. if (this.returnExpression === null) {
  9175. this.returnExpression = UNKNOWN_RETURN_EXPRESSION;
  9176. return (this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.interaction, recursionTracker, this));
  9177. }
  9178. return this.returnExpression;
  9179. }
  9180. }
  9181. class CatchScope extends ParameterScope {
  9182. addDeclaration(identifier, context, init, isHoisted) {
  9183. const existingParameter = this.variables.get(identifier.name);
  9184. if (existingParameter) {
  9185. // While we still create a hoisted declaration, the initializer goes to
  9186. // the parameter. Note that technically, the declaration now belongs to
  9187. // two variables, which is not correct but should not cause issues.
  9188. this.parent.addDeclaration(identifier, context, UNDEFINED_EXPRESSION, isHoisted);
  9189. existingParameter.addDeclaration(identifier, init);
  9190. return existingParameter;
  9191. }
  9192. return this.parent.addDeclaration(identifier, context, init, isHoisted);
  9193. }
  9194. }
  9195. class CatchClause extends NodeBase {
  9196. createScope(parentScope) {
  9197. this.scope = new CatchScope(parentScope, this.context);
  9198. }
  9199. parseNode(esTreeNode) {
  9200. // Parameters need to be declared first as the logic is that initializers
  9201. // of hoisted body variables are associated with parameters of the same
  9202. // name instead of the variable
  9203. const { param } = esTreeNode;
  9204. if (param) {
  9205. this.param = new (this.context.getNodeConstructor(param.type))(param, this, this.scope);
  9206. this.param.declare('parameter', UNKNOWN_EXPRESSION);
  9207. }
  9208. super.parseNode(esTreeNode);
  9209. }
  9210. }
  9211. class ChainExpression extends NodeBase {
  9212. // deoptimizations are not relevant as we are not caching values
  9213. deoptimizeCache() { }
  9214. getLiteralValueAtPath(path, recursionTracker, origin) {
  9215. if (this.expression.isSkippedAsOptional(origin))
  9216. return undefined;
  9217. return this.expression.getLiteralValueAtPath(path, recursionTracker, origin);
  9218. }
  9219. hasEffects(context) {
  9220. if (this.expression.isSkippedAsOptional(this))
  9221. return false;
  9222. return this.expression.hasEffects(context);
  9223. }
  9224. }
  9225. class ClassBodyScope extends ChildScope {
  9226. constructor(parent, classNode, context) {
  9227. super(parent);
  9228. this.variables.set('this', (this.thisVariable = new LocalVariable('this', null, classNode, context)));
  9229. this.instanceScope = new ChildScope(this);
  9230. this.instanceScope.variables.set('this', new ThisVariable(context));
  9231. }
  9232. findLexicalBoundary() {
  9233. return this;
  9234. }
  9235. }
  9236. class ClassBody extends NodeBase {
  9237. createScope(parentScope) {
  9238. this.scope = new ClassBodyScope(parentScope, this.parent, this.context);
  9239. }
  9240. include(context, includeChildrenRecursively) {
  9241. this.included = true;
  9242. this.context.includeVariableInModule(this.scope.thisVariable);
  9243. for (const definition of this.body) {
  9244. definition.include(context, includeChildrenRecursively);
  9245. }
  9246. }
  9247. parseNode(esTreeNode) {
  9248. const body = (this.body = []);
  9249. for (const definition of esTreeNode.body) {
  9250. body.push(new (this.context.getNodeConstructor(definition.type))(definition, this, definition.static ? this.scope : this.scope.instanceScope));
  9251. }
  9252. super.parseNode(esTreeNode);
  9253. }
  9254. applyDeoptimizations() { }
  9255. }
  9256. class MethodBase extends NodeBase {
  9257. constructor() {
  9258. super(...arguments);
  9259. this.accessedValue = null;
  9260. }
  9261. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  9262. if (interaction.type === INTERACTION_ACCESSED && this.kind === 'get' && path.length === 0) {
  9263. return this.value.deoptimizeArgumentsOnInteractionAtPath({
  9264. args: interaction.args,
  9265. type: INTERACTION_CALLED,
  9266. withNew: false
  9267. }, EMPTY_PATH, recursionTracker);
  9268. }
  9269. if (interaction.type === INTERACTION_ASSIGNED && this.kind === 'set' && path.length === 0) {
  9270. return this.value.deoptimizeArgumentsOnInteractionAtPath({
  9271. args: interaction.args,
  9272. type: INTERACTION_CALLED,
  9273. withNew: false
  9274. }, EMPTY_PATH, recursionTracker);
  9275. }
  9276. this.getAccessedValue()[0].deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  9277. }
  9278. // As getter properties directly receive their values from fixed function
  9279. // expressions, there is no known situation where a getter is deoptimized.
  9280. deoptimizeCache() { }
  9281. deoptimizePath(path) {
  9282. this.getAccessedValue()[0].deoptimizePath(path);
  9283. }
  9284. getLiteralValueAtPath(path, recursionTracker, origin) {
  9285. return this.getAccessedValue()[0].getLiteralValueAtPath(path, recursionTracker, origin);
  9286. }
  9287. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  9288. return this.getAccessedValue()[0].getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  9289. }
  9290. hasEffects(context) {
  9291. return this.key.hasEffects(context);
  9292. }
  9293. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9294. if (this.kind === 'get' && interaction.type === INTERACTION_ACCESSED && path.length === 0) {
  9295. return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
  9296. args: interaction.args,
  9297. type: INTERACTION_CALLED,
  9298. withNew: false
  9299. }, context);
  9300. }
  9301. // setters are only called for empty paths
  9302. if (this.kind === 'set' && interaction.type === INTERACTION_ASSIGNED) {
  9303. return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
  9304. args: interaction.args,
  9305. type: INTERACTION_CALLED,
  9306. withNew: false
  9307. }, context);
  9308. }
  9309. return this.getAccessedValue()[0].hasEffectsOnInteractionAtPath(path, interaction, context);
  9310. }
  9311. applyDeoptimizations() { }
  9312. getAccessedValue() {
  9313. if (this.accessedValue === null) {
  9314. if (this.kind === 'get') {
  9315. this.accessedValue = UNKNOWN_RETURN_EXPRESSION;
  9316. return (this.accessedValue = this.value.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, SHARED_RECURSION_TRACKER, this));
  9317. }
  9318. else {
  9319. return (this.accessedValue = [this.value, false]);
  9320. }
  9321. }
  9322. return this.accessedValue;
  9323. }
  9324. }
  9325. class MethodDefinition extends MethodBase {
  9326. applyDeoptimizations() { }
  9327. }
  9328. class ObjectMember extends ExpressionEntity {
  9329. constructor(object, key) {
  9330. super();
  9331. this.object = object;
  9332. this.key = key;
  9333. }
  9334. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  9335. this.object.deoptimizeArgumentsOnInteractionAtPath(interaction, [this.key, ...path], recursionTracker);
  9336. }
  9337. deoptimizePath(path) {
  9338. this.object.deoptimizePath([this.key, ...path]);
  9339. }
  9340. getLiteralValueAtPath(path, recursionTracker, origin) {
  9341. return this.object.getLiteralValueAtPath([this.key, ...path], recursionTracker, origin);
  9342. }
  9343. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  9344. return this.object.getReturnExpressionWhenCalledAtPath([this.key, ...path], interaction, recursionTracker, origin);
  9345. }
  9346. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9347. return this.object.hasEffectsOnInteractionAtPath([this.key, ...path], interaction, context);
  9348. }
  9349. }
  9350. class ClassNode extends NodeBase {
  9351. constructor() {
  9352. super(...arguments);
  9353. this.objectEntity = null;
  9354. }
  9355. createScope(parentScope) {
  9356. this.scope = new ChildScope(parentScope);
  9357. }
  9358. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  9359. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  9360. }
  9361. deoptimizeCache() {
  9362. this.getObjectEntity().deoptimizeAllProperties();
  9363. }
  9364. deoptimizePath(path) {
  9365. this.getObjectEntity().deoptimizePath(path);
  9366. }
  9367. getLiteralValueAtPath(path, recursionTracker, origin) {
  9368. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  9369. }
  9370. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  9371. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  9372. }
  9373. hasEffects(context) {
  9374. if (!this.deoptimized)
  9375. this.applyDeoptimizations();
  9376. const initEffect = this.superClass?.hasEffects(context) || this.body.hasEffects(context);
  9377. this.id?.markDeclarationReached();
  9378. return initEffect || super.hasEffects(context);
  9379. }
  9380. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9381. return interaction.type === INTERACTION_CALLED && path.length === 0
  9382. ? !interaction.withNew ||
  9383. (this.classConstructor === null
  9384. ? this.superClass?.hasEffectsOnInteractionAtPath(path, interaction, context)
  9385. : this.classConstructor.hasEffectsOnInteractionAtPath(path, interaction, context)) ||
  9386. false
  9387. : this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  9388. }
  9389. include(context, includeChildrenRecursively) {
  9390. if (!this.deoptimized)
  9391. this.applyDeoptimizations();
  9392. this.included = true;
  9393. this.superClass?.include(context, includeChildrenRecursively);
  9394. this.body.include(context, includeChildrenRecursively);
  9395. if (this.id) {
  9396. this.id.markDeclarationReached();
  9397. this.id.include();
  9398. }
  9399. }
  9400. initialise() {
  9401. this.id?.declare('class', this);
  9402. for (const method of this.body.body) {
  9403. if (method instanceof MethodDefinition && method.kind === 'constructor') {
  9404. this.classConstructor = method;
  9405. return;
  9406. }
  9407. }
  9408. this.classConstructor = null;
  9409. }
  9410. applyDeoptimizations() {
  9411. this.deoptimized = true;
  9412. for (const definition of this.body.body) {
  9413. if (!(definition.static ||
  9414. (definition instanceof MethodDefinition && definition.kind === 'constructor'))) {
  9415. // Calls to methods are not tracked, ensure that the return value is deoptimized
  9416. definition.deoptimizePath(UNKNOWN_PATH);
  9417. }
  9418. }
  9419. this.context.requestTreeshakingPass();
  9420. }
  9421. getObjectEntity() {
  9422. if (this.objectEntity !== null) {
  9423. return this.objectEntity;
  9424. }
  9425. const staticProperties = [];
  9426. const dynamicMethods = [];
  9427. for (const definition of this.body.body) {
  9428. const properties = definition.static ? staticProperties : dynamicMethods;
  9429. const definitionKind = definition.kind;
  9430. // Note that class fields do not end up on the prototype
  9431. if (properties === dynamicMethods && !definitionKind)
  9432. continue;
  9433. const kind = definitionKind === 'set' || definitionKind === 'get' ? definitionKind : 'init';
  9434. let key;
  9435. if (definition.computed) {
  9436. const keyValue = definition.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  9437. if (typeof keyValue === 'symbol') {
  9438. properties.push({ key: UnknownKey, kind, property: definition });
  9439. continue;
  9440. }
  9441. else {
  9442. key = String(keyValue);
  9443. }
  9444. }
  9445. else {
  9446. key =
  9447. definition.key instanceof Identifier
  9448. ? definition.key.name
  9449. : String(definition.key.value);
  9450. }
  9451. properties.push({ key, kind, property: definition });
  9452. }
  9453. staticProperties.unshift({
  9454. key: 'prototype',
  9455. kind: 'init',
  9456. property: new ObjectEntity(dynamicMethods, this.superClass ? new ObjectMember(this.superClass, 'prototype') : OBJECT_PROTOTYPE)
  9457. });
  9458. return (this.objectEntity = new ObjectEntity(staticProperties, this.superClass || OBJECT_PROTOTYPE));
  9459. }
  9460. }
  9461. class ClassDeclaration extends ClassNode {
  9462. initialise() {
  9463. super.initialise();
  9464. if (this.id !== null) {
  9465. this.id.variable.isId = true;
  9466. }
  9467. }
  9468. parseNode(esTreeNode) {
  9469. if (esTreeNode.id !== null) {
  9470. this.id = new Identifier(esTreeNode.id, this, this.scope.parent);
  9471. }
  9472. super.parseNode(esTreeNode);
  9473. }
  9474. render(code, options) {
  9475. const { exportNamesByVariable, format, snippets: { _, getPropertyAccess } } = options;
  9476. if (this.id) {
  9477. const { variable, name } = this.id;
  9478. if (format === 'system' && exportNamesByVariable.has(variable)) {
  9479. code.appendLeft(this.end, `${_}${getSystemExportStatement([variable], options)};`);
  9480. }
  9481. const renderedVariable = variable.getName(getPropertyAccess);
  9482. if (renderedVariable !== name) {
  9483. this.superClass?.render(code, options);
  9484. this.body.render(code, {
  9485. ...options,
  9486. useOriginalName: (_variable) => _variable === variable
  9487. });
  9488. code.prependRight(this.start, `let ${renderedVariable}${_}=${_}`);
  9489. code.prependLeft(this.end, ';');
  9490. return;
  9491. }
  9492. }
  9493. super.render(code, options);
  9494. }
  9495. applyDeoptimizations() {
  9496. super.applyDeoptimizations();
  9497. const { id, scope } = this;
  9498. if (id) {
  9499. const { name, variable } = id;
  9500. for (const accessedVariable of scope.accessedOutsideVariables.values()) {
  9501. if (accessedVariable !== variable) {
  9502. accessedVariable.forbidName(name);
  9503. }
  9504. }
  9505. }
  9506. }
  9507. }
  9508. class ClassExpression extends ClassNode {
  9509. render(code, options, { renderedSurroundingElement } = BLANK) {
  9510. super.render(code, options);
  9511. if (renderedSurroundingElement === ExpressionStatement$1) {
  9512. code.appendRight(this.start, '(');
  9513. code.prependLeft(this.end, ')');
  9514. }
  9515. }
  9516. }
  9517. class MultiExpression extends ExpressionEntity {
  9518. constructor(expressions) {
  9519. super();
  9520. this.expressions = expressions;
  9521. this.included = false;
  9522. }
  9523. deoptimizePath(path) {
  9524. for (const expression of this.expressions) {
  9525. expression.deoptimizePath(path);
  9526. }
  9527. }
  9528. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  9529. return [
  9530. new MultiExpression(this.expressions.map(expression => expression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0])),
  9531. false
  9532. ];
  9533. }
  9534. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9535. for (const expression of this.expressions) {
  9536. if (expression.hasEffectsOnInteractionAtPath(path, interaction, context))
  9537. return true;
  9538. }
  9539. return false;
  9540. }
  9541. }
  9542. class ConditionalExpression extends NodeBase {
  9543. constructor() {
  9544. super(...arguments);
  9545. this.expressionsToBeDeoptimized = [];
  9546. this.isBranchResolutionAnalysed = false;
  9547. this.usedBranch = null;
  9548. }
  9549. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  9550. this.consequent.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  9551. this.alternate.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  9552. }
  9553. deoptimizeCache() {
  9554. if (this.usedBranch !== null) {
  9555. const unusedBranch = this.usedBranch === this.consequent ? this.alternate : this.consequent;
  9556. this.usedBranch = null;
  9557. unusedBranch.deoptimizePath(UNKNOWN_PATH);
  9558. const { expressionsToBeDeoptimized } = this;
  9559. this.expressionsToBeDeoptimized = EMPTY_ARRAY;
  9560. for (const expression of expressionsToBeDeoptimized) {
  9561. expression.deoptimizeCache();
  9562. }
  9563. }
  9564. }
  9565. deoptimizePath(path) {
  9566. const usedBranch = this.getUsedBranch();
  9567. if (usedBranch) {
  9568. usedBranch.deoptimizePath(path);
  9569. }
  9570. else {
  9571. this.consequent.deoptimizePath(path);
  9572. this.alternate.deoptimizePath(path);
  9573. }
  9574. }
  9575. getLiteralValueAtPath(path, recursionTracker, origin) {
  9576. const usedBranch = this.getUsedBranch();
  9577. if (!usedBranch)
  9578. return UnknownValue;
  9579. this.expressionsToBeDeoptimized.push(origin);
  9580. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  9581. }
  9582. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  9583. const usedBranch = this.getUsedBranch();
  9584. if (!usedBranch)
  9585. return [
  9586. new MultiExpression([
  9587. this.consequent.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0],
  9588. this.alternate.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0]
  9589. ]),
  9590. false
  9591. ];
  9592. this.expressionsToBeDeoptimized.push(origin);
  9593. return usedBranch.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  9594. }
  9595. hasEffects(context) {
  9596. if (this.test.hasEffects(context))
  9597. return true;
  9598. const usedBranch = this.getUsedBranch();
  9599. if (!usedBranch) {
  9600. return this.consequent.hasEffects(context) || this.alternate.hasEffects(context);
  9601. }
  9602. return usedBranch.hasEffects(context);
  9603. }
  9604. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9605. const usedBranch = this.getUsedBranch();
  9606. if (!usedBranch) {
  9607. return (this.consequent.hasEffectsOnInteractionAtPath(path, interaction, context) ||
  9608. this.alternate.hasEffectsOnInteractionAtPath(path, interaction, context));
  9609. }
  9610. return usedBranch.hasEffectsOnInteractionAtPath(path, interaction, context);
  9611. }
  9612. include(context, includeChildrenRecursively) {
  9613. this.included = true;
  9614. const usedBranch = this.getUsedBranch();
  9615. if (includeChildrenRecursively || this.test.shouldBeIncluded(context) || usedBranch === null) {
  9616. this.test.include(context, includeChildrenRecursively);
  9617. this.consequent.include(context, includeChildrenRecursively);
  9618. this.alternate.include(context, includeChildrenRecursively);
  9619. }
  9620. else {
  9621. usedBranch.include(context, includeChildrenRecursively);
  9622. }
  9623. }
  9624. includeCallArguments(context, parameters) {
  9625. const usedBranch = this.getUsedBranch();
  9626. if (usedBranch) {
  9627. usedBranch.includeCallArguments(context, parameters);
  9628. }
  9629. else {
  9630. this.consequent.includeCallArguments(context, parameters);
  9631. this.alternate.includeCallArguments(context, parameters);
  9632. }
  9633. }
  9634. render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  9635. const usedBranch = this.getUsedBranch();
  9636. if (this.test.included) {
  9637. this.test.render(code, options, { renderedSurroundingElement });
  9638. this.consequent.render(code, options);
  9639. this.alternate.render(code, options);
  9640. }
  9641. else {
  9642. const colonPos = findFirstOccurrenceOutsideComment(code.original, ':', this.consequent.end);
  9643. const inclusionStart = findNonWhiteSpace(code.original, (this.consequent.included
  9644. ? findFirstOccurrenceOutsideComment(code.original, '?', this.test.end)
  9645. : colonPos) + 1);
  9646. if (preventASI) {
  9647. removeLineBreaks(code, inclusionStart, usedBranch.start);
  9648. }
  9649. code.remove(this.start, inclusionStart);
  9650. if (this.consequent.included) {
  9651. code.remove(colonPos, this.end);
  9652. }
  9653. removeAnnotations(this, code);
  9654. usedBranch.render(code, options, {
  9655. isCalleeOfRenderedParent,
  9656. preventASI: true,
  9657. renderedParentType: renderedParentType || this.parent.type,
  9658. renderedSurroundingElement: renderedSurroundingElement || this.parent.type
  9659. });
  9660. }
  9661. }
  9662. getUsedBranch() {
  9663. if (this.isBranchResolutionAnalysed) {
  9664. return this.usedBranch;
  9665. }
  9666. this.isBranchResolutionAnalysed = true;
  9667. const testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  9668. return typeof testValue === 'symbol'
  9669. ? null
  9670. : (this.usedBranch = testValue ? this.consequent : this.alternate);
  9671. }
  9672. }
  9673. class ContinueStatement extends NodeBase {
  9674. hasEffects(context) {
  9675. if (this.label) {
  9676. if (!context.ignore.labels.has(this.label.name))
  9677. return true;
  9678. context.includedLabels.add(this.label.name);
  9679. }
  9680. else {
  9681. if (!context.ignore.continues)
  9682. return true;
  9683. context.hasContinue = true;
  9684. }
  9685. context.brokenFlow = true;
  9686. return false;
  9687. }
  9688. include(context) {
  9689. this.included = true;
  9690. if (this.label) {
  9691. this.label.include();
  9692. context.includedLabels.add(this.label.name);
  9693. }
  9694. else {
  9695. context.hasContinue = true;
  9696. }
  9697. context.brokenFlow = true;
  9698. }
  9699. }
  9700. function hasLoopBodyEffects(context, body) {
  9701. const { brokenFlow, hasBreak, hasContinue, ignore } = context;
  9702. const { breaks, continues } = ignore;
  9703. ignore.breaks = true;
  9704. ignore.continues = true;
  9705. context.hasBreak = false;
  9706. context.hasContinue = false;
  9707. if (body.hasEffects(context))
  9708. return true;
  9709. ignore.breaks = breaks;
  9710. ignore.continues = continues;
  9711. context.hasBreak = hasBreak;
  9712. context.hasContinue = hasContinue;
  9713. context.brokenFlow = brokenFlow;
  9714. return false;
  9715. }
  9716. function includeLoopBody(context, body, includeChildrenRecursively) {
  9717. const { brokenFlow, hasBreak, hasContinue } = context;
  9718. context.hasBreak = false;
  9719. context.hasContinue = false;
  9720. body.include(context, includeChildrenRecursively, { asSingleStatement: true });
  9721. context.hasBreak = hasBreak;
  9722. context.hasContinue = hasContinue;
  9723. context.brokenFlow = brokenFlow;
  9724. }
  9725. class DoWhileStatement extends NodeBase {
  9726. hasEffects(context) {
  9727. if (this.test.hasEffects(context))
  9728. return true;
  9729. return hasLoopBodyEffects(context, this.body);
  9730. }
  9731. include(context, includeChildrenRecursively) {
  9732. this.included = true;
  9733. this.test.include(context, includeChildrenRecursively);
  9734. includeLoopBody(context, this.body, includeChildrenRecursively);
  9735. }
  9736. }
  9737. class EmptyStatement extends NodeBase {
  9738. hasEffects() {
  9739. return false;
  9740. }
  9741. }
  9742. class ExportAllDeclaration extends NodeBase {
  9743. hasEffects() {
  9744. return false;
  9745. }
  9746. initialise() {
  9747. this.context.addExport(this);
  9748. }
  9749. render(code, _options, nodeRenderOptions) {
  9750. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  9751. }
  9752. applyDeoptimizations() { }
  9753. }
  9754. ExportAllDeclaration.prototype.needsBoundaries = true;
  9755. class FunctionDeclaration extends FunctionNode {
  9756. initialise() {
  9757. super.initialise();
  9758. if (this.id !== null) {
  9759. this.id.variable.isId = true;
  9760. }
  9761. }
  9762. parseNode(esTreeNode) {
  9763. if (esTreeNode.id !== null) {
  9764. this.id = new Identifier(esTreeNode.id, this, this.scope.parent);
  9765. }
  9766. super.parseNode(esTreeNode);
  9767. }
  9768. }
  9769. // The header ends at the first non-white-space after "default"
  9770. function getDeclarationStart(code, start) {
  9771. return findNonWhiteSpace(code, findFirstOccurrenceOutsideComment(code, 'default', start) + 7);
  9772. }
  9773. function getFunctionIdInsertPosition(code, start) {
  9774. const declarationEnd = findFirstOccurrenceOutsideComment(code, 'function', start) + 'function'.length;
  9775. code = code.slice(declarationEnd, findFirstOccurrenceOutsideComment(code, '(', declarationEnd));
  9776. const generatorStarPos = findFirstOccurrenceOutsideComment(code, '*');
  9777. if (generatorStarPos === -1) {
  9778. return declarationEnd;
  9779. }
  9780. return declarationEnd + generatorStarPos + 1;
  9781. }
  9782. class ExportDefaultDeclaration extends NodeBase {
  9783. include(context, includeChildrenRecursively) {
  9784. super.include(context, includeChildrenRecursively);
  9785. if (includeChildrenRecursively) {
  9786. this.context.includeVariableInModule(this.variable);
  9787. }
  9788. }
  9789. initialise() {
  9790. const declaration = this.declaration;
  9791. this.declarationName =
  9792. (declaration.id && declaration.id.name) || this.declaration.name;
  9793. this.variable = this.scope.addExportDefaultDeclaration(this.declarationName || this.context.getModuleName(), this, this.context);
  9794. this.context.addExport(this);
  9795. }
  9796. render(code, options, nodeRenderOptions) {
  9797. const { start, end } = nodeRenderOptions;
  9798. const declarationStart = getDeclarationStart(code.original, this.start);
  9799. if (this.declaration instanceof FunctionDeclaration) {
  9800. this.renderNamedDeclaration(code, declarationStart, this.declaration.id === null
  9801. ? getFunctionIdInsertPosition(code.original, declarationStart)
  9802. : null, options);
  9803. }
  9804. else if (this.declaration instanceof ClassDeclaration) {
  9805. this.renderNamedDeclaration(code, declarationStart, this.declaration.id === null
  9806. ? findFirstOccurrenceOutsideComment(code.original, 'class', start) + 'class'.length
  9807. : null, options);
  9808. }
  9809. else if (this.variable.getOriginalVariable() !== this.variable) {
  9810. // Remove altogether to prevent re-declaring the same variable
  9811. treeshakeNode(this, code, start, end);
  9812. return;
  9813. }
  9814. else if (this.variable.included) {
  9815. this.renderVariableDeclaration(code, declarationStart, options);
  9816. }
  9817. else {
  9818. code.remove(this.start, declarationStart);
  9819. this.declaration.render(code, options, {
  9820. renderedSurroundingElement: ExpressionStatement$1
  9821. });
  9822. if (code.original[this.end - 1] !== ';') {
  9823. code.appendLeft(this.end, ';');
  9824. }
  9825. return;
  9826. }
  9827. this.declaration.render(code, options);
  9828. }
  9829. applyDeoptimizations() { }
  9830. renderNamedDeclaration(code, declarationStart, idInsertPosition, options) {
  9831. const { exportNamesByVariable, format, snippets: { getPropertyAccess } } = options;
  9832. const name = this.variable.getName(getPropertyAccess);
  9833. // Remove `export default`
  9834. code.remove(this.start, declarationStart);
  9835. if (idInsertPosition !== null) {
  9836. code.appendLeft(idInsertPosition, ` ${name}`);
  9837. }
  9838. if (format === 'system' &&
  9839. this.declaration instanceof ClassDeclaration &&
  9840. exportNamesByVariable.has(this.variable)) {
  9841. code.appendLeft(this.end, ` ${getSystemExportStatement([this.variable], options)};`);
  9842. }
  9843. }
  9844. renderVariableDeclaration(code, declarationStart, { format, exportNamesByVariable, snippets: { cnst, getPropertyAccess } }) {
  9845. const hasTrailingSemicolon = code.original.charCodeAt(this.end - 1) === 59; /*";"*/
  9846. const systemExportNames = format === 'system' && exportNamesByVariable.get(this.variable);
  9847. if (systemExportNames) {
  9848. code.overwrite(this.start, declarationStart, `${cnst} ${this.variable.getName(getPropertyAccess)} = exports('${systemExportNames[0]}', `);
  9849. code.appendRight(hasTrailingSemicolon ? this.end - 1 : this.end, ')' + (hasTrailingSemicolon ? '' : ';'));
  9850. }
  9851. else {
  9852. code.overwrite(this.start, declarationStart, `${cnst} ${this.variable.getName(getPropertyAccess)} = `);
  9853. if (!hasTrailingSemicolon) {
  9854. code.appendLeft(this.end, ';');
  9855. }
  9856. }
  9857. }
  9858. }
  9859. ExportDefaultDeclaration.prototype.needsBoundaries = true;
  9860. class ExportNamedDeclaration extends NodeBase {
  9861. bind() {
  9862. // Do not bind specifiers
  9863. this.declaration?.bind();
  9864. }
  9865. hasEffects(context) {
  9866. return !!this.declaration?.hasEffects(context);
  9867. }
  9868. initialise() {
  9869. this.context.addExport(this);
  9870. }
  9871. render(code, options, nodeRenderOptions) {
  9872. const { start, end } = nodeRenderOptions;
  9873. if (this.declaration === null) {
  9874. code.remove(start, end);
  9875. }
  9876. else {
  9877. code.remove(this.start, this.declaration.start);
  9878. this.declaration.render(code, options, { end, start });
  9879. }
  9880. }
  9881. applyDeoptimizations() { }
  9882. }
  9883. ExportNamedDeclaration.prototype.needsBoundaries = true;
  9884. class ExportSpecifier extends NodeBase {
  9885. applyDeoptimizations() { }
  9886. }
  9887. class ForInStatement extends NodeBase {
  9888. createScope(parentScope) {
  9889. this.scope = new BlockScope(parentScope);
  9890. }
  9891. hasEffects(context) {
  9892. const { body, deoptimized, left, right } = this;
  9893. if (!deoptimized)
  9894. this.applyDeoptimizations();
  9895. if (left.hasEffectsAsAssignmentTarget(context, false) || right.hasEffects(context))
  9896. return true;
  9897. return hasLoopBodyEffects(context, body);
  9898. }
  9899. include(context, includeChildrenRecursively) {
  9900. const { body, deoptimized, left, right } = this;
  9901. if (!deoptimized)
  9902. this.applyDeoptimizations();
  9903. this.included = true;
  9904. left.includeAsAssignmentTarget(context, includeChildrenRecursively || true, false);
  9905. right.include(context, includeChildrenRecursively);
  9906. includeLoopBody(context, body, includeChildrenRecursively);
  9907. }
  9908. initialise() {
  9909. this.left.setAssignedValue(UNKNOWN_EXPRESSION);
  9910. }
  9911. render(code, options) {
  9912. this.left.render(code, options, NO_SEMICOLON);
  9913. this.right.render(code, options, NO_SEMICOLON);
  9914. // handle no space between "in" and the right side
  9915. if (code.original.charCodeAt(this.right.start - 1) === 110 /* n */) {
  9916. code.prependLeft(this.right.start, ' ');
  9917. }
  9918. this.body.render(code, options);
  9919. }
  9920. applyDeoptimizations() {
  9921. this.deoptimized = true;
  9922. this.left.deoptimizePath(EMPTY_PATH);
  9923. this.context.requestTreeshakingPass();
  9924. }
  9925. }
  9926. class ForOfStatement extends NodeBase {
  9927. createScope(parentScope) {
  9928. this.scope = new BlockScope(parentScope);
  9929. }
  9930. hasEffects() {
  9931. if (!this.deoptimized)
  9932. this.applyDeoptimizations();
  9933. // Placeholder until proper Symbol.Iterator support
  9934. return true;
  9935. }
  9936. include(context, includeChildrenRecursively) {
  9937. const { body, deoptimized, left, right } = this;
  9938. if (!deoptimized)
  9939. this.applyDeoptimizations();
  9940. this.included = true;
  9941. left.includeAsAssignmentTarget(context, includeChildrenRecursively || true, false);
  9942. right.include(context, includeChildrenRecursively);
  9943. includeLoopBody(context, body, includeChildrenRecursively);
  9944. }
  9945. initialise() {
  9946. this.left.setAssignedValue(UNKNOWN_EXPRESSION);
  9947. }
  9948. render(code, options) {
  9949. this.left.render(code, options, NO_SEMICOLON);
  9950. this.right.render(code, options, NO_SEMICOLON);
  9951. // handle no space between "of" and the right side
  9952. if (code.original.charCodeAt(this.right.start - 1) === 102 /* f */) {
  9953. code.prependLeft(this.right.start, ' ');
  9954. }
  9955. this.body.render(code, options);
  9956. }
  9957. applyDeoptimizations() {
  9958. this.deoptimized = true;
  9959. this.left.deoptimizePath(EMPTY_PATH);
  9960. this.right.deoptimizePath(UNKNOWN_PATH);
  9961. this.context.requestTreeshakingPass();
  9962. }
  9963. }
  9964. class ForStatement extends NodeBase {
  9965. createScope(parentScope) {
  9966. this.scope = new BlockScope(parentScope);
  9967. }
  9968. hasEffects(context) {
  9969. if (this.init?.hasEffects(context) ||
  9970. this.test?.hasEffects(context) ||
  9971. this.update?.hasEffects(context)) {
  9972. return true;
  9973. }
  9974. return hasLoopBodyEffects(context, this.body);
  9975. }
  9976. include(context, includeChildrenRecursively) {
  9977. this.included = true;
  9978. this.init?.include(context, includeChildrenRecursively, { asSingleStatement: true });
  9979. this.test?.include(context, includeChildrenRecursively);
  9980. this.update?.include(context, includeChildrenRecursively);
  9981. includeLoopBody(context, this.body, includeChildrenRecursively);
  9982. }
  9983. render(code, options) {
  9984. this.init?.render(code, options, NO_SEMICOLON);
  9985. this.test?.render(code, options, NO_SEMICOLON);
  9986. this.update?.render(code, options, NO_SEMICOLON);
  9987. this.body.render(code, options);
  9988. }
  9989. }
  9990. class FunctionExpression extends FunctionNode {
  9991. render(code, options, { renderedSurroundingElement } = BLANK) {
  9992. super.render(code, options);
  9993. if (renderedSurroundingElement === ExpressionStatement$1) {
  9994. code.appendRight(this.start, '(');
  9995. code.prependLeft(this.end, ')');
  9996. }
  9997. }
  9998. }
  9999. class TrackingScope extends BlockScope {
  10000. constructor() {
  10001. super(...arguments);
  10002. this.hoistedDeclarations = [];
  10003. }
  10004. addDeclaration(identifier, context, init, isHoisted) {
  10005. this.hoistedDeclarations.push(identifier);
  10006. return super.addDeclaration(identifier, context, init, isHoisted);
  10007. }
  10008. }
  10009. const unset = Symbol('unset');
  10010. class IfStatement extends NodeBase {
  10011. constructor() {
  10012. super(...arguments);
  10013. this.testValue = unset;
  10014. }
  10015. deoptimizeCache() {
  10016. this.testValue = UnknownValue;
  10017. }
  10018. hasEffects(context) {
  10019. if (this.test.hasEffects(context)) {
  10020. return true;
  10021. }
  10022. const testValue = this.getTestValue();
  10023. if (typeof testValue === 'symbol') {
  10024. const { brokenFlow } = context;
  10025. if (this.consequent.hasEffects(context))
  10026. return true;
  10027. // eslint-disable-next-line unicorn/consistent-destructuring
  10028. const consequentBrokenFlow = context.brokenFlow;
  10029. context.brokenFlow = brokenFlow;
  10030. if (this.alternate === null)
  10031. return false;
  10032. if (this.alternate.hasEffects(context))
  10033. return true;
  10034. // eslint-disable-next-line unicorn/consistent-destructuring
  10035. context.brokenFlow = context.brokenFlow && consequentBrokenFlow;
  10036. return false;
  10037. }
  10038. return testValue ? this.consequent.hasEffects(context) : !!this.alternate?.hasEffects(context);
  10039. }
  10040. include(context, includeChildrenRecursively) {
  10041. this.included = true;
  10042. if (includeChildrenRecursively) {
  10043. this.includeRecursively(includeChildrenRecursively, context);
  10044. }
  10045. else {
  10046. const testValue = this.getTestValue();
  10047. if (typeof testValue === 'symbol') {
  10048. this.includeUnknownTest(context);
  10049. }
  10050. else {
  10051. this.includeKnownTest(context, testValue);
  10052. }
  10053. }
  10054. }
  10055. parseNode(esTreeNode) {
  10056. this.consequentScope = new TrackingScope(this.scope);
  10057. this.consequent = new (this.context.getNodeConstructor(esTreeNode.consequent.type))(esTreeNode.consequent, this, this.consequentScope);
  10058. if (esTreeNode.alternate) {
  10059. this.alternateScope = new TrackingScope(this.scope);
  10060. this.alternate = new (this.context.getNodeConstructor(esTreeNode.alternate.type))(esTreeNode.alternate, this, this.alternateScope);
  10061. }
  10062. super.parseNode(esTreeNode);
  10063. }
  10064. render(code, options) {
  10065. const { snippets: { getPropertyAccess } } = options;
  10066. // Note that unknown test values are always included
  10067. const testValue = this.getTestValue();
  10068. const hoistedDeclarations = [];
  10069. const includesIfElse = this.test.included;
  10070. const noTreeshake = !this.context.options.treeshake;
  10071. if (includesIfElse) {
  10072. this.test.render(code, options);
  10073. }
  10074. else {
  10075. code.remove(this.start, this.consequent.start);
  10076. }
  10077. if (this.consequent.included && (noTreeshake || typeof testValue === 'symbol' || testValue)) {
  10078. this.consequent.render(code, options);
  10079. }
  10080. else {
  10081. code.overwrite(this.consequent.start, this.consequent.end, includesIfElse ? ';' : '');
  10082. hoistedDeclarations.push(...this.consequentScope.hoistedDeclarations);
  10083. }
  10084. if (this.alternate) {
  10085. if (this.alternate.included && (noTreeshake || typeof testValue === 'symbol' || !testValue)) {
  10086. if (includesIfElse) {
  10087. if (code.original.charCodeAt(this.alternate.start - 1) === 101) {
  10088. code.prependLeft(this.alternate.start, ' ');
  10089. }
  10090. }
  10091. else {
  10092. code.remove(this.consequent.end, this.alternate.start);
  10093. }
  10094. this.alternate.render(code, options);
  10095. }
  10096. else {
  10097. if (includesIfElse && this.shouldKeepAlternateBranch()) {
  10098. code.overwrite(this.alternate.start, this.end, ';');
  10099. }
  10100. else {
  10101. code.remove(this.consequent.end, this.end);
  10102. }
  10103. hoistedDeclarations.push(...this.alternateScope.hoistedDeclarations);
  10104. }
  10105. }
  10106. this.renderHoistedDeclarations(hoistedDeclarations, code, getPropertyAccess);
  10107. }
  10108. applyDeoptimizations() { }
  10109. getTestValue() {
  10110. if (this.testValue === unset) {
  10111. return (this.testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this));
  10112. }
  10113. return this.testValue;
  10114. }
  10115. includeKnownTest(context, testValue) {
  10116. if (this.test.shouldBeIncluded(context)) {
  10117. this.test.include(context, false);
  10118. }
  10119. if (testValue && this.consequent.shouldBeIncluded(context)) {
  10120. this.consequent.include(context, false, { asSingleStatement: true });
  10121. }
  10122. if (!testValue && this.alternate?.shouldBeIncluded(context)) {
  10123. this.alternate.include(context, false, { asSingleStatement: true });
  10124. }
  10125. }
  10126. includeRecursively(includeChildrenRecursively, context) {
  10127. this.test.include(context, includeChildrenRecursively);
  10128. this.consequent.include(context, includeChildrenRecursively);
  10129. this.alternate?.include(context, includeChildrenRecursively);
  10130. }
  10131. includeUnknownTest(context) {
  10132. this.test.include(context, false);
  10133. const { brokenFlow } = context;
  10134. let consequentBrokenFlow = false;
  10135. if (this.consequent.shouldBeIncluded(context)) {
  10136. this.consequent.include(context, false, { asSingleStatement: true });
  10137. // eslint-disable-next-line unicorn/consistent-destructuring
  10138. consequentBrokenFlow = context.brokenFlow;
  10139. context.brokenFlow = brokenFlow;
  10140. }
  10141. if (this.alternate?.shouldBeIncluded(context)) {
  10142. this.alternate.include(context, false, { asSingleStatement: true });
  10143. // eslint-disable-next-line unicorn/consistent-destructuring
  10144. context.brokenFlow = context.brokenFlow && consequentBrokenFlow;
  10145. }
  10146. }
  10147. renderHoistedDeclarations(hoistedDeclarations, code, getPropertyAccess) {
  10148. const hoistedVariables = [
  10149. ...new Set(hoistedDeclarations.map(identifier => {
  10150. const variable = identifier.variable;
  10151. return variable.included ? variable.getName(getPropertyAccess) : '';
  10152. }))
  10153. ]
  10154. .filter(Boolean)
  10155. .join(', ');
  10156. if (hoistedVariables) {
  10157. const parentType = this.parent.type;
  10158. const needsBraces = parentType !== Program$1 && parentType !== BlockStatement$1;
  10159. code.prependRight(this.start, `${needsBraces ? '{ ' : ''}var ${hoistedVariables}; `);
  10160. if (needsBraces) {
  10161. code.appendLeft(this.end, ` }`);
  10162. }
  10163. }
  10164. }
  10165. shouldKeepAlternateBranch() {
  10166. let currentParent = this.parent;
  10167. do {
  10168. if (currentParent instanceof IfStatement && currentParent.alternate) {
  10169. return true;
  10170. }
  10171. if (currentParent instanceof BlockStatement) {
  10172. return false;
  10173. }
  10174. currentParent = currentParent.parent;
  10175. } while (currentParent);
  10176. return false;
  10177. }
  10178. }
  10179. class ImportAttribute extends NodeBase {
  10180. }
  10181. class ImportDeclaration extends NodeBase {
  10182. // Do not bind specifiers or assertions
  10183. bind() { }
  10184. hasEffects() {
  10185. return false;
  10186. }
  10187. initialise() {
  10188. this.context.addImport(this);
  10189. }
  10190. render(code, _options, nodeRenderOptions) {
  10191. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  10192. }
  10193. applyDeoptimizations() { }
  10194. }
  10195. ImportDeclaration.prototype.needsBoundaries = true;
  10196. class ImportDefaultSpecifier extends NodeBase {
  10197. applyDeoptimizations() { }
  10198. }
  10199. const INTEROP_DEFAULT_VARIABLE = '_interopDefault';
  10200. const INTEROP_DEFAULT_COMPAT_VARIABLE = '_interopDefaultCompat';
  10201. const INTEROP_NAMESPACE_VARIABLE = '_interopNamespace';
  10202. const INTEROP_NAMESPACE_COMPAT_VARIABLE = '_interopNamespaceCompat';
  10203. const INTEROP_NAMESPACE_DEFAULT_VARIABLE = '_interopNamespaceDefault';
  10204. const INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE = '_interopNamespaceDefaultOnly';
  10205. const MERGE_NAMESPACES_VARIABLE = '_mergeNamespaces';
  10206. const DOCUMENT_CURRENT_SCRIPT = '_documentCurrentScript';
  10207. const defaultInteropHelpersByInteropType = {
  10208. auto: INTEROP_DEFAULT_VARIABLE,
  10209. compat: INTEROP_DEFAULT_COMPAT_VARIABLE,
  10210. default: null,
  10211. defaultOnly: null,
  10212. esModule: null
  10213. };
  10214. const isDefaultAProperty = (interopType, externalLiveBindings) => interopType === 'esModule' ||
  10215. (externalLiveBindings && (interopType === 'auto' || interopType === 'compat'));
  10216. const namespaceInteropHelpersByInteropType = {
  10217. auto: INTEROP_NAMESPACE_VARIABLE,
  10218. compat: INTEROP_NAMESPACE_COMPAT_VARIABLE,
  10219. default: INTEROP_NAMESPACE_DEFAULT_VARIABLE,
  10220. defaultOnly: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE,
  10221. esModule: null
  10222. };
  10223. const canDefaultBeTakenFromNamespace = (interopType, externalLiveBindings) => interopType !== 'esModule' && isDefaultAProperty(interopType, externalLiveBindings);
  10224. const getHelpersBlock = (additionalHelpers, accessedGlobals, indent, snippets, liveBindings, freeze, namespaceToStringTag) => {
  10225. const usedHelpers = new Set(additionalHelpers);
  10226. for (const variable of HELPER_NAMES) {
  10227. if (accessedGlobals.has(variable)) {
  10228. usedHelpers.add(variable);
  10229. }
  10230. }
  10231. return HELPER_NAMES.map(variable => usedHelpers.has(variable)
  10232. ? HELPER_GENERATORS[variable](indent, snippets, liveBindings, freeze, namespaceToStringTag, usedHelpers)
  10233. : '').join('');
  10234. };
  10235. const HELPER_GENERATORS = {
  10236. [DOCUMENT_CURRENT_SCRIPT](_t, { _, n }) {
  10237. return `var${_}${DOCUMENT_CURRENT_SCRIPT}${_}=${_}typeof${_}document${_}!==${_}'undefined'${_}?${_}document.currentScript${_}:${_}null;${n}`;
  10238. },
  10239. [INTEROP_DEFAULT_COMPAT_VARIABLE](_t, snippets, liveBindings) {
  10240. const { _, getDirectReturnFunction, n } = snippets;
  10241. const [left, right] = getDirectReturnFunction(['e'], {
  10242. functionReturn: true,
  10243. lineBreakIndent: null,
  10244. name: INTEROP_DEFAULT_COMPAT_VARIABLE
  10245. });
  10246. return (`${left}${getIsCompatNamespace(snippets)}${_}?${_}` +
  10247. `${liveBindings ? getDefaultLiveBinding(snippets) : getDefaultStatic(snippets)}${right}${n}${n}`);
  10248. },
  10249. [INTEROP_DEFAULT_VARIABLE](_t, snippets, liveBindings) {
  10250. const { _, getDirectReturnFunction, n } = snippets;
  10251. const [left, right] = getDirectReturnFunction(['e'], {
  10252. functionReturn: true,
  10253. lineBreakIndent: null,
  10254. name: INTEROP_DEFAULT_VARIABLE
  10255. });
  10256. return (`${left}e${_}&&${_}e.__esModule${_}?${_}` +
  10257. `${liveBindings ? getDefaultLiveBinding(snippets) : getDefaultStatic(snippets)}${right}${n}${n}`);
  10258. },
  10259. [INTEROP_NAMESPACE_COMPAT_VARIABLE](t, snippets, liveBindings, freeze, namespaceToStringTag, usedHelpers) {
  10260. const { _, getDirectReturnFunction, n } = snippets;
  10261. if (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)) {
  10262. const [left, right] = getDirectReturnFunction(['e'], {
  10263. functionReturn: true,
  10264. lineBreakIndent: null,
  10265. name: INTEROP_NAMESPACE_COMPAT_VARIABLE
  10266. });
  10267. return `${left}${getIsCompatNamespace(snippets)}${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${right}${n}${n}`;
  10268. }
  10269. return (`function ${INTEROP_NAMESPACE_COMPAT_VARIABLE}(e)${_}{${n}` +
  10270. `${t}if${_}(${getIsCompatNamespace(snippets)})${_}return e;${n}` +
  10271. createNamespaceObject(t, t, snippets, liveBindings, freeze, namespaceToStringTag) +
  10272. `}${n}${n}`);
  10273. },
  10274. [INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE](_t, snippets, _liveBindings, freeze, namespaceToStringTag) {
  10275. const { getDirectReturnFunction, getObject, n } = snippets;
  10276. const [left, right] = getDirectReturnFunction(['e'], {
  10277. functionReturn: true,
  10278. lineBreakIndent: null,
  10279. name: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE
  10280. });
  10281. return `${left}${getFrozen(freeze, getWithToStringTag(namespaceToStringTag, getObject([
  10282. ['__proto__', 'null'],
  10283. ['default', 'e']
  10284. ], { lineBreakIndent: null }), snippets))}${right}${n}${n}`;
  10285. },
  10286. [INTEROP_NAMESPACE_DEFAULT_VARIABLE](t, snippets, liveBindings, freeze, namespaceToStringTag) {
  10287. const { _, n } = snippets;
  10288. return (`function ${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${_}{${n}` +
  10289. createNamespaceObject(t, t, snippets, liveBindings, freeze, namespaceToStringTag) +
  10290. `}${n}${n}`);
  10291. },
  10292. [INTEROP_NAMESPACE_VARIABLE](t, snippets, liveBindings, freeze, namespaceToStringTag, usedHelpers) {
  10293. const { _, getDirectReturnFunction, n } = snippets;
  10294. if (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)) {
  10295. const [left, right] = getDirectReturnFunction(['e'], {
  10296. functionReturn: true,
  10297. lineBreakIndent: null,
  10298. name: INTEROP_NAMESPACE_VARIABLE
  10299. });
  10300. return `${left}e${_}&&${_}e.__esModule${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${right}${n}${n}`;
  10301. }
  10302. return (`function ${INTEROP_NAMESPACE_VARIABLE}(e)${_}{${n}` +
  10303. `${t}if${_}(e${_}&&${_}e.__esModule)${_}return e;${n}` +
  10304. createNamespaceObject(t, t, snippets, liveBindings, freeze, namespaceToStringTag) +
  10305. `}${n}${n}`);
  10306. },
  10307. [MERGE_NAMESPACES_VARIABLE](t, snippets, liveBindings, freeze, namespaceToStringTag) {
  10308. const { _, cnst, n } = snippets;
  10309. const useForEach = cnst === 'var' && liveBindings;
  10310. return (`function ${MERGE_NAMESPACES_VARIABLE}(n, m)${_}{${n}` +
  10311. `${t}${loopOverNamespaces(`{${n}` +
  10312. `${t}${t}${t}if${_}(k${_}!==${_}'default'${_}&&${_}!(k in n))${_}{${n}` +
  10313. (liveBindings
  10314. ? useForEach
  10315. ? copyOwnPropertyLiveBinding
  10316. : copyPropertyLiveBinding
  10317. : copyPropertyStatic)(t, t + t + t + t, snippets) +
  10318. `${t}${t}${t}}${n}` +
  10319. `${t}${t}}`, useForEach, t, snippets)}${n}` +
  10320. `${t}return ${getFrozen(freeze, getWithToStringTag(namespaceToStringTag, 'n', snippets))};${n}` +
  10321. `}${n}${n}`);
  10322. }
  10323. };
  10324. const getDefaultLiveBinding = ({ _, getObject }) => `e${_}:${_}${getObject([['default', 'e']], { lineBreakIndent: null })}`;
  10325. const getDefaultStatic = ({ _, getPropertyAccess }) => `e${getPropertyAccess('default')}${_}:${_}e`;
  10326. const getIsCompatNamespace = ({ _ }) => `e${_}&&${_}typeof e${_}===${_}'object'${_}&&${_}'default'${_}in e`;
  10327. const createNamespaceObject = (t, index, snippets, liveBindings, freeze, namespaceToStringTag) => {
  10328. const { _, cnst, getObject, getPropertyAccess, n, s } = snippets;
  10329. const copyProperty = `{${n}` +
  10330. (liveBindings ? copyNonDefaultOwnPropertyLiveBinding : copyPropertyStatic)(t, index + t + t, snippets) +
  10331. `${index}${t}}`;
  10332. return (`${index}${cnst} n${_}=${_}Object.create(null${namespaceToStringTag
  10333. ? `,${_}{${_}[Symbol.toStringTag]:${_}${getToStringTagValue(getObject)}${_}}`
  10334. : ''});${n}` +
  10335. `${index}if${_}(e)${_}{${n}` +
  10336. `${index}${t}${loopOverKeys(copyProperty, !liveBindings, snippets)}${n}` +
  10337. `${index}}${n}` +
  10338. `${index}n${getPropertyAccess('default')}${_}=${_}e;${n}` +
  10339. `${index}return ${getFrozen(freeze, 'n')}${s}${n}`);
  10340. };
  10341. const loopOverKeys = (body, allowVariableLoopVariable, { _, cnst, getFunctionIntro, s }) => cnst !== 'var' || allowVariableLoopVariable
  10342. ? `for${_}(${cnst} k in e)${_}${body}`
  10343. : `Object.keys(e).forEach(${getFunctionIntro(['k'], {
  10344. isAsync: false,
  10345. name: null
  10346. })}${body})${s}`;
  10347. const loopOverNamespaces = (body, useForEach, t, { _, cnst, getDirectReturnFunction, getFunctionIntro, n }) => {
  10348. if (useForEach) {
  10349. const [left, right] = getDirectReturnFunction(['e'], {
  10350. functionReturn: false,
  10351. lineBreakIndent: { base: t, t },
  10352. name: null
  10353. });
  10354. return (`m.forEach(${left}` +
  10355. `e${_}&&${_}typeof e${_}!==${_}'string'${_}&&${_}!Array.isArray(e)${_}&&${_}Object.keys(e).forEach(${getFunctionIntro(['k'], {
  10356. isAsync: false,
  10357. name: null
  10358. })}${body})${right});`);
  10359. }
  10360. return (`for${_}(var i${_}=${_}0;${_}i${_}<${_}m.length;${_}i++)${_}{${n}` +
  10361. `${t}${t}${cnst} e${_}=${_}m[i];${n}` +
  10362. `${t}${t}if${_}(typeof e${_}!==${_}'string'${_}&&${_}!Array.isArray(e))${_}{${_}for${_}(${cnst} k in e)${_}${body}${_}}${n}${t}}`);
  10363. };
  10364. const copyNonDefaultOwnPropertyLiveBinding = (t, index, snippets) => {
  10365. const { _, n } = snippets;
  10366. return (`${index}if${_}(k${_}!==${_}'default')${_}{${n}` +
  10367. copyOwnPropertyLiveBinding(t, index + t, snippets) +
  10368. `${index}}${n}`);
  10369. };
  10370. const copyOwnPropertyLiveBinding = (t, index, { _, cnst, getDirectReturnFunction, n }) => {
  10371. const [left, right] = getDirectReturnFunction([], {
  10372. functionReturn: true,
  10373. lineBreakIndent: null,
  10374. name: null
  10375. });
  10376. return (`${index}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
  10377. `${index}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
  10378. `${index}${t}enumerable:${_}true,${n}` +
  10379. `${index}${t}get:${_}${left}e[k]${right}${n}` +
  10380. `${index}});${n}`);
  10381. };
  10382. const copyPropertyLiveBinding = (t, index, { _, cnst, getDirectReturnFunction, n }) => {
  10383. const [left, right] = getDirectReturnFunction([], {
  10384. functionReturn: true,
  10385. lineBreakIndent: null,
  10386. name: null
  10387. });
  10388. return (`${index}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
  10389. `${index}if${_}(d)${_}{${n}` +
  10390. `${index}${t}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
  10391. `${index}${t}${t}enumerable:${_}true,${n}` +
  10392. `${index}${t}${t}get:${_}${left}e[k]${right}${n}` +
  10393. `${index}${t}});${n}` +
  10394. `${index}}${n}`);
  10395. };
  10396. const copyPropertyStatic = (_t, index, { _, n }) => `${index}n[k]${_}=${_}e[k];${n}`;
  10397. const getFrozen = (freeze, fragment) => freeze ? `Object.freeze(${fragment})` : fragment;
  10398. const getWithToStringTag = (namespaceToStringTag, fragment, { _, getObject }) => namespaceToStringTag
  10399. ? `Object.defineProperty(${fragment},${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)})`
  10400. : fragment;
  10401. const HELPER_NAMES = Object.keys(HELPER_GENERATORS);
  10402. function getToStringTagValue(getObject) {
  10403. return getObject([['value', "'Module'"]], {
  10404. lineBreakIndent: null
  10405. });
  10406. }
  10407. function isReassignedExportsMember(variable, exportNamesByVariable) {
  10408. return (variable.renderBaseName !== null && exportNamesByVariable.has(variable) && variable.isReassigned);
  10409. }
  10410. class VariableDeclarator extends NodeBase {
  10411. declareDeclarator(kind) {
  10412. this.id.declare(kind, this.init || UNDEFINED_EXPRESSION);
  10413. }
  10414. deoptimizePath(path) {
  10415. this.id.deoptimizePath(path);
  10416. }
  10417. hasEffects(context) {
  10418. if (!this.deoptimized)
  10419. this.applyDeoptimizations();
  10420. const initEffect = this.init?.hasEffects(context);
  10421. this.id.markDeclarationReached();
  10422. return initEffect || this.id.hasEffects(context);
  10423. }
  10424. include(context, includeChildrenRecursively) {
  10425. const { deoptimized, id, init } = this;
  10426. if (!deoptimized)
  10427. this.applyDeoptimizations();
  10428. this.included = true;
  10429. init?.include(context, includeChildrenRecursively);
  10430. id.markDeclarationReached();
  10431. if (includeChildrenRecursively || id.shouldBeIncluded(context)) {
  10432. id.include(context, includeChildrenRecursively);
  10433. }
  10434. }
  10435. render(code, options) {
  10436. const { exportNamesByVariable, snippets: { _, getPropertyAccess } } = options;
  10437. const { end, id, init, start } = this;
  10438. const renderId = id.included;
  10439. if (renderId) {
  10440. id.render(code, options);
  10441. }
  10442. else {
  10443. const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', id.end);
  10444. code.remove(start, findNonWhiteSpace(code.original, operatorPos + 1));
  10445. }
  10446. if (init) {
  10447. if (id instanceof Identifier && init instanceof ClassExpression && !init.id) {
  10448. const renderedVariable = id.variable.getName(getPropertyAccess);
  10449. if (renderedVariable !== id.name) {
  10450. code.appendLeft(init.start + 5, ` ${id.name}`);
  10451. }
  10452. }
  10453. init.render(code, options, renderId ? BLANK : { renderedSurroundingElement: ExpressionStatement$1 });
  10454. }
  10455. else if (id instanceof Identifier &&
  10456. isReassignedExportsMember(id.variable, exportNamesByVariable)) {
  10457. code.appendLeft(end, `${_}=${_}void 0`);
  10458. }
  10459. }
  10460. applyDeoptimizations() {
  10461. this.deoptimized = true;
  10462. const { id, init } = this;
  10463. if (init && id instanceof Identifier && init instanceof ClassExpression && !init.id) {
  10464. const { name, variable } = id;
  10465. for (const accessedVariable of init.scope.accessedOutsideVariables.values()) {
  10466. if (accessedVariable !== variable) {
  10467. accessedVariable.forbidName(name);
  10468. }
  10469. }
  10470. }
  10471. }
  10472. }
  10473. // TODO once ImportExpression follows official ESTree specs with "null" as
  10474. // default, keys.ts should be updated
  10475. class ImportExpression extends NodeBase {
  10476. constructor() {
  10477. super(...arguments);
  10478. this.inlineNamespace = null;
  10479. this.assertions = null;
  10480. this.mechanism = null;
  10481. this.namespaceExportName = undefined;
  10482. this.resolution = null;
  10483. this.resolutionString = null;
  10484. }
  10485. // Do not bind assertions
  10486. bind() {
  10487. this.source.bind();
  10488. }
  10489. /**
  10490. * Get imported variables for deterministic usage, valid cases are:
  10491. *
  10492. * - `const { foo } = await import('bar')`.
  10493. * - `(await import('bar')).foo`
  10494. * - `import('bar').then(({ foo }) => {})`
  10495. *
  10496. * Returns empty array if it's side-effect only import.
  10497. * Returns undefined if it's not fully deterministic.
  10498. */
  10499. getDeterministicImportedNames() {
  10500. const parent1 = this.parent;
  10501. // Side-effect only: import('bar')
  10502. if (parent1 instanceof ExpressionStatement) {
  10503. return EMPTY_ARRAY;
  10504. }
  10505. if (parent1 instanceof AwaitExpression) {
  10506. const parent2 = parent1.parent;
  10507. // Side-effect only: await import('bar')
  10508. if (parent2 instanceof ExpressionStatement) {
  10509. return EMPTY_ARRAY;
  10510. }
  10511. // Case 1: const { foo } = await import('bar')
  10512. if (parent2 instanceof VariableDeclarator) {
  10513. const declaration = parent2.id;
  10514. return declaration instanceof ObjectPattern
  10515. ? getDeterministicObjectDestructure(declaration)
  10516. : undefined;
  10517. }
  10518. // Case 2: (await import('bar')).foo
  10519. if (parent2 instanceof MemberExpression) {
  10520. const id = parent2.property;
  10521. if (!parent2.computed && id instanceof Identifier) {
  10522. return [id.name];
  10523. }
  10524. }
  10525. return;
  10526. }
  10527. // Case 3: import('bar').then(({ foo }) => {})
  10528. if (parent1 instanceof MemberExpression) {
  10529. const callExpression = parent1.parent;
  10530. const property = parent1.property;
  10531. if (!(callExpression instanceof CallExpression) || !(property instanceof Identifier)) {
  10532. return;
  10533. }
  10534. const memberName = property.name;
  10535. // side-effect only, when only chaining .catch or .finally
  10536. if (callExpression.parent instanceof ExpressionStatement &&
  10537. ['catch', 'finally'].includes(memberName)) {
  10538. return EMPTY_ARRAY;
  10539. }
  10540. if (memberName !== 'then')
  10541. return;
  10542. // Side-effect only: import('bar').then()
  10543. if (callExpression.arguments.length === 0) {
  10544. return EMPTY_ARRAY;
  10545. }
  10546. const argument = callExpression.arguments[0];
  10547. if (callExpression.arguments.length !== 1 ||
  10548. !(argument instanceof ArrowFunctionExpression || argument instanceof FunctionExpression)) {
  10549. return;
  10550. }
  10551. // Side-effect only: import('bar').then(() => {})
  10552. if (argument.params.length === 0) {
  10553. return EMPTY_ARRAY;
  10554. }
  10555. const declaration = argument.params[0];
  10556. if (argument.params.length === 1 && declaration instanceof ObjectPattern) {
  10557. return getDeterministicObjectDestructure(declaration);
  10558. }
  10559. return;
  10560. }
  10561. }
  10562. hasEffects() {
  10563. return true;
  10564. }
  10565. include(context, includeChildrenRecursively) {
  10566. if (!this.included) {
  10567. this.included = true;
  10568. this.context.includeDynamicImport(this);
  10569. this.scope.addAccessedDynamicImport(this);
  10570. }
  10571. this.source.include(context, includeChildrenRecursively);
  10572. }
  10573. initialise() {
  10574. this.context.addDynamicImport(this);
  10575. }
  10576. parseNode(esTreeNode) {
  10577. // Keep the source AST to be used by renderDynamicImport
  10578. super.parseNode(esTreeNode, ['source']);
  10579. }
  10580. render(code, options) {
  10581. const { snippets: { _, getDirectReturnFunction, getObject, getPropertyAccess } } = options;
  10582. if (this.inlineNamespace) {
  10583. const [left, right] = getDirectReturnFunction([], {
  10584. functionReturn: true,
  10585. lineBreakIndent: null,
  10586. name: null
  10587. });
  10588. code.overwrite(this.start, this.end, `Promise.resolve().then(${left}${this.inlineNamespace.getName(getPropertyAccess)}${right})`);
  10589. return;
  10590. }
  10591. if (this.mechanism) {
  10592. code.overwrite(this.start, findFirstOccurrenceOutsideComment(code.original, '(', this.start + 6) + 1, this.mechanism.left);
  10593. code.overwrite(this.end - 1, this.end, this.mechanism.right);
  10594. }
  10595. if (this.resolutionString) {
  10596. code.overwrite(this.source.start, this.source.end, this.resolutionString);
  10597. if (this.namespaceExportName) {
  10598. const [left, right] = getDirectReturnFunction(['n'], {
  10599. functionReturn: true,
  10600. lineBreakIndent: null,
  10601. name: null
  10602. });
  10603. code.prependLeft(this.end, `.then(${left}n.${this.namespaceExportName}${right})`);
  10604. }
  10605. }
  10606. else {
  10607. this.source.render(code, options);
  10608. }
  10609. if (this.assertions !== true) {
  10610. if (this.arguments) {
  10611. code.overwrite(this.source.end, this.end - 1, '', { contentOnly: true });
  10612. }
  10613. if (this.assertions) {
  10614. code.appendLeft(this.end - 1, `,${_}${getObject([['assert', this.assertions]], {
  10615. lineBreakIndent: null
  10616. })}`);
  10617. }
  10618. }
  10619. }
  10620. setExternalResolution(exportMode, resolution, options, snippets, pluginDriver, accessedGlobalsByScope, resolutionString, namespaceExportName, assertions) {
  10621. const { format } = options;
  10622. this.inlineNamespace = null;
  10623. this.resolution = resolution;
  10624. this.resolutionString = resolutionString;
  10625. this.namespaceExportName = namespaceExportName;
  10626. this.assertions = assertions;
  10627. const accessedGlobals = [...(accessedImportGlobals[format] || [])];
  10628. let helper;
  10629. ({ helper, mechanism: this.mechanism } = this.getDynamicImportMechanismAndHelper(resolution, exportMode, options, snippets, pluginDriver));
  10630. if (helper) {
  10631. accessedGlobals.push(helper);
  10632. }
  10633. if (accessedGlobals.length > 0) {
  10634. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  10635. }
  10636. }
  10637. setInternalResolution(inlineNamespace) {
  10638. this.inlineNamespace = inlineNamespace;
  10639. }
  10640. applyDeoptimizations() { }
  10641. getDynamicImportMechanismAndHelper(resolution, exportMode, { compact, dynamicImportFunction, dynamicImportInCjs, format, generatedCode: { arrowFunctions }, interop }, { _, getDirectReturnFunction, getDirectReturnIifeLeft }, pluginDriver) {
  10642. const mechanism = pluginDriver.hookFirstSync('renderDynamicImport', [
  10643. {
  10644. customResolution: typeof this.resolution === 'string' ? this.resolution : null,
  10645. format,
  10646. moduleId: this.context.module.id,
  10647. targetModuleId: this.resolution && typeof this.resolution !== 'string' ? this.resolution.id : null
  10648. }
  10649. ]);
  10650. if (mechanism) {
  10651. return { helper: null, mechanism };
  10652. }
  10653. const hasDynamicTarget = !this.resolution || typeof this.resolution === 'string';
  10654. switch (format) {
  10655. case 'cjs': {
  10656. if (dynamicImportInCjs &&
  10657. (!resolution || typeof resolution === 'string' || resolution instanceof ExternalModule)) {
  10658. return { helper: null, mechanism: null };
  10659. }
  10660. const helper = getInteropHelper(resolution, exportMode, interop);
  10661. let left = `require(`;
  10662. let right = `)`;
  10663. if (helper) {
  10664. left = `/*#__PURE__*/${helper}(${left}`;
  10665. right += ')';
  10666. }
  10667. const [functionLeft, functionRight] = getDirectReturnFunction([], {
  10668. functionReturn: true,
  10669. lineBreakIndent: null,
  10670. name: null
  10671. });
  10672. left = `Promise.resolve().then(${functionLeft}${left}`;
  10673. right += `${functionRight})`;
  10674. if (!arrowFunctions && hasDynamicTarget) {
  10675. left = getDirectReturnIifeLeft(['t'], `${left}t${right}`, {
  10676. needsArrowReturnParens: false,
  10677. needsWrappedFunction: true
  10678. });
  10679. right = ')';
  10680. }
  10681. return {
  10682. helper,
  10683. mechanism: { left, right }
  10684. };
  10685. }
  10686. case 'amd': {
  10687. const resolve = compact ? 'c' : 'resolve';
  10688. const reject = compact ? 'e' : 'reject';
  10689. const helper = getInteropHelper(resolution, exportMode, interop);
  10690. const [resolveLeft, resolveRight] = getDirectReturnFunction(['m'], {
  10691. functionReturn: false,
  10692. lineBreakIndent: null,
  10693. name: null
  10694. });
  10695. const resolveNamespace = helper
  10696. ? `${resolveLeft}${resolve}(/*#__PURE__*/${helper}(m))${resolveRight}`
  10697. : resolve;
  10698. const [handlerLeft, handlerRight] = getDirectReturnFunction([resolve, reject], {
  10699. functionReturn: false,
  10700. lineBreakIndent: null,
  10701. name: null
  10702. });
  10703. let left = `new Promise(${handlerLeft}require([`;
  10704. let right = `],${_}${resolveNamespace},${_}${reject})${handlerRight})`;
  10705. if (!arrowFunctions && hasDynamicTarget) {
  10706. left = getDirectReturnIifeLeft(['t'], `${left}t${right}`, {
  10707. needsArrowReturnParens: false,
  10708. needsWrappedFunction: true
  10709. });
  10710. right = ')';
  10711. }
  10712. return {
  10713. helper,
  10714. mechanism: { left, right }
  10715. };
  10716. }
  10717. case 'system': {
  10718. return {
  10719. helper: null,
  10720. mechanism: {
  10721. left: 'module.import(',
  10722. right: ')'
  10723. }
  10724. };
  10725. }
  10726. case 'es': {
  10727. if (dynamicImportFunction) {
  10728. return {
  10729. helper: null,
  10730. mechanism: {
  10731. left: `${dynamicImportFunction}(`,
  10732. right: ')'
  10733. }
  10734. };
  10735. }
  10736. }
  10737. }
  10738. return { helper: null, mechanism: null };
  10739. }
  10740. }
  10741. function getInteropHelper(resolution, exportMode, interop) {
  10742. return exportMode === 'external'
  10743. ? namespaceInteropHelpersByInteropType[interop(resolution instanceof ExternalModule ? resolution.id : null)]
  10744. : exportMode === 'default'
  10745. ? INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE
  10746. : null;
  10747. }
  10748. const accessedImportGlobals = {
  10749. amd: ['require'],
  10750. cjs: ['require'],
  10751. system: ['module']
  10752. };
  10753. function getDeterministicObjectDestructure(objectPattern) {
  10754. const variables = [];
  10755. for (const property of objectPattern.properties) {
  10756. if (property.type === 'RestElement' || property.computed || property.key.type !== 'Identifier')
  10757. return;
  10758. variables.push(property.key.name);
  10759. }
  10760. return variables;
  10761. }
  10762. class ImportNamespaceSpecifier extends NodeBase {
  10763. applyDeoptimizations() { }
  10764. }
  10765. class ImportSpecifier extends NodeBase {
  10766. applyDeoptimizations() { }
  10767. }
  10768. class LabeledStatement extends NodeBase {
  10769. hasEffects(context) {
  10770. const brokenFlow = context.brokenFlow;
  10771. context.ignore.labels.add(this.label.name);
  10772. if (this.body.hasEffects(context))
  10773. return true;
  10774. context.ignore.labels.delete(this.label.name);
  10775. if (context.includedLabels.has(this.label.name)) {
  10776. context.includedLabels.delete(this.label.name);
  10777. context.brokenFlow = brokenFlow;
  10778. }
  10779. return false;
  10780. }
  10781. include(context, includeChildrenRecursively) {
  10782. this.included = true;
  10783. const brokenFlow = context.brokenFlow;
  10784. this.body.include(context, includeChildrenRecursively);
  10785. if (includeChildrenRecursively || context.includedLabels.has(this.label.name)) {
  10786. this.label.include();
  10787. context.includedLabels.delete(this.label.name);
  10788. context.brokenFlow = brokenFlow;
  10789. }
  10790. }
  10791. render(code, options) {
  10792. if (this.label.included) {
  10793. this.label.render(code, options);
  10794. }
  10795. else {
  10796. code.remove(this.start, findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, ':', this.label.end) + 1));
  10797. }
  10798. this.body.render(code, options);
  10799. }
  10800. }
  10801. class LogicalExpression extends NodeBase {
  10802. constructor() {
  10803. super(...arguments);
  10804. // We collect deoptimization information if usedBranch !== null
  10805. this.expressionsToBeDeoptimized = [];
  10806. this.isBranchResolutionAnalysed = false;
  10807. this.usedBranch = null;
  10808. }
  10809. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  10810. this.left.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  10811. this.right.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  10812. }
  10813. deoptimizeCache() {
  10814. if (this.usedBranch) {
  10815. const unusedBranch = this.usedBranch === this.left ? this.right : this.left;
  10816. this.usedBranch = null;
  10817. unusedBranch.deoptimizePath(UNKNOWN_PATH);
  10818. const { context, expressionsToBeDeoptimized } = this;
  10819. this.expressionsToBeDeoptimized = EMPTY_ARRAY;
  10820. for (const expression of expressionsToBeDeoptimized) {
  10821. expression.deoptimizeCache();
  10822. }
  10823. // Request another pass because we need to ensure "include" runs again if
  10824. // it is rendered
  10825. context.requestTreeshakingPass();
  10826. }
  10827. }
  10828. deoptimizePath(path) {
  10829. const usedBranch = this.getUsedBranch();
  10830. if (usedBranch) {
  10831. usedBranch.deoptimizePath(path);
  10832. }
  10833. else {
  10834. this.left.deoptimizePath(path);
  10835. this.right.deoptimizePath(path);
  10836. }
  10837. }
  10838. getLiteralValueAtPath(path, recursionTracker, origin) {
  10839. const usedBranch = this.getUsedBranch();
  10840. if (!usedBranch)
  10841. return UnknownValue;
  10842. this.expressionsToBeDeoptimized.push(origin);
  10843. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  10844. }
  10845. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  10846. const usedBranch = this.getUsedBranch();
  10847. if (!usedBranch)
  10848. return [
  10849. new MultiExpression([
  10850. this.left.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0],
  10851. this.right.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0]
  10852. ]),
  10853. false
  10854. ];
  10855. this.expressionsToBeDeoptimized.push(origin);
  10856. return usedBranch.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  10857. }
  10858. hasEffects(context) {
  10859. if (this.left.hasEffects(context)) {
  10860. return true;
  10861. }
  10862. if (this.getUsedBranch() !== this.left) {
  10863. return this.right.hasEffects(context);
  10864. }
  10865. return false;
  10866. }
  10867. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10868. const usedBranch = this.getUsedBranch();
  10869. if (!usedBranch) {
  10870. return (this.left.hasEffectsOnInteractionAtPath(path, interaction, context) ||
  10871. this.right.hasEffectsOnInteractionAtPath(path, interaction, context));
  10872. }
  10873. return usedBranch.hasEffectsOnInteractionAtPath(path, interaction, context);
  10874. }
  10875. include(context, includeChildrenRecursively) {
  10876. this.included = true;
  10877. const usedBranch = this.getUsedBranch();
  10878. if (includeChildrenRecursively ||
  10879. (usedBranch === this.right && this.left.shouldBeIncluded(context)) ||
  10880. !usedBranch) {
  10881. this.left.include(context, includeChildrenRecursively);
  10882. this.right.include(context, includeChildrenRecursively);
  10883. }
  10884. else {
  10885. usedBranch.include(context, includeChildrenRecursively);
  10886. }
  10887. }
  10888. render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  10889. if (!this.left.included || !this.right.included) {
  10890. const operatorPos = findFirstOccurrenceOutsideComment(code.original, this.operator, this.left.end);
  10891. if (this.right.included) {
  10892. const removePos = findNonWhiteSpace(code.original, operatorPos + 2);
  10893. code.remove(this.start, removePos);
  10894. if (preventASI) {
  10895. removeLineBreaks(code, removePos, this.right.start);
  10896. }
  10897. }
  10898. else {
  10899. code.remove(operatorPos, this.end);
  10900. }
  10901. removeAnnotations(this, code);
  10902. this.getUsedBranch().render(code, options, {
  10903. isCalleeOfRenderedParent,
  10904. preventASI,
  10905. renderedParentType: renderedParentType || this.parent.type,
  10906. renderedSurroundingElement: renderedSurroundingElement || this.parent.type
  10907. });
  10908. }
  10909. else {
  10910. this.left.render(code, options, {
  10911. preventASI,
  10912. renderedSurroundingElement
  10913. });
  10914. this.right.render(code, options);
  10915. }
  10916. }
  10917. getUsedBranch() {
  10918. if (!this.isBranchResolutionAnalysed) {
  10919. this.isBranchResolutionAnalysed = true;
  10920. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  10921. if (typeof leftValue === 'symbol') {
  10922. return null;
  10923. }
  10924. else {
  10925. this.usedBranch =
  10926. (this.operator === '||' && leftValue) ||
  10927. (this.operator === '&&' && !leftValue) ||
  10928. (this.operator === '??' && leftValue != null)
  10929. ? this.left
  10930. : this.right;
  10931. }
  10932. }
  10933. return this.usedBranch;
  10934. }
  10935. }
  10936. const FILE_PREFIX = 'ROLLUP_FILE_URL_';
  10937. const IMPORT = 'import';
  10938. class MetaProperty extends NodeBase {
  10939. constructor() {
  10940. super(...arguments);
  10941. this.metaProperty = null;
  10942. this.preliminaryChunkId = null;
  10943. this.referenceId = null;
  10944. }
  10945. getReferencedFileName(outputPluginDriver) {
  10946. const { meta: { name }, metaProperty } = this;
  10947. if (name === IMPORT && metaProperty?.startsWith(FILE_PREFIX)) {
  10948. return outputPluginDriver.getFileName(metaProperty.slice(FILE_PREFIX.length));
  10949. }
  10950. return null;
  10951. }
  10952. hasEffects() {
  10953. return false;
  10954. }
  10955. hasEffectsOnInteractionAtPath(path, { type }) {
  10956. return path.length > 1 || type !== INTERACTION_ACCESSED;
  10957. }
  10958. include() {
  10959. if (!this.included) {
  10960. this.included = true;
  10961. if (this.meta.name === IMPORT) {
  10962. this.context.addImportMeta(this);
  10963. const parent = this.parent;
  10964. const metaProperty = (this.metaProperty =
  10965. parent instanceof MemberExpression && typeof parent.propertyKey === 'string'
  10966. ? parent.propertyKey
  10967. : null);
  10968. if (metaProperty?.startsWith(FILE_PREFIX)) {
  10969. this.referenceId = metaProperty.slice(FILE_PREFIX.length);
  10970. }
  10971. }
  10972. }
  10973. }
  10974. render(code, renderOptions) {
  10975. const { format, pluginDriver, snippets } = renderOptions;
  10976. const { context: { module }, meta: { name }, metaProperty, parent, preliminaryChunkId, referenceId, start, end } = this;
  10977. const { id: moduleId } = module;
  10978. if (name !== IMPORT)
  10979. return;
  10980. const chunkId = preliminaryChunkId;
  10981. if (referenceId) {
  10982. const fileName = pluginDriver.getFileName(referenceId);
  10983. const relativePath = normalize(relative$1(dirname(chunkId), fileName));
  10984. const replacement = pluginDriver.hookFirstSync('resolveFileUrl', [
  10985. { chunkId, fileName, format, moduleId, referenceId, relativePath }
  10986. ]) || relativeUrlMechanisms[format](relativePath);
  10987. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  10988. return;
  10989. }
  10990. let replacement = pluginDriver.hookFirstSync('resolveImportMeta', [
  10991. metaProperty,
  10992. { chunkId, format, moduleId }
  10993. ]);
  10994. if (!replacement) {
  10995. replacement = importMetaMechanisms[format]?.(metaProperty, { chunkId, snippets });
  10996. renderOptions.accessedDocumentCurrentScript || (renderOptions.accessedDocumentCurrentScript = formatsMaybeAccessDocumentCurrentScript.includes(format) && replacement !== 'undefined');
  10997. }
  10998. if (typeof replacement === 'string') {
  10999. if (parent instanceof MemberExpression) {
  11000. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  11001. }
  11002. else {
  11003. code.overwrite(start, end, replacement, { contentOnly: true });
  11004. }
  11005. }
  11006. }
  11007. setResolution(format, accessedGlobalsByScope, preliminaryChunkId) {
  11008. this.preliminaryChunkId = preliminaryChunkId;
  11009. const accessedGlobals = (this.metaProperty?.startsWith(FILE_PREFIX) ? accessedFileUrlGlobals : accessedMetaUrlGlobals)[format];
  11010. if (accessedGlobals.length > 0) {
  11011. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  11012. }
  11013. }
  11014. }
  11015. const formatsMaybeAccessDocumentCurrentScript = ['cjs', 'iife', 'umd'];
  11016. const accessedMetaUrlGlobals = {
  11017. amd: ['document', 'module', 'URL'],
  11018. cjs: ['document', 'require', 'URL', DOCUMENT_CURRENT_SCRIPT],
  11019. es: [],
  11020. iife: ['document', 'URL', DOCUMENT_CURRENT_SCRIPT],
  11021. system: ['module'],
  11022. umd: ['document', 'require', 'URL', DOCUMENT_CURRENT_SCRIPT]
  11023. };
  11024. const accessedFileUrlGlobals = {
  11025. amd: ['document', 'require', 'URL'],
  11026. cjs: ['document', 'require', 'URL'],
  11027. es: [],
  11028. iife: ['document', 'URL'],
  11029. system: ['module', 'URL'],
  11030. umd: ['document', 'require', 'URL']
  11031. };
  11032. const getResolveUrl = (path, URL = 'URL') => `new ${URL}(${path}).href`;
  11033. const getRelativeUrlFromDocument = (relativePath, umd = false) => getResolveUrl(`'${escapeId(relativePath)}', ${umd ? `typeof document === 'undefined' ? location.href : ` : ''}document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT' && document.currentScript.src || document.baseURI`);
  11034. const getGenericImportMetaMechanism = (getUrl) => (property, { chunkId }) => {
  11035. const urlMechanism = getUrl(chunkId);
  11036. return property === null
  11037. ? `({ url: ${urlMechanism} })`
  11038. : property === 'url'
  11039. ? urlMechanism
  11040. : 'undefined';
  11041. };
  11042. const getFileUrlFromFullPath = (path) => `require('u' + 'rl').pathToFileURL(${path}).href`;
  11043. const getFileUrlFromRelativePath = (path) => getFileUrlFromFullPath(`__dirname + '/${path}'`);
  11044. const getUrlFromDocument = (chunkId, umd = false) => `${umd ? `typeof document === 'undefined' ? location.href : ` : ''}(${DOCUMENT_CURRENT_SCRIPT} && ${DOCUMENT_CURRENT_SCRIPT}.tagName.toUpperCase() === 'SCRIPT' && ${DOCUMENT_CURRENT_SCRIPT}.src || new URL('${escapeId(chunkId)}', document.baseURI).href)`;
  11045. const relativeUrlMechanisms = {
  11046. amd: relativePath => {
  11047. if (relativePath[0] !== '.')
  11048. relativePath = './' + relativePath;
  11049. return getResolveUrl(`require.toUrl('${relativePath}'), document.baseURI`);
  11050. },
  11051. cjs: relativePath => `(typeof document === 'undefined' ? ${getFileUrlFromRelativePath(relativePath)} : ${getRelativeUrlFromDocument(relativePath)})`,
  11052. es: relativePath => getResolveUrl(`'${relativePath}', import.meta.url`),
  11053. iife: relativePath => getRelativeUrlFromDocument(relativePath),
  11054. system: relativePath => getResolveUrl(`'${relativePath}', module.meta.url`),
  11055. umd: relativePath => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getFileUrlFromRelativePath(relativePath)} : ${getRelativeUrlFromDocument(relativePath, true)})`
  11056. };
  11057. const importMetaMechanisms = {
  11058. amd: getGenericImportMetaMechanism(() => getResolveUrl(`module.uri, document.baseURI`)),
  11059. cjs: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' ? ${getFileUrlFromFullPath('__filename')} : ${getUrlFromDocument(chunkId)})`),
  11060. iife: getGenericImportMetaMechanism(chunkId => getUrlFromDocument(chunkId)),
  11061. system: (property, { snippets: { getPropertyAccess } }) => property === null ? `module.meta` : `module.meta${getPropertyAccess(property)}`,
  11062. umd: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getFileUrlFromFullPath('__filename')} : ${getUrlFromDocument(chunkId, true)})`)
  11063. };
  11064. class NewExpression extends NodeBase {
  11065. hasEffects(context) {
  11066. try {
  11067. for (const argument of this.arguments) {
  11068. if (argument.hasEffects(context))
  11069. return true;
  11070. }
  11071. if (this.annotationPure) {
  11072. return false;
  11073. }
  11074. return (this.callee.hasEffects(context) ||
  11075. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  11076. }
  11077. finally {
  11078. if (!this.deoptimized)
  11079. this.applyDeoptimizations();
  11080. }
  11081. }
  11082. hasEffectsOnInteractionAtPath(path, { type }) {
  11083. return path.length > 0 || type !== INTERACTION_ACCESSED;
  11084. }
  11085. include(context, includeChildrenRecursively) {
  11086. if (!this.deoptimized)
  11087. this.applyDeoptimizations();
  11088. if (includeChildrenRecursively) {
  11089. super.include(context, includeChildrenRecursively);
  11090. }
  11091. else {
  11092. this.included = true;
  11093. this.callee.include(context, false);
  11094. }
  11095. this.callee.includeCallArguments(context, this.arguments);
  11096. }
  11097. initialise() {
  11098. this.interaction = {
  11099. args: [null, ...this.arguments],
  11100. type: INTERACTION_CALLED,
  11101. withNew: true
  11102. };
  11103. }
  11104. render(code, options) {
  11105. this.callee.render(code, options);
  11106. renderCallArguments(code, options, this);
  11107. }
  11108. applyDeoptimizations() {
  11109. this.deoptimized = true;
  11110. this.callee.deoptimizeArgumentsOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  11111. this.context.requestTreeshakingPass();
  11112. }
  11113. }
  11114. class ObjectExpression extends NodeBase {
  11115. constructor() {
  11116. super(...arguments);
  11117. this.objectEntity = null;
  11118. }
  11119. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  11120. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  11121. }
  11122. deoptimizeCache() {
  11123. this.getObjectEntity().deoptimizeAllProperties();
  11124. }
  11125. deoptimizePath(path) {
  11126. this.getObjectEntity().deoptimizePath(path);
  11127. }
  11128. getLiteralValueAtPath(path, recursionTracker, origin) {
  11129. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  11130. }
  11131. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  11132. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  11133. }
  11134. hasEffectsOnInteractionAtPath(path, interaction, context) {
  11135. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  11136. }
  11137. render(code, options, { renderedSurroundingElement } = BLANK) {
  11138. super.render(code, options);
  11139. if (renderedSurroundingElement === ExpressionStatement$1 ||
  11140. renderedSurroundingElement === ArrowFunctionExpression$1) {
  11141. code.appendRight(this.start, '(');
  11142. code.prependLeft(this.end, ')');
  11143. }
  11144. }
  11145. applyDeoptimizations() { }
  11146. getObjectEntity() {
  11147. if (this.objectEntity !== null) {
  11148. return this.objectEntity;
  11149. }
  11150. let prototype = OBJECT_PROTOTYPE;
  11151. const properties = [];
  11152. for (const property of this.properties) {
  11153. if (property instanceof SpreadElement) {
  11154. properties.push({ key: UnknownKey, kind: 'init', property });
  11155. continue;
  11156. }
  11157. let key;
  11158. if (property.computed) {
  11159. const keyValue = property.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  11160. if (typeof keyValue === 'symbol') {
  11161. properties.push({ key: UnknownKey, kind: property.kind, property });
  11162. continue;
  11163. }
  11164. else {
  11165. key = String(keyValue);
  11166. }
  11167. }
  11168. else {
  11169. key =
  11170. property.key instanceof Identifier
  11171. ? property.key.name
  11172. : String(property.key.value);
  11173. if (key === '__proto__' && property.kind === 'init') {
  11174. prototype =
  11175. property.value instanceof Literal && property.value.value === null
  11176. ? null
  11177. : property.value;
  11178. continue;
  11179. }
  11180. }
  11181. properties.push({ key, kind: property.kind, property });
  11182. }
  11183. return (this.objectEntity = new ObjectEntity(properties, prototype));
  11184. }
  11185. }
  11186. class PrivateIdentifier extends NodeBase {
  11187. }
  11188. class Program extends NodeBase {
  11189. constructor() {
  11190. super(...arguments);
  11191. this.hasCachedEffect = null;
  11192. this.hasLoggedEffect = false;
  11193. }
  11194. hasCachedEffects() {
  11195. if (!this.included) {
  11196. return false;
  11197. }
  11198. return this.hasCachedEffect === null
  11199. ? (this.hasCachedEffect = this.hasEffects(createHasEffectsContext()))
  11200. : this.hasCachedEffect;
  11201. }
  11202. hasEffects(context) {
  11203. for (const node of this.body) {
  11204. if (node.hasEffects(context)) {
  11205. if (this.context.options.experimentalLogSideEffects && !this.hasLoggedEffect) {
  11206. this.hasLoggedEffect = true;
  11207. const { code, log, module } = this.context;
  11208. log(LOGLEVEL_INFO, logFirstSideEffect(code, module.id, locate(code, node.start, { offsetLine: 1 })), node.start);
  11209. }
  11210. return (this.hasCachedEffect = true);
  11211. }
  11212. }
  11213. return false;
  11214. }
  11215. include(context, includeChildrenRecursively) {
  11216. this.included = true;
  11217. for (const node of this.body) {
  11218. if (includeChildrenRecursively || node.shouldBeIncluded(context)) {
  11219. node.include(context, includeChildrenRecursively);
  11220. }
  11221. }
  11222. }
  11223. render(code, options) {
  11224. let start = this.start;
  11225. if (code.original.startsWith('#!')) {
  11226. start = Math.min(code.original.indexOf('\n') + 1, this.end);
  11227. code.remove(0, start);
  11228. }
  11229. if (this.body.length > 0) {
  11230. // Keep all consecutive lines that start with a comment
  11231. while (code.original[start] === '/' && /[*/]/.test(code.original[start + 1])) {
  11232. const firstLineBreak = findFirstLineBreakOutsideComment(code.original.slice(start, this.body[0].start));
  11233. if (firstLineBreak[0] === -1) {
  11234. break;
  11235. }
  11236. start += firstLineBreak[1];
  11237. }
  11238. renderStatementList(this.body, code, start, this.end, options);
  11239. }
  11240. else {
  11241. super.render(code, options);
  11242. }
  11243. }
  11244. applyDeoptimizations() { }
  11245. }
  11246. class Property extends MethodBase {
  11247. constructor() {
  11248. super(...arguments);
  11249. this.declarationInit = null;
  11250. }
  11251. declare(kind, init) {
  11252. this.declarationInit = init;
  11253. return this.value.declare(kind, UNKNOWN_EXPRESSION);
  11254. }
  11255. hasEffects(context) {
  11256. if (!this.deoptimized)
  11257. this.applyDeoptimizations();
  11258. const propertyReadSideEffects = this.context.options.treeshake
  11259. .propertyReadSideEffects;
  11260. return ((this.parent.type === 'ObjectPattern' && propertyReadSideEffects === 'always') ||
  11261. this.key.hasEffects(context) ||
  11262. this.value.hasEffects(context));
  11263. }
  11264. markDeclarationReached() {
  11265. this.value.markDeclarationReached();
  11266. }
  11267. render(code, options) {
  11268. if (!this.shorthand) {
  11269. this.key.render(code, options);
  11270. }
  11271. this.value.render(code, options, { isShorthandProperty: this.shorthand });
  11272. }
  11273. applyDeoptimizations() {
  11274. this.deoptimized = true;
  11275. if (this.declarationInit !== null) {
  11276. this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
  11277. this.context.requestTreeshakingPass();
  11278. }
  11279. }
  11280. }
  11281. class PropertyDefinition extends NodeBase {
  11282. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  11283. this.value?.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  11284. }
  11285. deoptimizePath(path) {
  11286. this.value?.deoptimizePath(path);
  11287. }
  11288. getLiteralValueAtPath(path, recursionTracker, origin) {
  11289. return this.value
  11290. ? this.value.getLiteralValueAtPath(path, recursionTracker, origin)
  11291. : UnknownValue;
  11292. }
  11293. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  11294. return this.value
  11295. ? this.value.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)
  11296. : UNKNOWN_RETURN_EXPRESSION;
  11297. }
  11298. hasEffects(context) {
  11299. return this.key.hasEffects(context) || (this.static && !!this.value?.hasEffects(context));
  11300. }
  11301. hasEffectsOnInteractionAtPath(path, interaction, context) {
  11302. return !this.value || this.value.hasEffectsOnInteractionAtPath(path, interaction, context);
  11303. }
  11304. applyDeoptimizations() { }
  11305. }
  11306. class ReturnStatement extends NodeBase {
  11307. hasEffects(context) {
  11308. if (!context.ignore.returnYield || this.argument?.hasEffects(context))
  11309. return true;
  11310. context.brokenFlow = true;
  11311. return false;
  11312. }
  11313. include(context, includeChildrenRecursively) {
  11314. this.included = true;
  11315. this.argument?.include(context, includeChildrenRecursively);
  11316. context.brokenFlow = true;
  11317. }
  11318. initialise() {
  11319. this.scope.addReturnExpression(this.argument || UNKNOWN_EXPRESSION);
  11320. }
  11321. render(code, options) {
  11322. if (this.argument) {
  11323. this.argument.render(code, options, { preventASI: true });
  11324. if (this.argument.start === this.start + 6 /* 'return'.length */) {
  11325. code.prependLeft(this.start + 6, ' ');
  11326. }
  11327. }
  11328. }
  11329. }
  11330. class SequenceExpression extends NodeBase {
  11331. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  11332. this.expressions[this.expressions.length - 1].deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  11333. }
  11334. deoptimizePath(path) {
  11335. this.expressions[this.expressions.length - 1].deoptimizePath(path);
  11336. }
  11337. getLiteralValueAtPath(path, recursionTracker, origin) {
  11338. return this.expressions[this.expressions.length - 1].getLiteralValueAtPath(path, recursionTracker, origin);
  11339. }
  11340. hasEffects(context) {
  11341. for (const expression of this.expressions) {
  11342. if (expression.hasEffects(context))
  11343. return true;
  11344. }
  11345. return false;
  11346. }
  11347. hasEffectsOnInteractionAtPath(path, interaction, context) {
  11348. return this.expressions[this.expressions.length - 1].hasEffectsOnInteractionAtPath(path, interaction, context);
  11349. }
  11350. include(context, includeChildrenRecursively) {
  11351. this.included = true;
  11352. const lastExpression = this.expressions[this.expressions.length - 1];
  11353. for (const expression of this.expressions) {
  11354. if (includeChildrenRecursively ||
  11355. (expression === lastExpression && !(this.parent instanceof ExpressionStatement)) ||
  11356. expression.shouldBeIncluded(context))
  11357. expression.include(context, includeChildrenRecursively);
  11358. }
  11359. }
  11360. render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
  11361. let includedNodes = 0;
  11362. let lastSeparatorPos = null;
  11363. const lastNode = this.expressions[this.expressions.length - 1];
  11364. for (const { node, separator, start, end } of getCommaSeparatedNodesWithBoundaries(this.expressions, code, this.start, this.end)) {
  11365. if (!node.included) {
  11366. treeshakeNode(node, code, start, end);
  11367. continue;
  11368. }
  11369. includedNodes++;
  11370. lastSeparatorPos = separator;
  11371. if (includedNodes === 1 && preventASI) {
  11372. removeLineBreaks(code, start, node.start);
  11373. }
  11374. if (includedNodes === 1) {
  11375. const parentType = renderedParentType || this.parent.type;
  11376. node.render(code, options, {
  11377. isCalleeOfRenderedParent: isCalleeOfRenderedParent && node === lastNode,
  11378. renderedParentType: parentType,
  11379. renderedSurroundingElement: parentType
  11380. });
  11381. }
  11382. else {
  11383. node.render(code, options);
  11384. }
  11385. }
  11386. if (lastSeparatorPos) {
  11387. code.remove(lastSeparatorPos, this.end);
  11388. }
  11389. }
  11390. }
  11391. class StaticBlock extends NodeBase {
  11392. createScope(parentScope) {
  11393. this.scope = new BlockScope(parentScope);
  11394. }
  11395. hasEffects(context) {
  11396. for (const node of this.body) {
  11397. if (node.hasEffects(context))
  11398. return true;
  11399. }
  11400. return false;
  11401. }
  11402. include(context, includeChildrenRecursively) {
  11403. this.included = true;
  11404. for (const node of this.body) {
  11405. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  11406. node.include(context, includeChildrenRecursively);
  11407. }
  11408. }
  11409. render(code, options) {
  11410. if (this.body.length > 0) {
  11411. const bodyStartPos = findFirstOccurrenceOutsideComment(code.original.slice(this.start, this.end), '{') + 1;
  11412. renderStatementList(this.body, code, this.start + bodyStartPos, this.end - 1, options);
  11413. }
  11414. else {
  11415. super.render(code, options);
  11416. }
  11417. }
  11418. }
  11419. class Super extends NodeBase {
  11420. bind() {
  11421. this.variable = this.scope.findVariable('this');
  11422. }
  11423. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  11424. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  11425. }
  11426. deoptimizePath(path) {
  11427. this.variable.deoptimizePath(path);
  11428. }
  11429. include() {
  11430. if (!this.included) {
  11431. this.included = true;
  11432. this.context.includeVariableInModule(this.variable);
  11433. }
  11434. }
  11435. }
  11436. class SwitchCase extends NodeBase {
  11437. hasEffects(context) {
  11438. if (this.test?.hasEffects(context))
  11439. return true;
  11440. for (const node of this.consequent) {
  11441. if (context.brokenFlow)
  11442. break;
  11443. if (node.hasEffects(context))
  11444. return true;
  11445. }
  11446. return false;
  11447. }
  11448. include(context, includeChildrenRecursively) {
  11449. this.included = true;
  11450. this.test?.include(context, includeChildrenRecursively);
  11451. for (const node of this.consequent) {
  11452. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  11453. node.include(context, includeChildrenRecursively);
  11454. }
  11455. }
  11456. render(code, options, nodeRenderOptions) {
  11457. if (this.consequent.length > 0) {
  11458. this.test && this.test.render(code, options);
  11459. const testEnd = this.test
  11460. ? this.test.end
  11461. : findFirstOccurrenceOutsideComment(code.original, 'default', this.start) + 7;
  11462. const consequentStart = findFirstOccurrenceOutsideComment(code.original, ':', testEnd) + 1;
  11463. renderStatementList(this.consequent, code, consequentStart, nodeRenderOptions.end, options);
  11464. }
  11465. else {
  11466. super.render(code, options);
  11467. }
  11468. }
  11469. }
  11470. SwitchCase.prototype.needsBoundaries = true;
  11471. class SwitchStatement extends NodeBase {
  11472. createScope(parentScope) {
  11473. this.parentScope = parentScope;
  11474. this.scope = new BlockScope(parentScope);
  11475. }
  11476. hasEffects(context) {
  11477. if (this.discriminant.hasEffects(context))
  11478. return true;
  11479. const { brokenFlow, hasBreak, ignore } = context;
  11480. const { breaks } = ignore;
  11481. ignore.breaks = true;
  11482. context.hasBreak = false;
  11483. let onlyHasBrokenFlow = true;
  11484. for (const switchCase of this.cases) {
  11485. if (switchCase.hasEffects(context))
  11486. return true;
  11487. // eslint-disable-next-line unicorn/consistent-destructuring
  11488. onlyHasBrokenFlow && (onlyHasBrokenFlow = context.brokenFlow && !context.hasBreak);
  11489. context.hasBreak = false;
  11490. context.brokenFlow = brokenFlow;
  11491. }
  11492. if (this.defaultCase !== null) {
  11493. context.brokenFlow = onlyHasBrokenFlow;
  11494. }
  11495. ignore.breaks = breaks;
  11496. context.hasBreak = hasBreak;
  11497. return false;
  11498. }
  11499. include(context, includeChildrenRecursively) {
  11500. this.included = true;
  11501. this.discriminant.include(context, includeChildrenRecursively);
  11502. const { brokenFlow, hasBreak } = context;
  11503. context.hasBreak = false;
  11504. let onlyHasBrokenFlow = true;
  11505. let isCaseIncluded = includeChildrenRecursively ||
  11506. (this.defaultCase !== null && this.defaultCase < this.cases.length - 1);
  11507. for (let caseIndex = this.cases.length - 1; caseIndex >= 0; caseIndex--) {
  11508. const switchCase = this.cases[caseIndex];
  11509. if (switchCase.included) {
  11510. isCaseIncluded = true;
  11511. }
  11512. if (!isCaseIncluded) {
  11513. const hasEffectsContext = createHasEffectsContext();
  11514. hasEffectsContext.ignore.breaks = true;
  11515. isCaseIncluded = switchCase.hasEffects(hasEffectsContext);
  11516. }
  11517. if (isCaseIncluded) {
  11518. switchCase.include(context, includeChildrenRecursively);
  11519. // eslint-disable-next-line unicorn/consistent-destructuring
  11520. onlyHasBrokenFlow && (onlyHasBrokenFlow = context.brokenFlow && !context.hasBreak);
  11521. context.hasBreak = false;
  11522. context.brokenFlow = brokenFlow;
  11523. }
  11524. else {
  11525. onlyHasBrokenFlow = brokenFlow;
  11526. }
  11527. }
  11528. if (isCaseIncluded && this.defaultCase !== null) {
  11529. context.brokenFlow = onlyHasBrokenFlow;
  11530. }
  11531. context.hasBreak = hasBreak;
  11532. }
  11533. initialise() {
  11534. for (let caseIndex = 0; caseIndex < this.cases.length; caseIndex++) {
  11535. if (this.cases[caseIndex].test === null) {
  11536. this.defaultCase = caseIndex;
  11537. return;
  11538. }
  11539. }
  11540. this.defaultCase = null;
  11541. }
  11542. parseNode(esTreeNode) {
  11543. this.discriminant = new (this.context.getNodeConstructor(esTreeNode.discriminant.type))(esTreeNode.discriminant, this, this.parentScope);
  11544. super.parseNode(esTreeNode);
  11545. }
  11546. render(code, options) {
  11547. this.discriminant.render(code, options);
  11548. if (this.cases.length > 0) {
  11549. renderStatementList(this.cases, code, this.cases[0].start, this.end - 1, options);
  11550. }
  11551. }
  11552. }
  11553. class TaggedTemplateExpression extends CallExpressionBase {
  11554. bind() {
  11555. super.bind();
  11556. if (this.tag.type === Identifier$1) {
  11557. const name = this.tag.name;
  11558. const variable = this.scope.findVariable(name);
  11559. if (variable.isNamespace) {
  11560. this.context.log(LOGLEVEL_WARN, logCannotCallNamespace(name), this.start);
  11561. }
  11562. }
  11563. }
  11564. hasEffects(context) {
  11565. try {
  11566. for (const argument of this.quasi.expressions) {
  11567. if (argument.hasEffects(context))
  11568. return true;
  11569. }
  11570. return (this.tag.hasEffects(context) ||
  11571. this.tag.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  11572. }
  11573. finally {
  11574. if (!this.deoptimized)
  11575. this.applyDeoptimizations();
  11576. }
  11577. }
  11578. include(context, includeChildrenRecursively) {
  11579. if (!this.deoptimized)
  11580. this.applyDeoptimizations();
  11581. if (includeChildrenRecursively) {
  11582. super.include(context, includeChildrenRecursively);
  11583. }
  11584. else {
  11585. this.included = true;
  11586. this.tag.include(context, includeChildrenRecursively);
  11587. this.quasi.include(context, includeChildrenRecursively);
  11588. }
  11589. this.tag.includeCallArguments(context, this.args);
  11590. const [returnExpression] = this.getReturnExpression();
  11591. if (!returnExpression.included) {
  11592. returnExpression.include(context, false);
  11593. }
  11594. }
  11595. initialise() {
  11596. this.args = [UNKNOWN_EXPRESSION, ...this.quasi.expressions];
  11597. this.interaction = {
  11598. args: [
  11599. this.tag instanceof MemberExpression && !this.tag.variable ? this.tag.object : null,
  11600. ...this.args
  11601. ],
  11602. type: INTERACTION_CALLED,
  11603. withNew: false
  11604. };
  11605. }
  11606. render(code, options) {
  11607. this.tag.render(code, options, { isCalleeOfRenderedParent: true });
  11608. this.quasi.render(code, options);
  11609. }
  11610. applyDeoptimizations() {
  11611. this.deoptimized = true;
  11612. this.tag.deoptimizeArgumentsOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  11613. this.context.requestTreeshakingPass();
  11614. }
  11615. getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) {
  11616. if (this.returnExpression === null) {
  11617. this.returnExpression = UNKNOWN_RETURN_EXPRESSION;
  11618. return (this.returnExpression = this.tag.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.interaction, recursionTracker, this));
  11619. }
  11620. return this.returnExpression;
  11621. }
  11622. }
  11623. class TemplateElement extends NodeBase {
  11624. // Do not try to bind value
  11625. bind() { }
  11626. hasEffects() {
  11627. return false;
  11628. }
  11629. include() {
  11630. this.included = true;
  11631. }
  11632. parseNode(esTreeNode) {
  11633. this.value = esTreeNode.value;
  11634. super.parseNode(esTreeNode);
  11635. }
  11636. render() { }
  11637. }
  11638. class TemplateLiteral extends NodeBase {
  11639. deoptimizeArgumentsOnInteractionAtPath() { }
  11640. getLiteralValueAtPath(path) {
  11641. if (path.length > 0 || this.quasis.length !== 1) {
  11642. return UnknownValue;
  11643. }
  11644. return this.quasis[0].value.cooked;
  11645. }
  11646. getReturnExpressionWhenCalledAtPath(path) {
  11647. if (path.length !== 1) {
  11648. return UNKNOWN_RETURN_EXPRESSION;
  11649. }
  11650. return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
  11651. }
  11652. hasEffectsOnInteractionAtPath(path, interaction, context) {
  11653. if (interaction.type === INTERACTION_ACCESSED) {
  11654. return path.length > 1;
  11655. }
  11656. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  11657. return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
  11658. }
  11659. return true;
  11660. }
  11661. render(code, options) {
  11662. code.indentExclusionRanges.push([this.start, this.end]);
  11663. super.render(code, options);
  11664. }
  11665. }
  11666. class UndefinedVariable extends Variable {
  11667. constructor() {
  11668. super('undefined');
  11669. }
  11670. getLiteralValueAtPath() {
  11671. return undefined;
  11672. }
  11673. }
  11674. class ExportDefaultVariable extends LocalVariable {
  11675. constructor(name, exportDefaultDeclaration, context) {
  11676. super(name, exportDefaultDeclaration, exportDefaultDeclaration.declaration, context);
  11677. this.hasId = false;
  11678. this.originalId = null;
  11679. this.originalVariable = null;
  11680. const declaration = exportDefaultDeclaration.declaration;
  11681. if ((declaration instanceof FunctionDeclaration || declaration instanceof ClassDeclaration) &&
  11682. declaration.id) {
  11683. this.hasId = true;
  11684. this.originalId = declaration.id;
  11685. }
  11686. else if (declaration instanceof Identifier) {
  11687. this.originalId = declaration;
  11688. }
  11689. }
  11690. addReference(identifier) {
  11691. if (!this.hasId) {
  11692. this.name = identifier.name;
  11693. }
  11694. }
  11695. forbidName(name) {
  11696. const original = this.getOriginalVariable();
  11697. if (original === this) {
  11698. super.forbidName(name);
  11699. }
  11700. else {
  11701. original.forbidName(name);
  11702. }
  11703. }
  11704. getAssignedVariableName() {
  11705. return (this.originalId && this.originalId.name) || null;
  11706. }
  11707. getBaseVariableName() {
  11708. const original = this.getOriginalVariable();
  11709. return original === this ? super.getBaseVariableName() : original.getBaseVariableName();
  11710. }
  11711. getDirectOriginalVariable() {
  11712. return this.originalId &&
  11713. (this.hasId ||
  11714. !(this.originalId.isPossibleTDZ() ||
  11715. this.originalId.variable.isReassigned ||
  11716. this.originalId.variable instanceof UndefinedVariable ||
  11717. // this avoids a circular dependency
  11718. 'syntheticNamespace' in this.originalId.variable))
  11719. ? this.originalId.variable
  11720. : null;
  11721. }
  11722. getName(getPropertyAccess) {
  11723. const original = this.getOriginalVariable();
  11724. return original === this
  11725. ? super.getName(getPropertyAccess)
  11726. : original.getName(getPropertyAccess);
  11727. }
  11728. getOriginalVariable() {
  11729. if (this.originalVariable)
  11730. return this.originalVariable;
  11731. // eslint-disable-next-line @typescript-eslint/no-this-alias
  11732. let original = this;
  11733. let currentVariable;
  11734. const checkedVariables = new Set();
  11735. do {
  11736. checkedVariables.add(original);
  11737. currentVariable = original;
  11738. original = currentVariable.getDirectOriginalVariable();
  11739. } while (original instanceof ExportDefaultVariable && !checkedVariables.has(original));
  11740. return (this.originalVariable = original || currentVariable);
  11741. }
  11742. }
  11743. class ModuleScope extends ChildScope {
  11744. constructor(parent, context) {
  11745. super(parent);
  11746. this.context = context;
  11747. this.variables.set('this', new LocalVariable('this', null, UNDEFINED_EXPRESSION, context));
  11748. }
  11749. addExportDefaultDeclaration(name, exportDefaultDeclaration, context) {
  11750. const variable = new ExportDefaultVariable(name, exportDefaultDeclaration, context);
  11751. this.variables.set('default', variable);
  11752. return variable;
  11753. }
  11754. addNamespaceMemberAccess() { }
  11755. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  11756. // all module level variables are already deconflicted when deconflicting the chunk
  11757. for (const scope of this.children)
  11758. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  11759. }
  11760. findLexicalBoundary() {
  11761. return this;
  11762. }
  11763. findVariable(name) {
  11764. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  11765. if (knownVariable) {
  11766. return knownVariable;
  11767. }
  11768. const variable = this.context.traceVariable(name) || this.parent.findVariable(name);
  11769. if (variable instanceof GlobalVariable) {
  11770. this.accessedOutsideVariables.set(name, variable);
  11771. }
  11772. return variable;
  11773. }
  11774. }
  11775. class ThisExpression extends NodeBase {
  11776. bind() {
  11777. this.variable = this.scope.findVariable('this');
  11778. }
  11779. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  11780. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  11781. }
  11782. deoptimizePath(path) {
  11783. this.variable.deoptimizePath(path);
  11784. }
  11785. hasEffectsOnInteractionAtPath(path, interaction, context) {
  11786. if (path.length === 0) {
  11787. return interaction.type !== INTERACTION_ACCESSED;
  11788. }
  11789. return this.variable.hasEffectsOnInteractionAtPath(path, interaction, context);
  11790. }
  11791. include() {
  11792. if (!this.included) {
  11793. this.included = true;
  11794. this.context.includeVariableInModule(this.variable);
  11795. }
  11796. }
  11797. initialise() {
  11798. this.alias =
  11799. this.scope.findLexicalBoundary() instanceof ModuleScope ? this.context.moduleContext : null;
  11800. if (this.alias === 'undefined') {
  11801. this.context.log(LOGLEVEL_WARN, logThisIsUndefined(), this.start);
  11802. }
  11803. }
  11804. render(code) {
  11805. if (this.alias !== null) {
  11806. code.overwrite(this.start, this.end, this.alias, {
  11807. contentOnly: false,
  11808. storeName: true
  11809. });
  11810. }
  11811. }
  11812. }
  11813. class ThrowStatement extends NodeBase {
  11814. hasEffects() {
  11815. return true;
  11816. }
  11817. include(context, includeChildrenRecursively) {
  11818. this.included = true;
  11819. this.argument.include(context, includeChildrenRecursively);
  11820. context.brokenFlow = true;
  11821. }
  11822. render(code, options) {
  11823. this.argument.render(code, options, { preventASI: true });
  11824. if (this.argument.start === this.start + 5 /* 'throw'.length */) {
  11825. code.prependLeft(this.start + 5, ' ');
  11826. }
  11827. }
  11828. }
  11829. class TryStatement extends NodeBase {
  11830. constructor() {
  11831. super(...arguments);
  11832. this.directlyIncluded = false;
  11833. this.includedLabelsAfterBlock = null;
  11834. }
  11835. hasEffects(context) {
  11836. return ((this.context.options.treeshake.tryCatchDeoptimization
  11837. ? this.block.body.length > 0
  11838. : this.block.hasEffects(context)) || !!this.finalizer?.hasEffects(context));
  11839. }
  11840. include(context, includeChildrenRecursively) {
  11841. const tryCatchDeoptimization = this.context.options.treeshake
  11842. ?.tryCatchDeoptimization;
  11843. const { brokenFlow, includedLabels } = context;
  11844. if (!this.directlyIncluded || !tryCatchDeoptimization) {
  11845. this.included = true;
  11846. this.directlyIncluded = true;
  11847. this.block.include(context, tryCatchDeoptimization ? INCLUDE_PARAMETERS : includeChildrenRecursively);
  11848. if (includedLabels.size > 0) {
  11849. this.includedLabelsAfterBlock = [...includedLabels];
  11850. }
  11851. context.brokenFlow = brokenFlow;
  11852. }
  11853. else if (this.includedLabelsAfterBlock) {
  11854. for (const label of this.includedLabelsAfterBlock) {
  11855. includedLabels.add(label);
  11856. }
  11857. }
  11858. if (this.handler !== null) {
  11859. this.handler.include(context, includeChildrenRecursively);
  11860. context.brokenFlow = brokenFlow;
  11861. }
  11862. this.finalizer?.include(context, includeChildrenRecursively);
  11863. }
  11864. }
  11865. const unaryOperators = {
  11866. '!': value => !value,
  11867. '+': value => +value,
  11868. '-': value => -value,
  11869. delete: () => UnknownValue,
  11870. typeof: value => typeof value,
  11871. void: () => undefined,
  11872. '~': value => ~value
  11873. };
  11874. class UnaryExpression extends NodeBase {
  11875. getLiteralValueAtPath(path, recursionTracker, origin) {
  11876. if (path.length > 0)
  11877. return UnknownValue;
  11878. const argumentValue = this.argument.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  11879. if (typeof argumentValue === 'symbol')
  11880. return UnknownValue;
  11881. return unaryOperators[this.operator](argumentValue);
  11882. }
  11883. hasEffects(context) {
  11884. if (!this.deoptimized)
  11885. this.applyDeoptimizations();
  11886. if (this.operator === 'typeof' && this.argument instanceof Identifier)
  11887. return false;
  11888. return (this.argument.hasEffects(context) ||
  11889. (this.operator === 'delete' &&
  11890. this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context)));
  11891. }
  11892. hasEffectsOnInteractionAtPath(path, { type }) {
  11893. return type !== INTERACTION_ACCESSED || path.length > (this.operator === 'void' ? 0 : 1);
  11894. }
  11895. applyDeoptimizations() {
  11896. this.deoptimized = true;
  11897. if (this.operator === 'delete') {
  11898. this.argument.deoptimizePath(EMPTY_PATH);
  11899. this.context.requestTreeshakingPass();
  11900. }
  11901. }
  11902. }
  11903. class UnknownNode extends NodeBase {
  11904. hasEffects() {
  11905. return true;
  11906. }
  11907. include(context) {
  11908. super.include(context, true);
  11909. }
  11910. }
  11911. class UpdateExpression extends NodeBase {
  11912. hasEffects(context) {
  11913. if (!this.deoptimized)
  11914. this.applyDeoptimizations();
  11915. return this.argument.hasEffectsAsAssignmentTarget(context, true);
  11916. }
  11917. hasEffectsOnInteractionAtPath(path, { type }) {
  11918. return path.length > 1 || type !== INTERACTION_ACCESSED;
  11919. }
  11920. include(context, includeChildrenRecursively) {
  11921. if (!this.deoptimized)
  11922. this.applyDeoptimizations();
  11923. this.included = true;
  11924. this.argument.includeAsAssignmentTarget(context, includeChildrenRecursively, true);
  11925. }
  11926. initialise() {
  11927. this.argument.setAssignedValue(UNKNOWN_EXPRESSION);
  11928. }
  11929. render(code, options) {
  11930. const { exportNamesByVariable, format, snippets: { _ } } = options;
  11931. this.argument.render(code, options);
  11932. if (format === 'system') {
  11933. const variable = this.argument.variable;
  11934. const exportNames = exportNamesByVariable.get(variable);
  11935. if (exportNames) {
  11936. if (this.prefix) {
  11937. if (exportNames.length === 1) {
  11938. renderSystemExportExpression(variable, this.start, this.end, code, options);
  11939. }
  11940. else {
  11941. renderSystemExportSequenceAfterExpression(variable, this.start, this.end, this.parent.type !== ExpressionStatement$1, code, options);
  11942. }
  11943. }
  11944. else {
  11945. const operator = this.operator[0];
  11946. renderSystemExportSequenceBeforeExpression(variable, this.start, this.end, this.parent.type !== ExpressionStatement$1, code, options, `${_}${operator}${_}1`);
  11947. }
  11948. }
  11949. }
  11950. }
  11951. applyDeoptimizations() {
  11952. this.deoptimized = true;
  11953. this.argument.deoptimizePath(EMPTY_PATH);
  11954. if (this.argument instanceof Identifier) {
  11955. const variable = this.scope.findVariable(this.argument.name);
  11956. variable.isReassigned = true;
  11957. }
  11958. this.context.requestTreeshakingPass();
  11959. }
  11960. }
  11961. function areAllDeclarationsIncludedAndNotExported(declarations, exportNamesByVariable) {
  11962. for (const declarator of declarations) {
  11963. if (!declarator.id.included)
  11964. return false;
  11965. if (declarator.id.type === Identifier$1) {
  11966. if (exportNamesByVariable.has(declarator.id.variable))
  11967. return false;
  11968. }
  11969. else {
  11970. const exportedVariables = [];
  11971. declarator.id.addExportedVariables(exportedVariables, exportNamesByVariable);
  11972. if (exportedVariables.length > 0)
  11973. return false;
  11974. }
  11975. }
  11976. return true;
  11977. }
  11978. class VariableDeclaration extends NodeBase {
  11979. deoptimizePath() {
  11980. for (const declarator of this.declarations) {
  11981. declarator.deoptimizePath(EMPTY_PATH);
  11982. }
  11983. }
  11984. hasEffectsOnInteractionAtPath() {
  11985. return false;
  11986. }
  11987. include(context, includeChildrenRecursively, { asSingleStatement } = BLANK) {
  11988. this.included = true;
  11989. for (const declarator of this.declarations) {
  11990. if (includeChildrenRecursively || declarator.shouldBeIncluded(context))
  11991. declarator.include(context, includeChildrenRecursively);
  11992. const { id, init } = declarator;
  11993. if (asSingleStatement) {
  11994. id.include(context, includeChildrenRecursively);
  11995. }
  11996. if (init &&
  11997. id.included &&
  11998. !init.included &&
  11999. (id instanceof ObjectPattern || id instanceof ArrayPattern)) {
  12000. init.include(context, includeChildrenRecursively);
  12001. }
  12002. }
  12003. }
  12004. initialise() {
  12005. for (const declarator of this.declarations) {
  12006. declarator.declareDeclarator(this.kind);
  12007. }
  12008. }
  12009. render(code, options, nodeRenderOptions = BLANK) {
  12010. if (areAllDeclarationsIncludedAndNotExported(this.declarations, options.exportNamesByVariable)) {
  12011. for (const declarator of this.declarations) {
  12012. declarator.render(code, options);
  12013. }
  12014. if (!nodeRenderOptions.isNoStatement &&
  12015. code.original.charCodeAt(this.end - 1) !== 59 /*";"*/) {
  12016. code.appendLeft(this.end, ';');
  12017. }
  12018. }
  12019. else {
  12020. this.renderReplacedDeclarations(code, options);
  12021. }
  12022. }
  12023. applyDeoptimizations() { }
  12024. renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, systemPatternExports, options) {
  12025. if (code.original.charCodeAt(this.end - 1) === 59 /*";"*/) {
  12026. code.remove(this.end - 1, this.end);
  12027. }
  12028. separatorString += ';';
  12029. if (lastSeparatorPos === null) {
  12030. code.appendLeft(renderedContentEnd, separatorString);
  12031. }
  12032. else {
  12033. if (code.original.charCodeAt(actualContentEnd - 1) === 10 /*"\n"*/ &&
  12034. (code.original.charCodeAt(this.end) === 10 /*"\n"*/ ||
  12035. code.original.charCodeAt(this.end) === 13) /*"\r"*/) {
  12036. actualContentEnd--;
  12037. if (code.original.charCodeAt(actualContentEnd) === 13 /*"\r"*/) {
  12038. actualContentEnd--;
  12039. }
  12040. }
  12041. if (actualContentEnd === lastSeparatorPos + 1) {
  12042. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString);
  12043. }
  12044. else {
  12045. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  12046. code.remove(actualContentEnd, renderedContentEnd);
  12047. }
  12048. }
  12049. if (systemPatternExports.length > 0) {
  12050. code.appendLeft(renderedContentEnd, ` ${getSystemExportStatement(systemPatternExports, options)};`);
  12051. }
  12052. }
  12053. renderReplacedDeclarations(code, options) {
  12054. const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.declarations, code, this.start + this.kind.length, this.end - (code.original.charCodeAt(this.end - 1) === 59 /*";"*/ ? 1 : 0));
  12055. let actualContentEnd, renderedContentEnd;
  12056. renderedContentEnd = findNonWhiteSpace(code.original, this.start + this.kind.length);
  12057. let lastSeparatorPos = renderedContentEnd - 1;
  12058. code.remove(this.start, lastSeparatorPos);
  12059. let isInDeclaration = false;
  12060. let hasRenderedContent = false;
  12061. let separatorString = '', leadingString, nextSeparatorString;
  12062. const aggregatedSystemExports = [];
  12063. const singleSystemExport = gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports);
  12064. for (const { node, start, separator, contentEnd, end } of separatedNodes) {
  12065. if (!node.included) {
  12066. code.remove(start, end);
  12067. continue;
  12068. }
  12069. node.render(code, options);
  12070. leadingString = '';
  12071. nextSeparatorString = '';
  12072. if (!node.id.included ||
  12073. (node.id instanceof Identifier &&
  12074. isReassignedExportsMember(node.id.variable, options.exportNamesByVariable))) {
  12075. if (hasRenderedContent) {
  12076. separatorString += ';';
  12077. }
  12078. isInDeclaration = false;
  12079. }
  12080. else {
  12081. if (singleSystemExport && singleSystemExport === node.id.variable) {
  12082. const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', node.id.end);
  12083. renderSystemExportExpression(singleSystemExport, findNonWhiteSpace(code.original, operatorPos + 1), separator === null ? contentEnd : separator, code, options);
  12084. }
  12085. if (isInDeclaration) {
  12086. separatorString += ',';
  12087. }
  12088. else {
  12089. if (hasRenderedContent) {
  12090. separatorString += ';';
  12091. }
  12092. leadingString += `${this.kind} `;
  12093. isInDeclaration = true;
  12094. }
  12095. }
  12096. if (renderedContentEnd === lastSeparatorPos + 1) {
  12097. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString + leadingString);
  12098. }
  12099. else {
  12100. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  12101. code.appendLeft(renderedContentEnd, leadingString);
  12102. }
  12103. actualContentEnd = contentEnd;
  12104. renderedContentEnd = end;
  12105. hasRenderedContent = true;
  12106. lastSeparatorPos = separator;
  12107. separatorString = nextSeparatorString;
  12108. }
  12109. this.renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, aggregatedSystemExports, options);
  12110. }
  12111. }
  12112. function gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports) {
  12113. let singleSystemExport = null;
  12114. if (options.format === 'system') {
  12115. for (const { node } of separatedNodes) {
  12116. if (node.id instanceof Identifier &&
  12117. node.init &&
  12118. aggregatedSystemExports.length === 0 &&
  12119. options.exportNamesByVariable.get(node.id.variable)?.length === 1) {
  12120. singleSystemExport = node.id.variable;
  12121. aggregatedSystemExports.push(singleSystemExport);
  12122. }
  12123. else {
  12124. node.id.addExportedVariables(aggregatedSystemExports, options.exportNamesByVariable);
  12125. }
  12126. }
  12127. if (aggregatedSystemExports.length > 1) {
  12128. singleSystemExport = null;
  12129. }
  12130. else if (singleSystemExport) {
  12131. aggregatedSystemExports.length = 0;
  12132. }
  12133. }
  12134. return singleSystemExport;
  12135. }
  12136. class WhileStatement extends NodeBase {
  12137. hasEffects(context) {
  12138. if (this.test.hasEffects(context))
  12139. return true;
  12140. return hasLoopBodyEffects(context, this.body);
  12141. }
  12142. include(context, includeChildrenRecursively) {
  12143. this.included = true;
  12144. this.test.include(context, includeChildrenRecursively);
  12145. includeLoopBody(context, this.body, includeChildrenRecursively);
  12146. }
  12147. }
  12148. class YieldExpression extends NodeBase {
  12149. hasEffects(context) {
  12150. if (!this.deoptimized)
  12151. this.applyDeoptimizations();
  12152. return !(context.ignore.returnYield && !this.argument?.hasEffects(context));
  12153. }
  12154. render(code, options) {
  12155. if (this.argument) {
  12156. this.argument.render(code, options, { preventASI: true });
  12157. if (this.argument.start === this.start + 5 /* 'yield'.length */) {
  12158. code.prependLeft(this.start + 5, ' ');
  12159. }
  12160. }
  12161. }
  12162. }
  12163. const nodeConstructors = {
  12164. ArrayExpression,
  12165. ArrayPattern,
  12166. ArrowFunctionExpression,
  12167. AssignmentExpression,
  12168. AssignmentPattern,
  12169. AwaitExpression,
  12170. BinaryExpression,
  12171. BlockStatement,
  12172. BreakStatement,
  12173. CallExpression,
  12174. CatchClause,
  12175. ChainExpression,
  12176. ClassBody,
  12177. ClassDeclaration,
  12178. ClassExpression,
  12179. ConditionalExpression,
  12180. ContinueStatement,
  12181. DoWhileStatement,
  12182. EmptyStatement,
  12183. ExportAllDeclaration,
  12184. ExportDefaultDeclaration,
  12185. ExportNamedDeclaration,
  12186. ExportSpecifier,
  12187. ExpressionStatement,
  12188. ForInStatement,
  12189. ForOfStatement,
  12190. ForStatement,
  12191. FunctionDeclaration,
  12192. FunctionExpression,
  12193. Identifier,
  12194. IfStatement,
  12195. ImportAttribute,
  12196. ImportDeclaration,
  12197. ImportDefaultSpecifier,
  12198. ImportExpression,
  12199. ImportNamespaceSpecifier,
  12200. ImportSpecifier,
  12201. LabeledStatement,
  12202. Literal,
  12203. LogicalExpression,
  12204. MemberExpression,
  12205. MetaProperty,
  12206. MethodDefinition,
  12207. NewExpression,
  12208. ObjectExpression,
  12209. ObjectPattern,
  12210. PrivateIdentifier,
  12211. Program,
  12212. Property,
  12213. PropertyDefinition,
  12214. RestElement,
  12215. ReturnStatement,
  12216. SequenceExpression,
  12217. SpreadElement,
  12218. StaticBlock,
  12219. Super,
  12220. SwitchCase,
  12221. SwitchStatement,
  12222. TaggedTemplateExpression,
  12223. TemplateElement,
  12224. TemplateLiteral,
  12225. ThisExpression,
  12226. ThrowStatement,
  12227. TryStatement,
  12228. UnaryExpression,
  12229. UnknownNode,
  12230. UpdateExpression,
  12231. VariableDeclaration,
  12232. VariableDeclarator,
  12233. WhileStatement,
  12234. YieldExpression
  12235. };
  12236. const MISSING_EXPORT_SHIM_VARIABLE = '_missingExportShim';
  12237. class ExportShimVariable extends Variable {
  12238. constructor(module) {
  12239. super(MISSING_EXPORT_SHIM_VARIABLE);
  12240. this.module = module;
  12241. }
  12242. include() {
  12243. super.include();
  12244. this.module.needsExportShim = true;
  12245. }
  12246. }
  12247. class NamespaceVariable extends Variable {
  12248. constructor(context) {
  12249. super(context.getModuleName());
  12250. this.memberVariables = null;
  12251. this.mergedNamespaces = [];
  12252. this.referencedEarly = false;
  12253. this.references = [];
  12254. this.context = context;
  12255. this.module = context.module;
  12256. }
  12257. addReference(identifier) {
  12258. this.references.push(identifier);
  12259. this.name = identifier.name;
  12260. }
  12261. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  12262. if (path.length > 1 || (path.length === 1 && interaction.type === INTERACTION_CALLED)) {
  12263. const key = path[0];
  12264. if (typeof key === 'string') {
  12265. this.getMemberVariables()[key]?.deoptimizeArgumentsOnInteractionAtPath(interaction, path.slice(1), recursionTracker);
  12266. }
  12267. else {
  12268. deoptimizeInteraction(interaction);
  12269. }
  12270. }
  12271. }
  12272. deoptimizePath(path) {
  12273. if (path.length > 1) {
  12274. const key = path[0];
  12275. if (typeof key === 'string') {
  12276. this.getMemberVariables()[key]?.deoptimizePath(path.slice(1));
  12277. }
  12278. }
  12279. }
  12280. getLiteralValueAtPath(path) {
  12281. if (path[0] === SymbolToStringTag) {
  12282. return 'Module';
  12283. }
  12284. return UnknownValue;
  12285. }
  12286. getMemberVariables() {
  12287. if (this.memberVariables) {
  12288. return this.memberVariables;
  12289. }
  12290. const memberVariables = Object.create(null);
  12291. const sortedExports = [...this.context.getExports(), ...this.context.getReexports()].sort();
  12292. for (const name of sortedExports) {
  12293. if (name[0] !== '*' && name !== this.module.info.syntheticNamedExports) {
  12294. const exportedVariable = this.context.traceExport(name);
  12295. if (exportedVariable) {
  12296. memberVariables[name] = exportedVariable;
  12297. }
  12298. }
  12299. }
  12300. return (this.memberVariables = memberVariables);
  12301. }
  12302. hasEffectsOnInteractionAtPath(path, interaction, context) {
  12303. const { type } = interaction;
  12304. if (path.length === 0) {
  12305. // This can only be a call anyway
  12306. return true;
  12307. }
  12308. if (path.length === 1 && type !== INTERACTION_CALLED) {
  12309. return type === INTERACTION_ASSIGNED;
  12310. }
  12311. const key = path[0];
  12312. if (typeof key !== 'string') {
  12313. return true;
  12314. }
  12315. const memberVariable = this.getMemberVariables()[key];
  12316. return (!memberVariable ||
  12317. memberVariable.hasEffectsOnInteractionAtPath(path.slice(1), interaction, context));
  12318. }
  12319. include() {
  12320. this.included = true;
  12321. this.context.includeAllExports();
  12322. }
  12323. prepare(accessedGlobalsByScope) {
  12324. if (this.mergedNamespaces.length > 0) {
  12325. this.module.scope.addAccessedGlobals([MERGE_NAMESPACES_VARIABLE], accessedGlobalsByScope);
  12326. }
  12327. }
  12328. renderBlock(options) {
  12329. const { exportNamesByVariable, format, freeze, indent: t, namespaceToStringTag, snippets: { _, cnst, getObject, getPropertyAccess, n, s } } = options;
  12330. const memberVariables = this.getMemberVariables();
  12331. const members = Object.entries(memberVariables)
  12332. .filter(([_, variable]) => variable.included)
  12333. .map(([name, variable]) => {
  12334. if (this.referencedEarly || variable.isReassigned || variable === this) {
  12335. return [
  12336. null,
  12337. `get ${name}${_}()${_}{${_}return ${variable.getName(getPropertyAccess)}${s}${_}}`
  12338. ];
  12339. }
  12340. return [name, variable.getName(getPropertyAccess)];
  12341. });
  12342. members.unshift([null, `__proto__:${_}null`]);
  12343. let output = getObject(members, { lineBreakIndent: { base: '', t } });
  12344. if (this.mergedNamespaces.length > 0) {
  12345. const assignmentArguments = this.mergedNamespaces.map(variable => variable.getName(getPropertyAccess));
  12346. output = `/*#__PURE__*/${MERGE_NAMESPACES_VARIABLE}(${output},${_}[${assignmentArguments.join(`,${_}`)}])`;
  12347. }
  12348. else {
  12349. // The helper to merge namespaces will also take care of freezing and toStringTag
  12350. if (namespaceToStringTag) {
  12351. output = `/*#__PURE__*/Object.defineProperty(${output},${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)})`;
  12352. }
  12353. if (freeze) {
  12354. output = `/*#__PURE__*/Object.freeze(${output})`;
  12355. }
  12356. }
  12357. const name = this.getName(getPropertyAccess);
  12358. output = `${cnst} ${name}${_}=${_}${output};`;
  12359. if (format === 'system' && exportNamesByVariable.has(this)) {
  12360. output += `${n}${getSystemExportStatement([this], options)};`;
  12361. }
  12362. return output;
  12363. }
  12364. renderFirst() {
  12365. return this.referencedEarly;
  12366. }
  12367. setMergedNamespaces(mergedNamespaces) {
  12368. this.mergedNamespaces = mergedNamespaces;
  12369. const moduleExecIndex = this.context.getModuleExecIndex();
  12370. for (const identifier of this.references) {
  12371. if (identifier.context.getModuleExecIndex() <= moduleExecIndex) {
  12372. this.referencedEarly = true;
  12373. break;
  12374. }
  12375. }
  12376. }
  12377. }
  12378. NamespaceVariable.prototype.isNamespace = true;
  12379. class SyntheticNamedExportVariable extends Variable {
  12380. constructor(context, name, syntheticNamespace) {
  12381. super(name);
  12382. this.baseVariable = null;
  12383. this.context = context;
  12384. this.module = context.module;
  12385. this.syntheticNamespace = syntheticNamespace;
  12386. }
  12387. getBaseVariable() {
  12388. if (this.baseVariable)
  12389. return this.baseVariable;
  12390. let baseVariable = this.syntheticNamespace;
  12391. while (baseVariable instanceof ExportDefaultVariable ||
  12392. baseVariable instanceof SyntheticNamedExportVariable) {
  12393. if (baseVariable instanceof ExportDefaultVariable) {
  12394. const original = baseVariable.getOriginalVariable();
  12395. if (original === baseVariable)
  12396. break;
  12397. baseVariable = original;
  12398. }
  12399. if (baseVariable instanceof SyntheticNamedExportVariable) {
  12400. baseVariable = baseVariable.syntheticNamespace;
  12401. }
  12402. }
  12403. return (this.baseVariable = baseVariable);
  12404. }
  12405. getBaseVariableName() {
  12406. return this.syntheticNamespace.getBaseVariableName();
  12407. }
  12408. getName(getPropertyAccess) {
  12409. return `${this.syntheticNamespace.getName(getPropertyAccess)}${getPropertyAccess(this.name)}`;
  12410. }
  12411. include() {
  12412. this.included = true;
  12413. this.context.includeVariableInModule(this.syntheticNamespace);
  12414. }
  12415. setRenderNames(baseName, name) {
  12416. super.setRenderNames(baseName, name);
  12417. }
  12418. }
  12419. var BuildPhase;
  12420. (function (BuildPhase) {
  12421. BuildPhase[BuildPhase["LOAD_AND_PARSE"] = 0] = "LOAD_AND_PARSE";
  12422. BuildPhase[BuildPhase["ANALYSE"] = 1] = "ANALYSE";
  12423. BuildPhase[BuildPhase["GENERATE"] = 2] = "GENERATE";
  12424. })(BuildPhase || (BuildPhase = {}));
  12425. const sourceMapCache = new WeakMap();
  12426. /**
  12427. * This clears the decoded array and falls back to the encoded string form.
  12428. * Sourcemap mappings arrays can be very large and holding on to them for longer
  12429. * than is necessary leads to poor heap utilization.
  12430. */
  12431. function resetCacheToEncoded(cache) {
  12432. if (cache.encodedMappings === undefined && cache.decodedMappings) {
  12433. cache.encodedMappings = encode(cache.decodedMappings);
  12434. }
  12435. cache.decodedMappings = undefined;
  12436. }
  12437. function resetSourcemapCache(map, sourcemapChain) {
  12438. if (map) {
  12439. const cache = sourceMapCache.get(map);
  12440. if (cache) {
  12441. resetCacheToEncoded(cache);
  12442. }
  12443. }
  12444. if (!sourcemapChain) {
  12445. return;
  12446. }
  12447. for (const map of sourcemapChain) {
  12448. if (map.missing)
  12449. continue;
  12450. resetSourcemapCache(map);
  12451. }
  12452. }
  12453. function decodedSourcemap(map) {
  12454. if (!map)
  12455. return null;
  12456. if (typeof map === 'string') {
  12457. map = JSON.parse(map);
  12458. }
  12459. if (!map.mappings) {
  12460. return {
  12461. mappings: [],
  12462. names: [],
  12463. sources: [],
  12464. version: 3
  12465. };
  12466. }
  12467. const originalMappings = map.mappings;
  12468. const isAlreadyDecoded = Array.isArray(originalMappings);
  12469. const cache = {
  12470. decodedMappings: isAlreadyDecoded ? originalMappings : undefined,
  12471. encodedMappings: isAlreadyDecoded ? undefined : originalMappings
  12472. };
  12473. const decodedMap = {
  12474. ...map,
  12475. // By moving mappings behind an accessor, we can avoid unneeded computation for cases
  12476. // where the mappings field is never actually accessed. This appears to greatly reduce
  12477. // the overhead of sourcemap decoding in terms of both compute time and memory usage.
  12478. get mappings() {
  12479. if (cache.decodedMappings) {
  12480. return cache.decodedMappings;
  12481. }
  12482. // If decodedMappings doesn't exist then encodedMappings should.
  12483. // The only scenario where cache.encodedMappings should be undefined is if the map
  12484. // this was constructed from was already decoded, or if mappings was set to a new
  12485. // decoded string. In either case, this line shouldn't get hit.
  12486. cache.decodedMappings = cache.encodedMappings ? decode(cache.encodedMappings) : [];
  12487. cache.encodedMappings = undefined;
  12488. return cache.decodedMappings;
  12489. }
  12490. };
  12491. sourceMapCache.set(decodedMap, cache);
  12492. return decodedMap;
  12493. }
  12494. function getId(m) {
  12495. return m.id;
  12496. }
  12497. function getOriginalLocation(sourcemapChain, location) {
  12498. const filteredSourcemapChain = sourcemapChain.filter((sourcemap) => !sourcemap.missing);
  12499. traceSourcemap: while (filteredSourcemapChain.length > 0) {
  12500. const sourcemap = filteredSourcemapChain.pop();
  12501. const line = sourcemap.mappings[location.line - 1];
  12502. if (line) {
  12503. const filteredLine = line.filter((segment) => segment.length > 1);
  12504. const lastSegment = filteredLine[filteredLine.length - 1];
  12505. for (const segment of filteredLine) {
  12506. if (segment[0] >= location.column || segment === lastSegment) {
  12507. location = {
  12508. column: segment[3],
  12509. line: segment[2] + 1
  12510. };
  12511. continue traceSourcemap;
  12512. }
  12513. }
  12514. }
  12515. throw new Error("Can't resolve original location of error.");
  12516. }
  12517. return location;
  12518. }
  12519. function getAssertionsFromImportExpression(node) {
  12520. const assertProperty = node.arguments?.[0]?.properties.find((property) => getPropertyKey(property) === 'assert')?.value;
  12521. if (!assertProperty) {
  12522. return EMPTY_OBJECT;
  12523. }
  12524. const assertFields = assertProperty.properties
  12525. .map(property => {
  12526. const key = getPropertyKey(property);
  12527. if (typeof key === 'string' &&
  12528. typeof property.value.value === 'string') {
  12529. return [key, property.value.value];
  12530. }
  12531. return null;
  12532. })
  12533. .filter((property) => !!property);
  12534. if (assertFields.length > 0) {
  12535. return Object.fromEntries(assertFields);
  12536. }
  12537. return EMPTY_OBJECT;
  12538. }
  12539. const getPropertyKey = (property) => {
  12540. const key = property.key;
  12541. return key && (key.name || key.value);
  12542. };
  12543. function getAssertionsFromImportExportDeclaration(assertions) {
  12544. return assertions?.length
  12545. ? Object.fromEntries(assertions.map(assertion => [getPropertyKey(assertion), assertion.value.value]))
  12546. : EMPTY_OBJECT;
  12547. }
  12548. function doAssertionsDiffer(assertionA, assertionB) {
  12549. const keysA = Object.keys(assertionA);
  12550. return (keysA.length !== Object.keys(assertionB).length ||
  12551. keysA.some(key => assertionA[key] !== assertionB[key]));
  12552. }
  12553. let timers = new Map();
  12554. function getPersistedLabel(label, level) {
  12555. switch (level) {
  12556. case 1: {
  12557. return `# ${label}`;
  12558. }
  12559. case 2: {
  12560. return `## ${label}`;
  12561. }
  12562. case 3: {
  12563. return label;
  12564. }
  12565. default: {
  12566. return `${' '.repeat(level - 4)}- ${label}`;
  12567. }
  12568. }
  12569. }
  12570. function timeStartImpl(label, level = 3) {
  12571. label = getPersistedLabel(label, level);
  12572. const startMemory = process$1.memoryUsage().heapUsed;
  12573. const startTime = performance.now();
  12574. const timer = timers.get(label);
  12575. if (timer === undefined) {
  12576. timers.set(label, {
  12577. memory: 0,
  12578. startMemory,
  12579. startTime,
  12580. time: 0,
  12581. totalMemory: 0
  12582. });
  12583. }
  12584. else {
  12585. timer.startMemory = startMemory;
  12586. timer.startTime = startTime;
  12587. }
  12588. }
  12589. function timeEndImpl(label, level = 3) {
  12590. label = getPersistedLabel(label, level);
  12591. const timer = timers.get(label);
  12592. if (timer !== undefined) {
  12593. const currentMemory = process$1.memoryUsage().heapUsed;
  12594. timer.memory += currentMemory - timer.startMemory;
  12595. timer.time += performance.now() - timer.startTime;
  12596. timer.totalMemory = Math.max(timer.totalMemory, currentMemory);
  12597. }
  12598. }
  12599. function getTimings() {
  12600. const newTimings = {};
  12601. for (const [label, { memory, time, totalMemory }] of timers) {
  12602. newTimings[label] = [time, memory, totalMemory];
  12603. }
  12604. return newTimings;
  12605. }
  12606. let timeStart = doNothing;
  12607. let timeEnd = doNothing;
  12608. const TIMED_PLUGIN_HOOKS = [
  12609. 'augmentChunkHash',
  12610. 'buildEnd',
  12611. 'buildStart',
  12612. 'generateBundle',
  12613. 'load',
  12614. 'moduleParsed',
  12615. 'options',
  12616. 'outputOptions',
  12617. 'renderChunk',
  12618. 'renderDynamicImport',
  12619. 'renderStart',
  12620. 'resolveDynamicImport',
  12621. 'resolveFileUrl',
  12622. 'resolveId',
  12623. 'resolveImportMeta',
  12624. 'shouldTransformCachedModule',
  12625. 'transform',
  12626. 'writeBundle'
  12627. ];
  12628. function getPluginWithTimers(plugin, index) {
  12629. if (plugin._hasTimer)
  12630. return plugin;
  12631. plugin._hasTimer = true;
  12632. for (const hook of TIMED_PLUGIN_HOOKS) {
  12633. if (hook in plugin) {
  12634. let timerLabel = `plugin ${index}`;
  12635. if (plugin.name) {
  12636. timerLabel += ` (${plugin.name})`;
  12637. }
  12638. timerLabel += ` - ${hook}`;
  12639. const handler = function (...parameters) {
  12640. timeStart(timerLabel, 4);
  12641. const result = hookFunction.apply(this, parameters);
  12642. timeEnd(timerLabel, 4);
  12643. return result;
  12644. };
  12645. let hookFunction;
  12646. if (typeof plugin[hook].handler === 'function') {
  12647. hookFunction = plugin[hook].handler;
  12648. plugin[hook].handler = handler;
  12649. }
  12650. else {
  12651. hookFunction = plugin[hook];
  12652. plugin[hook] = handler;
  12653. }
  12654. }
  12655. }
  12656. return plugin;
  12657. }
  12658. function initialiseTimers(inputOptions) {
  12659. if (inputOptions.perf) {
  12660. timers = new Map();
  12661. timeStart = timeStartImpl;
  12662. timeEnd = timeEndImpl;
  12663. inputOptions.plugins = inputOptions.plugins.map(getPluginWithTimers);
  12664. }
  12665. else {
  12666. timeStart = doNothing;
  12667. timeEnd = doNothing;
  12668. }
  12669. }
  12670. function markModuleAndImpureDependenciesAsExecuted(baseModule) {
  12671. baseModule.isExecuted = true;
  12672. const modules = [baseModule];
  12673. const visitedModules = new Set();
  12674. for (const module of modules) {
  12675. for (const dependency of [...module.dependencies, ...module.implicitlyLoadedBefore]) {
  12676. if (!(dependency instanceof ExternalModule) &&
  12677. !dependency.isExecuted &&
  12678. (dependency.info.moduleSideEffects || module.implicitlyLoadedBefore.has(dependency)) &&
  12679. !visitedModules.has(dependency.id)) {
  12680. dependency.isExecuted = true;
  12681. visitedModules.add(dependency.id);
  12682. modules.push(dependency);
  12683. }
  12684. }
  12685. }
  12686. }
  12687. const MISSING_EXPORT_SHIM_DESCRIPTION = {
  12688. identifier: null,
  12689. localName: MISSING_EXPORT_SHIM_VARIABLE
  12690. };
  12691. function getVariableForExportNameRecursive(target, name, importerForSideEffects, isExportAllSearch, searchedNamesAndModules = new Map()) {
  12692. const searchedModules = searchedNamesAndModules.get(name);
  12693. if (searchedModules) {
  12694. if (searchedModules.has(target)) {
  12695. return isExportAllSearch ? [null] : error(logCircularReexport(name, target.id));
  12696. }
  12697. searchedModules.add(target);
  12698. }
  12699. else {
  12700. searchedNamesAndModules.set(name, new Set([target]));
  12701. }
  12702. return target.getVariableForExportName(name, {
  12703. importerForSideEffects,
  12704. isExportAllSearch,
  12705. searchedNamesAndModules
  12706. });
  12707. }
  12708. function getAndExtendSideEffectModules(variable, module) {
  12709. const sideEffectModules = getOrCreate(module.sideEffectDependenciesByVariable, variable, (getNewSet));
  12710. let currentVariable = variable;
  12711. const referencedVariables = new Set([currentVariable]);
  12712. while (true) {
  12713. const importingModule = currentVariable.module;
  12714. currentVariable =
  12715. currentVariable instanceof ExportDefaultVariable
  12716. ? currentVariable.getDirectOriginalVariable()
  12717. : currentVariable instanceof SyntheticNamedExportVariable
  12718. ? currentVariable.syntheticNamespace
  12719. : null;
  12720. if (!currentVariable || referencedVariables.has(currentVariable)) {
  12721. break;
  12722. }
  12723. referencedVariables.add(currentVariable);
  12724. sideEffectModules.add(importingModule);
  12725. const originalSideEffects = importingModule.sideEffectDependenciesByVariable.get(currentVariable);
  12726. if (originalSideEffects) {
  12727. for (const module of originalSideEffects) {
  12728. sideEffectModules.add(module);
  12729. }
  12730. }
  12731. }
  12732. return sideEffectModules;
  12733. }
  12734. class Module {
  12735. constructor(graph, id, options, isEntry, moduleSideEffects, syntheticNamedExports, meta, assertions) {
  12736. this.graph = graph;
  12737. this.id = id;
  12738. this.options = options;
  12739. this.alternativeReexportModules = new Map();
  12740. this.chunkFileNames = new Set();
  12741. this.chunkNames = [];
  12742. this.cycles = new Set();
  12743. this.dependencies = new Set();
  12744. this.dynamicDependencies = new Set();
  12745. this.dynamicImporters = [];
  12746. this.dynamicImports = [];
  12747. this.execIndex = Infinity;
  12748. this.implicitlyLoadedAfter = new Set();
  12749. this.implicitlyLoadedBefore = new Set();
  12750. this.importDescriptions = new Map();
  12751. this.importMetas = [];
  12752. this.importedFromNotTreeshaken = false;
  12753. this.importers = [];
  12754. this.includedDynamicImporters = [];
  12755. this.includedImports = new Set();
  12756. this.isExecuted = false;
  12757. this.isUserDefinedEntryPoint = false;
  12758. this.needsExportShim = false;
  12759. this.sideEffectDependenciesByVariable = new Map();
  12760. this.sourcesWithAssertions = new Map();
  12761. this.allExportNames = null;
  12762. this.ast = null;
  12763. this.exportAllModules = [];
  12764. this.exportAllSources = new Set();
  12765. this.exportNamesByVariable = null;
  12766. this.exportShimVariable = new ExportShimVariable(this);
  12767. this.exports = new Map();
  12768. this.namespaceReexportsByName = new Map();
  12769. this.reexportDescriptions = new Map();
  12770. this.relevantDependencies = null;
  12771. this.syntheticExports = new Map();
  12772. this.syntheticNamespace = null;
  12773. this.transformDependencies = [];
  12774. this.transitiveReexports = null;
  12775. this.excludeFromSourcemap = /\0/.test(id);
  12776. this.context = options.moduleContext(id);
  12777. this.preserveSignature = this.options.preserveEntrySignatures;
  12778. // eslint-disable-next-line @typescript-eslint/no-this-alias
  12779. const module = this;
  12780. const { dynamicImports, dynamicImporters, exportAllSources, exports, implicitlyLoadedAfter, implicitlyLoadedBefore, importers, reexportDescriptions, sourcesWithAssertions } = this;
  12781. this.info = {
  12782. assertions,
  12783. ast: null,
  12784. code: null,
  12785. get dynamicallyImportedIdResolutions() {
  12786. return dynamicImports
  12787. .map(({ argument }) => typeof argument === 'string' && module.resolvedIds[argument])
  12788. .filter(Boolean);
  12789. },
  12790. get dynamicallyImportedIds() {
  12791. // We cannot use this.dynamicDependencies because this is needed before
  12792. // dynamicDependencies are populated
  12793. return dynamicImports.map(({ id }) => id).filter((id) => id != null);
  12794. },
  12795. get dynamicImporters() {
  12796. return dynamicImporters.sort();
  12797. },
  12798. get exportedBindings() {
  12799. const exportBindings = { '.': [...exports.keys()] };
  12800. for (const [name, { source }] of reexportDescriptions) {
  12801. (exportBindings[source] ?? (exportBindings[source] = [])).push(name);
  12802. }
  12803. for (const source of exportAllSources) {
  12804. (exportBindings[source] ?? (exportBindings[source] = [])).push('*');
  12805. }
  12806. return exportBindings;
  12807. },
  12808. get exports() {
  12809. return [
  12810. ...exports.keys(),
  12811. ...reexportDescriptions.keys(),
  12812. ...[...exportAllSources].map(() => '*')
  12813. ];
  12814. },
  12815. get hasDefaultExport() {
  12816. // This information is only valid after parsing
  12817. if (!module.ast) {
  12818. return null;
  12819. }
  12820. return module.exports.has('default') || reexportDescriptions.has('default');
  12821. },
  12822. get hasModuleSideEffects() {
  12823. warnDeprecation('Accessing ModuleInfo.hasModuleSideEffects from plugins is deprecated. Please use ModuleInfo.moduleSideEffects instead.', URL_THIS_GETMODULEINFO, true, options);
  12824. return this.moduleSideEffects;
  12825. },
  12826. id,
  12827. get implicitlyLoadedAfterOneOf() {
  12828. // eslint-disable-next-line unicorn/prefer-spread
  12829. return Array.from(implicitlyLoadedAfter, getId).sort();
  12830. },
  12831. get implicitlyLoadedBefore() {
  12832. // eslint-disable-next-line unicorn/prefer-spread
  12833. return Array.from(implicitlyLoadedBefore, getId).sort();
  12834. },
  12835. get importedIdResolutions() {
  12836. // eslint-disable-next-line unicorn/prefer-spread
  12837. return Array.from(sourcesWithAssertions.keys(), source => module.resolvedIds[source]).filter(Boolean);
  12838. },
  12839. get importedIds() {
  12840. // We cannot use this.dependencies because this is needed before
  12841. // dependencies are populated
  12842. // eslint-disable-next-line unicorn/prefer-spread
  12843. return Array.from(sourcesWithAssertions.keys(), source => module.resolvedIds[source]?.id).filter(Boolean);
  12844. },
  12845. get importers() {
  12846. return importers.sort();
  12847. },
  12848. isEntry,
  12849. isExternal: false,
  12850. get isIncluded() {
  12851. if (graph.phase !== BuildPhase.GENERATE) {
  12852. return null;
  12853. }
  12854. return module.isIncluded();
  12855. },
  12856. meta: { ...meta },
  12857. moduleSideEffects,
  12858. syntheticNamedExports
  12859. };
  12860. // Hide the deprecated key so that it only warns when accessed explicitly
  12861. // eslint-disable-next-line unicorn/consistent-destructuring
  12862. Object.defineProperty(this.info, 'hasModuleSideEffects', {
  12863. enumerable: false
  12864. });
  12865. }
  12866. basename() {
  12867. const base = basename(this.id);
  12868. const extension = extname(this.id);
  12869. return makeLegal(extension ? base.slice(0, -extension.length) : base);
  12870. }
  12871. bindReferences() {
  12872. this.ast.bind();
  12873. }
  12874. error(properties, pos) {
  12875. this.addLocationToLogProps(properties, pos);
  12876. return error(properties);
  12877. }
  12878. // sum up the length of all ast nodes that are included
  12879. estimateSize() {
  12880. let size = 0;
  12881. for (const node of this.ast.body) {
  12882. if (node.included) {
  12883. size += node.end - node.start;
  12884. }
  12885. }
  12886. return size;
  12887. }
  12888. getAllExportNames() {
  12889. if (this.allExportNames) {
  12890. return this.allExportNames;
  12891. }
  12892. this.allExportNames = new Set([...this.exports.keys(), ...this.reexportDescriptions.keys()]);
  12893. for (const module of this.exportAllModules) {
  12894. if (module instanceof ExternalModule) {
  12895. this.allExportNames.add(`*${module.id}`);
  12896. continue;
  12897. }
  12898. for (const name of module.getAllExportNames()) {
  12899. if (name !== 'default')
  12900. this.allExportNames.add(name);
  12901. }
  12902. }
  12903. // We do not count the synthetic namespace as a regular export to hide it
  12904. // from entry signatures and namespace objects
  12905. if (typeof this.info.syntheticNamedExports === 'string') {
  12906. this.allExportNames.delete(this.info.syntheticNamedExports);
  12907. }
  12908. return this.allExportNames;
  12909. }
  12910. getDependenciesToBeIncluded() {
  12911. if (this.relevantDependencies)
  12912. return this.relevantDependencies;
  12913. this.relevantDependencies = new Set();
  12914. const necessaryDependencies = new Set();
  12915. const alwaysCheckedDependencies = new Set();
  12916. const dependencyVariables = new Set(this.includedImports);
  12917. if (this.info.isEntry ||
  12918. this.includedDynamicImporters.length > 0 ||
  12919. this.namespace.included ||
  12920. this.implicitlyLoadedAfter.size > 0) {
  12921. for (const exportName of [...this.getReexports(), ...this.getExports()]) {
  12922. const [exportedVariable] = this.getVariableForExportName(exportName);
  12923. if (exportedVariable?.included) {
  12924. dependencyVariables.add(exportedVariable);
  12925. }
  12926. }
  12927. }
  12928. for (let variable of dependencyVariables) {
  12929. const sideEffectDependencies = this.sideEffectDependenciesByVariable.get(variable);
  12930. if (sideEffectDependencies) {
  12931. for (const module of sideEffectDependencies) {
  12932. alwaysCheckedDependencies.add(module);
  12933. }
  12934. }
  12935. if (variable instanceof SyntheticNamedExportVariable) {
  12936. variable = variable.getBaseVariable();
  12937. }
  12938. else if (variable instanceof ExportDefaultVariable) {
  12939. variable = variable.getOriginalVariable();
  12940. }
  12941. necessaryDependencies.add(variable.module);
  12942. }
  12943. if (!this.options.treeshake || this.info.moduleSideEffects === 'no-treeshake') {
  12944. for (const dependency of this.dependencies) {
  12945. this.relevantDependencies.add(dependency);
  12946. }
  12947. }
  12948. else {
  12949. this.addRelevantSideEffectDependencies(this.relevantDependencies, necessaryDependencies, alwaysCheckedDependencies);
  12950. }
  12951. for (const dependency of necessaryDependencies) {
  12952. this.relevantDependencies.add(dependency);
  12953. }
  12954. return this.relevantDependencies;
  12955. }
  12956. getExportNamesByVariable() {
  12957. if (this.exportNamesByVariable) {
  12958. return this.exportNamesByVariable;
  12959. }
  12960. const exportNamesByVariable = new Map();
  12961. for (const exportName of this.getAllExportNames()) {
  12962. let [tracedVariable] = this.getVariableForExportName(exportName);
  12963. if (tracedVariable instanceof ExportDefaultVariable) {
  12964. tracedVariable = tracedVariable.getOriginalVariable();
  12965. }
  12966. if (!tracedVariable ||
  12967. !(tracedVariable.included || tracedVariable instanceof ExternalVariable)) {
  12968. continue;
  12969. }
  12970. const existingExportNames = exportNamesByVariable.get(tracedVariable);
  12971. if (existingExportNames) {
  12972. existingExportNames.push(exportName);
  12973. }
  12974. else {
  12975. exportNamesByVariable.set(tracedVariable, [exportName]);
  12976. }
  12977. }
  12978. return (this.exportNamesByVariable = exportNamesByVariable);
  12979. }
  12980. getExports() {
  12981. return [...this.exports.keys()];
  12982. }
  12983. getReexports() {
  12984. if (this.transitiveReexports) {
  12985. return this.transitiveReexports;
  12986. }
  12987. // to avoid infinite recursion when using circular `export * from X`
  12988. this.transitiveReexports = [];
  12989. const reexports = new Set(this.reexportDescriptions.keys());
  12990. for (const module of this.exportAllModules) {
  12991. if (module instanceof ExternalModule) {
  12992. reexports.add(`*${module.id}`);
  12993. }
  12994. else {
  12995. for (const name of [...module.getReexports(), ...module.getExports()]) {
  12996. if (name !== 'default')
  12997. reexports.add(name);
  12998. }
  12999. }
  13000. }
  13001. return (this.transitiveReexports = [...reexports]);
  13002. }
  13003. getRenderedExports() {
  13004. // only direct exports are counted here, not reexports at all
  13005. const renderedExports = [];
  13006. const removedExports = [];
  13007. for (const exportName of this.exports.keys()) {
  13008. const [variable] = this.getVariableForExportName(exportName);
  13009. (variable && variable.included ? renderedExports : removedExports).push(exportName);
  13010. }
  13011. return { removedExports, renderedExports };
  13012. }
  13013. getSyntheticNamespace() {
  13014. if (this.syntheticNamespace === null) {
  13015. this.syntheticNamespace = undefined;
  13016. [this.syntheticNamespace] = this.getVariableForExportName(typeof this.info.syntheticNamedExports === 'string'
  13017. ? this.info.syntheticNamedExports
  13018. : 'default', { onlyExplicit: true });
  13019. }
  13020. if (!this.syntheticNamespace) {
  13021. return error(logSyntheticNamedExportsNeedNamespaceExport(this.id, this.info.syntheticNamedExports));
  13022. }
  13023. return this.syntheticNamespace;
  13024. }
  13025. getVariableForExportName(name, { importerForSideEffects, isExportAllSearch, onlyExplicit, searchedNamesAndModules } = EMPTY_OBJECT) {
  13026. if (name[0] === '*') {
  13027. if (name.length === 1) {
  13028. // export * from './other'
  13029. return [this.namespace];
  13030. }
  13031. // export * from 'external'
  13032. const module = this.graph.modulesById.get(name.slice(1));
  13033. return module.getVariableForExportName('*');
  13034. }
  13035. // export { foo } from './other'
  13036. const reexportDeclaration = this.reexportDescriptions.get(name);
  13037. if (reexportDeclaration) {
  13038. const [variable] = getVariableForExportNameRecursive(reexportDeclaration.module, reexportDeclaration.localName, importerForSideEffects, false, searchedNamesAndModules);
  13039. if (!variable) {
  13040. return this.error(logMissingExport(reexportDeclaration.localName, this.id, reexportDeclaration.module.id), reexportDeclaration.start);
  13041. }
  13042. if (importerForSideEffects) {
  13043. setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
  13044. if (this.info.moduleSideEffects) {
  13045. getOrCreate(importerForSideEffects.sideEffectDependenciesByVariable, variable, (getNewSet)).add(this);
  13046. }
  13047. }
  13048. return [variable];
  13049. }
  13050. const exportDeclaration = this.exports.get(name);
  13051. if (exportDeclaration) {
  13052. if (exportDeclaration === MISSING_EXPORT_SHIM_DESCRIPTION) {
  13053. return [this.exportShimVariable];
  13054. }
  13055. const name = exportDeclaration.localName;
  13056. const variable = this.traceVariable(name, {
  13057. importerForSideEffects,
  13058. searchedNamesAndModules
  13059. });
  13060. if (importerForSideEffects) {
  13061. setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
  13062. getOrCreate(importerForSideEffects.sideEffectDependenciesByVariable, variable, (getNewSet)).add(this);
  13063. }
  13064. return [variable];
  13065. }
  13066. if (onlyExplicit) {
  13067. return [null];
  13068. }
  13069. if (name !== 'default') {
  13070. const foundNamespaceReexport = this.namespaceReexportsByName.get(name) ??
  13071. this.getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules);
  13072. this.namespaceReexportsByName.set(name, foundNamespaceReexport);
  13073. if (foundNamespaceReexport[0]) {
  13074. return foundNamespaceReexport;
  13075. }
  13076. }
  13077. if (this.info.syntheticNamedExports) {
  13078. return [
  13079. getOrCreate(this.syntheticExports, name, () => new SyntheticNamedExportVariable(this.astContext, name, this.getSyntheticNamespace()))
  13080. ];
  13081. }
  13082. // we don't want to create shims when we are just
  13083. // probing export * modules for exports
  13084. if (!isExportAllSearch && this.options.shimMissingExports) {
  13085. this.shimMissingExport(name);
  13086. return [this.exportShimVariable];
  13087. }
  13088. return [null];
  13089. }
  13090. hasEffects() {
  13091. return this.info.moduleSideEffects === 'no-treeshake' || this.ast.hasCachedEffects();
  13092. }
  13093. include() {
  13094. const context = createInclusionContext();
  13095. if (this.ast.shouldBeIncluded(context))
  13096. this.ast.include(context, false);
  13097. }
  13098. includeAllExports(includeNamespaceMembers) {
  13099. if (!this.isExecuted) {
  13100. markModuleAndImpureDependenciesAsExecuted(this);
  13101. this.graph.needsTreeshakingPass = true;
  13102. }
  13103. for (const exportName of this.exports.keys()) {
  13104. if (includeNamespaceMembers || exportName !== this.info.syntheticNamedExports) {
  13105. const variable = this.getVariableForExportName(exportName)[0];
  13106. variable.deoptimizePath(UNKNOWN_PATH);
  13107. if (!variable.included) {
  13108. this.includeVariable(variable);
  13109. }
  13110. }
  13111. }
  13112. for (const name of this.getReexports()) {
  13113. const [variable] = this.getVariableForExportName(name);
  13114. if (variable) {
  13115. variable.deoptimizePath(UNKNOWN_PATH);
  13116. if (!variable.included) {
  13117. this.includeVariable(variable);
  13118. }
  13119. if (variable instanceof ExternalVariable) {
  13120. variable.module.reexported = true;
  13121. }
  13122. }
  13123. }
  13124. if (includeNamespaceMembers) {
  13125. this.namespace.setMergedNamespaces(this.includeAndGetAdditionalMergedNamespaces());
  13126. }
  13127. }
  13128. includeAllInBundle() {
  13129. this.ast.include(createInclusionContext(), true);
  13130. this.includeAllExports(false);
  13131. }
  13132. includeExportsByNames(names) {
  13133. if (!this.isExecuted) {
  13134. markModuleAndImpureDependenciesAsExecuted(this);
  13135. this.graph.needsTreeshakingPass = true;
  13136. }
  13137. let includeNamespaceMembers = false;
  13138. for (const name of names) {
  13139. const variable = this.getVariableForExportName(name)[0];
  13140. if (variable) {
  13141. variable.deoptimizePath(UNKNOWN_PATH);
  13142. if (!variable.included) {
  13143. this.includeVariable(variable);
  13144. }
  13145. }
  13146. if (!this.exports.has(name) && !this.reexportDescriptions.has(name)) {
  13147. includeNamespaceMembers = true;
  13148. }
  13149. }
  13150. if (includeNamespaceMembers) {
  13151. this.namespace.setMergedNamespaces(this.includeAndGetAdditionalMergedNamespaces());
  13152. }
  13153. }
  13154. isIncluded() {
  13155. // Modules where this.ast is missing have been loaded via this.load and are
  13156. // not yet fully processed, hence they cannot be included.
  13157. return (this.ast &&
  13158. (this.ast.included ||
  13159. this.namespace.included ||
  13160. this.importedFromNotTreeshaken ||
  13161. this.exportShimVariable.included));
  13162. }
  13163. linkImports() {
  13164. this.addModulesToImportDescriptions(this.importDescriptions);
  13165. this.addModulesToImportDescriptions(this.reexportDescriptions);
  13166. const externalExportAllModules = [];
  13167. for (const source of this.exportAllSources) {
  13168. const module = this.graph.modulesById.get(this.resolvedIds[source].id);
  13169. if (module instanceof ExternalModule) {
  13170. externalExportAllModules.push(module);
  13171. continue;
  13172. }
  13173. this.exportAllModules.push(module);
  13174. }
  13175. this.exportAllModules.push(...externalExportAllModules);
  13176. }
  13177. log(level, properties, pos) {
  13178. this.addLocationToLogProps(properties, pos);
  13179. this.options.onLog(level, properties);
  13180. }
  13181. render(options) {
  13182. const source = this.magicString.clone();
  13183. this.ast.render(source, options);
  13184. source.trim();
  13185. const { usesTopLevelAwait } = this.astContext;
  13186. if (usesTopLevelAwait && options.format !== 'es' && options.format !== 'system') {
  13187. return error(logInvalidFormatForTopLevelAwait(this.id, options.format));
  13188. }
  13189. return { source, usesTopLevelAwait };
  13190. }
  13191. setSource({ ast, code, customTransformCache, originalCode, originalSourcemap, resolvedIds, sourcemapChain, transformDependencies, transformFiles, ...moduleOptions }) {
  13192. timeStart('generate ast', 3);
  13193. this.info.code = code;
  13194. this.originalCode = originalCode;
  13195. // We need to call decodedSourcemap on the input in case they were hydrated from json in the cache and don't
  13196. // have the lazy evaluation cache configured. Right now this isn't enforced by the type system because the
  13197. // RollupCache stores `ExistingDecodedSourcemap` instead of `ExistingRawSourcemap`
  13198. this.originalSourcemap = decodedSourcemap(originalSourcemap);
  13199. this.sourcemapChain = sourcemapChain.map(mapOrMissing => mapOrMissing.missing ? mapOrMissing : decodedSourcemap(mapOrMissing));
  13200. // If coming from cache and this value is already fully decoded, we want to re-encode here to save memory.
  13201. resetSourcemapCache(this.originalSourcemap, this.sourcemapChain);
  13202. if (transformFiles) {
  13203. this.transformFiles = transformFiles;
  13204. }
  13205. this.transformDependencies = transformDependencies;
  13206. this.customTransformCache = customTransformCache;
  13207. this.updateOptions(moduleOptions);
  13208. const moduleAst = ast ?? this.tryParse();
  13209. timeEnd('generate ast', 3);
  13210. timeStart('analyze ast', 3);
  13211. this.resolvedIds = resolvedIds ?? Object.create(null);
  13212. // By default, `id` is the file name. Custom resolvers and loaders
  13213. // can change that, but it makes sense to use it for the source file name
  13214. const fileName = this.id;
  13215. this.magicString = new MagicString(code, {
  13216. filename: (this.excludeFromSourcemap ? null : fileName),
  13217. indentExclusionRanges: []
  13218. });
  13219. this.astContext = {
  13220. addDynamicImport: this.addDynamicImport.bind(this),
  13221. addExport: this.addExport.bind(this),
  13222. addImport: this.addImport.bind(this),
  13223. addImportMeta: this.addImportMeta.bind(this),
  13224. code,
  13225. deoptimizationTracker: this.graph.deoptimizationTracker,
  13226. error: this.error.bind(this),
  13227. fileName,
  13228. getExports: this.getExports.bind(this),
  13229. getModuleExecIndex: () => this.execIndex,
  13230. getModuleName: this.basename.bind(this),
  13231. getNodeConstructor: (name) => nodeConstructors[name] || nodeConstructors.UnknownNode,
  13232. getReexports: this.getReexports.bind(this),
  13233. importDescriptions: this.importDescriptions,
  13234. includeAllExports: () => this.includeAllExports(true),
  13235. includeDynamicImport: this.includeDynamicImport.bind(this),
  13236. includeVariableInModule: this.includeVariableInModule.bind(this),
  13237. log: this.log.bind(this),
  13238. magicString: this.magicString,
  13239. manualPureFunctions: this.graph.pureFunctions,
  13240. module: this,
  13241. moduleContext: this.context,
  13242. options: this.options,
  13243. requestTreeshakingPass: () => (this.graph.needsTreeshakingPass = true),
  13244. traceExport: (name) => this.getVariableForExportName(name)[0],
  13245. traceVariable: this.traceVariable.bind(this),
  13246. usesTopLevelAwait: false
  13247. };
  13248. this.scope = new ModuleScope(this.graph.scope, this.astContext);
  13249. this.namespace = new NamespaceVariable(this.astContext);
  13250. this.ast = new Program(moduleAst, { context: this.astContext, type: 'Module' }, this.scope);
  13251. // Assign AST directly if has existing one as there's no way to drop it from memory.
  13252. // If cache is enabled, also assign directly as otherwise it takes more CPU and memory to re-compute.
  13253. if (ast || this.options.cache !== false) {
  13254. this.info.ast = moduleAst;
  13255. }
  13256. else {
  13257. // Make lazy and apply LRU cache to not hog the memory
  13258. Object.defineProperty(this.info, 'ast', {
  13259. get: () => {
  13260. if (this.graph.astLru.has(fileName)) {
  13261. return this.graph.astLru.get(fileName);
  13262. }
  13263. else {
  13264. const parsedAst = this.tryParse();
  13265. this.graph.astLru.set(fileName, parsedAst);
  13266. return parsedAst;
  13267. }
  13268. }
  13269. });
  13270. }
  13271. timeEnd('analyze ast', 3);
  13272. }
  13273. toJSON() {
  13274. return {
  13275. assertions: this.info.assertions,
  13276. ast: this.info.ast,
  13277. code: this.info.code,
  13278. customTransformCache: this.customTransformCache,
  13279. // eslint-disable-next-line unicorn/prefer-spread
  13280. dependencies: Array.from(this.dependencies, getId),
  13281. id: this.id,
  13282. meta: this.info.meta,
  13283. moduleSideEffects: this.info.moduleSideEffects,
  13284. originalCode: this.originalCode,
  13285. originalSourcemap: this.originalSourcemap,
  13286. resolvedIds: this.resolvedIds,
  13287. sourcemapChain: this.sourcemapChain,
  13288. syntheticNamedExports: this.info.syntheticNamedExports,
  13289. transformDependencies: this.transformDependencies,
  13290. transformFiles: this.transformFiles
  13291. };
  13292. }
  13293. traceVariable(name, { importerForSideEffects, isExportAllSearch, searchedNamesAndModules } = EMPTY_OBJECT) {
  13294. const localVariable = this.scope.variables.get(name);
  13295. if (localVariable) {
  13296. return localVariable;
  13297. }
  13298. const importDescription = this.importDescriptions.get(name);
  13299. if (importDescription) {
  13300. const otherModule = importDescription.module;
  13301. if (otherModule instanceof Module && importDescription.name === '*') {
  13302. return otherModule.namespace;
  13303. }
  13304. const [declaration] = getVariableForExportNameRecursive(otherModule, importDescription.name, importerForSideEffects || this, isExportAllSearch, searchedNamesAndModules);
  13305. if (!declaration) {
  13306. return this.error(logMissingExport(importDescription.name, this.id, otherModule.id), importDescription.start);
  13307. }
  13308. return declaration;
  13309. }
  13310. return null;
  13311. }
  13312. updateOptions({ meta, moduleSideEffects, syntheticNamedExports }) {
  13313. if (moduleSideEffects != null) {
  13314. this.info.moduleSideEffects = moduleSideEffects;
  13315. }
  13316. if (syntheticNamedExports != null) {
  13317. this.info.syntheticNamedExports = syntheticNamedExports;
  13318. }
  13319. if (meta != null) {
  13320. Object.assign(this.info.meta, meta);
  13321. }
  13322. }
  13323. addDynamicImport(node) {
  13324. let argument = node.source;
  13325. if (argument instanceof TemplateLiteral) {
  13326. if (argument.quasis.length === 1 && argument.quasis[0].value.cooked) {
  13327. argument = argument.quasis[0].value.cooked;
  13328. }
  13329. }
  13330. else if (argument instanceof Literal && typeof argument.value === 'string') {
  13331. argument = argument.value;
  13332. }
  13333. this.dynamicImports.push({ argument, id: null, node, resolution: null });
  13334. }
  13335. addExport(node) {
  13336. if (node instanceof ExportDefaultDeclaration) {
  13337. // export default foo;
  13338. this.exports.set('default', {
  13339. identifier: node.variable.getAssignedVariableName(),
  13340. localName: 'default'
  13341. });
  13342. }
  13343. else if (node instanceof ExportAllDeclaration) {
  13344. const source = node.source.value;
  13345. this.addSource(source, node);
  13346. if (node.exported) {
  13347. // export * as name from './other'
  13348. const name = node.exported.name;
  13349. this.reexportDescriptions.set(name, {
  13350. localName: '*',
  13351. module: null,
  13352. source,
  13353. start: node.start
  13354. });
  13355. }
  13356. else {
  13357. // export * from './other'
  13358. this.exportAllSources.add(source);
  13359. }
  13360. }
  13361. else if (node.source instanceof Literal) {
  13362. // export { name } from './other'
  13363. const source = node.source.value;
  13364. this.addSource(source, node);
  13365. for (const { exported, local, start } of node.specifiers) {
  13366. const name = exported instanceof Literal ? exported.value : exported.name;
  13367. this.reexportDescriptions.set(name, {
  13368. localName: local instanceof Literal ? local.value : local.name,
  13369. module: null,
  13370. source,
  13371. start
  13372. });
  13373. }
  13374. }
  13375. else if (node.declaration) {
  13376. const declaration = node.declaration;
  13377. if (declaration instanceof VariableDeclaration) {
  13378. // export var { foo, bar } = ...
  13379. // export var foo = 1, bar = 2;
  13380. for (const declarator of declaration.declarations) {
  13381. for (const localName of extractAssignedNames(declarator.id)) {
  13382. this.exports.set(localName, { identifier: null, localName });
  13383. }
  13384. }
  13385. }
  13386. else {
  13387. // export function foo () {}
  13388. const localName = declaration.id.name;
  13389. this.exports.set(localName, { identifier: null, localName });
  13390. }
  13391. }
  13392. else {
  13393. // export { foo, bar, baz }
  13394. for (const { local, exported } of node.specifiers) {
  13395. // except for reexports, local must be an Identifier
  13396. const localName = local.name;
  13397. const exportedName = exported instanceof Identifier ? exported.name : exported.value;
  13398. this.exports.set(exportedName, { identifier: null, localName });
  13399. }
  13400. }
  13401. }
  13402. addImport(node) {
  13403. const source = node.source.value;
  13404. this.addSource(source, node);
  13405. for (const specifier of node.specifiers) {
  13406. const name = specifier instanceof ImportDefaultSpecifier
  13407. ? 'default'
  13408. : specifier instanceof ImportNamespaceSpecifier
  13409. ? '*'
  13410. : specifier.imported instanceof Identifier
  13411. ? specifier.imported.name
  13412. : specifier.imported.value;
  13413. this.importDescriptions.set(specifier.local.name, {
  13414. module: null,
  13415. name,
  13416. source,
  13417. start: specifier.start
  13418. });
  13419. }
  13420. }
  13421. addImportMeta(node) {
  13422. this.importMetas.push(node);
  13423. }
  13424. addLocationToLogProps(properties, pos) {
  13425. properties.id = this.id;
  13426. properties.pos = pos;
  13427. let code = this.info.code;
  13428. const location = locate(code, pos, { offsetLine: 1 });
  13429. if (location) {
  13430. let { column, line } = location;
  13431. try {
  13432. ({ column, line } = getOriginalLocation(this.sourcemapChain, { column, line }));
  13433. code = this.originalCode;
  13434. }
  13435. catch (error_) {
  13436. this.options.onLog(LOGLEVEL_WARN, logInvalidSourcemapForError(error_, this.id, column, line, pos));
  13437. }
  13438. augmentCodeLocation(properties, { column, line }, code, this.id);
  13439. }
  13440. }
  13441. addModulesToImportDescriptions(importDescription) {
  13442. for (const specifier of importDescription.values()) {
  13443. const { id } = this.resolvedIds[specifier.source];
  13444. specifier.module = this.graph.modulesById.get(id);
  13445. }
  13446. }
  13447. addRelevantSideEffectDependencies(relevantDependencies, necessaryDependencies, alwaysCheckedDependencies) {
  13448. const handledDependencies = new Set();
  13449. const addSideEffectDependencies = (possibleDependencies) => {
  13450. for (const dependency of possibleDependencies) {
  13451. if (handledDependencies.has(dependency)) {
  13452. continue;
  13453. }
  13454. handledDependencies.add(dependency);
  13455. if (necessaryDependencies.has(dependency)) {
  13456. relevantDependencies.add(dependency);
  13457. continue;
  13458. }
  13459. if (!(dependency.info.moduleSideEffects || alwaysCheckedDependencies.has(dependency))) {
  13460. continue;
  13461. }
  13462. if (dependency instanceof ExternalModule || dependency.hasEffects()) {
  13463. relevantDependencies.add(dependency);
  13464. continue;
  13465. }
  13466. addSideEffectDependencies(dependency.dependencies);
  13467. }
  13468. };
  13469. addSideEffectDependencies(this.dependencies);
  13470. addSideEffectDependencies(alwaysCheckedDependencies);
  13471. }
  13472. addSource(source, declaration) {
  13473. const parsedAssertions = getAssertionsFromImportExportDeclaration(declaration.assertions);
  13474. const existingAssertions = this.sourcesWithAssertions.get(source);
  13475. if (existingAssertions) {
  13476. if (doAssertionsDiffer(existingAssertions, parsedAssertions)) {
  13477. this.log(LOGLEVEL_WARN, logInconsistentImportAssertions(existingAssertions, parsedAssertions, source, this.id), declaration.start);
  13478. }
  13479. }
  13480. else {
  13481. this.sourcesWithAssertions.set(source, parsedAssertions);
  13482. }
  13483. }
  13484. getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules) {
  13485. let foundSyntheticDeclaration = null;
  13486. const foundInternalDeclarations = new Map();
  13487. const foundExternalDeclarations = new Set();
  13488. for (const module of this.exportAllModules) {
  13489. // Synthetic namespaces should not hide "regular" exports of the same name
  13490. if (module.info.syntheticNamedExports === name) {
  13491. continue;
  13492. }
  13493. const [variable, indirectExternal] = getVariableForExportNameRecursive(module, name, importerForSideEffects, true,
  13494. // We are creating a copy to handle the case where the same binding is
  13495. // imported through different namespace reexports gracefully
  13496. copyNameToModulesMap(searchedNamesAndModules));
  13497. if (module instanceof ExternalModule || indirectExternal) {
  13498. foundExternalDeclarations.add(variable);
  13499. }
  13500. else if (variable instanceof SyntheticNamedExportVariable) {
  13501. if (!foundSyntheticDeclaration) {
  13502. foundSyntheticDeclaration = variable;
  13503. }
  13504. }
  13505. else if (variable) {
  13506. foundInternalDeclarations.set(variable, module);
  13507. }
  13508. }
  13509. if (foundInternalDeclarations.size > 0) {
  13510. const foundDeclarationList = [...foundInternalDeclarations];
  13511. const usedDeclaration = foundDeclarationList[0][0];
  13512. if (foundDeclarationList.length === 1) {
  13513. return [usedDeclaration];
  13514. }
  13515. this.options.onLog(LOGLEVEL_WARN, logNamespaceConflict(name, this.id, foundDeclarationList.map(([, module]) => module.id)));
  13516. // TODO we are pretending it was not found while it should behave like "undefined"
  13517. return [null];
  13518. }
  13519. if (foundExternalDeclarations.size > 0) {
  13520. const foundDeclarationList = [...foundExternalDeclarations];
  13521. const usedDeclaration = foundDeclarationList[0];
  13522. if (foundDeclarationList.length > 1) {
  13523. this.options.onLog(LOGLEVEL_WARN, logAmbiguousExternalNamespaces(name, this.id, usedDeclaration.module.id, foundDeclarationList.map(declaration => declaration.module.id)));
  13524. }
  13525. return [usedDeclaration, true];
  13526. }
  13527. if (foundSyntheticDeclaration) {
  13528. return [foundSyntheticDeclaration];
  13529. }
  13530. return [null];
  13531. }
  13532. includeAndGetAdditionalMergedNamespaces() {
  13533. const externalNamespaces = new Set();
  13534. const syntheticNamespaces = new Set();
  13535. for (const module of [this, ...this.exportAllModules]) {
  13536. if (module instanceof ExternalModule) {
  13537. const [externalVariable] = module.getVariableForExportName('*');
  13538. externalVariable.include();
  13539. this.includedImports.add(externalVariable);
  13540. externalNamespaces.add(externalVariable);
  13541. }
  13542. else if (module.info.syntheticNamedExports) {
  13543. const syntheticNamespace = module.getSyntheticNamespace();
  13544. syntheticNamespace.include();
  13545. this.includedImports.add(syntheticNamespace);
  13546. syntheticNamespaces.add(syntheticNamespace);
  13547. }
  13548. }
  13549. return [...syntheticNamespaces, ...externalNamespaces];
  13550. }
  13551. includeDynamicImport(node) {
  13552. const resolution = this.dynamicImports.find(dynamicImport => dynamicImport.node === node).resolution;
  13553. if (resolution instanceof Module) {
  13554. resolution.includedDynamicImporters.push(this);
  13555. const importedNames = this.options.treeshake
  13556. ? node.getDeterministicImportedNames()
  13557. : undefined;
  13558. if (importedNames) {
  13559. resolution.includeExportsByNames(importedNames);
  13560. }
  13561. else {
  13562. resolution.includeAllExports(true);
  13563. }
  13564. }
  13565. }
  13566. includeVariable(variable) {
  13567. const variableModule = variable.module;
  13568. if (variable.included) {
  13569. if (variableModule instanceof Module && variableModule !== this) {
  13570. getAndExtendSideEffectModules(variable, this);
  13571. }
  13572. }
  13573. else {
  13574. variable.include();
  13575. this.graph.needsTreeshakingPass = true;
  13576. if (variableModule instanceof Module) {
  13577. if (!variableModule.isExecuted) {
  13578. markModuleAndImpureDependenciesAsExecuted(variableModule);
  13579. }
  13580. if (variableModule !== this) {
  13581. const sideEffectModules = getAndExtendSideEffectModules(variable, this);
  13582. for (const module of sideEffectModules) {
  13583. if (!module.isExecuted) {
  13584. markModuleAndImpureDependenciesAsExecuted(module);
  13585. }
  13586. }
  13587. }
  13588. }
  13589. }
  13590. }
  13591. includeVariableInModule(variable) {
  13592. this.includeVariable(variable);
  13593. const variableModule = variable.module;
  13594. if (variableModule && variableModule !== this) {
  13595. this.includedImports.add(variable);
  13596. }
  13597. }
  13598. shimMissingExport(name) {
  13599. this.options.onLog(LOGLEVEL_WARN, logShimmedExport(this.id, name));
  13600. this.exports.set(name, MISSING_EXPORT_SHIM_DESCRIPTION);
  13601. }
  13602. tryParse() {
  13603. try {
  13604. return this.graph.contextParse(this.info.code);
  13605. }
  13606. catch (error_) {
  13607. return this.error(logParseError(error_, this.id), error_.pos);
  13608. }
  13609. }
  13610. }
  13611. // if there is a cyclic import in the reexport chain, we should not
  13612. // import from the original module but from the cyclic module to not
  13613. // mess up execution order.
  13614. function setAlternativeExporterIfCyclic(variable, importer, reexporter) {
  13615. if (variable.module instanceof Module && variable.module !== reexporter) {
  13616. const exporterCycles = variable.module.cycles;
  13617. if (exporterCycles.size > 0) {
  13618. const importerCycles = reexporter.cycles;
  13619. for (const cycleSymbol of importerCycles) {
  13620. if (exporterCycles.has(cycleSymbol)) {
  13621. importer.alternativeReexportModules.set(variable, reexporter);
  13622. break;
  13623. }
  13624. }
  13625. }
  13626. }
  13627. }
  13628. const copyNameToModulesMap = (searchedNamesAndModules) => searchedNamesAndModules &&
  13629. // eslint-disable-next-line unicorn/prefer-spread
  13630. new Map(Array.from(searchedNamesAndModules, ([name, modules]) => [name, new Set(modules)]));
  13631. function removeJsExtension(name) {
  13632. return name.endsWith('.js') ? name.slice(0, -3) : name;
  13633. }
  13634. function getCompleteAmdId(options, chunkId) {
  13635. if (options.autoId) {
  13636. return `${options.basePath ? options.basePath + '/' : ''}${removeJsExtension(chunkId)}`;
  13637. }
  13638. return options.id ?? '';
  13639. }
  13640. function getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, mechanism = 'return ') {
  13641. const { _, getDirectReturnFunction, getFunctionIntro, getPropertyAccess, n, s } = snippets;
  13642. if (!namedExportsMode) {
  13643. return `${n}${n}${mechanism}${getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings, getPropertyAccess)};`;
  13644. }
  13645. let exportBlock = '';
  13646. for (const { defaultVariableName, importPath, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  13647. if (reexports && namedExportsMode) {
  13648. for (const specifier of reexports) {
  13649. if (specifier.reexported !== '*') {
  13650. const importName = getReexportedImportName(name, specifier.imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, importPath, externalLiveBindings, getPropertyAccess);
  13651. if (exportBlock)
  13652. exportBlock += n;
  13653. if (specifier.imported !== '*' && specifier.needsLiveBinding) {
  13654. const [left, right] = getDirectReturnFunction([], {
  13655. functionReturn: true,
  13656. lineBreakIndent: null,
  13657. name: null
  13658. });
  13659. exportBlock +=
  13660. `Object.defineProperty(exports,${_}'${specifier.reexported}',${_}{${n}` +
  13661. `${t}enumerable:${_}true,${n}` +
  13662. `${t}get:${_}${left}${importName}${right}${n}});`;
  13663. }
  13664. else {
  13665. exportBlock += `exports${getPropertyAccess(specifier.reexported)}${_}=${_}${importName};`;
  13666. }
  13667. }
  13668. }
  13669. }
  13670. }
  13671. for (const { exported, local } of exports) {
  13672. const lhs = `exports${getPropertyAccess(exported)}`;
  13673. const rhs = local;
  13674. if (lhs !== rhs) {
  13675. if (exportBlock)
  13676. exportBlock += n;
  13677. exportBlock += `${lhs}${_}=${_}${rhs};`;
  13678. }
  13679. }
  13680. for (const { name, reexports } of dependencies) {
  13681. if (reexports && namedExportsMode) {
  13682. for (const specifier of reexports) {
  13683. if (specifier.reexported === '*') {
  13684. if (exportBlock)
  13685. exportBlock += n;
  13686. const copyPropertyIfNecessary = `{${n}${t}if${_}(k${_}!==${_}'default'${_}&&${_}!Object.prototype.hasOwnProperty.call(exports,${_}k))${_}${getDefineProperty(name, specifier.needsLiveBinding, t, snippets)}${s}${n}}`;
  13687. exportBlock += `Object.keys(${name}).forEach(${getFunctionIntro(['k'], {
  13688. isAsync: false,
  13689. name: null
  13690. })}${copyPropertyIfNecessary});`;
  13691. }
  13692. }
  13693. }
  13694. }
  13695. if (exportBlock) {
  13696. return `${n}${n}${exportBlock}`;
  13697. }
  13698. return '';
  13699. }
  13700. function getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings, getPropertyAccess) {
  13701. if (exports.length > 0) {
  13702. return exports[0].local;
  13703. }
  13704. else {
  13705. for (const { defaultVariableName, importPath, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  13706. if (reexports) {
  13707. return getReexportedImportName(name, reexports[0].imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, importPath, externalLiveBindings, getPropertyAccess);
  13708. }
  13709. }
  13710. }
  13711. }
  13712. function getReexportedImportName(moduleVariableName, imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, moduleId, externalLiveBindings, getPropertyAccess) {
  13713. if (imported === 'default') {
  13714. if (!isChunk) {
  13715. const moduleInterop = interop(moduleId);
  13716. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  13717. ? defaultVariableName
  13718. : moduleVariableName;
  13719. return isDefaultAProperty(moduleInterop, externalLiveBindings)
  13720. ? `${variableName}${getPropertyAccess('default')}`
  13721. : variableName;
  13722. }
  13723. return depNamedExportsMode
  13724. ? `${moduleVariableName}${getPropertyAccess('default')}`
  13725. : moduleVariableName;
  13726. }
  13727. if (imported === '*') {
  13728. return (isChunk ? !depNamedExportsMode : namespaceInteropHelpersByInteropType[interop(moduleId)])
  13729. ? namespaceVariableName
  13730. : moduleVariableName;
  13731. }
  13732. return `${moduleVariableName}${getPropertyAccess(imported)}`;
  13733. }
  13734. function getEsModuleValue(getObject) {
  13735. return getObject([['value', 'true']], {
  13736. lineBreakIndent: null
  13737. });
  13738. }
  13739. function getNamespaceMarkers(hasNamedExports, addEsModule, addNamespaceToStringTag, { _, getObject }) {
  13740. if (hasNamedExports) {
  13741. if (addEsModule) {
  13742. if (addNamespaceToStringTag) {
  13743. return `Object.defineProperties(exports,${_}${getObject([
  13744. ['__esModule', getEsModuleValue(getObject)],
  13745. [null, `[Symbol.toStringTag]:${_}${getToStringTagValue(getObject)}`]
  13746. ], {
  13747. lineBreakIndent: null
  13748. })});`;
  13749. }
  13750. return `Object.defineProperty(exports,${_}'__esModule',${_}${getEsModuleValue(getObject)});`;
  13751. }
  13752. if (addNamespaceToStringTag) {
  13753. return `Object.defineProperty(exports,${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)});`;
  13754. }
  13755. }
  13756. return '';
  13757. }
  13758. const getDefineProperty = (name, needsLiveBinding, t, { _, getDirectReturnFunction, n }) => {
  13759. if (needsLiveBinding) {
  13760. const [left, right] = getDirectReturnFunction([], {
  13761. functionReturn: true,
  13762. lineBreakIndent: null,
  13763. name: null
  13764. });
  13765. return (`Object.defineProperty(exports,${_}k,${_}{${n}` +
  13766. `${t}${t}enumerable:${_}true,${n}` +
  13767. `${t}${t}get:${_}${left}${name}[k]${right}${n}${t}})`);
  13768. }
  13769. return `exports[k]${_}=${_}${name}[k]`;
  13770. };
  13771. function getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, indent, snippets) {
  13772. const { _, cnst, n } = snippets;
  13773. const neededInteropHelpers = new Set();
  13774. const interopStatements = [];
  13775. const addInteropStatement = (helperVariableName, helper, dependencyVariableName) => {
  13776. neededInteropHelpers.add(helper);
  13777. interopStatements.push(`${cnst} ${helperVariableName}${_}=${_}/*#__PURE__*/${helper}(${dependencyVariableName});`);
  13778. };
  13779. for (const { defaultVariableName, imports, importPath, isChunk, name, namedExportsMode, namespaceVariableName, reexports } of dependencies) {
  13780. if (isChunk) {
  13781. for (const { imported, reexported } of [
  13782. ...(imports || []),
  13783. ...(reexports || [])
  13784. ]) {
  13785. if (imported === '*' && reexported !== '*') {
  13786. if (!namedExportsMode) {
  13787. addInteropStatement(namespaceVariableName, INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE, name);
  13788. }
  13789. break;
  13790. }
  13791. }
  13792. }
  13793. else {
  13794. const moduleInterop = interop(importPath);
  13795. let hasDefault = false;
  13796. let hasNamespace = false;
  13797. for (const { imported, reexported } of [
  13798. ...(imports || []),
  13799. ...(reexports || [])
  13800. ]) {
  13801. let helper;
  13802. let variableName;
  13803. if (imported === 'default') {
  13804. if (!hasDefault) {
  13805. hasDefault = true;
  13806. if (defaultVariableName !== namespaceVariableName) {
  13807. variableName = defaultVariableName;
  13808. helper = defaultInteropHelpersByInteropType[moduleInterop];
  13809. }
  13810. }
  13811. }
  13812. else if (imported === '*' && reexported !== '*' && !hasNamespace) {
  13813. hasNamespace = true;
  13814. helper = namespaceInteropHelpersByInteropType[moduleInterop];
  13815. variableName = namespaceVariableName;
  13816. }
  13817. if (helper) {
  13818. addInteropStatement(variableName, helper, name);
  13819. }
  13820. }
  13821. }
  13822. }
  13823. return `${getHelpersBlock(neededInteropHelpers, accessedGlobals, indent, snippets, externalLiveBindings, freeze, namespaceToStringTag)}${interopStatements.length > 0 ? `${interopStatements.join(n)}${n}${n}` : ''}`;
  13824. }
  13825. function addJsExtension(name) {
  13826. return name.endsWith('.js') ? name : name + '.js';
  13827. }
  13828. // AMD resolution will only respect the AMD baseUrl if the .js extension is omitted.
  13829. // The assumption is that this makes sense for all relative ids:
  13830. // https://requirejs.org/docs/api.html#jsfiles
  13831. function updateExtensionForRelativeAmdId(id, forceJsExtensionForImports) {
  13832. if (id[0] !== '.') {
  13833. return id;
  13834. }
  13835. return forceJsExtensionForImports ? addJsExtension(id) : removeJsExtension(id);
  13836. }
  13837. const require$$0 = [
  13838. "assert",
  13839. "async_hooks",
  13840. "buffer",
  13841. "child_process",
  13842. "cluster",
  13843. "console",
  13844. "constants",
  13845. "crypto",
  13846. "dgram",
  13847. "diagnostics_channel",
  13848. "dns",
  13849. "domain",
  13850. "events",
  13851. "fs",
  13852. "http",
  13853. "http2",
  13854. "https",
  13855. "inspector",
  13856. "module",
  13857. "net",
  13858. "os",
  13859. "path",
  13860. "perf_hooks",
  13861. "process",
  13862. "punycode",
  13863. "querystring",
  13864. "readline",
  13865. "repl",
  13866. "stream",
  13867. "string_decoder",
  13868. "timers",
  13869. "tls",
  13870. "trace_events",
  13871. "tty",
  13872. "url",
  13873. "util",
  13874. "v8",
  13875. "vm",
  13876. "wasi",
  13877. "worker_threads",
  13878. "zlib"
  13879. ];
  13880. var _static = require$$0;
  13881. const builtinModules = /*@__PURE__*/getDefaultExportFromCjs(_static);
  13882. const nodeBuiltins = new Set([
  13883. ...builtinModules,
  13884. // TODO
  13885. // remove once builtin-modules includes PR: https://github.com/sindresorhus/builtin-modules/pull/17
  13886. 'assert/strict',
  13887. 'dns/promises',
  13888. 'fs/promises',
  13889. 'path/posix',
  13890. 'path/win32',
  13891. 'readline/promises',
  13892. 'stream/consumers',
  13893. 'stream/promises',
  13894. 'stream/web',
  13895. 'timers/promises',
  13896. 'util/types'
  13897. ]);
  13898. function warnOnBuiltins(log, dependencies) {
  13899. const externalBuiltins = dependencies
  13900. .map(({ importPath }) => importPath)
  13901. .filter(importPath => nodeBuiltins.has(importPath) || importPath.startsWith('node:'));
  13902. if (externalBuiltins.length === 0)
  13903. return;
  13904. log(LOGLEVEL_WARN, logMissingNodeBuiltins(externalBuiltins));
  13905. }
  13906. function amd(magicString, { accessedGlobals, dependencies, exports, hasDefaultExport, hasExports, id, indent: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, log, outro, snippets }, { amd, esModule, externalLiveBindings, freeze, interop, namespaceToStringTag, strict }) {
  13907. warnOnBuiltins(log, dependencies);
  13908. const deps = dependencies.map(m => `'${updateExtensionForRelativeAmdId(m.importPath, amd.forceJsExtensionForImports)}'`);
  13909. const parameters = dependencies.map(m => m.name);
  13910. const { n, getNonArrowFunctionIntro, _ } = snippets;
  13911. if (namedExportsMode && hasExports) {
  13912. parameters.unshift(`exports`);
  13913. deps.unshift(`'exports'`);
  13914. }
  13915. if (accessedGlobals.has('require')) {
  13916. parameters.unshift('require');
  13917. deps.unshift(`'require'`);
  13918. }
  13919. if (accessedGlobals.has('module')) {
  13920. parameters.unshift('module');
  13921. deps.unshift(`'module'`);
  13922. }
  13923. const completeAmdId = getCompleteAmdId(amd, id);
  13924. const defineParameters = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
  13925. (deps.length > 0 ? `[${deps.join(`,${_}`)}],${_}` : ``);
  13926. const useStrict = strict ? `${_}'use strict';` : '';
  13927. magicString.prepend(`${intro}${getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets)}`);
  13928. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings);
  13929. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && (esModule === true || (esModule === 'if-default-prop' && hasDefaultExport)), isModuleFacade && namespaceToStringTag, snippets);
  13930. if (namespaceMarkers) {
  13931. namespaceMarkers = n + n + namespaceMarkers;
  13932. }
  13933. magicString
  13934. .append(`${exportBlock}${namespaceMarkers}${outro}`)
  13935. .indent(t)
  13936. // factory function should be wrapped by parentheses to avoid lazy parsing,
  13937. // cf. https://v8.dev/blog/preparser#pife
  13938. .prepend(`${amd.define}(${defineParameters}(${getNonArrowFunctionIntro(parameters, {
  13939. isAsync: false,
  13940. name: null
  13941. })}{${useStrict}${n}${n}`)
  13942. .append(`${n}${n}}));`);
  13943. }
  13944. function cjs(magicString, { accessedGlobals, dependencies, exports, hasDefaultExport, hasExports, indent: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, outro, snippets }, { compact, esModule, externalLiveBindings, freeze, interop, namespaceToStringTag, strict }) {
  13945. const { _, n } = snippets;
  13946. const useStrict = strict ? `'use strict';${n}${n}` : '';
  13947. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && (esModule === true || (esModule === 'if-default-prop' && hasDefaultExport)), isModuleFacade && namespaceToStringTag, snippets);
  13948. if (namespaceMarkers) {
  13949. namespaceMarkers += n + n;
  13950. }
  13951. const importBlock = getImportBlock$1(dependencies, snippets, compact);
  13952. const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets);
  13953. magicString.prepend(`${useStrict}${intro}${namespaceMarkers}${importBlock}${interopBlock}`);
  13954. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, `module.exports${_}=${_}`);
  13955. magicString.append(`${exportBlock}${outro}`);
  13956. }
  13957. function getImportBlock$1(dependencies, { _, cnst, n }, compact) {
  13958. let importBlock = '';
  13959. let definingVariable = false;
  13960. for (const { importPath, name, reexports, imports } of dependencies) {
  13961. if (!reexports && !imports) {
  13962. if (importBlock) {
  13963. importBlock += compact && !definingVariable ? ',' : `;${n}`;
  13964. }
  13965. definingVariable = false;
  13966. importBlock += `require('${importPath}')`;
  13967. }
  13968. else {
  13969. importBlock += compact && definingVariable ? ',' : `${importBlock ? `;${n}` : ''}${cnst} `;
  13970. definingVariable = true;
  13971. importBlock += `${name}${_}=${_}require('${importPath}')`;
  13972. }
  13973. }
  13974. if (importBlock) {
  13975. return `${importBlock};${n}${n}`;
  13976. }
  13977. return '';
  13978. }
  13979. function es(magicString, { accessedGlobals, indent: t, intro, outro, dependencies, exports, snippets }, { externalLiveBindings, freeze, namespaceToStringTag }) {
  13980. const { n } = snippets;
  13981. const importBlock = getImportBlock(dependencies, snippets);
  13982. if (importBlock.length > 0)
  13983. intro += importBlock.join(n) + n + n;
  13984. intro += getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, namespaceToStringTag);
  13985. if (intro)
  13986. magicString.prepend(intro);
  13987. const exportBlock = getExportBlock(exports, snippets);
  13988. if (exportBlock.length > 0)
  13989. magicString.append(n + n + exportBlock.join(n).trim());
  13990. if (outro)
  13991. magicString.append(outro);
  13992. magicString.trim();
  13993. }
  13994. function getImportBlock(dependencies, { _ }) {
  13995. const importBlock = [];
  13996. for (const { importPath, reexports, imports, name, assertions } of dependencies) {
  13997. const assertion = assertions ? `${_}assert${_}${assertions}` : '';
  13998. const pathWithAssertion = `'${importPath}'${assertion};`;
  13999. if (!reexports && !imports) {
  14000. importBlock.push(`import${_}${pathWithAssertion}`);
  14001. continue;
  14002. }
  14003. if (imports) {
  14004. let defaultImport = null;
  14005. let starImport = null;
  14006. const importedNames = [];
  14007. for (const specifier of imports) {
  14008. if (specifier.imported === 'default') {
  14009. defaultImport = specifier;
  14010. }
  14011. else if (specifier.imported === '*') {
  14012. starImport = specifier;
  14013. }
  14014. else {
  14015. importedNames.push(specifier);
  14016. }
  14017. }
  14018. if (starImport) {
  14019. importBlock.push(`import${_}*${_}as ${starImport.local} from${_}${pathWithAssertion}`);
  14020. }
  14021. if (defaultImport && importedNames.length === 0) {
  14022. importBlock.push(`import ${defaultImport.local} from${_}${pathWithAssertion}`);
  14023. }
  14024. else if (importedNames.length > 0) {
  14025. importBlock.push(`import ${defaultImport ? `${defaultImport.local},${_}` : ''}{${_}${importedNames
  14026. .map(specifier => specifier.imported === specifier.local
  14027. ? specifier.imported
  14028. : `${specifier.imported} as ${specifier.local}`)
  14029. .join(`,${_}`)}${_}}${_}from${_}${pathWithAssertion}`);
  14030. }
  14031. }
  14032. if (reexports) {
  14033. let starExport = null;
  14034. const namespaceReexports = [];
  14035. const namedReexports = [];
  14036. for (const specifier of reexports) {
  14037. if (specifier.reexported === '*') {
  14038. starExport = specifier;
  14039. }
  14040. else if (specifier.imported === '*') {
  14041. namespaceReexports.push(specifier);
  14042. }
  14043. else {
  14044. namedReexports.push(specifier);
  14045. }
  14046. }
  14047. if (starExport) {
  14048. importBlock.push(`export${_}*${_}from${_}${pathWithAssertion}`);
  14049. }
  14050. if (namespaceReexports.length > 0) {
  14051. if (!imports ||
  14052. !imports.some(specifier => specifier.imported === '*' && specifier.local === name)) {
  14053. importBlock.push(`import${_}*${_}as ${name} from${_}${pathWithAssertion}`);
  14054. }
  14055. for (const specifier of namespaceReexports) {
  14056. importBlock.push(`export${_}{${_}${name === specifier.reexported ? name : `${name} as ${specifier.reexported}`} };`);
  14057. }
  14058. }
  14059. if (namedReexports.length > 0) {
  14060. importBlock.push(`export${_}{${_}${namedReexports
  14061. .map(specifier => specifier.imported === specifier.reexported
  14062. ? specifier.imported
  14063. : `${specifier.imported} as ${specifier.reexported}`)
  14064. .join(`,${_}`)}${_}}${_}from${_}${pathWithAssertion}`);
  14065. }
  14066. }
  14067. }
  14068. return importBlock;
  14069. }
  14070. function getExportBlock(exports, { _, cnst }) {
  14071. const exportBlock = [];
  14072. const exportDeclaration = [];
  14073. for (const specifier of exports) {
  14074. if (specifier.expression) {
  14075. exportBlock.push(`${cnst} ${specifier.local}${_}=${_}${specifier.expression};`);
  14076. }
  14077. exportDeclaration.push(specifier.exported === specifier.local
  14078. ? specifier.local
  14079. : `${specifier.local} as ${specifier.exported}`);
  14080. }
  14081. if (exportDeclaration.length > 0) {
  14082. exportBlock.push(`export${_}{${_}${exportDeclaration.join(`,${_}`)}${_}};`);
  14083. }
  14084. return exportBlock;
  14085. }
  14086. const keypath = (keypath, getPropertyAccess) => keypath.split('.').map(getPropertyAccess).join('');
  14087. function setupNamespace(name, root, globals, { _, getPropertyAccess, s }, compact) {
  14088. const parts = name.split('.');
  14089. parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
  14090. parts.pop();
  14091. let propertyPath = root;
  14092. return (parts
  14093. .map(part => {
  14094. propertyPath += getPropertyAccess(part);
  14095. return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}${s}`;
  14096. })
  14097. .join(compact ? ',' : '\n') + (compact && parts.length > 0 ? ';' : '\n'));
  14098. }
  14099. function assignToDeepVariable(deepName, root, globals, assignment, { _, getPropertyAccess }) {
  14100. const parts = deepName.split('.');
  14101. parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
  14102. const last = parts.pop();
  14103. let propertyPath = root;
  14104. let deepAssignment = [
  14105. ...parts.map(part => {
  14106. propertyPath += getPropertyAccess(part);
  14107. return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}`;
  14108. }),
  14109. `${propertyPath}${getPropertyAccess(last)}`
  14110. ].join(`,${_}`) + `${_}=${_}${assignment}`;
  14111. if (parts.length > 0) {
  14112. deepAssignment = `(${deepAssignment})`;
  14113. }
  14114. return deepAssignment;
  14115. }
  14116. function trimEmptyImports(dependencies) {
  14117. let index = dependencies.length;
  14118. while (index--) {
  14119. const { imports, reexports } = dependencies[index];
  14120. if (imports || reexports) {
  14121. return dependencies.slice(0, index + 1);
  14122. }
  14123. }
  14124. return [];
  14125. }
  14126. function iife(magicString, { accessedGlobals, dependencies, exports, hasDefaultExport, hasExports, indent: t, intro, namedExportsMode, log, outro, snippets }, { compact, esModule, extend, freeze, externalLiveBindings, globals, interop, name, namespaceToStringTag, strict }) {
  14127. const { _, getNonArrowFunctionIntro, getPropertyAccess, n } = snippets;
  14128. const isNamespaced = name && name.includes('.');
  14129. const useVariableAssignment = !extend && !isNamespaced;
  14130. if (name && useVariableAssignment && !isLegal(name)) {
  14131. return error(logIllegalIdentifierAsName(name));
  14132. }
  14133. warnOnBuiltins(log, dependencies);
  14134. const external = trimEmptyImports(dependencies);
  14135. const deps = external.map(dep => dep.globalName || 'null');
  14136. const parameters = external.map(m => m.name);
  14137. if (hasExports && !name) {
  14138. log(LOGLEVEL_WARN, logMissingNameOptionForIifeExport());
  14139. }
  14140. if (namedExportsMode && hasExports) {
  14141. if (extend) {
  14142. deps.unshift(`this${keypath(name, getPropertyAccess)}${_}=${_}this${keypath(name, getPropertyAccess)}${_}||${_}{}`);
  14143. parameters.unshift('exports');
  14144. }
  14145. else {
  14146. deps.unshift('{}');
  14147. parameters.unshift('exports');
  14148. }
  14149. }
  14150. const useStrict = strict ? `${t}'use strict';${n}` : '';
  14151. const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets);
  14152. magicString.prepend(`${intro}${interopBlock}`);
  14153. let wrapperIntro = `(${getNonArrowFunctionIntro(parameters, {
  14154. isAsync: false,
  14155. name: null
  14156. })}{${n}${useStrict}${n}`;
  14157. if (hasExports) {
  14158. if (name && !(extend && namedExportsMode)) {
  14159. wrapperIntro =
  14160. (useVariableAssignment ? `var ${name}` : `this${keypath(name, getPropertyAccess)}`) +
  14161. `${_}=${_}${wrapperIntro}`;
  14162. }
  14163. if (isNamespaced) {
  14164. wrapperIntro = setupNamespace(name, 'this', globals, snippets, compact) + wrapperIntro;
  14165. }
  14166. }
  14167. let wrapperOutro = `${n}${n}})(${deps.join(`,${_}`)});`;
  14168. if (hasExports && !extend && namedExportsMode) {
  14169. wrapperOutro = `${n}${n}${t}return exports;${wrapperOutro}`;
  14170. }
  14171. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings);
  14172. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule === true || (esModule === 'if-default-prop' && hasDefaultExport), namespaceToStringTag, snippets);
  14173. if (namespaceMarkers) {
  14174. namespaceMarkers = n + n + namespaceMarkers;
  14175. }
  14176. magicString
  14177. .append(`${exportBlock}${namespaceMarkers}${outro}`)
  14178. .indent(t)
  14179. .prepend(wrapperIntro)
  14180. .append(wrapperOutro);
  14181. }
  14182. function system(magicString, { accessedGlobals, dependencies, exports, hasExports, indent: t, intro, snippets, outro, usesTopLevelAwait }, { externalLiveBindings, freeze, name, namespaceToStringTag, strict, systemNullSetters }) {
  14183. const { _, getFunctionIntro, getNonArrowFunctionIntro, n, s } = snippets;
  14184. const { importBindings, setters, starExcludes } = analyzeDependencies(dependencies, exports, t, snippets);
  14185. const registeredName = name ? `'${name}',${_}` : '';
  14186. const wrapperParameters = accessedGlobals.has('module')
  14187. ? ['exports', 'module']
  14188. : hasExports
  14189. ? ['exports']
  14190. : [];
  14191. // factory function should be wrapped by parentheses to avoid lazy parsing,
  14192. // cf. https://v8.dev/blog/preparser#pife
  14193. let wrapperStart = `System.register(${registeredName}[` +
  14194. dependencies.map(({ importPath }) => `'${importPath}'`).join(`,${_}`) +
  14195. `],${_}(${getNonArrowFunctionIntro(wrapperParameters, {
  14196. isAsync: false,
  14197. name: null
  14198. })}{${n}${t}${strict ? "'use strict';" : ''}` +
  14199. getStarExcludesBlock(starExcludes, t, snippets) +
  14200. getImportBindingsBlock(importBindings, t, snippets) +
  14201. `${n}${t}return${_}{${setters.length > 0
  14202. ? `${n}${t}${t}setters:${_}[${setters
  14203. .map(setter => setter
  14204. ? `${getFunctionIntro(['module'], {
  14205. isAsync: false,
  14206. name: null
  14207. })}{${n}${t}${t}${t}${setter}${n}${t}${t}}`
  14208. : systemNullSetters
  14209. ? `null`
  14210. : `${getFunctionIntro([], { isAsync: false, name: null })}{}`)
  14211. .join(`,${_}`)}],`
  14212. : ''}${n}`;
  14213. wrapperStart += `${t}${t}execute:${_}(${getNonArrowFunctionIntro([], {
  14214. isAsync: usesTopLevelAwait,
  14215. name: null
  14216. })}{${n}${n}`;
  14217. const wrapperEnd = `${t}${t}})${n}${t}}${s}${n}}));`;
  14218. magicString
  14219. .prepend(intro +
  14220. getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, namespaceToStringTag) +
  14221. getHoistedExportsBlock(exports, t, snippets))
  14222. .append(`${outro}${n}${n}` +
  14223. getSyntheticExportsBlock(exports, t, snippets) +
  14224. getMissingExportsBlock(exports, t, snippets))
  14225. .indent(`${t}${t}${t}`)
  14226. .append(wrapperEnd)
  14227. .prepend(wrapperStart);
  14228. }
  14229. function analyzeDependencies(dependencies, exports, t, { _, cnst, getObject, getPropertyAccess, n }) {
  14230. const importBindings = [];
  14231. const setters = [];
  14232. let starExcludes = null;
  14233. for (const { imports, reexports } of dependencies) {
  14234. const setter = [];
  14235. if (imports) {
  14236. for (const specifier of imports) {
  14237. importBindings.push(specifier.local);
  14238. if (specifier.imported === '*') {
  14239. setter.push(`${specifier.local}${_}=${_}module;`);
  14240. }
  14241. else {
  14242. setter.push(`${specifier.local}${_}=${_}module${getPropertyAccess(specifier.imported)};`);
  14243. }
  14244. }
  14245. }
  14246. if (reexports) {
  14247. const reexportedNames = [];
  14248. let hasStarReexport = false;
  14249. for (const { imported, reexported } of reexports) {
  14250. if (reexported === '*') {
  14251. hasStarReexport = true;
  14252. }
  14253. else {
  14254. reexportedNames.push([
  14255. reexported,
  14256. imported === '*' ? 'module' : `module${getPropertyAccess(imported)}`
  14257. ]);
  14258. }
  14259. }
  14260. if (reexportedNames.length > 1 || hasStarReexport) {
  14261. const exportMapping = getObject(reexportedNames, { lineBreakIndent: null });
  14262. if (hasStarReexport) {
  14263. if (!starExcludes) {
  14264. starExcludes = getStarExcludes({ dependencies, exports });
  14265. }
  14266. setter.push(`${cnst} setter${_}=${_}${exportMapping};`, `for${_}(${cnst} name in module)${_}{`, `${t}if${_}(!_starExcludes[name])${_}setter[name]${_}=${_}module[name];`, '}', 'exports(setter);');
  14267. }
  14268. else {
  14269. setter.push(`exports(${exportMapping});`);
  14270. }
  14271. }
  14272. else {
  14273. const [key, value] = reexportedNames[0];
  14274. setter.push(`exports('${key}',${_}${value});`);
  14275. }
  14276. }
  14277. setters.push(setter.join(`${n}${t}${t}${t}`));
  14278. }
  14279. return { importBindings, setters, starExcludes };
  14280. }
  14281. const getStarExcludes = ({ dependencies, exports }) => {
  14282. const starExcludes = new Set(exports.map(expt => expt.exported));
  14283. starExcludes.add('default');
  14284. for (const { reexports } of dependencies) {
  14285. if (reexports) {
  14286. for (const reexport of reexports) {
  14287. if (reexport.reexported !== '*')
  14288. starExcludes.add(reexport.reexported);
  14289. }
  14290. }
  14291. }
  14292. return starExcludes;
  14293. };
  14294. const getStarExcludesBlock = (starExcludes, t, { _, cnst, getObject, n }) => starExcludes
  14295. ? `${n}${t}${cnst} _starExcludes${_}=${_}${getObject([...starExcludes].map(property => [property, '1']), { lineBreakIndent: { base: t, t } })};`
  14296. : '';
  14297. const getImportBindingsBlock = (importBindings, t, { _, n }) => (importBindings.length > 0 ? `${n}${t}var ${importBindings.join(`,${_}`)};` : '');
  14298. const getHoistedExportsBlock = (exports, t, snippets) => getExportsBlock(exports.filter(expt => expt.hoisted).map(expt => ({ name: expt.exported, value: expt.local })), t, snippets);
  14299. function getExportsBlock(exports, t, { _, n }) {
  14300. if (exports.length === 0) {
  14301. return '';
  14302. }
  14303. if (exports.length === 1) {
  14304. return `exports('${exports[0].name}',${_}${exports[0].value});${n}${n}`;
  14305. }
  14306. return (`exports({${n}` +
  14307. exports.map(({ name, value }) => `${t}${name}:${_}${value}`).join(`,${n}`) +
  14308. `${n}});${n}${n}`);
  14309. }
  14310. const getSyntheticExportsBlock = (exports, t, snippets) => getExportsBlock(exports
  14311. .filter(expt => expt.expression)
  14312. .map(expt => ({ name: expt.exported, value: expt.local })), t, snippets);
  14313. const getMissingExportsBlock = (exports, t, snippets) => getExportsBlock(exports
  14314. .filter(expt => expt.local === MISSING_EXPORT_SHIM_VARIABLE)
  14315. .map(expt => ({ name: expt.exported, value: MISSING_EXPORT_SHIM_VARIABLE })), t, snippets);
  14316. function globalProperty(name, globalVariable, getPropertyAccess) {
  14317. if (!name)
  14318. return 'null';
  14319. return `${globalVariable}${keypath(name, getPropertyAccess)}`;
  14320. }
  14321. function safeAccess(name, globalVariable, { _, getPropertyAccess }) {
  14322. let propertyPath = globalVariable;
  14323. return name
  14324. .split('.')
  14325. .map(part => (propertyPath += getPropertyAccess(part)))
  14326. .join(`${_}&&${_}`);
  14327. }
  14328. function umd(magicString, { accessedGlobals, dependencies, exports, hasDefaultExport, hasExports, id, indent: t, intro, namedExportsMode, log, outro, snippets }, { amd, compact, esModule, extend, externalLiveBindings, freeze, interop, name, namespaceToStringTag, globals, noConflict, strict }) {
  14329. const { _, cnst, getFunctionIntro, getNonArrowFunctionIntro, getPropertyAccess, n, s } = snippets;
  14330. const factoryVariable = compact ? 'f' : 'factory';
  14331. const globalVariable = compact ? 'g' : 'global';
  14332. if (hasExports && !name) {
  14333. return error(logMissingNameOptionForUmdExport());
  14334. }
  14335. warnOnBuiltins(log, dependencies);
  14336. const amdDeps = dependencies.map(m => `'${updateExtensionForRelativeAmdId(m.importPath, amd.forceJsExtensionForImports)}'`);
  14337. const cjsDeps = dependencies.map(m => `require('${m.importPath}')`);
  14338. const trimmedImports = trimEmptyImports(dependencies);
  14339. const globalDeps = trimmedImports.map(module => globalProperty(module.globalName, globalVariable, getPropertyAccess));
  14340. const factoryParameters = trimmedImports.map(m => m.name);
  14341. if (namedExportsMode && (hasExports || noConflict)) {
  14342. amdDeps.unshift(`'exports'`);
  14343. cjsDeps.unshift(`exports`);
  14344. globalDeps.unshift(assignToDeepVariable(name, globalVariable, globals, `${extend ? `${globalProperty(name, globalVariable, getPropertyAccess)}${_}||${_}` : ''}{}`, snippets));
  14345. factoryParameters.unshift('exports');
  14346. }
  14347. const completeAmdId = getCompleteAmdId(amd, id);
  14348. const amdParameters = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
  14349. (amdDeps.length > 0 ? `[${amdDeps.join(`,${_}`)}],${_}` : ``);
  14350. const define = amd.define;
  14351. const cjsExport = !namedExportsMode && hasExports ? `module.exports${_}=${_}` : ``;
  14352. const useStrict = strict ? `${_}'use strict';${n}` : ``;
  14353. let iifeExport;
  14354. if (noConflict) {
  14355. const noConflictExportsVariable = compact ? 'e' : 'exports';
  14356. let factory;
  14357. if (!namedExportsMode && hasExports) {
  14358. factory = `${cnst} ${noConflictExportsVariable}${_}=${_}${assignToDeepVariable(name, globalVariable, globals, `${factoryVariable}(${globalDeps.join(`,${_}`)})`, snippets)};`;
  14359. }
  14360. else {
  14361. const module = globalDeps.shift();
  14362. factory =
  14363. `${cnst} ${noConflictExportsVariable}${_}=${_}${module};${n}` +
  14364. `${t}${t}${factoryVariable}(${[noConflictExportsVariable, ...globalDeps].join(`,${_}`)});`;
  14365. }
  14366. iifeExport =
  14367. `(${getFunctionIntro([], { isAsync: false, name: null })}{${n}` +
  14368. `${t}${t}${cnst} current${_}=${_}${safeAccess(name, globalVariable, snippets)};${n}` +
  14369. `${t}${t}${factory}${n}` +
  14370. `${t}${t}${noConflictExportsVariable}.noConflict${_}=${_}${getFunctionIntro([], {
  14371. isAsync: false,
  14372. name: null
  14373. })}{${_}` +
  14374. `${globalProperty(name, globalVariable, getPropertyAccess)}${_}=${_}current;${_}return ${noConflictExportsVariable}${s}${_}};${n}` +
  14375. `${t}})()`;
  14376. }
  14377. else {
  14378. iifeExport = `${factoryVariable}(${globalDeps.join(`,${_}`)})`;
  14379. if (!namedExportsMode && hasExports) {
  14380. iifeExport = assignToDeepVariable(name, globalVariable, globals, iifeExport, snippets);
  14381. }
  14382. }
  14383. const iifeNeedsGlobal = hasExports || (noConflict && namedExportsMode) || globalDeps.length > 0;
  14384. const wrapperParameters = [factoryVariable];
  14385. if (iifeNeedsGlobal) {
  14386. wrapperParameters.unshift(globalVariable);
  14387. }
  14388. const globalArgument = iifeNeedsGlobal ? `this,${_}` : '';
  14389. const iifeStart = iifeNeedsGlobal
  14390. ? `(${globalVariable}${_}=${_}typeof globalThis${_}!==${_}'undefined'${_}?${_}globalThis${_}:${_}${globalVariable}${_}||${_}self,${_}`
  14391. : '';
  14392. const iifeEnd = iifeNeedsGlobal ? ')' : '';
  14393. const cjsIntro = iifeNeedsGlobal
  14394. ? `${t}typeof exports${_}===${_}'object'${_}&&${_}typeof module${_}!==${_}'undefined'${_}?` +
  14395. `${_}${cjsExport}${factoryVariable}(${cjsDeps.join(`,${_}`)})${_}:${n}`
  14396. : '';
  14397. const wrapperIntro = `(${getNonArrowFunctionIntro(wrapperParameters, { isAsync: false, name: null })}{${n}` +
  14398. cjsIntro +
  14399. `${t}typeof ${define}${_}===${_}'function'${_}&&${_}${define}.amd${_}?${_}${define}(${amdParameters}${factoryVariable})${_}:${n}` +
  14400. `${t}${iifeStart}${iifeExport}${iifeEnd};${n}` +
  14401. // factory function should be wrapped by parentheses to avoid lazy parsing,
  14402. // cf. https://v8.dev/blog/preparser#pife
  14403. `})(${globalArgument}(${getNonArrowFunctionIntro(factoryParameters, {
  14404. isAsync: false,
  14405. name: null
  14406. })}{${useStrict}${n}`;
  14407. const wrapperOutro = n + n + '}));';
  14408. magicString.prepend(`${intro}${getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets)}`);
  14409. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings);
  14410. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule === true || (esModule === 'if-default-prop' && hasDefaultExport), namespaceToStringTag, snippets);
  14411. if (namespaceMarkers) {
  14412. namespaceMarkers = n + n + namespaceMarkers;
  14413. }
  14414. magicString
  14415. .append(`${exportBlock}${namespaceMarkers}${outro}`)
  14416. .trim()
  14417. .indent(t)
  14418. .append(wrapperOutro)
  14419. .prepend(wrapperIntro);
  14420. }
  14421. const finalisers = { amd, cjs, es, iife, system, umd };
  14422. const concatSeparator = (out, next) => (next ? `${out}\n${next}` : out);
  14423. const concatDblSeparator = (out, next) => (next ? `${out}\n\n${next}` : out);
  14424. async function createAddons(options, outputPluginDriver, chunk) {
  14425. try {
  14426. let [banner, footer, intro, outro] = await Promise.all([
  14427. outputPluginDriver.hookReduceValue('banner', options.banner(chunk), [chunk], concatSeparator),
  14428. outputPluginDriver.hookReduceValue('footer', options.footer(chunk), [chunk], concatSeparator),
  14429. outputPluginDriver.hookReduceValue('intro', options.intro(chunk), [chunk], concatDblSeparator),
  14430. outputPluginDriver.hookReduceValue('outro', options.outro(chunk), [chunk], concatDblSeparator)
  14431. ]);
  14432. if (intro)
  14433. intro += '\n\n';
  14434. if (outro)
  14435. outro = `\n\n${outro}`;
  14436. if (banner)
  14437. banner += '\n';
  14438. if (footer)
  14439. footer = '\n' + footer;
  14440. return { banner, footer, intro, outro };
  14441. }
  14442. catch (error_) {
  14443. return error(logAddonNotGenerated(error_.message, error_.hook, error_.plugin));
  14444. }
  14445. }
  14446. const DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT = {
  14447. amd: deconflictImportsOther,
  14448. cjs: deconflictImportsOther,
  14449. es: deconflictImportsEsmOrSystem,
  14450. iife: deconflictImportsOther,
  14451. system: deconflictImportsEsmOrSystem,
  14452. umd: deconflictImportsOther
  14453. };
  14454. function deconflictChunk(modules, dependenciesToBeDeconflicted, imports, usedNames, format, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports, exportNamesByVariable, accessedGlobalsByScope, includedNamespaces) {
  14455. const reversedModules = [...modules].reverse();
  14456. for (const module of reversedModules) {
  14457. module.scope.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
  14458. }
  14459. deconflictTopLevelVariables(usedNames, reversedModules, includedNamespaces);
  14460. DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT[format](usedNames, imports, dependenciesToBeDeconflicted, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports);
  14461. for (const module of reversedModules) {
  14462. module.scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  14463. }
  14464. }
  14465. function deconflictImportsEsmOrSystem(usedNames, imports, dependenciesToBeDeconflicted, _interop, preserveModules, _externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports) {
  14466. // This is needed for namespace reexports
  14467. for (const dependency of dependenciesToBeDeconflicted.dependencies) {
  14468. if (preserveModules || dependency instanceof ExternalChunk) {
  14469. dependency.variableName = getSafeName(dependency.suggestedVariableName, usedNames, null);
  14470. }
  14471. }
  14472. for (const variable of imports) {
  14473. const module = variable.module;
  14474. const name = variable.name;
  14475. if (variable.isNamespace && (preserveModules || module instanceof ExternalModule)) {
  14476. variable.setRenderNames(null, (module instanceof ExternalModule
  14477. ? externalChunkByModule.get(module)
  14478. : chunkByModule.get(module)).variableName);
  14479. }
  14480. else if (module instanceof ExternalModule && name === 'default') {
  14481. variable.setRenderNames(null, getSafeName([...module.exportedVariables].some(([exportedVariable, exportedName]) => exportedName === '*' && exportedVariable.included)
  14482. ? module.suggestedVariableName + '__default'
  14483. : module.suggestedVariableName, usedNames, variable.forbiddenNames));
  14484. }
  14485. else {
  14486. variable.setRenderNames(null, getSafeName(name, usedNames, variable.forbiddenNames));
  14487. }
  14488. }
  14489. for (const variable of syntheticExports) {
  14490. variable.setRenderNames(null, getSafeName(variable.name, usedNames, variable.forbiddenNames));
  14491. }
  14492. }
  14493. function deconflictImportsOther(usedNames, imports, { deconflictedDefault, deconflictedNamespace, dependencies }, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule) {
  14494. for (const chunk of dependencies) {
  14495. chunk.variableName = getSafeName(chunk.suggestedVariableName, usedNames, null);
  14496. }
  14497. for (const chunk of deconflictedNamespace) {
  14498. chunk.namespaceVariableName = getSafeName(`${chunk.suggestedVariableName}__namespace`, usedNames, null);
  14499. }
  14500. for (const externalModule of deconflictedDefault) {
  14501. externalModule.defaultVariableName =
  14502. deconflictedNamespace.has(externalModule) &&
  14503. canDefaultBeTakenFromNamespace(interop(externalModule.id), externalLiveBindings)
  14504. ? externalModule.namespaceVariableName
  14505. : getSafeName(`${externalModule.suggestedVariableName}__default`, usedNames, null);
  14506. }
  14507. for (const variable of imports) {
  14508. const module = variable.module;
  14509. if (module instanceof ExternalModule) {
  14510. const chunk = externalChunkByModule.get(module);
  14511. const name = variable.name;
  14512. if (name === 'default') {
  14513. const moduleInterop = interop(module.id);
  14514. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  14515. ? chunk.defaultVariableName
  14516. : chunk.variableName;
  14517. if (isDefaultAProperty(moduleInterop, externalLiveBindings)) {
  14518. variable.setRenderNames(variableName, 'default');
  14519. }
  14520. else {
  14521. variable.setRenderNames(null, variableName);
  14522. }
  14523. }
  14524. else if (name === '*') {
  14525. variable.setRenderNames(null, namespaceInteropHelpersByInteropType[interop(module.id)]
  14526. ? chunk.namespaceVariableName
  14527. : chunk.variableName);
  14528. }
  14529. else {
  14530. // if the second parameter is `null`, it uses its "name" for the property name
  14531. variable.setRenderNames(chunk.variableName, null);
  14532. }
  14533. }
  14534. else {
  14535. const chunk = chunkByModule.get(module);
  14536. if (preserveModules && variable.isNamespace) {
  14537. variable.setRenderNames(null, chunk.exportMode === 'default' ? chunk.namespaceVariableName : chunk.variableName);
  14538. }
  14539. else if (chunk.exportMode === 'default') {
  14540. variable.setRenderNames(null, chunk.variableName);
  14541. }
  14542. else {
  14543. variable.setRenderNames(chunk.variableName, chunk.getVariableExportName(variable));
  14544. }
  14545. }
  14546. }
  14547. }
  14548. function deconflictTopLevelVariables(usedNames, modules, includedNamespaces) {
  14549. for (const module of modules) {
  14550. for (const variable of module.scope.variables.values()) {
  14551. if (variable.included &&
  14552. // this will only happen for exports in some formats
  14553. !(variable.renderBaseName ||
  14554. (variable instanceof ExportDefaultVariable && variable.getOriginalVariable() !== variable))) {
  14555. variable.setRenderNames(null, getSafeName(variable.name, usedNames, variable.forbiddenNames));
  14556. }
  14557. }
  14558. if (includedNamespaces.has(module)) {
  14559. const namespace = module.namespace;
  14560. namespace.setRenderNames(null, getSafeName(namespace.name, usedNames, namespace.forbiddenNames));
  14561. }
  14562. }
  14563. }
  14564. function assignExportsToMangledNames(exports, exportsByName, exportNamesByVariable) {
  14565. let nameIndex = 0;
  14566. for (const variable of exports) {
  14567. let [exportName] = variable.name;
  14568. if (exportsByName.has(exportName)) {
  14569. do {
  14570. exportName = toBase64(++nameIndex);
  14571. // skip past leading number identifiers
  14572. if (exportName.charCodeAt(0) === 49 /* '1' */) {
  14573. nameIndex += 9 * 64 ** (exportName.length - 1);
  14574. exportName = toBase64(nameIndex);
  14575. }
  14576. } while (RESERVED_NAMES$1.has(exportName) || exportsByName.has(exportName));
  14577. }
  14578. exportsByName.set(exportName, variable);
  14579. exportNamesByVariable.set(variable, [exportName]);
  14580. }
  14581. }
  14582. function assignExportsToNames(exports, exportsByName, exportNamesByVariable) {
  14583. for (const variable of exports) {
  14584. let nameIndex = 0;
  14585. let exportName = variable.name;
  14586. while (exportsByName.has(exportName)) {
  14587. exportName = variable.name + '$' + ++nameIndex;
  14588. }
  14589. exportsByName.set(exportName, variable);
  14590. exportNamesByVariable.set(variable, [exportName]);
  14591. }
  14592. }
  14593. function getExportMode(chunk, { exports: exportMode, name, format }, facadeModuleId, log) {
  14594. const exportKeys = chunk.getExportNames();
  14595. if (exportMode === 'default') {
  14596. if (exportKeys.length !== 1 || exportKeys[0] !== 'default') {
  14597. return error(logIncompatibleExportOptionValue('default', exportKeys, facadeModuleId));
  14598. }
  14599. }
  14600. else if (exportMode === 'none' && exportKeys.length > 0) {
  14601. return error(logIncompatibleExportOptionValue('none', exportKeys, facadeModuleId));
  14602. }
  14603. if (exportMode === 'auto') {
  14604. if (exportKeys.length === 0) {
  14605. exportMode = 'none';
  14606. }
  14607. else if (exportKeys.length === 1 && exportKeys[0] === 'default') {
  14608. exportMode = 'default';
  14609. }
  14610. else {
  14611. if (format !== 'es' && format !== 'system' && exportKeys.includes('default')) {
  14612. log(LOGLEVEL_WARN, logMixedExport(facadeModuleId, name));
  14613. }
  14614. exportMode = 'named';
  14615. }
  14616. }
  14617. return exportMode;
  14618. }
  14619. function guessIndentString(code) {
  14620. const lines = code.split('\n');
  14621. const tabbed = lines.filter(line => /^\t+/.test(line));
  14622. const spaced = lines.filter(line => /^ {2,}/.test(line));
  14623. if (tabbed.length === 0 && spaced.length === 0) {
  14624. return null;
  14625. }
  14626. // More lines tabbed than spaced? Assume tabs, and
  14627. // default to tabs in the case of a tie (or nothing
  14628. // to go on)
  14629. if (tabbed.length >= spaced.length) {
  14630. return '\t';
  14631. }
  14632. // Otherwise, we need to guess the multiple
  14633. const min = spaced.reduce((previous, current) => {
  14634. const numberSpaces = /^ +/.exec(current)[0].length;
  14635. return Math.min(numberSpaces, previous);
  14636. }, Infinity);
  14637. return ' '.repeat(min);
  14638. }
  14639. function getIndentString(modules, options) {
  14640. if (options.indent !== true)
  14641. return options.indent;
  14642. for (const module of modules) {
  14643. const indent = guessIndentString(module.originalCode);
  14644. if (indent !== null)
  14645. return indent;
  14646. }
  14647. return '\t';
  14648. }
  14649. function getStaticDependencies(chunk, orderedModules, chunkByModule, externalChunkByModule) {
  14650. const staticDependencyBlocks = [];
  14651. const handledDependencies = new Set();
  14652. for (let modulePos = orderedModules.length - 1; modulePos >= 0; modulePos--) {
  14653. const module = orderedModules[modulePos];
  14654. if (!handledDependencies.has(module)) {
  14655. const staticDependencies = [];
  14656. addStaticDependencies(module, staticDependencies, handledDependencies, chunk, chunkByModule, externalChunkByModule);
  14657. staticDependencyBlocks.unshift(staticDependencies);
  14658. }
  14659. }
  14660. const dependencies = new Set();
  14661. for (const block of staticDependencyBlocks) {
  14662. for (const dependency of block) {
  14663. dependencies.add(dependency);
  14664. }
  14665. }
  14666. return dependencies;
  14667. }
  14668. function addStaticDependencies(module, staticDependencies, handledModules, chunk, chunkByModule, externalChunkByModule) {
  14669. const dependencies = module.getDependenciesToBeIncluded();
  14670. for (const dependency of dependencies) {
  14671. if (dependency instanceof ExternalModule) {
  14672. staticDependencies.push(externalChunkByModule.get(dependency));
  14673. continue;
  14674. }
  14675. const dependencyChunk = chunkByModule.get(dependency);
  14676. if (dependencyChunk !== chunk) {
  14677. staticDependencies.push(dependencyChunk);
  14678. continue;
  14679. }
  14680. if (!handledModules.has(dependency)) {
  14681. handledModules.add(dependency);
  14682. addStaticDependencies(dependency, staticDependencies, handledModules, chunk, chunkByModule, externalChunkByModule);
  14683. }
  14684. }
  14685. }
  14686. // Four random characters from the private use area to minimize risk of
  14687. // conflicts
  14688. const hashPlaceholderLeft = '!~{';
  14689. const hashPlaceholderRight = '}~';
  14690. const hashPlaceholderOverhead = hashPlaceholderLeft.length + hashPlaceholderRight.length;
  14691. // This is the size of a sha256
  14692. const maxHashSize = 64;
  14693. const defaultHashSize = 8;
  14694. const getHashPlaceholderGenerator = () => {
  14695. let nextIndex = 0;
  14696. return (optionName, hashSize = defaultHashSize) => {
  14697. if (hashSize > maxHashSize) {
  14698. return error(logFailedValidation(`Hashes cannot be longer than ${maxHashSize} characters, received ${hashSize}. Check the "${optionName}" option.`));
  14699. }
  14700. const placeholder = `${hashPlaceholderLeft}${toBase64(++nextIndex).padStart(hashSize - hashPlaceholderOverhead, '0')}${hashPlaceholderRight}`;
  14701. if (placeholder.length > hashSize) {
  14702. return error(logFailedValidation(`To generate hashes for this number of chunks (currently ${nextIndex}), you need a minimum hash size of ${placeholder.length}, received ${hashSize}. Check the "${optionName}" option.`));
  14703. }
  14704. return placeholder;
  14705. };
  14706. };
  14707. const REPLACER_REGEX = new RegExp(`${hashPlaceholderLeft}[0-9a-zA-Z_$]{1,${maxHashSize - hashPlaceholderOverhead}}${hashPlaceholderRight}`, 'g');
  14708. const replacePlaceholders = (code, hashesByPlaceholder) => code.replace(REPLACER_REGEX, placeholder => hashesByPlaceholder.get(placeholder) || placeholder);
  14709. const replaceSinglePlaceholder = (code, placeholder, value) => code.replace(REPLACER_REGEX, match => (match === placeholder ? value : match));
  14710. const replacePlaceholdersWithDefaultAndGetContainedPlaceholders = (code, placeholders) => {
  14711. const containedPlaceholders = new Set();
  14712. const transformedCode = code.replace(REPLACER_REGEX, placeholder => {
  14713. if (placeholders.has(placeholder)) {
  14714. containedPlaceholders.add(placeholder);
  14715. return `${hashPlaceholderLeft}${'0'.repeat(placeholder.length - hashPlaceholderOverhead)}${hashPlaceholderRight}`;
  14716. }
  14717. return placeholder;
  14718. });
  14719. return { containedPlaceholders, transformedCode };
  14720. };
  14721. const lowercaseBundleKeys = Symbol('bundleKeys');
  14722. const FILE_PLACEHOLDER = {
  14723. type: 'placeholder'
  14724. };
  14725. const getOutputBundle = (outputBundleBase) => {
  14726. const reservedLowercaseBundleKeys = new Set();
  14727. return new Proxy(outputBundleBase, {
  14728. deleteProperty(target, key) {
  14729. if (typeof key === 'string') {
  14730. reservedLowercaseBundleKeys.delete(key.toLowerCase());
  14731. }
  14732. return Reflect.deleteProperty(target, key);
  14733. },
  14734. get(target, key) {
  14735. if (key === lowercaseBundleKeys) {
  14736. return reservedLowercaseBundleKeys;
  14737. }
  14738. return Reflect.get(target, key);
  14739. },
  14740. set(target, key, value) {
  14741. if (typeof key === 'string') {
  14742. reservedLowercaseBundleKeys.add(key.toLowerCase());
  14743. }
  14744. return Reflect.set(target, key, value);
  14745. }
  14746. });
  14747. };
  14748. const removeUnreferencedAssets = (outputBundle) => {
  14749. const unreferencedAssets = new Set();
  14750. const bundleEntries = Object.values(outputBundle);
  14751. for (const asset of bundleEntries) {
  14752. asset.type === 'asset' && asset.needsCodeReference && unreferencedAssets.add(asset.fileName);
  14753. }
  14754. for (const chunk of bundleEntries) {
  14755. if (chunk.type === 'chunk') {
  14756. for (const referencedFile of chunk.referencedFiles) {
  14757. unreferencedAssets.has(referencedFile) && unreferencedAssets.delete(referencedFile);
  14758. }
  14759. }
  14760. }
  14761. for (const file of unreferencedAssets) {
  14762. delete outputBundle[file];
  14763. }
  14764. };
  14765. function renderNamePattern(pattern, patternName, replacements) {
  14766. if (isPathFragment(pattern))
  14767. return error(logFailedValidation(`Invalid pattern "${pattern}" for "${patternName}", patterns can be neither absolute nor relative paths. If you want your files to be stored in a subdirectory, write its name without a leading slash like this: subdirectory/pattern.`));
  14768. return pattern.replace(/\[(\w+)(:\d+)?]/g, (_match, type, size) => {
  14769. if (!replacements.hasOwnProperty(type) || (size && type !== 'hash')) {
  14770. return error(logFailedValidation(`"[${type}${size || ''}]" is not a valid placeholder in the "${patternName}" pattern.`));
  14771. }
  14772. const replacement = replacements[type](size && Number.parseInt(size.slice(1)));
  14773. if (isPathFragment(replacement))
  14774. return error(logFailedValidation(`Invalid substitution "${replacement}" for placeholder "[${type}]" in "${patternName}" pattern, can be neither absolute nor relative path.`));
  14775. return replacement;
  14776. });
  14777. }
  14778. function makeUnique(name, { [lowercaseBundleKeys]: reservedLowercaseBundleKeys }) {
  14779. if (!reservedLowercaseBundleKeys.has(name.toLowerCase()))
  14780. return name;
  14781. const extension = extname(name);
  14782. name = name.slice(0, Math.max(0, name.length - extension.length));
  14783. let uniqueName, uniqueIndex = 1;
  14784. while (reservedLowercaseBundleKeys.has((uniqueName = name + ++uniqueIndex + extension).toLowerCase()))
  14785. ;
  14786. return uniqueName;
  14787. }
  14788. const NON_ASSET_EXTENSIONS = new Set([
  14789. '.js',
  14790. '.jsx',
  14791. '.ts',
  14792. '.tsx',
  14793. '.mjs',
  14794. '.mts',
  14795. '.cjs',
  14796. '.cts'
  14797. ]);
  14798. function getGlobalName(chunk, globals, hasExports, log) {
  14799. const globalName = typeof globals === 'function' ? globals(chunk.id) : globals[chunk.id];
  14800. if (globalName) {
  14801. return globalName;
  14802. }
  14803. if (hasExports) {
  14804. log(LOGLEVEL_WARN, logMissingGlobalName(chunk.id, chunk.variableName));
  14805. return chunk.variableName;
  14806. }
  14807. }
  14808. class Chunk {
  14809. constructor(orderedModules, inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, manualChunkAlias, getPlaceholder, bundle, inputBase, snippets) {
  14810. this.orderedModules = orderedModules;
  14811. this.inputOptions = inputOptions;
  14812. this.outputOptions = outputOptions;
  14813. this.unsetOptions = unsetOptions;
  14814. this.pluginDriver = pluginDriver;
  14815. this.modulesById = modulesById;
  14816. this.chunkByModule = chunkByModule;
  14817. this.externalChunkByModule = externalChunkByModule;
  14818. this.facadeChunkByModule = facadeChunkByModule;
  14819. this.includedNamespaces = includedNamespaces;
  14820. this.manualChunkAlias = manualChunkAlias;
  14821. this.getPlaceholder = getPlaceholder;
  14822. this.bundle = bundle;
  14823. this.inputBase = inputBase;
  14824. this.snippets = snippets;
  14825. this.entryModules = [];
  14826. this.exportMode = 'named';
  14827. this.facadeModule = null;
  14828. this.namespaceVariableName = '';
  14829. this.variableName = '';
  14830. this.accessedGlobalsByScope = new Map();
  14831. this.dependencies = new Set();
  14832. this.dynamicEntryModules = [];
  14833. this.dynamicName = null;
  14834. this.exportNamesByVariable = new Map();
  14835. this.exports = new Set();
  14836. this.exportsByName = new Map();
  14837. this.fileName = null;
  14838. this.implicitEntryModules = [];
  14839. this.implicitlyLoadedBefore = new Set();
  14840. this.imports = new Set();
  14841. this.includedDynamicImports = null;
  14842. this.includedReexportsByModule = new Map();
  14843. // This may be updated in the constructor
  14844. this.isEmpty = true;
  14845. this.name = null;
  14846. this.needsExportsShim = false;
  14847. this.preRenderedChunkInfo = null;
  14848. this.preliminaryFileName = null;
  14849. this.preliminarySourcemapFileName = null;
  14850. this.renderedChunkInfo = null;
  14851. this.renderedDependencies = null;
  14852. this.renderedModules = Object.create(null);
  14853. this.sortedExportNames = null;
  14854. this.strictFacade = false;
  14855. this.execIndex = orderedModules.length > 0 ? orderedModules[0].execIndex : Infinity;
  14856. const chunkModules = new Set(orderedModules);
  14857. for (const module of orderedModules) {
  14858. chunkByModule.set(module, this);
  14859. if (module.namespace.included && !outputOptions.preserveModules) {
  14860. includedNamespaces.add(module);
  14861. }
  14862. if (this.isEmpty && module.isIncluded()) {
  14863. this.isEmpty = false;
  14864. }
  14865. if (module.info.isEntry || outputOptions.preserveModules) {
  14866. this.entryModules.push(module);
  14867. }
  14868. for (const importer of module.includedDynamicImporters) {
  14869. if (!chunkModules.has(importer)) {
  14870. this.dynamicEntryModules.push(module);
  14871. // Modules with synthetic exports need an artificial namespace for dynamic imports
  14872. if (module.info.syntheticNamedExports) {
  14873. includedNamespaces.add(module);
  14874. this.exports.add(module.namespace);
  14875. }
  14876. }
  14877. }
  14878. if (module.implicitlyLoadedAfter.size > 0) {
  14879. this.implicitEntryModules.push(module);
  14880. }
  14881. }
  14882. this.suggestedVariableName = makeLegal(this.generateVariableName());
  14883. }
  14884. static generateFacade(inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, facadedModule, facadeName, getPlaceholder, bundle, inputBase, snippets) {
  14885. const chunk = new Chunk([], inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, null, getPlaceholder, bundle, inputBase, snippets);
  14886. chunk.assignFacadeName(facadeName, facadedModule);
  14887. if (!facadeChunkByModule.has(facadedModule)) {
  14888. facadeChunkByModule.set(facadedModule, chunk);
  14889. }
  14890. for (const dependency of facadedModule.getDependenciesToBeIncluded()) {
  14891. chunk.dependencies.add(dependency instanceof Module
  14892. ? chunkByModule.get(dependency)
  14893. : externalChunkByModule.get(dependency));
  14894. }
  14895. if (!chunk.dependencies.has(chunkByModule.get(facadedModule)) &&
  14896. facadedModule.info.moduleSideEffects &&
  14897. facadedModule.hasEffects()) {
  14898. chunk.dependencies.add(chunkByModule.get(facadedModule));
  14899. }
  14900. chunk.ensureReexportsAreAvailableForModule(facadedModule);
  14901. chunk.facadeModule = facadedModule;
  14902. chunk.strictFacade = true;
  14903. return chunk;
  14904. }
  14905. canModuleBeFacade(module, exposedVariables) {
  14906. const moduleExportNamesByVariable = module.getExportNamesByVariable();
  14907. // All exports of this chunk need to be exposed by the candidate module
  14908. for (const exposedVariable of this.exports) {
  14909. if (!moduleExportNamesByVariable.has(exposedVariable)) {
  14910. return false;
  14911. }
  14912. }
  14913. // Additionally, we need to expose namespaces of dynamic entries that are not the facade module and exports from other entry modules
  14914. for (const exposedVariable of exposedVariables) {
  14915. if (!(exposedVariable.module === module ||
  14916. moduleExportNamesByVariable.has(exposedVariable) ||
  14917. (exposedVariable instanceof SyntheticNamedExportVariable &&
  14918. moduleExportNamesByVariable.has(exposedVariable.getBaseVariable())))) {
  14919. return false;
  14920. }
  14921. }
  14922. return true;
  14923. }
  14924. finalizeChunk(code, map, sourcemapFileName, hashesByPlaceholder) {
  14925. const renderedChunkInfo = this.getRenderedChunkInfo();
  14926. const finalize = (code) => replacePlaceholders(code, hashesByPlaceholder);
  14927. const preliminaryFileName = renderedChunkInfo.fileName;
  14928. const fileName = (this.fileName = finalize(preliminaryFileName));
  14929. return {
  14930. ...renderedChunkInfo,
  14931. code,
  14932. dynamicImports: renderedChunkInfo.dynamicImports.map(finalize),
  14933. fileName,
  14934. implicitlyLoadedBefore: renderedChunkInfo.implicitlyLoadedBefore.map(finalize),
  14935. importedBindings: Object.fromEntries(Object.entries(renderedChunkInfo.importedBindings).map(([fileName, bindings]) => [
  14936. finalize(fileName),
  14937. bindings
  14938. ])),
  14939. imports: renderedChunkInfo.imports.map(finalize),
  14940. map,
  14941. preliminaryFileName,
  14942. referencedFiles: renderedChunkInfo.referencedFiles.map(finalize),
  14943. sourcemapFileName
  14944. };
  14945. }
  14946. generateExports() {
  14947. this.sortedExportNames = null;
  14948. const remainingExports = new Set(this.exports);
  14949. if (this.facadeModule !== null &&
  14950. (this.facadeModule.preserveSignature !== false || this.strictFacade)) {
  14951. const exportNamesByVariable = this.facadeModule.getExportNamesByVariable();
  14952. for (const [variable, exportNames] of exportNamesByVariable) {
  14953. this.exportNamesByVariable.set(variable, [...exportNames]);
  14954. for (const exportName of exportNames) {
  14955. this.exportsByName.set(exportName, variable);
  14956. }
  14957. remainingExports.delete(variable);
  14958. }
  14959. }
  14960. if (this.outputOptions.minifyInternalExports) {
  14961. assignExportsToMangledNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  14962. }
  14963. else {
  14964. assignExportsToNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  14965. }
  14966. if (this.outputOptions.preserveModules || (this.facadeModule && this.facadeModule.info.isEntry))
  14967. this.exportMode = getExportMode(this, this.outputOptions, this.facadeModule.id, this.inputOptions.onLog);
  14968. }
  14969. generateFacades() {
  14970. const facades = [];
  14971. const entryModules = new Set([...this.entryModules, ...this.implicitEntryModules]);
  14972. const exposedVariables = new Set(this.dynamicEntryModules.map(({ namespace }) => namespace));
  14973. for (const module of entryModules) {
  14974. if (module.preserveSignature) {
  14975. for (const exportedVariable of module.getExportNamesByVariable().keys()) {
  14976. // We need to expose all entry exports from this chunk
  14977. if (this.chunkByModule.get(exportedVariable.module) === this) {
  14978. exposedVariables.add(exportedVariable);
  14979. }
  14980. }
  14981. }
  14982. }
  14983. for (const module of entryModules) {
  14984. // eslint-disable-next-line unicorn/prefer-spread
  14985. const requiredFacades = Array.from(new Set(module.chunkNames.filter(({ isUserDefined }) => isUserDefined).map(({ name }) => name)),
  14986. // mapping must run after Set 'name' dedupe
  14987. name => ({
  14988. name
  14989. }));
  14990. if (requiredFacades.length === 0 && module.isUserDefinedEntryPoint) {
  14991. requiredFacades.push({});
  14992. }
  14993. // eslint-disable-next-line unicorn/prefer-spread
  14994. requiredFacades.push(...Array.from(module.chunkFileNames, fileName => ({ fileName })));
  14995. if (requiredFacades.length === 0) {
  14996. requiredFacades.push({});
  14997. }
  14998. if (!this.facadeModule) {
  14999. const needsStrictFacade = !this.outputOptions.preserveModules &&
  15000. (module.preserveSignature === 'strict' ||
  15001. (module.preserveSignature === 'exports-only' &&
  15002. module.getExportNamesByVariable().size > 0));
  15003. if (!needsStrictFacade || this.canModuleBeFacade(module, exposedVariables)) {
  15004. this.facadeModule = module;
  15005. this.facadeChunkByModule.set(module, this);
  15006. if (module.preserveSignature) {
  15007. this.strictFacade = needsStrictFacade;
  15008. }
  15009. this.assignFacadeName(requiredFacades.shift(), module, this.outputOptions.preserveModules);
  15010. }
  15011. }
  15012. for (const facadeName of requiredFacades) {
  15013. facades.push(Chunk.generateFacade(this.inputOptions, this.outputOptions, this.unsetOptions, this.pluginDriver, this.modulesById, this.chunkByModule, this.externalChunkByModule, this.facadeChunkByModule, this.includedNamespaces, module, facadeName, this.getPlaceholder, this.bundle, this.inputBase, this.snippets));
  15014. }
  15015. }
  15016. for (const module of this.dynamicEntryModules) {
  15017. if (module.info.syntheticNamedExports)
  15018. continue;
  15019. if (!this.facadeModule && this.canModuleBeFacade(module, exposedVariables)) {
  15020. this.facadeModule = module;
  15021. this.facadeChunkByModule.set(module, this);
  15022. this.strictFacade = true;
  15023. this.dynamicName = getChunkNameFromModule(module);
  15024. }
  15025. else if (this.facadeModule === module &&
  15026. !this.strictFacade &&
  15027. this.canModuleBeFacade(module, exposedVariables)) {
  15028. this.strictFacade = true;
  15029. }
  15030. else if (!this.facadeChunkByModule.get(module)?.strictFacade) {
  15031. this.includedNamespaces.add(module);
  15032. this.exports.add(module.namespace);
  15033. }
  15034. }
  15035. if (!this.outputOptions.preserveModules) {
  15036. this.addNecessaryImportsForFacades();
  15037. }
  15038. return facades;
  15039. }
  15040. getChunkName() {
  15041. return (this.name ?? (this.name = this.outputOptions.sanitizeFileName(this.getFallbackChunkName())));
  15042. }
  15043. getExportNames() {
  15044. return (this.sortedExportNames ?? (this.sortedExportNames = [...this.exportsByName.keys()].sort()));
  15045. }
  15046. getFileName() {
  15047. return this.fileName || this.getPreliminaryFileName().fileName;
  15048. }
  15049. getImportPath(importer) {
  15050. return escapeId(getImportPath(importer, this.getFileName(), this.outputOptions.format === 'amd' && !this.outputOptions.amd.forceJsExtensionForImports, true));
  15051. }
  15052. getPreliminaryFileName() {
  15053. if (this.preliminaryFileName) {
  15054. return this.preliminaryFileName;
  15055. }
  15056. let fileName;
  15057. let hashPlaceholder = null;
  15058. const { chunkFileNames, entryFileNames, file, format, preserveModules } = this.outputOptions;
  15059. if (file) {
  15060. fileName = basename(file);
  15061. }
  15062. else if (this.fileName === null) {
  15063. const [pattern, patternName] = preserveModules || this.facadeModule?.isUserDefinedEntryPoint
  15064. ? [entryFileNames, 'output.entryFileNames']
  15065. : [chunkFileNames, 'output.chunkFileNames'];
  15066. fileName = renderNamePattern(typeof pattern === 'function' ? pattern(this.getPreRenderedChunkInfo()) : pattern, patternName, {
  15067. format: () => format,
  15068. hash: size => hashPlaceholder || (hashPlaceholder = this.getPlaceholder(patternName, size)),
  15069. name: () => this.getChunkName()
  15070. });
  15071. if (!hashPlaceholder) {
  15072. fileName = makeUnique(fileName, this.bundle);
  15073. }
  15074. }
  15075. else {
  15076. fileName = this.fileName;
  15077. }
  15078. if (!hashPlaceholder) {
  15079. this.bundle[fileName] = FILE_PLACEHOLDER;
  15080. }
  15081. // Caching is essential to not conflict with the file name reservation above
  15082. return (this.preliminaryFileName = { fileName, hashPlaceholder });
  15083. }
  15084. getPreliminarySourcemapFileName() {
  15085. if (this.preliminarySourcemapFileName) {
  15086. return this.preliminarySourcemapFileName;
  15087. }
  15088. let sourcemapFileName = null;
  15089. let hashPlaceholder = null;
  15090. const { sourcemapFileNames, format } = this.outputOptions;
  15091. if (sourcemapFileNames) {
  15092. const [pattern, patternName] = [sourcemapFileNames, 'output.sourcemapFileNames'];
  15093. sourcemapFileName = renderNamePattern(typeof pattern === 'function' ? pattern(this.getPreRenderedChunkInfo()) : pattern, patternName, {
  15094. chunkhash: () => this.getPreliminaryFileName().hashPlaceholder || '',
  15095. format: () => format,
  15096. hash: size => hashPlaceholder || (hashPlaceholder = this.getPlaceholder(patternName, size)),
  15097. name: () => this.getChunkName()
  15098. });
  15099. if (!hashPlaceholder) {
  15100. sourcemapFileName = makeUnique(sourcemapFileName, this.bundle);
  15101. }
  15102. }
  15103. else {
  15104. return null;
  15105. }
  15106. return (this.preliminarySourcemapFileName = { fileName: sourcemapFileName, hashPlaceholder });
  15107. }
  15108. getRenderedChunkInfo() {
  15109. if (this.renderedChunkInfo) {
  15110. return this.renderedChunkInfo;
  15111. }
  15112. return (this.renderedChunkInfo = {
  15113. ...this.getPreRenderedChunkInfo(),
  15114. dynamicImports: this.getDynamicDependencies().map(resolveFileName),
  15115. fileName: this.getFileName(),
  15116. // eslint-disable-next-line unicorn/prefer-spread
  15117. implicitlyLoadedBefore: Array.from(this.implicitlyLoadedBefore, resolveFileName),
  15118. importedBindings: getImportedBindingsPerDependency(this.getRenderedDependencies(), resolveFileName),
  15119. // eslint-disable-next-line unicorn/prefer-spread
  15120. imports: Array.from(this.dependencies, resolveFileName),
  15121. modules: this.renderedModules,
  15122. referencedFiles: this.getReferencedFiles()
  15123. });
  15124. }
  15125. getVariableExportName(variable) {
  15126. if (this.outputOptions.preserveModules && variable instanceof NamespaceVariable) {
  15127. return '*';
  15128. }
  15129. return this.exportNamesByVariable.get(variable)[0];
  15130. }
  15131. link() {
  15132. this.dependencies = getStaticDependencies(this, this.orderedModules, this.chunkByModule, this.externalChunkByModule);
  15133. for (const module of this.orderedModules) {
  15134. this.addImplicitlyLoadedBeforeFromModule(module);
  15135. this.setUpChunkImportsAndExportsForModule(module);
  15136. }
  15137. }
  15138. async render() {
  15139. const { dependencies, exportMode, facadeModule, inputOptions: { onLog }, outputOptions, pluginDriver, snippets } = this;
  15140. const { format, hoistTransitiveImports, preserveModules } = outputOptions;
  15141. // for static and dynamic entry points, add transitive dependencies to this
  15142. // chunk's dependencies to avoid loading latency
  15143. if (hoistTransitiveImports && !preserveModules && facadeModule !== null) {
  15144. for (const dep of dependencies) {
  15145. if (dep instanceof Chunk)
  15146. this.inlineChunkDependencies(dep);
  15147. }
  15148. }
  15149. const preliminaryFileName = this.getPreliminaryFileName();
  15150. const preliminarySourcemapFileName = this.getPreliminarySourcemapFileName();
  15151. const { accessedGlobals, indent, magicString, renderedSource, usedModules, usesTopLevelAwait } = this.renderModules(preliminaryFileName.fileName);
  15152. const renderedDependencies = [...this.getRenderedDependencies().values()];
  15153. const renderedExports = exportMode === 'none' ? [] : this.getChunkExportDeclarations(format);
  15154. let hasExports = renderedExports.length > 0;
  15155. let hasDefaultExport = false;
  15156. for (const renderedDependence of renderedDependencies) {
  15157. const { reexports } = renderedDependence;
  15158. if (reexports?.length) {
  15159. hasExports = true;
  15160. if (!hasDefaultExport && reexports.some(reexport => reexport.reexported === 'default')) {
  15161. hasDefaultExport = true;
  15162. }
  15163. if (format === 'es') {
  15164. renderedDependence.reexports = reexports.filter(
  15165. // eslint-disable-next-line unicorn/prefer-array-some
  15166. ({ reexported }) => !renderedExports.find(({ exported }) => exported === reexported));
  15167. }
  15168. }
  15169. }
  15170. if (!hasDefaultExport) {
  15171. for (const { exported } of renderedExports) {
  15172. if (exported === 'default') {
  15173. hasDefaultExport = true;
  15174. break;
  15175. }
  15176. }
  15177. }
  15178. const { intro, outro, banner, footer } = await createAddons(outputOptions, pluginDriver, this.getRenderedChunkInfo());
  15179. finalisers[format](renderedSource, {
  15180. accessedGlobals,
  15181. dependencies: renderedDependencies,
  15182. exports: renderedExports,
  15183. hasDefaultExport,
  15184. hasExports,
  15185. id: preliminaryFileName.fileName,
  15186. indent,
  15187. intro,
  15188. isEntryFacade: preserveModules || (facadeModule !== null && facadeModule.info.isEntry),
  15189. isModuleFacade: facadeModule !== null,
  15190. log: onLog,
  15191. namedExportsMode: exportMode !== 'default',
  15192. outro,
  15193. snippets,
  15194. usesTopLevelAwait
  15195. }, outputOptions);
  15196. if (banner)
  15197. magicString.prepend(banner);
  15198. if (footer)
  15199. magicString.append(footer);
  15200. return {
  15201. chunk: this,
  15202. magicString,
  15203. preliminaryFileName,
  15204. preliminarySourcemapFileName,
  15205. usedModules
  15206. };
  15207. }
  15208. addImplicitlyLoadedBeforeFromModule(baseModule) {
  15209. const { chunkByModule, implicitlyLoadedBefore } = this;
  15210. for (const module of baseModule.implicitlyLoadedBefore) {
  15211. const chunk = chunkByModule.get(module);
  15212. if (chunk && chunk !== this) {
  15213. implicitlyLoadedBefore.add(chunk);
  15214. }
  15215. }
  15216. }
  15217. addNecessaryImportsForFacades() {
  15218. for (const [module, variables] of this.includedReexportsByModule) {
  15219. if (this.includedNamespaces.has(module)) {
  15220. for (const variable of variables) {
  15221. this.imports.add(variable);
  15222. }
  15223. }
  15224. }
  15225. }
  15226. assignFacadeName({ fileName, name }, facadedModule, preservePath) {
  15227. if (fileName) {
  15228. this.fileName = fileName;
  15229. }
  15230. else {
  15231. this.name = this.outputOptions.sanitizeFileName(name ||
  15232. (preservePath
  15233. ? this.getPreserveModulesChunkNameFromModule(facadedModule)
  15234. : getChunkNameFromModule(facadedModule)));
  15235. }
  15236. }
  15237. checkCircularDependencyImport(variable, importingModule) {
  15238. const variableModule = variable.module;
  15239. if (variableModule instanceof Module) {
  15240. const exportChunk = this.chunkByModule.get(variableModule);
  15241. let alternativeReexportModule;
  15242. do {
  15243. alternativeReexportModule = importingModule.alternativeReexportModules.get(variable);
  15244. if (alternativeReexportModule) {
  15245. const exportingChunk = this.chunkByModule.get(alternativeReexportModule);
  15246. if (exportingChunk !== exportChunk) {
  15247. this.inputOptions.onLog(LOGLEVEL_WARN, logCyclicCrossChunkReexport(
  15248. // Namespaces do not have an export name
  15249. variableModule.getExportNamesByVariable().get(variable)?.[0] || '*', variableModule.id, alternativeReexportModule.id, importingModule.id, this.outputOptions.preserveModules));
  15250. }
  15251. importingModule = alternativeReexportModule;
  15252. }
  15253. } while (alternativeReexportModule);
  15254. }
  15255. }
  15256. ensureReexportsAreAvailableForModule(module) {
  15257. const includedReexports = [];
  15258. const map = module.getExportNamesByVariable();
  15259. for (const exportedVariable of map.keys()) {
  15260. const isSynthetic = exportedVariable instanceof SyntheticNamedExportVariable;
  15261. const importedVariable = isSynthetic ? exportedVariable.getBaseVariable() : exportedVariable;
  15262. this.checkCircularDependencyImport(importedVariable, module);
  15263. // When preserving modules, we do not create namespace objects but directly
  15264. // use the actual namespaces, which would be broken by this logic.
  15265. if (!(importedVariable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
  15266. const exportingModule = importedVariable.module;
  15267. if (exportingModule instanceof Module) {
  15268. const chunk = this.chunkByModule.get(exportingModule);
  15269. if (chunk && chunk !== this) {
  15270. chunk.exports.add(importedVariable);
  15271. includedReexports.push(importedVariable);
  15272. if (isSynthetic) {
  15273. this.imports.add(importedVariable);
  15274. }
  15275. }
  15276. }
  15277. }
  15278. }
  15279. if (includedReexports.length > 0) {
  15280. this.includedReexportsByModule.set(module, includedReexports);
  15281. }
  15282. }
  15283. generateVariableName() {
  15284. if (this.manualChunkAlias) {
  15285. return this.manualChunkAlias;
  15286. }
  15287. const moduleForNaming = this.entryModules[0] ||
  15288. this.implicitEntryModules[0] ||
  15289. this.dynamicEntryModules[0] ||
  15290. this.orderedModules[this.orderedModules.length - 1];
  15291. if (moduleForNaming) {
  15292. return getChunkNameFromModule(moduleForNaming);
  15293. }
  15294. return 'chunk';
  15295. }
  15296. getChunkExportDeclarations(format) {
  15297. const exports = [];
  15298. for (const exportName of this.getExportNames()) {
  15299. if (exportName[0] === '*')
  15300. continue;
  15301. const variable = this.exportsByName.get(exportName);
  15302. if (!(variable instanceof SyntheticNamedExportVariable)) {
  15303. const module = variable.module;
  15304. if (module) {
  15305. const chunk = this.chunkByModule.get(module);
  15306. if (chunk !== this) {
  15307. if (!chunk || format !== 'es') {
  15308. continue;
  15309. }
  15310. const chunkDep = this.renderedDependencies.get(chunk);
  15311. if (!chunkDep) {
  15312. continue;
  15313. }
  15314. const { imports, reexports } = chunkDep;
  15315. const importedByReexported = reexports?.find(({ reexported }) => reexported === exportName);
  15316. const isImported = imports?.find(({ imported }) => imported === importedByReexported?.imported);
  15317. if (!isImported) {
  15318. continue;
  15319. }
  15320. }
  15321. }
  15322. }
  15323. let expression = null;
  15324. let hoisted = false;
  15325. let local = variable.getName(this.snippets.getPropertyAccess);
  15326. if (variable instanceof LocalVariable) {
  15327. for (const declaration of variable.declarations) {
  15328. if (declaration.parent instanceof FunctionDeclaration ||
  15329. (declaration instanceof ExportDefaultDeclaration &&
  15330. declaration.declaration instanceof FunctionDeclaration)) {
  15331. hoisted = true;
  15332. break;
  15333. }
  15334. }
  15335. }
  15336. else if (variable instanceof SyntheticNamedExportVariable) {
  15337. expression = local;
  15338. if (format === 'es') {
  15339. local = variable.renderName;
  15340. }
  15341. }
  15342. exports.push({
  15343. exported: exportName,
  15344. expression,
  15345. hoisted,
  15346. local
  15347. });
  15348. }
  15349. return exports;
  15350. }
  15351. getDependenciesToBeDeconflicted(addNonNamespacesAndInteropHelpers, addDependenciesWithoutBindings, interop) {
  15352. const dependencies = new Set();
  15353. const deconflictedDefault = new Set();
  15354. const deconflictedNamespace = new Set();
  15355. for (const variable of [...this.exportNamesByVariable.keys(), ...this.imports]) {
  15356. if (addNonNamespacesAndInteropHelpers || variable.isNamespace) {
  15357. const module = variable.module;
  15358. if (module instanceof ExternalModule) {
  15359. const chunk = this.externalChunkByModule.get(module);
  15360. dependencies.add(chunk);
  15361. if (addNonNamespacesAndInteropHelpers) {
  15362. if (variable.name === 'default') {
  15363. if (defaultInteropHelpersByInteropType[interop(module.id)]) {
  15364. deconflictedDefault.add(chunk);
  15365. }
  15366. }
  15367. else if (variable.name === '*' &&
  15368. namespaceInteropHelpersByInteropType[interop(module.id)]) {
  15369. deconflictedNamespace.add(chunk);
  15370. }
  15371. }
  15372. }
  15373. else {
  15374. const chunk = this.chunkByModule.get(module);
  15375. if (chunk !== this) {
  15376. dependencies.add(chunk);
  15377. if (addNonNamespacesAndInteropHelpers &&
  15378. chunk.exportMode === 'default' &&
  15379. variable.isNamespace) {
  15380. deconflictedNamespace.add(chunk);
  15381. }
  15382. }
  15383. }
  15384. }
  15385. }
  15386. if (addDependenciesWithoutBindings) {
  15387. for (const dependency of this.dependencies) {
  15388. dependencies.add(dependency);
  15389. }
  15390. }
  15391. return { deconflictedDefault, deconflictedNamespace, dependencies };
  15392. }
  15393. getDynamicDependencies() {
  15394. return this.getIncludedDynamicImports()
  15395. .map(resolvedDynamicImport => resolvedDynamicImport.facadeChunk ||
  15396. resolvedDynamicImport.chunk ||
  15397. resolvedDynamicImport.externalChunk ||
  15398. resolvedDynamicImport.resolution)
  15399. .filter((resolution) => resolution !== this &&
  15400. (resolution instanceof Chunk || resolution instanceof ExternalChunk));
  15401. }
  15402. getDynamicImportStringAndAssertions(resolution, fileName) {
  15403. if (resolution instanceof ExternalModule) {
  15404. const chunk = this.externalChunkByModule.get(resolution);
  15405. return [`'${chunk.getImportPath(fileName)}'`, chunk.getImportAssertions(this.snippets)];
  15406. }
  15407. return [
  15408. resolution || '',
  15409. (this.outputOptions.format === 'es' && this.outputOptions.externalImportAssertions) || null
  15410. ];
  15411. }
  15412. getFallbackChunkName() {
  15413. if (this.manualChunkAlias) {
  15414. return this.manualChunkAlias;
  15415. }
  15416. if (this.dynamicName) {
  15417. return this.dynamicName;
  15418. }
  15419. if (this.fileName) {
  15420. return getAliasName(this.fileName);
  15421. }
  15422. return getAliasName(this.orderedModules[this.orderedModules.length - 1].id);
  15423. }
  15424. getImportSpecifiers() {
  15425. const { interop } = this.outputOptions;
  15426. const importsByDependency = new Map();
  15427. for (const variable of this.imports) {
  15428. const module = variable.module;
  15429. let dependency;
  15430. let imported;
  15431. if (module instanceof ExternalModule) {
  15432. dependency = this.externalChunkByModule.get(module);
  15433. imported = variable.name;
  15434. if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
  15435. return error(logUnexpectedNamedImport(module.id, imported, false));
  15436. }
  15437. }
  15438. else {
  15439. dependency = this.chunkByModule.get(module);
  15440. imported = dependency.getVariableExportName(variable);
  15441. }
  15442. getOrCreate(importsByDependency, dependency, getNewArray).push({
  15443. imported,
  15444. local: variable.getName(this.snippets.getPropertyAccess)
  15445. });
  15446. }
  15447. return importsByDependency;
  15448. }
  15449. getIncludedDynamicImports() {
  15450. if (this.includedDynamicImports) {
  15451. return this.includedDynamicImports;
  15452. }
  15453. const includedDynamicImports = [];
  15454. for (const module of this.orderedModules) {
  15455. for (const { node, resolution } of module.dynamicImports) {
  15456. if (!node.included) {
  15457. continue;
  15458. }
  15459. includedDynamicImports.push(resolution instanceof Module
  15460. ? {
  15461. chunk: this.chunkByModule.get(resolution),
  15462. externalChunk: null,
  15463. facadeChunk: this.facadeChunkByModule.get(resolution),
  15464. node,
  15465. resolution
  15466. }
  15467. : resolution instanceof ExternalModule
  15468. ? {
  15469. chunk: null,
  15470. externalChunk: this.externalChunkByModule.get(resolution),
  15471. facadeChunk: null,
  15472. node,
  15473. resolution
  15474. }
  15475. : { chunk: null, externalChunk: null, facadeChunk: null, node, resolution });
  15476. }
  15477. }
  15478. return (this.includedDynamicImports = includedDynamicImports);
  15479. }
  15480. getPreRenderedChunkInfo() {
  15481. if (this.preRenderedChunkInfo) {
  15482. return this.preRenderedChunkInfo;
  15483. }
  15484. const { dynamicEntryModules, facadeModule, implicitEntryModules, orderedModules } = this;
  15485. return (this.preRenderedChunkInfo = {
  15486. exports: this.getExportNames(),
  15487. facadeModuleId: facadeModule && facadeModule.id,
  15488. isDynamicEntry: dynamicEntryModules.length > 0,
  15489. isEntry: !!facadeModule?.info.isEntry,
  15490. isImplicitEntry: implicitEntryModules.length > 0,
  15491. moduleIds: orderedModules.map(({ id }) => id),
  15492. name: this.getChunkName(),
  15493. type: 'chunk'
  15494. });
  15495. }
  15496. getPreserveModulesChunkNameFromModule(module) {
  15497. const predefinedChunkName = getPredefinedChunkNameFromModule(module);
  15498. if (predefinedChunkName)
  15499. return predefinedChunkName;
  15500. const { preserveModulesRoot, sanitizeFileName } = this.outputOptions;
  15501. const sanitizedId = sanitizeFileName(normalize(module.id.split(QUERY_HASH_REGEX, 1)[0]));
  15502. const extensionName = extname(sanitizedId);
  15503. const idWithoutExtension = NON_ASSET_EXTENSIONS.has(extensionName)
  15504. ? sanitizedId.slice(0, -extensionName.length)
  15505. : sanitizedId;
  15506. if (isAbsolute(idWithoutExtension)) {
  15507. return preserveModulesRoot && resolve(idWithoutExtension).startsWith(preserveModulesRoot)
  15508. ? idWithoutExtension.slice(preserveModulesRoot.length).replace(/^[/\\]/, '')
  15509. : relative(this.inputBase, idWithoutExtension);
  15510. }
  15511. else {
  15512. return `_virtual/${basename(idWithoutExtension)}`;
  15513. }
  15514. }
  15515. getReexportSpecifiers() {
  15516. const { externalLiveBindings, interop } = this.outputOptions;
  15517. const reexportSpecifiers = new Map();
  15518. for (let exportName of this.getExportNames()) {
  15519. let dependency;
  15520. let imported;
  15521. let needsLiveBinding = false;
  15522. if (exportName[0] === '*') {
  15523. const id = exportName.slice(1);
  15524. if (interop(id) === 'defaultOnly') {
  15525. this.inputOptions.onLog(LOGLEVEL_WARN, logUnexpectedNamespaceReexport(id));
  15526. }
  15527. needsLiveBinding = externalLiveBindings;
  15528. dependency = this.externalChunkByModule.get(this.modulesById.get(id));
  15529. imported = exportName = '*';
  15530. }
  15531. else {
  15532. const variable = this.exportsByName.get(exportName);
  15533. if (variable instanceof SyntheticNamedExportVariable)
  15534. continue;
  15535. const module = variable.module;
  15536. if (module instanceof Module) {
  15537. dependency = this.chunkByModule.get(module);
  15538. if (dependency === this)
  15539. continue;
  15540. imported = dependency.getVariableExportName(variable);
  15541. needsLiveBinding = variable.isReassigned;
  15542. }
  15543. else {
  15544. dependency = this.externalChunkByModule.get(module);
  15545. imported = variable.name;
  15546. if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
  15547. return error(logUnexpectedNamedImport(module.id, imported, true));
  15548. }
  15549. needsLiveBinding =
  15550. externalLiveBindings &&
  15551. (imported !== 'default' || isDefaultAProperty(interop(module.id), true));
  15552. }
  15553. }
  15554. getOrCreate(reexportSpecifiers, dependency, getNewArray).push({
  15555. imported,
  15556. needsLiveBinding,
  15557. reexported: exportName
  15558. });
  15559. }
  15560. return reexportSpecifiers;
  15561. }
  15562. getReferencedFiles() {
  15563. const referencedFiles = new Set();
  15564. for (const module of this.orderedModules) {
  15565. for (const meta of module.importMetas) {
  15566. const fileName = meta.getReferencedFileName(this.pluginDriver);
  15567. if (fileName) {
  15568. referencedFiles.add(fileName);
  15569. }
  15570. }
  15571. }
  15572. return [...referencedFiles];
  15573. }
  15574. getRenderedDependencies() {
  15575. if (this.renderedDependencies) {
  15576. return this.renderedDependencies;
  15577. }
  15578. const importSpecifiers = this.getImportSpecifiers();
  15579. const reexportSpecifiers = this.getReexportSpecifiers();
  15580. const renderedDependencies = new Map();
  15581. const fileName = this.getFileName();
  15582. for (const dep of this.dependencies) {
  15583. const imports = importSpecifiers.get(dep) || null;
  15584. const reexports = reexportSpecifiers.get(dep) || null;
  15585. const namedExportsMode = dep instanceof ExternalChunk || dep.exportMode !== 'default';
  15586. const importPath = dep.getImportPath(fileName);
  15587. renderedDependencies.set(dep, {
  15588. assertions: dep instanceof ExternalChunk ? dep.getImportAssertions(this.snippets) : null,
  15589. defaultVariableName: dep.defaultVariableName,
  15590. globalName: dep instanceof ExternalChunk &&
  15591. (this.outputOptions.format === 'umd' || this.outputOptions.format === 'iife') &&
  15592. getGlobalName(dep, this.outputOptions.globals, (imports || reexports) !== null, this.inputOptions.onLog),
  15593. importPath,
  15594. imports,
  15595. isChunk: dep instanceof Chunk,
  15596. name: dep.variableName,
  15597. namedExportsMode,
  15598. namespaceVariableName: dep.namespaceVariableName,
  15599. reexports
  15600. });
  15601. }
  15602. return (this.renderedDependencies = renderedDependencies);
  15603. }
  15604. inlineChunkDependencies(chunk) {
  15605. for (const dep of chunk.dependencies) {
  15606. if (this.dependencies.has(dep))
  15607. continue;
  15608. this.dependencies.add(dep);
  15609. if (dep instanceof Chunk) {
  15610. this.inlineChunkDependencies(dep);
  15611. }
  15612. }
  15613. }
  15614. // This method changes properties on the AST before rendering and must not be async
  15615. renderModules(fileName) {
  15616. const { accessedGlobalsByScope, dependencies, exportNamesByVariable, includedNamespaces, inputOptions: { onLog }, isEmpty, orderedModules, outputOptions, pluginDriver, renderedModules, snippets } = this;
  15617. const { compact, dynamicImportFunction, format, freeze, namespaceToStringTag } = outputOptions;
  15618. const { _, cnst, n } = snippets;
  15619. this.setDynamicImportResolutions(fileName);
  15620. this.setImportMetaResolutions(fileName);
  15621. this.setIdentifierRenderResolutions();
  15622. const magicString = new Bundle$1({ separator: `${n}${n}` });
  15623. const indent = getIndentString(orderedModules, outputOptions);
  15624. const usedModules = [];
  15625. let hoistedSource = '';
  15626. const accessedGlobals = new Set();
  15627. const renderedModuleSources = new Map();
  15628. const renderOptions = {
  15629. accessedDocumentCurrentScript: false,
  15630. dynamicImportFunction,
  15631. exportNamesByVariable,
  15632. format,
  15633. freeze,
  15634. indent,
  15635. namespaceToStringTag,
  15636. pluginDriver,
  15637. snippets,
  15638. useOriginalName: null
  15639. };
  15640. let usesTopLevelAwait = false;
  15641. for (const module of orderedModules) {
  15642. let renderedLength = 0;
  15643. let source;
  15644. if (module.isIncluded() || includedNamespaces.has(module)) {
  15645. const rendered = module.render(renderOptions);
  15646. if (!renderOptions.accessedDocumentCurrentScript &&
  15647. formatsMaybeAccessDocumentCurrentScript.includes(format)) {
  15648. // eslint-disable-next-line unicorn/consistent-destructuring
  15649. this.accessedGlobalsByScope.get(module.scope)?.delete(DOCUMENT_CURRENT_SCRIPT);
  15650. }
  15651. renderOptions.accessedDocumentCurrentScript = false;
  15652. ({ source } = rendered);
  15653. usesTopLevelAwait || (usesTopLevelAwait = rendered.usesTopLevelAwait);
  15654. renderedLength = source.length();
  15655. if (renderedLength) {
  15656. if (compact && source.lastLine().includes('//'))
  15657. source.append('\n');
  15658. renderedModuleSources.set(module, source);
  15659. magicString.addSource(source);
  15660. usedModules.push(module);
  15661. }
  15662. const namespace = module.namespace;
  15663. if (includedNamespaces.has(module)) {
  15664. const rendered = namespace.renderBlock(renderOptions);
  15665. if (namespace.renderFirst())
  15666. hoistedSource += n + rendered;
  15667. else
  15668. magicString.addSource(new MagicString(rendered));
  15669. }
  15670. const accessedGlobalVariables = accessedGlobalsByScope.get(module.scope);
  15671. if (accessedGlobalVariables) {
  15672. for (const name of accessedGlobalVariables) {
  15673. accessedGlobals.add(name);
  15674. }
  15675. }
  15676. }
  15677. const { renderedExports, removedExports } = module.getRenderedExports();
  15678. renderedModules[module.id] = {
  15679. get code() {
  15680. return source?.toString() ?? null;
  15681. },
  15682. originalLength: module.originalCode.length,
  15683. removedExports,
  15684. renderedExports,
  15685. renderedLength
  15686. };
  15687. }
  15688. if (hoistedSource)
  15689. magicString.prepend(hoistedSource + n + n);
  15690. // eslint-disable-next-line unicorn/consistent-destructuring
  15691. if (this.needsExportsShim) {
  15692. magicString.prepend(`${n}${cnst} ${MISSING_EXPORT_SHIM_VARIABLE}${_}=${_}void 0;${n}${n}`);
  15693. }
  15694. const renderedSource = compact ? magicString : magicString.trim();
  15695. if (isEmpty && this.getExportNames().length === 0 && dependencies.size === 0) {
  15696. onLog(LOGLEVEL_WARN, logEmptyChunk(this.getChunkName()));
  15697. }
  15698. return { accessedGlobals, indent, magicString, renderedSource, usedModules, usesTopLevelAwait };
  15699. }
  15700. setDynamicImportResolutions(fileName) {
  15701. const { accessedGlobalsByScope, outputOptions, pluginDriver, snippets } = this;
  15702. for (const resolvedDynamicImport of this.getIncludedDynamicImports()) {
  15703. if (resolvedDynamicImport.chunk) {
  15704. const { chunk, facadeChunk, node, resolution } = resolvedDynamicImport;
  15705. if (chunk === this) {
  15706. node.setInternalResolution(resolution.namespace);
  15707. }
  15708. else {
  15709. node.setExternalResolution((facadeChunk || chunk).exportMode, resolution, outputOptions, snippets, pluginDriver, accessedGlobalsByScope, `'${(facadeChunk || chunk).getImportPath(fileName)}'`, !facadeChunk?.strictFacade && chunk.exportNamesByVariable.get(resolution.namespace)[0], null);
  15710. }
  15711. }
  15712. else {
  15713. const { node, resolution } = resolvedDynamicImport;
  15714. const [resolutionString, assertions] = this.getDynamicImportStringAndAssertions(resolution, fileName);
  15715. node.setExternalResolution('external', resolution, outputOptions, snippets, pluginDriver, accessedGlobalsByScope, resolutionString, false, assertions);
  15716. }
  15717. }
  15718. }
  15719. setIdentifierRenderResolutions() {
  15720. const { format, interop, namespaceToStringTag, preserveModules, externalLiveBindings } = this.outputOptions;
  15721. const syntheticExports = new Set();
  15722. for (const exportName of this.getExportNames()) {
  15723. const exportVariable = this.exportsByName.get(exportName);
  15724. if (format !== 'es' &&
  15725. format !== 'system' &&
  15726. exportVariable.isReassigned &&
  15727. !exportVariable.isId) {
  15728. exportVariable.setRenderNames('exports', exportName);
  15729. }
  15730. else if (exportVariable instanceof SyntheticNamedExportVariable) {
  15731. syntheticExports.add(exportVariable);
  15732. }
  15733. else {
  15734. exportVariable.setRenderNames(null, null);
  15735. }
  15736. }
  15737. for (const module of this.orderedModules) {
  15738. if (module.needsExportShim) {
  15739. this.needsExportsShim = true;
  15740. break;
  15741. }
  15742. }
  15743. const usedNames = new Set(['Object', 'Promise']);
  15744. if (this.needsExportsShim) {
  15745. usedNames.add(MISSING_EXPORT_SHIM_VARIABLE);
  15746. }
  15747. if (namespaceToStringTag) {
  15748. usedNames.add('Symbol');
  15749. }
  15750. switch (format) {
  15751. case 'system': {
  15752. usedNames.add('module').add('exports');
  15753. break;
  15754. }
  15755. case 'es': {
  15756. break;
  15757. }
  15758. case 'cjs': {
  15759. usedNames.add('module').add('require').add('__filename').add('__dirname');
  15760. }
  15761. // fallthrough
  15762. default: {
  15763. usedNames.add('exports');
  15764. for (const helper of HELPER_NAMES) {
  15765. usedNames.add(helper);
  15766. }
  15767. }
  15768. }
  15769. deconflictChunk(this.orderedModules, this.getDependenciesToBeDeconflicted(format !== 'es' && format !== 'system', format === 'amd' || format === 'umd' || format === 'iife', interop), this.imports, usedNames, format, interop, preserveModules, externalLiveBindings, this.chunkByModule, this.externalChunkByModule, syntheticExports, this.exportNamesByVariable, this.accessedGlobalsByScope, this.includedNamespaces);
  15770. }
  15771. setImportMetaResolutions(fileName) {
  15772. const { accessedGlobalsByScope, includedNamespaces, orderedModules, outputOptions: { format } } = this;
  15773. for (const module of orderedModules) {
  15774. for (const importMeta of module.importMetas) {
  15775. importMeta.setResolution(format, accessedGlobalsByScope, fileName);
  15776. }
  15777. if (includedNamespaces.has(module)) {
  15778. module.namespace.prepare(accessedGlobalsByScope);
  15779. }
  15780. }
  15781. }
  15782. setUpChunkImportsAndExportsForModule(module) {
  15783. const moduleImports = new Set(module.includedImports);
  15784. // when we are not preserving modules, we need to make all namespace variables available for
  15785. // rendering the namespace object
  15786. if (!this.outputOptions.preserveModules && this.includedNamespaces.has(module)) {
  15787. const memberVariables = module.namespace.getMemberVariables();
  15788. for (const variable of Object.values(memberVariables)) {
  15789. if (variable.included) {
  15790. moduleImports.add(variable);
  15791. }
  15792. }
  15793. }
  15794. for (let variable of moduleImports) {
  15795. if (variable instanceof ExportDefaultVariable) {
  15796. variable = variable.getOriginalVariable();
  15797. }
  15798. if (variable instanceof SyntheticNamedExportVariable) {
  15799. variable = variable.getBaseVariable();
  15800. }
  15801. const chunk = this.chunkByModule.get(variable.module);
  15802. if (chunk !== this) {
  15803. this.imports.add(variable);
  15804. if (variable.module instanceof Module) {
  15805. this.checkCircularDependencyImport(variable, module);
  15806. // When preserving modules, we do not create namespace objects but directly
  15807. // use the actual namespaces, which would be broken by this logic.
  15808. if (!(variable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
  15809. chunk.exports.add(variable);
  15810. }
  15811. }
  15812. }
  15813. }
  15814. if (this.includedNamespaces.has(module) ||
  15815. (module.info.isEntry && module.preserveSignature !== false) ||
  15816. module.includedDynamicImporters.some(importer => this.chunkByModule.get(importer) !== this)) {
  15817. this.ensureReexportsAreAvailableForModule(module);
  15818. }
  15819. for (const { node, resolution } of module.dynamicImports) {
  15820. if (node.included &&
  15821. resolution instanceof Module &&
  15822. this.chunkByModule.get(resolution) === this &&
  15823. !this.includedNamespaces.has(resolution)) {
  15824. this.includedNamespaces.add(resolution);
  15825. this.ensureReexportsAreAvailableForModule(resolution);
  15826. }
  15827. }
  15828. }
  15829. }
  15830. function getChunkNameFromModule(module) {
  15831. return getPredefinedChunkNameFromModule(module) ?? getAliasName(module.id);
  15832. }
  15833. function getPredefinedChunkNameFromModule(module) {
  15834. return (module.chunkNames.find(({ isUserDefined }) => isUserDefined)?.name ?? module.chunkNames[0]?.name);
  15835. }
  15836. function getImportedBindingsPerDependency(renderedDependencies, resolveFileName) {
  15837. const importedBindingsPerDependency = {};
  15838. for (const [dependency, declaration] of renderedDependencies) {
  15839. const specifiers = new Set();
  15840. if (declaration.imports) {
  15841. for (const { imported } of declaration.imports) {
  15842. specifiers.add(imported);
  15843. }
  15844. }
  15845. if (declaration.reexports) {
  15846. for (const { imported } of declaration.reexports) {
  15847. specifiers.add(imported);
  15848. }
  15849. }
  15850. importedBindingsPerDependency[resolveFileName(dependency)] = [...specifiers];
  15851. }
  15852. return importedBindingsPerDependency;
  15853. }
  15854. const QUERY_HASH_REGEX = /[#?]/;
  15855. const resolveFileName = (dependency) => dependency.getFileName();
  15856. /**
  15857. * Concatenate a number of iterables to a new iterable without fully evaluating
  15858. * their iterators. Useful when e.g. working with large sets or lists and when
  15859. * there is a chance that the iterators will not be fully exhausted.
  15860. */
  15861. function* concatLazy(iterables) {
  15862. for (const iterable of iterables) {
  15863. yield* iterable;
  15864. }
  15865. }
  15866. /**
  15867. * At its core, the algorithm first starts from each static or dynamic entry
  15868. * point and then assigns that entry point to all modules than can be reached
  15869. * via static imports. We call this the *dependent entry points* of that
  15870. * module.
  15871. *
  15872. * Then we group all modules with the same dependent entry points into chunks
  15873. * as those modules will always be loaded together.
  15874. *
  15875. * One non-trivial optimization we can apply is that dynamic entries are
  15876. * different from static entries in so far as when a dynamic import occurs,
  15877. * some
  15878. * modules are already in memory. If some of these modules are also
  15879. * dependencies
  15880. * of the dynamic entry, then it does not make sense to create a separate chunk
  15881. * for them. Instead, the dynamic import target can load them from the
  15882. * importing
  15883. * chunk.
  15884. *
  15885. * With regard to chunking, if B is implicitly loaded after A, then this can be
  15886. * handled the same way as if there was a dynamic import A => B.
  15887. *
  15888. * Example:
  15889. * Assume A -> B (A imports B), A => C (A dynamically imports C) and C -> B.
  15890. * Then the initial algorithm would assign A into the A chunk, C into the C
  15891. * chunk and B into the AC chunk, i.e. the chunk with the dependent entry
  15892. * points
  15893. * A and C.
  15894. * However we know that C can only be loaded from A, so A and its dependency B
  15895. * must already be in memory when C is loaded. So it is enough to create only
  15896. * two chunks A containing [AB] and C containing [C].
  15897. *
  15898. * So we do not assign the dynamic entry C as dependent entry point to modules
  15899. * that are already loaded.
  15900. *
  15901. * In a more complex example, let us assume that we have entry points X and Y.
  15902. * Further, let us assume
  15903. * X -> A, X -> B, X -> C,
  15904. * Y -> A, Y -> B,
  15905. * A => D,
  15906. * D -> B, D -> C
  15907. * So without dynamic import optimization, the dependent entry points are
  15908. * A: XY, B: DXY, C: DX, D: D, X: X, Y: Y,
  15909. * so we would for now create six chunks.
  15910. *
  15911. * Now D is loaded only after A is loaded. But A is loaded if either X is
  15912. * loaded
  15913. * or Y is loaded. So the modules that are already in memory when D is loaded
  15914. * are the intersection of all modules that X depends on with all modules that
  15915. * Y
  15916. * depends on, which in this case are the modules A and B.
  15917. * We could also say they are all modules that have both X and Y as dependent
  15918. * entry points.
  15919. *
  15920. * So we can remove D as dependent entry point from A and B, which means they
  15921. * both now have only XY as dependent entry points and can be merged into the
  15922. * same chunk.
  15923. *
  15924. * Now let us extend this to the most general case where we have several
  15925. * dynamic
  15926. * importers for one dynamic entry point.
  15927. *
  15928. * In the most general form, it works like this:
  15929. * For each dynamic entry point, we have a number of dynamic importers, which
  15930. * are the modules importing it. Using the previous ideas, we can determine
  15931. * the modules already in memory for each dynamic importer by looking for all
  15932. * modules that have all the dependent entry points of the dynamic importer as
  15933. * dependent entry points.
  15934. * So the modules that are guaranteed to be in memory when the dynamic entry
  15935. * point is loaded are the intersection of the modules already in memory for
  15936. * each dynamic importer.
  15937. *
  15938. * Assuming that A => D and B => D and A has dependent entry points XY and B
  15939. * has
  15940. * dependent entry points YZ, then the modules guaranteed to be in memory are
  15941. * all modules that have at least XYZ as dependent entry points.
  15942. * We call XYZ the *dynamically dependent entry points* of D.
  15943. *
  15944. * Now there is one last case to consider: If one of the dynamically dependent
  15945. * entries is itself a dynamic entry, then any module is in memory that either
  15946. * is a dependency of that dynamic entry or again has the dynamic dependent
  15947. * entries of that dynamic entry as dependent entry points.
  15948. *
  15949. * A naive algorithm for this proved to be costly as it contained an O(n^3)
  15950. * complexity with regard to dynamic entries that blew up for very large
  15951. * projects.
  15952. *
  15953. * If we have an efficient way to do Set operations, an alternative approach
  15954. * would be to instead collect already loaded modules per dynamic entry. And as
  15955. * all chunks from the initial grouping would behave the same, we can instead
  15956. * collect already loaded chunks for a performance improvement.
  15957. *
  15958. * To do that efficiently, need
  15959. * - a Map of dynamic imports per dynamic entry, which contains all dynamic
  15960. * imports that can be triggered by a dynamic entry
  15961. * - a Map of static dependencies per entry
  15962. * - a Map of already loaded chunks per entry that we initially populate with
  15963. * empty Sets for static entries and Sets containing all entries for dynamic
  15964. * entries
  15965. *
  15966. * For efficient operations, we assign each entry a numerical index and
  15967. * represent Sets of Chunks as BigInt values where each chunk corresponds to a
  15968. * bit index. Then thw last two maps can be represented as arrays of BigInt
  15969. * values.
  15970. *
  15971. * Then we iterate through each dynamic entry. We set the already loaded modules
  15972. * to the intersection of the previously already loaded modules with the union
  15973. * of the already loaded modules of that chunk with its static dependencies.
  15974. *
  15975. * If the already loaded modules changed, then we use the Map of dynamic imports
  15976. * per dynamic entry to marks all dynamic entry dependencies as "dirty" and put
  15977. * them back into the iteration. As an additional optimization, we note for
  15978. * each dynamic entry which dynamic dependent entries have changed and only
  15979. * intersect those entries again on subsequent interations.
  15980. *
  15981. * Then we remove the dynamic entries from the list of dependent entries for
  15982. * those chunks that are already loaded for that dynamic entry and create
  15983. * another round of chunks.
  15984. */
  15985. function getChunkAssignments(entries, manualChunkAliasByEntry, minChunkSize, log) {
  15986. const { chunkDefinitions, modulesInManualChunks } = getChunkDefinitionsFromManualChunks(manualChunkAliasByEntry);
  15987. const { allEntries, dependentEntriesByModule, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry } = analyzeModuleGraph(entries);
  15988. // Each chunk is identified by its position in this array
  15989. const initialChunks = getChunksFromDependentEntries(getModulesWithDependentEntries(dependentEntriesByModule, modulesInManualChunks));
  15990. // This mutates initialChunks but also clears
  15991. // dynamicallyDependentEntriesByDynamicEntry as side effect
  15992. removeUnnecessaryDependentEntries(initialChunks, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry, allEntries);
  15993. chunkDefinitions.push(...getOptimizedChunks(getChunksFromDependentEntries(initialChunks), allEntries.length, minChunkSize, log).map(({ modules }) => ({
  15994. alias: null,
  15995. modules
  15996. })));
  15997. return chunkDefinitions;
  15998. }
  15999. function getChunkDefinitionsFromManualChunks(manualChunkAliasByEntry) {
  16000. const chunkDefinitions = [];
  16001. const modulesInManualChunks = new Set(manualChunkAliasByEntry.keys());
  16002. const manualChunkModulesByAlias = Object.create(null);
  16003. for (const [entry, alias] of manualChunkAliasByEntry) {
  16004. addStaticDependenciesToManualChunk(entry, (manualChunkModulesByAlias[alias] || (manualChunkModulesByAlias[alias] = [])), modulesInManualChunks);
  16005. }
  16006. for (const [alias, modules] of Object.entries(manualChunkModulesByAlias)) {
  16007. chunkDefinitions.push({ alias, modules });
  16008. }
  16009. return { chunkDefinitions, modulesInManualChunks };
  16010. }
  16011. function addStaticDependenciesToManualChunk(entry, manualChunkModules, modulesInManualChunks) {
  16012. const modulesToHandle = new Set([entry]);
  16013. for (const module of modulesToHandle) {
  16014. modulesInManualChunks.add(module);
  16015. manualChunkModules.push(module);
  16016. for (const dependency of module.dependencies) {
  16017. if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
  16018. modulesToHandle.add(dependency);
  16019. }
  16020. }
  16021. }
  16022. }
  16023. function analyzeModuleGraph(entries) {
  16024. const dynamicEntryModules = new Set();
  16025. const dependentEntriesByModule = new Map();
  16026. const dynamicImportModulesByEntry = [];
  16027. const allEntriesSet = new Set(entries);
  16028. let entryIndex = 0;
  16029. for (const currentEntry of allEntriesSet) {
  16030. const dynamicImportsForCurrentEntry = new Set();
  16031. dynamicImportModulesByEntry.push(dynamicImportsForCurrentEntry);
  16032. const modulesToHandle = new Set([currentEntry]);
  16033. for (const module of modulesToHandle) {
  16034. getOrCreate(dependentEntriesByModule, module, (getNewSet)).add(entryIndex);
  16035. for (const dependency of module.getDependenciesToBeIncluded()) {
  16036. if (!(dependency instanceof ExternalModule)) {
  16037. modulesToHandle.add(dependency);
  16038. }
  16039. }
  16040. for (const { resolution } of module.dynamicImports) {
  16041. if (resolution instanceof Module &&
  16042. resolution.includedDynamicImporters.length > 0 &&
  16043. !allEntriesSet.has(resolution)) {
  16044. dynamicEntryModules.add(resolution);
  16045. allEntriesSet.add(resolution);
  16046. dynamicImportsForCurrentEntry.add(resolution);
  16047. }
  16048. }
  16049. for (const dependency of module.implicitlyLoadedBefore) {
  16050. if (!allEntriesSet.has(dependency)) {
  16051. dynamicEntryModules.add(dependency);
  16052. allEntriesSet.add(dependency);
  16053. }
  16054. }
  16055. }
  16056. entryIndex++;
  16057. }
  16058. const allEntries = [...allEntriesSet];
  16059. const { dynamicEntries, dynamicImportsByEntry } = getDynamicEntries(allEntries, dynamicEntryModules, dynamicImportModulesByEntry);
  16060. return {
  16061. allEntries,
  16062. dependentEntriesByModule,
  16063. dynamicallyDependentEntriesByDynamicEntry: getDynamicallyDependentEntriesByDynamicEntry(dependentEntriesByModule, dynamicEntries, allEntries),
  16064. dynamicImportsByEntry
  16065. };
  16066. }
  16067. function getDynamicEntries(allEntries, dynamicEntryModules, dynamicImportModulesByEntry) {
  16068. const entryIndexByModule = new Map();
  16069. const dynamicEntries = new Set();
  16070. for (const [entryIndex, entry] of allEntries.entries()) {
  16071. entryIndexByModule.set(entry, entryIndex);
  16072. if (dynamicEntryModules.has(entry)) {
  16073. dynamicEntries.add(entryIndex);
  16074. }
  16075. }
  16076. const dynamicImportsByEntry = [];
  16077. for (const dynamicImportModules of dynamicImportModulesByEntry) {
  16078. const dynamicImports = new Set();
  16079. for (const dynamicEntry of dynamicImportModules) {
  16080. dynamicImports.add(entryIndexByModule.get(dynamicEntry));
  16081. }
  16082. dynamicImportsByEntry.push(dynamicImports);
  16083. }
  16084. return { dynamicEntries, dynamicImportsByEntry };
  16085. }
  16086. function getDynamicallyDependentEntriesByDynamicEntry(dependentEntriesByModule, dynamicEntries, allEntries) {
  16087. const dynamicallyDependentEntriesByDynamicEntry = new Map();
  16088. for (const dynamicEntryIndex of dynamicEntries) {
  16089. const dynamicallyDependentEntries = getOrCreate(dynamicallyDependentEntriesByDynamicEntry, dynamicEntryIndex, (getNewSet));
  16090. const dynamicEntry = allEntries[dynamicEntryIndex];
  16091. for (const importer of concatLazy([
  16092. dynamicEntry.includedDynamicImporters,
  16093. dynamicEntry.implicitlyLoadedAfter
  16094. ])) {
  16095. for (const entry of dependentEntriesByModule.get(importer)) {
  16096. dynamicallyDependentEntries.add(entry);
  16097. }
  16098. }
  16099. }
  16100. return dynamicallyDependentEntriesByDynamicEntry;
  16101. }
  16102. function getChunksFromDependentEntries(modulesWithDependentEntries) {
  16103. var _a;
  16104. const chunkModules = Object.create(null);
  16105. for (const { dependentEntries, modules } of modulesWithDependentEntries) {
  16106. let chunkSignature = 0n;
  16107. for (const entryIndex of dependentEntries) {
  16108. chunkSignature |= 1n << BigInt(entryIndex);
  16109. }
  16110. (chunkModules[_a = String(chunkSignature)] || (chunkModules[_a] = {
  16111. dependentEntries: new Set(dependentEntries),
  16112. modules: []
  16113. })).modules.push(...modules);
  16114. }
  16115. return Object.values(chunkModules);
  16116. }
  16117. function* getModulesWithDependentEntries(dependentEntriesByModule, modulesInManualChunks) {
  16118. for (const [module, dependentEntries] of dependentEntriesByModule) {
  16119. if (!modulesInManualChunks.has(module)) {
  16120. yield { dependentEntries, modules: [module] };
  16121. }
  16122. }
  16123. }
  16124. /**
  16125. * This removes all unnecessary dynamic entries from the dependenEntries in its
  16126. * first argument. It will also consume its second argument, so if
  16127. * dynamicallyDependentEntriesByDynamicEntry is ever needed after this, we
  16128. * should make a copy.
  16129. */
  16130. function removeUnnecessaryDependentEntries(chunks, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry, allEntries) {
  16131. // The indices correspond to the indices in allEntries. The chunks correspond
  16132. // to bits in the bigint values where chunk 0 is the lowest bit.
  16133. const staticDependenciesPerEntry = allEntries.map(() => 0n);
  16134. const alreadyLoadedChunksPerEntry = allEntries.map((_entry, entryIndex) => dynamicallyDependentEntriesByDynamicEntry.has(entryIndex) ? -1n : 0n);
  16135. // This toggles the bits for each chunk that is a dependency of an entry
  16136. let chunkMask = 1n;
  16137. for (const { dependentEntries } of chunks) {
  16138. for (const entryIndex of dependentEntries) {
  16139. staticDependenciesPerEntry[entryIndex] |= chunkMask;
  16140. }
  16141. chunkMask <<= 1n;
  16142. }
  16143. // Warning: This will consume dynamicallyDependentEntriesByDynamicEntry.
  16144. // If we no longer want this, we should make a copy here.
  16145. const updatedDynamicallyDependentEntriesByDynamicEntry = dynamicallyDependentEntriesByDynamicEntry;
  16146. for (const [dynamicEntryIndex, updatedDynamicallyDependentEntries] of updatedDynamicallyDependentEntriesByDynamicEntry) {
  16147. updatedDynamicallyDependentEntriesByDynamicEntry.delete(dynamicEntryIndex);
  16148. const previousLoadedModules = alreadyLoadedChunksPerEntry[dynamicEntryIndex];
  16149. let newLoadedModules = previousLoadedModules;
  16150. for (const entryIndex of updatedDynamicallyDependentEntries) {
  16151. newLoadedModules &=
  16152. staticDependenciesPerEntry[entryIndex] | alreadyLoadedChunksPerEntry[entryIndex];
  16153. }
  16154. if (newLoadedModules !== previousLoadedModules) {
  16155. alreadyLoadedChunksPerEntry[dynamicEntryIndex] = newLoadedModules;
  16156. for (const dynamicImport of dynamicImportsByEntry[dynamicEntryIndex]) {
  16157. getOrCreate(updatedDynamicallyDependentEntriesByDynamicEntry, dynamicImport, (getNewSet)).add(dynamicEntryIndex);
  16158. }
  16159. }
  16160. }
  16161. // Remove entries from dependent entries if a chunk is already loaded without
  16162. // that entry.
  16163. chunkMask = 1n;
  16164. for (const { dependentEntries } of chunks) {
  16165. for (const entryIndex of dependentEntries) {
  16166. if ((alreadyLoadedChunksPerEntry[entryIndex] & chunkMask) === chunkMask) {
  16167. dependentEntries.delete(entryIndex);
  16168. }
  16169. }
  16170. chunkMask <<= 1n;
  16171. }
  16172. }
  16173. /**
  16174. * This function tries to get rid of small chunks by merging them with other
  16175. * chunks.
  16176. *
  16177. * We can only merge chunks safely if after the merge, loading any entry point
  16178. * in any allowed order will not trigger side effects that should not have been
  16179. * triggered. While side effects are usually things like global function calls,
  16180. * global variable mutations or potentially thrown errors, details do not
  16181. * matter here, and we just discern chunks without side effects (pure chunks)
  16182. * from other chunks.
  16183. *
  16184. * As a first step, we assign each pre-generated chunk with side effects a
  16185. * label. I.e. we have side effect "A" if the non-pure chunk "A" is loaded.
  16186. *
  16187. * Now to determine the side effects of loading a chunk, one also has to take
  16188. * the side effects of its dependencies into account. So if A depends on B
  16189. * (A -> B) and both have side effects, loading A triggers effects AB.
  16190. *
  16191. * Now from the previous step we know that each chunk is uniquely determine by
  16192. * the entry points that depend on it and cause it to load, which we will call
  16193. * its dependent entry points.
  16194. *
  16195. * E.g. if X -> A and Y -> A, then the dependent entry points of A are XY.
  16196. * Starting from that idea, we can determine a set of chunks—and thus a set
  16197. * of side effects—that must have been triggered if a certain chunk has been
  16198. * loaded. Basically, it is the intersection of all chunks loaded by the
  16199. * dependent entry points of a given chunk. We call the corresponding side
  16200. * effects the correlated side effects of that chunk.
  16201. *
  16202. * Example:
  16203. * X -> ABC, Y -> ADE, A-> F, B -> D
  16204. * Then taking dependencies into account, X -> ABCDF, Y -> ADEF
  16205. * The intersection is ADF. So we know that when A is loaded, D and F must also
  16206. * be in memory even though neither D nor A is a dependency of the other.
  16207. * If all have side effects, we call ADF the correlated side effects of A. The
  16208. * correlated side effects need to remain constant when merging chunks.
  16209. *
  16210. * In contrast, we have the dependency side effects of A, which represents
  16211. * the side effects we trigger if we directly load A. In this example, the
  16212. * dependency side effects are AF.
  16213. * For entry chunks, dependency and correlated side effects are the same.
  16214. *
  16215. * With these concepts, merging chunks is allowed if the correlated side
  16216. * effects of each entry do not change. Thus, we are allowed to merge two
  16217. * chunks if
  16218. *
  16219. * a) the dependency side effects of each chunk are a subset of the correlated
  16220. * side effects of the other chunk, so no additional side effects are
  16221. * triggered for any entry, or
  16222. * b) The dependent entry points of chunk A are a subset of the dependent entry
  16223. * points of chunk B while the dependency side effects of A are a subset of
  16224. * the correlated side effects of B. Because in that scenario, whenever A is
  16225. * loaded, B is loaded as well. But there are cases when B is loaded where A
  16226. * is not loaded. So if we merge the chunks, all dependency side effects of
  16227. * A will be added to the correlated side effects of B, and as the latter is
  16228. * not allowed to change, the former need to be a subset of the latter.
  16229. *
  16230. * Another consideration when merging small chunks into other chunks is to
  16231. * avoid
  16232. * that too much additional code is loaded. This is achieved when the dependent
  16233. * entries of the small chunk are a subset of the dependent entries of the
  16234. * other
  16235. * chunk. Because then when the small chunk is loaded, the other chunk was
  16236. * loaded/in memory anyway, so at most when the other chunk is loaded, the
  16237. * additional size of the small chunk is loaded unnecessarily.
  16238. *
  16239. * So the algorithm performs merges in two passes:
  16240. *
  16241. * 1. First we try to merge small chunks A only into other chunks B if the
  16242. * dependent entries of A are a subset of the dependent entries of B and the
  16243. * dependency side effects of A are a subset of the correlated side effects
  16244. * of B.
  16245. * 2. Only then for all remaining small chunks, we look for arbitrary merges
  16246. * following the rule (a), starting with the smallest chunks to look for
  16247. * possible merge targets.
  16248. */
  16249. function getOptimizedChunks(initialChunks, numberOfEntries, minChunkSize, log) {
  16250. timeStart('optimize chunks', 3);
  16251. const chunkPartition = getPartitionedChunks(initialChunks, numberOfEntries, minChunkSize);
  16252. if (!chunkPartition) {
  16253. timeEnd('optimize chunks', 3);
  16254. return initialChunks; // the actual modules
  16255. }
  16256. minChunkSize > 1 &&
  16257. log('info', logOptimizeChunkStatus(initialChunks.length, chunkPartition.small.size, 'Initially'));
  16258. mergeChunks(chunkPartition, minChunkSize);
  16259. minChunkSize > 1 &&
  16260. log('info', logOptimizeChunkStatus(chunkPartition.small.size + chunkPartition.big.size, chunkPartition.small.size, 'After merging chunks'));
  16261. timeEnd('optimize chunks', 3);
  16262. return [...chunkPartition.small, ...chunkPartition.big];
  16263. }
  16264. function getPartitionedChunks(initialChunks, numberOfEntries, minChunkSize) {
  16265. const smallChunks = [];
  16266. const bigChunks = [];
  16267. const chunkByModule = new Map();
  16268. const sizeByAtom = [];
  16269. let sideEffectAtoms = 0n;
  16270. let containedAtoms = 1n;
  16271. for (const { dependentEntries, modules } of initialChunks) {
  16272. const chunkDescription = {
  16273. containedAtoms,
  16274. correlatedAtoms: 0n,
  16275. dependencies: new Set(),
  16276. dependentChunks: new Set(),
  16277. dependentEntries,
  16278. modules,
  16279. pure: true,
  16280. size: 0
  16281. };
  16282. let size = 0;
  16283. let pure = true;
  16284. for (const module of modules) {
  16285. chunkByModule.set(module, chunkDescription);
  16286. // Unfortunately, we cannot take tree-shaking into account here because
  16287. // rendering did not happen yet, but we can detect empty modules
  16288. if (module.isIncluded()) {
  16289. pure && (pure = !module.hasEffects());
  16290. // we use a trivial size for the default minChunkSize to improve
  16291. // performance
  16292. size += minChunkSize > 1 ? module.estimateSize() : 1;
  16293. }
  16294. }
  16295. chunkDescription.pure = pure;
  16296. chunkDescription.size = size;
  16297. sizeByAtom.push(size);
  16298. if (!pure) {
  16299. sideEffectAtoms |= containedAtoms;
  16300. }
  16301. (size < minChunkSize ? smallChunks : bigChunks).push(chunkDescription);
  16302. containedAtoms <<= 1n;
  16303. }
  16304. // If there are no small chunks, we will not optimize
  16305. if (smallChunks.length === 0) {
  16306. return null;
  16307. }
  16308. sideEffectAtoms |= addChunkDependenciesAndAtomsAndGetSideEffectAtoms([bigChunks, smallChunks], chunkByModule, numberOfEntries, containedAtoms);
  16309. return {
  16310. big: new Set(bigChunks),
  16311. sideEffectAtoms,
  16312. sizeByAtom,
  16313. small: new Set(smallChunks)
  16314. };
  16315. }
  16316. function mergeChunks(chunkPartition, minChunkSize) {
  16317. const { small } = chunkPartition;
  16318. for (const mergedChunk of small) {
  16319. const bestTargetChunk = findBestMergeTarget(mergedChunk, chunkPartition,
  16320. // In the default case, we do not accept size increases
  16321. minChunkSize <= 1 ? 1 : Infinity);
  16322. if (bestTargetChunk) {
  16323. const { containedAtoms, correlatedAtoms, modules, pure, size } = mergedChunk;
  16324. small.delete(mergedChunk);
  16325. getChunksInPartition(bestTargetChunk, minChunkSize, chunkPartition).delete(bestTargetChunk);
  16326. bestTargetChunk.modules.push(...modules);
  16327. bestTargetChunk.size += size;
  16328. bestTargetChunk.pure && (bestTargetChunk.pure = pure);
  16329. const { dependencies, dependentChunks, dependentEntries } = bestTargetChunk;
  16330. bestTargetChunk.correlatedAtoms &= correlatedAtoms;
  16331. bestTargetChunk.containedAtoms |= containedAtoms;
  16332. for (const entry of mergedChunk.dependentEntries) {
  16333. dependentEntries.add(entry);
  16334. }
  16335. for (const dependency of mergedChunk.dependencies) {
  16336. dependencies.add(dependency);
  16337. dependency.dependentChunks.delete(mergedChunk);
  16338. dependency.dependentChunks.add(bestTargetChunk);
  16339. }
  16340. for (const dependentChunk of mergedChunk.dependentChunks) {
  16341. dependentChunks.add(dependentChunk);
  16342. dependentChunk.dependencies.delete(mergedChunk);
  16343. dependentChunk.dependencies.add(bestTargetChunk);
  16344. }
  16345. dependencies.delete(bestTargetChunk);
  16346. dependentChunks.delete(bestTargetChunk);
  16347. getChunksInPartition(bestTargetChunk, minChunkSize, chunkPartition).add(bestTargetChunk);
  16348. }
  16349. }
  16350. }
  16351. function addChunkDependenciesAndAtomsAndGetSideEffectAtoms(chunkLists, chunkByModule, numberOfEntries, nextAtomSignature) {
  16352. const signatureByExternalModule = new Map();
  16353. let sideEffectAtoms = 0n;
  16354. const atomsByEntry = [];
  16355. for (let index = 0; index < numberOfEntries; index++) {
  16356. atomsByEntry.push(0n);
  16357. }
  16358. for (const chunks of chunkLists) {
  16359. chunks.sort(compareChunkSize);
  16360. for (const chunk of chunks) {
  16361. const { dependencies, dependentEntries, modules } = chunk;
  16362. for (const module of modules) {
  16363. for (const dependency of module.getDependenciesToBeIncluded()) {
  16364. if (dependency instanceof ExternalModule) {
  16365. if (dependency.info.moduleSideEffects) {
  16366. chunk.containedAtoms |= getOrCreate(signatureByExternalModule, dependency, () => {
  16367. const signature = nextAtomSignature;
  16368. nextAtomSignature <<= 1n;
  16369. sideEffectAtoms |= signature;
  16370. return signature;
  16371. });
  16372. }
  16373. }
  16374. else {
  16375. const dependencyChunk = chunkByModule.get(dependency);
  16376. if (dependencyChunk && dependencyChunk !== chunk) {
  16377. dependencies.add(dependencyChunk);
  16378. dependencyChunk.dependentChunks.add(chunk);
  16379. }
  16380. }
  16381. }
  16382. }
  16383. const { containedAtoms } = chunk;
  16384. for (const entryIndex of dependentEntries) {
  16385. atomsByEntry[entryIndex] |= containedAtoms;
  16386. }
  16387. }
  16388. }
  16389. for (const chunks of chunkLists) {
  16390. for (const chunk of chunks) {
  16391. const { dependentEntries } = chunk;
  16392. // Correlated atoms are the intersection of all entry atoms
  16393. chunk.correlatedAtoms = -1n;
  16394. for (const entryIndex of dependentEntries) {
  16395. chunk.correlatedAtoms &= atomsByEntry[entryIndex];
  16396. }
  16397. }
  16398. }
  16399. return sideEffectAtoms;
  16400. }
  16401. function findBestMergeTarget(mergedChunk, { big, sideEffectAtoms, sizeByAtom, small }, smallestAdditionalSize) {
  16402. let bestTargetChunk = null;
  16403. // In the default case, we do not accept size increases
  16404. for (const targetChunk of concatLazy([small, big])) {
  16405. if (mergedChunk === targetChunk)
  16406. continue;
  16407. const additionalSizeAfterMerge = getAdditionalSizeAfterMerge(mergedChunk, targetChunk, smallestAdditionalSize, sideEffectAtoms, sizeByAtom);
  16408. if (additionalSizeAfterMerge < smallestAdditionalSize) {
  16409. bestTargetChunk = targetChunk;
  16410. if (additionalSizeAfterMerge === 0)
  16411. break;
  16412. smallestAdditionalSize = additionalSizeAfterMerge;
  16413. }
  16414. }
  16415. return bestTargetChunk;
  16416. }
  16417. function getChunksInPartition(chunk, minChunkSize, chunkPartition) {
  16418. return chunk.size < minChunkSize ? chunkPartition.small : chunkPartition.big;
  16419. }
  16420. function compareChunkSize({ size: sizeA }, { size: sizeB }) {
  16421. return sizeA - sizeB;
  16422. }
  16423. /**
  16424. * Determine the additional unused code size that would be added by merging the
  16425. * two chunks. This is not an exact measurement but rather an upper bound. If
  16426. * the merge produces cycles or adds non-correlated side effects, `Infinity`
  16427. * is returned.
  16428. * Merging will not produce cycles if none of the direct non-merged
  16429. * dependencies of a chunk have the other chunk as a transitive dependency.
  16430. */
  16431. function getAdditionalSizeAfterMerge(mergedChunk, targetChunk,
  16432. // The maximum additional unused code size allowed to be added by the merge,
  16433. // taking dependencies into account, needs to be below this number
  16434. currentAdditionalSize, sideEffectAtoms, sizeByAtom) {
  16435. const firstSize = getAdditionalSizeIfNoTransitiveDependencyOrNonCorrelatedSideEffect(mergedChunk, targetChunk, currentAdditionalSize, sideEffectAtoms, sizeByAtom);
  16436. return firstSize < currentAdditionalSize
  16437. ? firstSize +
  16438. getAdditionalSizeIfNoTransitiveDependencyOrNonCorrelatedSideEffect(targetChunk, mergedChunk, currentAdditionalSize - firstSize, sideEffectAtoms, sizeByAtom)
  16439. : Infinity;
  16440. }
  16441. function getAdditionalSizeIfNoTransitiveDependencyOrNonCorrelatedSideEffect(dependentChunk, dependencyChunk, currentAdditionalSize, sideEffectAtoms, sizeByAtom) {
  16442. const { correlatedAtoms } = dependencyChunk;
  16443. let dependencyAtoms = dependentChunk.containedAtoms;
  16444. const dependentContainedSideEffects = dependencyAtoms & sideEffectAtoms;
  16445. if ((correlatedAtoms & dependentContainedSideEffects) !== dependentContainedSideEffects) {
  16446. return Infinity;
  16447. }
  16448. const chunksToCheck = new Set(dependentChunk.dependencies);
  16449. for (const { dependencies, containedAtoms } of chunksToCheck) {
  16450. dependencyAtoms |= containedAtoms;
  16451. const containedSideEffects = containedAtoms & sideEffectAtoms;
  16452. if ((correlatedAtoms & containedSideEffects) !== containedSideEffects) {
  16453. return Infinity;
  16454. }
  16455. for (const dependency of dependencies) {
  16456. if (dependency === dependencyChunk) {
  16457. return Infinity;
  16458. }
  16459. chunksToCheck.add(dependency);
  16460. }
  16461. }
  16462. return getAtomsSizeIfBelowLimit(dependencyAtoms & ~correlatedAtoms, currentAdditionalSize, sizeByAtom);
  16463. }
  16464. function getAtomsSizeIfBelowLimit(atoms, currentAdditionalSize, sizeByAtom) {
  16465. let size = 0;
  16466. let atomIndex = 0;
  16467. let atomSignature = 1n;
  16468. const { length } = sizeByAtom;
  16469. for (; atomIndex < length; atomIndex++) {
  16470. if ((atoms & atomSignature) === atomSignature) {
  16471. size += sizeByAtom[atomIndex];
  16472. }
  16473. atomSignature <<= 1n;
  16474. if (size >= currentAdditionalSize) {
  16475. return Infinity;
  16476. }
  16477. }
  16478. return size;
  16479. }
  16480. // ported from https://github.com/substack/node-commondir
  16481. function commondir(files) {
  16482. if (files.length === 0)
  16483. return '/';
  16484. if (files.length === 1)
  16485. return dirname(files[0]);
  16486. const commonSegments = files.slice(1).reduce((commonSegments, file) => {
  16487. const pathSegements = file.split(/\/+|\\+/);
  16488. let index;
  16489. for (index = 0; commonSegments[index] === pathSegements[index] &&
  16490. index < Math.min(commonSegments.length, pathSegements.length); index++)
  16491. ;
  16492. return commonSegments.slice(0, index);
  16493. }, files[0].split(/\/+|\\+/));
  16494. // Windows correctly handles paths with forward-slashes
  16495. return commonSegments.length > 1 ? commonSegments.join('/') : '/';
  16496. }
  16497. const compareExecIndex = (unitA, unitB) => unitA.execIndex > unitB.execIndex ? 1 : -1;
  16498. function sortByExecutionOrder(units) {
  16499. units.sort(compareExecIndex);
  16500. }
  16501. function analyseModuleExecution(entryModules) {
  16502. let nextExecIndex = 0;
  16503. const cyclePaths = [];
  16504. const analysedModules = new Set();
  16505. const dynamicImports = new Set();
  16506. const parents = new Map();
  16507. const orderedModules = [];
  16508. const analyseModule = (module) => {
  16509. if (module instanceof Module) {
  16510. for (const dependency of module.dependencies) {
  16511. if (parents.has(dependency)) {
  16512. if (!analysedModules.has(dependency)) {
  16513. cyclePaths.push(getCyclePath(dependency, module, parents));
  16514. }
  16515. continue;
  16516. }
  16517. parents.set(dependency, module);
  16518. analyseModule(dependency);
  16519. }
  16520. for (const dependency of module.implicitlyLoadedBefore) {
  16521. dynamicImports.add(dependency);
  16522. }
  16523. for (const { resolution } of module.dynamicImports) {
  16524. if (resolution instanceof Module) {
  16525. dynamicImports.add(resolution);
  16526. }
  16527. }
  16528. orderedModules.push(module);
  16529. }
  16530. module.execIndex = nextExecIndex++;
  16531. analysedModules.add(module);
  16532. };
  16533. for (const currentEntry of entryModules) {
  16534. if (!parents.has(currentEntry)) {
  16535. parents.set(currentEntry, null);
  16536. analyseModule(currentEntry);
  16537. }
  16538. }
  16539. for (const currentEntry of dynamicImports) {
  16540. if (!parents.has(currentEntry)) {
  16541. parents.set(currentEntry, null);
  16542. analyseModule(currentEntry);
  16543. }
  16544. }
  16545. return { cyclePaths, orderedModules };
  16546. }
  16547. function getCyclePath(module, parent, parents) {
  16548. const cycleSymbol = Symbol(module.id);
  16549. const path = [module.id];
  16550. let nextModule = parent;
  16551. module.cycles.add(cycleSymbol);
  16552. while (nextModule !== module) {
  16553. nextModule.cycles.add(cycleSymbol);
  16554. path.push(nextModule.id);
  16555. nextModule = parents.get(nextModule);
  16556. }
  16557. path.push(path[0]);
  16558. path.reverse();
  16559. return path;
  16560. }
  16561. function getGenerateCodeSnippets({ compact, generatedCode: { arrowFunctions, constBindings, objectShorthand, reservedNamesAsProps } }) {
  16562. const { _, n, s } = compact ? { _: '', n: '', s: '' } : { _: ' ', n: '\n', s: ';' };
  16563. const cnst = constBindings ? 'const' : 'var';
  16564. const getNonArrowFunctionIntro = (parameters, { isAsync, name }) => `${isAsync ? `async ` : ''}function${name ? ` ${name}` : ''}${_}(${parameters.join(`,${_}`)})${_}`;
  16565. const getFunctionIntro = arrowFunctions
  16566. ? (parameters, { isAsync, name }) => {
  16567. const singleParameter = parameters.length === 1;
  16568. const asyncString = isAsync ? `async${singleParameter ? ' ' : _}` : '';
  16569. return `${name ? `${cnst} ${name}${_}=${_}` : ''}${asyncString}${singleParameter ? parameters[0] : `(${parameters.join(`,${_}`)})`}${_}=>${_}`;
  16570. }
  16571. : getNonArrowFunctionIntro;
  16572. const getDirectReturnFunction = (parameters, { functionReturn, lineBreakIndent, name }) => [
  16573. `${getFunctionIntro(parameters, {
  16574. isAsync: false,
  16575. name
  16576. })}${arrowFunctions
  16577. ? lineBreakIndent
  16578. ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}`
  16579. : ''
  16580. : `{${lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _}${functionReturn ? 'return ' : ''}`}`,
  16581. arrowFunctions
  16582. ? `${name ? ';' : ''}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : ''}`
  16583. : `${s}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`
  16584. ];
  16585. const isValidPropertyName = reservedNamesAsProps
  16586. ? (name) => validPropertyName.test(name)
  16587. : (name) => !RESERVED_NAMES$1.has(name) && validPropertyName.test(name);
  16588. return {
  16589. _,
  16590. cnst,
  16591. getDirectReturnFunction,
  16592. getDirectReturnIifeLeft: (parameters, returned, { needsArrowReturnParens, needsWrappedFunction }) => {
  16593. const [left, right] = getDirectReturnFunction(parameters, {
  16594. functionReturn: true,
  16595. lineBreakIndent: null,
  16596. name: null
  16597. });
  16598. return `${wrapIfNeeded(`${left}${wrapIfNeeded(returned, arrowFunctions && needsArrowReturnParens)}${right}`, arrowFunctions || needsWrappedFunction)}(`;
  16599. },
  16600. getFunctionIntro,
  16601. getNonArrowFunctionIntro,
  16602. getObject(fields, { lineBreakIndent }) {
  16603. const prefix = lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _;
  16604. return `{${fields
  16605. .map(([key, value]) => {
  16606. if (key === null)
  16607. return `${prefix}${value}`;
  16608. const needsQuotes = !isValidPropertyName(key);
  16609. return key === value && objectShorthand && !needsQuotes
  16610. ? prefix + key
  16611. : `${prefix}${needsQuotes ? `'${key}'` : key}:${_}${value}`;
  16612. })
  16613. .join(`,`)}${fields.length === 0 ? '' : lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`;
  16614. },
  16615. getPropertyAccess: (name) => isValidPropertyName(name) ? `.${name}` : `[${JSON.stringify(name)}]`,
  16616. n,
  16617. s
  16618. };
  16619. }
  16620. const wrapIfNeeded = (code, needsParens) => needsParens ? `(${code})` : code;
  16621. const validPropertyName = /^(?!\d)[\w$]+$/;
  16622. class Source {
  16623. constructor(filename, content) {
  16624. this.isOriginal = true;
  16625. this.filename = filename;
  16626. this.content = content;
  16627. }
  16628. traceSegment(line, column, name) {
  16629. return { column, line, name, source: this };
  16630. }
  16631. }
  16632. class Link {
  16633. constructor(map, sources) {
  16634. this.sources = sources;
  16635. this.names = map.names;
  16636. this.mappings = map.mappings;
  16637. }
  16638. traceMappings() {
  16639. const sources = [];
  16640. const sourceIndexMap = new Map();
  16641. const sourcesContent = [];
  16642. const names = [];
  16643. const nameIndexMap = new Map();
  16644. const mappings = [];
  16645. for (const line of this.mappings) {
  16646. const tracedLine = [];
  16647. for (const segment of line) {
  16648. if (segment.length === 1)
  16649. continue;
  16650. const source = this.sources[segment[1]];
  16651. if (!source)
  16652. continue;
  16653. const traced = source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : '');
  16654. if (traced) {
  16655. const { column, line, name, source: { content, filename } } = traced;
  16656. let sourceIndex = sourceIndexMap.get(filename);
  16657. if (sourceIndex === undefined) {
  16658. sourceIndex = sources.length;
  16659. sources.push(filename);
  16660. sourceIndexMap.set(filename, sourceIndex);
  16661. sourcesContent[sourceIndex] = content;
  16662. }
  16663. else if (sourcesContent[sourceIndex] == null) {
  16664. sourcesContent[sourceIndex] = content;
  16665. }
  16666. else if (content != null && sourcesContent[sourceIndex] !== content) {
  16667. return error(logConflictingSourcemapSources(filename));
  16668. }
  16669. const tracedSegment = [segment[0], sourceIndex, line, column];
  16670. if (name) {
  16671. let nameIndex = nameIndexMap.get(name);
  16672. if (nameIndex === undefined) {
  16673. nameIndex = names.length;
  16674. names.push(name);
  16675. nameIndexMap.set(name, nameIndex);
  16676. }
  16677. tracedSegment[4] = nameIndex;
  16678. }
  16679. tracedLine.push(tracedSegment);
  16680. }
  16681. }
  16682. mappings.push(tracedLine);
  16683. }
  16684. return { mappings, names, sources, sourcesContent };
  16685. }
  16686. traceSegment(line, column, name) {
  16687. const segments = this.mappings[line];
  16688. if (!segments)
  16689. return null;
  16690. // binary search through segments for the given column
  16691. let searchStart = 0;
  16692. let searchEnd = segments.length - 1;
  16693. while (searchStart <= searchEnd) {
  16694. const m = (searchStart + searchEnd) >> 1;
  16695. const segment = segments[m];
  16696. // If a sourcemap does not have sufficient resolution to contain a
  16697. // necessary mapping, e.g. because it only contains line information, we
  16698. // use the best approximation we could find
  16699. if (segment[0] === column || searchStart === searchEnd) {
  16700. if (segment.length == 1)
  16701. return null;
  16702. const source = this.sources[segment[1]];
  16703. if (!source)
  16704. return null;
  16705. return source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : name);
  16706. }
  16707. if (segment[0] > column) {
  16708. searchEnd = m - 1;
  16709. }
  16710. else {
  16711. searchStart = m + 1;
  16712. }
  16713. }
  16714. return null;
  16715. }
  16716. }
  16717. function getLinkMap(log) {
  16718. return function linkMap(source, map) {
  16719. if (!map.missing) {
  16720. return new Link(map, [source]);
  16721. }
  16722. log(LOGLEVEL_WARN, logSourcemapBroken(map.plugin));
  16723. return new Link({
  16724. mappings: [],
  16725. names: []
  16726. }, [source]);
  16727. };
  16728. }
  16729. function getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, linkMap) {
  16730. let source;
  16731. if (originalSourcemap) {
  16732. const sources = originalSourcemap.sources;
  16733. const sourcesContent = originalSourcemap.sourcesContent || [];
  16734. const directory = dirname(id) || '.';
  16735. const sourceRoot = originalSourcemap.sourceRoot || '.';
  16736. const baseSources = sources.map((source, index) => new Source(resolve(directory, sourceRoot, source), sourcesContent[index]));
  16737. source = new Link(originalSourcemap, baseSources);
  16738. }
  16739. else {
  16740. source = new Source(id, originalCode);
  16741. }
  16742. return sourcemapChain.reduce(linkMap, source);
  16743. }
  16744. function collapseSourcemaps(file, map, modules, bundleSourcemapChain, excludeContent, log) {
  16745. const linkMap = getLinkMap(log);
  16746. const moduleSources = modules
  16747. .filter(module => !module.excludeFromSourcemap)
  16748. .map(module => getCollapsedSourcemap(module.id, module.originalCode, module.originalSourcemap, module.sourcemapChain, linkMap));
  16749. const link = new Link(map, moduleSources);
  16750. const source = bundleSourcemapChain.reduce(linkMap, link);
  16751. let { sources, sourcesContent, names, mappings } = source.traceMappings();
  16752. if (file) {
  16753. const directory = dirname(file);
  16754. sources = sources.map((source) => relative$1(directory, source));
  16755. file = basename(file);
  16756. }
  16757. sourcesContent = (excludeContent ? null : sourcesContent);
  16758. for (const module of modules) {
  16759. resetSourcemapCache(module.originalSourcemap, module.sourcemapChain);
  16760. }
  16761. return new SourceMap({ file, mappings, names, sources, sourcesContent });
  16762. }
  16763. function collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, log) {
  16764. if (sourcemapChain.length === 0) {
  16765. return originalSourcemap;
  16766. }
  16767. const source = getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, getLinkMap(log));
  16768. const map = source.traceMappings();
  16769. return decodedSourcemap({ version: 3, ...map });
  16770. }
  16771. const createHash = () => createHash$1('sha256');
  16772. async function renderChunks(chunks, bundle, pluginDriver, outputOptions, log) {
  16773. timeStart('render chunks', 2);
  16774. reserveEntryChunksInBundle(chunks);
  16775. const renderedChunks = await Promise.all(chunks.map(chunk => chunk.render()));
  16776. timeEnd('render chunks', 2);
  16777. timeStart('transform chunks', 2);
  16778. const chunkGraph = getChunkGraph(chunks);
  16779. const { initialHashesByPlaceholder, nonHashedChunksWithPlaceholders, renderedChunksByPlaceholder, hashDependenciesByPlaceholder } = await transformChunksAndGenerateContentHashes(renderedChunks, chunkGraph, outputOptions, pluginDriver, log);
  16780. const hashesByPlaceholder = generateFinalHashes(renderedChunksByPlaceholder, hashDependenciesByPlaceholder, initialHashesByPlaceholder, bundle);
  16781. addChunksToBundle(renderedChunksByPlaceholder, hashesByPlaceholder, bundle, nonHashedChunksWithPlaceholders, pluginDriver, outputOptions);
  16782. timeEnd('transform chunks', 2);
  16783. }
  16784. function reserveEntryChunksInBundle(chunks) {
  16785. for (const chunk of chunks) {
  16786. if (chunk.facadeModule && chunk.facadeModule.isUserDefinedEntryPoint) {
  16787. // reserves name in bundle as side effect if it does not contain a hash
  16788. chunk.getPreliminaryFileName();
  16789. }
  16790. }
  16791. }
  16792. function getChunkGraph(chunks) {
  16793. return Object.fromEntries(chunks.map(chunk => {
  16794. const renderedChunkInfo = chunk.getRenderedChunkInfo();
  16795. return [renderedChunkInfo.fileName, renderedChunkInfo];
  16796. }));
  16797. }
  16798. async function transformChunk(magicString, fileName, usedModules, chunkGraph, options, outputPluginDriver, log) {
  16799. let map = null;
  16800. const sourcemapChain = [];
  16801. let code = await outputPluginDriver.hookReduceArg0('renderChunk', [magicString.toString(), chunkGraph[fileName], options, { chunks: chunkGraph }], (code, result, plugin) => {
  16802. if (result == null)
  16803. return code;
  16804. if (typeof result === 'string')
  16805. result = {
  16806. code: result,
  16807. map: undefined
  16808. };
  16809. // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning
  16810. if (result.map !== null) {
  16811. const map = decodedSourcemap(result.map);
  16812. sourcemapChain.push(map || { missing: true, plugin: plugin.name });
  16813. }
  16814. return result.code;
  16815. });
  16816. const { compact, dir, file, sourcemap, sourcemapExcludeSources, sourcemapFile, sourcemapPathTransform, sourcemapIgnoreList } = options;
  16817. if (!compact && code[code.length - 1] !== '\n')
  16818. code += '\n';
  16819. if (sourcemap) {
  16820. timeStart('sourcemaps', 3);
  16821. let resultingFile;
  16822. if (file)
  16823. resultingFile = resolve(sourcemapFile || file);
  16824. else if (dir)
  16825. resultingFile = resolve(dir, fileName);
  16826. else
  16827. resultingFile = resolve(fileName);
  16828. const decodedMap = magicString.generateDecodedMap({});
  16829. map = collapseSourcemaps(resultingFile, decodedMap, usedModules, sourcemapChain, sourcemapExcludeSources, log);
  16830. for (let sourcesIndex = 0; sourcesIndex < map.sources.length; ++sourcesIndex) {
  16831. let sourcePath = map.sources[sourcesIndex];
  16832. const sourcemapPath = `${resultingFile}.map`;
  16833. const ignoreList = sourcemapIgnoreList(sourcePath, sourcemapPath);
  16834. if (typeof ignoreList !== 'boolean') {
  16835. error(logFailedValidation('sourcemapIgnoreList function must return a boolean.'));
  16836. }
  16837. if (ignoreList) {
  16838. if (map.x_google_ignoreList === undefined) {
  16839. map.x_google_ignoreList = [];
  16840. }
  16841. if (!map.x_google_ignoreList.includes(sourcesIndex)) {
  16842. map.x_google_ignoreList.push(sourcesIndex);
  16843. }
  16844. }
  16845. if (sourcemapPathTransform) {
  16846. sourcePath = sourcemapPathTransform(sourcePath, sourcemapPath);
  16847. if (typeof sourcePath !== 'string') {
  16848. error(logFailedValidation(`sourcemapPathTransform function must return a string.`));
  16849. }
  16850. }
  16851. map.sources[sourcesIndex] = normalize(sourcePath);
  16852. }
  16853. timeEnd('sourcemaps', 3);
  16854. }
  16855. return {
  16856. code,
  16857. map
  16858. };
  16859. }
  16860. async function transformChunksAndGenerateContentHashes(renderedChunks, chunkGraph, outputOptions, pluginDriver, log) {
  16861. const nonHashedChunksWithPlaceholders = [];
  16862. const renderedChunksByPlaceholder = new Map();
  16863. const hashDependenciesByPlaceholder = new Map();
  16864. const initialHashesByPlaceholder = new Map();
  16865. const placeholders = new Set();
  16866. for (const { preliminaryFileName: { hashPlaceholder } } of renderedChunks) {
  16867. if (hashPlaceholder)
  16868. placeholders.add(hashPlaceholder);
  16869. }
  16870. await Promise.all(renderedChunks.map(async ({ chunk, preliminaryFileName: { fileName, hashPlaceholder }, preliminarySourcemapFileName, magicString, usedModules }) => {
  16871. const transformedChunk = {
  16872. chunk,
  16873. fileName,
  16874. sourcemapFileName: preliminarySourcemapFileName?.fileName ?? null,
  16875. ...(await transformChunk(magicString, fileName, usedModules, chunkGraph, outputOptions, pluginDriver, log))
  16876. };
  16877. const { code, map } = transformedChunk;
  16878. if (hashPlaceholder) {
  16879. // To create a reproducible content-only hash, all placeholders are
  16880. // replaced with the same value before hashing
  16881. const { containedPlaceholders, transformedCode } = replacePlaceholdersWithDefaultAndGetContainedPlaceholders(code, placeholders);
  16882. const hash = createHash().update(transformedCode);
  16883. const hashAugmentation = pluginDriver.hookReduceValueSync('augmentChunkHash', '', [chunk.getRenderedChunkInfo()], (augmentation, pluginHash) => {
  16884. if (pluginHash) {
  16885. augmentation += pluginHash;
  16886. }
  16887. return augmentation;
  16888. });
  16889. if (hashAugmentation) {
  16890. hash.update(hashAugmentation);
  16891. }
  16892. renderedChunksByPlaceholder.set(hashPlaceholder, transformedChunk);
  16893. hashDependenciesByPlaceholder.set(hashPlaceholder, {
  16894. containedPlaceholders,
  16895. contentHash: hash.digest('hex')
  16896. });
  16897. }
  16898. else {
  16899. nonHashedChunksWithPlaceholders.push(transformedChunk);
  16900. }
  16901. const sourcemapHashPlaceholder = preliminarySourcemapFileName?.hashPlaceholder;
  16902. if (map && sourcemapHashPlaceholder) {
  16903. initialHashesByPlaceholder.set(preliminarySourcemapFileName.hashPlaceholder, createHash()
  16904. .update(map.toString())
  16905. .digest('hex')
  16906. .slice(0, preliminarySourcemapFileName.hashPlaceholder.length));
  16907. }
  16908. }));
  16909. return {
  16910. hashDependenciesByPlaceholder,
  16911. initialHashesByPlaceholder,
  16912. nonHashedChunksWithPlaceholders,
  16913. renderedChunksByPlaceholder
  16914. };
  16915. }
  16916. function generateFinalHashes(renderedChunksByPlaceholder, hashDependenciesByPlaceholder, initialHashesByPlaceholder, bundle) {
  16917. const hashesByPlaceholder = new Map(initialHashesByPlaceholder);
  16918. for (const [placeholder, { fileName }] of renderedChunksByPlaceholder) {
  16919. let hash = createHash();
  16920. const hashDependencyPlaceholders = new Set([placeholder]);
  16921. for (const dependencyPlaceholder of hashDependencyPlaceholders) {
  16922. const { containedPlaceholders, contentHash } = hashDependenciesByPlaceholder.get(dependencyPlaceholder);
  16923. hash.update(contentHash);
  16924. for (const containedPlaceholder of containedPlaceholders) {
  16925. // When looping over a map, setting an entry only causes a new iteration if the key is new
  16926. hashDependencyPlaceholders.add(containedPlaceholder);
  16927. }
  16928. }
  16929. let finalFileName;
  16930. let finalHash;
  16931. do {
  16932. // In case of a hash collision, create a hash of the hash
  16933. if (finalHash) {
  16934. hash = createHash().update(finalHash);
  16935. }
  16936. finalHash = hash.digest('hex').slice(0, placeholder.length);
  16937. finalFileName = replaceSinglePlaceholder(fileName, placeholder, finalHash);
  16938. } while (bundle[lowercaseBundleKeys].has(finalFileName.toLowerCase()));
  16939. bundle[finalFileName] = FILE_PLACEHOLDER;
  16940. hashesByPlaceholder.set(placeholder, finalHash);
  16941. }
  16942. return hashesByPlaceholder;
  16943. }
  16944. function addChunksToBundle(renderedChunksByPlaceholder, hashesByPlaceholder, bundle, nonHashedChunksWithPlaceholders, pluginDriver, options) {
  16945. for (const { chunk, code, fileName, sourcemapFileName, map } of renderedChunksByPlaceholder.values()) {
  16946. let updatedCode = replacePlaceholders(code, hashesByPlaceholder);
  16947. const finalFileName = replacePlaceholders(fileName, hashesByPlaceholder);
  16948. let finalSourcemapFileName = null;
  16949. if (map) {
  16950. finalSourcemapFileName = sourcemapFileName
  16951. ? replacePlaceholders(sourcemapFileName, hashesByPlaceholder)
  16952. : `${finalFileName}.map`;
  16953. map.file = replacePlaceholders(map.file, hashesByPlaceholder);
  16954. updatedCode += emitSourceMapAndGetComment(finalSourcemapFileName, map, pluginDriver, options);
  16955. }
  16956. bundle[finalFileName] = chunk.finalizeChunk(updatedCode, map, finalSourcemapFileName, hashesByPlaceholder);
  16957. }
  16958. for (const { chunk, code, fileName, sourcemapFileName, map } of nonHashedChunksWithPlaceholders) {
  16959. let updatedCode = hashesByPlaceholder.size > 0 ? replacePlaceholders(code, hashesByPlaceholder) : code;
  16960. let finalSourcemapFileName = null;
  16961. if (map) {
  16962. finalSourcemapFileName = sourcemapFileName
  16963. ? replacePlaceholders(sourcemapFileName, hashesByPlaceholder)
  16964. : `${fileName}.map`;
  16965. updatedCode += emitSourceMapAndGetComment(finalSourcemapFileName, map, pluginDriver, options);
  16966. }
  16967. bundle[fileName] = chunk.finalizeChunk(updatedCode, map, finalSourcemapFileName, hashesByPlaceholder);
  16968. }
  16969. }
  16970. function emitSourceMapAndGetComment(fileName, map, pluginDriver, { sourcemap, sourcemapBaseUrl }) {
  16971. let url;
  16972. if (sourcemap === 'inline') {
  16973. url = map.toUrl();
  16974. }
  16975. else {
  16976. const sourcemapFileName = basename(fileName);
  16977. url = sourcemapBaseUrl
  16978. ? new URL(sourcemapFileName, sourcemapBaseUrl).toString()
  16979. : sourcemapFileName;
  16980. pluginDriver.emitFile({ fileName, source: map.toString(), type: 'asset' });
  16981. }
  16982. return sourcemap === 'hidden' ? '' : `//# ${SOURCEMAPPING_URL}=${url}\n`;
  16983. }
  16984. class Bundle {
  16985. constructor(outputOptions, unsetOptions, inputOptions, pluginDriver, graph) {
  16986. this.outputOptions = outputOptions;
  16987. this.unsetOptions = unsetOptions;
  16988. this.inputOptions = inputOptions;
  16989. this.pluginDriver = pluginDriver;
  16990. this.graph = graph;
  16991. this.facadeChunkByModule = new Map();
  16992. this.includedNamespaces = new Set();
  16993. }
  16994. async generate(isWrite) {
  16995. timeStart('GENERATE', 1);
  16996. const outputBundleBase = Object.create(null);
  16997. const outputBundle = getOutputBundle(outputBundleBase);
  16998. this.pluginDriver.setOutputBundle(outputBundle, this.outputOptions);
  16999. try {
  17000. timeStart('initialize render', 2);
  17001. await this.pluginDriver.hookParallel('renderStart', [this.outputOptions, this.inputOptions]);
  17002. timeEnd('initialize render', 2);
  17003. timeStart('generate chunks', 2);
  17004. const getHashPlaceholder = getHashPlaceholderGenerator();
  17005. const chunks = await this.generateChunks(outputBundle, getHashPlaceholder);
  17006. if (chunks.length > 1) {
  17007. validateOptionsForMultiChunkOutput(this.outputOptions, this.inputOptions.onLog);
  17008. }
  17009. this.pluginDriver.setChunkInformation(this.facadeChunkByModule);
  17010. for (const chunk of chunks) {
  17011. chunk.generateExports();
  17012. }
  17013. timeEnd('generate chunks', 2);
  17014. await renderChunks(chunks, outputBundle, this.pluginDriver, this.outputOptions, this.inputOptions.onLog);
  17015. }
  17016. catch (error_) {
  17017. await this.pluginDriver.hookParallel('renderError', [error_]);
  17018. throw error_;
  17019. }
  17020. removeUnreferencedAssets(outputBundle);
  17021. timeStart('generate bundle', 2);
  17022. await this.pluginDriver.hookSeq('generateBundle', [
  17023. this.outputOptions,
  17024. outputBundle,
  17025. isWrite
  17026. ]);
  17027. this.finaliseAssets(outputBundle);
  17028. timeEnd('generate bundle', 2);
  17029. timeEnd('GENERATE', 1);
  17030. return outputBundleBase;
  17031. }
  17032. async addManualChunks(manualChunks) {
  17033. const manualChunkAliasByEntry = new Map();
  17034. const chunkEntries = await Promise.all(Object.entries(manualChunks).map(async ([alias, files]) => ({
  17035. alias,
  17036. entries: await this.graph.moduleLoader.addAdditionalModules(files, true)
  17037. })));
  17038. for (const { alias, entries } of chunkEntries) {
  17039. for (const entry of entries) {
  17040. addModuleToManualChunk(alias, entry, manualChunkAliasByEntry);
  17041. }
  17042. }
  17043. return manualChunkAliasByEntry;
  17044. }
  17045. assignManualChunks(getManualChunk) {
  17046. // eslint-disable-next-line unicorn/prefer-module
  17047. const manualChunkAliasesWithEntry = [];
  17048. const manualChunksApi = {
  17049. getModuleIds: () => this.graph.modulesById.keys(),
  17050. getModuleInfo: this.graph.getModuleInfo
  17051. };
  17052. for (const module of this.graph.modulesById.values()) {
  17053. if (module instanceof Module) {
  17054. const manualChunkAlias = getManualChunk(module.id, manualChunksApi);
  17055. if (typeof manualChunkAlias === 'string') {
  17056. manualChunkAliasesWithEntry.push([manualChunkAlias, module]);
  17057. }
  17058. }
  17059. }
  17060. manualChunkAliasesWithEntry.sort(([aliasA], [aliasB]) => aliasA > aliasB ? 1 : aliasA < aliasB ? -1 : 0);
  17061. const manualChunkAliasByEntry = new Map();
  17062. for (const [alias, module] of manualChunkAliasesWithEntry) {
  17063. addModuleToManualChunk(alias, module, manualChunkAliasByEntry);
  17064. }
  17065. return manualChunkAliasByEntry;
  17066. }
  17067. finaliseAssets(bundle) {
  17068. if (this.outputOptions.validate) {
  17069. for (const file of Object.values(bundle)) {
  17070. if ('code' in file) {
  17071. try {
  17072. this.graph.contextParse(file.code, {
  17073. ecmaVersion: 'latest'
  17074. });
  17075. }
  17076. catch (error_) {
  17077. this.inputOptions.onLog(LOGLEVEL_WARN, logChunkInvalid(file, error_));
  17078. }
  17079. }
  17080. }
  17081. }
  17082. this.pluginDriver.finaliseAssets();
  17083. }
  17084. async generateChunks(bundle, getHashPlaceholder) {
  17085. const { experimentalMinChunkSize, inlineDynamicImports, manualChunks, preserveModules } = this.outputOptions;
  17086. const manualChunkAliasByEntry = typeof manualChunks === 'object'
  17087. ? await this.addManualChunks(manualChunks)
  17088. : this.assignManualChunks(manualChunks);
  17089. const snippets = getGenerateCodeSnippets(this.outputOptions);
  17090. const includedModules = getIncludedModules(this.graph.modulesById);
  17091. const inputBase = commondir(getAbsoluteEntryModulePaths(includedModules, preserveModules));
  17092. const externalChunkByModule = getExternalChunkByModule(this.graph.modulesById, this.outputOptions, inputBase);
  17093. const chunks = [];
  17094. const chunkByModule = new Map();
  17095. for (const { alias, modules } of inlineDynamicImports
  17096. ? [{ alias: null, modules: includedModules }]
  17097. : preserveModules
  17098. ? includedModules.map(module => ({ alias: null, modules: [module] }))
  17099. : getChunkAssignments(this.graph.entryModules, manualChunkAliasByEntry, experimentalMinChunkSize, this.inputOptions.onLog)) {
  17100. sortByExecutionOrder(modules);
  17101. const chunk = new Chunk(modules, this.inputOptions, this.outputOptions, this.unsetOptions, this.pluginDriver, this.graph.modulesById, chunkByModule, externalChunkByModule, this.facadeChunkByModule, this.includedNamespaces, alias, getHashPlaceholder, bundle, inputBase, snippets);
  17102. chunks.push(chunk);
  17103. }
  17104. for (const chunk of chunks) {
  17105. chunk.link();
  17106. }
  17107. const facades = [];
  17108. for (const chunk of chunks) {
  17109. facades.push(...chunk.generateFacades());
  17110. }
  17111. return [...chunks, ...facades];
  17112. }
  17113. }
  17114. function validateOptionsForMultiChunkOutput(outputOptions, log) {
  17115. if (outputOptions.format === 'umd' || outputOptions.format === 'iife')
  17116. return error(logInvalidOption('output.format', URL_OUTPUT_FORMAT, 'UMD and IIFE output formats are not supported for code-splitting builds', outputOptions.format));
  17117. if (typeof outputOptions.file === 'string')
  17118. return error(logInvalidOption('output.file', URL_OUTPUT_DIR, 'when building multiple chunks, the "output.dir" option must be used, not "output.file". To inline dynamic imports, set the "inlineDynamicImports" option'));
  17119. if (outputOptions.sourcemapFile)
  17120. return error(logInvalidOption('output.sourcemapFile', URL_OUTPUT_SOURCEMAPFILE, '"output.sourcemapFile" is only supported for single-file builds'));
  17121. if (!outputOptions.amd.autoId && outputOptions.amd.id)
  17122. log(LOGLEVEL_WARN, logInvalidOption('output.amd.id', URL_OUTPUT_AMD_ID, 'this option is only properly supported for single-file builds. Use "output.amd.autoId" and "output.amd.basePath" instead'));
  17123. }
  17124. function getIncludedModules(modulesById) {
  17125. const includedModules = [];
  17126. for (const module of modulesById.values()) {
  17127. if (module instanceof Module &&
  17128. (module.isIncluded() || module.info.isEntry || module.includedDynamicImporters.length > 0)) {
  17129. includedModules.push(module);
  17130. }
  17131. }
  17132. return includedModules;
  17133. }
  17134. function getAbsoluteEntryModulePaths(includedModules, preserveModules) {
  17135. const absoluteEntryModulePaths = [];
  17136. for (const module of includedModules) {
  17137. if ((module.info.isEntry || preserveModules) && isAbsolute(module.id)) {
  17138. absoluteEntryModulePaths.push(module.id);
  17139. }
  17140. }
  17141. return absoluteEntryModulePaths;
  17142. }
  17143. function getExternalChunkByModule(modulesById, outputOptions, inputBase) {
  17144. const externalChunkByModule = new Map();
  17145. for (const module of modulesById.values()) {
  17146. if (module instanceof ExternalModule) {
  17147. externalChunkByModule.set(module, new ExternalChunk(module, outputOptions, inputBase));
  17148. }
  17149. }
  17150. return externalChunkByModule;
  17151. }
  17152. function addModuleToManualChunk(alias, module, manualChunkAliasByEntry) {
  17153. const existingAlias = manualChunkAliasByEntry.get(module);
  17154. if (typeof existingAlias === 'string' && existingAlias !== alias) {
  17155. return error(logCannotAssignModuleToChunk(module.id, alias, existingAlias));
  17156. }
  17157. manualChunkAliasByEntry.set(module, alias);
  17158. }
  17159. // This file was generated. Do not modify manually!
  17160. 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, 81, 2, 71, 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, 3, 0, 158, 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, 10, 1, 2, 0, 49, 6, 4, 4, 14, 9, 5351, 0, 7, 14, 13835, 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, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 983, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];
  17161. // This file was generated. Do not modify manually!
  17162. 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, 20, 1, 64, 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, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 4026, 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, 16, 0, 30, 2, 3, 0, 15, 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, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 757, 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, 4153, 7, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938, 6, 4191];
  17163. // This file was generated. Do not modify manually!
  17164. 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\u0cf3\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-\u0ece\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";
  17165. // This file was generated. Do not modify manually!
  17166. 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";
  17167. // These are a run-length and offset encoded representation of the
  17168. // >0xffff code points that are a valid part of identifiers. The
  17169. // offset starts at 0x10000, and each pair of numbers represents an
  17170. // offset to the next range, and then a size of the range.
  17171. // Reserved word lists for various dialects of the language
  17172. var reservedWords = {
  17173. 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",
  17174. 5: "class enum extends super const export import",
  17175. 6: "enum",
  17176. strict: "implements interface let package private protected public static yield",
  17177. strictBind: "eval arguments"
  17178. };
  17179. // And the keywords
  17180. 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";
  17181. var keywords$1 = {
  17182. 5: ecma5AndLessKeywords,
  17183. "5module": ecma5AndLessKeywords + " export import",
  17184. 6: ecma5AndLessKeywords + " const class extends export import super"
  17185. };
  17186. var keywordRelationalOperator = /^in(stanceof)?$/;
  17187. // ## Character categories
  17188. var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  17189. var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  17190. // This has a complexity linear to the value of the code. The
  17191. // assumption is that looking up astral identifier characters is
  17192. // rare.
  17193. function isInAstralSet(code, set) {
  17194. var pos = 0x10000;
  17195. for (var i = 0; i < set.length; i += 2) {
  17196. pos += set[i];
  17197. if (pos > code) { return false }
  17198. pos += set[i + 1];
  17199. if (pos >= code) { return true }
  17200. }
  17201. return false
  17202. }
  17203. // Test whether a given character code starts an identifier.
  17204. function isIdentifierStart(code, astral) {
  17205. if (code < 65) { return code === 36 }
  17206. if (code < 91) { return true }
  17207. if (code < 97) { return code === 95 }
  17208. if (code < 123) { return true }
  17209. if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) }
  17210. if (astral === false) { return false }
  17211. return isInAstralSet(code, astralIdentifierStartCodes)
  17212. }
  17213. // Test whether a given character is part of an identifier.
  17214. function isIdentifierChar(code, astral) {
  17215. if (code < 48) { return code === 36 }
  17216. if (code < 58) { return true }
  17217. if (code < 65) { return false }
  17218. if (code < 91) { return true }
  17219. if (code < 97) { return code === 95 }
  17220. if (code < 123) { return true }
  17221. if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) }
  17222. if (astral === false) { return false }
  17223. return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes)
  17224. }
  17225. // ## Token types
  17226. // The assignment of fine-grained, information-carrying type objects
  17227. // allows the tokenizer to store the information it has about a
  17228. // token in a way that is very cheap for the parser to look up.
  17229. // All token type variables start with an underscore, to make them
  17230. // easy to recognize.
  17231. // The `beforeExpr` property is used to disambiguate between regular
  17232. // expressions and divisions. It is set on all token types that can
  17233. // be followed by an expression (thus, a slash after them would be a
  17234. // regular expression).
  17235. //
  17236. // The `startsExpr` property is used to check if the token ends a
  17237. // `yield` expression. It is set on all token types that either can
  17238. // directly start an expression (like a quotation mark) or can
  17239. // continue an expression (like the body of a string).
  17240. //
  17241. // `isLoop` marks a keyword as starting a loop, which is important
  17242. // to know when parsing a label, in order to allow or disallow
  17243. // continue jumps to that label.
  17244. var TokenType = function TokenType(label, conf) {
  17245. if ( conf === void 0 ) conf = {};
  17246. this.label = label;
  17247. this.keyword = conf.keyword;
  17248. this.beforeExpr = !!conf.beforeExpr;
  17249. this.startsExpr = !!conf.startsExpr;
  17250. this.isLoop = !!conf.isLoop;
  17251. this.isAssign = !!conf.isAssign;
  17252. this.prefix = !!conf.prefix;
  17253. this.postfix = !!conf.postfix;
  17254. this.binop = conf.binop || null;
  17255. this.updateContext = null;
  17256. };
  17257. function binop(name, prec) {
  17258. return new TokenType(name, {beforeExpr: true, binop: prec})
  17259. }
  17260. var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true};
  17261. // Map keyword names to token types.
  17262. var keywords = {};
  17263. // Succinct definitions of keyword token types
  17264. function kw(name, options) {
  17265. if ( options === void 0 ) options = {};
  17266. options.keyword = name;
  17267. return keywords[name] = new TokenType(name, options)
  17268. }
  17269. var types$1 = {
  17270. num: new TokenType("num", startsExpr),
  17271. regexp: new TokenType("regexp", startsExpr),
  17272. string: new TokenType("string", startsExpr),
  17273. name: new TokenType("name", startsExpr),
  17274. privateId: new TokenType("privateId", startsExpr),
  17275. eof: new TokenType("eof"),
  17276. // Punctuation token types.
  17277. bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}),
  17278. bracketR: new TokenType("]"),
  17279. braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}),
  17280. braceR: new TokenType("}"),
  17281. parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}),
  17282. parenR: new TokenType(")"),
  17283. comma: new TokenType(",", beforeExpr),
  17284. semi: new TokenType(";", beforeExpr),
  17285. colon: new TokenType(":", beforeExpr),
  17286. dot: new TokenType("."),
  17287. question: new TokenType("?", beforeExpr),
  17288. questionDot: new TokenType("?."),
  17289. arrow: new TokenType("=>", beforeExpr),
  17290. template: new TokenType("template"),
  17291. invalidTemplate: new TokenType("invalidTemplate"),
  17292. ellipsis: new TokenType("...", beforeExpr),
  17293. backQuote: new TokenType("`", startsExpr),
  17294. dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}),
  17295. // Operators. These carry several kinds of properties to help the
  17296. // parser use them properly (the presence of these properties is
  17297. // what categorizes them as operators).
  17298. //
  17299. // `binop`, when present, specifies that this operator is a binary
  17300. // operator, and will refer to its precedence.
  17301. //
  17302. // `prefix` and `postfix` mark the operator as a prefix or postfix
  17303. // unary operator.
  17304. //
  17305. // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
  17306. // binary operators with a very low precedence, that should result
  17307. // in AssignmentExpression nodes.
  17308. eq: new TokenType("=", {beforeExpr: true, isAssign: true}),
  17309. assign: new TokenType("_=", {beforeExpr: true, isAssign: true}),
  17310. incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}),
  17311. prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}),
  17312. logicalOR: binop("||", 1),
  17313. logicalAND: binop("&&", 2),
  17314. bitwiseOR: binop("|", 3),
  17315. bitwiseXOR: binop("^", 4),
  17316. bitwiseAND: binop("&", 5),
  17317. equality: binop("==/!=/===/!==", 6),
  17318. relational: binop("</>/<=/>=", 7),
  17319. bitShift: binop("<</>>/>>>", 8),
  17320. plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}),
  17321. modulo: binop("%", 10),
  17322. star: binop("*", 10),
  17323. slash: binop("/", 10),
  17324. starstar: new TokenType("**", {beforeExpr: true}),
  17325. coalesce: binop("??", 1),
  17326. // Keyword token types.
  17327. _break: kw("break"),
  17328. _case: kw("case", beforeExpr),
  17329. _catch: kw("catch"),
  17330. _continue: kw("continue"),
  17331. _debugger: kw("debugger"),
  17332. _default: kw("default", beforeExpr),
  17333. _do: kw("do", {isLoop: true, beforeExpr: true}),
  17334. _else: kw("else", beforeExpr),
  17335. _finally: kw("finally"),
  17336. _for: kw("for", {isLoop: true}),
  17337. _function: kw("function", startsExpr),
  17338. _if: kw("if"),
  17339. _return: kw("return", beforeExpr),
  17340. _switch: kw("switch"),
  17341. _throw: kw("throw", beforeExpr),
  17342. _try: kw("try"),
  17343. _var: kw("var"),
  17344. _const: kw("const"),
  17345. _while: kw("while", {isLoop: true}),
  17346. _with: kw("with"),
  17347. _new: kw("new", {beforeExpr: true, startsExpr: true}),
  17348. _this: kw("this", startsExpr),
  17349. _super: kw("super", startsExpr),
  17350. _class: kw("class", startsExpr),
  17351. _extends: kw("extends", beforeExpr),
  17352. _export: kw("export"),
  17353. _import: kw("import", startsExpr),
  17354. _null: kw("null", startsExpr),
  17355. _true: kw("true", startsExpr),
  17356. _false: kw("false", startsExpr),
  17357. _in: kw("in", {beforeExpr: true, binop: 7}),
  17358. _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}),
  17359. _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}),
  17360. _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}),
  17361. _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true})
  17362. };
  17363. // Matches a whole line break (where CRLF is considered a single
  17364. // line break). Used to count lines.
  17365. var lineBreak = /\r\n?|\n|\u2028|\u2029/;
  17366. var lineBreakG = new RegExp(lineBreak.source, "g");
  17367. function isNewLine(code) {
  17368. return code === 10 || code === 13 || code === 0x2028 || code === 0x2029
  17369. }
  17370. function nextLineBreak(code, from, end) {
  17371. if ( end === void 0 ) end = code.length;
  17372. for (var i = from; i < end; i++) {
  17373. var next = code.charCodeAt(i);
  17374. if (isNewLine(next))
  17375. { return i < end - 1 && next === 13 && code.charCodeAt(i + 1) === 10 ? i + 2 : i + 1 }
  17376. }
  17377. return -1
  17378. }
  17379. var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
  17380. var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
  17381. var ref = Object.prototype;
  17382. var hasOwnProperty = ref.hasOwnProperty;
  17383. var toString = ref.toString;
  17384. var hasOwn = Object.hasOwn || (function (obj, propName) { return (
  17385. hasOwnProperty.call(obj, propName)
  17386. ); });
  17387. var isArray = Array.isArray || (function (obj) { return (
  17388. toString.call(obj) === "[object Array]"
  17389. ); });
  17390. function wordsRegexp(words) {
  17391. return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$")
  17392. }
  17393. function codePointToString(code) {
  17394. // UTF-16 Decoding
  17395. if (code <= 0xFFFF) { return String.fromCharCode(code) }
  17396. code -= 0x10000;
  17397. return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00)
  17398. }
  17399. var loneSurrogate = /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/;
  17400. // These are used when `options.locations` is on, for the
  17401. // `startLoc` and `endLoc` properties.
  17402. var Position = function Position(line, col) {
  17403. this.line = line;
  17404. this.column = col;
  17405. };
  17406. Position.prototype.offset = function offset (n) {
  17407. return new Position(this.line, this.column + n)
  17408. };
  17409. var SourceLocation = function SourceLocation(p, start, end) {
  17410. this.start = start;
  17411. this.end = end;
  17412. if (p.sourceFile !== null) { this.source = p.sourceFile; }
  17413. };
  17414. // The `getLineInfo` function is mostly useful when the
  17415. // `locations` option is off (for performance reasons) and you
  17416. // want to find the line/column position for a given character
  17417. // offset. `input` should be the code string that the offset refers
  17418. // into.
  17419. function getLineInfo(input, offset) {
  17420. for (var line = 1, cur = 0;;) {
  17421. var nextBreak = nextLineBreak(input, cur, offset);
  17422. if (nextBreak < 0) { return new Position(line, offset - cur) }
  17423. ++line;
  17424. cur = nextBreak;
  17425. }
  17426. }
  17427. // A second argument must be given to configure the parser process.
  17428. // These options are recognized (only `ecmaVersion` is required):
  17429. var defaultOptions = {
  17430. // `ecmaVersion` indicates the ECMAScript version to parse. Must be
  17431. // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10
  17432. // (2019), 11 (2020), 12 (2021), 13 (2022), 14 (2023), or `"latest"`
  17433. // (the latest version the library supports). This influences
  17434. // support for strict mode, the set of reserved words, and support
  17435. // for new syntax features.
  17436. ecmaVersion: null,
  17437. // `sourceType` indicates the mode the code should be parsed in.
  17438. // Can be either `"script"` or `"module"`. This influences global
  17439. // strict mode and parsing of `import` and `export` declarations.
  17440. sourceType: "script",
  17441. // `onInsertedSemicolon` can be a callback that will be called
  17442. // when a semicolon is automatically inserted. It will be passed
  17443. // the position of the comma as an offset, and if `locations` is
  17444. // enabled, it is given the location as a `{line, column}` object
  17445. // as second argument.
  17446. onInsertedSemicolon: null,
  17447. // `onTrailingComma` is similar to `onInsertedSemicolon`, but for
  17448. // trailing commas.
  17449. onTrailingComma: null,
  17450. // By default, reserved words are only enforced if ecmaVersion >= 5.
  17451. // Set `allowReserved` to a boolean value to explicitly turn this on
  17452. // an off. When this option has the value "never", reserved words
  17453. // and keywords can also not be used as property names.
  17454. allowReserved: null,
  17455. // When enabled, a return at the top level is not considered an
  17456. // error.
  17457. allowReturnOutsideFunction: false,
  17458. // When enabled, import/export statements are not constrained to
  17459. // appearing at the top of the program, and an import.meta expression
  17460. // in a script isn't considered an error.
  17461. allowImportExportEverywhere: false,
  17462. // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022.
  17463. // When enabled, await identifiers are allowed to appear at the top-level scope,
  17464. // but they are still not allowed in non-async functions.
  17465. allowAwaitOutsideFunction: null,
  17466. // When enabled, super identifiers are not constrained to
  17467. // appearing in methods and do not raise an error when they appear elsewhere.
  17468. allowSuperOutsideMethod: null,
  17469. // When enabled, hashbang directive in the beginning of file is
  17470. // allowed and treated as a line comment. Enabled by default when
  17471. // `ecmaVersion` >= 2023.
  17472. allowHashBang: false,
  17473. // By default, the parser will verify that private properties are
  17474. // only used in places where they are valid and have been declared.
  17475. // Set this to false to turn such checks off.
  17476. checkPrivateFields: true,
  17477. // When `locations` is on, `loc` properties holding objects with
  17478. // `start` and `end` properties in `{line, column}` form (with
  17479. // line being 1-based and column 0-based) will be attached to the
  17480. // nodes.
  17481. locations: false,
  17482. // A function can be passed as `onToken` option, which will
  17483. // cause Acorn to call that function with object in the same
  17484. // format as tokens returned from `tokenizer().getToken()`. Note
  17485. // that you are not allowed to call the parser from the
  17486. // callback—that will corrupt its internal state.
  17487. onToken: null,
  17488. // A function can be passed as `onComment` option, which will
  17489. // cause Acorn to call that function with `(block, text, start,
  17490. // end)` parameters whenever a comment is skipped. `block` is a
  17491. // boolean indicating whether this is a block (`/* */`) comment,
  17492. // `text` is the content of the comment, and `start` and `end` are
  17493. // character offsets that denote the start and end of the comment.
  17494. // When the `locations` option is on, two more parameters are
  17495. // passed, the full `{line, column}` locations of the start and
  17496. // end of the comments. Note that you are not allowed to call the
  17497. // parser from the callback—that will corrupt its internal state.
  17498. onComment: null,
  17499. // Nodes have their start and end characters offsets recorded in
  17500. // `start` and `end` properties (directly on the node, rather than
  17501. // the `loc` object, which holds line/column data. To also add a
  17502. // [semi-standardized][range] `range` property holding a `[start,
  17503. // end]` array with the same numbers, set the `ranges` option to
  17504. // `true`.
  17505. //
  17506. // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
  17507. ranges: false,
  17508. // It is possible to parse multiple files into a single AST by
  17509. // passing the tree produced by parsing the first file as
  17510. // `program` option in subsequent parses. This will add the
  17511. // toplevel forms of the parsed file to the `Program` (top) node
  17512. // of an existing parse tree.
  17513. program: null,
  17514. // When `locations` is on, you can pass this to record the source
  17515. // file in every node's `loc` object.
  17516. sourceFile: null,
  17517. // This value, if given, is stored in every node, whether
  17518. // `locations` is on or off.
  17519. directSourceFile: null,
  17520. // When enabled, parenthesized expressions are represented by
  17521. // (non-standard) ParenthesizedExpression nodes
  17522. preserveParens: false
  17523. };
  17524. // Interpret and default an options object
  17525. var warnedAboutEcmaVersion = false;
  17526. function getOptions(opts) {
  17527. var options = {};
  17528. for (var opt in defaultOptions)
  17529. { options[opt] = opts && hasOwn(opts, opt) ? opts[opt] : defaultOptions[opt]; }
  17530. if (options.ecmaVersion === "latest") {
  17531. options.ecmaVersion = 1e8;
  17532. } else if (options.ecmaVersion == null) {
  17533. if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) {
  17534. warnedAboutEcmaVersion = true;
  17535. console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.");
  17536. }
  17537. options.ecmaVersion = 11;
  17538. } else if (options.ecmaVersion >= 2015) {
  17539. options.ecmaVersion -= 2009;
  17540. }
  17541. if (options.allowReserved == null)
  17542. { options.allowReserved = options.ecmaVersion < 5; }
  17543. if (!opts || opts.allowHashBang == null)
  17544. { options.allowHashBang = options.ecmaVersion >= 14; }
  17545. if (isArray(options.onToken)) {
  17546. var tokens = options.onToken;
  17547. options.onToken = function (token) { return tokens.push(token); };
  17548. }
  17549. if (isArray(options.onComment))
  17550. { options.onComment = pushComment(options, options.onComment); }
  17551. return options
  17552. }
  17553. function pushComment(options, array) {
  17554. return function(block, text, start, end, startLoc, endLoc) {
  17555. var comment = {
  17556. type: block ? "Block" : "Line",
  17557. value: text,
  17558. start: start,
  17559. end: end
  17560. };
  17561. if (options.locations)
  17562. { comment.loc = new SourceLocation(this, startLoc, endLoc); }
  17563. if (options.ranges)
  17564. { comment.range = [start, end]; }
  17565. array.push(comment);
  17566. }
  17567. }
  17568. // Each scope gets a bitset that may contain these flags
  17569. var
  17570. SCOPE_TOP = 1,
  17571. SCOPE_FUNCTION = 2,
  17572. SCOPE_ASYNC = 4,
  17573. SCOPE_GENERATOR = 8,
  17574. SCOPE_ARROW = 16,
  17575. SCOPE_SIMPLE_CATCH = 32,
  17576. SCOPE_SUPER = 64,
  17577. SCOPE_DIRECT_SUPER = 128,
  17578. SCOPE_CLASS_STATIC_BLOCK = 256,
  17579. SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK;
  17580. function functionFlags(async, generator) {
  17581. return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0)
  17582. }
  17583. // Used in checkLVal* and declareName to determine the type of a binding
  17584. var
  17585. BIND_NONE = 0, // Not a binding
  17586. BIND_VAR = 1, // Var-style binding
  17587. BIND_LEXICAL = 2, // Let- or const-style binding
  17588. BIND_FUNCTION = 3, // Function declaration
  17589. BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding
  17590. BIND_OUTSIDE = 5; // Special case for function names as bound inside the function
  17591. var Parser = function Parser(options, input, startPos) {
  17592. this.options = options = getOptions(options);
  17593. this.sourceFile = options.sourceFile;
  17594. this.keywords = wordsRegexp(keywords$1[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);
  17595. var reserved = "";
  17596. if (options.allowReserved !== true) {
  17597. reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3];
  17598. if (options.sourceType === "module") { reserved += " await"; }
  17599. }
  17600. this.reservedWords = wordsRegexp(reserved);
  17601. var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict;
  17602. this.reservedWordsStrict = wordsRegexp(reservedStrict);
  17603. this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind);
  17604. this.input = String(input);
  17605. // Used to signal to callers of `readWord1` whether the word
  17606. // contained any escape sequences. This is needed because words with
  17607. // escape sequences must not be interpreted as keywords.
  17608. this.containsEsc = false;
  17609. // Set up token state
  17610. // The current position of the tokenizer in the input.
  17611. if (startPos) {
  17612. this.pos = startPos;
  17613. this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;
  17614. this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;
  17615. } else {
  17616. this.pos = this.lineStart = 0;
  17617. this.curLine = 1;
  17618. }
  17619. // Properties of the current token:
  17620. // Its type
  17621. this.type = types$1.eof;
  17622. // For tokens that include more information than their type, the value
  17623. this.value = null;
  17624. // Its start and end offset
  17625. this.start = this.end = this.pos;
  17626. // And, if locations are used, the {line, column} object
  17627. // corresponding to those offsets
  17628. this.startLoc = this.endLoc = this.curPosition();
  17629. // Position information for the previous token
  17630. this.lastTokEndLoc = this.lastTokStartLoc = null;
  17631. this.lastTokStart = this.lastTokEnd = this.pos;
  17632. // The context stack is used to superficially track syntactic
  17633. // context to predict whether a regular expression is allowed in a
  17634. // given position.
  17635. this.context = this.initialContext();
  17636. this.exprAllowed = true;
  17637. // Figure out if it's a module code.
  17638. this.inModule = options.sourceType === "module";
  17639. this.strict = this.inModule || this.strictDirective(this.pos);
  17640. // Used to signify the start of a potential arrow function
  17641. this.potentialArrowAt = -1;
  17642. this.potentialArrowInForAwait = false;
  17643. // Positions to delayed-check that yield/await does not exist in default parameters.
  17644. this.yieldPos = this.awaitPos = this.awaitIdentPos = 0;
  17645. // Labels in scope.
  17646. this.labels = [];
  17647. // Thus-far undefined exports.
  17648. this.undefinedExports = Object.create(null);
  17649. // If enabled, skip leading hashbang line.
  17650. if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!")
  17651. { this.skipLineComment(2); }
  17652. // Scope tracking for duplicate variable names (see scope.js)
  17653. this.scopeStack = [];
  17654. this.enterScope(SCOPE_TOP);
  17655. // For RegExp validation
  17656. this.regexpState = null;
  17657. // The stack of private names.
  17658. // Each element has two properties: 'declared' and 'used'.
  17659. // When it exited from the outermost class definition, all used private names must be declared.
  17660. this.privateNameStack = [];
  17661. };
  17662. 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 } };
  17663. Parser.prototype.parse = function parse () {
  17664. var node = this.options.program || this.startNode();
  17665. this.nextToken();
  17666. return this.parseTopLevel(node)
  17667. };
  17668. prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 };
  17669. prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 && !this.currentVarScope().inClassFieldInit };
  17670. prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 && !this.currentVarScope().inClassFieldInit };
  17671. prototypeAccessors.canAwait.get = function () {
  17672. for (var i = this.scopeStack.length - 1; i >= 0; i--) {
  17673. var scope = this.scopeStack[i];
  17674. if (scope.inClassFieldInit || scope.flags & SCOPE_CLASS_STATIC_BLOCK) { return false }
  17675. if (scope.flags & SCOPE_FUNCTION) { return (scope.flags & SCOPE_ASYNC) > 0 }
  17676. }
  17677. return (this.inModule && this.options.ecmaVersion >= 13) || this.options.allowAwaitOutsideFunction
  17678. };
  17679. prototypeAccessors.allowSuper.get = function () {
  17680. var ref = this.currentThisScope();
  17681. var flags = ref.flags;
  17682. var inClassFieldInit = ref.inClassFieldInit;
  17683. return (flags & SCOPE_SUPER) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod
  17684. };
  17685. prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 };
  17686. prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) };
  17687. prototypeAccessors.allowNewDotTarget.get = function () {
  17688. var ref = this.currentThisScope();
  17689. var flags = ref.flags;
  17690. var inClassFieldInit = ref.inClassFieldInit;
  17691. return (flags & (SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK)) > 0 || inClassFieldInit
  17692. };
  17693. prototypeAccessors.inClassStaticBlock.get = function () {
  17694. return (this.currentVarScope().flags & SCOPE_CLASS_STATIC_BLOCK) > 0
  17695. };
  17696. Parser.extend = function extend () {
  17697. var plugins = [], len = arguments.length;
  17698. while ( len-- ) plugins[ len ] = arguments[ len ];
  17699. var cls = this;
  17700. for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); }
  17701. return cls
  17702. };
  17703. Parser.parse = function parse (input, options) {
  17704. return new this(options, input).parse()
  17705. };
  17706. Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) {
  17707. var parser = new this(options, input, pos);
  17708. parser.nextToken();
  17709. return parser.parseExpression()
  17710. };
  17711. Parser.tokenizer = function tokenizer (input, options) {
  17712. return new this(options, input)
  17713. };
  17714. Object.defineProperties( Parser.prototype, prototypeAccessors );
  17715. var pp$9 = Parser.prototype;
  17716. // ## Parser utilities
  17717. var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/;
  17718. pp$9.strictDirective = function(start) {
  17719. if (this.options.ecmaVersion < 5) { return false }
  17720. for (;;) {
  17721. // Try to find string literal.
  17722. skipWhiteSpace.lastIndex = start;
  17723. start += skipWhiteSpace.exec(this.input)[0].length;
  17724. var match = literal.exec(this.input.slice(start));
  17725. if (!match) { return false }
  17726. if ((match[1] || match[2]) === "use strict") {
  17727. skipWhiteSpace.lastIndex = start + match[0].length;
  17728. var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length;
  17729. var next = this.input.charAt(end);
  17730. return next === ";" || next === "}" ||
  17731. (lineBreak.test(spaceAfter[0]) &&
  17732. !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "="))
  17733. }
  17734. start += match[0].length;
  17735. // Skip semicolon, if any.
  17736. skipWhiteSpace.lastIndex = start;
  17737. start += skipWhiteSpace.exec(this.input)[0].length;
  17738. if (this.input[start] === ";")
  17739. { start++; }
  17740. }
  17741. };
  17742. // Predicate that tests whether the next token is of the given
  17743. // type, and if yes, consumes it as a side effect.
  17744. pp$9.eat = function(type) {
  17745. if (this.type === type) {
  17746. this.next();
  17747. return true
  17748. } else {
  17749. return false
  17750. }
  17751. };
  17752. // Tests whether parsed token is a contextual keyword.
  17753. pp$9.isContextual = function(name) {
  17754. return this.type === types$1.name && this.value === name && !this.containsEsc
  17755. };
  17756. // Consumes contextual keyword if possible.
  17757. pp$9.eatContextual = function(name) {
  17758. if (!this.isContextual(name)) { return false }
  17759. this.next();
  17760. return true
  17761. };
  17762. // Asserts that following token is given contextual keyword.
  17763. pp$9.expectContextual = function(name) {
  17764. if (!this.eatContextual(name)) { this.unexpected(); }
  17765. };
  17766. // Test whether a semicolon can be inserted at the current position.
  17767. pp$9.canInsertSemicolon = function() {
  17768. return this.type === types$1.eof ||
  17769. this.type === types$1.braceR ||
  17770. lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
  17771. };
  17772. pp$9.insertSemicolon = function() {
  17773. if (this.canInsertSemicolon()) {
  17774. if (this.options.onInsertedSemicolon)
  17775. { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); }
  17776. return true
  17777. }
  17778. };
  17779. // Consume a semicolon, or, failing that, see if we are allowed to
  17780. // pretend that there is a semicolon at this position.
  17781. pp$9.semicolon = function() {
  17782. if (!this.eat(types$1.semi) && !this.insertSemicolon()) { this.unexpected(); }
  17783. };
  17784. pp$9.afterTrailingComma = function(tokType, notNext) {
  17785. if (this.type === tokType) {
  17786. if (this.options.onTrailingComma)
  17787. { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); }
  17788. if (!notNext)
  17789. { this.next(); }
  17790. return true
  17791. }
  17792. };
  17793. // Expect a token of a given type. If found, consume it, otherwise,
  17794. // raise an unexpected token error.
  17795. pp$9.expect = function(type) {
  17796. this.eat(type) || this.unexpected();
  17797. };
  17798. // Raise an unexpected token error.
  17799. pp$9.unexpected = function(pos) {
  17800. this.raise(pos != null ? pos : this.start, "Unexpected token");
  17801. };
  17802. var DestructuringErrors = function DestructuringErrors() {
  17803. this.shorthandAssign =
  17804. this.trailingComma =
  17805. this.parenthesizedAssign =
  17806. this.parenthesizedBind =
  17807. this.doubleProto =
  17808. -1;
  17809. };
  17810. pp$9.checkPatternErrors = function(refDestructuringErrors, isAssign) {
  17811. if (!refDestructuringErrors) { return }
  17812. if (refDestructuringErrors.trailingComma > -1)
  17813. { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); }
  17814. var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;
  17815. if (parens > -1) { this.raiseRecoverable(parens, isAssign ? "Assigning to rvalue" : "Parenthesized pattern"); }
  17816. };
  17817. pp$9.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
  17818. if (!refDestructuringErrors) { return false }
  17819. var shorthandAssign = refDestructuringErrors.shorthandAssign;
  17820. var doubleProto = refDestructuringErrors.doubleProto;
  17821. if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 }
  17822. if (shorthandAssign >= 0)
  17823. { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); }
  17824. if (doubleProto >= 0)
  17825. { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); }
  17826. };
  17827. pp$9.checkYieldAwaitInDefaultParams = function() {
  17828. if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos))
  17829. { this.raise(this.yieldPos, "Yield expression cannot be a default value"); }
  17830. if (this.awaitPos)
  17831. { this.raise(this.awaitPos, "Await expression cannot be a default value"); }
  17832. };
  17833. pp$9.isSimpleAssignTarget = function(expr) {
  17834. if (expr.type === "ParenthesizedExpression")
  17835. { return this.isSimpleAssignTarget(expr.expression) }
  17836. return expr.type === "Identifier" || expr.type === "MemberExpression"
  17837. };
  17838. var pp$8 = Parser.prototype;
  17839. // ### Statement parsing
  17840. // Parse a program. Initializes the parser, reads any number of
  17841. // statements, and wraps them in a Program node. Optionally takes a
  17842. // `program` argument. If present, the statements will be appended
  17843. // to its body instead of creating a new node.
  17844. pp$8.parseTopLevel = function(node) {
  17845. var exports = Object.create(null);
  17846. if (!node.body) { node.body = []; }
  17847. while (this.type !== types$1.eof) {
  17848. var stmt = this.parseStatement(null, true, exports);
  17849. node.body.push(stmt);
  17850. }
  17851. if (this.inModule)
  17852. { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1)
  17853. {
  17854. var name = list[i];
  17855. this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined"));
  17856. } }
  17857. this.adaptDirectivePrologue(node.body);
  17858. this.next();
  17859. node.sourceType = this.options.sourceType;
  17860. return this.finishNode(node, "Program")
  17861. };
  17862. var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"};
  17863. pp$8.isLet = function(context) {
  17864. if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false }
  17865. skipWhiteSpace.lastIndex = this.pos;
  17866. var skip = skipWhiteSpace.exec(this.input);
  17867. var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
  17868. // For ambiguous cases, determine if a LexicalDeclaration (or only a
  17869. // Statement) is allowed here. If context is not empty then only a Statement
  17870. // is allowed. However, `let [` is an explicit negative lookahead for
  17871. // ExpressionStatement, so special-case it first.
  17872. if (nextCh === 91 || nextCh === 92) { return true } // '[', '/'
  17873. if (context) { return false }
  17874. if (nextCh === 123 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } // '{', astral
  17875. if (isIdentifierStart(nextCh, true)) {
  17876. var pos = next + 1;
  17877. while (isIdentifierChar(nextCh = this.input.charCodeAt(pos), true)) { ++pos; }
  17878. if (nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true }
  17879. var ident = this.input.slice(next, pos);
  17880. if (!keywordRelationalOperator.test(ident)) { return true }
  17881. }
  17882. return false
  17883. };
  17884. // check 'async [no LineTerminator here] function'
  17885. // - 'async /*foo*/ function' is OK.
  17886. // - 'async /*\n*/ function' is invalid.
  17887. pp$8.isAsyncFunction = function() {
  17888. if (this.options.ecmaVersion < 8 || !this.isContextual("async"))
  17889. { return false }
  17890. skipWhiteSpace.lastIndex = this.pos;
  17891. var skip = skipWhiteSpace.exec(this.input);
  17892. var next = this.pos + skip[0].length, after;
  17893. return !lineBreak.test(this.input.slice(this.pos, next)) &&
  17894. this.input.slice(next, next + 8) === "function" &&
  17895. (next + 8 === this.input.length ||
  17896. !(isIdentifierChar(after = this.input.charCodeAt(next + 8)) || after > 0xd7ff && after < 0xdc00))
  17897. };
  17898. // Parse a single statement.
  17899. //
  17900. // If expecting a statement and finding a slash operator, parse a
  17901. // regular expression literal. This is to handle cases like
  17902. // `if (foo) /blah/.exec(foo)`, where looking at the previous token
  17903. // does not help.
  17904. pp$8.parseStatement = function(context, topLevel, exports) {
  17905. var starttype = this.type, node = this.startNode(), kind;
  17906. if (this.isLet(context)) {
  17907. starttype = types$1._var;
  17908. kind = "let";
  17909. }
  17910. // Most types of statements are recognized by the keyword they
  17911. // start with. Many are trivial to parse, some require a bit of
  17912. // complexity.
  17913. switch (starttype) {
  17914. case types$1._break: case types$1._continue: return this.parseBreakContinueStatement(node, starttype.keyword)
  17915. case types$1._debugger: return this.parseDebuggerStatement(node)
  17916. case types$1._do: return this.parseDoStatement(node)
  17917. case types$1._for: return this.parseForStatement(node)
  17918. case types$1._function:
  17919. // Function as sole body of either an if statement or a labeled statement
  17920. // works, but not when it is part of a labeled statement that is the sole
  17921. // body of an if statement.
  17922. if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); }
  17923. return this.parseFunctionStatement(node, false, !context)
  17924. case types$1._class:
  17925. if (context) { this.unexpected(); }
  17926. return this.parseClass(node, true)
  17927. case types$1._if: return this.parseIfStatement(node)
  17928. case types$1._return: return this.parseReturnStatement(node)
  17929. case types$1._switch: return this.parseSwitchStatement(node)
  17930. case types$1._throw: return this.parseThrowStatement(node)
  17931. case types$1._try: return this.parseTryStatement(node)
  17932. case types$1._const: case types$1._var:
  17933. kind = kind || this.value;
  17934. if (context && kind !== "var") { this.unexpected(); }
  17935. return this.parseVarStatement(node, kind)
  17936. case types$1._while: return this.parseWhileStatement(node)
  17937. case types$1._with: return this.parseWithStatement(node)
  17938. case types$1.braceL: return this.parseBlock(true, node)
  17939. case types$1.semi: return this.parseEmptyStatement(node)
  17940. case types$1._export:
  17941. case types$1._import:
  17942. if (this.options.ecmaVersion > 10 && starttype === types$1._import) {
  17943. skipWhiteSpace.lastIndex = this.pos;
  17944. var skip = skipWhiteSpace.exec(this.input);
  17945. var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
  17946. if (nextCh === 40 || nextCh === 46) // '(' or '.'
  17947. { return this.parseExpressionStatement(node, this.parseExpression()) }
  17948. }
  17949. if (!this.options.allowImportExportEverywhere) {
  17950. if (!topLevel)
  17951. { this.raise(this.start, "'import' and 'export' may only appear at the top level"); }
  17952. if (!this.inModule)
  17953. { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); }
  17954. }
  17955. return starttype === types$1._import ? this.parseImport(node) : this.parseExport(node, exports)
  17956. // If the statement does not start with a statement keyword or a
  17957. // brace, it's an ExpressionStatement or LabeledStatement. We
  17958. // simply start parsing an expression, and afterwards, if the
  17959. // next token is a colon and the expression was a simple
  17960. // Identifier node, we switch to interpreting it as a label.
  17961. default:
  17962. if (this.isAsyncFunction()) {
  17963. if (context) { this.unexpected(); }
  17964. this.next();
  17965. return this.parseFunctionStatement(node, true, !context)
  17966. }
  17967. var maybeName = this.value, expr = this.parseExpression();
  17968. if (starttype === types$1.name && expr.type === "Identifier" && this.eat(types$1.colon))
  17969. { return this.parseLabeledStatement(node, maybeName, expr, context) }
  17970. else { return this.parseExpressionStatement(node, expr) }
  17971. }
  17972. };
  17973. pp$8.parseBreakContinueStatement = function(node, keyword) {
  17974. var isBreak = keyword === "break";
  17975. this.next();
  17976. if (this.eat(types$1.semi) || this.insertSemicolon()) { node.label = null; }
  17977. else if (this.type !== types$1.name) { this.unexpected(); }
  17978. else {
  17979. node.label = this.parseIdent();
  17980. this.semicolon();
  17981. }
  17982. // Verify that there is an actual destination to break or
  17983. // continue to.
  17984. var i = 0;
  17985. for (; i < this.labels.length; ++i) {
  17986. var lab = this.labels[i];
  17987. if (node.label == null || lab.name === node.label.name) {
  17988. if (lab.kind != null && (isBreak || lab.kind === "loop")) { break }
  17989. if (node.label && isBreak) { break }
  17990. }
  17991. }
  17992. if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); }
  17993. return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement")
  17994. };
  17995. pp$8.parseDebuggerStatement = function(node) {
  17996. this.next();
  17997. this.semicolon();
  17998. return this.finishNode(node, "DebuggerStatement")
  17999. };
  18000. pp$8.parseDoStatement = function(node) {
  18001. this.next();
  18002. this.labels.push(loopLabel);
  18003. node.body = this.parseStatement("do");
  18004. this.labels.pop();
  18005. this.expect(types$1._while);
  18006. node.test = this.parseParenExpression();
  18007. if (this.options.ecmaVersion >= 6)
  18008. { this.eat(types$1.semi); }
  18009. else
  18010. { this.semicolon(); }
  18011. return this.finishNode(node, "DoWhileStatement")
  18012. };
  18013. // Disambiguating between a `for` and a `for`/`in` or `for`/`of`
  18014. // loop is non-trivial. Basically, we have to parse the init `var`
  18015. // statement or expression, disallowing the `in` operator (see
  18016. // the second parameter to `parseExpression`), and then check
  18017. // whether the next token is `in` or `of`. When there is no init
  18018. // part (semicolon immediately after the opening parenthesis), it
  18019. // is a regular `for` loop.
  18020. pp$8.parseForStatement = function(node) {
  18021. this.next();
  18022. var awaitAt = (this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await")) ? this.lastTokStart : -1;
  18023. this.labels.push(loopLabel);
  18024. this.enterScope(0);
  18025. this.expect(types$1.parenL);
  18026. if (this.type === types$1.semi) {
  18027. if (awaitAt > -1) { this.unexpected(awaitAt); }
  18028. return this.parseFor(node, null)
  18029. }
  18030. var isLet = this.isLet();
  18031. if (this.type === types$1._var || this.type === types$1._const || isLet) {
  18032. var init$1 = this.startNode(), kind = isLet ? "let" : this.value;
  18033. this.next();
  18034. this.parseVar(init$1, true, kind);
  18035. this.finishNode(init$1, "VariableDeclaration");
  18036. if ((this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) {
  18037. if (this.options.ecmaVersion >= 9) {
  18038. if (this.type === types$1._in) {
  18039. if (awaitAt > -1) { this.unexpected(awaitAt); }
  18040. } else { node.await = awaitAt > -1; }
  18041. }
  18042. return this.parseForIn(node, init$1)
  18043. }
  18044. if (awaitAt > -1) { this.unexpected(awaitAt); }
  18045. return this.parseFor(node, init$1)
  18046. }
  18047. var startsWithLet = this.isContextual("let"), isForOf = false;
  18048. var refDestructuringErrors = new DestructuringErrors;
  18049. var init = this.parseExpression(awaitAt > -1 ? "await" : true, refDestructuringErrors);
  18050. if (this.type === types$1._in || (isForOf = this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
  18051. if (this.options.ecmaVersion >= 9) {
  18052. if (this.type === types$1._in) {
  18053. if (awaitAt > -1) { this.unexpected(awaitAt); }
  18054. } else { node.await = awaitAt > -1; }
  18055. }
  18056. if (startsWithLet && isForOf) { this.raise(init.start, "The left-hand side of a for-of loop may not start with 'let'."); }
  18057. this.toAssignable(init, false, refDestructuringErrors);
  18058. this.checkLValPattern(init);
  18059. return this.parseForIn(node, init)
  18060. } else {
  18061. this.checkExpressionErrors(refDestructuringErrors, true);
  18062. }
  18063. if (awaitAt > -1) { this.unexpected(awaitAt); }
  18064. return this.parseFor(node, init)
  18065. };
  18066. pp$8.parseFunctionStatement = function(node, isAsync, declarationPosition) {
  18067. this.next();
  18068. return this.parseFunction(node, FUNC_STATEMENT$1 | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync)
  18069. };
  18070. pp$8.parseIfStatement = function(node) {
  18071. this.next();
  18072. node.test = this.parseParenExpression();
  18073. // allow function declarations in branches, but only in non-strict mode
  18074. node.consequent = this.parseStatement("if");
  18075. node.alternate = this.eat(types$1._else) ? this.parseStatement("if") : null;
  18076. return this.finishNode(node, "IfStatement")
  18077. };
  18078. pp$8.parseReturnStatement = function(node) {
  18079. if (!this.inFunction && !this.options.allowReturnOutsideFunction)
  18080. { this.raise(this.start, "'return' outside of function"); }
  18081. this.next();
  18082. // In `return` (and `break`/`continue`), the keywords with
  18083. // optional arguments, we eagerly look for a semicolon or the
  18084. // possibility to insert one.
  18085. if (this.eat(types$1.semi) || this.insertSemicolon()) { node.argument = null; }
  18086. else { node.argument = this.parseExpression(); this.semicolon(); }
  18087. return this.finishNode(node, "ReturnStatement")
  18088. };
  18089. pp$8.parseSwitchStatement = function(node) {
  18090. this.next();
  18091. node.discriminant = this.parseParenExpression();
  18092. node.cases = [];
  18093. this.expect(types$1.braceL);
  18094. this.labels.push(switchLabel);
  18095. this.enterScope(0);
  18096. // Statements under must be grouped (by label) in SwitchCase
  18097. // nodes. `cur` is used to keep the node that we are currently
  18098. // adding statements to.
  18099. var cur;
  18100. for (var sawDefault = false; this.type !== types$1.braceR;) {
  18101. if (this.type === types$1._case || this.type === types$1._default) {
  18102. var isCase = this.type === types$1._case;
  18103. if (cur) { this.finishNode(cur, "SwitchCase"); }
  18104. node.cases.push(cur = this.startNode());
  18105. cur.consequent = [];
  18106. this.next();
  18107. if (isCase) {
  18108. cur.test = this.parseExpression();
  18109. } else {
  18110. if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); }
  18111. sawDefault = true;
  18112. cur.test = null;
  18113. }
  18114. this.expect(types$1.colon);
  18115. } else {
  18116. if (!cur) { this.unexpected(); }
  18117. cur.consequent.push(this.parseStatement(null));
  18118. }
  18119. }
  18120. this.exitScope();
  18121. if (cur) { this.finishNode(cur, "SwitchCase"); }
  18122. this.next(); // Closing brace
  18123. this.labels.pop();
  18124. return this.finishNode(node, "SwitchStatement")
  18125. };
  18126. pp$8.parseThrowStatement = function(node) {
  18127. this.next();
  18128. if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start)))
  18129. { this.raise(this.lastTokEnd, "Illegal newline after throw"); }
  18130. node.argument = this.parseExpression();
  18131. this.semicolon();
  18132. return this.finishNode(node, "ThrowStatement")
  18133. };
  18134. // Reused empty array added for node fields that are always empty.
  18135. var empty$1 = [];
  18136. pp$8.parseCatchClauseParam = function() {
  18137. var param = this.parseBindingAtom();
  18138. var simple = param.type === "Identifier";
  18139. this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0);
  18140. this.checkLValPattern(param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL);
  18141. this.expect(types$1.parenR);
  18142. return param
  18143. };
  18144. pp$8.parseTryStatement = function(node) {
  18145. this.next();
  18146. node.block = this.parseBlock();
  18147. node.handler = null;
  18148. if (this.type === types$1._catch) {
  18149. var clause = this.startNode();
  18150. this.next();
  18151. if (this.eat(types$1.parenL)) {
  18152. clause.param = this.parseCatchClauseParam();
  18153. } else {
  18154. if (this.options.ecmaVersion < 10) { this.unexpected(); }
  18155. clause.param = null;
  18156. this.enterScope(0);
  18157. }
  18158. clause.body = this.parseBlock(false);
  18159. this.exitScope();
  18160. node.handler = this.finishNode(clause, "CatchClause");
  18161. }
  18162. node.finalizer = this.eat(types$1._finally) ? this.parseBlock() : null;
  18163. if (!node.handler && !node.finalizer)
  18164. { this.raise(node.start, "Missing catch or finally clause"); }
  18165. return this.finishNode(node, "TryStatement")
  18166. };
  18167. pp$8.parseVarStatement = function(node, kind, allowMissingInitializer) {
  18168. this.next();
  18169. this.parseVar(node, false, kind, allowMissingInitializer);
  18170. this.semicolon();
  18171. return this.finishNode(node, "VariableDeclaration")
  18172. };
  18173. pp$8.parseWhileStatement = function(node) {
  18174. this.next();
  18175. node.test = this.parseParenExpression();
  18176. this.labels.push(loopLabel);
  18177. node.body = this.parseStatement("while");
  18178. this.labels.pop();
  18179. return this.finishNode(node, "WhileStatement")
  18180. };
  18181. pp$8.parseWithStatement = function(node) {
  18182. if (this.strict) { this.raise(this.start, "'with' in strict mode"); }
  18183. this.next();
  18184. node.object = this.parseParenExpression();
  18185. node.body = this.parseStatement("with");
  18186. return this.finishNode(node, "WithStatement")
  18187. };
  18188. pp$8.parseEmptyStatement = function(node) {
  18189. this.next();
  18190. return this.finishNode(node, "EmptyStatement")
  18191. };
  18192. pp$8.parseLabeledStatement = function(node, maybeName, expr, context) {
  18193. for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1)
  18194. {
  18195. var label = list[i$1];
  18196. if (label.name === maybeName)
  18197. { this.raise(expr.start, "Label '" + maybeName + "' is already declared");
  18198. } }
  18199. var kind = this.type.isLoop ? "loop" : this.type === types$1._switch ? "switch" : null;
  18200. for (var i = this.labels.length - 1; i >= 0; i--) {
  18201. var label$1 = this.labels[i];
  18202. if (label$1.statementStart === node.start) {
  18203. // Update information about previous labels on this node
  18204. label$1.statementStart = this.start;
  18205. label$1.kind = kind;
  18206. } else { break }
  18207. }
  18208. this.labels.push({name: maybeName, kind: kind, statementStart: this.start});
  18209. node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
  18210. this.labels.pop();
  18211. node.label = expr;
  18212. return this.finishNode(node, "LabeledStatement")
  18213. };
  18214. pp$8.parseExpressionStatement = function(node, expr) {
  18215. node.expression = expr;
  18216. this.semicolon();
  18217. return this.finishNode(node, "ExpressionStatement")
  18218. };
  18219. // Parse a semicolon-enclosed block of statements, handling `"use
  18220. // strict"` declarations when `allowStrict` is true (used for
  18221. // function bodies).
  18222. pp$8.parseBlock = function(createNewLexicalScope, node, exitStrict) {
  18223. if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true;
  18224. if ( node === void 0 ) node = this.startNode();
  18225. node.body = [];
  18226. this.expect(types$1.braceL);
  18227. if (createNewLexicalScope) { this.enterScope(0); }
  18228. while (this.type !== types$1.braceR) {
  18229. var stmt = this.parseStatement(null);
  18230. node.body.push(stmt);
  18231. }
  18232. if (exitStrict) { this.strict = false; }
  18233. this.next();
  18234. if (createNewLexicalScope) { this.exitScope(); }
  18235. return this.finishNode(node, "BlockStatement")
  18236. };
  18237. // Parse a regular `for` loop. The disambiguation code in
  18238. // `parseStatement` will already have parsed the init statement or
  18239. // expression.
  18240. pp$8.parseFor = function(node, init) {
  18241. node.init = init;
  18242. this.expect(types$1.semi);
  18243. node.test = this.type === types$1.semi ? null : this.parseExpression();
  18244. this.expect(types$1.semi);
  18245. node.update = this.type === types$1.parenR ? null : this.parseExpression();
  18246. this.expect(types$1.parenR);
  18247. node.body = this.parseStatement("for");
  18248. this.exitScope();
  18249. this.labels.pop();
  18250. return this.finishNode(node, "ForStatement")
  18251. };
  18252. // Parse a `for`/`in` and `for`/`of` loop, which are almost
  18253. // same from parser's perspective.
  18254. pp$8.parseForIn = function(node, init) {
  18255. var isForIn = this.type === types$1._in;
  18256. this.next();
  18257. if (
  18258. init.type === "VariableDeclaration" &&
  18259. init.declarations[0].init != null &&
  18260. (
  18261. !isForIn ||
  18262. this.options.ecmaVersion < 8 ||
  18263. this.strict ||
  18264. init.kind !== "var" ||
  18265. init.declarations[0].id.type !== "Identifier"
  18266. )
  18267. ) {
  18268. this.raise(
  18269. init.start,
  18270. ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer")
  18271. );
  18272. }
  18273. node.left = init;
  18274. node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
  18275. this.expect(types$1.parenR);
  18276. node.body = this.parseStatement("for");
  18277. this.exitScope();
  18278. this.labels.pop();
  18279. return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement")
  18280. };
  18281. // Parse a list of variable declarations.
  18282. pp$8.parseVar = function(node, isFor, kind, allowMissingInitializer) {
  18283. node.declarations = [];
  18284. node.kind = kind;
  18285. for (;;) {
  18286. var decl = this.startNode();
  18287. this.parseVarId(decl, kind);
  18288. if (this.eat(types$1.eq)) {
  18289. decl.init = this.parseMaybeAssign(isFor);
  18290. } else if (!allowMissingInitializer && kind === "const" && !(this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) {
  18291. this.unexpected();
  18292. } else if (!allowMissingInitializer && decl.id.type !== "Identifier" && !(isFor && (this.type === types$1._in || this.isContextual("of")))) {
  18293. this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
  18294. } else {
  18295. decl.init = null;
  18296. }
  18297. node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
  18298. if (!this.eat(types$1.comma)) { break }
  18299. }
  18300. return node
  18301. };
  18302. pp$8.parseVarId = function(decl, kind) {
  18303. decl.id = this.parseBindingAtom();
  18304. this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false);
  18305. };
  18306. var FUNC_STATEMENT$1 = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID$1 = 4;
  18307. // Parse a function declaration or literal (depending on the
  18308. // `statement & FUNC_STATEMENT`).
  18309. // Remove `allowExpressionBody` for 7.0.0, as it is only called with false
  18310. pp$8.parseFunction = function(node, statement, allowExpressionBody, isAsync, forInit) {
  18311. this.initFunction(node);
  18312. if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) {
  18313. if (this.type === types$1.star && (statement & FUNC_HANGING_STATEMENT))
  18314. { this.unexpected(); }
  18315. node.generator = this.eat(types$1.star);
  18316. }
  18317. if (this.options.ecmaVersion >= 8)
  18318. { node.async = !!isAsync; }
  18319. if (statement & FUNC_STATEMENT$1) {
  18320. node.id = (statement & FUNC_NULLABLE_ID$1) && this.type !== types$1.name ? null : this.parseIdent();
  18321. if (node.id && !(statement & FUNC_HANGING_STATEMENT))
  18322. // If it is a regular function declaration in sloppy mode, then it is
  18323. // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding
  18324. // mode depends on properties of the current scope (see
  18325. // treatFunctionsAsVar).
  18326. { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); }
  18327. }
  18328. var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  18329. this.yieldPos = 0;
  18330. this.awaitPos = 0;
  18331. this.awaitIdentPos = 0;
  18332. this.enterScope(functionFlags(node.async, node.generator));
  18333. if (!(statement & FUNC_STATEMENT$1))
  18334. { node.id = this.type === types$1.name ? this.parseIdent() : null; }
  18335. this.parseFunctionParams(node);
  18336. this.parseFunctionBody(node, allowExpressionBody, false, forInit);
  18337. this.yieldPos = oldYieldPos;
  18338. this.awaitPos = oldAwaitPos;
  18339. this.awaitIdentPos = oldAwaitIdentPos;
  18340. return this.finishNode(node, (statement & FUNC_STATEMENT$1) ? "FunctionDeclaration" : "FunctionExpression")
  18341. };
  18342. pp$8.parseFunctionParams = function(node) {
  18343. this.expect(types$1.parenL);
  18344. node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8);
  18345. this.checkYieldAwaitInDefaultParams();
  18346. };
  18347. // Parse a class declaration or literal (depending on the
  18348. // `isStatement` parameter).
  18349. pp$8.parseClass = function(node, isStatement) {
  18350. this.next();
  18351. // ecma-262 14.6 Class Definitions
  18352. // A class definition is always strict mode code.
  18353. var oldStrict = this.strict;
  18354. this.strict = true;
  18355. this.parseClassId(node, isStatement);
  18356. this.parseClassSuper(node);
  18357. var privateNameMap = this.enterClassBody();
  18358. var classBody = this.startNode();
  18359. var hadConstructor = false;
  18360. classBody.body = [];
  18361. this.expect(types$1.braceL);
  18362. while (this.type !== types$1.braceR) {
  18363. var element = this.parseClassElement(node.superClass !== null);
  18364. if (element) {
  18365. classBody.body.push(element);
  18366. if (element.type === "MethodDefinition" && element.kind === "constructor") {
  18367. if (hadConstructor) { this.raiseRecoverable(element.start, "Duplicate constructor in the same class"); }
  18368. hadConstructor = true;
  18369. } else if (element.key && element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) {
  18370. this.raiseRecoverable(element.key.start, ("Identifier '#" + (element.key.name) + "' has already been declared"));
  18371. }
  18372. }
  18373. }
  18374. this.strict = oldStrict;
  18375. this.next();
  18376. node.body = this.finishNode(classBody, "ClassBody");
  18377. this.exitClassBody();
  18378. return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression")
  18379. };
  18380. pp$8.parseClassElement = function(constructorAllowsSuper) {
  18381. if (this.eat(types$1.semi)) { return null }
  18382. var ecmaVersion = this.options.ecmaVersion;
  18383. var node = this.startNode();
  18384. var keyName = "";
  18385. var isGenerator = false;
  18386. var isAsync = false;
  18387. var kind = "method";
  18388. var isStatic = false;
  18389. if (this.eatContextual("static")) {
  18390. // Parse static init block
  18391. if (ecmaVersion >= 13 && this.eat(types$1.braceL)) {
  18392. this.parseClassStaticBlock(node);
  18393. return node
  18394. }
  18395. if (this.isClassElementNameStart() || this.type === types$1.star) {
  18396. isStatic = true;
  18397. } else {
  18398. keyName = "static";
  18399. }
  18400. }
  18401. node.static = isStatic;
  18402. if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) {
  18403. if ((this.isClassElementNameStart() || this.type === types$1.star) && !this.canInsertSemicolon()) {
  18404. isAsync = true;
  18405. } else {
  18406. keyName = "async";
  18407. }
  18408. }
  18409. if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(types$1.star)) {
  18410. isGenerator = true;
  18411. }
  18412. if (!keyName && !isAsync && !isGenerator) {
  18413. var lastValue = this.value;
  18414. if (this.eatContextual("get") || this.eatContextual("set")) {
  18415. if (this.isClassElementNameStart()) {
  18416. kind = lastValue;
  18417. } else {
  18418. keyName = lastValue;
  18419. }
  18420. }
  18421. }
  18422. // Parse element name
  18423. if (keyName) {
  18424. // 'async', 'get', 'set', or 'static' were not a keyword contextually.
  18425. // The last token is any of those. Make it the element name.
  18426. node.computed = false;
  18427. node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc);
  18428. node.key.name = keyName;
  18429. this.finishNode(node.key, "Identifier");
  18430. } else {
  18431. this.parseClassElementName(node);
  18432. }
  18433. // Parse element value
  18434. if (ecmaVersion < 13 || this.type === types$1.parenL || kind !== "method" || isGenerator || isAsync) {
  18435. var isConstructor = !node.static && checkKeyName(node, "constructor");
  18436. var allowsDirectSuper = isConstructor && constructorAllowsSuper;
  18437. // Couldn't move this check into the 'parseClassMethod' method for backward compatibility.
  18438. if (isConstructor && kind !== "method") { this.raise(node.key.start, "Constructor can't have get/set modifier"); }
  18439. node.kind = isConstructor ? "constructor" : kind;
  18440. this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper);
  18441. } else {
  18442. this.parseClassField(node);
  18443. }
  18444. return node
  18445. };
  18446. pp$8.isClassElementNameStart = function() {
  18447. return (
  18448. this.type === types$1.name ||
  18449. this.type === types$1.privateId ||
  18450. this.type === types$1.num ||
  18451. this.type === types$1.string ||
  18452. this.type === types$1.bracketL ||
  18453. this.type.keyword
  18454. )
  18455. };
  18456. pp$8.parseClassElementName = function(element) {
  18457. if (this.type === types$1.privateId) {
  18458. if (this.value === "constructor") {
  18459. this.raise(this.start, "Classes can't have an element named '#constructor'");
  18460. }
  18461. element.computed = false;
  18462. element.key = this.parsePrivateIdent();
  18463. } else {
  18464. this.parsePropertyName(element);
  18465. }
  18466. };
  18467. pp$8.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) {
  18468. // Check key and flags
  18469. var key = method.key;
  18470. if (method.kind === "constructor") {
  18471. if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); }
  18472. if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); }
  18473. } else if (method.static && checkKeyName(method, "prototype")) {
  18474. this.raise(key.start, "Classes may not have a static property named prototype");
  18475. }
  18476. // Parse value
  18477. var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper);
  18478. // Check value
  18479. if (method.kind === "get" && value.params.length !== 0)
  18480. { this.raiseRecoverable(value.start, "getter should have no params"); }
  18481. if (method.kind === "set" && value.params.length !== 1)
  18482. { this.raiseRecoverable(value.start, "setter should have exactly one param"); }
  18483. if (method.kind === "set" && value.params[0].type === "RestElement")
  18484. { this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params"); }
  18485. return this.finishNode(method, "MethodDefinition")
  18486. };
  18487. pp$8.parseClassField = function(field) {
  18488. if (checkKeyName(field, "constructor")) {
  18489. this.raise(field.key.start, "Classes can't have a field named 'constructor'");
  18490. } else if (field.static && checkKeyName(field, "prototype")) {
  18491. this.raise(field.key.start, "Classes can't have a static field named 'prototype'");
  18492. }
  18493. if (this.eat(types$1.eq)) {
  18494. // To raise SyntaxError if 'arguments' exists in the initializer.
  18495. var scope = this.currentThisScope();
  18496. var inClassFieldInit = scope.inClassFieldInit;
  18497. scope.inClassFieldInit = true;
  18498. field.value = this.parseMaybeAssign();
  18499. scope.inClassFieldInit = inClassFieldInit;
  18500. } else {
  18501. field.value = null;
  18502. }
  18503. this.semicolon();
  18504. return this.finishNode(field, "PropertyDefinition")
  18505. };
  18506. pp$8.parseClassStaticBlock = function(node) {
  18507. node.body = [];
  18508. var oldLabels = this.labels;
  18509. this.labels = [];
  18510. this.enterScope(SCOPE_CLASS_STATIC_BLOCK | SCOPE_SUPER);
  18511. while (this.type !== types$1.braceR) {
  18512. var stmt = this.parseStatement(null);
  18513. node.body.push(stmt);
  18514. }
  18515. this.next();
  18516. this.exitScope();
  18517. this.labels = oldLabels;
  18518. return this.finishNode(node, "StaticBlock")
  18519. };
  18520. pp$8.parseClassId = function(node, isStatement) {
  18521. if (this.type === types$1.name) {
  18522. node.id = this.parseIdent();
  18523. if (isStatement)
  18524. { this.checkLValSimple(node.id, BIND_LEXICAL, false); }
  18525. } else {
  18526. if (isStatement === true)
  18527. { this.unexpected(); }
  18528. node.id = null;
  18529. }
  18530. };
  18531. pp$8.parseClassSuper = function(node) {
  18532. node.superClass = this.eat(types$1._extends) ? this.parseExprSubscripts(null, false) : null;
  18533. };
  18534. pp$8.enterClassBody = function() {
  18535. var element = {declared: Object.create(null), used: []};
  18536. this.privateNameStack.push(element);
  18537. return element.declared
  18538. };
  18539. pp$8.exitClassBody = function() {
  18540. var ref = this.privateNameStack.pop();
  18541. var declared = ref.declared;
  18542. var used = ref.used;
  18543. if (!this.options.checkPrivateFields) { return }
  18544. var len = this.privateNameStack.length;
  18545. var parent = len === 0 ? null : this.privateNameStack[len - 1];
  18546. for (var i = 0; i < used.length; ++i) {
  18547. var id = used[i];
  18548. if (!hasOwn(declared, id.name)) {
  18549. if (parent) {
  18550. parent.used.push(id);
  18551. } else {
  18552. this.raiseRecoverable(id.start, ("Private field '#" + (id.name) + "' must be declared in an enclosing class"));
  18553. }
  18554. }
  18555. }
  18556. };
  18557. function isPrivateNameConflicted(privateNameMap, element) {
  18558. var name = element.key.name;
  18559. var curr = privateNameMap[name];
  18560. var next = "true";
  18561. if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) {
  18562. next = (element.static ? "s" : "i") + element.kind;
  18563. }
  18564. // `class { get #a(){}; static set #a(_){} }` is also conflict.
  18565. if (
  18566. curr === "iget" && next === "iset" ||
  18567. curr === "iset" && next === "iget" ||
  18568. curr === "sget" && next === "sset" ||
  18569. curr === "sset" && next === "sget"
  18570. ) {
  18571. privateNameMap[name] = "true";
  18572. return false
  18573. } else if (!curr) {
  18574. privateNameMap[name] = next;
  18575. return false
  18576. } else {
  18577. return true
  18578. }
  18579. }
  18580. function checkKeyName(node, name) {
  18581. var computed = node.computed;
  18582. var key = node.key;
  18583. return !computed && (
  18584. key.type === "Identifier" && key.name === name ||
  18585. key.type === "Literal" && key.value === name
  18586. )
  18587. }
  18588. // Parses module export declaration.
  18589. pp$8.parseExportAllDeclaration = function(node, exports) {
  18590. if (this.options.ecmaVersion >= 11) {
  18591. if (this.eatContextual("as")) {
  18592. node.exported = this.parseModuleExportName();
  18593. this.checkExport(exports, node.exported, this.lastTokStart);
  18594. } else {
  18595. node.exported = null;
  18596. }
  18597. }
  18598. this.expectContextual("from");
  18599. if (this.type !== types$1.string) { this.unexpected(); }
  18600. node.source = this.parseExprAtom();
  18601. this.semicolon();
  18602. return this.finishNode(node, "ExportAllDeclaration")
  18603. };
  18604. pp$8.parseExport = function(node, exports) {
  18605. this.next();
  18606. // export * from '...'
  18607. if (this.eat(types$1.star)) {
  18608. return this.parseExportAllDeclaration(node, exports)
  18609. }
  18610. if (this.eat(types$1._default)) { // export default ...
  18611. this.checkExport(exports, "default", this.lastTokStart);
  18612. node.declaration = this.parseExportDefaultDeclaration();
  18613. return this.finishNode(node, "ExportDefaultDeclaration")
  18614. }
  18615. // export var|const|let|function|class ...
  18616. if (this.shouldParseExportStatement()) {
  18617. node.declaration = this.parseExportDeclaration(node);
  18618. if (node.declaration.type === "VariableDeclaration")
  18619. { this.checkVariableExport(exports, node.declaration.declarations); }
  18620. else
  18621. { this.checkExport(exports, node.declaration.id, node.declaration.id.start); }
  18622. node.specifiers = [];
  18623. node.source = null;
  18624. } else { // export { x, y as z } [from '...']
  18625. node.declaration = null;
  18626. node.specifiers = this.parseExportSpecifiers(exports);
  18627. if (this.eatContextual("from")) {
  18628. if (this.type !== types$1.string) { this.unexpected(); }
  18629. node.source = this.parseExprAtom();
  18630. } else {
  18631. for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
  18632. // check for keywords used as local names
  18633. var spec = list[i];
  18634. this.checkUnreserved(spec.local);
  18635. // check if export is defined
  18636. this.checkLocalExport(spec.local);
  18637. if (spec.local.type === "Literal") {
  18638. this.raise(spec.local.start, "A string literal cannot be used as an exported binding without `from`.");
  18639. }
  18640. }
  18641. node.source = null;
  18642. }
  18643. this.semicolon();
  18644. }
  18645. return this.finishNode(node, "ExportNamedDeclaration")
  18646. };
  18647. pp$8.parseExportDeclaration = function(node) {
  18648. return this.parseStatement(null)
  18649. };
  18650. pp$8.parseExportDefaultDeclaration = function() {
  18651. var isAsync;
  18652. if (this.type === types$1._function || (isAsync = this.isAsyncFunction())) {
  18653. var fNode = this.startNode();
  18654. this.next();
  18655. if (isAsync) { this.next(); }
  18656. return this.parseFunction(fNode, FUNC_STATEMENT$1 | FUNC_NULLABLE_ID$1, false, isAsync)
  18657. } else if (this.type === types$1._class) {
  18658. var cNode = this.startNode();
  18659. return this.parseClass(cNode, "nullableID")
  18660. } else {
  18661. var declaration = this.parseMaybeAssign();
  18662. this.semicolon();
  18663. return declaration
  18664. }
  18665. };
  18666. pp$8.checkExport = function(exports, name, pos) {
  18667. if (!exports) { return }
  18668. if (typeof name !== "string")
  18669. { name = name.type === "Identifier" ? name.name : name.value; }
  18670. if (hasOwn(exports, name))
  18671. { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); }
  18672. exports[name] = true;
  18673. };
  18674. pp$8.checkPatternExport = function(exports, pat) {
  18675. var type = pat.type;
  18676. if (type === "Identifier")
  18677. { this.checkExport(exports, pat, pat.start); }
  18678. else if (type === "ObjectPattern")
  18679. { for (var i = 0, list = pat.properties; i < list.length; i += 1)
  18680. {
  18681. var prop = list[i];
  18682. this.checkPatternExport(exports, prop);
  18683. } }
  18684. else if (type === "ArrayPattern")
  18685. { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) {
  18686. var elt = list$1[i$1];
  18687. if (elt) { this.checkPatternExport(exports, elt); }
  18688. } }
  18689. else if (type === "Property")
  18690. { this.checkPatternExport(exports, pat.value); }
  18691. else if (type === "AssignmentPattern")
  18692. { this.checkPatternExport(exports, pat.left); }
  18693. else if (type === "RestElement")
  18694. { this.checkPatternExport(exports, pat.argument); }
  18695. else if (type === "ParenthesizedExpression")
  18696. { this.checkPatternExport(exports, pat.expression); }
  18697. };
  18698. pp$8.checkVariableExport = function(exports, decls) {
  18699. if (!exports) { return }
  18700. for (var i = 0, list = decls; i < list.length; i += 1)
  18701. {
  18702. var decl = list[i];
  18703. this.checkPatternExport(exports, decl.id);
  18704. }
  18705. };
  18706. pp$8.shouldParseExportStatement = function() {
  18707. return this.type.keyword === "var" ||
  18708. this.type.keyword === "const" ||
  18709. this.type.keyword === "class" ||
  18710. this.type.keyword === "function" ||
  18711. this.isLet() ||
  18712. this.isAsyncFunction()
  18713. };
  18714. // Parses a comma-separated list of module exports.
  18715. pp$8.parseExportSpecifier = function(exports) {
  18716. var node = this.startNode();
  18717. node.local = this.parseModuleExportName();
  18718. node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local;
  18719. this.checkExport(
  18720. exports,
  18721. node.exported,
  18722. node.exported.start
  18723. );
  18724. return this.finishNode(node, "ExportSpecifier")
  18725. };
  18726. pp$8.parseExportSpecifiers = function(exports) {
  18727. var nodes = [], first = true;
  18728. // export { x, y as z } [from '...']
  18729. this.expect(types$1.braceL);
  18730. while (!this.eat(types$1.braceR)) {
  18731. if (!first) {
  18732. this.expect(types$1.comma);
  18733. if (this.afterTrailingComma(types$1.braceR)) { break }
  18734. } else { first = false; }
  18735. nodes.push(this.parseExportSpecifier(exports));
  18736. }
  18737. return nodes
  18738. };
  18739. // Parses import declaration.
  18740. pp$8.parseImport = function(node) {
  18741. this.next();
  18742. // import '...'
  18743. if (this.type === types$1.string) {
  18744. node.specifiers = empty$1;
  18745. node.source = this.parseExprAtom();
  18746. } else {
  18747. node.specifiers = this.parseImportSpecifiers();
  18748. this.expectContextual("from");
  18749. node.source = this.type === types$1.string ? this.parseExprAtom() : this.unexpected();
  18750. }
  18751. this.semicolon();
  18752. return this.finishNode(node, "ImportDeclaration")
  18753. };
  18754. // Parses a comma-separated list of module imports.
  18755. pp$8.parseImportSpecifier = function() {
  18756. var node = this.startNode();
  18757. node.imported = this.parseModuleExportName();
  18758. if (this.eatContextual("as")) {
  18759. node.local = this.parseIdent();
  18760. } else {
  18761. this.checkUnreserved(node.imported);
  18762. node.local = node.imported;
  18763. }
  18764. this.checkLValSimple(node.local, BIND_LEXICAL);
  18765. return this.finishNode(node, "ImportSpecifier")
  18766. };
  18767. pp$8.parseImportDefaultSpecifier = function() {
  18768. // import defaultObj, { x, y as z } from '...'
  18769. var node = this.startNode();
  18770. node.local = this.parseIdent();
  18771. this.checkLValSimple(node.local, BIND_LEXICAL);
  18772. return this.finishNode(node, "ImportDefaultSpecifier")
  18773. };
  18774. pp$8.parseImportNamespaceSpecifier = function() {
  18775. var node = this.startNode();
  18776. this.next();
  18777. this.expectContextual("as");
  18778. node.local = this.parseIdent();
  18779. this.checkLValSimple(node.local, BIND_LEXICAL);
  18780. return this.finishNode(node, "ImportNamespaceSpecifier")
  18781. };
  18782. pp$8.parseImportSpecifiers = function() {
  18783. var nodes = [], first = true;
  18784. if (this.type === types$1.name) {
  18785. nodes.push(this.parseImportDefaultSpecifier());
  18786. if (!this.eat(types$1.comma)) { return nodes }
  18787. }
  18788. if (this.type === types$1.star) {
  18789. nodes.push(this.parseImportNamespaceSpecifier());
  18790. return nodes
  18791. }
  18792. this.expect(types$1.braceL);
  18793. while (!this.eat(types$1.braceR)) {
  18794. if (!first) {
  18795. this.expect(types$1.comma);
  18796. if (this.afterTrailingComma(types$1.braceR)) { break }
  18797. } else { first = false; }
  18798. nodes.push(this.parseImportSpecifier());
  18799. }
  18800. return nodes
  18801. };
  18802. pp$8.parseModuleExportName = function() {
  18803. if (this.options.ecmaVersion >= 13 && this.type === types$1.string) {
  18804. var stringLiteral = this.parseLiteral(this.value);
  18805. if (loneSurrogate.test(stringLiteral.value)) {
  18806. this.raise(stringLiteral.start, "An export name cannot include a lone surrogate.");
  18807. }
  18808. return stringLiteral
  18809. }
  18810. return this.parseIdent(true)
  18811. };
  18812. // Set `ExpressionStatement#directive` property for directive prologues.
  18813. pp$8.adaptDirectivePrologue = function(statements) {
  18814. for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) {
  18815. statements[i].directive = statements[i].expression.raw.slice(1, -1);
  18816. }
  18817. };
  18818. pp$8.isDirectiveCandidate = function(statement) {
  18819. return (
  18820. this.options.ecmaVersion >= 5 &&
  18821. statement.type === "ExpressionStatement" &&
  18822. statement.expression.type === "Literal" &&
  18823. typeof statement.expression.value === "string" &&
  18824. // Reject parenthesized strings.
  18825. (this.input[statement.start] === "\"" || this.input[statement.start] === "'")
  18826. )
  18827. };
  18828. var pp$7 = Parser.prototype;
  18829. // Convert existing expression atom to assignable pattern
  18830. // if possible.
  18831. pp$7.toAssignable = function(node, isBinding, refDestructuringErrors) {
  18832. if (this.options.ecmaVersion >= 6 && node) {
  18833. switch (node.type) {
  18834. case "Identifier":
  18835. if (this.inAsync && node.name === "await")
  18836. { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); }
  18837. break
  18838. case "ObjectPattern":
  18839. case "ArrayPattern":
  18840. case "AssignmentPattern":
  18841. case "RestElement":
  18842. break
  18843. case "ObjectExpression":
  18844. node.type = "ObjectPattern";
  18845. if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  18846. for (var i = 0, list = node.properties; i < list.length; i += 1) {
  18847. var prop = list[i];
  18848. this.toAssignable(prop, isBinding);
  18849. // Early error:
  18850. // AssignmentRestProperty[Yield, Await] :
  18851. // `...` DestructuringAssignmentTarget[Yield, Await]
  18852. //
  18853. // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|.
  18854. if (
  18855. prop.type === "RestElement" &&
  18856. (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")
  18857. ) {
  18858. this.raise(prop.argument.start, "Unexpected token");
  18859. }
  18860. }
  18861. break
  18862. case "Property":
  18863. // AssignmentProperty has type === "Property"
  18864. if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); }
  18865. this.toAssignable(node.value, isBinding);
  18866. break
  18867. case "ArrayExpression":
  18868. node.type = "ArrayPattern";
  18869. if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  18870. this.toAssignableList(node.elements, isBinding);
  18871. break
  18872. case "SpreadElement":
  18873. node.type = "RestElement";
  18874. this.toAssignable(node.argument, isBinding);
  18875. if (node.argument.type === "AssignmentPattern")
  18876. { this.raise(node.argument.start, "Rest elements cannot have a default value"); }
  18877. break
  18878. case "AssignmentExpression":
  18879. if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); }
  18880. node.type = "AssignmentPattern";
  18881. delete node.operator;
  18882. this.toAssignable(node.left, isBinding);
  18883. break
  18884. case "ParenthesizedExpression":
  18885. this.toAssignable(node.expression, isBinding, refDestructuringErrors);
  18886. break
  18887. case "ChainExpression":
  18888. this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side");
  18889. break
  18890. case "MemberExpression":
  18891. if (!isBinding) { break }
  18892. default:
  18893. this.raise(node.start, "Assigning to rvalue");
  18894. }
  18895. } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  18896. return node
  18897. };
  18898. // Convert list of expression atoms to binding list.
  18899. pp$7.toAssignableList = function(exprList, isBinding) {
  18900. var end = exprList.length;
  18901. for (var i = 0; i < end; i++) {
  18902. var elt = exprList[i];
  18903. if (elt) { this.toAssignable(elt, isBinding); }
  18904. }
  18905. if (end) {
  18906. var last = exprList[end - 1];
  18907. if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier")
  18908. { this.unexpected(last.argument.start); }
  18909. }
  18910. return exprList
  18911. };
  18912. // Parses spread element.
  18913. pp$7.parseSpread = function(refDestructuringErrors) {
  18914. var node = this.startNode();
  18915. this.next();
  18916. node.argument = this.parseMaybeAssign(false, refDestructuringErrors);
  18917. return this.finishNode(node, "SpreadElement")
  18918. };
  18919. pp$7.parseRestBinding = function() {
  18920. var node = this.startNode();
  18921. this.next();
  18922. // RestElement inside of a function parameter must be an identifier
  18923. if (this.options.ecmaVersion === 6 && this.type !== types$1.name)
  18924. { this.unexpected(); }
  18925. node.argument = this.parseBindingAtom();
  18926. return this.finishNode(node, "RestElement")
  18927. };
  18928. // Parses lvalue (assignable) atom.
  18929. pp$7.parseBindingAtom = function() {
  18930. if (this.options.ecmaVersion >= 6) {
  18931. switch (this.type) {
  18932. case types$1.bracketL:
  18933. var node = this.startNode();
  18934. this.next();
  18935. node.elements = this.parseBindingList(types$1.bracketR, true, true);
  18936. return this.finishNode(node, "ArrayPattern")
  18937. case types$1.braceL:
  18938. return this.parseObj(true)
  18939. }
  18940. }
  18941. return this.parseIdent()
  18942. };
  18943. pp$7.parseBindingList = function(close, allowEmpty, allowTrailingComma, allowModifiers) {
  18944. var elts = [], first = true;
  18945. while (!this.eat(close)) {
  18946. if (first) { first = false; }
  18947. else { this.expect(types$1.comma); }
  18948. if (allowEmpty && this.type === types$1.comma) {
  18949. elts.push(null);
  18950. } else if (allowTrailingComma && this.afterTrailingComma(close)) {
  18951. break
  18952. } else if (this.type === types$1.ellipsis) {
  18953. var rest = this.parseRestBinding();
  18954. this.parseBindingListItem(rest);
  18955. elts.push(rest);
  18956. if (this.type === types$1.comma) { this.raiseRecoverable(this.start, "Comma is not permitted after the rest element"); }
  18957. this.expect(close);
  18958. break
  18959. } else {
  18960. elts.push(this.parseAssignableListItem(allowModifiers));
  18961. }
  18962. }
  18963. return elts
  18964. };
  18965. pp$7.parseAssignableListItem = function(allowModifiers) {
  18966. var elem = this.parseMaybeDefault(this.start, this.startLoc);
  18967. this.parseBindingListItem(elem);
  18968. return elem
  18969. };
  18970. pp$7.parseBindingListItem = function(param) {
  18971. return param
  18972. };
  18973. // Parses assignment pattern around given atom if possible.
  18974. pp$7.parseMaybeDefault = function(startPos, startLoc, left) {
  18975. left = left || this.parseBindingAtom();
  18976. if (this.options.ecmaVersion < 6 || !this.eat(types$1.eq)) { return left }
  18977. var node = this.startNodeAt(startPos, startLoc);
  18978. node.left = left;
  18979. node.right = this.parseMaybeAssign();
  18980. return this.finishNode(node, "AssignmentPattern")
  18981. };
  18982. // The following three functions all verify that a node is an lvalue —
  18983. // something that can be bound, or assigned to. In order to do so, they perform
  18984. // a variety of checks:
  18985. //
  18986. // - Check that none of the bound/assigned-to identifiers are reserved words.
  18987. // - Record name declarations for bindings in the appropriate scope.
  18988. // - Check duplicate argument names, if checkClashes is set.
  18989. //
  18990. // If a complex binding pattern is encountered (e.g., object and array
  18991. // destructuring), the entire pattern is recursively checked.
  18992. //
  18993. // There are three versions of checkLVal*() appropriate for different
  18994. // circumstances:
  18995. //
  18996. // - checkLValSimple() shall be used if the syntactic construct supports
  18997. // nothing other than identifiers and member expressions. Parenthesized
  18998. // expressions are also correctly handled. This is generally appropriate for
  18999. // constructs for which the spec says
  19000. //
  19001. // > It is a Syntax Error if AssignmentTargetType of [the production] is not
  19002. // > simple.
  19003. //
  19004. // It is also appropriate for checking if an identifier is valid and not
  19005. // defined elsewhere, like import declarations or function/class identifiers.
  19006. //
  19007. // Examples where this is used include:
  19008. // a += …;
  19009. // import a from '…';
  19010. // where a is the node to be checked.
  19011. //
  19012. // - checkLValPattern() shall be used if the syntactic construct supports
  19013. // anything checkLValSimple() supports, as well as object and array
  19014. // destructuring patterns. This is generally appropriate for constructs for
  19015. // which the spec says
  19016. //
  19017. // > It is a Syntax Error if [the production] is neither an ObjectLiteral nor
  19018. // > an ArrayLiteral and AssignmentTargetType of [the production] is not
  19019. // > simple.
  19020. //
  19021. // Examples where this is used include:
  19022. // (a = …);
  19023. // const a = …;
  19024. // try { … } catch (a) { … }
  19025. // where a is the node to be checked.
  19026. //
  19027. // - checkLValInnerPattern() shall be used if the syntactic construct supports
  19028. // anything checkLValPattern() supports, as well as default assignment
  19029. // patterns, rest elements, and other constructs that may appear within an
  19030. // object or array destructuring pattern.
  19031. //
  19032. // As a special case, function parameters also use checkLValInnerPattern(),
  19033. // as they also support defaults and rest constructs.
  19034. //
  19035. // These functions deliberately support both assignment and binding constructs,
  19036. // as the logic for both is exceedingly similar. If the node is the target of
  19037. // an assignment, then bindingType should be set to BIND_NONE. Otherwise, it
  19038. // should be set to the appropriate BIND_* constant, like BIND_VAR or
  19039. // BIND_LEXICAL.
  19040. //
  19041. // If the function is called with a non-BIND_NONE bindingType, then
  19042. // additionally a checkClashes object may be specified to allow checking for
  19043. // duplicate argument names. checkClashes is ignored if the provided construct
  19044. // is an assignment (i.e., bindingType is BIND_NONE).
  19045. pp$7.checkLValSimple = function(expr, bindingType, checkClashes) {
  19046. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  19047. var isBind = bindingType !== BIND_NONE;
  19048. switch (expr.type) {
  19049. case "Identifier":
  19050. if (this.strict && this.reservedWordsStrictBind.test(expr.name))
  19051. { this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); }
  19052. if (isBind) {
  19053. if (bindingType === BIND_LEXICAL && expr.name === "let")
  19054. { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); }
  19055. if (checkClashes) {
  19056. if (hasOwn(checkClashes, expr.name))
  19057. { this.raiseRecoverable(expr.start, "Argument name clash"); }
  19058. checkClashes[expr.name] = true;
  19059. }
  19060. if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); }
  19061. }
  19062. break
  19063. case "ChainExpression":
  19064. this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side");
  19065. break
  19066. case "MemberExpression":
  19067. if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); }
  19068. break
  19069. case "ParenthesizedExpression":
  19070. if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); }
  19071. return this.checkLValSimple(expr.expression, bindingType, checkClashes)
  19072. default:
  19073. this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue");
  19074. }
  19075. };
  19076. pp$7.checkLValPattern = function(expr, bindingType, checkClashes) {
  19077. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  19078. switch (expr.type) {
  19079. case "ObjectPattern":
  19080. for (var i = 0, list = expr.properties; i < list.length; i += 1) {
  19081. var prop = list[i];
  19082. this.checkLValInnerPattern(prop, bindingType, checkClashes);
  19083. }
  19084. break
  19085. case "ArrayPattern":
  19086. for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) {
  19087. var elem = list$1[i$1];
  19088. if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); }
  19089. }
  19090. break
  19091. default:
  19092. this.checkLValSimple(expr, bindingType, checkClashes);
  19093. }
  19094. };
  19095. pp$7.checkLValInnerPattern = function(expr, bindingType, checkClashes) {
  19096. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  19097. switch (expr.type) {
  19098. case "Property":
  19099. // AssignmentProperty has type === "Property"
  19100. this.checkLValInnerPattern(expr.value, bindingType, checkClashes);
  19101. break
  19102. case "AssignmentPattern":
  19103. this.checkLValPattern(expr.left, bindingType, checkClashes);
  19104. break
  19105. case "RestElement":
  19106. this.checkLValPattern(expr.argument, bindingType, checkClashes);
  19107. break
  19108. default:
  19109. this.checkLValPattern(expr, bindingType, checkClashes);
  19110. }
  19111. };
  19112. // The algorithm used to determine whether a regexp can appear at a
  19113. // given point in the program is loosely based on sweet.js' approach.
  19114. // See https://github.com/mozilla/sweet.js/wiki/design
  19115. var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) {
  19116. this.token = token;
  19117. this.isExpr = !!isExpr;
  19118. this.preserveSpace = !!preserveSpace;
  19119. this.override = override;
  19120. this.generator = !!generator;
  19121. };
  19122. var types = {
  19123. b_stat: new TokContext("{", false),
  19124. b_expr: new TokContext("{", true),
  19125. b_tmpl: new TokContext("${", false),
  19126. p_stat: new TokContext("(", false),
  19127. p_expr: new TokContext("(", true),
  19128. q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }),
  19129. f_stat: new TokContext("function", false),
  19130. f_expr: new TokContext("function", true),
  19131. f_expr_gen: new TokContext("function", true, false, null, true),
  19132. f_gen: new TokContext("function", false, false, null, true)
  19133. };
  19134. var pp$6 = Parser.prototype;
  19135. pp$6.initialContext = function() {
  19136. return [types.b_stat]
  19137. };
  19138. pp$6.curContext = function() {
  19139. return this.context[this.context.length - 1]
  19140. };
  19141. pp$6.braceIsBlock = function(prevType) {
  19142. var parent = this.curContext();
  19143. if (parent === types.f_expr || parent === types.f_stat)
  19144. { return true }
  19145. if (prevType === types$1.colon && (parent === types.b_stat || parent === types.b_expr))
  19146. { return !parent.isExpr }
  19147. // The check for `tt.name && exprAllowed` detects whether we are
  19148. // after a `yield` or `of` construct. See the `updateContext` for
  19149. // `tt.name`.
  19150. if (prevType === types$1._return || prevType === types$1.name && this.exprAllowed)
  19151. { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }
  19152. if (prevType === types$1._else || prevType === types$1.semi || prevType === types$1.eof || prevType === types$1.parenR || prevType === types$1.arrow)
  19153. { return true }
  19154. if (prevType === types$1.braceL)
  19155. { return parent === types.b_stat }
  19156. if (prevType === types$1._var || prevType === types$1._const || prevType === types$1.name)
  19157. { return false }
  19158. return !this.exprAllowed
  19159. };
  19160. pp$6.inGeneratorContext = function() {
  19161. for (var i = this.context.length - 1; i >= 1; i--) {
  19162. var context = this.context[i];
  19163. if (context.token === "function")
  19164. { return context.generator }
  19165. }
  19166. return false
  19167. };
  19168. pp$6.updateContext = function(prevType) {
  19169. var update, type = this.type;
  19170. if (type.keyword && prevType === types$1.dot)
  19171. { this.exprAllowed = false; }
  19172. else if (update = type.updateContext)
  19173. { update.call(this, prevType); }
  19174. else
  19175. { this.exprAllowed = type.beforeExpr; }
  19176. };
  19177. // Used to handle egde cases when token context could not be inferred correctly during tokenization phase
  19178. pp$6.overrideContext = function(tokenCtx) {
  19179. if (this.curContext() !== tokenCtx) {
  19180. this.context[this.context.length - 1] = tokenCtx;
  19181. }
  19182. };
  19183. // Token-specific context update code
  19184. types$1.parenR.updateContext = types$1.braceR.updateContext = function() {
  19185. if (this.context.length === 1) {
  19186. this.exprAllowed = true;
  19187. return
  19188. }
  19189. var out = this.context.pop();
  19190. if (out === types.b_stat && this.curContext().token === "function") {
  19191. out = this.context.pop();
  19192. }
  19193. this.exprAllowed = !out.isExpr;
  19194. };
  19195. types$1.braceL.updateContext = function(prevType) {
  19196. this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr);
  19197. this.exprAllowed = true;
  19198. };
  19199. types$1.dollarBraceL.updateContext = function() {
  19200. this.context.push(types.b_tmpl);
  19201. this.exprAllowed = true;
  19202. };
  19203. types$1.parenL.updateContext = function(prevType) {
  19204. var statementParens = prevType === types$1._if || prevType === types$1._for || prevType === types$1._with || prevType === types$1._while;
  19205. this.context.push(statementParens ? types.p_stat : types.p_expr);
  19206. this.exprAllowed = true;
  19207. };
  19208. types$1.incDec.updateContext = function() {
  19209. // tokExprAllowed stays unchanged
  19210. };
  19211. types$1._function.updateContext = types$1._class.updateContext = function(prevType) {
  19212. if (prevType.beforeExpr && prevType !== types$1._else &&
  19213. !(prevType === types$1.semi && this.curContext() !== types.p_stat) &&
  19214. !(prevType === types$1._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) &&
  19215. !((prevType === types$1.colon || prevType === types$1.braceL) && this.curContext() === types.b_stat))
  19216. { this.context.push(types.f_expr); }
  19217. else
  19218. { this.context.push(types.f_stat); }
  19219. this.exprAllowed = false;
  19220. };
  19221. types$1.backQuote.updateContext = function() {
  19222. if (this.curContext() === types.q_tmpl)
  19223. { this.context.pop(); }
  19224. else
  19225. { this.context.push(types.q_tmpl); }
  19226. this.exprAllowed = false;
  19227. };
  19228. types$1.star.updateContext = function(prevType) {
  19229. if (prevType === types$1._function) {
  19230. var index = this.context.length - 1;
  19231. if (this.context[index] === types.f_expr)
  19232. { this.context[index] = types.f_expr_gen; }
  19233. else
  19234. { this.context[index] = types.f_gen; }
  19235. }
  19236. this.exprAllowed = true;
  19237. };
  19238. types$1.name.updateContext = function(prevType) {
  19239. var allowed = false;
  19240. if (this.options.ecmaVersion >= 6 && prevType !== types$1.dot) {
  19241. if (this.value === "of" && !this.exprAllowed ||
  19242. this.value === "yield" && this.inGeneratorContext())
  19243. { allowed = true; }
  19244. }
  19245. this.exprAllowed = allowed;
  19246. };
  19247. // A recursive descent parser operates by defining functions for all
  19248. // syntactic elements, and recursively calling those, each function
  19249. // advancing the input stream and returning an AST node. Precedence
  19250. // of constructs (for example, the fact that `!x[1]` means `!(x[1])`
  19251. // instead of `(!x)[1]` is handled by the fact that the parser
  19252. // function that parses unary prefix operators is called first, and
  19253. // in turn calls the function that parses `[]` subscripts — that
  19254. // way, it'll receive the node for `x[1]` already parsed, and wraps
  19255. // *that* in the unary operator node.
  19256. //
  19257. // Acorn uses an [operator precedence parser][opp] to handle binary
  19258. // operator precedence, because it is much more compact than using
  19259. // the technique outlined above, which uses different, nesting
  19260. // functions to specify precedence, for all of the ten binary
  19261. // precedence levels that JavaScript defines.
  19262. //
  19263. // [opp]: http://en.wikipedia.org/wiki/Operator-precedence_parser
  19264. var pp$5 = Parser.prototype;
  19265. // Check if property name clashes with already added.
  19266. // Object/class getters and setters are not allowed to clash —
  19267. // either with each other or with an init property — and in
  19268. // strict mode, init properties are also not allowed to be repeated.
  19269. pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) {
  19270. if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement")
  19271. { return }
  19272. if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand))
  19273. { return }
  19274. var key = prop.key;
  19275. var name;
  19276. switch (key.type) {
  19277. case "Identifier": name = key.name; break
  19278. case "Literal": name = String(key.value); break
  19279. default: return
  19280. }
  19281. var kind = prop.kind;
  19282. if (this.options.ecmaVersion >= 6) {
  19283. if (name === "__proto__" && kind === "init") {
  19284. if (propHash.proto) {
  19285. if (refDestructuringErrors) {
  19286. if (refDestructuringErrors.doubleProto < 0) {
  19287. refDestructuringErrors.doubleProto = key.start;
  19288. }
  19289. } else {
  19290. this.raiseRecoverable(key.start, "Redefinition of __proto__ property");
  19291. }
  19292. }
  19293. propHash.proto = true;
  19294. }
  19295. return
  19296. }
  19297. name = "$" + name;
  19298. var other = propHash[name];
  19299. if (other) {
  19300. var redefinition;
  19301. if (kind === "init") {
  19302. redefinition = this.strict && other.init || other.get || other.set;
  19303. } else {
  19304. redefinition = other.init || other[kind];
  19305. }
  19306. if (redefinition)
  19307. { this.raiseRecoverable(key.start, "Redefinition of property"); }
  19308. } else {
  19309. other = propHash[name] = {
  19310. init: false,
  19311. get: false,
  19312. set: false
  19313. };
  19314. }
  19315. other[kind] = true;
  19316. };
  19317. // ### Expression parsing
  19318. // These nest, from the most general expression type at the top to
  19319. // 'atomic', nondivisible expression types at the bottom. Most of
  19320. // the functions will simply let the function(s) below them parse,
  19321. // and, *if* the syntactic construct they handle is present, wrap
  19322. // the AST node that the inner parser gave them in another node.
  19323. // Parse a full expression. The optional arguments are used to
  19324. // forbid the `in` operator (in for loops initalization expressions)
  19325. // and provide reference for storing '=' operator inside shorthand
  19326. // property assignment in contexts where both object expression
  19327. // and object pattern might appear (so it's possible to raise
  19328. // delayed syntax error at correct position).
  19329. pp$5.parseExpression = function(forInit, refDestructuringErrors) {
  19330. var startPos = this.start, startLoc = this.startLoc;
  19331. var expr = this.parseMaybeAssign(forInit, refDestructuringErrors);
  19332. if (this.type === types$1.comma) {
  19333. var node = this.startNodeAt(startPos, startLoc);
  19334. node.expressions = [expr];
  19335. while (this.eat(types$1.comma)) { node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors)); }
  19336. return this.finishNode(node, "SequenceExpression")
  19337. }
  19338. return expr
  19339. };
  19340. // Parse an assignment expression. This includes applications of
  19341. // operators like `+=`.
  19342. pp$5.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) {
  19343. if (this.isContextual("yield")) {
  19344. if (this.inGenerator) { return this.parseYield(forInit) }
  19345. // The tokenizer will assume an expression is allowed after
  19346. // `yield`, but this isn't that kind of yield
  19347. else { this.exprAllowed = false; }
  19348. }
  19349. var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldDoubleProto = -1;
  19350. if (refDestructuringErrors) {
  19351. oldParenAssign = refDestructuringErrors.parenthesizedAssign;
  19352. oldTrailingComma = refDestructuringErrors.trailingComma;
  19353. oldDoubleProto = refDestructuringErrors.doubleProto;
  19354. refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;
  19355. } else {
  19356. refDestructuringErrors = new DestructuringErrors;
  19357. ownDestructuringErrors = true;
  19358. }
  19359. var startPos = this.start, startLoc = this.startLoc;
  19360. if (this.type === types$1.parenL || this.type === types$1.name) {
  19361. this.potentialArrowAt = this.start;
  19362. this.potentialArrowInForAwait = forInit === "await";
  19363. }
  19364. var left = this.parseMaybeConditional(forInit, refDestructuringErrors);
  19365. if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); }
  19366. if (this.type.isAssign) {
  19367. var node = this.startNodeAt(startPos, startLoc);
  19368. node.operator = this.value;
  19369. if (this.type === types$1.eq)
  19370. { left = this.toAssignable(left, false, refDestructuringErrors); }
  19371. if (!ownDestructuringErrors) {
  19372. refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1;
  19373. }
  19374. if (refDestructuringErrors.shorthandAssign >= left.start)
  19375. { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly
  19376. if (this.type === types$1.eq)
  19377. { this.checkLValPattern(left); }
  19378. else
  19379. { this.checkLValSimple(left); }
  19380. node.left = left;
  19381. this.next();
  19382. node.right = this.parseMaybeAssign(forInit);
  19383. if (oldDoubleProto > -1) { refDestructuringErrors.doubleProto = oldDoubleProto; }
  19384. return this.finishNode(node, "AssignmentExpression")
  19385. } else {
  19386. if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); }
  19387. }
  19388. if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; }
  19389. if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; }
  19390. return left
  19391. };
  19392. // Parse a ternary conditional (`?:`) operator.
  19393. pp$5.parseMaybeConditional = function(forInit, refDestructuringErrors) {
  19394. var startPos = this.start, startLoc = this.startLoc;
  19395. var expr = this.parseExprOps(forInit, refDestructuringErrors);
  19396. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  19397. if (this.eat(types$1.question)) {
  19398. var node = this.startNodeAt(startPos, startLoc);
  19399. node.test = expr;
  19400. node.consequent = this.parseMaybeAssign();
  19401. this.expect(types$1.colon);
  19402. node.alternate = this.parseMaybeAssign(forInit);
  19403. return this.finishNode(node, "ConditionalExpression")
  19404. }
  19405. return expr
  19406. };
  19407. // Start the precedence parser.
  19408. pp$5.parseExprOps = function(forInit, refDestructuringErrors) {
  19409. var startPos = this.start, startLoc = this.startLoc;
  19410. var expr = this.parseMaybeUnary(refDestructuringErrors, false, false, forInit);
  19411. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  19412. return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit)
  19413. };
  19414. // Parse binary operators with the operator precedence parsing
  19415. // algorithm. `left` is the left-hand side of the operator.
  19416. // `minPrec` provides context that allows the function to stop and
  19417. // defer further parser to one of its callers when it encounters an
  19418. // operator that has a lower precedence than the set it is parsing.
  19419. pp$5.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) {
  19420. var prec = this.type.binop;
  19421. if (prec != null && (!forInit || this.type !== types$1._in)) {
  19422. if (prec > minPrec) {
  19423. var logical = this.type === types$1.logicalOR || this.type === types$1.logicalAND;
  19424. var coalesce = this.type === types$1.coalesce;
  19425. if (coalesce) {
  19426. // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions.
  19427. // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error.
  19428. prec = types$1.logicalAND.binop;
  19429. }
  19430. var op = this.value;
  19431. this.next();
  19432. var startPos = this.start, startLoc = this.startLoc;
  19433. var right = this.parseExprOp(this.parseMaybeUnary(null, false, false, forInit), startPos, startLoc, prec, forInit);
  19434. var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce);
  19435. if ((logical && this.type === types$1.coalesce) || (coalesce && (this.type === types$1.logicalOR || this.type === types$1.logicalAND))) {
  19436. this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses");
  19437. }
  19438. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit)
  19439. }
  19440. }
  19441. return left
  19442. };
  19443. pp$5.buildBinary = function(startPos, startLoc, left, right, op, logical) {
  19444. if (right.type === "PrivateIdentifier") { this.raise(right.start, "Private identifier can only be left side of binary expression"); }
  19445. var node = this.startNodeAt(startPos, startLoc);
  19446. node.left = left;
  19447. node.operator = op;
  19448. node.right = right;
  19449. return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression")
  19450. };
  19451. // Parse unary operators, both prefix and postfix.
  19452. pp$5.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec, forInit) {
  19453. var startPos = this.start, startLoc = this.startLoc, expr;
  19454. if (this.isContextual("await") && this.canAwait) {
  19455. expr = this.parseAwait(forInit);
  19456. sawUnary = true;
  19457. } else if (this.type.prefix) {
  19458. var node = this.startNode(), update = this.type === types$1.incDec;
  19459. node.operator = this.value;
  19460. node.prefix = true;
  19461. this.next();
  19462. node.argument = this.parseMaybeUnary(null, true, update, forInit);
  19463. this.checkExpressionErrors(refDestructuringErrors, true);
  19464. if (update) { this.checkLValSimple(node.argument); }
  19465. else if (this.strict && node.operator === "delete" &&
  19466. node.argument.type === "Identifier")
  19467. { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); }
  19468. else if (node.operator === "delete" && isPrivateFieldAccess(node.argument))
  19469. { this.raiseRecoverable(node.start, "Private fields can not be deleted"); }
  19470. else { sawUnary = true; }
  19471. expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
  19472. } else if (!sawUnary && this.type === types$1.privateId) {
  19473. if ((forInit || this.privateNameStack.length === 0) && this.options.checkPrivateFields) { this.unexpected(); }
  19474. expr = this.parsePrivateIdent();
  19475. // only could be private fields in 'in', such as #x in obj
  19476. if (this.type !== types$1._in) { this.unexpected(); }
  19477. } else {
  19478. expr = this.parseExprSubscripts(refDestructuringErrors, forInit);
  19479. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  19480. while (this.type.postfix && !this.canInsertSemicolon()) {
  19481. var node$1 = this.startNodeAt(startPos, startLoc);
  19482. node$1.operator = this.value;
  19483. node$1.prefix = false;
  19484. node$1.argument = expr;
  19485. this.checkLValSimple(expr);
  19486. this.next();
  19487. expr = this.finishNode(node$1, "UpdateExpression");
  19488. }
  19489. }
  19490. if (!incDec && this.eat(types$1.starstar)) {
  19491. if (sawUnary)
  19492. { this.unexpected(this.lastTokStart); }
  19493. else
  19494. { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false, false, forInit), "**", false) }
  19495. } else {
  19496. return expr
  19497. }
  19498. };
  19499. function isPrivateFieldAccess(node) {
  19500. return (
  19501. node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" ||
  19502. node.type === "ChainExpression" && isPrivateFieldAccess(node.expression)
  19503. )
  19504. }
  19505. // Parse call, dot, and `[]`-subscript expressions.
  19506. pp$5.parseExprSubscripts = function(refDestructuringErrors, forInit) {
  19507. var startPos = this.start, startLoc = this.startLoc;
  19508. var expr = this.parseExprAtom(refDestructuringErrors, forInit);
  19509. if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")")
  19510. { return expr }
  19511. var result = this.parseSubscripts(expr, startPos, startLoc, false, forInit);
  19512. if (refDestructuringErrors && result.type === "MemberExpression") {
  19513. if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; }
  19514. if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; }
  19515. if (refDestructuringErrors.trailingComma >= result.start) { refDestructuringErrors.trailingComma = -1; }
  19516. }
  19517. return result
  19518. };
  19519. pp$5.parseSubscripts = function(base, startPos, startLoc, noCalls, forInit) {
  19520. var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" &&
  19521. this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 &&
  19522. this.potentialArrowAt === base.start;
  19523. var optionalChained = false;
  19524. while (true) {
  19525. var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit);
  19526. if (element.optional) { optionalChained = true; }
  19527. if (element === base || element.type === "ArrowFunctionExpression") {
  19528. if (optionalChained) {
  19529. var chainNode = this.startNodeAt(startPos, startLoc);
  19530. chainNode.expression = element;
  19531. element = this.finishNode(chainNode, "ChainExpression");
  19532. }
  19533. return element
  19534. }
  19535. base = element;
  19536. }
  19537. };
  19538. pp$5.shouldParseAsyncArrow = function() {
  19539. return !this.canInsertSemicolon() && this.eat(types$1.arrow)
  19540. };
  19541. pp$5.parseSubscriptAsyncArrow = function(startPos, startLoc, exprList, forInit) {
  19542. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true, forInit)
  19543. };
  19544. pp$5.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) {
  19545. var optionalSupported = this.options.ecmaVersion >= 11;
  19546. var optional = optionalSupported && this.eat(types$1.questionDot);
  19547. if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); }
  19548. var computed = this.eat(types$1.bracketL);
  19549. if (computed || (optional && this.type !== types$1.parenL && this.type !== types$1.backQuote) || this.eat(types$1.dot)) {
  19550. var node = this.startNodeAt(startPos, startLoc);
  19551. node.object = base;
  19552. if (computed) {
  19553. node.property = this.parseExpression();
  19554. this.expect(types$1.bracketR);
  19555. } else if (this.type === types$1.privateId && base.type !== "Super") {
  19556. node.property = this.parsePrivateIdent();
  19557. } else {
  19558. node.property = this.parseIdent(this.options.allowReserved !== "never");
  19559. }
  19560. node.computed = !!computed;
  19561. if (optionalSupported) {
  19562. node.optional = optional;
  19563. }
  19564. base = this.finishNode(node, "MemberExpression");
  19565. } else if (!noCalls && this.eat(types$1.parenL)) {
  19566. var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  19567. this.yieldPos = 0;
  19568. this.awaitPos = 0;
  19569. this.awaitIdentPos = 0;
  19570. var exprList = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);
  19571. if (maybeAsyncArrow && !optional && this.shouldParseAsyncArrow()) {
  19572. this.checkPatternErrors(refDestructuringErrors, false);
  19573. this.checkYieldAwaitInDefaultParams();
  19574. if (this.awaitIdentPos > 0)
  19575. { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); }
  19576. this.yieldPos = oldYieldPos;
  19577. this.awaitPos = oldAwaitPos;
  19578. this.awaitIdentPos = oldAwaitIdentPos;
  19579. return this.parseSubscriptAsyncArrow(startPos, startLoc, exprList, forInit)
  19580. }
  19581. this.checkExpressionErrors(refDestructuringErrors, true);
  19582. this.yieldPos = oldYieldPos || this.yieldPos;
  19583. this.awaitPos = oldAwaitPos || this.awaitPos;
  19584. this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;
  19585. var node$1 = this.startNodeAt(startPos, startLoc);
  19586. node$1.callee = base;
  19587. node$1.arguments = exprList;
  19588. if (optionalSupported) {
  19589. node$1.optional = optional;
  19590. }
  19591. base = this.finishNode(node$1, "CallExpression");
  19592. } else if (this.type === types$1.backQuote) {
  19593. if (optional || optionalChained) {
  19594. this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions");
  19595. }
  19596. var node$2 = this.startNodeAt(startPos, startLoc);
  19597. node$2.tag = base;
  19598. node$2.quasi = this.parseTemplate({isTagged: true});
  19599. base = this.finishNode(node$2, "TaggedTemplateExpression");
  19600. }
  19601. return base
  19602. };
  19603. // Parse an atomic expression — either a single token that is an
  19604. // expression, an expression started by a keyword like `function` or
  19605. // `new`, or an expression wrapped in punctuation like `()`, `[]`,
  19606. // or `{}`.
  19607. pp$5.parseExprAtom = function(refDestructuringErrors, forInit, forNew) {
  19608. // If a division operator appears in an expression position, the
  19609. // tokenizer got confused, and we force it to read a regexp instead.
  19610. if (this.type === types$1.slash) { this.readRegexp(); }
  19611. var node, canBeArrow = this.potentialArrowAt === this.start;
  19612. switch (this.type) {
  19613. case types$1._super:
  19614. if (!this.allowSuper)
  19615. { this.raise(this.start, "'super' keyword outside a method"); }
  19616. node = this.startNode();
  19617. this.next();
  19618. if (this.type === types$1.parenL && !this.allowDirectSuper)
  19619. { this.raise(node.start, "super() call outside constructor of a subclass"); }
  19620. // The `super` keyword can appear at below:
  19621. // SuperProperty:
  19622. // super [ Expression ]
  19623. // super . IdentifierName
  19624. // SuperCall:
  19625. // super ( Arguments )
  19626. if (this.type !== types$1.dot && this.type !== types$1.bracketL && this.type !== types$1.parenL)
  19627. { this.unexpected(); }
  19628. return this.finishNode(node, "Super")
  19629. case types$1._this:
  19630. node = this.startNode();
  19631. this.next();
  19632. return this.finishNode(node, "ThisExpression")
  19633. case types$1.name:
  19634. var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc;
  19635. var id = this.parseIdent(false);
  19636. if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types$1._function)) {
  19637. this.overrideContext(types.f_expr);
  19638. return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true, forInit)
  19639. }
  19640. if (canBeArrow && !this.canInsertSemicolon()) {
  19641. if (this.eat(types$1.arrow))
  19642. { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false, forInit) }
  19643. if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types$1.name && !containsEsc &&
  19644. (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) {
  19645. id = this.parseIdent(false);
  19646. if (this.canInsertSemicolon() || !this.eat(types$1.arrow))
  19647. { this.unexpected(); }
  19648. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true, forInit)
  19649. }
  19650. }
  19651. return id
  19652. case types$1.regexp:
  19653. var value = this.value;
  19654. node = this.parseLiteral(value.value);
  19655. node.regex = {pattern: value.pattern, flags: value.flags};
  19656. return node
  19657. case types$1.num: case types$1.string:
  19658. return this.parseLiteral(this.value)
  19659. case types$1._null: case types$1._true: case types$1._false:
  19660. node = this.startNode();
  19661. node.value = this.type === types$1._null ? null : this.type === types$1._true;
  19662. node.raw = this.type.keyword;
  19663. this.next();
  19664. return this.finishNode(node, "Literal")
  19665. case types$1.parenL:
  19666. var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow, forInit);
  19667. if (refDestructuringErrors) {
  19668. if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))
  19669. { refDestructuringErrors.parenthesizedAssign = start; }
  19670. if (refDestructuringErrors.parenthesizedBind < 0)
  19671. { refDestructuringErrors.parenthesizedBind = start; }
  19672. }
  19673. return expr
  19674. case types$1.bracketL:
  19675. node = this.startNode();
  19676. this.next();
  19677. node.elements = this.parseExprList(types$1.bracketR, true, true, refDestructuringErrors);
  19678. return this.finishNode(node, "ArrayExpression")
  19679. case types$1.braceL:
  19680. this.overrideContext(types.b_expr);
  19681. return this.parseObj(false, refDestructuringErrors)
  19682. case types$1._function:
  19683. node = this.startNode();
  19684. this.next();
  19685. return this.parseFunction(node, 0)
  19686. case types$1._class:
  19687. return this.parseClass(this.startNode(), false)
  19688. case types$1._new:
  19689. return this.parseNew()
  19690. case types$1.backQuote:
  19691. return this.parseTemplate()
  19692. case types$1._import:
  19693. if (this.options.ecmaVersion >= 11) {
  19694. return this.parseExprImport(forNew)
  19695. } else {
  19696. return this.unexpected()
  19697. }
  19698. default:
  19699. return this.parseExprAtomDefault()
  19700. }
  19701. };
  19702. pp$5.parseExprAtomDefault = function() {
  19703. this.unexpected();
  19704. };
  19705. pp$5.parseExprImport = function(forNew) {
  19706. var node = this.startNode();
  19707. // Consume `import` as an identifier for `import.meta`.
  19708. // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`.
  19709. if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); }
  19710. var meta = this.parseIdent(true);
  19711. if (this.type === types$1.parenL && !forNew) {
  19712. return this.parseDynamicImport(node)
  19713. } else if (this.type === types$1.dot) {
  19714. node.meta = meta;
  19715. return this.parseImportMeta(node)
  19716. } else {
  19717. this.unexpected();
  19718. }
  19719. };
  19720. pp$5.parseDynamicImport = function(node) {
  19721. this.next(); // skip `(`
  19722. // Parse node.source.
  19723. node.source = this.parseMaybeAssign();
  19724. // Verify ending.
  19725. if (!this.eat(types$1.parenR)) {
  19726. var errorPos = this.start;
  19727. if (this.eat(types$1.comma) && this.eat(types$1.parenR)) {
  19728. this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()");
  19729. } else {
  19730. this.unexpected(errorPos);
  19731. }
  19732. }
  19733. return this.finishNode(node, "ImportExpression")
  19734. };
  19735. pp$5.parseImportMeta = function(node) {
  19736. this.next(); // skip `.`
  19737. var containsEsc = this.containsEsc;
  19738. node.property = this.parseIdent(true);
  19739. if (node.property.name !== "meta")
  19740. { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); }
  19741. if (containsEsc)
  19742. { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); }
  19743. if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere)
  19744. { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); }
  19745. return this.finishNode(node, "MetaProperty")
  19746. };
  19747. pp$5.parseLiteral = function(value) {
  19748. var node = this.startNode();
  19749. node.value = value;
  19750. node.raw = this.input.slice(this.start, this.end);
  19751. if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); }
  19752. this.next();
  19753. return this.finishNode(node, "Literal")
  19754. };
  19755. pp$5.parseParenExpression = function() {
  19756. this.expect(types$1.parenL);
  19757. var val = this.parseExpression();
  19758. this.expect(types$1.parenR);
  19759. return val
  19760. };
  19761. pp$5.shouldParseArrow = function(exprList) {
  19762. return !this.canInsertSemicolon()
  19763. };
  19764. pp$5.parseParenAndDistinguishExpression = function(canBeArrow, forInit) {
  19765. var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;
  19766. if (this.options.ecmaVersion >= 6) {
  19767. this.next();
  19768. var innerStartPos = this.start, innerStartLoc = this.startLoc;
  19769. var exprList = [], first = true, lastIsComma = false;
  19770. var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart;
  19771. this.yieldPos = 0;
  19772. this.awaitPos = 0;
  19773. // Do not save awaitIdentPos to allow checking awaits nested in parameters
  19774. while (this.type !== types$1.parenR) {
  19775. first ? first = false : this.expect(types$1.comma);
  19776. if (allowTrailingComma && this.afterTrailingComma(types$1.parenR, true)) {
  19777. lastIsComma = true;
  19778. break
  19779. } else if (this.type === types$1.ellipsis) {
  19780. spreadStart = this.start;
  19781. exprList.push(this.parseParenItem(this.parseRestBinding()));
  19782. if (this.type === types$1.comma) {
  19783. this.raiseRecoverable(
  19784. this.start,
  19785. "Comma is not permitted after the rest element"
  19786. );
  19787. }
  19788. break
  19789. } else {
  19790. exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));
  19791. }
  19792. }
  19793. var innerEndPos = this.lastTokEnd, innerEndLoc = this.lastTokEndLoc;
  19794. this.expect(types$1.parenR);
  19795. if (canBeArrow && this.shouldParseArrow(exprList) && this.eat(types$1.arrow)) {
  19796. this.checkPatternErrors(refDestructuringErrors, false);
  19797. this.checkYieldAwaitInDefaultParams();
  19798. this.yieldPos = oldYieldPos;
  19799. this.awaitPos = oldAwaitPos;
  19800. return this.parseParenArrowList(startPos, startLoc, exprList, forInit)
  19801. }
  19802. if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); }
  19803. if (spreadStart) { this.unexpected(spreadStart); }
  19804. this.checkExpressionErrors(refDestructuringErrors, true);
  19805. this.yieldPos = oldYieldPos || this.yieldPos;
  19806. this.awaitPos = oldAwaitPos || this.awaitPos;
  19807. if (exprList.length > 1) {
  19808. val = this.startNodeAt(innerStartPos, innerStartLoc);
  19809. val.expressions = exprList;
  19810. this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
  19811. } else {
  19812. val = exprList[0];
  19813. }
  19814. } else {
  19815. val = this.parseParenExpression();
  19816. }
  19817. if (this.options.preserveParens) {
  19818. var par = this.startNodeAt(startPos, startLoc);
  19819. par.expression = val;
  19820. return this.finishNode(par, "ParenthesizedExpression")
  19821. } else {
  19822. return val
  19823. }
  19824. };
  19825. pp$5.parseParenItem = function(item) {
  19826. return item
  19827. };
  19828. pp$5.parseParenArrowList = function(startPos, startLoc, exprList, forInit) {
  19829. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, false, forInit)
  19830. };
  19831. // New's precedence is slightly tricky. It must allow its argument to
  19832. // be a `[]` or dot subscript expression, but not a call — at least,
  19833. // not without wrapping it in parentheses. Thus, it uses the noCalls
  19834. // argument to parseSubscripts to prevent it from consuming the
  19835. // argument list.
  19836. var empty = [];
  19837. pp$5.parseNew = function() {
  19838. if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); }
  19839. var node = this.startNode();
  19840. var meta = this.parseIdent(true);
  19841. if (this.options.ecmaVersion >= 6 && this.eat(types$1.dot)) {
  19842. node.meta = meta;
  19843. var containsEsc = this.containsEsc;
  19844. node.property = this.parseIdent(true);
  19845. if (node.property.name !== "target")
  19846. { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); }
  19847. if (containsEsc)
  19848. { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); }
  19849. if (!this.allowNewDotTarget)
  19850. { this.raiseRecoverable(node.start, "'new.target' can only be used in functions and class static block"); }
  19851. return this.finishNode(node, "MetaProperty")
  19852. }
  19853. var startPos = this.start, startLoc = this.startLoc;
  19854. node.callee = this.parseSubscripts(this.parseExprAtom(null, false, true), startPos, startLoc, true, false);
  19855. if (this.eat(types$1.parenL)) { node.arguments = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false); }
  19856. else { node.arguments = empty; }
  19857. return this.finishNode(node, "NewExpression")
  19858. };
  19859. // Parse template expression.
  19860. pp$5.parseTemplateElement = function(ref) {
  19861. var isTagged = ref.isTagged;
  19862. var elem = this.startNode();
  19863. if (this.type === types$1.invalidTemplate) {
  19864. if (!isTagged) {
  19865. this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");
  19866. }
  19867. elem.value = {
  19868. raw: this.value,
  19869. cooked: null
  19870. };
  19871. } else {
  19872. elem.value = {
  19873. raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
  19874. cooked: this.value
  19875. };
  19876. }
  19877. this.next();
  19878. elem.tail = this.type === types$1.backQuote;
  19879. return this.finishNode(elem, "TemplateElement")
  19880. };
  19881. pp$5.parseTemplate = function(ref) {
  19882. if ( ref === void 0 ) ref = {};
  19883. var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false;
  19884. var node = this.startNode();
  19885. this.next();
  19886. node.expressions = [];
  19887. var curElt = this.parseTemplateElement({isTagged: isTagged});
  19888. node.quasis = [curElt];
  19889. while (!curElt.tail) {
  19890. if (this.type === types$1.eof) { this.raise(this.pos, "Unterminated template literal"); }
  19891. this.expect(types$1.dollarBraceL);
  19892. node.expressions.push(this.parseExpression());
  19893. this.expect(types$1.braceR);
  19894. node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged}));
  19895. }
  19896. this.next();
  19897. return this.finishNode(node, "TemplateLiteral")
  19898. };
  19899. pp$5.isAsyncProp = function(prop) {
  19900. return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" &&
  19901. (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)) &&
  19902. !lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
  19903. };
  19904. // Parse an object literal or binding pattern.
  19905. pp$5.parseObj = function(isPattern, refDestructuringErrors) {
  19906. var node = this.startNode(), first = true, propHash = {};
  19907. node.properties = [];
  19908. this.next();
  19909. while (!this.eat(types$1.braceR)) {
  19910. if (!first) {
  19911. this.expect(types$1.comma);
  19912. if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types$1.braceR)) { break }
  19913. } else { first = false; }
  19914. var prop = this.parseProperty(isPattern, refDestructuringErrors);
  19915. if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); }
  19916. node.properties.push(prop);
  19917. }
  19918. return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")
  19919. };
  19920. pp$5.parseProperty = function(isPattern, refDestructuringErrors) {
  19921. var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc;
  19922. if (this.options.ecmaVersion >= 9 && this.eat(types$1.ellipsis)) {
  19923. if (isPattern) {
  19924. prop.argument = this.parseIdent(false);
  19925. if (this.type === types$1.comma) {
  19926. this.raiseRecoverable(this.start, "Comma is not permitted after the rest element");
  19927. }
  19928. return this.finishNode(prop, "RestElement")
  19929. }
  19930. // Parse argument.
  19931. prop.argument = this.parseMaybeAssign(false, refDestructuringErrors);
  19932. // To disallow trailing comma via `this.toAssignable()`.
  19933. if (this.type === types$1.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {
  19934. refDestructuringErrors.trailingComma = this.start;
  19935. }
  19936. // Finish
  19937. return this.finishNode(prop, "SpreadElement")
  19938. }
  19939. if (this.options.ecmaVersion >= 6) {
  19940. prop.method = false;
  19941. prop.shorthand = false;
  19942. if (isPattern || refDestructuringErrors) {
  19943. startPos = this.start;
  19944. startLoc = this.startLoc;
  19945. }
  19946. if (!isPattern)
  19947. { isGenerator = this.eat(types$1.star); }
  19948. }
  19949. var containsEsc = this.containsEsc;
  19950. this.parsePropertyName(prop);
  19951. if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {
  19952. isAsync = true;
  19953. isGenerator = this.options.ecmaVersion >= 9 && this.eat(types$1.star);
  19954. this.parsePropertyName(prop);
  19955. } else {
  19956. isAsync = false;
  19957. }
  19958. this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc);
  19959. return this.finishNode(prop, "Property")
  19960. };
  19961. pp$5.parseGetterSetter = function(prop) {
  19962. prop.kind = prop.key.name;
  19963. this.parsePropertyName(prop);
  19964. prop.value = this.parseMethod(false);
  19965. var paramCount = prop.kind === "get" ? 0 : 1;
  19966. if (prop.value.params.length !== paramCount) {
  19967. var start = prop.value.start;
  19968. if (prop.kind === "get")
  19969. { this.raiseRecoverable(start, "getter should have no params"); }
  19970. else
  19971. { this.raiseRecoverable(start, "setter should have exactly one param"); }
  19972. } else {
  19973. if (prop.kind === "set" && prop.value.params[0].type === "RestElement")
  19974. { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); }
  19975. }
  19976. };
  19977. pp$5.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) {
  19978. if ((isGenerator || isAsync) && this.type === types$1.colon)
  19979. { this.unexpected(); }
  19980. if (this.eat(types$1.colon)) {
  19981. prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);
  19982. prop.kind = "init";
  19983. } else if (this.options.ecmaVersion >= 6 && this.type === types$1.parenL) {
  19984. if (isPattern) { this.unexpected(); }
  19985. prop.kind = "init";
  19986. prop.method = true;
  19987. prop.value = this.parseMethod(isGenerator, isAsync);
  19988. } else if (!isPattern && !containsEsc &&
  19989. this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" &&
  19990. (prop.key.name === "get" || prop.key.name === "set") &&
  19991. (this.type !== types$1.comma && this.type !== types$1.braceR && this.type !== types$1.eq)) {
  19992. if (isGenerator || isAsync) { this.unexpected(); }
  19993. this.parseGetterSetter(prop);
  19994. } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
  19995. if (isGenerator || isAsync) { this.unexpected(); }
  19996. this.checkUnreserved(prop.key);
  19997. if (prop.key.name === "await" && !this.awaitIdentPos)
  19998. { this.awaitIdentPos = startPos; }
  19999. prop.kind = "init";
  20000. if (isPattern) {
  20001. prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
  20002. } else if (this.type === types$1.eq && refDestructuringErrors) {
  20003. if (refDestructuringErrors.shorthandAssign < 0)
  20004. { refDestructuringErrors.shorthandAssign = this.start; }
  20005. prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
  20006. } else {
  20007. prop.value = this.copyNode(prop.key);
  20008. }
  20009. prop.shorthand = true;
  20010. } else { this.unexpected(); }
  20011. };
  20012. pp$5.parsePropertyName = function(prop) {
  20013. if (this.options.ecmaVersion >= 6) {
  20014. if (this.eat(types$1.bracketL)) {
  20015. prop.computed = true;
  20016. prop.key = this.parseMaybeAssign();
  20017. this.expect(types$1.bracketR);
  20018. return prop.key
  20019. } else {
  20020. prop.computed = false;
  20021. }
  20022. }
  20023. return prop.key = this.type === types$1.num || this.type === types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never")
  20024. };
  20025. // Initialize empty function node.
  20026. pp$5.initFunction = function(node) {
  20027. node.id = null;
  20028. if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; }
  20029. if (this.options.ecmaVersion >= 8) { node.async = false; }
  20030. };
  20031. // Parse object or class method.
  20032. pp$5.parseMethod = function(isGenerator, isAsync, allowDirectSuper) {
  20033. var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  20034. this.initFunction(node);
  20035. if (this.options.ecmaVersion >= 6)
  20036. { node.generator = isGenerator; }
  20037. if (this.options.ecmaVersion >= 8)
  20038. { node.async = !!isAsync; }
  20039. this.yieldPos = 0;
  20040. this.awaitPos = 0;
  20041. this.awaitIdentPos = 0;
  20042. this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
  20043. this.expect(types$1.parenL);
  20044. node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8);
  20045. this.checkYieldAwaitInDefaultParams();
  20046. this.parseFunctionBody(node, false, true, false);
  20047. this.yieldPos = oldYieldPos;
  20048. this.awaitPos = oldAwaitPos;
  20049. this.awaitIdentPos = oldAwaitIdentPos;
  20050. return this.finishNode(node, "FunctionExpression")
  20051. };
  20052. // Parse arrow function expression with given parameters.
  20053. pp$5.parseArrowExpression = function(node, params, isAsync, forInit) {
  20054. var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  20055. this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW);
  20056. this.initFunction(node);
  20057. if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; }
  20058. this.yieldPos = 0;
  20059. this.awaitPos = 0;
  20060. this.awaitIdentPos = 0;
  20061. node.params = this.toAssignableList(params, true);
  20062. this.parseFunctionBody(node, true, false, forInit);
  20063. this.yieldPos = oldYieldPos;
  20064. this.awaitPos = oldAwaitPos;
  20065. this.awaitIdentPos = oldAwaitIdentPos;
  20066. return this.finishNode(node, "ArrowFunctionExpression")
  20067. };
  20068. // Parse function body and check parameters.
  20069. pp$5.parseFunctionBody = function(node, isArrowFunction, isMethod, forInit) {
  20070. var isExpression = isArrowFunction && this.type !== types$1.braceL;
  20071. var oldStrict = this.strict, useStrict = false;
  20072. if (isExpression) {
  20073. node.body = this.parseMaybeAssign(forInit);
  20074. node.expression = true;
  20075. this.checkParams(node, false);
  20076. } else {
  20077. var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);
  20078. if (!oldStrict || nonSimple) {
  20079. useStrict = this.strictDirective(this.end);
  20080. // If this is a strict mode function, verify that argument names
  20081. // are not repeated, and it does not try to bind the words `eval`
  20082. // or `arguments`.
  20083. if (useStrict && nonSimple)
  20084. { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); }
  20085. }
  20086. // Start a new scope with regard to labels and the `inFunction`
  20087. // flag (restore them to their old value afterwards).
  20088. var oldLabels = this.labels;
  20089. this.labels = [];
  20090. if (useStrict) { this.strict = true; }
  20091. // Add the params to varDeclaredNames to ensure that an error is thrown
  20092. // if a let/const declaration in the function clashes with one of the params.
  20093. this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params));
  20094. // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'
  20095. if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); }
  20096. node.body = this.parseBlock(false, undefined, useStrict && !oldStrict);
  20097. node.expression = false;
  20098. this.adaptDirectivePrologue(node.body.body);
  20099. this.labels = oldLabels;
  20100. }
  20101. this.exitScope();
  20102. };
  20103. pp$5.isSimpleParamList = function(params) {
  20104. for (var i = 0, list = params; i < list.length; i += 1)
  20105. {
  20106. var param = list[i];
  20107. if (param.type !== "Identifier") { return false
  20108. } }
  20109. return true
  20110. };
  20111. // Checks function params for various disallowed patterns such as using "eval"
  20112. // or "arguments" and duplicate parameters.
  20113. pp$5.checkParams = function(node, allowDuplicates) {
  20114. var nameHash = Object.create(null);
  20115. for (var i = 0, list = node.params; i < list.length; i += 1)
  20116. {
  20117. var param = list[i];
  20118. this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash);
  20119. }
  20120. };
  20121. // Parses a comma-separated list of expressions, and returns them as
  20122. // an array. `close` is the token type that ends the list, and
  20123. // `allowEmpty` can be turned on to allow subsequent commas with
  20124. // nothing in between them to be parsed as `null` (which is needed
  20125. // for array literals).
  20126. pp$5.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
  20127. var elts = [], first = true;
  20128. while (!this.eat(close)) {
  20129. if (!first) {
  20130. this.expect(types$1.comma);
  20131. if (allowTrailingComma && this.afterTrailingComma(close)) { break }
  20132. } else { first = false; }
  20133. var elt = (void 0);
  20134. if (allowEmpty && this.type === types$1.comma)
  20135. { elt = null; }
  20136. else if (this.type === types$1.ellipsis) {
  20137. elt = this.parseSpread(refDestructuringErrors);
  20138. if (refDestructuringErrors && this.type === types$1.comma && refDestructuringErrors.trailingComma < 0)
  20139. { refDestructuringErrors.trailingComma = this.start; }
  20140. } else {
  20141. elt = this.parseMaybeAssign(false, refDestructuringErrors);
  20142. }
  20143. elts.push(elt);
  20144. }
  20145. return elts
  20146. };
  20147. pp$5.checkUnreserved = function(ref) {
  20148. var start = ref.start;
  20149. var end = ref.end;
  20150. var name = ref.name;
  20151. if (this.inGenerator && name === "yield")
  20152. { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); }
  20153. if (this.inAsync && name === "await")
  20154. { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); }
  20155. if (this.currentThisScope().inClassFieldInit && name === "arguments")
  20156. { this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer"); }
  20157. if (this.inClassStaticBlock && (name === "arguments" || name === "await"))
  20158. { this.raise(start, ("Cannot use " + name + " in class static initialization block")); }
  20159. if (this.keywords.test(name))
  20160. { this.raise(start, ("Unexpected keyword '" + name + "'")); }
  20161. if (this.options.ecmaVersion < 6 &&
  20162. this.input.slice(start, end).indexOf("\\") !== -1) { return }
  20163. var re = this.strict ? this.reservedWordsStrict : this.reservedWords;
  20164. if (re.test(name)) {
  20165. if (!this.inAsync && name === "await")
  20166. { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); }
  20167. this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved"));
  20168. }
  20169. };
  20170. // Parse the next token as an identifier. If `liberal` is true (used
  20171. // when parsing properties), it will also convert keywords into
  20172. // identifiers.
  20173. pp$5.parseIdent = function(liberal) {
  20174. var node = this.parseIdentNode();
  20175. this.next(!!liberal);
  20176. this.finishNode(node, "Identifier");
  20177. if (!liberal) {
  20178. this.checkUnreserved(node);
  20179. if (node.name === "await" && !this.awaitIdentPos)
  20180. { this.awaitIdentPos = node.start; }
  20181. }
  20182. return node
  20183. };
  20184. pp$5.parseIdentNode = function() {
  20185. var node = this.startNode();
  20186. if (this.type === types$1.name) {
  20187. node.name = this.value;
  20188. } else if (this.type.keyword) {
  20189. node.name = this.type.keyword;
  20190. // To fix https://github.com/acornjs/acorn/issues/575
  20191. // `class` and `function` keywords push new context into this.context.
  20192. // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name.
  20193. // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword
  20194. if ((node.name === "class" || node.name === "function") &&
  20195. (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {
  20196. this.context.pop();
  20197. }
  20198. } else {
  20199. this.unexpected();
  20200. }
  20201. return node
  20202. };
  20203. pp$5.parsePrivateIdent = function() {
  20204. var node = this.startNode();
  20205. if (this.type === types$1.privateId) {
  20206. node.name = this.value;
  20207. } else {
  20208. this.unexpected();
  20209. }
  20210. this.next();
  20211. this.finishNode(node, "PrivateIdentifier");
  20212. // For validating existence
  20213. if (this.options.checkPrivateFields) {
  20214. if (this.privateNameStack.length === 0) {
  20215. this.raise(node.start, ("Private field '#" + (node.name) + "' must be declared in an enclosing class"));
  20216. } else {
  20217. this.privateNameStack[this.privateNameStack.length - 1].used.push(node);
  20218. }
  20219. }
  20220. return node
  20221. };
  20222. // Parses yield expression inside generator.
  20223. pp$5.parseYield = function(forInit) {
  20224. if (!this.yieldPos) { this.yieldPos = this.start; }
  20225. var node = this.startNode();
  20226. this.next();
  20227. if (this.type === types$1.semi || this.canInsertSemicolon() || (this.type !== types$1.star && !this.type.startsExpr)) {
  20228. node.delegate = false;
  20229. node.argument = null;
  20230. } else {
  20231. node.delegate = this.eat(types$1.star);
  20232. node.argument = this.parseMaybeAssign(forInit);
  20233. }
  20234. return this.finishNode(node, "YieldExpression")
  20235. };
  20236. pp$5.parseAwait = function(forInit) {
  20237. if (!this.awaitPos) { this.awaitPos = this.start; }
  20238. var node = this.startNode();
  20239. this.next();
  20240. node.argument = this.parseMaybeUnary(null, true, false, forInit);
  20241. return this.finishNode(node, "AwaitExpression")
  20242. };
  20243. var pp$4 = Parser.prototype;
  20244. // This function is used to raise exceptions on parse errors. It
  20245. // takes an offset integer (into the current `input`) to indicate
  20246. // the location of the error, attaches the position to the end
  20247. // of the error message, and then raises a `SyntaxError` with that
  20248. // message.
  20249. pp$4.raise = function(pos, message) {
  20250. var loc = getLineInfo(this.input, pos);
  20251. message += " (" + loc.line + ":" + loc.column + ")";
  20252. var err = new SyntaxError(message);
  20253. err.pos = pos; err.loc = loc; err.raisedAt = this.pos;
  20254. throw err
  20255. };
  20256. pp$4.raiseRecoverable = pp$4.raise;
  20257. pp$4.curPosition = function() {
  20258. if (this.options.locations) {
  20259. return new Position(this.curLine, this.pos - this.lineStart)
  20260. }
  20261. };
  20262. var pp$3 = Parser.prototype;
  20263. var Scope = function Scope(flags) {
  20264. this.flags = flags;
  20265. // A list of var-declared names in the current lexical scope
  20266. this.var = [];
  20267. // A list of lexically-declared names in the current lexical scope
  20268. this.lexical = [];
  20269. // A list of lexically-declared FunctionDeclaration names in the current lexical scope
  20270. this.functions = [];
  20271. // A switch to disallow the identifier reference 'arguments'
  20272. this.inClassFieldInit = false;
  20273. };
  20274. // The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names.
  20275. pp$3.enterScope = function(flags) {
  20276. this.scopeStack.push(new Scope(flags));
  20277. };
  20278. pp$3.exitScope = function() {
  20279. this.scopeStack.pop();
  20280. };
  20281. // The spec says:
  20282. // > At the top level of a function, or script, function declarations are
  20283. // > treated like var declarations rather than like lexical declarations.
  20284. pp$3.treatFunctionsAsVarInScope = function(scope) {
  20285. return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP)
  20286. };
  20287. pp$3.declareName = function(name, bindingType, pos) {
  20288. var redeclared = false;
  20289. if (bindingType === BIND_LEXICAL) {
  20290. var scope = this.currentScope();
  20291. redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
  20292. scope.lexical.push(name);
  20293. if (this.inModule && (scope.flags & SCOPE_TOP))
  20294. { delete this.undefinedExports[name]; }
  20295. } else if (bindingType === BIND_SIMPLE_CATCH) {
  20296. var scope$1 = this.currentScope();
  20297. scope$1.lexical.push(name);
  20298. } else if (bindingType === BIND_FUNCTION) {
  20299. var scope$2 = this.currentScope();
  20300. if (this.treatFunctionsAsVar)
  20301. { redeclared = scope$2.lexical.indexOf(name) > -1; }
  20302. else
  20303. { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; }
  20304. scope$2.functions.push(name);
  20305. } else {
  20306. for (var i = this.scopeStack.length - 1; i >= 0; --i) {
  20307. var scope$3 = this.scopeStack[i];
  20308. if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) ||
  20309. !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) {
  20310. redeclared = true;
  20311. break
  20312. }
  20313. scope$3.var.push(name);
  20314. if (this.inModule && (scope$3.flags & SCOPE_TOP))
  20315. { delete this.undefinedExports[name]; }
  20316. if (scope$3.flags & SCOPE_VAR) { break }
  20317. }
  20318. }
  20319. if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); }
  20320. };
  20321. pp$3.checkLocalExport = function(id) {
  20322. // scope.functions must be empty as Module code is always strict.
  20323. if (this.scopeStack[0].lexical.indexOf(id.name) === -1 &&
  20324. this.scopeStack[0].var.indexOf(id.name) === -1) {
  20325. this.undefinedExports[id.name] = id;
  20326. }
  20327. };
  20328. pp$3.currentScope = function() {
  20329. return this.scopeStack[this.scopeStack.length - 1]
  20330. };
  20331. pp$3.currentVarScope = function() {
  20332. for (var i = this.scopeStack.length - 1;; i--) {
  20333. var scope = this.scopeStack[i];
  20334. if (scope.flags & SCOPE_VAR) { return scope }
  20335. }
  20336. };
  20337. // Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`.
  20338. pp$3.currentThisScope = function() {
  20339. for (var i = this.scopeStack.length - 1;; i--) {
  20340. var scope = this.scopeStack[i];
  20341. if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope }
  20342. }
  20343. };
  20344. var Node = function Node(parser, pos, loc) {
  20345. this.type = "";
  20346. this.start = pos;
  20347. this.end = 0;
  20348. if (parser.options.locations)
  20349. { this.loc = new SourceLocation(parser, loc); }
  20350. if (parser.options.directSourceFile)
  20351. { this.sourceFile = parser.options.directSourceFile; }
  20352. if (parser.options.ranges)
  20353. { this.range = [pos, 0]; }
  20354. };
  20355. // Start an AST node, attaching a start offset.
  20356. var pp$2 = Parser.prototype;
  20357. pp$2.startNode = function() {
  20358. return new Node(this, this.start, this.startLoc)
  20359. };
  20360. pp$2.startNodeAt = function(pos, loc) {
  20361. return new Node(this, pos, loc)
  20362. };
  20363. // Finish an AST node, adding `type` and `end` properties.
  20364. function finishNodeAt(node, type, pos, loc) {
  20365. node.type = type;
  20366. node.end = pos;
  20367. if (this.options.locations)
  20368. { node.loc.end = loc; }
  20369. if (this.options.ranges)
  20370. { node.range[1] = pos; }
  20371. return node
  20372. }
  20373. pp$2.finishNode = function(node, type) {
  20374. return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)
  20375. };
  20376. // Finish node at given position
  20377. pp$2.finishNodeAt = function(node, type, pos, loc) {
  20378. return finishNodeAt.call(this, node, type, pos, loc)
  20379. };
  20380. pp$2.copyNode = function(node) {
  20381. var newNode = new Node(this, node.start, this.startLoc);
  20382. for (var prop in node) { newNode[prop] = node[prop]; }
  20383. return newNode
  20384. };
  20385. // This file contains Unicode properties extracted from the ECMAScript specification.
  20386. // The lists are extracted like so:
  20387. // $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText)
  20388. // #table-binary-unicode-properties
  20389. 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";
  20390. var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic";
  20391. var ecma11BinaryProperties = ecma10BinaryProperties;
  20392. var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict";
  20393. var ecma13BinaryProperties = ecma12BinaryProperties;
  20394. var ecma14BinaryProperties = ecma13BinaryProperties;
  20395. var unicodeBinaryProperties = {
  20396. 9: ecma9BinaryProperties,
  20397. 10: ecma10BinaryProperties,
  20398. 11: ecma11BinaryProperties,
  20399. 12: ecma12BinaryProperties,
  20400. 13: ecma13BinaryProperties,
  20401. 14: ecma14BinaryProperties
  20402. };
  20403. // #table-binary-unicode-properties-of-strings
  20404. var ecma14BinaryPropertiesOfStrings = "Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji";
  20405. var unicodeBinaryPropertiesOfStrings = {
  20406. 9: "",
  20407. 10: "",
  20408. 11: "",
  20409. 12: "",
  20410. 13: "",
  20411. 14: ecma14BinaryPropertiesOfStrings
  20412. };
  20413. // #table-unicode-general-category-values
  20414. 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";
  20415. // #table-unicode-script-values
  20416. 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";
  20417. var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";
  20418. var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";
  20419. var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";
  20420. var ecma13ScriptValues = ecma12ScriptValues + " Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith";
  20421. var ecma14ScriptValues = ecma13ScriptValues + " Hrkt Katakana_Or_Hiragana Kawi Nag_Mundari Nagm Unknown Zzzz";
  20422. var unicodeScriptValues = {
  20423. 9: ecma9ScriptValues,
  20424. 10: ecma10ScriptValues,
  20425. 11: ecma11ScriptValues,
  20426. 12: ecma12ScriptValues,
  20427. 13: ecma13ScriptValues,
  20428. 14: ecma14ScriptValues
  20429. };
  20430. var data = {};
  20431. function buildUnicodeData(ecmaVersion) {
  20432. var d = data[ecmaVersion] = {
  20433. binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues),
  20434. binaryOfStrings: wordsRegexp(unicodeBinaryPropertiesOfStrings[ecmaVersion]),
  20435. nonBinary: {
  20436. General_Category: wordsRegexp(unicodeGeneralCategoryValues),
  20437. Script: wordsRegexp(unicodeScriptValues[ecmaVersion])
  20438. }
  20439. };
  20440. d.nonBinary.Script_Extensions = d.nonBinary.Script;
  20441. d.nonBinary.gc = d.nonBinary.General_Category;
  20442. d.nonBinary.sc = d.nonBinary.Script;
  20443. d.nonBinary.scx = d.nonBinary.Script_Extensions;
  20444. }
  20445. for (var i = 0, list = [9, 10, 11, 12, 13, 14]; i < list.length; i += 1) {
  20446. var ecmaVersion = list[i];
  20447. buildUnicodeData(ecmaVersion);
  20448. }
  20449. var pp$1 = Parser.prototype;
  20450. var RegExpValidationState = function RegExpValidationState(parser) {
  20451. this.parser = parser;
  20452. this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : "") + (parser.options.ecmaVersion >= 15 ? "v" : "");
  20453. this.unicodeProperties = data[parser.options.ecmaVersion >= 14 ? 14 : parser.options.ecmaVersion];
  20454. this.source = "";
  20455. this.flags = "";
  20456. this.start = 0;
  20457. this.switchU = false;
  20458. this.switchV = false;
  20459. this.switchN = false;
  20460. this.pos = 0;
  20461. this.lastIntValue = 0;
  20462. this.lastStringValue = "";
  20463. this.lastAssertionIsQuantifiable = false;
  20464. this.numCapturingParens = 0;
  20465. this.maxBackReference = 0;
  20466. this.groupNames = [];
  20467. this.backReferenceNames = [];
  20468. };
  20469. RegExpValidationState.prototype.reset = function reset (start, pattern, flags) {
  20470. var unicodeSets = flags.indexOf("v") !== -1;
  20471. var unicode = flags.indexOf("u") !== -1;
  20472. this.start = start | 0;
  20473. this.source = pattern + "";
  20474. this.flags = flags;
  20475. if (unicodeSets && this.parser.options.ecmaVersion >= 15) {
  20476. this.switchU = true;
  20477. this.switchV = true;
  20478. this.switchN = true;
  20479. } else {
  20480. this.switchU = unicode && this.parser.options.ecmaVersion >= 6;
  20481. this.switchV = false;
  20482. this.switchN = unicode && this.parser.options.ecmaVersion >= 9;
  20483. }
  20484. };
  20485. RegExpValidationState.prototype.raise = function raise (message) {
  20486. this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message));
  20487. };
  20488. // If u flag is given, this returns the code point at the index (it combines a surrogate pair).
  20489. // Otherwise, this returns the code unit of the index (can be a part of a surrogate pair).
  20490. RegExpValidationState.prototype.at = function at (i, forceU) {
  20491. if ( forceU === void 0 ) forceU = false;
  20492. var s = this.source;
  20493. var l = s.length;
  20494. if (i >= l) {
  20495. return -1
  20496. }
  20497. var c = s.charCodeAt(i);
  20498. if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) {
  20499. return c
  20500. }
  20501. var next = s.charCodeAt(i + 1);
  20502. return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c
  20503. };
  20504. RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) {
  20505. if ( forceU === void 0 ) forceU = false;
  20506. var s = this.source;
  20507. var l = s.length;
  20508. if (i >= l) {
  20509. return l
  20510. }
  20511. var c = s.charCodeAt(i), next;
  20512. if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l ||
  20513. (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) {
  20514. return i + 1
  20515. }
  20516. return i + 2
  20517. };
  20518. RegExpValidationState.prototype.current = function current (forceU) {
  20519. if ( forceU === void 0 ) forceU = false;
  20520. return this.at(this.pos, forceU)
  20521. };
  20522. RegExpValidationState.prototype.lookahead = function lookahead (forceU) {
  20523. if ( forceU === void 0 ) forceU = false;
  20524. return this.at(this.nextIndex(this.pos, forceU), forceU)
  20525. };
  20526. RegExpValidationState.prototype.advance = function advance (forceU) {
  20527. if ( forceU === void 0 ) forceU = false;
  20528. this.pos = this.nextIndex(this.pos, forceU);
  20529. };
  20530. RegExpValidationState.prototype.eat = function eat (ch, forceU) {
  20531. if ( forceU === void 0 ) forceU = false;
  20532. if (this.current(forceU) === ch) {
  20533. this.advance(forceU);
  20534. return true
  20535. }
  20536. return false
  20537. };
  20538. RegExpValidationState.prototype.eatChars = function eatChars (chs, forceU) {
  20539. if ( forceU === void 0 ) forceU = false;
  20540. var pos = this.pos;
  20541. for (var i = 0, list = chs; i < list.length; i += 1) {
  20542. var ch = list[i];
  20543. var current = this.at(pos, forceU);
  20544. if (current === -1 || current !== ch) {
  20545. return false
  20546. }
  20547. pos = this.nextIndex(pos, forceU);
  20548. }
  20549. this.pos = pos;
  20550. return true
  20551. };
  20552. /**
  20553. * Validate the flags part of a given RegExpLiteral.
  20554. *
  20555. * @param {RegExpValidationState} state The state to validate RegExp.
  20556. * @returns {void}
  20557. */
  20558. pp$1.validateRegExpFlags = function(state) {
  20559. var validFlags = state.validFlags;
  20560. var flags = state.flags;
  20561. var u = false;
  20562. var v = false;
  20563. for (var i = 0; i < flags.length; i++) {
  20564. var flag = flags.charAt(i);
  20565. if (validFlags.indexOf(flag) === -1) {
  20566. this.raise(state.start, "Invalid regular expression flag");
  20567. }
  20568. if (flags.indexOf(flag, i + 1) > -1) {
  20569. this.raise(state.start, "Duplicate regular expression flag");
  20570. }
  20571. if (flag === "u") { u = true; }
  20572. if (flag === "v") { v = true; }
  20573. }
  20574. if (this.options.ecmaVersion >= 15 && u && v) {
  20575. this.raise(state.start, "Invalid regular expression flag");
  20576. }
  20577. };
  20578. /**
  20579. * Validate the pattern part of a given RegExpLiteral.
  20580. *
  20581. * @param {RegExpValidationState} state The state to validate RegExp.
  20582. * @returns {void}
  20583. */
  20584. pp$1.validateRegExpPattern = function(state) {
  20585. this.regexp_pattern(state);
  20586. // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of
  20587. // parsing contains a |GroupName|, reparse with the goal symbol
  20588. // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError*
  20589. // exception if _P_ did not conform to the grammar, if any elements of _P_
  20590. // were not matched by the parse, or if any Early Error conditions exist.
  20591. if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) {
  20592. state.switchN = true;
  20593. this.regexp_pattern(state);
  20594. }
  20595. };
  20596. // https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern
  20597. pp$1.regexp_pattern = function(state) {
  20598. state.pos = 0;
  20599. state.lastIntValue = 0;
  20600. state.lastStringValue = "";
  20601. state.lastAssertionIsQuantifiable = false;
  20602. state.numCapturingParens = 0;
  20603. state.maxBackReference = 0;
  20604. state.groupNames.length = 0;
  20605. state.backReferenceNames.length = 0;
  20606. this.regexp_disjunction(state);
  20607. if (state.pos !== state.source.length) {
  20608. // Make the same messages as V8.
  20609. if (state.eat(0x29 /* ) */)) {
  20610. state.raise("Unmatched ')'");
  20611. }
  20612. if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) {
  20613. state.raise("Lone quantifier brackets");
  20614. }
  20615. }
  20616. if (state.maxBackReference > state.numCapturingParens) {
  20617. state.raise("Invalid escape");
  20618. }
  20619. for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) {
  20620. var name = list[i];
  20621. if (state.groupNames.indexOf(name) === -1) {
  20622. state.raise("Invalid named capture referenced");
  20623. }
  20624. }
  20625. };
  20626. // https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction
  20627. pp$1.regexp_disjunction = function(state) {
  20628. this.regexp_alternative(state);
  20629. while (state.eat(0x7C /* | */)) {
  20630. this.regexp_alternative(state);
  20631. }
  20632. // Make the same message as V8.
  20633. if (this.regexp_eatQuantifier(state, true)) {
  20634. state.raise("Nothing to repeat");
  20635. }
  20636. if (state.eat(0x7B /* { */)) {
  20637. state.raise("Lone quantifier brackets");
  20638. }
  20639. };
  20640. // https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative
  20641. pp$1.regexp_alternative = function(state) {
  20642. while (state.pos < state.source.length && this.regexp_eatTerm(state))
  20643. { }
  20644. };
  20645. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term
  20646. pp$1.regexp_eatTerm = function(state) {
  20647. if (this.regexp_eatAssertion(state)) {
  20648. // Handle `QuantifiableAssertion Quantifier` alternative.
  20649. // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion
  20650. // is a QuantifiableAssertion.
  20651. if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) {
  20652. // Make the same message as V8.
  20653. if (state.switchU) {
  20654. state.raise("Invalid quantifier");
  20655. }
  20656. }
  20657. return true
  20658. }
  20659. if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) {
  20660. this.regexp_eatQuantifier(state);
  20661. return true
  20662. }
  20663. return false
  20664. };
  20665. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion
  20666. pp$1.regexp_eatAssertion = function(state) {
  20667. var start = state.pos;
  20668. state.lastAssertionIsQuantifiable = false;
  20669. // ^, $
  20670. if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) {
  20671. return true
  20672. }
  20673. // \b \B
  20674. if (state.eat(0x5C /* \ */)) {
  20675. if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) {
  20676. return true
  20677. }
  20678. state.pos = start;
  20679. }
  20680. // Lookahead / Lookbehind
  20681. if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) {
  20682. var lookbehind = false;
  20683. if (this.options.ecmaVersion >= 9) {
  20684. lookbehind = state.eat(0x3C /* < */);
  20685. }
  20686. if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) {
  20687. this.regexp_disjunction(state);
  20688. if (!state.eat(0x29 /* ) */)) {
  20689. state.raise("Unterminated group");
  20690. }
  20691. state.lastAssertionIsQuantifiable = !lookbehind;
  20692. return true
  20693. }
  20694. }
  20695. state.pos = start;
  20696. return false
  20697. };
  20698. // https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier
  20699. pp$1.regexp_eatQuantifier = function(state, noError) {
  20700. if ( noError === void 0 ) noError = false;
  20701. if (this.regexp_eatQuantifierPrefix(state, noError)) {
  20702. state.eat(0x3F /* ? */);
  20703. return true
  20704. }
  20705. return false
  20706. };
  20707. // https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix
  20708. pp$1.regexp_eatQuantifierPrefix = function(state, noError) {
  20709. return (
  20710. state.eat(0x2A /* * */) ||
  20711. state.eat(0x2B /* + */) ||
  20712. state.eat(0x3F /* ? */) ||
  20713. this.regexp_eatBracedQuantifier(state, noError)
  20714. )
  20715. };
  20716. pp$1.regexp_eatBracedQuantifier = function(state, noError) {
  20717. var start = state.pos;
  20718. if (state.eat(0x7B /* { */)) {
  20719. var min = 0, max = -1;
  20720. if (this.regexp_eatDecimalDigits(state)) {
  20721. min = state.lastIntValue;
  20722. if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) {
  20723. max = state.lastIntValue;
  20724. }
  20725. if (state.eat(0x7D /* } */)) {
  20726. // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term
  20727. if (max !== -1 && max < min && !noError) {
  20728. state.raise("numbers out of order in {} quantifier");
  20729. }
  20730. return true
  20731. }
  20732. }
  20733. if (state.switchU && !noError) {
  20734. state.raise("Incomplete quantifier");
  20735. }
  20736. state.pos = start;
  20737. }
  20738. return false
  20739. };
  20740. // https://www.ecma-international.org/ecma-262/8.0/#prod-Atom
  20741. pp$1.regexp_eatAtom = function(state) {
  20742. return (
  20743. this.regexp_eatPatternCharacters(state) ||
  20744. state.eat(0x2E /* . */) ||
  20745. this.regexp_eatReverseSolidusAtomEscape(state) ||
  20746. this.regexp_eatCharacterClass(state) ||
  20747. this.regexp_eatUncapturingGroup(state) ||
  20748. this.regexp_eatCapturingGroup(state)
  20749. )
  20750. };
  20751. pp$1.regexp_eatReverseSolidusAtomEscape = function(state) {
  20752. var start = state.pos;
  20753. if (state.eat(0x5C /* \ */)) {
  20754. if (this.regexp_eatAtomEscape(state)) {
  20755. return true
  20756. }
  20757. state.pos = start;
  20758. }
  20759. return false
  20760. };
  20761. pp$1.regexp_eatUncapturingGroup = function(state) {
  20762. var start = state.pos;
  20763. if (state.eat(0x28 /* ( */)) {
  20764. if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) {
  20765. this.regexp_disjunction(state);
  20766. if (state.eat(0x29 /* ) */)) {
  20767. return true
  20768. }
  20769. state.raise("Unterminated group");
  20770. }
  20771. state.pos = start;
  20772. }
  20773. return false
  20774. };
  20775. pp$1.regexp_eatCapturingGroup = function(state) {
  20776. if (state.eat(0x28 /* ( */)) {
  20777. if (this.options.ecmaVersion >= 9) {
  20778. this.regexp_groupSpecifier(state);
  20779. } else if (state.current() === 0x3F /* ? */) {
  20780. state.raise("Invalid group");
  20781. }
  20782. this.regexp_disjunction(state);
  20783. if (state.eat(0x29 /* ) */)) {
  20784. state.numCapturingParens += 1;
  20785. return true
  20786. }
  20787. state.raise("Unterminated group");
  20788. }
  20789. return false
  20790. };
  20791. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom
  20792. pp$1.regexp_eatExtendedAtom = function(state) {
  20793. return (
  20794. state.eat(0x2E /* . */) ||
  20795. this.regexp_eatReverseSolidusAtomEscape(state) ||
  20796. this.regexp_eatCharacterClass(state) ||
  20797. this.regexp_eatUncapturingGroup(state) ||
  20798. this.regexp_eatCapturingGroup(state) ||
  20799. this.regexp_eatInvalidBracedQuantifier(state) ||
  20800. this.regexp_eatExtendedPatternCharacter(state)
  20801. )
  20802. };
  20803. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier
  20804. pp$1.regexp_eatInvalidBracedQuantifier = function(state) {
  20805. if (this.regexp_eatBracedQuantifier(state, true)) {
  20806. state.raise("Nothing to repeat");
  20807. }
  20808. return false
  20809. };
  20810. // https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter
  20811. pp$1.regexp_eatSyntaxCharacter = function(state) {
  20812. var ch = state.current();
  20813. if (isSyntaxCharacter(ch)) {
  20814. state.lastIntValue = ch;
  20815. state.advance();
  20816. return true
  20817. }
  20818. return false
  20819. };
  20820. function isSyntaxCharacter(ch) {
  20821. return (
  20822. ch === 0x24 /* $ */ ||
  20823. ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ ||
  20824. ch === 0x2E /* . */ ||
  20825. ch === 0x3F /* ? */ ||
  20826. ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ ||
  20827. ch >= 0x7B /* { */ && ch <= 0x7D /* } */
  20828. )
  20829. }
  20830. // https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter
  20831. // But eat eager.
  20832. pp$1.regexp_eatPatternCharacters = function(state) {
  20833. var start = state.pos;
  20834. var ch = 0;
  20835. while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) {
  20836. state.advance();
  20837. }
  20838. return state.pos !== start
  20839. };
  20840. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter
  20841. pp$1.regexp_eatExtendedPatternCharacter = function(state) {
  20842. var ch = state.current();
  20843. if (
  20844. ch !== -1 &&
  20845. ch !== 0x24 /* $ */ &&
  20846. !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) &&
  20847. ch !== 0x2E /* . */ &&
  20848. ch !== 0x3F /* ? */ &&
  20849. ch !== 0x5B /* [ */ &&
  20850. ch !== 0x5E /* ^ */ &&
  20851. ch !== 0x7C /* | */
  20852. ) {
  20853. state.advance();
  20854. return true
  20855. }
  20856. return false
  20857. };
  20858. // GroupSpecifier ::
  20859. // [empty]
  20860. // `?` GroupName
  20861. pp$1.regexp_groupSpecifier = function(state) {
  20862. if (state.eat(0x3F /* ? */)) {
  20863. if (this.regexp_eatGroupName(state)) {
  20864. if (state.groupNames.indexOf(state.lastStringValue) !== -1) {
  20865. state.raise("Duplicate capture group name");
  20866. }
  20867. state.groupNames.push(state.lastStringValue);
  20868. return
  20869. }
  20870. state.raise("Invalid group");
  20871. }
  20872. };
  20873. // GroupName ::
  20874. // `<` RegExpIdentifierName `>`
  20875. // Note: this updates `state.lastStringValue` property with the eaten name.
  20876. pp$1.regexp_eatGroupName = function(state) {
  20877. state.lastStringValue = "";
  20878. if (state.eat(0x3C /* < */)) {
  20879. if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) {
  20880. return true
  20881. }
  20882. state.raise("Invalid capture group name");
  20883. }
  20884. return false
  20885. };
  20886. // RegExpIdentifierName ::
  20887. // RegExpIdentifierStart
  20888. // RegExpIdentifierName RegExpIdentifierPart
  20889. // Note: this updates `state.lastStringValue` property with the eaten name.
  20890. pp$1.regexp_eatRegExpIdentifierName = function(state) {
  20891. state.lastStringValue = "";
  20892. if (this.regexp_eatRegExpIdentifierStart(state)) {
  20893. state.lastStringValue += codePointToString(state.lastIntValue);
  20894. while (this.regexp_eatRegExpIdentifierPart(state)) {
  20895. state.lastStringValue += codePointToString(state.lastIntValue);
  20896. }
  20897. return true
  20898. }
  20899. return false
  20900. };
  20901. // RegExpIdentifierStart ::
  20902. // UnicodeIDStart
  20903. // `$`
  20904. // `_`
  20905. // `\` RegExpUnicodeEscapeSequence[+U]
  20906. pp$1.regexp_eatRegExpIdentifierStart = function(state) {
  20907. var start = state.pos;
  20908. var forceU = this.options.ecmaVersion >= 11;
  20909. var ch = state.current(forceU);
  20910. state.advance(forceU);
  20911. if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
  20912. ch = state.lastIntValue;
  20913. }
  20914. if (isRegExpIdentifierStart(ch)) {
  20915. state.lastIntValue = ch;
  20916. return true
  20917. }
  20918. state.pos = start;
  20919. return false
  20920. };
  20921. function isRegExpIdentifierStart(ch) {
  20922. return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */
  20923. }
  20924. // RegExpIdentifierPart ::
  20925. // UnicodeIDContinue
  20926. // `$`
  20927. // `_`
  20928. // `\` RegExpUnicodeEscapeSequence[+U]
  20929. // <ZWNJ>
  20930. // <ZWJ>
  20931. pp$1.regexp_eatRegExpIdentifierPart = function(state) {
  20932. var start = state.pos;
  20933. var forceU = this.options.ecmaVersion >= 11;
  20934. var ch = state.current(forceU);
  20935. state.advance(forceU);
  20936. if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
  20937. ch = state.lastIntValue;
  20938. }
  20939. if (isRegExpIdentifierPart(ch)) {
  20940. state.lastIntValue = ch;
  20941. return true
  20942. }
  20943. state.pos = start;
  20944. return false
  20945. };
  20946. function isRegExpIdentifierPart(ch) {
  20947. return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* <ZWNJ> */ || ch === 0x200D /* <ZWJ> */
  20948. }
  20949. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape
  20950. pp$1.regexp_eatAtomEscape = function(state) {
  20951. if (
  20952. this.regexp_eatBackReference(state) ||
  20953. this.regexp_eatCharacterClassEscape(state) ||
  20954. this.regexp_eatCharacterEscape(state) ||
  20955. (state.switchN && this.regexp_eatKGroupName(state))
  20956. ) {
  20957. return true
  20958. }
  20959. if (state.switchU) {
  20960. // Make the same message as V8.
  20961. if (state.current() === 0x63 /* c */) {
  20962. state.raise("Invalid unicode escape");
  20963. }
  20964. state.raise("Invalid escape");
  20965. }
  20966. return false
  20967. };
  20968. pp$1.regexp_eatBackReference = function(state) {
  20969. var start = state.pos;
  20970. if (this.regexp_eatDecimalEscape(state)) {
  20971. var n = state.lastIntValue;
  20972. if (state.switchU) {
  20973. // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape
  20974. if (n > state.maxBackReference) {
  20975. state.maxBackReference = n;
  20976. }
  20977. return true
  20978. }
  20979. if (n <= state.numCapturingParens) {
  20980. return true
  20981. }
  20982. state.pos = start;
  20983. }
  20984. return false
  20985. };
  20986. pp$1.regexp_eatKGroupName = function(state) {
  20987. if (state.eat(0x6B /* k */)) {
  20988. if (this.regexp_eatGroupName(state)) {
  20989. state.backReferenceNames.push(state.lastStringValue);
  20990. return true
  20991. }
  20992. state.raise("Invalid named reference");
  20993. }
  20994. return false
  20995. };
  20996. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape
  20997. pp$1.regexp_eatCharacterEscape = function(state) {
  20998. return (
  20999. this.regexp_eatControlEscape(state) ||
  21000. this.regexp_eatCControlLetter(state) ||
  21001. this.regexp_eatZero(state) ||
  21002. this.regexp_eatHexEscapeSequence(state) ||
  21003. this.regexp_eatRegExpUnicodeEscapeSequence(state, false) ||
  21004. (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) ||
  21005. this.regexp_eatIdentityEscape(state)
  21006. )
  21007. };
  21008. pp$1.regexp_eatCControlLetter = function(state) {
  21009. var start = state.pos;
  21010. if (state.eat(0x63 /* c */)) {
  21011. if (this.regexp_eatControlLetter(state)) {
  21012. return true
  21013. }
  21014. state.pos = start;
  21015. }
  21016. return false
  21017. };
  21018. pp$1.regexp_eatZero = function(state) {
  21019. if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) {
  21020. state.lastIntValue = 0;
  21021. state.advance();
  21022. return true
  21023. }
  21024. return false
  21025. };
  21026. // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape
  21027. pp$1.regexp_eatControlEscape = function(state) {
  21028. var ch = state.current();
  21029. if (ch === 0x74 /* t */) {
  21030. state.lastIntValue = 0x09; /* \t */
  21031. state.advance();
  21032. return true
  21033. }
  21034. if (ch === 0x6E /* n */) {
  21035. state.lastIntValue = 0x0A; /* \n */
  21036. state.advance();
  21037. return true
  21038. }
  21039. if (ch === 0x76 /* v */) {
  21040. state.lastIntValue = 0x0B; /* \v */
  21041. state.advance();
  21042. return true
  21043. }
  21044. if (ch === 0x66 /* f */) {
  21045. state.lastIntValue = 0x0C; /* \f */
  21046. state.advance();
  21047. return true
  21048. }
  21049. if (ch === 0x72 /* r */) {
  21050. state.lastIntValue = 0x0D; /* \r */
  21051. state.advance();
  21052. return true
  21053. }
  21054. return false
  21055. };
  21056. // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter
  21057. pp$1.regexp_eatControlLetter = function(state) {
  21058. var ch = state.current();
  21059. if (isControlLetter(ch)) {
  21060. state.lastIntValue = ch % 0x20;
  21061. state.advance();
  21062. return true
  21063. }
  21064. return false
  21065. };
  21066. function isControlLetter(ch) {
  21067. return (
  21068. (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) ||
  21069. (ch >= 0x61 /* a */ && ch <= 0x7A /* z */)
  21070. )
  21071. }
  21072. // https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence
  21073. pp$1.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) {
  21074. if ( forceU === void 0 ) forceU = false;
  21075. var start = state.pos;
  21076. var switchU = forceU || state.switchU;
  21077. if (state.eat(0x75 /* u */)) {
  21078. if (this.regexp_eatFixedHexDigits(state, 4)) {
  21079. var lead = state.lastIntValue;
  21080. if (switchU && lead >= 0xD800 && lead <= 0xDBFF) {
  21081. var leadSurrogateEnd = state.pos;
  21082. if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) {
  21083. var trail = state.lastIntValue;
  21084. if (trail >= 0xDC00 && trail <= 0xDFFF) {
  21085. state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
  21086. return true
  21087. }
  21088. }
  21089. state.pos = leadSurrogateEnd;
  21090. state.lastIntValue = lead;
  21091. }
  21092. return true
  21093. }
  21094. if (
  21095. switchU &&
  21096. state.eat(0x7B /* { */) &&
  21097. this.regexp_eatHexDigits(state) &&
  21098. state.eat(0x7D /* } */) &&
  21099. isValidUnicode(state.lastIntValue)
  21100. ) {
  21101. return true
  21102. }
  21103. if (switchU) {
  21104. state.raise("Invalid unicode escape");
  21105. }
  21106. state.pos = start;
  21107. }
  21108. return false
  21109. };
  21110. function isValidUnicode(ch) {
  21111. return ch >= 0 && ch <= 0x10FFFF
  21112. }
  21113. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape
  21114. pp$1.regexp_eatIdentityEscape = function(state) {
  21115. if (state.switchU) {
  21116. if (this.regexp_eatSyntaxCharacter(state)) {
  21117. return true
  21118. }
  21119. if (state.eat(0x2F /* / */)) {
  21120. state.lastIntValue = 0x2F; /* / */
  21121. return true
  21122. }
  21123. return false
  21124. }
  21125. var ch = state.current();
  21126. if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) {
  21127. state.lastIntValue = ch;
  21128. state.advance();
  21129. return true
  21130. }
  21131. return false
  21132. };
  21133. // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape
  21134. pp$1.regexp_eatDecimalEscape = function(state) {
  21135. state.lastIntValue = 0;
  21136. var ch = state.current();
  21137. if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) {
  21138. do {
  21139. state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
  21140. state.advance();
  21141. } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */)
  21142. return true
  21143. }
  21144. return false
  21145. };
  21146. // Return values used by character set parsing methods, needed to
  21147. // forbid negation of sets that can match strings.
  21148. var CharSetNone = 0; // Nothing parsed
  21149. var CharSetOk = 1; // Construct parsed, cannot contain strings
  21150. var CharSetString = 2; // Construct parsed, can contain strings
  21151. // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape
  21152. pp$1.regexp_eatCharacterClassEscape = function(state) {
  21153. var ch = state.current();
  21154. if (isCharacterClassEscape(ch)) {
  21155. state.lastIntValue = -1;
  21156. state.advance();
  21157. return CharSetOk
  21158. }
  21159. var negate = false;
  21160. if (
  21161. state.switchU &&
  21162. this.options.ecmaVersion >= 9 &&
  21163. ((negate = ch === 0x50 /* P */) || ch === 0x70 /* p */)
  21164. ) {
  21165. state.lastIntValue = -1;
  21166. state.advance();
  21167. var result;
  21168. if (
  21169. state.eat(0x7B /* { */) &&
  21170. (result = this.regexp_eatUnicodePropertyValueExpression(state)) &&
  21171. state.eat(0x7D /* } */)
  21172. ) {
  21173. if (negate && result === CharSetString) { state.raise("Invalid property name"); }
  21174. return result
  21175. }
  21176. state.raise("Invalid property name");
  21177. }
  21178. return CharSetNone
  21179. };
  21180. function isCharacterClassEscape(ch) {
  21181. return (
  21182. ch === 0x64 /* d */ ||
  21183. ch === 0x44 /* D */ ||
  21184. ch === 0x73 /* s */ ||
  21185. ch === 0x53 /* S */ ||
  21186. ch === 0x77 /* w */ ||
  21187. ch === 0x57 /* W */
  21188. )
  21189. }
  21190. // UnicodePropertyValueExpression ::
  21191. // UnicodePropertyName `=` UnicodePropertyValue
  21192. // LoneUnicodePropertyNameOrValue
  21193. pp$1.regexp_eatUnicodePropertyValueExpression = function(state) {
  21194. var start = state.pos;
  21195. // UnicodePropertyName `=` UnicodePropertyValue
  21196. if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) {
  21197. var name = state.lastStringValue;
  21198. if (this.regexp_eatUnicodePropertyValue(state)) {
  21199. var value = state.lastStringValue;
  21200. this.regexp_validateUnicodePropertyNameAndValue(state, name, value);
  21201. return CharSetOk
  21202. }
  21203. }
  21204. state.pos = start;
  21205. // LoneUnicodePropertyNameOrValue
  21206. if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {
  21207. var nameOrValue = state.lastStringValue;
  21208. return this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue)
  21209. }
  21210. return CharSetNone
  21211. };
  21212. pp$1.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {
  21213. if (!hasOwn(state.unicodeProperties.nonBinary, name))
  21214. { state.raise("Invalid property name"); }
  21215. if (!state.unicodeProperties.nonBinary[name].test(value))
  21216. { state.raise("Invalid property value"); }
  21217. };
  21218. pp$1.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) {
  21219. if (state.unicodeProperties.binary.test(nameOrValue)) { return CharSetOk }
  21220. if (state.switchV && state.unicodeProperties.binaryOfStrings.test(nameOrValue)) { return CharSetString }
  21221. state.raise("Invalid property name");
  21222. };
  21223. // UnicodePropertyName ::
  21224. // UnicodePropertyNameCharacters
  21225. pp$1.regexp_eatUnicodePropertyName = function(state) {
  21226. var ch = 0;
  21227. state.lastStringValue = "";
  21228. while (isUnicodePropertyNameCharacter(ch = state.current())) {
  21229. state.lastStringValue += codePointToString(ch);
  21230. state.advance();
  21231. }
  21232. return state.lastStringValue !== ""
  21233. };
  21234. function isUnicodePropertyNameCharacter(ch) {
  21235. return isControlLetter(ch) || ch === 0x5F /* _ */
  21236. }
  21237. // UnicodePropertyValue ::
  21238. // UnicodePropertyValueCharacters
  21239. pp$1.regexp_eatUnicodePropertyValue = function(state) {
  21240. var ch = 0;
  21241. state.lastStringValue = "";
  21242. while (isUnicodePropertyValueCharacter(ch = state.current())) {
  21243. state.lastStringValue += codePointToString(ch);
  21244. state.advance();
  21245. }
  21246. return state.lastStringValue !== ""
  21247. };
  21248. function isUnicodePropertyValueCharacter(ch) {
  21249. return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch)
  21250. }
  21251. // LoneUnicodePropertyNameOrValue ::
  21252. // UnicodePropertyValueCharacters
  21253. pp$1.regexp_eatLoneUnicodePropertyNameOrValue = function(state) {
  21254. return this.regexp_eatUnicodePropertyValue(state)
  21255. };
  21256. // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass
  21257. pp$1.regexp_eatCharacterClass = function(state) {
  21258. if (state.eat(0x5B /* [ */)) {
  21259. var negate = state.eat(0x5E /* ^ */);
  21260. var result = this.regexp_classContents(state);
  21261. if (!state.eat(0x5D /* ] */))
  21262. { state.raise("Unterminated character class"); }
  21263. if (negate && result === CharSetString)
  21264. { state.raise("Negated character class may contain strings"); }
  21265. return true
  21266. }
  21267. return false
  21268. };
  21269. // https://tc39.es/ecma262/#prod-ClassContents
  21270. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges
  21271. pp$1.regexp_classContents = function(state) {
  21272. if (state.current() === 0x5D /* ] */) { return CharSetOk }
  21273. if (state.switchV) { return this.regexp_classSetExpression(state) }
  21274. this.regexp_nonEmptyClassRanges(state);
  21275. return CharSetOk
  21276. };
  21277. // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges
  21278. // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash
  21279. pp$1.regexp_nonEmptyClassRanges = function(state) {
  21280. while (this.regexp_eatClassAtom(state)) {
  21281. var left = state.lastIntValue;
  21282. if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) {
  21283. var right = state.lastIntValue;
  21284. if (state.switchU && (left === -1 || right === -1)) {
  21285. state.raise("Invalid character class");
  21286. }
  21287. if (left !== -1 && right !== -1 && left > right) {
  21288. state.raise("Range out of order in character class");
  21289. }
  21290. }
  21291. }
  21292. };
  21293. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom
  21294. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash
  21295. pp$1.regexp_eatClassAtom = function(state) {
  21296. var start = state.pos;
  21297. if (state.eat(0x5C /* \ */)) {
  21298. if (this.regexp_eatClassEscape(state)) {
  21299. return true
  21300. }
  21301. if (state.switchU) {
  21302. // Make the same message as V8.
  21303. var ch$1 = state.current();
  21304. if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) {
  21305. state.raise("Invalid class escape");
  21306. }
  21307. state.raise("Invalid escape");
  21308. }
  21309. state.pos = start;
  21310. }
  21311. var ch = state.current();
  21312. if (ch !== 0x5D /* ] */) {
  21313. state.lastIntValue = ch;
  21314. state.advance();
  21315. return true
  21316. }
  21317. return false
  21318. };
  21319. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape
  21320. pp$1.regexp_eatClassEscape = function(state) {
  21321. var start = state.pos;
  21322. if (state.eat(0x62 /* b */)) {
  21323. state.lastIntValue = 0x08; /* <BS> */
  21324. return true
  21325. }
  21326. if (state.switchU && state.eat(0x2D /* - */)) {
  21327. state.lastIntValue = 0x2D; /* - */
  21328. return true
  21329. }
  21330. if (!state.switchU && state.eat(0x63 /* c */)) {
  21331. if (this.regexp_eatClassControlLetter(state)) {
  21332. return true
  21333. }
  21334. state.pos = start;
  21335. }
  21336. return (
  21337. this.regexp_eatCharacterClassEscape(state) ||
  21338. this.regexp_eatCharacterEscape(state)
  21339. )
  21340. };
  21341. // https://tc39.es/ecma262/#prod-ClassSetExpression
  21342. // https://tc39.es/ecma262/#prod-ClassUnion
  21343. // https://tc39.es/ecma262/#prod-ClassIntersection
  21344. // https://tc39.es/ecma262/#prod-ClassSubtraction
  21345. pp$1.regexp_classSetExpression = function(state) {
  21346. var result = CharSetOk, subResult;
  21347. if (this.regexp_eatClassSetRange(state)) ; else if (subResult = this.regexp_eatClassSetOperand(state)) {
  21348. if (subResult === CharSetString) { result = CharSetString; }
  21349. // https://tc39.es/ecma262/#prod-ClassIntersection
  21350. var start = state.pos;
  21351. while (state.eatChars([0x26, 0x26] /* && */)) {
  21352. if (
  21353. state.current() !== 0x26 /* & */ &&
  21354. (subResult = this.regexp_eatClassSetOperand(state))
  21355. ) {
  21356. if (subResult !== CharSetString) { result = CharSetOk; }
  21357. continue
  21358. }
  21359. state.raise("Invalid character in character class");
  21360. }
  21361. if (start !== state.pos) { return result }
  21362. // https://tc39.es/ecma262/#prod-ClassSubtraction
  21363. while (state.eatChars([0x2D, 0x2D] /* -- */)) {
  21364. if (this.regexp_eatClassSetOperand(state)) { continue }
  21365. state.raise("Invalid character in character class");
  21366. }
  21367. if (start !== state.pos) { return result }
  21368. } else {
  21369. state.raise("Invalid character in character class");
  21370. }
  21371. // https://tc39.es/ecma262/#prod-ClassUnion
  21372. for (;;) {
  21373. if (this.regexp_eatClassSetRange(state)) { continue }
  21374. subResult = this.regexp_eatClassSetOperand(state);
  21375. if (!subResult) { return result }
  21376. if (subResult === CharSetString) { result = CharSetString; }
  21377. }
  21378. };
  21379. // https://tc39.es/ecma262/#prod-ClassSetRange
  21380. pp$1.regexp_eatClassSetRange = function(state) {
  21381. var start = state.pos;
  21382. if (this.regexp_eatClassSetCharacter(state)) {
  21383. var left = state.lastIntValue;
  21384. if (state.eat(0x2D /* - */) && this.regexp_eatClassSetCharacter(state)) {
  21385. var right = state.lastIntValue;
  21386. if (left !== -1 && right !== -1 && left > right) {
  21387. state.raise("Range out of order in character class");
  21388. }
  21389. return true
  21390. }
  21391. state.pos = start;
  21392. }
  21393. return false
  21394. };
  21395. // https://tc39.es/ecma262/#prod-ClassSetOperand
  21396. pp$1.regexp_eatClassSetOperand = function(state) {
  21397. if (this.regexp_eatClassSetCharacter(state)) { return CharSetOk }
  21398. return this.regexp_eatClassStringDisjunction(state) || this.regexp_eatNestedClass(state)
  21399. };
  21400. // https://tc39.es/ecma262/#prod-NestedClass
  21401. pp$1.regexp_eatNestedClass = function(state) {
  21402. var start = state.pos;
  21403. if (state.eat(0x5B /* [ */)) {
  21404. var negate = state.eat(0x5E /* ^ */);
  21405. var result = this.regexp_classContents(state);
  21406. if (state.eat(0x5D /* ] */)) {
  21407. if (negate && result === CharSetString) {
  21408. state.raise("Negated character class may contain strings");
  21409. }
  21410. return result
  21411. }
  21412. state.pos = start;
  21413. }
  21414. if (state.eat(0x5C /* \ */)) {
  21415. var result$1 = this.regexp_eatCharacterClassEscape(state);
  21416. if (result$1) {
  21417. return result$1
  21418. }
  21419. state.pos = start;
  21420. }
  21421. return null
  21422. };
  21423. // https://tc39.es/ecma262/#prod-ClassStringDisjunction
  21424. pp$1.regexp_eatClassStringDisjunction = function(state) {
  21425. var start = state.pos;
  21426. if (state.eatChars([0x5C, 0x71] /* \q */)) {
  21427. if (state.eat(0x7B /* { */)) {
  21428. var result = this.regexp_classStringDisjunctionContents(state);
  21429. if (state.eat(0x7D /* } */)) {
  21430. return result
  21431. }
  21432. } else {
  21433. // Make the same message as V8.
  21434. state.raise("Invalid escape");
  21435. }
  21436. state.pos = start;
  21437. }
  21438. return null
  21439. };
  21440. // https://tc39.es/ecma262/#prod-ClassStringDisjunctionContents
  21441. pp$1.regexp_classStringDisjunctionContents = function(state) {
  21442. var result = this.regexp_classString(state);
  21443. while (state.eat(0x7C /* | */)) {
  21444. if (this.regexp_classString(state) === CharSetString) { result = CharSetString; }
  21445. }
  21446. return result
  21447. };
  21448. // https://tc39.es/ecma262/#prod-ClassString
  21449. // https://tc39.es/ecma262/#prod-NonEmptyClassString
  21450. pp$1.regexp_classString = function(state) {
  21451. var count = 0;
  21452. while (this.regexp_eatClassSetCharacter(state)) { count++; }
  21453. return count === 1 ? CharSetOk : CharSetString
  21454. };
  21455. // https://tc39.es/ecma262/#prod-ClassSetCharacter
  21456. pp$1.regexp_eatClassSetCharacter = function(state) {
  21457. var start = state.pos;
  21458. if (state.eat(0x5C /* \ */)) {
  21459. if (
  21460. this.regexp_eatCharacterEscape(state) ||
  21461. this.regexp_eatClassSetReservedPunctuator(state)
  21462. ) {
  21463. return true
  21464. }
  21465. if (state.eat(0x62 /* b */)) {
  21466. state.lastIntValue = 0x08; /* <BS> */
  21467. return true
  21468. }
  21469. state.pos = start;
  21470. return false
  21471. }
  21472. var ch = state.current();
  21473. if (ch < 0 || ch === state.lookahead() && isClassSetReservedDoublePunctuatorCharacter(ch)) { return false }
  21474. if (isClassSetSyntaxCharacter(ch)) { return false }
  21475. state.advance();
  21476. state.lastIntValue = ch;
  21477. return true
  21478. };
  21479. // https://tc39.es/ecma262/#prod-ClassSetReservedDoublePunctuator
  21480. function isClassSetReservedDoublePunctuatorCharacter(ch) {
  21481. return (
  21482. ch === 0x21 /* ! */ ||
  21483. ch >= 0x23 /* # */ && ch <= 0x26 /* & */ ||
  21484. ch >= 0x2A /* * */ && ch <= 0x2C /* , */ ||
  21485. ch === 0x2E /* . */ ||
  21486. ch >= 0x3A /* : */ && ch <= 0x40 /* @ */ ||
  21487. ch === 0x5E /* ^ */ ||
  21488. ch === 0x60 /* ` */ ||
  21489. ch === 0x7E /* ~ */
  21490. )
  21491. }
  21492. // https://tc39.es/ecma262/#prod-ClassSetSyntaxCharacter
  21493. function isClassSetSyntaxCharacter(ch) {
  21494. return (
  21495. ch === 0x28 /* ( */ ||
  21496. ch === 0x29 /* ) */ ||
  21497. ch === 0x2D /* - */ ||
  21498. ch === 0x2F /* / */ ||
  21499. ch >= 0x5B /* [ */ && ch <= 0x5D /* ] */ ||
  21500. ch >= 0x7B /* { */ && ch <= 0x7D /* } */
  21501. )
  21502. }
  21503. // https://tc39.es/ecma262/#prod-ClassSetReservedPunctuator
  21504. pp$1.regexp_eatClassSetReservedPunctuator = function(state) {
  21505. var ch = state.current();
  21506. if (isClassSetReservedPunctuator(ch)) {
  21507. state.lastIntValue = ch;
  21508. state.advance();
  21509. return true
  21510. }
  21511. return false
  21512. };
  21513. // https://tc39.es/ecma262/#prod-ClassSetReservedPunctuator
  21514. function isClassSetReservedPunctuator(ch) {
  21515. return (
  21516. ch === 0x21 /* ! */ ||
  21517. ch === 0x23 /* # */ ||
  21518. ch === 0x25 /* % */ ||
  21519. ch === 0x26 /* & */ ||
  21520. ch === 0x2C /* , */ ||
  21521. ch === 0x2D /* - */ ||
  21522. ch >= 0x3A /* : */ && ch <= 0x3E /* > */ ||
  21523. ch === 0x40 /* @ */ ||
  21524. ch === 0x60 /* ` */ ||
  21525. ch === 0x7E /* ~ */
  21526. )
  21527. }
  21528. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter
  21529. pp$1.regexp_eatClassControlLetter = function(state) {
  21530. var ch = state.current();
  21531. if (isDecimalDigit(ch) || ch === 0x5F /* _ */) {
  21532. state.lastIntValue = ch % 0x20;
  21533. state.advance();
  21534. return true
  21535. }
  21536. return false
  21537. };
  21538. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
  21539. pp$1.regexp_eatHexEscapeSequence = function(state) {
  21540. var start = state.pos;
  21541. if (state.eat(0x78 /* x */)) {
  21542. if (this.regexp_eatFixedHexDigits(state, 2)) {
  21543. return true
  21544. }
  21545. if (state.switchU) {
  21546. state.raise("Invalid escape");
  21547. }
  21548. state.pos = start;
  21549. }
  21550. return false
  21551. };
  21552. // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits
  21553. pp$1.regexp_eatDecimalDigits = function(state) {
  21554. var start = state.pos;
  21555. var ch = 0;
  21556. state.lastIntValue = 0;
  21557. while (isDecimalDigit(ch = state.current())) {
  21558. state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
  21559. state.advance();
  21560. }
  21561. return state.pos !== start
  21562. };
  21563. function isDecimalDigit(ch) {
  21564. return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */
  21565. }
  21566. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits
  21567. pp$1.regexp_eatHexDigits = function(state) {
  21568. var start = state.pos;
  21569. var ch = 0;
  21570. state.lastIntValue = 0;
  21571. while (isHexDigit(ch = state.current())) {
  21572. state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
  21573. state.advance();
  21574. }
  21575. return state.pos !== start
  21576. };
  21577. function isHexDigit(ch) {
  21578. return (
  21579. (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) ||
  21580. (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) ||
  21581. (ch >= 0x61 /* a */ && ch <= 0x66 /* f */)
  21582. )
  21583. }
  21584. function hexToInt(ch) {
  21585. if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) {
  21586. return 10 + (ch - 0x41 /* A */)
  21587. }
  21588. if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) {
  21589. return 10 + (ch - 0x61 /* a */)
  21590. }
  21591. return ch - 0x30 /* 0 */
  21592. }
  21593. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence
  21594. // Allows only 0-377(octal) i.e. 0-255(decimal).
  21595. pp$1.regexp_eatLegacyOctalEscapeSequence = function(state) {
  21596. if (this.regexp_eatOctalDigit(state)) {
  21597. var n1 = state.lastIntValue;
  21598. if (this.regexp_eatOctalDigit(state)) {
  21599. var n2 = state.lastIntValue;
  21600. if (n1 <= 3 && this.regexp_eatOctalDigit(state)) {
  21601. state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue;
  21602. } else {
  21603. state.lastIntValue = n1 * 8 + n2;
  21604. }
  21605. } else {
  21606. state.lastIntValue = n1;
  21607. }
  21608. return true
  21609. }
  21610. return false
  21611. };
  21612. // https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit
  21613. pp$1.regexp_eatOctalDigit = function(state) {
  21614. var ch = state.current();
  21615. if (isOctalDigit(ch)) {
  21616. state.lastIntValue = ch - 0x30; /* 0 */
  21617. state.advance();
  21618. return true
  21619. }
  21620. state.lastIntValue = 0;
  21621. return false
  21622. };
  21623. function isOctalDigit(ch) {
  21624. return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */
  21625. }
  21626. // https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits
  21627. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit
  21628. // And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
  21629. pp$1.regexp_eatFixedHexDigits = function(state, length) {
  21630. var start = state.pos;
  21631. state.lastIntValue = 0;
  21632. for (var i = 0; i < length; ++i) {
  21633. var ch = state.current();
  21634. if (!isHexDigit(ch)) {
  21635. state.pos = start;
  21636. return false
  21637. }
  21638. state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
  21639. state.advance();
  21640. }
  21641. return true
  21642. };
  21643. // Object type used to represent tokens. Note that normally, tokens
  21644. // simply exist as properties on the parser object. This is only
  21645. // used for the onToken callback and the external tokenizer.
  21646. var Token = function Token(p) {
  21647. this.type = p.type;
  21648. this.value = p.value;
  21649. this.start = p.start;
  21650. this.end = p.end;
  21651. if (p.options.locations)
  21652. { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); }
  21653. if (p.options.ranges)
  21654. { this.range = [p.start, p.end]; }
  21655. };
  21656. // ## Tokenizer
  21657. var pp = Parser.prototype;
  21658. // Move to the next token
  21659. pp.next = function(ignoreEscapeSequenceInKeyword) {
  21660. if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc)
  21661. { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); }
  21662. if (this.options.onToken)
  21663. { this.options.onToken(new Token(this)); }
  21664. this.lastTokEnd = this.end;
  21665. this.lastTokStart = this.start;
  21666. this.lastTokEndLoc = this.endLoc;
  21667. this.lastTokStartLoc = this.startLoc;
  21668. this.nextToken();
  21669. };
  21670. pp.getToken = function() {
  21671. this.next();
  21672. return new Token(this)
  21673. };
  21674. // If we're in an ES6 environment, make parsers iterable
  21675. if (typeof Symbol !== "undefined")
  21676. { pp[Symbol.iterator] = function() {
  21677. var this$1$1 = this;
  21678. return {
  21679. next: function () {
  21680. var token = this$1$1.getToken();
  21681. return {
  21682. done: token.type === types$1.eof,
  21683. value: token
  21684. }
  21685. }
  21686. }
  21687. }; }
  21688. // Toggle strict mode. Re-reads the next number or string to please
  21689. // pedantic tests (`"use strict"; 010;` should fail).
  21690. // Read a single token, updating the parser object's token-related
  21691. // properties.
  21692. pp.nextToken = function() {
  21693. var curContext = this.curContext();
  21694. if (!curContext || !curContext.preserveSpace) { this.skipSpace(); }
  21695. this.start = this.pos;
  21696. if (this.options.locations) { this.startLoc = this.curPosition(); }
  21697. if (this.pos >= this.input.length) { return this.finishToken(types$1.eof) }
  21698. if (curContext.override) { return curContext.override(this) }
  21699. else { this.readToken(this.fullCharCodeAtPos()); }
  21700. };
  21701. pp.readToken = function(code) {
  21702. // Identifier or keyword. '\uXXXX' sequences are allowed in
  21703. // identifiers, so '\' also dispatches to that.
  21704. if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)
  21705. { return this.readWord() }
  21706. return this.getTokenFromCode(code)
  21707. };
  21708. pp.fullCharCodeAtPos = function() {
  21709. var code = this.input.charCodeAt(this.pos);
  21710. if (code <= 0xd7ff || code >= 0xdc00) { return code }
  21711. var next = this.input.charCodeAt(this.pos + 1);
  21712. return next <= 0xdbff || next >= 0xe000 ? code : (code << 10) + next - 0x35fdc00
  21713. };
  21714. pp.skipBlockComment = function() {
  21715. var startLoc = this.options.onComment && this.curPosition();
  21716. var start = this.pos, end = this.input.indexOf("*/", this.pos += 2);
  21717. if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); }
  21718. this.pos = end + 2;
  21719. if (this.options.locations) {
  21720. for (var nextBreak = (void 0), pos = start; (nextBreak = nextLineBreak(this.input, pos, this.pos)) > -1;) {
  21721. ++this.curLine;
  21722. pos = this.lineStart = nextBreak;
  21723. }
  21724. }
  21725. if (this.options.onComment)
  21726. { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,
  21727. startLoc, this.curPosition()); }
  21728. };
  21729. pp.skipLineComment = function(startSkip) {
  21730. var start = this.pos;
  21731. var startLoc = this.options.onComment && this.curPosition();
  21732. var ch = this.input.charCodeAt(this.pos += startSkip);
  21733. while (this.pos < this.input.length && !isNewLine(ch)) {
  21734. ch = this.input.charCodeAt(++this.pos);
  21735. }
  21736. if (this.options.onComment)
  21737. { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos,
  21738. startLoc, this.curPosition()); }
  21739. };
  21740. // Called at the start of the parse and after every token. Skips
  21741. // whitespace and comments, and.
  21742. pp.skipSpace = function() {
  21743. loop: while (this.pos < this.input.length) {
  21744. var ch = this.input.charCodeAt(this.pos);
  21745. switch (ch) {
  21746. case 32: case 160: // ' '
  21747. ++this.pos;
  21748. break
  21749. case 13:
  21750. if (this.input.charCodeAt(this.pos + 1) === 10) {
  21751. ++this.pos;
  21752. }
  21753. case 10: case 8232: case 8233:
  21754. ++this.pos;
  21755. if (this.options.locations) {
  21756. ++this.curLine;
  21757. this.lineStart = this.pos;
  21758. }
  21759. break
  21760. case 47: // '/'
  21761. switch (this.input.charCodeAt(this.pos + 1)) {
  21762. case 42: // '*'
  21763. this.skipBlockComment();
  21764. break
  21765. case 47:
  21766. this.skipLineComment(2);
  21767. break
  21768. default:
  21769. break loop
  21770. }
  21771. break
  21772. default:
  21773. if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
  21774. ++this.pos;
  21775. } else {
  21776. break loop
  21777. }
  21778. }
  21779. }
  21780. };
  21781. // Called at the end of every token. Sets `end`, `val`, and
  21782. // maintains `context` and `exprAllowed`, and skips the space after
  21783. // the token, so that the next one's `start` will point at the
  21784. // right position.
  21785. pp.finishToken = function(type, val) {
  21786. this.end = this.pos;
  21787. if (this.options.locations) { this.endLoc = this.curPosition(); }
  21788. var prevType = this.type;
  21789. this.type = type;
  21790. this.value = val;
  21791. this.updateContext(prevType);
  21792. };
  21793. // ### Token reading
  21794. // This is the function that is called to fetch the next token. It
  21795. // is somewhat obscure, because it works in character codes rather
  21796. // than characters, and because operator parsing has been inlined
  21797. // into it.
  21798. //
  21799. // All in the name of speed.
  21800. //
  21801. pp.readToken_dot = function() {
  21802. var next = this.input.charCodeAt(this.pos + 1);
  21803. if (next >= 48 && next <= 57) { return this.readNumber(true) }
  21804. var next2 = this.input.charCodeAt(this.pos + 2);
  21805. if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'
  21806. this.pos += 3;
  21807. return this.finishToken(types$1.ellipsis)
  21808. } else {
  21809. ++this.pos;
  21810. return this.finishToken(types$1.dot)
  21811. }
  21812. };
  21813. pp.readToken_slash = function() { // '/'
  21814. var next = this.input.charCodeAt(this.pos + 1);
  21815. if (this.exprAllowed) { ++this.pos; return this.readRegexp() }
  21816. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  21817. return this.finishOp(types$1.slash, 1)
  21818. };
  21819. pp.readToken_mult_modulo_exp = function(code) { // '%*'
  21820. var next = this.input.charCodeAt(this.pos + 1);
  21821. var size = 1;
  21822. var tokentype = code === 42 ? types$1.star : types$1.modulo;
  21823. // exponentiation operator ** and **=
  21824. if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) {
  21825. ++size;
  21826. tokentype = types$1.starstar;
  21827. next = this.input.charCodeAt(this.pos + 2);
  21828. }
  21829. if (next === 61) { return this.finishOp(types$1.assign, size + 1) }
  21830. return this.finishOp(tokentype, size)
  21831. };
  21832. pp.readToken_pipe_amp = function(code) { // '|&'
  21833. var next = this.input.charCodeAt(this.pos + 1);
  21834. if (next === code) {
  21835. if (this.options.ecmaVersion >= 12) {
  21836. var next2 = this.input.charCodeAt(this.pos + 2);
  21837. if (next2 === 61) { return this.finishOp(types$1.assign, 3) }
  21838. }
  21839. return this.finishOp(code === 124 ? types$1.logicalOR : types$1.logicalAND, 2)
  21840. }
  21841. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  21842. return this.finishOp(code === 124 ? types$1.bitwiseOR : types$1.bitwiseAND, 1)
  21843. };
  21844. pp.readToken_caret = function() { // '^'
  21845. var next = this.input.charCodeAt(this.pos + 1);
  21846. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  21847. return this.finishOp(types$1.bitwiseXOR, 1)
  21848. };
  21849. pp.readToken_plus_min = function(code) { // '+-'
  21850. var next = this.input.charCodeAt(this.pos + 1);
  21851. if (next === code) {
  21852. if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 &&
  21853. (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {
  21854. // A `-->` line comment
  21855. this.skipLineComment(3);
  21856. this.skipSpace();
  21857. return this.nextToken()
  21858. }
  21859. return this.finishOp(types$1.incDec, 2)
  21860. }
  21861. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  21862. return this.finishOp(types$1.plusMin, 1)
  21863. };
  21864. pp.readToken_lt_gt = function(code) { // '<>'
  21865. var next = this.input.charCodeAt(this.pos + 1);
  21866. var size = 1;
  21867. if (next === code) {
  21868. size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
  21869. if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types$1.assign, size + 1) }
  21870. return this.finishOp(types$1.bitShift, size)
  21871. }
  21872. if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 &&
  21873. this.input.charCodeAt(this.pos + 3) === 45) {
  21874. // `<!--`, an XML-style comment that should be interpreted as a line comment
  21875. this.skipLineComment(4);
  21876. this.skipSpace();
  21877. return this.nextToken()
  21878. }
  21879. if (next === 61) { size = 2; }
  21880. return this.finishOp(types$1.relational, size)
  21881. };
  21882. pp.readToken_eq_excl = function(code) { // '=!'
  21883. var next = this.input.charCodeAt(this.pos + 1);
  21884. if (next === 61) { return this.finishOp(types$1.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2) }
  21885. if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { // '=>'
  21886. this.pos += 2;
  21887. return this.finishToken(types$1.arrow)
  21888. }
  21889. return this.finishOp(code === 61 ? types$1.eq : types$1.prefix, 1)
  21890. };
  21891. pp.readToken_question = function() { // '?'
  21892. var ecmaVersion = this.options.ecmaVersion;
  21893. if (ecmaVersion >= 11) {
  21894. var next = this.input.charCodeAt(this.pos + 1);
  21895. if (next === 46) {
  21896. var next2 = this.input.charCodeAt(this.pos + 2);
  21897. if (next2 < 48 || next2 > 57) { return this.finishOp(types$1.questionDot, 2) }
  21898. }
  21899. if (next === 63) {
  21900. if (ecmaVersion >= 12) {
  21901. var next2$1 = this.input.charCodeAt(this.pos + 2);
  21902. if (next2$1 === 61) { return this.finishOp(types$1.assign, 3) }
  21903. }
  21904. return this.finishOp(types$1.coalesce, 2)
  21905. }
  21906. }
  21907. return this.finishOp(types$1.question, 1)
  21908. };
  21909. pp.readToken_numberSign = function() { // '#'
  21910. var ecmaVersion = this.options.ecmaVersion;
  21911. var code = 35; // '#'
  21912. if (ecmaVersion >= 13) {
  21913. ++this.pos;
  21914. code = this.fullCharCodeAtPos();
  21915. if (isIdentifierStart(code, true) || code === 92 /* '\' */) {
  21916. return this.finishToken(types$1.privateId, this.readWord1())
  21917. }
  21918. }
  21919. this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
  21920. };
  21921. pp.getTokenFromCode = function(code) {
  21922. switch (code) {
  21923. // The interpretation of a dot depends on whether it is followed
  21924. // by a digit or another two dots.
  21925. case 46: // '.'
  21926. return this.readToken_dot()
  21927. // Punctuation tokens.
  21928. case 40: ++this.pos; return this.finishToken(types$1.parenL)
  21929. case 41: ++this.pos; return this.finishToken(types$1.parenR)
  21930. case 59: ++this.pos; return this.finishToken(types$1.semi)
  21931. case 44: ++this.pos; return this.finishToken(types$1.comma)
  21932. case 91: ++this.pos; return this.finishToken(types$1.bracketL)
  21933. case 93: ++this.pos; return this.finishToken(types$1.bracketR)
  21934. case 123: ++this.pos; return this.finishToken(types$1.braceL)
  21935. case 125: ++this.pos; return this.finishToken(types$1.braceR)
  21936. case 58: ++this.pos; return this.finishToken(types$1.colon)
  21937. case 96: // '`'
  21938. if (this.options.ecmaVersion < 6) { break }
  21939. ++this.pos;
  21940. return this.finishToken(types$1.backQuote)
  21941. case 48: // '0'
  21942. var next = this.input.charCodeAt(this.pos + 1);
  21943. if (next === 120 || next === 88) { return this.readRadixNumber(16) } // '0x', '0X' - hex number
  21944. if (this.options.ecmaVersion >= 6) {
  21945. if (next === 111 || next === 79) { return this.readRadixNumber(8) } // '0o', '0O' - octal number
  21946. if (next === 98 || next === 66) { return this.readRadixNumber(2) } // '0b', '0B' - binary number
  21947. }
  21948. // Anything else beginning with a digit is an integer, octal
  21949. // number, or float.
  21950. case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9
  21951. return this.readNumber(false)
  21952. // Quotes produce strings.
  21953. case 34: case 39: // '"', "'"
  21954. return this.readString(code)
  21955. // Operators are parsed inline in tiny state machines. '=' (61) is
  21956. // often referred to. `finishOp` simply skips the amount of
  21957. // characters it is given as second argument, and returns a token
  21958. // of the type given by its first argument.
  21959. case 47: // '/'
  21960. return this.readToken_slash()
  21961. case 37: case 42: // '%*'
  21962. return this.readToken_mult_modulo_exp(code)
  21963. case 124: case 38: // '|&'
  21964. return this.readToken_pipe_amp(code)
  21965. case 94: // '^'
  21966. return this.readToken_caret()
  21967. case 43: case 45: // '+-'
  21968. return this.readToken_plus_min(code)
  21969. case 60: case 62: // '<>'
  21970. return this.readToken_lt_gt(code)
  21971. case 61: case 33: // '=!'
  21972. return this.readToken_eq_excl(code)
  21973. case 63: // '?'
  21974. return this.readToken_question()
  21975. case 126: // '~'
  21976. return this.finishOp(types$1.prefix, 1)
  21977. case 35: // '#'
  21978. return this.readToken_numberSign()
  21979. }
  21980. this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
  21981. };
  21982. pp.finishOp = function(type, size) {
  21983. var str = this.input.slice(this.pos, this.pos + size);
  21984. this.pos += size;
  21985. return this.finishToken(type, str)
  21986. };
  21987. pp.readRegexp = function() {
  21988. var escaped, inClass, start = this.pos;
  21989. for (;;) {
  21990. if (this.pos >= this.input.length) { this.raise(start, "Unterminated regular expression"); }
  21991. var ch = this.input.charAt(this.pos);
  21992. if (lineBreak.test(ch)) { this.raise(start, "Unterminated regular expression"); }
  21993. if (!escaped) {
  21994. if (ch === "[") { inClass = true; }
  21995. else if (ch === "]" && inClass) { inClass = false; }
  21996. else if (ch === "/" && !inClass) { break }
  21997. escaped = ch === "\\";
  21998. } else { escaped = false; }
  21999. ++this.pos;
  22000. }
  22001. var pattern = this.input.slice(start, this.pos);
  22002. ++this.pos;
  22003. var flagsStart = this.pos;
  22004. var flags = this.readWord1();
  22005. if (this.containsEsc) { this.unexpected(flagsStart); }
  22006. // Validate pattern
  22007. var state = this.regexpState || (this.regexpState = new RegExpValidationState(this));
  22008. state.reset(start, pattern, flags);
  22009. this.validateRegExpFlags(state);
  22010. this.validateRegExpPattern(state);
  22011. // Create Literal#value property value.
  22012. var value = null;
  22013. try {
  22014. value = new RegExp(pattern, flags);
  22015. } catch (e) {
  22016. // ESTree requires null if it failed to instantiate RegExp object.
  22017. // https://github.com/estree/estree/blob/a27003adf4fd7bfad44de9cef372a2eacd527b1c/es5.md#regexpliteral
  22018. }
  22019. return this.finishToken(types$1.regexp, {pattern: pattern, flags: flags, value: value})
  22020. };
  22021. // Read an integer in the given radix. Return null if zero digits
  22022. // were read, the integer value otherwise. When `len` is given, this
  22023. // will return `null` unless the integer has exactly `len` digits.
  22024. pp.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) {
  22025. // `len` is used for character escape sequences. In that case, disallow separators.
  22026. var allowSeparators = this.options.ecmaVersion >= 12 && len === undefined;
  22027. // `maybeLegacyOctalNumericLiteral` is true if it doesn't have prefix (0x,0o,0b)
  22028. // and isn't fraction part nor exponent part. In that case, if the first digit
  22029. // is zero then disallow separators.
  22030. var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48;
  22031. var start = this.pos, total = 0, lastCode = 0;
  22032. for (var i = 0, e = len == null ? Infinity : len; i < e; ++i, ++this.pos) {
  22033. var code = this.input.charCodeAt(this.pos), val = (void 0);
  22034. if (allowSeparators && code === 95) {
  22035. if (isLegacyOctalNumericLiteral) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals"); }
  22036. if (lastCode === 95) { this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore"); }
  22037. if (i === 0) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits"); }
  22038. lastCode = code;
  22039. continue
  22040. }
  22041. if (code >= 97) { val = code - 97 + 10; } // a
  22042. else if (code >= 65) { val = code - 65 + 10; } // A
  22043. else if (code >= 48 && code <= 57) { val = code - 48; } // 0-9
  22044. else { val = Infinity; }
  22045. if (val >= radix) { break }
  22046. lastCode = code;
  22047. total = total * radix + val;
  22048. }
  22049. if (allowSeparators && lastCode === 95) { this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits"); }
  22050. if (this.pos === start || len != null && this.pos - start !== len) { return null }
  22051. return total
  22052. };
  22053. function stringToNumber(str, isLegacyOctalNumericLiteral) {
  22054. if (isLegacyOctalNumericLiteral) {
  22055. return parseInt(str, 8)
  22056. }
  22057. // `parseFloat(value)` stops parsing at the first numeric separator then returns a wrong value.
  22058. return parseFloat(str.replace(/_/g, ""))
  22059. }
  22060. function stringToBigInt(str) {
  22061. if (typeof BigInt !== "function") {
  22062. return null
  22063. }
  22064. // `BigInt(value)` throws syntax error if the string contains numeric separators.
  22065. return BigInt(str.replace(/_/g, ""))
  22066. }
  22067. pp.readRadixNumber = function(radix) {
  22068. var start = this.pos;
  22069. this.pos += 2; // 0x
  22070. var val = this.readInt(radix);
  22071. if (val == null) { this.raise(this.start + 2, "Expected number in radix " + radix); }
  22072. if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
  22073. val = stringToBigInt(this.input.slice(start, this.pos));
  22074. ++this.pos;
  22075. } else if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  22076. return this.finishToken(types$1.num, val)
  22077. };
  22078. // Read an integer, octal integer, or floating-point number.
  22079. pp.readNumber = function(startsWithDot) {
  22080. var start = this.pos;
  22081. if (!startsWithDot && this.readInt(10, undefined, true) === null) { this.raise(start, "Invalid number"); }
  22082. var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  22083. if (octal && this.strict) { this.raise(start, "Invalid number"); }
  22084. var next = this.input.charCodeAt(this.pos);
  22085. if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {
  22086. var val$1 = stringToBigInt(this.input.slice(start, this.pos));
  22087. ++this.pos;
  22088. if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  22089. return this.finishToken(types$1.num, val$1)
  22090. }
  22091. if (octal && /[89]/.test(this.input.slice(start, this.pos))) { octal = false; }
  22092. if (next === 46 && !octal) { // '.'
  22093. ++this.pos;
  22094. this.readInt(10);
  22095. next = this.input.charCodeAt(this.pos);
  22096. }
  22097. if ((next === 69 || next === 101) && !octal) { // 'eE'
  22098. next = this.input.charCodeAt(++this.pos);
  22099. if (next === 43 || next === 45) { ++this.pos; } // '+-'
  22100. if (this.readInt(10) === null) { this.raise(start, "Invalid number"); }
  22101. }
  22102. if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  22103. var val = stringToNumber(this.input.slice(start, this.pos), octal);
  22104. return this.finishToken(types$1.num, val)
  22105. };
  22106. // Read a string value, interpreting backslash-escapes.
  22107. pp.readCodePoint = function() {
  22108. var ch = this.input.charCodeAt(this.pos), code;
  22109. if (ch === 123) { // '{'
  22110. if (this.options.ecmaVersion < 6) { this.unexpected(); }
  22111. var codePos = ++this.pos;
  22112. code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
  22113. ++this.pos;
  22114. if (code > 0x10FFFF) { this.invalidStringToken(codePos, "Code point out of bounds"); }
  22115. } else {
  22116. code = this.readHexChar(4);
  22117. }
  22118. return code
  22119. };
  22120. pp.readString = function(quote) {
  22121. var out = "", chunkStart = ++this.pos;
  22122. for (;;) {
  22123. if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated string constant"); }
  22124. var ch = this.input.charCodeAt(this.pos);
  22125. if (ch === quote) { break }
  22126. if (ch === 92) { // '\'
  22127. out += this.input.slice(chunkStart, this.pos);
  22128. out += this.readEscapedChar(false);
  22129. chunkStart = this.pos;
  22130. } else if (ch === 0x2028 || ch === 0x2029) {
  22131. if (this.options.ecmaVersion < 10) { this.raise(this.start, "Unterminated string constant"); }
  22132. ++this.pos;
  22133. if (this.options.locations) {
  22134. this.curLine++;
  22135. this.lineStart = this.pos;
  22136. }
  22137. } else {
  22138. if (isNewLine(ch)) { this.raise(this.start, "Unterminated string constant"); }
  22139. ++this.pos;
  22140. }
  22141. }
  22142. out += this.input.slice(chunkStart, this.pos++);
  22143. return this.finishToken(types$1.string, out)
  22144. };
  22145. // Reads template string tokens.
  22146. var INVALID_TEMPLATE_ESCAPE_ERROR = {};
  22147. pp.tryReadTemplateToken = function() {
  22148. this.inTemplateElement = true;
  22149. try {
  22150. this.readTmplToken();
  22151. } catch (err) {
  22152. if (err === INVALID_TEMPLATE_ESCAPE_ERROR) {
  22153. this.readInvalidTemplateToken();
  22154. } else {
  22155. throw err
  22156. }
  22157. }
  22158. this.inTemplateElement = false;
  22159. };
  22160. pp.invalidStringToken = function(position, message) {
  22161. if (this.inTemplateElement && this.options.ecmaVersion >= 9) {
  22162. throw INVALID_TEMPLATE_ESCAPE_ERROR
  22163. } else {
  22164. this.raise(position, message);
  22165. }
  22166. };
  22167. pp.readTmplToken = function() {
  22168. var out = "", chunkStart = this.pos;
  22169. for (;;) {
  22170. if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated template"); }
  22171. var ch = this.input.charCodeAt(this.pos);
  22172. if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) { // '`', '${'
  22173. if (this.pos === this.start && (this.type === types$1.template || this.type === types$1.invalidTemplate)) {
  22174. if (ch === 36) {
  22175. this.pos += 2;
  22176. return this.finishToken(types$1.dollarBraceL)
  22177. } else {
  22178. ++this.pos;
  22179. return this.finishToken(types$1.backQuote)
  22180. }
  22181. }
  22182. out += this.input.slice(chunkStart, this.pos);
  22183. return this.finishToken(types$1.template, out)
  22184. }
  22185. if (ch === 92) { // '\'
  22186. out += this.input.slice(chunkStart, this.pos);
  22187. out += this.readEscapedChar(true);
  22188. chunkStart = this.pos;
  22189. } else if (isNewLine(ch)) {
  22190. out += this.input.slice(chunkStart, this.pos);
  22191. ++this.pos;
  22192. switch (ch) {
  22193. case 13:
  22194. if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; }
  22195. case 10:
  22196. out += "\n";
  22197. break
  22198. default:
  22199. out += String.fromCharCode(ch);
  22200. break
  22201. }
  22202. if (this.options.locations) {
  22203. ++this.curLine;
  22204. this.lineStart = this.pos;
  22205. }
  22206. chunkStart = this.pos;
  22207. } else {
  22208. ++this.pos;
  22209. }
  22210. }
  22211. };
  22212. // Reads a template token to search for the end, without validating any escape sequences
  22213. pp.readInvalidTemplateToken = function() {
  22214. for (; this.pos < this.input.length; this.pos++) {
  22215. switch (this.input[this.pos]) {
  22216. case "\\":
  22217. ++this.pos;
  22218. break
  22219. case "$":
  22220. if (this.input[this.pos + 1] !== "{") {
  22221. break
  22222. }
  22223. // falls through
  22224. case "`":
  22225. return this.finishToken(types$1.invalidTemplate, this.input.slice(this.start, this.pos))
  22226. // no default
  22227. }
  22228. }
  22229. this.raise(this.start, "Unterminated template");
  22230. };
  22231. // Used to read escaped characters
  22232. pp.readEscapedChar = function(inTemplate) {
  22233. var ch = this.input.charCodeAt(++this.pos);
  22234. ++this.pos;
  22235. switch (ch) {
  22236. case 110: return "\n" // 'n' -> '\n'
  22237. case 114: return "\r" // 'r' -> '\r'
  22238. case 120: return String.fromCharCode(this.readHexChar(2)) // 'x'
  22239. case 117: return codePointToString(this.readCodePoint()) // 'u'
  22240. case 116: return "\t" // 't' -> '\t'
  22241. case 98: return "\b" // 'b' -> '\b'
  22242. case 118: return "\u000b" // 'v' -> '\u000b'
  22243. case 102: return "\f" // 'f' -> '\f'
  22244. case 13: if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; } // '\r\n'
  22245. case 10: // ' \n'
  22246. if (this.options.locations) { this.lineStart = this.pos; ++this.curLine; }
  22247. return ""
  22248. case 56:
  22249. case 57:
  22250. if (this.strict) {
  22251. this.invalidStringToken(
  22252. this.pos - 1,
  22253. "Invalid escape sequence"
  22254. );
  22255. }
  22256. if (inTemplate) {
  22257. var codePos = this.pos - 1;
  22258. this.invalidStringToken(
  22259. codePos,
  22260. "Invalid escape sequence in template string"
  22261. );
  22262. }
  22263. default:
  22264. if (ch >= 48 && ch <= 55) {
  22265. var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
  22266. var octal = parseInt(octalStr, 8);
  22267. if (octal > 255) {
  22268. octalStr = octalStr.slice(0, -1);
  22269. octal = parseInt(octalStr, 8);
  22270. }
  22271. this.pos += octalStr.length - 1;
  22272. ch = this.input.charCodeAt(this.pos);
  22273. if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) {
  22274. this.invalidStringToken(
  22275. this.pos - 1 - octalStr.length,
  22276. inTemplate
  22277. ? "Octal literal in template string"
  22278. : "Octal literal in strict mode"
  22279. );
  22280. }
  22281. return String.fromCharCode(octal)
  22282. }
  22283. if (isNewLine(ch)) {
  22284. // Unicode new line characters after \ get removed from output in both
  22285. // template literals and strings
  22286. return ""
  22287. }
  22288. return String.fromCharCode(ch)
  22289. }
  22290. };
  22291. // Used to read character escape sequences ('\x', '\u', '\U').
  22292. pp.readHexChar = function(len) {
  22293. var codePos = this.pos;
  22294. var n = this.readInt(16, len);
  22295. if (n === null) { this.invalidStringToken(codePos, "Bad character escape sequence"); }
  22296. return n
  22297. };
  22298. // Read an identifier, and return it as a string. Sets `this.containsEsc`
  22299. // to whether the word contained a '\u' escape.
  22300. //
  22301. // Incrementally adds only escaped chars, adding other chunks as-is
  22302. // as a micro-optimization.
  22303. pp.readWord1 = function() {
  22304. this.containsEsc = false;
  22305. var word = "", first = true, chunkStart = this.pos;
  22306. var astral = this.options.ecmaVersion >= 6;
  22307. while (this.pos < this.input.length) {
  22308. var ch = this.fullCharCodeAtPos();
  22309. if (isIdentifierChar(ch, astral)) {
  22310. this.pos += ch <= 0xffff ? 1 : 2;
  22311. } else if (ch === 92) { // "\"
  22312. this.containsEsc = true;
  22313. word += this.input.slice(chunkStart, this.pos);
  22314. var escStart = this.pos;
  22315. if (this.input.charCodeAt(++this.pos) !== 117) // "u"
  22316. { this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX"); }
  22317. ++this.pos;
  22318. var esc = this.readCodePoint();
  22319. if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral))
  22320. { this.invalidStringToken(escStart, "Invalid Unicode escape"); }
  22321. word += codePointToString(esc);
  22322. chunkStart = this.pos;
  22323. } else {
  22324. break
  22325. }
  22326. first = false;
  22327. }
  22328. return word + this.input.slice(chunkStart, this.pos)
  22329. };
  22330. // Read an identifier or keyword token. Will check for reserved
  22331. // words when necessary.
  22332. pp.readWord = function() {
  22333. var word = this.readWord1();
  22334. var type = types$1.name;
  22335. if (this.keywords.test(word)) {
  22336. type = keywords[word];
  22337. }
  22338. return this.finishToken(type, word)
  22339. };
  22340. // Acorn is a tiny, fast JavaScript parser written in JavaScript.
  22341. //
  22342. // Acorn was written by Marijn Haverbeke, Ingvar Stepanyan, and
  22343. // various contributors and released under an MIT license.
  22344. //
  22345. // Git repositories for Acorn are available at
  22346. //
  22347. // http://marijnhaverbeke.nl/git/acorn
  22348. // https://github.com/acornjs/acorn.git
  22349. //
  22350. // Please use the [github bug tracker][ghbt] to report issues.
  22351. //
  22352. // [ghbt]: https://github.com/acornjs/acorn/issues
  22353. //
  22354. // [walk]: util/walk.js
  22355. var version = "8.10.0";
  22356. Parser.acorn = {
  22357. Parser: Parser,
  22358. version: version,
  22359. defaultOptions: defaultOptions,
  22360. Position: Position,
  22361. SourceLocation: SourceLocation,
  22362. getLineInfo: getLineInfo,
  22363. Node: Node,
  22364. TokenType: TokenType,
  22365. tokTypes: types$1,
  22366. keywordTypes: keywords,
  22367. TokContext: TokContext,
  22368. tokContexts: types,
  22369. isIdentifierChar: isIdentifierChar,
  22370. isIdentifierStart: isIdentifierStart,
  22371. Token: Token,
  22372. isNewLine: isNewLine,
  22373. lineBreak: lineBreak,
  22374. lineBreakG: lineBreakG,
  22375. nonASCIIwhitespace: nonASCIIwhitespace
  22376. };
  22377. // The main exported interface (under `self.acorn` when in the
  22378. // browser) is a `parse` function that takes a code string and
  22379. // returns an abstract syntax tree as specified by [Mozilla parser
  22380. // API][api].
  22381. //
  22382. // [api]: https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API
  22383. function parse(input, options) {
  22384. return Parser.parse(input, options)
  22385. }
  22386. // This function tries to parse a single expression at a given
  22387. // offset in a string. Useful for parsing mixed-language formats
  22388. // that embed JavaScript expressions.
  22389. function parseExpressionAt(input, pos, options) {
  22390. return Parser.parseExpressionAt(input, pos, options)
  22391. }
  22392. // Acorn is organized as a tokenizer and a recursive-descent parser.
  22393. // The `tokenizer` export provides an interface to the tokenizer.
  22394. function tokenizer(input, options) {
  22395. return Parser.tokenizer(input, options)
  22396. }
  22397. const _acorn = /*#__PURE__*/Object.defineProperty({
  22398. __proto__: null,
  22399. Node,
  22400. Parser,
  22401. Position,
  22402. SourceLocation,
  22403. TokContext,
  22404. Token,
  22405. TokenType,
  22406. defaultOptions,
  22407. getLineInfo,
  22408. isIdentifierChar,
  22409. isIdentifierStart,
  22410. isNewLine,
  22411. keywordTypes: keywords,
  22412. lineBreak,
  22413. lineBreakG,
  22414. nonASCIIwhitespace,
  22415. parse,
  22416. parseExpressionAt,
  22417. tokContexts: types,
  22418. tokTypes: types$1,
  22419. tokenizer,
  22420. version
  22421. }, Symbol.toStringTag, { value: 'Module' });
  22422. function flru (max) {
  22423. var num, curr, prev;
  22424. var limit = max || 1;
  22425. function keep(key, value) {
  22426. if (++num > limit) {
  22427. prev = curr;
  22428. reset(1);
  22429. ++num;
  22430. }
  22431. curr[key] = value;
  22432. }
  22433. function reset(isPartial) {
  22434. num = 0;
  22435. curr = Object.create(null);
  22436. isPartial || (prev=Object.create(null));
  22437. }
  22438. reset();
  22439. return {
  22440. clear: reset,
  22441. has: function (key) {
  22442. return curr[key] !== void 0 || prev[key] !== void 0;
  22443. },
  22444. get: function (key) {
  22445. var val = curr[key];
  22446. if (val !== void 0) return val;
  22447. if ((val=prev[key]) !== void 0) {
  22448. keep(key, val);
  22449. return val;
  22450. }
  22451. },
  22452. set: function (key, value) {
  22453. if (curr[key] !== void 0) {
  22454. curr[key] = value;
  22455. } else {
  22456. keep(key, value);
  22457. }
  22458. }
  22459. };
  22460. }
  22461. function resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, assertions) {
  22462. let skipped = null;
  22463. let replaceContext = null;
  22464. if (skip) {
  22465. skipped = new Set();
  22466. for (const skippedCall of skip) {
  22467. if (source === skippedCall.source && importer === skippedCall.importer) {
  22468. skipped.add(skippedCall.plugin);
  22469. }
  22470. }
  22471. replaceContext = (pluginContext, plugin) => ({
  22472. ...pluginContext,
  22473. resolve: (source, importer, { assertions, custom, isEntry, skipSelf } = BLANK) => moduleLoaderResolveId(source, importer, custom, isEntry, assertions || EMPTY_OBJECT, skipSelf ? [...skip, { importer, plugin, source }] : skip)
  22474. });
  22475. }
  22476. return pluginDriver.hookFirstAndGetPlugin('resolveId', [source, importer, { assertions, custom: customOptions, isEntry }], replaceContext, skipped);
  22477. }
  22478. async function resolveId(source, importer, preserveSymlinks, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, assertions) {
  22479. const pluginResult = await resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, assertions);
  22480. if (pluginResult != null) {
  22481. const [resolveIdResult, plugin] = pluginResult;
  22482. if (typeof resolveIdResult === 'object' && !resolveIdResult.resolvedBy) {
  22483. return {
  22484. ...resolveIdResult,
  22485. resolvedBy: plugin.name
  22486. };
  22487. }
  22488. if (typeof resolveIdResult === 'string') {
  22489. return {
  22490. id: resolveIdResult,
  22491. resolvedBy: plugin.name
  22492. };
  22493. }
  22494. return resolveIdResult;
  22495. }
  22496. // external modules (non-entry modules that start with neither '.' or '/')
  22497. // are skipped at this stage.
  22498. if (importer !== undefined && !isAbsolute(source) && source[0] !== '.')
  22499. return null;
  22500. // `resolve` processes paths from right to left, prepending them until an
  22501. // absolute path is created. Absolute importees therefore shortcircuit the
  22502. // resolve call and require no special handing on our part.
  22503. // See https://nodejs.org/api/path.html#path_path_resolve_paths
  22504. return addJsExtensionIfNecessary(importer ? resolve(dirname(importer), source) : resolve(source), preserveSymlinks);
  22505. }
  22506. async function addJsExtensionIfNecessary(file, preserveSymlinks) {
  22507. return ((await findFile(file, preserveSymlinks)) ??
  22508. (await findFile(file + '.mjs', preserveSymlinks)) ??
  22509. (await findFile(file + '.js', preserveSymlinks)));
  22510. }
  22511. async function findFile(file, preserveSymlinks) {
  22512. try {
  22513. const stats = await lstat(file);
  22514. if (!preserveSymlinks && stats.isSymbolicLink())
  22515. return await findFile(await realpath(file), preserveSymlinks);
  22516. if ((preserveSymlinks && stats.isSymbolicLink()) || stats.isFile()) {
  22517. // check case
  22518. const name = basename(file);
  22519. const files = await readdir(dirname(file));
  22520. if (files.includes(name))
  22521. return file;
  22522. }
  22523. }
  22524. catch {
  22525. // suppress
  22526. }
  22527. }
  22528. const ANONYMOUS_PLUGIN_PREFIX = 'at position ';
  22529. const ANONYMOUS_OUTPUT_PLUGIN_PREFIX = 'at output position ';
  22530. function createPluginCache(cache) {
  22531. return {
  22532. delete(id) {
  22533. return delete cache[id];
  22534. },
  22535. get(id) {
  22536. const item = cache[id];
  22537. if (!item)
  22538. return;
  22539. item[0] = 0;
  22540. return item[1];
  22541. },
  22542. has(id) {
  22543. const item = cache[id];
  22544. if (!item)
  22545. return false;
  22546. item[0] = 0;
  22547. return true;
  22548. },
  22549. set(id, value) {
  22550. cache[id] = [0, value];
  22551. }
  22552. };
  22553. }
  22554. function getTrackedPluginCache(pluginCache, onUse) {
  22555. return {
  22556. delete(id) {
  22557. onUse();
  22558. return pluginCache.delete(id);
  22559. },
  22560. get(id) {
  22561. onUse();
  22562. return pluginCache.get(id);
  22563. },
  22564. has(id) {
  22565. onUse();
  22566. return pluginCache.has(id);
  22567. },
  22568. set(id, value) {
  22569. onUse();
  22570. return pluginCache.set(id, value);
  22571. }
  22572. };
  22573. }
  22574. const NO_CACHE = {
  22575. delete() {
  22576. return false;
  22577. },
  22578. get() {
  22579. return undefined;
  22580. },
  22581. has() {
  22582. return false;
  22583. },
  22584. set() { }
  22585. };
  22586. function uncacheablePluginError(pluginName) {
  22587. if (pluginName.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  22588. pluginName.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX)) {
  22589. return error(logAnonymousPluginCache());
  22590. }
  22591. return error(logDuplicatePluginName(pluginName));
  22592. }
  22593. function getCacheForUncacheablePlugin(pluginName) {
  22594. return {
  22595. delete() {
  22596. return uncacheablePluginError(pluginName);
  22597. },
  22598. get() {
  22599. return uncacheablePluginError(pluginName);
  22600. },
  22601. has() {
  22602. return uncacheablePluginError(pluginName);
  22603. },
  22604. set() {
  22605. return uncacheablePluginError(pluginName);
  22606. }
  22607. };
  22608. }
  22609. async function asyncFlatten(array) {
  22610. do {
  22611. array = (await Promise.all(array)).flat(Infinity);
  22612. } while (array.some((v) => v?.then));
  22613. return array;
  22614. }
  22615. const getOnLog = (config, logLevel, printLog = defaultPrintLog) => {
  22616. const { onwarn, onLog } = config;
  22617. const defaultOnLog = getDefaultOnLog(printLog, onwarn);
  22618. if (onLog) {
  22619. const minimalPriority = logLevelPriority[logLevel];
  22620. return (level, log) => onLog(level, addLogToString(log), (level, handledLog) => {
  22621. if (level === LOGLEVEL_ERROR) {
  22622. return error(normalizeLog(handledLog));
  22623. }
  22624. if (logLevelPriority[level] >= minimalPriority) {
  22625. defaultOnLog(level, normalizeLog(handledLog));
  22626. }
  22627. });
  22628. }
  22629. return defaultOnLog;
  22630. };
  22631. const getDefaultOnLog = (printLog, onwarn) => onwarn
  22632. ? (level, log) => {
  22633. if (level === LOGLEVEL_WARN) {
  22634. onwarn(addLogToString(log), warning => printLog(LOGLEVEL_WARN, normalizeLog(warning)));
  22635. }
  22636. else {
  22637. printLog(level, log);
  22638. }
  22639. }
  22640. : printLog;
  22641. const addLogToString = (log) => {
  22642. Object.defineProperty(log, 'toString', {
  22643. value: () => getExtendedLogMessage(log),
  22644. writable: true
  22645. });
  22646. return log;
  22647. };
  22648. const normalizeLog = (log) => typeof log === 'string'
  22649. ? { message: log }
  22650. : typeof log === 'function'
  22651. ? normalizeLog(log())
  22652. : log;
  22653. const getExtendedLogMessage = (log) => {
  22654. let prefix = '';
  22655. if (log.plugin) {
  22656. prefix += `(${log.plugin} plugin) `;
  22657. }
  22658. if (log.loc) {
  22659. prefix += `${relativeId(log.loc.file)} (${log.loc.line}:${log.loc.column}) `;
  22660. }
  22661. return prefix + log.message;
  22662. };
  22663. const defaultPrintLog = (level, log) => {
  22664. const message = getExtendedLogMessage(log);
  22665. switch (level) {
  22666. case LOGLEVEL_WARN: {
  22667. return console.warn(message);
  22668. }
  22669. case LOGLEVEL_DEBUG: {
  22670. return console.debug(message);
  22671. }
  22672. default: {
  22673. return console.info(message);
  22674. }
  22675. }
  22676. };
  22677. function warnUnknownOptions(passedOptions, validOptions, optionType, log, ignoredKeys = /$./) {
  22678. const validOptionSet = new Set(validOptions);
  22679. const unknownOptions = Object.keys(passedOptions).filter(key => !(validOptionSet.has(key) || ignoredKeys.test(key)));
  22680. if (unknownOptions.length > 0) {
  22681. log(LOGLEVEL_WARN, logUnknownOption(optionType, unknownOptions, [...validOptionSet].sort()));
  22682. }
  22683. }
  22684. const treeshakePresets = {
  22685. recommended: {
  22686. annotations: true,
  22687. correctVarValueBeforeDeclaration: false,
  22688. manualPureFunctions: EMPTY_ARRAY,
  22689. moduleSideEffects: () => true,
  22690. propertyReadSideEffects: true,
  22691. tryCatchDeoptimization: true,
  22692. unknownGlobalSideEffects: false
  22693. },
  22694. safest: {
  22695. annotations: true,
  22696. correctVarValueBeforeDeclaration: true,
  22697. manualPureFunctions: EMPTY_ARRAY,
  22698. moduleSideEffects: () => true,
  22699. propertyReadSideEffects: true,
  22700. tryCatchDeoptimization: true,
  22701. unknownGlobalSideEffects: true
  22702. },
  22703. smallest: {
  22704. annotations: true,
  22705. correctVarValueBeforeDeclaration: false,
  22706. manualPureFunctions: EMPTY_ARRAY,
  22707. moduleSideEffects: () => false,
  22708. propertyReadSideEffects: false,
  22709. tryCatchDeoptimization: false,
  22710. unknownGlobalSideEffects: false
  22711. }
  22712. };
  22713. const generatedCodePresets = {
  22714. es2015: {
  22715. arrowFunctions: true,
  22716. constBindings: true,
  22717. objectShorthand: true,
  22718. reservedNamesAsProps: true,
  22719. symbols: true
  22720. },
  22721. es5: {
  22722. arrowFunctions: false,
  22723. constBindings: false,
  22724. objectShorthand: false,
  22725. reservedNamesAsProps: true,
  22726. symbols: false
  22727. }
  22728. };
  22729. const objectifyOption = (value) => value && typeof value === 'object' ? value : {};
  22730. const objectifyOptionWithPresets = (presets, optionName, urlSnippet, additionalValues) => (value) => {
  22731. if (typeof value === 'string') {
  22732. const preset = presets[value];
  22733. if (preset) {
  22734. return preset;
  22735. }
  22736. error(logInvalidOption(optionName, urlSnippet, `valid values are ${additionalValues}${printQuotedStringList(Object.keys(presets))}. You can also supply an object for more fine-grained control`, value));
  22737. }
  22738. return objectifyOption(value);
  22739. };
  22740. const getOptionWithPreset = (value, presets, optionName, urlSnippet, additionalValues) => {
  22741. const presetName = value?.preset;
  22742. if (presetName) {
  22743. const preset = presets[presetName];
  22744. if (preset) {
  22745. return { ...preset, ...value };
  22746. }
  22747. else {
  22748. error(logInvalidOption(`${optionName}.preset`, urlSnippet, `valid values are ${printQuotedStringList(Object.keys(presets))}`, presetName));
  22749. }
  22750. }
  22751. return objectifyOptionWithPresets(presets, optionName, urlSnippet, additionalValues)(value);
  22752. };
  22753. const normalizePluginOption = async (plugins) => (await asyncFlatten([plugins])).filter(Boolean);
  22754. async function transform(source, module, pluginDriver, log) {
  22755. const id = module.id;
  22756. const sourcemapChain = [];
  22757. let originalSourcemap = source.map === null ? null : decodedSourcemap(source.map);
  22758. const originalCode = source.code;
  22759. let ast = source.ast;
  22760. const transformDependencies = [];
  22761. const emittedFiles = [];
  22762. let customTransformCache = false;
  22763. const useCustomTransformCache = () => (customTransformCache = true);
  22764. let pluginName = '';
  22765. let currentSource = source.code;
  22766. function transformReducer(previousCode, result, plugin) {
  22767. let code;
  22768. let map;
  22769. if (typeof result === 'string') {
  22770. code = result;
  22771. }
  22772. else if (result && typeof result === 'object') {
  22773. module.updateOptions(result);
  22774. if (result.code == null) {
  22775. if (result.map || result.ast) {
  22776. log(LOGLEVEL_WARN, logNoTransformMapOrAstWithoutCode(plugin.name));
  22777. }
  22778. return previousCode;
  22779. }
  22780. ({ code, map, ast } = result);
  22781. }
  22782. else {
  22783. return previousCode;
  22784. }
  22785. // strict null check allows 'null' maps to not be pushed to the chain,
  22786. // while 'undefined' gets the missing map warning
  22787. if (map !== null) {
  22788. sourcemapChain.push(decodedSourcemap(typeof map === 'string' ? JSON.parse(map) : map) || {
  22789. missing: true,
  22790. plugin: plugin.name
  22791. });
  22792. }
  22793. currentSource = code;
  22794. return code;
  22795. }
  22796. const getLogHandler = (handler) => (log, pos) => {
  22797. log = normalizeLog(log);
  22798. if (pos)
  22799. augmentCodeLocation(log, pos, currentSource, id);
  22800. log.id = id;
  22801. log.hook = 'transform';
  22802. handler(log);
  22803. };
  22804. let code;
  22805. try {
  22806. code = await pluginDriver.hookReduceArg0('transform', [currentSource, id], transformReducer, (pluginContext, plugin) => {
  22807. pluginName = plugin.name;
  22808. return {
  22809. ...pluginContext,
  22810. addWatchFile(id) {
  22811. transformDependencies.push(id);
  22812. pluginContext.addWatchFile(id);
  22813. },
  22814. cache: customTransformCache
  22815. ? pluginContext.cache
  22816. : getTrackedPluginCache(pluginContext.cache, useCustomTransformCache),
  22817. debug: getLogHandler(pluginContext.debug),
  22818. emitFile(emittedFile) {
  22819. emittedFiles.push(emittedFile);
  22820. return pluginDriver.emitFile(emittedFile);
  22821. },
  22822. error(error_, pos) {
  22823. if (typeof error_ === 'string')
  22824. error_ = { message: error_ };
  22825. if (pos)
  22826. augmentCodeLocation(error_, pos, currentSource, id);
  22827. error_.id = id;
  22828. error_.hook = 'transform';
  22829. return pluginContext.error(error_);
  22830. },
  22831. getCombinedSourcemap() {
  22832. const combinedMap = collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, log);
  22833. if (!combinedMap) {
  22834. const magicString = new MagicString(originalCode);
  22835. return magicString.generateMap({ hires: true, includeContent: true, source: id });
  22836. }
  22837. if (originalSourcemap !== combinedMap) {
  22838. originalSourcemap = combinedMap;
  22839. sourcemapChain.length = 0;
  22840. }
  22841. return new SourceMap({
  22842. ...combinedMap,
  22843. file: null,
  22844. sourcesContent: combinedMap.sourcesContent
  22845. });
  22846. },
  22847. info: getLogHandler(pluginContext.info),
  22848. setAssetSource() {
  22849. return this.error(logInvalidSetAssetSourceCall());
  22850. },
  22851. warn: getLogHandler(pluginContext.warn)
  22852. };
  22853. });
  22854. }
  22855. catch (error_) {
  22856. return error(logPluginError(error_, pluginName, { hook: 'transform', id }));
  22857. }
  22858. if (!customTransformCache && // files emitted by a transform hook need to be emitted again if the hook is skipped
  22859. emittedFiles.length > 0)
  22860. module.transformFiles = emittedFiles;
  22861. return {
  22862. ast,
  22863. code,
  22864. customTransformCache,
  22865. originalCode,
  22866. originalSourcemap,
  22867. sourcemapChain,
  22868. transformDependencies
  22869. };
  22870. }
  22871. const RESOLVE_DEPENDENCIES = 'resolveDependencies';
  22872. class ModuleLoader {
  22873. constructor(graph, modulesById, options, pluginDriver) {
  22874. this.graph = graph;
  22875. this.modulesById = modulesById;
  22876. this.options = options;
  22877. this.pluginDriver = pluginDriver;
  22878. this.implicitEntryModules = new Set();
  22879. this.indexedEntryModules = [];
  22880. this.latestLoadModulesPromise = Promise.resolve();
  22881. this.moduleLoadPromises = new Map();
  22882. this.modulesWithLoadedDependencies = new Set();
  22883. this.nextChunkNamePriority = 0;
  22884. this.nextEntryModuleIndex = 0;
  22885. this.resolveId = async (source, importer, customOptions, isEntry, assertions, skip = null) => this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(this.options.external(source, importer, false)
  22886. ? false
  22887. : await resolveId(source, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, skip, customOptions, typeof isEntry === 'boolean' ? isEntry : !importer, assertions), importer, source), assertions);
  22888. this.hasModuleSideEffects = options.treeshake
  22889. ? options.treeshake.moduleSideEffects
  22890. : () => true;
  22891. }
  22892. async addAdditionalModules(unresolvedModules, isAddForManualChunks) {
  22893. const result = this.extendLoadModulesPromise(Promise.all(unresolvedModules.map(id => this.loadEntryModule(id, false, undefined, null, isAddForManualChunks))));
  22894. await this.awaitLoadModulesPromise();
  22895. return result;
  22896. }
  22897. async addEntryModules(unresolvedEntryModules, isUserDefined) {
  22898. const firstEntryModuleIndex = this.nextEntryModuleIndex;
  22899. this.nextEntryModuleIndex += unresolvedEntryModules.length;
  22900. const firstChunkNamePriority = this.nextChunkNamePriority;
  22901. this.nextChunkNamePriority += unresolvedEntryModules.length;
  22902. const newEntryModules = await this.extendLoadModulesPromise(Promise.all(unresolvedEntryModules.map(({ id, importer }) => this.loadEntryModule(id, true, importer, null))).then(entryModules => {
  22903. for (const [index, entryModule] of entryModules.entries()) {
  22904. entryModule.isUserDefinedEntryPoint =
  22905. entryModule.isUserDefinedEntryPoint || isUserDefined;
  22906. addChunkNamesToModule(entryModule, unresolvedEntryModules[index], isUserDefined, firstChunkNamePriority + index);
  22907. const existingIndexedModule = this.indexedEntryModules.find(indexedModule => indexedModule.module === entryModule);
  22908. if (existingIndexedModule) {
  22909. existingIndexedModule.index = Math.min(existingIndexedModule.index, firstEntryModuleIndex + index);
  22910. }
  22911. else {
  22912. this.indexedEntryModules.push({
  22913. index: firstEntryModuleIndex + index,
  22914. module: entryModule
  22915. });
  22916. }
  22917. }
  22918. this.indexedEntryModules.sort(({ index: indexA }, { index: indexB }) => indexA > indexB ? 1 : -1);
  22919. return entryModules;
  22920. }));
  22921. await this.awaitLoadModulesPromise();
  22922. return {
  22923. entryModules: this.indexedEntryModules.map(({ module }) => module),
  22924. implicitEntryModules: [...this.implicitEntryModules],
  22925. newEntryModules
  22926. };
  22927. }
  22928. async emitChunk({ fileName, id, importer, name, implicitlyLoadedAfterOneOf, preserveSignature }) {
  22929. const unresolvedModule = {
  22930. fileName: fileName || null,
  22931. id,
  22932. importer,
  22933. name: name || null
  22934. };
  22935. const module = implicitlyLoadedAfterOneOf
  22936. ? await this.addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfterOneOf)
  22937. : (await this.addEntryModules([unresolvedModule], false)).newEntryModules[0];
  22938. if (preserveSignature != null) {
  22939. module.preserveSignature = preserveSignature;
  22940. }
  22941. return module;
  22942. }
  22943. async preloadModule(resolvedId) {
  22944. const module = await this.fetchModule(this.getResolvedIdWithDefaults(resolvedId, EMPTY_OBJECT), undefined, false, resolvedId.resolveDependencies ? RESOLVE_DEPENDENCIES : true);
  22945. return module.info;
  22946. }
  22947. addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfter) {
  22948. const chunkNamePriority = this.nextChunkNamePriority++;
  22949. return this.extendLoadModulesPromise(this.loadEntryModule(unresolvedModule.id, false, unresolvedModule.importer, null).then(async (entryModule) => {
  22950. addChunkNamesToModule(entryModule, unresolvedModule, false, chunkNamePriority);
  22951. if (!entryModule.info.isEntry) {
  22952. this.implicitEntryModules.add(entryModule);
  22953. const implicitlyLoadedAfterModules = await Promise.all(implicitlyLoadedAfter.map(id => this.loadEntryModule(id, false, unresolvedModule.importer, entryModule.id)));
  22954. for (const module of implicitlyLoadedAfterModules) {
  22955. entryModule.implicitlyLoadedAfter.add(module);
  22956. }
  22957. for (const dependant of entryModule.implicitlyLoadedAfter) {
  22958. dependant.implicitlyLoadedBefore.add(entryModule);
  22959. }
  22960. }
  22961. return entryModule;
  22962. }));
  22963. }
  22964. async addModuleSource(id, importer, module) {
  22965. let source;
  22966. try {
  22967. source = await this.graph.fileOperationQueue.run(async () => (await this.pluginDriver.hookFirst('load', [id])) ?? (await readFile(id, 'utf8')));
  22968. }
  22969. catch (error_) {
  22970. let message = `Could not load ${id}`;
  22971. if (importer)
  22972. message += ` (imported by ${relativeId(importer)})`;
  22973. message += `: ${error_.message}`;
  22974. error_.message = message;
  22975. throw error_;
  22976. }
  22977. const sourceDescription = typeof source === 'string'
  22978. ? { code: source }
  22979. : source != null && typeof source === 'object' && typeof source.code === 'string'
  22980. ? source
  22981. : error(logBadLoader(id));
  22982. const cachedModule = this.graph.cachedModules.get(id);
  22983. if (cachedModule &&
  22984. !cachedModule.customTransformCache &&
  22985. cachedModule.originalCode === sourceDescription.code &&
  22986. !(await this.pluginDriver.hookFirst('shouldTransformCachedModule', [
  22987. {
  22988. ast: cachedModule.ast,
  22989. code: cachedModule.code,
  22990. id: cachedModule.id,
  22991. meta: cachedModule.meta,
  22992. moduleSideEffects: cachedModule.moduleSideEffects,
  22993. resolvedSources: cachedModule.resolvedIds,
  22994. syntheticNamedExports: cachedModule.syntheticNamedExports
  22995. }
  22996. ]))) {
  22997. if (cachedModule.transformFiles) {
  22998. for (const emittedFile of cachedModule.transformFiles)
  22999. this.pluginDriver.emitFile(emittedFile);
  23000. }
  23001. module.setSource(cachedModule);
  23002. }
  23003. else {
  23004. module.updateOptions(sourceDescription);
  23005. module.setSource(await transform(sourceDescription, module, this.pluginDriver, this.options.onLog));
  23006. }
  23007. }
  23008. async awaitLoadModulesPromise() {
  23009. let startingPromise;
  23010. do {
  23011. startingPromise = this.latestLoadModulesPromise;
  23012. await startingPromise;
  23013. } while (startingPromise !== this.latestLoadModulesPromise);
  23014. }
  23015. extendLoadModulesPromise(loadNewModulesPromise) {
  23016. this.latestLoadModulesPromise = Promise.all([
  23017. loadNewModulesPromise,
  23018. this.latestLoadModulesPromise
  23019. ]);
  23020. this.latestLoadModulesPromise.catch(() => {
  23021. /* Avoid unhandled Promise rejections */
  23022. });
  23023. return loadNewModulesPromise;
  23024. }
  23025. async fetchDynamicDependencies(module, resolveDynamicImportPromises) {
  23026. const dependencies = await Promise.all(resolveDynamicImportPromises.map(resolveDynamicImportPromise => resolveDynamicImportPromise.then(async ([dynamicImport, resolvedId]) => {
  23027. if (resolvedId === null)
  23028. return null;
  23029. if (typeof resolvedId === 'string') {
  23030. dynamicImport.resolution = resolvedId;
  23031. return null;
  23032. }
  23033. return (dynamicImport.resolution = await this.fetchResolvedDependency(relativeId(resolvedId.id), module.id, resolvedId));
  23034. })));
  23035. for (const dependency of dependencies) {
  23036. if (dependency) {
  23037. module.dynamicDependencies.add(dependency);
  23038. dependency.dynamicImporters.push(module.id);
  23039. }
  23040. }
  23041. }
  23042. // If this is a preload, then this method always waits for the dependencies of
  23043. // the module to be resolved.
  23044. // Otherwise, if the module does not exist, it waits for the module and all
  23045. // its dependencies to be loaded.
  23046. // Otherwise, it returns immediately.
  23047. async fetchModule({ assertions, id, meta, moduleSideEffects, syntheticNamedExports }, importer, isEntry, isPreload) {
  23048. const existingModule = this.modulesById.get(id);
  23049. if (existingModule instanceof Module) {
  23050. if (importer && doAssertionsDiffer(assertions, existingModule.info.assertions)) {
  23051. this.options.onLog(LOGLEVEL_WARN, logInconsistentImportAssertions(existingModule.info.assertions, assertions, id, importer));
  23052. }
  23053. await this.handleExistingModule(existingModule, isEntry, isPreload);
  23054. return existingModule;
  23055. }
  23056. if (existingModule instanceof ExternalModule) {
  23057. return error(logExternalModulesCannotBeTransformedToModules(existingModule.id));
  23058. }
  23059. const module = new Module(this.graph, id, this.options, isEntry, moduleSideEffects, syntheticNamedExports, meta, assertions);
  23060. this.modulesById.set(id, module);
  23061. this.graph.watchFiles[id] = true;
  23062. const loadPromise = this.addModuleSource(id, importer, module).then(() => [
  23063. this.getResolveStaticDependencyPromises(module),
  23064. this.getResolveDynamicImportPromises(module),
  23065. loadAndResolveDependenciesPromise
  23066. ]);
  23067. const loadAndResolveDependenciesPromise = waitForDependencyResolution(loadPromise).then(() => this.pluginDriver.hookParallel('moduleParsed', [module.info]));
  23068. loadAndResolveDependenciesPromise.catch(() => {
  23069. /* avoid unhandled promise rejections */
  23070. });
  23071. this.moduleLoadPromises.set(module, loadPromise);
  23072. const resolveDependencyPromises = await loadPromise;
  23073. if (!isPreload) {
  23074. await this.fetchModuleDependencies(module, ...resolveDependencyPromises);
  23075. }
  23076. else if (isPreload === RESOLVE_DEPENDENCIES) {
  23077. await loadAndResolveDependenciesPromise;
  23078. }
  23079. return module;
  23080. }
  23081. async fetchModuleDependencies(module, resolveStaticDependencyPromises, resolveDynamicDependencyPromises, loadAndResolveDependenciesPromise) {
  23082. if (this.modulesWithLoadedDependencies.has(module)) {
  23083. return;
  23084. }
  23085. this.modulesWithLoadedDependencies.add(module);
  23086. await Promise.all([
  23087. this.fetchStaticDependencies(module, resolveStaticDependencyPromises),
  23088. this.fetchDynamicDependencies(module, resolveDynamicDependencyPromises)
  23089. ]);
  23090. module.linkImports();
  23091. // To handle errors when resolving dependencies or in moduleParsed
  23092. await loadAndResolveDependenciesPromise;
  23093. }
  23094. fetchResolvedDependency(source, importer, resolvedId) {
  23095. if (resolvedId.external) {
  23096. const { assertions, external, id, moduleSideEffects, meta } = resolvedId;
  23097. let externalModule = this.modulesById.get(id);
  23098. if (!externalModule) {
  23099. externalModule = new ExternalModule(this.options, id, moduleSideEffects, meta, external !== 'absolute' && isAbsolute(id), assertions);
  23100. this.modulesById.set(id, externalModule);
  23101. }
  23102. else if (!(externalModule instanceof ExternalModule)) {
  23103. return error(logInternalIdCannotBeExternal(source, importer));
  23104. }
  23105. else if (doAssertionsDiffer(externalModule.info.assertions, assertions)) {
  23106. this.options.onLog(LOGLEVEL_WARN, logInconsistentImportAssertions(externalModule.info.assertions, assertions, source, importer));
  23107. }
  23108. return Promise.resolve(externalModule);
  23109. }
  23110. return this.fetchModule(resolvedId, importer, false, false);
  23111. }
  23112. async fetchStaticDependencies(module, resolveStaticDependencyPromises) {
  23113. for (const dependency of await Promise.all(resolveStaticDependencyPromises.map(resolveStaticDependencyPromise => resolveStaticDependencyPromise.then(([source, resolvedId]) => this.fetchResolvedDependency(source, module.id, resolvedId))))) {
  23114. module.dependencies.add(dependency);
  23115. dependency.importers.push(module.id);
  23116. }
  23117. if (!this.options.treeshake || module.info.moduleSideEffects === 'no-treeshake') {
  23118. for (const dependency of module.dependencies) {
  23119. if (dependency instanceof Module) {
  23120. dependency.importedFromNotTreeshaken = true;
  23121. }
  23122. }
  23123. }
  23124. }
  23125. getNormalizedResolvedIdWithoutDefaults(resolveIdResult, importer, source) {
  23126. const { makeAbsoluteExternalsRelative } = this.options;
  23127. if (resolveIdResult) {
  23128. if (typeof resolveIdResult === 'object') {
  23129. const external = resolveIdResult.external || this.options.external(resolveIdResult.id, importer, true);
  23130. return {
  23131. ...resolveIdResult,
  23132. external: external &&
  23133. (external === 'relative' ||
  23134. !isAbsolute(resolveIdResult.id) ||
  23135. (external === true &&
  23136. isNotAbsoluteExternal(resolveIdResult.id, source, makeAbsoluteExternalsRelative)) ||
  23137. 'absolute')
  23138. };
  23139. }
  23140. const external = this.options.external(resolveIdResult, importer, true);
  23141. return {
  23142. external: external &&
  23143. (isNotAbsoluteExternal(resolveIdResult, source, makeAbsoluteExternalsRelative) ||
  23144. 'absolute'),
  23145. id: external && makeAbsoluteExternalsRelative
  23146. ? normalizeRelativeExternalId(resolveIdResult, importer)
  23147. : resolveIdResult
  23148. };
  23149. }
  23150. const id = makeAbsoluteExternalsRelative
  23151. ? normalizeRelativeExternalId(source, importer)
  23152. : source;
  23153. if (resolveIdResult !== false && !this.options.external(id, importer, true)) {
  23154. return null;
  23155. }
  23156. return {
  23157. external: isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) || 'absolute',
  23158. id
  23159. };
  23160. }
  23161. getResolveDynamicImportPromises(module) {
  23162. return module.dynamicImports.map(async (dynamicImport) => {
  23163. const resolvedId = await this.resolveDynamicImport(module, typeof dynamicImport.argument === 'string'
  23164. ? dynamicImport.argument
  23165. : dynamicImport.argument.esTreeNode, module.id, getAssertionsFromImportExpression(dynamicImport.node));
  23166. if (resolvedId && typeof resolvedId === 'object') {
  23167. dynamicImport.id = resolvedId.id;
  23168. }
  23169. return [dynamicImport, resolvedId];
  23170. });
  23171. }
  23172. getResolveStaticDependencyPromises(module) {
  23173. // eslint-disable-next-line unicorn/prefer-spread
  23174. return Array.from(module.sourcesWithAssertions, async ([source, assertions]) => [
  23175. source,
  23176. (module.resolvedIds[source] =
  23177. module.resolvedIds[source] ||
  23178. this.handleInvalidResolvedId(await this.resolveId(source, module.id, EMPTY_OBJECT, false, assertions), source, module.id, assertions))
  23179. ]);
  23180. }
  23181. getResolvedIdWithDefaults(resolvedId, assertions) {
  23182. if (!resolvedId) {
  23183. return null;
  23184. }
  23185. const external = resolvedId.external || false;
  23186. return {
  23187. assertions: resolvedId.assertions || assertions,
  23188. external,
  23189. id: resolvedId.id,
  23190. meta: resolvedId.meta || {},
  23191. moduleSideEffects: resolvedId.moduleSideEffects ?? this.hasModuleSideEffects(resolvedId.id, !!external),
  23192. resolvedBy: resolvedId.resolvedBy ?? 'rollup',
  23193. syntheticNamedExports: resolvedId.syntheticNamedExports ?? false
  23194. };
  23195. }
  23196. async handleExistingModule(module, isEntry, isPreload) {
  23197. const loadPromise = this.moduleLoadPromises.get(module);
  23198. if (isPreload) {
  23199. return isPreload === RESOLVE_DEPENDENCIES
  23200. ? waitForDependencyResolution(loadPromise)
  23201. : loadPromise;
  23202. }
  23203. if (isEntry) {
  23204. module.info.isEntry = true;
  23205. this.implicitEntryModules.delete(module);
  23206. for (const dependant of module.implicitlyLoadedAfter) {
  23207. dependant.implicitlyLoadedBefore.delete(module);
  23208. }
  23209. module.implicitlyLoadedAfter.clear();
  23210. }
  23211. return this.fetchModuleDependencies(module, ...(await loadPromise));
  23212. }
  23213. handleInvalidResolvedId(resolvedId, source, importer, assertions) {
  23214. if (resolvedId === null) {
  23215. if (isRelative(source)) {
  23216. return error(logUnresolvedImport(source, importer));
  23217. }
  23218. this.options.onLog(LOGLEVEL_WARN, logUnresolvedImportTreatedAsExternal(source, importer));
  23219. return {
  23220. assertions,
  23221. external: true,
  23222. id: source,
  23223. meta: {},
  23224. moduleSideEffects: this.hasModuleSideEffects(source, true),
  23225. resolvedBy: 'rollup',
  23226. syntheticNamedExports: false
  23227. };
  23228. }
  23229. else if (resolvedId.external && resolvedId.syntheticNamedExports) {
  23230. this.options.onLog(LOGLEVEL_WARN, logExternalSyntheticExports(source, importer));
  23231. }
  23232. return resolvedId;
  23233. }
  23234. async loadEntryModule(unresolvedId, isEntry, importer, implicitlyLoadedBefore, isLoadForManualChunks = false) {
  23235. const resolveIdResult = await resolveId(unresolvedId, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, null, EMPTY_OBJECT, true, EMPTY_OBJECT);
  23236. if (resolveIdResult == null) {
  23237. return error(implicitlyLoadedBefore === null
  23238. ? logUnresolvedEntry(unresolvedId)
  23239. : logUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore));
  23240. }
  23241. const isExternalModules = typeof resolveIdResult === 'object' && resolveIdResult.external;
  23242. if (resolveIdResult === false || isExternalModules) {
  23243. return error(implicitlyLoadedBefore === null
  23244. ? isExternalModules && isLoadForManualChunks
  23245. ? logExternalModulesCannotBeIncludedInManualChunks(unresolvedId)
  23246. : logEntryCannotBeExternal(unresolvedId)
  23247. : logImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore));
  23248. }
  23249. return this.fetchModule(this.getResolvedIdWithDefaults(typeof resolveIdResult === 'object'
  23250. ? resolveIdResult
  23251. : { id: resolveIdResult }, EMPTY_OBJECT), undefined, isEntry, false);
  23252. }
  23253. async resolveDynamicImport(module, specifier, importer, assertions) {
  23254. const resolution = await this.pluginDriver.hookFirst('resolveDynamicImport', [
  23255. specifier,
  23256. importer,
  23257. { assertions }
  23258. ]);
  23259. if (typeof specifier !== 'string') {
  23260. if (typeof resolution === 'string') {
  23261. return resolution;
  23262. }
  23263. if (!resolution) {
  23264. return null;
  23265. }
  23266. return this.getResolvedIdWithDefaults(resolution, assertions);
  23267. }
  23268. if (resolution == null) {
  23269. const existingResolution = module.resolvedIds[specifier];
  23270. if (existingResolution) {
  23271. if (doAssertionsDiffer(existingResolution.assertions, assertions)) {
  23272. this.options.onLog(LOGLEVEL_WARN, logInconsistentImportAssertions(existingResolution.assertions, assertions, specifier, importer));
  23273. }
  23274. return existingResolution;
  23275. }
  23276. return (module.resolvedIds[specifier] = this.handleInvalidResolvedId(await this.resolveId(specifier, module.id, EMPTY_OBJECT, false, assertions), specifier, module.id, assertions));
  23277. }
  23278. return this.handleInvalidResolvedId(this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(resolution, importer, specifier), assertions), specifier, importer, assertions);
  23279. }
  23280. }
  23281. function normalizeRelativeExternalId(source, importer) {
  23282. return isRelative(source)
  23283. ? importer
  23284. ? resolve(importer, '..', source)
  23285. : resolve(source)
  23286. : source;
  23287. }
  23288. function addChunkNamesToModule(module, { fileName, name }, isUserDefined, priority) {
  23289. if (fileName !== null) {
  23290. module.chunkFileNames.add(fileName);
  23291. }
  23292. else if (name !== null) {
  23293. // Always keep chunkNames sorted by priority
  23294. let namePosition = 0;
  23295. while (module.chunkNames[namePosition]?.priority < priority)
  23296. namePosition++;
  23297. module.chunkNames.splice(namePosition, 0, { isUserDefined, name, priority });
  23298. }
  23299. }
  23300. function isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) {
  23301. return (makeAbsoluteExternalsRelative === true ||
  23302. (makeAbsoluteExternalsRelative === 'ifRelativeSource' && isRelative(source)) ||
  23303. !isAbsolute(id));
  23304. }
  23305. async function waitForDependencyResolution(loadPromise) {
  23306. const [resolveStaticDependencyPromises, resolveDynamicImportPromises] = await loadPromise;
  23307. return Promise.all([...resolveStaticDependencyPromises, ...resolveDynamicImportPromises]);
  23308. }
  23309. class GlobalScope extends Scope$1 {
  23310. constructor() {
  23311. super();
  23312. this.parent = null;
  23313. this.variables.set('undefined', new UndefinedVariable());
  23314. }
  23315. findVariable(name) {
  23316. let variable = this.variables.get(name);
  23317. if (!variable) {
  23318. variable = new GlobalVariable(name);
  23319. this.variables.set(name, variable);
  23320. }
  23321. return variable;
  23322. }
  23323. }
  23324. function getSourceHash(source) {
  23325. return createHash().update(source).digest('hex');
  23326. }
  23327. function generateAssetFileName(name, source, sourceHash, outputOptions, bundle) {
  23328. const emittedName = outputOptions.sanitizeFileName(name || 'asset');
  23329. return makeUnique(renderNamePattern(typeof outputOptions.assetFileNames === 'function'
  23330. ? outputOptions.assetFileNames({ name, source, type: 'asset' })
  23331. : outputOptions.assetFileNames, 'output.assetFileNames', {
  23332. ext: () => extname(emittedName).slice(1),
  23333. extname: () => extname(emittedName),
  23334. hash: size => sourceHash.slice(0, Math.max(0, size || defaultHashSize)),
  23335. name: () => emittedName.slice(0, Math.max(0, emittedName.length - extname(emittedName).length))
  23336. }), bundle);
  23337. }
  23338. function reserveFileNameInBundle(fileName, { bundle }, log) {
  23339. if (bundle[lowercaseBundleKeys].has(fileName.toLowerCase())) {
  23340. log(LOGLEVEL_WARN, logFileNameConflict(fileName));
  23341. }
  23342. else {
  23343. bundle[fileName] = FILE_PLACEHOLDER;
  23344. }
  23345. }
  23346. const emittedFileTypes = new Set(['chunk', 'asset', 'prebuilt-chunk']);
  23347. function hasValidType(emittedFile) {
  23348. return Boolean(emittedFile &&
  23349. emittedFileTypes.has(emittedFile.type));
  23350. }
  23351. function hasValidName(emittedFile) {
  23352. const validatedName = emittedFile.fileName || emittedFile.name;
  23353. return !validatedName || (typeof validatedName === 'string' && !isPathFragment(validatedName));
  23354. }
  23355. function getValidSource(source, emittedFile, fileReferenceId) {
  23356. if (!(typeof source === 'string' || source instanceof Uint8Array)) {
  23357. const assetName = emittedFile.fileName || emittedFile.name || fileReferenceId;
  23358. return error(logFailedValidation(`Could not set source for ${typeof assetName === 'string' ? `asset "${assetName}"` : 'unnamed asset'}, asset source needs to be a string, Uint8Array or Buffer.`));
  23359. }
  23360. return source;
  23361. }
  23362. function getAssetFileName(file, referenceId) {
  23363. if (typeof file.fileName !== 'string') {
  23364. return error(logAssetNotFinalisedForFileName(file.name || referenceId));
  23365. }
  23366. return file.fileName;
  23367. }
  23368. function getChunkFileName(file, facadeChunkByModule) {
  23369. if (file.fileName) {
  23370. return file.fileName;
  23371. }
  23372. if (facadeChunkByModule) {
  23373. return facadeChunkByModule.get(file.module).getFileName();
  23374. }
  23375. return error(logChunkNotGeneratedForFileName(file.fileName || file.name));
  23376. }
  23377. class FileEmitter {
  23378. constructor(graph, options, baseFileEmitter) {
  23379. this.graph = graph;
  23380. this.options = options;
  23381. this.facadeChunkByModule = null;
  23382. this.nextIdBase = 1;
  23383. this.output = null;
  23384. this.outputFileEmitters = [];
  23385. this.emitFile = (emittedFile) => {
  23386. if (!hasValidType(emittedFile)) {
  23387. return error(logFailedValidation(`Emitted files must be of type "asset", "chunk" or "prebuilt-chunk", received "${emittedFile && emittedFile.type}".`));
  23388. }
  23389. if (emittedFile.type === 'prebuilt-chunk') {
  23390. return this.emitPrebuiltChunk(emittedFile);
  23391. }
  23392. if (!hasValidName(emittedFile)) {
  23393. return error(logFailedValidation(`The "fileName" or "name" properties of emitted chunks and assets must be strings that are neither absolute nor relative paths, received "${emittedFile.fileName || emittedFile.name}".`));
  23394. }
  23395. if (emittedFile.type === 'chunk') {
  23396. return this.emitChunk(emittedFile);
  23397. }
  23398. return this.emitAsset(emittedFile);
  23399. };
  23400. this.finaliseAssets = () => {
  23401. for (const [referenceId, emittedFile] of this.filesByReferenceId) {
  23402. if (emittedFile.type === 'asset' && typeof emittedFile.fileName !== 'string')
  23403. return error(logNoAssetSourceSet(emittedFile.name || referenceId));
  23404. }
  23405. };
  23406. this.getFileName = (fileReferenceId) => {
  23407. const emittedFile = this.filesByReferenceId.get(fileReferenceId);
  23408. if (!emittedFile)
  23409. return error(logFileReferenceIdNotFoundForFilename(fileReferenceId));
  23410. if (emittedFile.type === 'chunk') {
  23411. return getChunkFileName(emittedFile, this.facadeChunkByModule);
  23412. }
  23413. if (emittedFile.type === 'prebuilt-chunk') {
  23414. return emittedFile.fileName;
  23415. }
  23416. return getAssetFileName(emittedFile, fileReferenceId);
  23417. };
  23418. this.setAssetSource = (referenceId, requestedSource) => {
  23419. const consumedFile = this.filesByReferenceId.get(referenceId);
  23420. if (!consumedFile)
  23421. return error(logAssetReferenceIdNotFoundForSetSource(referenceId));
  23422. if (consumedFile.type !== 'asset') {
  23423. return error(logFailedValidation(`Asset sources can only be set for emitted assets but "${referenceId}" is an emitted chunk.`));
  23424. }
  23425. if (consumedFile.source !== undefined) {
  23426. return error(logAssetSourceAlreadySet(consumedFile.name || referenceId));
  23427. }
  23428. const source = getValidSource(requestedSource, consumedFile, referenceId);
  23429. if (this.output) {
  23430. this.finalizeAdditionalAsset(consumedFile, source, this.output);
  23431. }
  23432. else {
  23433. consumedFile.source = source;
  23434. for (const emitter of this.outputFileEmitters) {
  23435. emitter.finalizeAdditionalAsset(consumedFile, source, emitter.output);
  23436. }
  23437. }
  23438. };
  23439. this.setChunkInformation = (facadeChunkByModule) => {
  23440. this.facadeChunkByModule = facadeChunkByModule;
  23441. };
  23442. this.setOutputBundle = (bundle, outputOptions) => {
  23443. const output = (this.output = {
  23444. bundle,
  23445. fileNamesBySource: new Map(),
  23446. outputOptions
  23447. });
  23448. for (const emittedFile of this.filesByReferenceId.values()) {
  23449. if (emittedFile.fileName) {
  23450. reserveFileNameInBundle(emittedFile.fileName, output, this.options.onLog);
  23451. }
  23452. }
  23453. const consumedAssetsByHash = new Map();
  23454. for (const consumedFile of this.filesByReferenceId.values()) {
  23455. if (consumedFile.type === 'asset' && consumedFile.source !== undefined) {
  23456. if (consumedFile.fileName) {
  23457. this.finalizeAdditionalAsset(consumedFile, consumedFile.source, output);
  23458. }
  23459. else {
  23460. const sourceHash = getSourceHash(consumedFile.source);
  23461. getOrCreate(consumedAssetsByHash, sourceHash, () => []).push(consumedFile);
  23462. }
  23463. }
  23464. else if (consumedFile.type === 'prebuilt-chunk') {
  23465. this.output.bundle[consumedFile.fileName] = this.createPrebuiltChunk(consumedFile);
  23466. }
  23467. }
  23468. for (const [sourceHash, consumedFiles] of consumedAssetsByHash) {
  23469. this.finalizeAssetsWithSameSource(consumedFiles, sourceHash, output);
  23470. }
  23471. };
  23472. this.filesByReferenceId = baseFileEmitter
  23473. ? new Map(baseFileEmitter.filesByReferenceId)
  23474. : new Map();
  23475. baseFileEmitter?.addOutputFileEmitter(this);
  23476. }
  23477. addOutputFileEmitter(outputFileEmitter) {
  23478. this.outputFileEmitters.push(outputFileEmitter);
  23479. }
  23480. assignReferenceId(file, idBase) {
  23481. let referenceId = idBase;
  23482. do {
  23483. referenceId = createHash().update(referenceId).digest('hex').slice(0, 8);
  23484. } while (this.filesByReferenceId.has(referenceId) ||
  23485. this.outputFileEmitters.some(({ filesByReferenceId }) => filesByReferenceId.has(referenceId)));
  23486. file.referenceId = referenceId;
  23487. this.filesByReferenceId.set(referenceId, file);
  23488. for (const { filesByReferenceId } of this.outputFileEmitters) {
  23489. filesByReferenceId.set(referenceId, file);
  23490. }
  23491. return referenceId;
  23492. }
  23493. createPrebuiltChunk(prebuiltChunk) {
  23494. return {
  23495. code: prebuiltChunk.code,
  23496. dynamicImports: [],
  23497. exports: prebuiltChunk.exports || [],
  23498. facadeModuleId: null,
  23499. fileName: prebuiltChunk.fileName,
  23500. implicitlyLoadedBefore: [],
  23501. importedBindings: {},
  23502. imports: [],
  23503. isDynamicEntry: false,
  23504. isEntry: false,
  23505. isImplicitEntry: false,
  23506. map: prebuiltChunk.map || null,
  23507. moduleIds: [],
  23508. modules: {},
  23509. name: prebuiltChunk.fileName,
  23510. preliminaryFileName: prebuiltChunk.fileName,
  23511. referencedFiles: [],
  23512. sourcemapFileName: prebuiltChunk.sourcemapFileName || null,
  23513. type: 'chunk'
  23514. };
  23515. }
  23516. emitAsset(emittedAsset) {
  23517. const source = emittedAsset.source === undefined
  23518. ? undefined
  23519. : getValidSource(emittedAsset.source, emittedAsset, null);
  23520. const consumedAsset = {
  23521. fileName: emittedAsset.fileName,
  23522. name: emittedAsset.name,
  23523. needsCodeReference: !!emittedAsset.needsCodeReference,
  23524. referenceId: '',
  23525. source,
  23526. type: 'asset'
  23527. };
  23528. const referenceId = this.assignReferenceId(consumedAsset, emittedAsset.fileName || emittedAsset.name || String(this.nextIdBase++));
  23529. if (this.output) {
  23530. this.emitAssetWithReferenceId(consumedAsset, this.output);
  23531. }
  23532. else {
  23533. for (const fileEmitter of this.outputFileEmitters) {
  23534. fileEmitter.emitAssetWithReferenceId(consumedAsset, fileEmitter.output);
  23535. }
  23536. }
  23537. return referenceId;
  23538. }
  23539. emitAssetWithReferenceId(consumedAsset, output) {
  23540. const { fileName, source } = consumedAsset;
  23541. if (fileName) {
  23542. reserveFileNameInBundle(fileName, output, this.options.onLog);
  23543. }
  23544. if (source !== undefined) {
  23545. this.finalizeAdditionalAsset(consumedAsset, source, output);
  23546. }
  23547. }
  23548. emitChunk(emittedChunk) {
  23549. if (this.graph.phase > BuildPhase.LOAD_AND_PARSE) {
  23550. return error(logInvalidRollupPhaseForChunkEmission());
  23551. }
  23552. if (typeof emittedChunk.id !== 'string') {
  23553. return error(logFailedValidation(`Emitted chunks need to have a valid string id, received "${emittedChunk.id}"`));
  23554. }
  23555. const consumedChunk = {
  23556. fileName: emittedChunk.fileName,
  23557. module: null,
  23558. name: emittedChunk.name || emittedChunk.id,
  23559. referenceId: '',
  23560. type: 'chunk'
  23561. };
  23562. this.graph.moduleLoader
  23563. .emitChunk(emittedChunk)
  23564. .then(module => (consumedChunk.module = module))
  23565. .catch(() => {
  23566. // Avoid unhandled Promise rejection as the error will be thrown later
  23567. // once module loading has finished
  23568. });
  23569. return this.assignReferenceId(consumedChunk, emittedChunk.id);
  23570. }
  23571. emitPrebuiltChunk(emitPrebuiltChunk) {
  23572. if (typeof emitPrebuiltChunk.code !== 'string') {
  23573. return error(logFailedValidation(`Emitted prebuilt chunks need to have a valid string code, received "${emitPrebuiltChunk.code}".`));
  23574. }
  23575. if (typeof emitPrebuiltChunk.fileName !== 'string' ||
  23576. isPathFragment(emitPrebuiltChunk.fileName)) {
  23577. return error(logFailedValidation(`The "fileName" property of emitted prebuilt chunks must be strings that are neither absolute nor relative paths, received "${emitPrebuiltChunk.fileName}".`));
  23578. }
  23579. const consumedPrebuiltChunk = {
  23580. code: emitPrebuiltChunk.code,
  23581. exports: emitPrebuiltChunk.exports,
  23582. fileName: emitPrebuiltChunk.fileName,
  23583. map: emitPrebuiltChunk.map,
  23584. referenceId: '',
  23585. type: 'prebuilt-chunk'
  23586. };
  23587. const referenceId = this.assignReferenceId(consumedPrebuiltChunk, consumedPrebuiltChunk.fileName);
  23588. if (this.output) {
  23589. this.output.bundle[consumedPrebuiltChunk.fileName] =
  23590. this.createPrebuiltChunk(consumedPrebuiltChunk);
  23591. }
  23592. return referenceId;
  23593. }
  23594. finalizeAdditionalAsset(consumedFile, source, { bundle, fileNamesBySource, outputOptions }) {
  23595. let { fileName, needsCodeReference, referenceId } = consumedFile;
  23596. // Deduplicate assets if an explicit fileName is not provided
  23597. if (!fileName) {
  23598. const sourceHash = getSourceHash(source);
  23599. fileName = fileNamesBySource.get(sourceHash);
  23600. if (!fileName) {
  23601. fileName = generateAssetFileName(consumedFile.name, source, sourceHash, outputOptions, bundle);
  23602. fileNamesBySource.set(sourceHash, fileName);
  23603. }
  23604. }
  23605. // We must not modify the original assets to avoid interaction between outputs
  23606. const assetWithFileName = { ...consumedFile, fileName, source };
  23607. this.filesByReferenceId.set(referenceId, assetWithFileName);
  23608. const existingAsset = bundle[fileName];
  23609. if (existingAsset?.type === 'asset') {
  23610. existingAsset.needsCodeReference && (existingAsset.needsCodeReference = needsCodeReference);
  23611. }
  23612. else {
  23613. bundle[fileName] = {
  23614. fileName,
  23615. name: consumedFile.name,
  23616. needsCodeReference,
  23617. source,
  23618. type: 'asset'
  23619. };
  23620. }
  23621. }
  23622. finalizeAssetsWithSameSource(consumedFiles, sourceHash, { bundle, fileNamesBySource, outputOptions }) {
  23623. let fileName = '';
  23624. let usedConsumedFile;
  23625. let needsCodeReference = true;
  23626. for (const consumedFile of consumedFiles) {
  23627. needsCodeReference && (needsCodeReference = consumedFile.needsCodeReference);
  23628. const assetFileName = generateAssetFileName(consumedFile.name, consumedFile.source, sourceHash, outputOptions, bundle);
  23629. if (!fileName ||
  23630. assetFileName.length < fileName.length ||
  23631. (assetFileName.length === fileName.length && assetFileName < fileName)) {
  23632. fileName = assetFileName;
  23633. usedConsumedFile = consumedFile;
  23634. }
  23635. }
  23636. fileNamesBySource.set(sourceHash, fileName);
  23637. for (const consumedFile of consumedFiles) {
  23638. // We must not modify the original assets to avoid interaction between outputs
  23639. const assetWithFileName = { ...consumedFile, fileName };
  23640. this.filesByReferenceId.set(consumedFile.referenceId, assetWithFileName);
  23641. }
  23642. bundle[fileName] = {
  23643. fileName,
  23644. name: usedConsumedFile.name,
  23645. needsCodeReference,
  23646. source: usedConsumedFile.source,
  23647. type: 'asset'
  23648. };
  23649. }
  23650. }
  23651. function getLogHandler(level, code, logger, pluginName, logLevel) {
  23652. if (logLevelPriority[level] < logLevelPriority[logLevel]) {
  23653. return doNothing;
  23654. }
  23655. return (log, pos) => {
  23656. if (pos != null) {
  23657. logger(LOGLEVEL_WARN, logInvalidLogPosition(pluginName));
  23658. }
  23659. log = normalizeLog(log);
  23660. if (log.code && !log.pluginCode) {
  23661. log.pluginCode = log.code;
  23662. }
  23663. log.code = code;
  23664. log.plugin = pluginName;
  23665. logger(level, log);
  23666. };
  23667. }
  23668. function getPluginContext(plugin, pluginCache, graph, options, fileEmitter, existingPluginNames) {
  23669. const { logLevel, onLog } = options;
  23670. let cacheable = true;
  23671. if (typeof plugin.cacheKey !== 'string') {
  23672. if (plugin.name.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  23673. plugin.name.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX) ||
  23674. existingPluginNames.has(plugin.name)) {
  23675. cacheable = false;
  23676. }
  23677. else {
  23678. existingPluginNames.add(plugin.name);
  23679. }
  23680. }
  23681. let cacheInstance;
  23682. if (!pluginCache) {
  23683. cacheInstance = NO_CACHE;
  23684. }
  23685. else if (cacheable) {
  23686. const cacheKey = plugin.cacheKey || plugin.name;
  23687. cacheInstance = createPluginCache(pluginCache[cacheKey] || (pluginCache[cacheKey] = Object.create(null)));
  23688. }
  23689. else {
  23690. cacheInstance = getCacheForUncacheablePlugin(plugin.name);
  23691. }
  23692. return {
  23693. addWatchFile(id) {
  23694. if (graph.phase >= BuildPhase.GENERATE) {
  23695. return this.error(logInvalidRollupPhaseForAddWatchFile());
  23696. }
  23697. graph.watchFiles[id] = true;
  23698. },
  23699. cache: cacheInstance,
  23700. debug: getLogHandler(LOGLEVEL_DEBUG, 'PLUGIN_LOG', onLog, plugin.name, logLevel),
  23701. emitFile: fileEmitter.emitFile.bind(fileEmitter),
  23702. error(error_) {
  23703. return error(logPluginError(normalizeLog(error_), plugin.name));
  23704. },
  23705. getFileName: fileEmitter.getFileName,
  23706. getModuleIds: () => graph.modulesById.keys(),
  23707. getModuleInfo: graph.getModuleInfo,
  23708. getWatchFiles: () => Object.keys(graph.watchFiles),
  23709. info: getLogHandler(LOGLEVEL_INFO, 'PLUGIN_LOG', onLog, plugin.name, logLevel),
  23710. load(resolvedId) {
  23711. return graph.moduleLoader.preloadModule(resolvedId);
  23712. },
  23713. meta: {
  23714. rollupVersion: version$1,
  23715. watchMode: graph.watchMode
  23716. },
  23717. get moduleIds() {
  23718. function* wrappedModuleIds() {
  23719. // We are wrapping this in a generator to only show the message once we are actually iterating
  23720. warnDeprecation(`Accessing "this.moduleIds" on the plugin context by plugin ${plugin.name} is deprecated. The "this.getModuleIds" plugin context function should be used instead.`, URL_THIS_GETMODULEIDS, true, options, plugin.name);
  23721. yield* moduleIds;
  23722. }
  23723. const moduleIds = graph.modulesById.keys();
  23724. return wrappedModuleIds();
  23725. },
  23726. parse: graph.contextParse.bind(graph),
  23727. resolve(source, importer, { assertions, custom, isEntry, skipSelf } = BLANK) {
  23728. return graph.moduleLoader.resolveId(source, importer, custom, isEntry, assertions || EMPTY_OBJECT, skipSelf ? [{ importer, plugin, source }] : null);
  23729. },
  23730. setAssetSource: fileEmitter.setAssetSource,
  23731. warn: getLogHandler(LOGLEVEL_WARN, 'PLUGIN_WARNING', onLog, plugin.name, logLevel)
  23732. };
  23733. }
  23734. // This will make sure no input hook is omitted
  23735. const inputHookNames = {
  23736. buildEnd: 1,
  23737. buildStart: 1,
  23738. closeBundle: 1,
  23739. closeWatcher: 1,
  23740. load: 1,
  23741. moduleParsed: 1,
  23742. onLog: 1,
  23743. options: 1,
  23744. resolveDynamicImport: 1,
  23745. resolveId: 1,
  23746. shouldTransformCachedModule: 1,
  23747. transform: 1,
  23748. watchChange: 1
  23749. };
  23750. const inputHooks = Object.keys(inputHookNames);
  23751. class PluginDriver {
  23752. constructor(graph, options, userPlugins, pluginCache, basePluginDriver) {
  23753. this.graph = graph;
  23754. this.options = options;
  23755. this.pluginCache = pluginCache;
  23756. this.sortedPlugins = new Map();
  23757. this.unfulfilledActions = new Set();
  23758. this.fileEmitter = new FileEmitter(graph, options, basePluginDriver && basePluginDriver.fileEmitter);
  23759. this.emitFile = this.fileEmitter.emitFile.bind(this.fileEmitter);
  23760. this.getFileName = this.fileEmitter.getFileName.bind(this.fileEmitter);
  23761. this.finaliseAssets = this.fileEmitter.finaliseAssets.bind(this.fileEmitter);
  23762. this.setChunkInformation = this.fileEmitter.setChunkInformation.bind(this.fileEmitter);
  23763. this.setOutputBundle = this.fileEmitter.setOutputBundle.bind(this.fileEmitter);
  23764. this.plugins = [...(basePluginDriver ? basePluginDriver.plugins : []), ...userPlugins];
  23765. const existingPluginNames = new Set();
  23766. this.pluginContexts = new Map(this.plugins.map(plugin => [
  23767. plugin,
  23768. getPluginContext(plugin, pluginCache, graph, options, this.fileEmitter, existingPluginNames)
  23769. ]));
  23770. if (basePluginDriver) {
  23771. for (const plugin of userPlugins) {
  23772. for (const hook of inputHooks) {
  23773. if (hook in plugin) {
  23774. options.onLog(LOGLEVEL_WARN, logInputHookInOutputPlugin(plugin.name, hook));
  23775. }
  23776. }
  23777. }
  23778. }
  23779. }
  23780. createOutputPluginDriver(plugins) {
  23781. return new PluginDriver(this.graph, this.options, plugins, this.pluginCache, this);
  23782. }
  23783. getUnfulfilledHookActions() {
  23784. return this.unfulfilledActions;
  23785. }
  23786. // chains, first non-null result stops and returns
  23787. hookFirst(hookName, parameters, replaceContext, skipped) {
  23788. return this.hookFirstAndGetPlugin(hookName, parameters, replaceContext, skipped).then(result => result && result[0]);
  23789. }
  23790. // chains, first non-null result stops and returns result and last plugin
  23791. async hookFirstAndGetPlugin(hookName, parameters, replaceContext, skipped) {
  23792. for (const plugin of this.getSortedPlugins(hookName)) {
  23793. if (skipped?.has(plugin))
  23794. continue;
  23795. const result = await this.runHook(hookName, parameters, plugin, replaceContext);
  23796. if (result != null)
  23797. return [result, plugin];
  23798. }
  23799. return null;
  23800. }
  23801. // chains synchronously, first non-null result stops and returns
  23802. hookFirstSync(hookName, parameters, replaceContext) {
  23803. for (const plugin of this.getSortedPlugins(hookName)) {
  23804. const result = this.runHookSync(hookName, parameters, plugin, replaceContext);
  23805. if (result != null)
  23806. return result;
  23807. }
  23808. return null;
  23809. }
  23810. // parallel, ignores returns
  23811. async hookParallel(hookName, parameters, replaceContext) {
  23812. const parallelPromises = [];
  23813. for (const plugin of this.getSortedPlugins(hookName)) {
  23814. if (plugin[hookName].sequential) {
  23815. await Promise.all(parallelPromises);
  23816. parallelPromises.length = 0;
  23817. await this.runHook(hookName, parameters, plugin, replaceContext);
  23818. }
  23819. else {
  23820. parallelPromises.push(this.runHook(hookName, parameters, plugin, replaceContext));
  23821. }
  23822. }
  23823. await Promise.all(parallelPromises);
  23824. }
  23825. // chains, reduces returned value, handling the reduced value as the first hook argument
  23826. hookReduceArg0(hookName, [argument0, ...rest], reduce, replaceContext) {
  23827. let promise = Promise.resolve(argument0);
  23828. for (const plugin of this.getSortedPlugins(hookName)) {
  23829. promise = promise.then(argument0 => this.runHook(hookName, [argument0, ...rest], plugin, replaceContext).then(result => reduce.call(this.pluginContexts.get(plugin), argument0, result, plugin)));
  23830. }
  23831. return promise;
  23832. }
  23833. // chains synchronously, reduces returned value, handling the reduced value as the first hook argument
  23834. hookReduceArg0Sync(hookName, [argument0, ...rest], reduce, replaceContext) {
  23835. for (const plugin of this.getSortedPlugins(hookName)) {
  23836. const parameters = [argument0, ...rest];
  23837. const result = this.runHookSync(hookName, parameters, plugin, replaceContext);
  23838. argument0 = reduce.call(this.pluginContexts.get(plugin), argument0, result, plugin);
  23839. }
  23840. return argument0;
  23841. }
  23842. // chains, reduces returned value to type string, handling the reduced value separately. permits hooks as values.
  23843. async hookReduceValue(hookName, initialValue, parameters, reducer) {
  23844. const results = [];
  23845. const parallelResults = [];
  23846. for (const plugin of this.getSortedPlugins(hookName, validateAddonPluginHandler)) {
  23847. if (plugin[hookName].sequential) {
  23848. results.push(...(await Promise.all(parallelResults)));
  23849. parallelResults.length = 0;
  23850. results.push(await this.runHook(hookName, parameters, plugin));
  23851. }
  23852. else {
  23853. parallelResults.push(this.runHook(hookName, parameters, plugin));
  23854. }
  23855. }
  23856. results.push(...(await Promise.all(parallelResults)));
  23857. return results.reduce(reducer, await initialValue);
  23858. }
  23859. // chains synchronously, reduces returned value to type T, handling the reduced value separately. permits hooks as values.
  23860. hookReduceValueSync(hookName, initialValue, parameters, reduce, replaceContext) {
  23861. let accumulator = initialValue;
  23862. for (const plugin of this.getSortedPlugins(hookName)) {
  23863. const result = this.runHookSync(hookName, parameters, plugin, replaceContext);
  23864. accumulator = reduce.call(this.pluginContexts.get(plugin), accumulator, result, plugin);
  23865. }
  23866. return accumulator;
  23867. }
  23868. // chains, ignores returns
  23869. hookSeq(hookName, parameters, replaceContext) {
  23870. let promise = Promise.resolve();
  23871. for (const plugin of this.getSortedPlugins(hookName)) {
  23872. promise = promise.then(() => this.runHook(hookName, parameters, plugin, replaceContext));
  23873. }
  23874. return promise.then(noReturn);
  23875. }
  23876. getSortedPlugins(hookName, validateHandler) {
  23877. return getOrCreate(this.sortedPlugins, hookName, () => getSortedValidatedPlugins(hookName, this.plugins, validateHandler));
  23878. }
  23879. // Implementation signature
  23880. runHook(hookName, parameters, plugin, replaceContext) {
  23881. // We always filter for plugins that support the hook before running it
  23882. const hook = plugin[hookName];
  23883. const handler = typeof hook === 'object' ? hook.handler : hook;
  23884. let context = this.pluginContexts.get(plugin);
  23885. if (replaceContext) {
  23886. context = replaceContext(context, plugin);
  23887. }
  23888. let action = null;
  23889. return Promise.resolve()
  23890. .then(() => {
  23891. if (typeof handler !== 'function') {
  23892. return handler;
  23893. }
  23894. // eslint-disable-next-line @typescript-eslint/ban-types
  23895. const hookResult = handler.apply(context, parameters);
  23896. if (!hookResult?.then) {
  23897. // short circuit for non-thenables and non-Promises
  23898. return hookResult;
  23899. }
  23900. // Track pending hook actions to properly error out when
  23901. // unfulfilled promises cause rollup to abruptly and confusingly
  23902. // exit with a successful 0 return code but without producing any
  23903. // output, errors or warnings.
  23904. action = [plugin.name, hookName, parameters];
  23905. this.unfulfilledActions.add(action);
  23906. // Although it would be more elegant to just return hookResult here
  23907. // and put the .then() handler just above the .catch() handler below,
  23908. // doing so would subtly change the defacto async event dispatch order
  23909. // which at least one test and some plugins in the wild may depend on.
  23910. return Promise.resolve(hookResult).then(result => {
  23911. // action was fulfilled
  23912. this.unfulfilledActions.delete(action);
  23913. return result;
  23914. });
  23915. })
  23916. .catch(error_ => {
  23917. if (action !== null) {
  23918. // action considered to be fulfilled since error being handled
  23919. this.unfulfilledActions.delete(action);
  23920. }
  23921. return error(logPluginError(error_, plugin.name, { hook: hookName }));
  23922. });
  23923. }
  23924. /**
  23925. * Run a sync plugin hook and return the result.
  23926. * @param hookName Name of the plugin hook. Must be in `PluginHooks`.
  23927. * @param args Arguments passed to the plugin hook.
  23928. * @param plugin The acutal plugin
  23929. * @param replaceContext When passed, the plugin context can be overridden.
  23930. */
  23931. runHookSync(hookName, parameters, plugin, replaceContext) {
  23932. const hook = plugin[hookName];
  23933. const handler = typeof hook === 'object' ? hook.handler : hook;
  23934. let context = this.pluginContexts.get(plugin);
  23935. if (replaceContext) {
  23936. context = replaceContext(context, plugin);
  23937. }
  23938. try {
  23939. // eslint-disable-next-line @typescript-eslint/ban-types
  23940. return handler.apply(context, parameters);
  23941. }
  23942. catch (error_) {
  23943. return error(logPluginError(error_, plugin.name, { hook: hookName }));
  23944. }
  23945. }
  23946. }
  23947. function getSortedValidatedPlugins(hookName, plugins, validateHandler = validateFunctionPluginHandler) {
  23948. const pre = [];
  23949. const normal = [];
  23950. const post = [];
  23951. for (const plugin of plugins) {
  23952. const hook = plugin[hookName];
  23953. if (hook) {
  23954. if (typeof hook === 'object') {
  23955. validateHandler(hook.handler, hookName, plugin);
  23956. if (hook.order === 'pre') {
  23957. pre.push(plugin);
  23958. continue;
  23959. }
  23960. if (hook.order === 'post') {
  23961. post.push(plugin);
  23962. continue;
  23963. }
  23964. }
  23965. else {
  23966. validateHandler(hook, hookName, plugin);
  23967. }
  23968. normal.push(plugin);
  23969. }
  23970. }
  23971. return [...pre, ...normal, ...post];
  23972. }
  23973. function validateFunctionPluginHandler(handler, hookName, plugin) {
  23974. if (typeof handler !== 'function') {
  23975. error(logInvalidFunctionPluginHook(hookName, plugin.name));
  23976. }
  23977. }
  23978. function validateAddonPluginHandler(handler, hookName, plugin) {
  23979. if (typeof handler !== 'string' && typeof handler !== 'function') {
  23980. return error(logInvalidAddonPluginHook(hookName, plugin.name));
  23981. }
  23982. }
  23983. function noReturn() { }
  23984. class Queue {
  23985. constructor(maxParallel) {
  23986. this.maxParallel = maxParallel;
  23987. this.queue = [];
  23988. this.workerCount = 0;
  23989. }
  23990. run(task) {
  23991. return new Promise((resolve, reject) => {
  23992. this.queue.push({ reject, resolve, task });
  23993. this.work();
  23994. });
  23995. }
  23996. async work() {
  23997. if (this.workerCount >= this.maxParallel)
  23998. return;
  23999. this.workerCount++;
  24000. let entry;
  24001. while ((entry = this.queue.shift())) {
  24002. const { reject, resolve, task } = entry;
  24003. try {
  24004. const result = await task();
  24005. resolve(result);
  24006. }
  24007. catch (error) {
  24008. reject(error);
  24009. }
  24010. }
  24011. this.workerCount--;
  24012. }
  24013. }
  24014. function normalizeEntryModules(entryModules) {
  24015. if (Array.isArray(entryModules)) {
  24016. return entryModules.map(id => ({
  24017. fileName: null,
  24018. id,
  24019. implicitlyLoadedAfter: [],
  24020. importer: undefined,
  24021. name: null
  24022. }));
  24023. }
  24024. return Object.entries(entryModules).map(([name, id]) => ({
  24025. fileName: null,
  24026. id,
  24027. implicitlyLoadedAfter: [],
  24028. importer: undefined,
  24029. name
  24030. }));
  24031. }
  24032. class Graph {
  24033. constructor(options, watcher) {
  24034. this.options = options;
  24035. this.astLru = flru(5);
  24036. this.cachedModules = new Map();
  24037. this.deoptimizationTracker = new PathTracker();
  24038. this.entryModules = [];
  24039. this.modulesById = new Map();
  24040. this.needsTreeshakingPass = false;
  24041. this.phase = BuildPhase.LOAD_AND_PARSE;
  24042. this.scope = new GlobalScope();
  24043. this.watchFiles = Object.create(null);
  24044. this.watchMode = false;
  24045. this.externalModules = [];
  24046. this.implicitEntryModules = [];
  24047. this.modules = [];
  24048. this.getModuleInfo = (moduleId) => {
  24049. const foundModule = this.modulesById.get(moduleId);
  24050. if (!foundModule)
  24051. return null;
  24052. return foundModule.info;
  24053. };
  24054. if (options.cache !== false) {
  24055. if (options.cache?.modules) {
  24056. for (const module of options.cache.modules)
  24057. this.cachedModules.set(module.id, module);
  24058. }
  24059. this.pluginCache = options.cache?.plugins || Object.create(null);
  24060. // increment access counter
  24061. for (const name in this.pluginCache) {
  24062. const cache = this.pluginCache[name];
  24063. for (const value of Object.values(cache))
  24064. value[0]++;
  24065. }
  24066. }
  24067. if (watcher) {
  24068. this.watchMode = true;
  24069. const handleChange = (...parameters) => this.pluginDriver.hookParallel('watchChange', parameters);
  24070. const handleClose = () => this.pluginDriver.hookParallel('closeWatcher', []);
  24071. watcher.onCurrentRun('change', handleChange);
  24072. watcher.onCurrentRun('close', handleClose);
  24073. }
  24074. this.pluginDriver = new PluginDriver(this, options, options.plugins, this.pluginCache);
  24075. this.acornParser = Parser.extend(...options.acornInjectPlugins);
  24076. this.moduleLoader = new ModuleLoader(this, this.modulesById, this.options, this.pluginDriver);
  24077. this.fileOperationQueue = new Queue(options.maxParallelFileOps);
  24078. this.pureFunctions = getPureFunctions(options);
  24079. }
  24080. async build() {
  24081. timeStart('generate module graph', 2);
  24082. await this.generateModuleGraph();
  24083. timeEnd('generate module graph', 2);
  24084. timeStart('sort and bind modules', 2);
  24085. this.phase = BuildPhase.ANALYSE;
  24086. this.sortModules();
  24087. timeEnd('sort and bind modules', 2);
  24088. timeStart('mark included statements', 2);
  24089. this.includeStatements();
  24090. timeEnd('mark included statements', 2);
  24091. this.phase = BuildPhase.GENERATE;
  24092. }
  24093. contextParse(code, options = {}) {
  24094. const onCommentOrig = options.onComment;
  24095. const comments = [];
  24096. options.onComment =
  24097. onCommentOrig && typeof onCommentOrig == 'function'
  24098. ? (block, text, start, end, ...parameters) => {
  24099. comments.push({ end, start, type: block ? 'Block' : 'Line', value: text });
  24100. return onCommentOrig.call(options, block, text, start, end, ...parameters);
  24101. }
  24102. : comments;
  24103. const ast = this.acornParser.parse(code, {
  24104. ...this.options.acorn,
  24105. ...options
  24106. });
  24107. if (typeof onCommentOrig == 'object') {
  24108. onCommentOrig.push(...comments);
  24109. }
  24110. options.onComment = onCommentOrig;
  24111. addAnnotations(comments, ast, code);
  24112. return ast;
  24113. }
  24114. getCache() {
  24115. // handle plugin cache eviction
  24116. for (const name in this.pluginCache) {
  24117. const cache = this.pluginCache[name];
  24118. let allDeleted = true;
  24119. for (const [key, value] of Object.entries(cache)) {
  24120. if (value[0] >= this.options.experimentalCacheExpiry)
  24121. delete cache[key];
  24122. else
  24123. allDeleted = false;
  24124. }
  24125. if (allDeleted)
  24126. delete this.pluginCache[name];
  24127. }
  24128. return {
  24129. modules: this.modules.map(module => module.toJSON()),
  24130. plugins: this.pluginCache
  24131. };
  24132. }
  24133. async generateModuleGraph() {
  24134. ({ entryModules: this.entryModules, implicitEntryModules: this.implicitEntryModules } =
  24135. await this.moduleLoader.addEntryModules(normalizeEntryModules(this.options.input), true));
  24136. if (this.entryModules.length === 0) {
  24137. throw new Error('You must supply options.input to rollup');
  24138. }
  24139. for (const module of this.modulesById.values()) {
  24140. if (module instanceof Module) {
  24141. this.modules.push(module);
  24142. }
  24143. else {
  24144. this.externalModules.push(module);
  24145. }
  24146. }
  24147. }
  24148. includeStatements() {
  24149. const entryModules = [...this.entryModules, ...this.implicitEntryModules];
  24150. for (const module of entryModules) {
  24151. markModuleAndImpureDependenciesAsExecuted(module);
  24152. }
  24153. if (this.options.treeshake) {
  24154. let treeshakingPass = 1;
  24155. do {
  24156. timeStart(`treeshaking pass ${treeshakingPass}`, 3);
  24157. this.needsTreeshakingPass = false;
  24158. for (const module of this.modules) {
  24159. if (module.isExecuted) {
  24160. if (module.info.moduleSideEffects === 'no-treeshake') {
  24161. module.includeAllInBundle();
  24162. }
  24163. else {
  24164. module.include();
  24165. }
  24166. }
  24167. }
  24168. if (treeshakingPass === 1) {
  24169. // We only include exports after the first pass to avoid issues with
  24170. // the TDZ detection logic
  24171. for (const module of entryModules) {
  24172. if (module.preserveSignature !== false) {
  24173. module.includeAllExports(false);
  24174. this.needsTreeshakingPass = true;
  24175. }
  24176. }
  24177. }
  24178. timeEnd(`treeshaking pass ${treeshakingPass++}`, 3);
  24179. } while (this.needsTreeshakingPass);
  24180. }
  24181. else {
  24182. for (const module of this.modules)
  24183. module.includeAllInBundle();
  24184. }
  24185. for (const externalModule of this.externalModules)
  24186. externalModule.warnUnusedImports();
  24187. for (const module of this.implicitEntryModules) {
  24188. for (const dependant of module.implicitlyLoadedAfter) {
  24189. if (!(dependant.info.isEntry || dependant.isIncluded())) {
  24190. error(logImplicitDependantIsNotIncluded(dependant));
  24191. }
  24192. }
  24193. }
  24194. }
  24195. sortModules() {
  24196. const { orderedModules, cyclePaths } = analyseModuleExecution(this.entryModules);
  24197. for (const cyclePath of cyclePaths) {
  24198. this.options.onLog(LOGLEVEL_WARN, logCircularDependency(cyclePath));
  24199. }
  24200. this.modules = orderedModules;
  24201. for (const module of this.modules) {
  24202. module.bindReferences();
  24203. }
  24204. this.warnForMissingExports();
  24205. }
  24206. warnForMissingExports() {
  24207. for (const module of this.modules) {
  24208. for (const importDescription of module.importDescriptions.values()) {
  24209. if (importDescription.name !== '*' &&
  24210. !importDescription.module.getVariableForExportName(importDescription.name)[0]) {
  24211. module.log(LOGLEVEL_WARN, logMissingExport(importDescription.name, module.id, importDescription.module.id), importDescription.start);
  24212. }
  24213. }
  24214. }
  24215. }
  24216. }
  24217. function formatAction([pluginName, hookName, parameters]) {
  24218. const action = `(${pluginName}) ${hookName}`;
  24219. const s = JSON.stringify;
  24220. switch (hookName) {
  24221. case 'resolveId': {
  24222. return `${action} ${s(parameters[0])} ${s(parameters[1])}`;
  24223. }
  24224. case 'load': {
  24225. return `${action} ${s(parameters[0])}`;
  24226. }
  24227. case 'transform': {
  24228. return `${action} ${s(parameters[1])}`;
  24229. }
  24230. case 'shouldTransformCachedModule': {
  24231. return `${action} ${s(parameters[0].id)}`;
  24232. }
  24233. case 'moduleParsed': {
  24234. return `${action} ${s(parameters[0].id)}`;
  24235. }
  24236. }
  24237. return action;
  24238. }
  24239. let handleBeforeExit = null;
  24240. const rejectByPluginDriver = new Map();
  24241. async function catchUnfinishedHookActions(pluginDriver, callback) {
  24242. const emptyEventLoopPromise = new Promise((_, reject) => {
  24243. rejectByPluginDriver.set(pluginDriver, reject);
  24244. if (!handleBeforeExit) {
  24245. // We only ever create a single event listener to avoid max listener and
  24246. // other issues
  24247. handleBeforeExit = () => {
  24248. for (const [pluginDriver, reject] of rejectByPluginDriver) {
  24249. const unfulfilledActions = pluginDriver.getUnfulfilledHookActions();
  24250. reject(new Error(`Unexpected early exit. This happens when Promises returned by plugins cannot resolve. Unfinished hook action(s) on exit:\n` +
  24251. [...unfulfilledActions].map(formatAction).join('\n')));
  24252. }
  24253. };
  24254. process$1.once('beforeExit', handleBeforeExit);
  24255. }
  24256. });
  24257. try {
  24258. return await Promise.race([callback(), emptyEventLoopPromise]);
  24259. }
  24260. finally {
  24261. rejectByPluginDriver.delete(pluginDriver);
  24262. if (rejectByPluginDriver.size === 0) {
  24263. process$1.off('beforeExit', handleBeforeExit);
  24264. handleBeforeExit = null;
  24265. }
  24266. }
  24267. }
  24268. function getLogger(plugins, onLog, watchMode, logLevel) {
  24269. plugins = getSortedValidatedPlugins('onLog', plugins);
  24270. const minimalPriority = logLevelPriority[logLevel];
  24271. const logger = (level, log, skipped = EMPTY_SET) => {
  24272. const logPriority = logLevelPriority[level];
  24273. if (logPriority < minimalPriority) {
  24274. return;
  24275. }
  24276. for (const plugin of plugins) {
  24277. if (skipped.has(plugin))
  24278. continue;
  24279. const { onLog: pluginOnLog } = plugin;
  24280. const getLogHandler = (level) => {
  24281. if (logLevelPriority[level] < minimalPriority) {
  24282. return doNothing;
  24283. }
  24284. return log => logger(level, normalizeLog(log), new Set(skipped).add(plugin));
  24285. };
  24286. const handler = 'handler' in pluginOnLog ? pluginOnLog.handler : pluginOnLog;
  24287. if (handler.call({
  24288. debug: getLogHandler(LOGLEVEL_DEBUG),
  24289. error: (log) => error(normalizeLog(log)),
  24290. info: getLogHandler(LOGLEVEL_INFO),
  24291. meta: { rollupVersion: version$1, watchMode },
  24292. warn: getLogHandler(LOGLEVEL_WARN)
  24293. }, level, log) === false) {
  24294. return;
  24295. }
  24296. }
  24297. onLog(level, log);
  24298. };
  24299. return logger;
  24300. }
  24301. const leftCurlyBrace = "{".charCodeAt(0);
  24302. const space = " ".charCodeAt(0);
  24303. const keyword = "assert";
  24304. const FUNC_STATEMENT = 1, FUNC_NULLABLE_ID = 4;
  24305. function importAssertions(Parser) {
  24306. // Use supplied version acorn version if present, to avoid
  24307. // reference mismatches due to different acorn versions. This
  24308. // allows this plugin to be used with Rollup which supplies
  24309. // its own internal version of acorn and thereby sidesteps
  24310. // the package manager.
  24311. const acorn = Parser.acorn || _acorn;
  24312. const { tokTypes: tt, TokenType } = acorn;
  24313. return class extends Parser {
  24314. constructor(...args) {
  24315. super(...args);
  24316. this.assertToken = new TokenType(keyword);
  24317. }
  24318. _codeAt(i) {
  24319. return this.input.charCodeAt(i);
  24320. }
  24321. _eat(t) {
  24322. if (this.type !== t) {
  24323. this.unexpected();
  24324. }
  24325. this.next();
  24326. }
  24327. readToken(code) {
  24328. let i = 0;
  24329. for (; i < keyword.length; i++) {
  24330. if (this._codeAt(this.pos + i) !== keyword.charCodeAt(i)) {
  24331. return super.readToken(code);
  24332. }
  24333. }
  24334. // ensure that the keyword is at the correct location
  24335. // ie `assert{...` or `assert {...`
  24336. for (;; i++) {
  24337. if (this._codeAt(this.pos + i) === leftCurlyBrace) {
  24338. // Found '{'
  24339. break;
  24340. } else if (this._codeAt(this.pos + i) === space) {
  24341. // white space is allowed between `assert` and `{`, so continue.
  24342. continue;
  24343. } else {
  24344. return super.readToken(code);
  24345. }
  24346. }
  24347. // If we're inside a dynamic import expression we'll parse
  24348. // the `assert` keyword as a standard object property name
  24349. // ie `import(""./foo.json", { assert: { type: "json" } })`
  24350. if (this.type.label === "{") {
  24351. return super.readToken(code);
  24352. }
  24353. this.pos += keyword.length;
  24354. return this.finishToken(this.assertToken);
  24355. }
  24356. parseDynamicImport(node) {
  24357. this.next(); // skip `(`
  24358. // Parse node.source.
  24359. node.source = this.parseMaybeAssign();
  24360. if (this.eat(tt.comma)) {
  24361. const obj = this.parseObj(false);
  24362. node.arguments = [obj];
  24363. }
  24364. this._eat(tt.parenR);
  24365. return this.finishNode(node, "ImportExpression");
  24366. }
  24367. // ported from acorn/src/statement.js pp.parseExport
  24368. parseExport(node, exports) {
  24369. this.next();
  24370. // export * from '...'
  24371. if (this.eat(tt.star)) {
  24372. if (this.options.ecmaVersion >= 11) {
  24373. if (this.eatContextual("as")) {
  24374. node.exported = this.parseIdent(true);
  24375. this.checkExport(exports, node.exported.name, this.lastTokStart);
  24376. } else {
  24377. node.exported = null;
  24378. }
  24379. }
  24380. this.expectContextual("from");
  24381. if (this.type !== tt.string) { this.unexpected(); }
  24382. node.source = this.parseExprAtom();
  24383. if (this.type === this.assertToken || this.type === tt._with) {
  24384. this.next();
  24385. const assertions = this.parseImportAssertions();
  24386. if (assertions) {
  24387. node.assertions = assertions;
  24388. }
  24389. }
  24390. this.semicolon();
  24391. return this.finishNode(node, "ExportAllDeclaration")
  24392. }
  24393. if (this.eat(tt._default)) { // export default ...
  24394. this.checkExport(exports, "default", this.lastTokStart);
  24395. var isAsync;
  24396. if (this.type === tt._function || (isAsync = this.isAsyncFunction())) {
  24397. var fNode = this.startNode();
  24398. this.next();
  24399. if (isAsync) { this.next(); }
  24400. node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync);
  24401. } else if (this.type === tt._class) {
  24402. var cNode = this.startNode();
  24403. node.declaration = this.parseClass(cNode, "nullableID");
  24404. } else {
  24405. node.declaration = this.parseMaybeAssign();
  24406. this.semicolon();
  24407. }
  24408. return this.finishNode(node, "ExportDefaultDeclaration")
  24409. }
  24410. // export var|const|let|function|class ...
  24411. if (this.shouldParseExportStatement()) {
  24412. node.declaration = this.parseStatement(null);
  24413. if (node.declaration.type === "VariableDeclaration")
  24414. { this.checkVariableExport(exports, node.declaration.declarations); }
  24415. else
  24416. { this.checkExport(exports, node.declaration.id.name, node.declaration.id.start); }
  24417. node.specifiers = [];
  24418. node.source = null;
  24419. } else { // export { x, y as z } [from '...']
  24420. node.declaration = null;
  24421. node.specifiers = this.parseExportSpecifiers(exports);
  24422. if (this.eatContextual("from")) {
  24423. if (this.type !== tt.string) { this.unexpected(); }
  24424. node.source = this.parseExprAtom();
  24425. if (this.type === this.assertToken || this.type === tt._with) {
  24426. this.next();
  24427. const assertions = this.parseImportAssertions();
  24428. if (assertions) {
  24429. node.assertions = assertions;
  24430. }
  24431. }
  24432. } else {
  24433. for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
  24434. // check for keywords used as local names
  24435. var spec = list[i];
  24436. this.checkUnreserved(spec.local);
  24437. // check if export is defined
  24438. this.checkLocalExport(spec.local);
  24439. }
  24440. node.source = null;
  24441. }
  24442. this.semicolon();
  24443. }
  24444. return this.finishNode(node, "ExportNamedDeclaration")
  24445. }
  24446. parseImport(node) {
  24447. this.next();
  24448. // import '...'
  24449. if (this.type === tt.string) {
  24450. node.specifiers = [];
  24451. node.source = this.parseExprAtom();
  24452. } else {
  24453. node.specifiers = this.parseImportSpecifiers();
  24454. this.expectContextual("from");
  24455. node.source =
  24456. this.type === tt.string ? this.parseExprAtom() : this.unexpected();
  24457. }
  24458. if (this.type === this.assertToken || this.type == tt._with) {
  24459. this.next();
  24460. const assertions = this.parseImportAssertions();
  24461. if (assertions) {
  24462. node.assertions = assertions;
  24463. }
  24464. }
  24465. this.semicolon();
  24466. return this.finishNode(node, "ImportDeclaration");
  24467. }
  24468. parseImportAssertions() {
  24469. this._eat(tt.braceL);
  24470. const attrs = this.parseAssertEntries();
  24471. this._eat(tt.braceR);
  24472. return attrs;
  24473. }
  24474. parseAssertEntries() {
  24475. const attrs = [];
  24476. const attrNames = new Set();
  24477. do {
  24478. if (this.type === tt.braceR) {
  24479. break;
  24480. }
  24481. const node = this.startNode();
  24482. // parse AssertionKey : IdentifierName, StringLiteral
  24483. let assertionKeyNode;
  24484. if (this.type === tt.string) {
  24485. assertionKeyNode = this.parseLiteral(this.value);
  24486. } else {
  24487. assertionKeyNode = this.parseIdent(true);
  24488. }
  24489. this.next();
  24490. node.key = assertionKeyNode;
  24491. // check if we already have an entry for an attribute
  24492. // if a duplicate entry is found, throw an error
  24493. // for now this logic will come into play only when someone declares `type` twice
  24494. if (attrNames.has(node.key.name)) {
  24495. this.raise(this.pos, "Duplicated key in assertions");
  24496. }
  24497. attrNames.add(node.key.name);
  24498. if (this.type !== tt.string) {
  24499. this.raise(
  24500. this.pos,
  24501. "Only string is supported as an assertion value"
  24502. );
  24503. }
  24504. node.value = this.parseLiteral(this.value);
  24505. attrs.push(this.finishNode(node, "ImportAttribute"));
  24506. } while (this.eat(tt.comma));
  24507. return attrs;
  24508. }
  24509. };
  24510. }
  24511. function ensureArray(items) {
  24512. if (Array.isArray(items)) {
  24513. return items.filter(Boolean);
  24514. }
  24515. if (items) {
  24516. return [items];
  24517. }
  24518. return [];
  24519. }
  24520. async function normalizeInputOptions(config, watchMode) {
  24521. // These are options that may trigger special warnings or behaviour later
  24522. // if the user did not select an explicit value
  24523. const unsetOptions = new Set();
  24524. const context = config.context ?? 'undefined';
  24525. const plugins = await normalizePluginOption(config.plugins);
  24526. const logLevel = config.logLevel || LOGLEVEL_INFO;
  24527. const onLog = getLogger(plugins, getOnLog(config, logLevel), watchMode, logLevel);
  24528. const strictDeprecations = config.strictDeprecations || false;
  24529. const maxParallelFileOps = getMaxParallelFileOps(config, onLog, strictDeprecations);
  24530. const options = {
  24531. acorn: getAcorn(config),
  24532. acornInjectPlugins: getAcornInjectPlugins(config),
  24533. cache: getCache(config),
  24534. context,
  24535. experimentalCacheExpiry: config.experimentalCacheExpiry ?? 10,
  24536. experimentalLogSideEffects: config.experimentalLogSideEffects || false,
  24537. external: getIdMatcher(config.external),
  24538. inlineDynamicImports: getInlineDynamicImports$1(config, onLog, strictDeprecations),
  24539. input: getInput(config),
  24540. logLevel,
  24541. makeAbsoluteExternalsRelative: config.makeAbsoluteExternalsRelative ?? 'ifRelativeSource',
  24542. manualChunks: getManualChunks$1(config, onLog, strictDeprecations),
  24543. maxParallelFileOps,
  24544. maxParallelFileReads: maxParallelFileOps,
  24545. moduleContext: getModuleContext(config, context),
  24546. onLog,
  24547. onwarn: warning => onLog(LOGLEVEL_WARN, warning),
  24548. perf: config.perf || false,
  24549. plugins,
  24550. preserveEntrySignatures: config.preserveEntrySignatures ?? 'exports-only',
  24551. preserveModules: getPreserveModules$1(config, onLog, strictDeprecations),
  24552. preserveSymlinks: config.preserveSymlinks || false,
  24553. shimMissingExports: config.shimMissingExports || false,
  24554. strictDeprecations,
  24555. treeshake: getTreeshake(config)
  24556. };
  24557. warnUnknownOptions(config, [...Object.keys(options), 'watch'], 'input options', onLog, /^(output)$/);
  24558. return { options, unsetOptions };
  24559. }
  24560. const getAcorn = (config) => ({
  24561. ecmaVersion: 'latest',
  24562. sourceType: 'module',
  24563. ...config.acorn
  24564. });
  24565. const getAcornInjectPlugins = (config) => [
  24566. importAssertions,
  24567. ...ensureArray(config.acornInjectPlugins)
  24568. ];
  24569. const getCache = (config) => config.cache === true // `true` is the default
  24570. ? undefined
  24571. : config.cache?.cache || config.cache;
  24572. const getIdMatcher = (option) => {
  24573. if (option === true) {
  24574. return () => true;
  24575. }
  24576. if (typeof option === 'function') {
  24577. return (id, ...parameters) => (!id.startsWith('\0') && option(id, ...parameters)) || false;
  24578. }
  24579. if (option) {
  24580. const ids = new Set();
  24581. const matchers = [];
  24582. for (const value of ensureArray(option)) {
  24583. if (value instanceof RegExp) {
  24584. matchers.push(value);
  24585. }
  24586. else {
  24587. ids.add(value);
  24588. }
  24589. }
  24590. return (id, ..._arguments) => ids.has(id) || matchers.some(matcher => matcher.test(id));
  24591. }
  24592. return () => false;
  24593. };
  24594. const getInlineDynamicImports$1 = (config, log, strictDeprecations) => {
  24595. const configInlineDynamicImports = config.inlineDynamicImports;
  24596. if (configInlineDynamicImports) {
  24597. warnDeprecationWithOptions('The "inlineDynamicImports" option is deprecated. Use the "output.inlineDynamicImports" option instead.', URL_OUTPUT_INLINEDYNAMICIMPORTS, true, log, strictDeprecations);
  24598. }
  24599. return configInlineDynamicImports;
  24600. };
  24601. const getInput = (config) => {
  24602. const configInput = config.input;
  24603. return configInput == null ? [] : typeof configInput === 'string' ? [configInput] : configInput;
  24604. };
  24605. const getManualChunks$1 = (config, log, strictDeprecations) => {
  24606. const configManualChunks = config.manualChunks;
  24607. if (configManualChunks) {
  24608. warnDeprecationWithOptions('The "manualChunks" option is deprecated. Use the "output.manualChunks" option instead.', URL_OUTPUT_MANUALCHUNKS, true, log, strictDeprecations);
  24609. }
  24610. return configManualChunks;
  24611. };
  24612. const getMaxParallelFileOps = (config, log, strictDeprecations) => {
  24613. const maxParallelFileReads = config.maxParallelFileReads;
  24614. if (typeof maxParallelFileReads === 'number') {
  24615. warnDeprecationWithOptions('The "maxParallelFileReads" option is deprecated. Use the "maxParallelFileOps" option instead.', URL_MAXPARALLELFILEOPS, true, log, strictDeprecations);
  24616. }
  24617. const maxParallelFileOps = config.maxParallelFileOps ?? maxParallelFileReads;
  24618. if (typeof maxParallelFileOps === 'number') {
  24619. if (maxParallelFileOps <= 0)
  24620. return Infinity;
  24621. return maxParallelFileOps;
  24622. }
  24623. return 20;
  24624. };
  24625. const getModuleContext = (config, context) => {
  24626. const configModuleContext = config.moduleContext;
  24627. if (typeof configModuleContext === 'function') {
  24628. return id => configModuleContext(id) ?? context;
  24629. }
  24630. if (configModuleContext) {
  24631. const contextByModuleId = Object.create(null);
  24632. for (const [key, moduleContext] of Object.entries(configModuleContext)) {
  24633. contextByModuleId[resolve(key)] = moduleContext;
  24634. }
  24635. return id => contextByModuleId[id] ?? context;
  24636. }
  24637. return () => context;
  24638. };
  24639. const getPreserveModules$1 = (config, log, strictDeprecations) => {
  24640. const configPreserveModules = config.preserveModules;
  24641. if (configPreserveModules) {
  24642. warnDeprecationWithOptions('The "preserveModules" option is deprecated. Use the "output.preserveModules" option instead.', URL_OUTPUT_PRESERVEMODULES, true, log, strictDeprecations);
  24643. }
  24644. return configPreserveModules;
  24645. };
  24646. const getTreeshake = (config) => {
  24647. const configTreeshake = config.treeshake;
  24648. if (configTreeshake === false) {
  24649. return false;
  24650. }
  24651. const configWithPreset = getOptionWithPreset(config.treeshake, treeshakePresets, 'treeshake', URL_TREESHAKE, 'false, true, ');
  24652. return {
  24653. annotations: configWithPreset.annotations !== false,
  24654. correctVarValueBeforeDeclaration: configWithPreset.correctVarValueBeforeDeclaration === true,
  24655. manualPureFunctions: configWithPreset.manualPureFunctions ?? EMPTY_ARRAY,
  24656. moduleSideEffects: getHasModuleSideEffects(configWithPreset.moduleSideEffects),
  24657. propertyReadSideEffects: configWithPreset.propertyReadSideEffects === 'always'
  24658. ? 'always'
  24659. : configWithPreset.propertyReadSideEffects !== false,
  24660. tryCatchDeoptimization: configWithPreset.tryCatchDeoptimization !== false,
  24661. unknownGlobalSideEffects: configWithPreset.unknownGlobalSideEffects !== false
  24662. };
  24663. };
  24664. const getHasModuleSideEffects = (moduleSideEffectsOption) => {
  24665. if (typeof moduleSideEffectsOption === 'boolean') {
  24666. return () => moduleSideEffectsOption;
  24667. }
  24668. if (moduleSideEffectsOption === 'no-external') {
  24669. return (_id, external) => !external;
  24670. }
  24671. if (typeof moduleSideEffectsOption === 'function') {
  24672. return (id, external) => id.startsWith('\0') ? true : moduleSideEffectsOption(id, external) !== false;
  24673. }
  24674. if (Array.isArray(moduleSideEffectsOption)) {
  24675. const ids = new Set(moduleSideEffectsOption);
  24676. return id => ids.has(id);
  24677. }
  24678. if (moduleSideEffectsOption) {
  24679. error(logInvalidOption('treeshake.moduleSideEffects', URL_TREESHAKE_MODULESIDEEFFECTS, 'please use one of false, "no-external", a function or an array'));
  24680. }
  24681. return () => true;
  24682. };
  24683. // https://datatracker.ietf.org/doc/html/rfc2396
  24684. // eslint-disable-next-line no-control-regex
  24685. const INVALID_CHAR_REGEX = /[\u0000-\u001F"#$&*+,:;<=>?[\]^`{|}\u007F]/g;
  24686. const DRIVE_LETTER_REGEX = /^[a-z]:/i;
  24687. function sanitizeFileName(name) {
  24688. const match = DRIVE_LETTER_REGEX.exec(name);
  24689. const driveLetter = match ? match[0] : '';
  24690. // A `:` is only allowed as part of a windows drive letter (ex: C:\foo)
  24691. // Otherwise, avoid them because they can refer to NTFS alternate data streams.
  24692. return driveLetter + name.slice(driveLetter.length).replace(INVALID_CHAR_REGEX, '_');
  24693. }
  24694. async function normalizeOutputOptions(config, inputOptions, unsetInputOptions) {
  24695. // These are options that may trigger special warnings or behaviour later
  24696. // if the user did not select an explicit value
  24697. const unsetOptions = new Set(unsetInputOptions);
  24698. const compact = config.compact || false;
  24699. const format = getFormat(config);
  24700. const inlineDynamicImports = getInlineDynamicImports(config, inputOptions);
  24701. const preserveModules = getPreserveModules(config, inlineDynamicImports, inputOptions);
  24702. const file = getFile(config, preserveModules, inputOptions);
  24703. const preferConst = getPreferConst(config, inputOptions);
  24704. const generatedCode = getGeneratedCode(config, preferConst);
  24705. const outputOptions = {
  24706. amd: getAmd(config),
  24707. assetFileNames: config.assetFileNames ?? 'assets/[name]-[hash][extname]',
  24708. banner: getAddon(config, 'banner'),
  24709. chunkFileNames: config.chunkFileNames ?? '[name]-[hash].js',
  24710. compact,
  24711. dir: getDir(config, file),
  24712. dynamicImportFunction: getDynamicImportFunction(config, inputOptions, format),
  24713. dynamicImportInCjs: config.dynamicImportInCjs ?? true,
  24714. entryFileNames: getEntryFileNames(config, unsetOptions),
  24715. esModule: config.esModule ?? 'if-default-prop',
  24716. experimentalDeepDynamicChunkOptimization: getExperimentalDeepDynamicChunkOptimization(config, inputOptions),
  24717. experimentalMinChunkSize: config.experimentalMinChunkSize ?? 1,
  24718. exports: getExports(config, unsetOptions),
  24719. extend: config.extend || false,
  24720. externalImportAssertions: config.externalImportAssertions ?? true,
  24721. externalLiveBindings: config.externalLiveBindings ?? true,
  24722. file,
  24723. footer: getAddon(config, 'footer'),
  24724. format,
  24725. freeze: config.freeze ?? true,
  24726. generatedCode,
  24727. globals: config.globals || {},
  24728. hoistTransitiveImports: config.hoistTransitiveImports ?? true,
  24729. indent: getIndent(config, compact),
  24730. inlineDynamicImports,
  24731. interop: getInterop(config),
  24732. intro: getAddon(config, 'intro'),
  24733. manualChunks: getManualChunks(config, inlineDynamicImports, preserveModules, inputOptions),
  24734. minifyInternalExports: getMinifyInternalExports(config, format, compact),
  24735. name: config.name,
  24736. namespaceToStringTag: getNamespaceToStringTag(config, generatedCode, inputOptions),
  24737. noConflict: config.noConflict || false,
  24738. outro: getAddon(config, 'outro'),
  24739. paths: config.paths || {},
  24740. plugins: await normalizePluginOption(config.plugins),
  24741. preferConst,
  24742. preserveModules,
  24743. preserveModulesRoot: getPreserveModulesRoot(config),
  24744. sanitizeFileName: typeof config.sanitizeFileName === 'function'
  24745. ? config.sanitizeFileName
  24746. : config.sanitizeFileName === false
  24747. ? id => id
  24748. : sanitizeFileName,
  24749. sourcemap: config.sourcemap || false,
  24750. sourcemapBaseUrl: getSourcemapBaseUrl(config),
  24751. sourcemapExcludeSources: config.sourcemapExcludeSources || false,
  24752. sourcemapFile: config.sourcemapFile,
  24753. sourcemapFileNames: getSourcemapFileNames(config, unsetOptions),
  24754. sourcemapIgnoreList: typeof config.sourcemapIgnoreList === 'function'
  24755. ? config.sourcemapIgnoreList
  24756. : config.sourcemapIgnoreList === false
  24757. ? () => false
  24758. : relativeSourcePath => relativeSourcePath.includes('node_modules'),
  24759. sourcemapPathTransform: config.sourcemapPathTransform,
  24760. strict: config.strict ?? true,
  24761. systemNullSetters: config.systemNullSetters ?? true,
  24762. validate: config.validate || false
  24763. };
  24764. warnUnknownOptions(config, Object.keys(outputOptions), 'output options', inputOptions.onLog);
  24765. return { options: outputOptions, unsetOptions };
  24766. }
  24767. const getFile = (config, preserveModules, inputOptions) => {
  24768. const { file } = config;
  24769. if (typeof file === 'string') {
  24770. if (preserveModules) {
  24771. return error(logInvalidOption('output.file', URL_OUTPUT_DIR, 'you must set "output.dir" instead of "output.file" when using the "output.preserveModules" option'));
  24772. }
  24773. if (!Array.isArray(inputOptions.input))
  24774. return error(logInvalidOption('output.file', URL_OUTPUT_DIR, 'you must set "output.dir" instead of "output.file" when providing named inputs'));
  24775. }
  24776. return file;
  24777. };
  24778. const getFormat = (config) => {
  24779. const configFormat = config.format;
  24780. switch (configFormat) {
  24781. case undefined:
  24782. case 'es':
  24783. case 'esm':
  24784. case 'module': {
  24785. return 'es';
  24786. }
  24787. case 'cjs':
  24788. case 'commonjs': {
  24789. return 'cjs';
  24790. }
  24791. case 'system':
  24792. case 'systemjs': {
  24793. return 'system';
  24794. }
  24795. case 'amd':
  24796. case 'iife':
  24797. case 'umd': {
  24798. return configFormat;
  24799. }
  24800. default: {
  24801. return error(logInvalidOption('output.format', URL_OUTPUT_FORMAT, `Valid values are "amd", "cjs", "system", "es", "iife" or "umd"`, configFormat));
  24802. }
  24803. }
  24804. };
  24805. const getInlineDynamicImports = (config, inputOptions) => {
  24806. const inlineDynamicImports = (config.inlineDynamicImports ?? inputOptions.inlineDynamicImports) || false;
  24807. const { input } = inputOptions;
  24808. if (inlineDynamicImports && (Array.isArray(input) ? input : Object.keys(input)).length > 1) {
  24809. return error(logInvalidOption('output.inlineDynamicImports', URL_OUTPUT_INLINEDYNAMICIMPORTS, 'multiple inputs are not supported when "output.inlineDynamicImports" is true'));
  24810. }
  24811. return inlineDynamicImports;
  24812. };
  24813. const getPreserveModules = (config, inlineDynamicImports, inputOptions) => {
  24814. const preserveModules = (config.preserveModules ?? inputOptions.preserveModules) || false;
  24815. if (preserveModules) {
  24816. if (inlineDynamicImports) {
  24817. return error(logInvalidOption('output.inlineDynamicImports', URL_OUTPUT_INLINEDYNAMICIMPORTS, `this option is not supported for "output.preserveModules"`));
  24818. }
  24819. if (inputOptions.preserveEntrySignatures === false) {
  24820. return error(logInvalidOption('preserveEntrySignatures', URL_PRESERVEENTRYSIGNATURES, 'setting this option to false is not supported for "output.preserveModules"'));
  24821. }
  24822. }
  24823. return preserveModules;
  24824. };
  24825. const getPreferConst = (config, inputOptions) => {
  24826. const configPreferConst = config.preferConst;
  24827. if (configPreferConst != null) {
  24828. warnDeprecation(`The "output.preferConst" option is deprecated. Use the "output.generatedCode.constBindings" option instead.`, URL_OUTPUT_GENERATEDCODE_CONSTBINDINGS, true, inputOptions);
  24829. }
  24830. return !!configPreferConst;
  24831. };
  24832. const getPreserveModulesRoot = (config) => {
  24833. const { preserveModulesRoot } = config;
  24834. if (preserveModulesRoot === null || preserveModulesRoot === undefined) {
  24835. return undefined;
  24836. }
  24837. return resolve(preserveModulesRoot);
  24838. };
  24839. const getAmd = (config) => {
  24840. const mergedOption = {
  24841. autoId: false,
  24842. basePath: '',
  24843. define: 'define',
  24844. forceJsExtensionForImports: false,
  24845. ...config.amd
  24846. };
  24847. if ((mergedOption.autoId || mergedOption.basePath) && mergedOption.id) {
  24848. return error(logInvalidOption('output.amd.id', URL_OUTPUT_AMD_ID, 'this option cannot be used together with "output.amd.autoId"/"output.amd.basePath"'));
  24849. }
  24850. if (mergedOption.basePath && !mergedOption.autoId) {
  24851. return error(logInvalidOption('output.amd.basePath', URL_OUTPUT_AMD_BASEPATH, 'this option only works with "output.amd.autoId"'));
  24852. }
  24853. return mergedOption.autoId
  24854. ? {
  24855. autoId: true,
  24856. basePath: mergedOption.basePath,
  24857. define: mergedOption.define,
  24858. forceJsExtensionForImports: mergedOption.forceJsExtensionForImports
  24859. }
  24860. : {
  24861. autoId: false,
  24862. define: mergedOption.define,
  24863. forceJsExtensionForImports: mergedOption.forceJsExtensionForImports,
  24864. id: mergedOption.id
  24865. };
  24866. };
  24867. const getAddon = (config, name) => {
  24868. const configAddon = config[name];
  24869. if (typeof configAddon === 'function') {
  24870. return configAddon;
  24871. }
  24872. return () => configAddon || '';
  24873. };
  24874. // eslint-disable-next-line unicorn/prevent-abbreviations
  24875. const getDir = (config, file) => {
  24876. const { dir } = config;
  24877. if (typeof dir === 'string' && typeof file === 'string') {
  24878. return error(logInvalidOption('output.dir', URL_OUTPUT_DIR, 'you must set either "output.file" for a single-file build or "output.dir" when generating multiple chunks'));
  24879. }
  24880. return dir;
  24881. };
  24882. const getDynamicImportFunction = (config, inputOptions, format) => {
  24883. const configDynamicImportFunction = config.dynamicImportFunction;
  24884. if (configDynamicImportFunction) {
  24885. warnDeprecation(`The "output.dynamicImportFunction" option is deprecated. Use the "renderDynamicImport" plugin hook instead.`, URL_RENDERDYNAMICIMPORT, true, inputOptions);
  24886. if (format !== 'es') {
  24887. inputOptions.onLog(LOGLEVEL_WARN, logInvalidOption('output.dynamicImportFunction', URL_OUTPUT_DYNAMICIMPORTFUNCTION, 'this option is ignored for formats other than "es"'));
  24888. }
  24889. }
  24890. return configDynamicImportFunction;
  24891. };
  24892. const getEntryFileNames = (config, unsetOptions) => {
  24893. const configEntryFileNames = config.entryFileNames;
  24894. if (configEntryFileNames == null) {
  24895. unsetOptions.add('entryFileNames');
  24896. }
  24897. return configEntryFileNames ?? '[name].js';
  24898. };
  24899. function getExperimentalDeepDynamicChunkOptimization(config, inputOptions) {
  24900. const configExperimentalDeepDynamicChunkOptimization = config.experimentalDeepDynamicChunkOptimization;
  24901. if (configExperimentalDeepDynamicChunkOptimization != null) {
  24902. warnDeprecation(`The "output.experimentalDeepDynamicChunkOptimization" option is deprecated as Rollup always runs the full chunking algorithm now. The option should be removed.`, URL_OUTPUT_EXPERIMENTALDEEPCHUNKOPTIMIZATION, true, inputOptions);
  24903. }
  24904. return configExperimentalDeepDynamicChunkOptimization || false;
  24905. }
  24906. function getExports(config, unsetOptions) {
  24907. const configExports = config.exports;
  24908. if (configExports == null) {
  24909. unsetOptions.add('exports');
  24910. }
  24911. else if (!['default', 'named', 'none', 'auto'].includes(configExports)) {
  24912. return error(logInvalidExportOptionValue(configExports));
  24913. }
  24914. return configExports || 'auto';
  24915. }
  24916. const getGeneratedCode = (config, preferConst) => {
  24917. const configWithPreset = getOptionWithPreset(config.generatedCode, generatedCodePresets, 'output.generatedCode', URL_OUTPUT_GENERATEDCODE, '');
  24918. return {
  24919. arrowFunctions: configWithPreset.arrowFunctions === true,
  24920. constBindings: configWithPreset.constBindings === true || preferConst,
  24921. objectShorthand: configWithPreset.objectShorthand === true,
  24922. reservedNamesAsProps: configWithPreset.reservedNamesAsProps !== false,
  24923. symbols: configWithPreset.symbols === true
  24924. };
  24925. };
  24926. const getIndent = (config, compact) => {
  24927. if (compact) {
  24928. return '';
  24929. }
  24930. const configIndent = config.indent;
  24931. return configIndent === false ? '' : configIndent ?? true;
  24932. };
  24933. const ALLOWED_INTEROP_TYPES = new Set([
  24934. 'compat',
  24935. 'auto',
  24936. 'esModule',
  24937. 'default',
  24938. 'defaultOnly'
  24939. ]);
  24940. const getInterop = (config) => {
  24941. const configInterop = config.interop;
  24942. if (typeof configInterop === 'function') {
  24943. const interopPerId = Object.create(null);
  24944. let defaultInterop = null;
  24945. return id => id === null
  24946. ? defaultInterop || validateInterop((defaultInterop = configInterop(id)))
  24947. : id in interopPerId
  24948. ? interopPerId[id]
  24949. : validateInterop((interopPerId[id] = configInterop(id)));
  24950. }
  24951. return configInterop === undefined ? () => 'default' : () => validateInterop(configInterop);
  24952. };
  24953. const validateInterop = (interop) => {
  24954. if (!ALLOWED_INTEROP_TYPES.has(interop)) {
  24955. return error(logInvalidOption('output.interop', URL_OUTPUT_INTEROP,
  24956. // eslint-disable-next-line unicorn/prefer-spread
  24957. `use one of ${Array.from(ALLOWED_INTEROP_TYPES, value => JSON.stringify(value)).join(', ')}`, interop));
  24958. }
  24959. return interop;
  24960. };
  24961. const getManualChunks = (config, inlineDynamicImports, preserveModules, inputOptions) => {
  24962. const configManualChunks = config.manualChunks || inputOptions.manualChunks;
  24963. if (configManualChunks) {
  24964. if (inlineDynamicImports) {
  24965. return error(logInvalidOption('output.manualChunks', URL_OUTPUT_MANUALCHUNKS, 'this option is not supported for "output.inlineDynamicImports"'));
  24966. }
  24967. if (preserveModules) {
  24968. return error(logInvalidOption('output.manualChunks', URL_OUTPUT_MANUALCHUNKS, 'this option is not supported for "output.preserveModules"'));
  24969. }
  24970. }
  24971. return configManualChunks || {};
  24972. };
  24973. const getMinifyInternalExports = (config, format, compact) => config.minifyInternalExports ?? (compact || format === 'es' || format === 'system');
  24974. const getNamespaceToStringTag = (config, generatedCode, inputOptions) => {
  24975. const configNamespaceToStringTag = config.namespaceToStringTag;
  24976. if (configNamespaceToStringTag != null) {
  24977. warnDeprecation(`The "output.namespaceToStringTag" option is deprecated. Use the "output.generatedCode.symbols" option instead.`, URL_OUTPUT_GENERATEDCODE_SYMBOLS, true, inputOptions);
  24978. return configNamespaceToStringTag;
  24979. }
  24980. return generatedCode.symbols || false;
  24981. };
  24982. const getSourcemapFileNames = (config, unsetOptions) => {
  24983. const configSourcemapFileNames = config.sourcemapFileNames;
  24984. if (configSourcemapFileNames == null) {
  24985. unsetOptions.add('sourcemapFileNames');
  24986. }
  24987. return configSourcemapFileNames;
  24988. };
  24989. const getSourcemapBaseUrl = (config) => {
  24990. const { sourcemapBaseUrl } = config;
  24991. if (sourcemapBaseUrl) {
  24992. if (isValidUrl(sourcemapBaseUrl)) {
  24993. return addTrailingSlashIfMissed(sourcemapBaseUrl);
  24994. }
  24995. return error(logInvalidOption('output.sourcemapBaseUrl', URL_OUTPUT_SOURCEMAPBASEURL, `must be a valid URL, received ${JSON.stringify(sourcemapBaseUrl)}`));
  24996. }
  24997. };
  24998. function rollup(rawInputOptions) {
  24999. return rollupInternal(rawInputOptions, null);
  25000. }
  25001. async function rollupInternal(rawInputOptions, watcher) {
  25002. const { options: inputOptions, unsetOptions: unsetInputOptions } = await getInputOptions(rawInputOptions, watcher !== null);
  25003. initialiseTimers(inputOptions);
  25004. const graph = new Graph(inputOptions, watcher);
  25005. // remove the cache object from the memory after graph creation (cache is not used anymore)
  25006. const useCache = rawInputOptions.cache !== false;
  25007. if (rawInputOptions.cache) {
  25008. inputOptions.cache = undefined;
  25009. rawInputOptions.cache = undefined;
  25010. }
  25011. timeStart('BUILD', 1);
  25012. await catchUnfinishedHookActions(graph.pluginDriver, async () => {
  25013. try {
  25014. timeStart('initialize', 2);
  25015. await graph.pluginDriver.hookParallel('buildStart', [inputOptions]);
  25016. timeEnd('initialize', 2);
  25017. await graph.build();
  25018. }
  25019. catch (error_) {
  25020. const watchFiles = Object.keys(graph.watchFiles);
  25021. if (watchFiles.length > 0) {
  25022. error_.watchFiles = watchFiles;
  25023. }
  25024. await graph.pluginDriver.hookParallel('buildEnd', [error_]);
  25025. await graph.pluginDriver.hookParallel('closeBundle', []);
  25026. throw error_;
  25027. }
  25028. await graph.pluginDriver.hookParallel('buildEnd', []);
  25029. });
  25030. timeEnd('BUILD', 1);
  25031. const result = {
  25032. cache: useCache ? graph.getCache() : undefined,
  25033. async close() {
  25034. if (result.closed)
  25035. return;
  25036. result.closed = true;
  25037. await graph.pluginDriver.hookParallel('closeBundle', []);
  25038. },
  25039. closed: false,
  25040. async generate(rawOutputOptions) {
  25041. if (result.closed)
  25042. return error(logAlreadyClosed());
  25043. return handleGenerateWrite(false, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  25044. },
  25045. watchFiles: Object.keys(graph.watchFiles),
  25046. async write(rawOutputOptions) {
  25047. if (result.closed)
  25048. return error(logAlreadyClosed());
  25049. return handleGenerateWrite(true, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  25050. }
  25051. };
  25052. if (inputOptions.perf)
  25053. result.getTimings = getTimings;
  25054. return result;
  25055. }
  25056. async function getInputOptions(initialInputOptions, watchMode) {
  25057. if (!initialInputOptions) {
  25058. throw new Error('You must supply an options object to rollup');
  25059. }
  25060. const processedInputOptions = await getProcessedInputOptions(initialInputOptions, watchMode);
  25061. const { options, unsetOptions } = await normalizeInputOptions(processedInputOptions, watchMode);
  25062. normalizePlugins(options.plugins, ANONYMOUS_PLUGIN_PREFIX);
  25063. return { options, unsetOptions };
  25064. }
  25065. async function getProcessedInputOptions(inputOptions, watchMode) {
  25066. const plugins = getSortedValidatedPlugins('options', await normalizePluginOption(inputOptions.plugins));
  25067. const logLevel = inputOptions.logLevel || LOGLEVEL_INFO;
  25068. const logger = getLogger(plugins, getOnLog(inputOptions, logLevel), watchMode, logLevel);
  25069. for (const plugin of plugins) {
  25070. const { name, options } = plugin;
  25071. const handler = 'handler' in options ? options.handler : options;
  25072. const processedOptions = await handler.call({
  25073. debug: getLogHandler(LOGLEVEL_DEBUG, 'PLUGIN_LOG', logger, name, logLevel),
  25074. error: (error_) => error(logPluginError(normalizeLog(error_), name, { hook: 'onLog' })),
  25075. info: getLogHandler(LOGLEVEL_INFO, 'PLUGIN_LOG', logger, name, logLevel),
  25076. meta: { rollupVersion: version$1, watchMode },
  25077. warn: getLogHandler(LOGLEVEL_WARN, 'PLUGIN_WARNING', logger, name, logLevel)
  25078. }, inputOptions);
  25079. if (processedOptions) {
  25080. inputOptions = processedOptions;
  25081. }
  25082. }
  25083. return inputOptions;
  25084. }
  25085. function normalizePlugins(plugins, anonymousPrefix) {
  25086. for (const [index, plugin] of plugins.entries()) {
  25087. if (!plugin.name) {
  25088. plugin.name = `${anonymousPrefix}${index + 1}`;
  25089. }
  25090. }
  25091. }
  25092. async function handleGenerateWrite(isWrite, inputOptions, unsetInputOptions, rawOutputOptions, graph) {
  25093. const { options: outputOptions, outputPluginDriver, unsetOptions } = await getOutputOptionsAndPluginDriver(rawOutputOptions, graph.pluginDriver, inputOptions, unsetInputOptions);
  25094. return catchUnfinishedHookActions(outputPluginDriver, async () => {
  25095. const bundle = new Bundle(outputOptions, unsetOptions, inputOptions, outputPluginDriver, graph);
  25096. const generated = await bundle.generate(isWrite);
  25097. if (isWrite) {
  25098. timeStart('WRITE', 1);
  25099. if (!outputOptions.dir && !outputOptions.file) {
  25100. return error(logMissingFileOrDirOption());
  25101. }
  25102. await Promise.all(Object.values(generated).map(chunk => graph.fileOperationQueue.run(() => writeOutputFile(chunk, outputOptions))));
  25103. await outputPluginDriver.hookParallel('writeBundle', [outputOptions, generated]);
  25104. timeEnd('WRITE', 1);
  25105. }
  25106. return createOutput(generated);
  25107. });
  25108. }
  25109. async function getOutputOptionsAndPluginDriver(rawOutputOptions, inputPluginDriver, inputOptions, unsetInputOptions) {
  25110. if (!rawOutputOptions) {
  25111. throw new Error('You must supply an options object');
  25112. }
  25113. const rawPlugins = await normalizePluginOption(rawOutputOptions.plugins);
  25114. normalizePlugins(rawPlugins, ANONYMOUS_OUTPUT_PLUGIN_PREFIX);
  25115. const outputPluginDriver = inputPluginDriver.createOutputPluginDriver(rawPlugins);
  25116. return {
  25117. ...(await getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver)),
  25118. outputPluginDriver
  25119. };
  25120. }
  25121. function getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver) {
  25122. return normalizeOutputOptions(outputPluginDriver.hookReduceArg0Sync('outputOptions', [rawOutputOptions], (outputOptions, result) => result || outputOptions, pluginContext => {
  25123. const emitError = () => pluginContext.error(logCannotEmitFromOptionsHook());
  25124. return {
  25125. ...pluginContext,
  25126. emitFile: emitError,
  25127. setAssetSource: emitError
  25128. };
  25129. }), inputOptions, unsetInputOptions);
  25130. }
  25131. function createOutput(outputBundle) {
  25132. return {
  25133. output: Object.values(outputBundle).filter(outputFile => Object.keys(outputFile).length > 0).sort((outputFileA, outputFileB) => getSortingFileType(outputFileA) - getSortingFileType(outputFileB))
  25134. };
  25135. }
  25136. var SortingFileType;
  25137. (function (SortingFileType) {
  25138. SortingFileType[SortingFileType["ENTRY_CHUNK"] = 0] = "ENTRY_CHUNK";
  25139. SortingFileType[SortingFileType["SECONDARY_CHUNK"] = 1] = "SECONDARY_CHUNK";
  25140. SortingFileType[SortingFileType["ASSET"] = 2] = "ASSET";
  25141. })(SortingFileType || (SortingFileType = {}));
  25142. function getSortingFileType(file) {
  25143. if (file.type === 'asset') {
  25144. return SortingFileType.ASSET;
  25145. }
  25146. if (file.isEntry) {
  25147. return SortingFileType.ENTRY_CHUNK;
  25148. }
  25149. return SortingFileType.SECONDARY_CHUNK;
  25150. }
  25151. async function writeOutputFile(outputFile, outputOptions) {
  25152. const fileName = resolve(outputOptions.dir || dirname(outputOptions.file), outputFile.fileName);
  25153. // 'recursive: true' does not throw if the folder structure, or parts of it, already exist
  25154. await mkdir(dirname(fileName), { recursive: true });
  25155. return writeFile(fileName, outputFile.type === 'asset' ? outputFile.source : outputFile.code);
  25156. }
  25157. /**
  25158. * Auxiliary function for defining rollup configuration
  25159. * Mainly to facilitate IDE code prompts, after all, export default does not
  25160. * prompt, even if you add @type annotations, it is not accurate
  25161. * @param options
  25162. */
  25163. function defineConfig(options) {
  25164. return options;
  25165. }
  25166. const {
  25167. env = {},
  25168. argv = [],
  25169. platform = "",
  25170. } = typeof process === "undefined" ? {} : process;
  25171. const isDisabled = "NO_COLOR" in env || argv.includes("--no-color");
  25172. const isForced = "FORCE_COLOR" in env || argv.includes("--color");
  25173. const isWindows = platform === "win32";
  25174. const isDumbTerminal = env.TERM === "dumb";
  25175. const isCompatibleTerminal =
  25176. tty && tty.isatty && tty.isatty(1) && env.TERM && !isDumbTerminal;
  25177. const isCI =
  25178. "CI" in env &&
  25179. ("GITHUB_ACTIONS" in env || "GITLAB_CI" in env || "CIRCLECI" in env);
  25180. const isColorSupported =
  25181. !isDisabled &&
  25182. (isForced || (isWindows && !isDumbTerminal) || isCompatibleTerminal || isCI);
  25183. const replaceClose = (
  25184. index,
  25185. string,
  25186. close,
  25187. replace,
  25188. head = string.substring(0, index) + replace,
  25189. tail = string.substring(index + close.length),
  25190. next = tail.indexOf(close)
  25191. ) => head + (next < 0 ? tail : replaceClose(next, tail, close, replace));
  25192. const clearBleed = (index, string, open, close, replace) =>
  25193. index < 0
  25194. ? open + string + close
  25195. : open + replaceClose(index, string, close, replace) + close;
  25196. const filterEmpty =
  25197. (open, close, replace = open, at = open.length + 1) =>
  25198. (string) =>
  25199. string || !(string === "" || string === undefined)
  25200. ? clearBleed(
  25201. ("" + string).indexOf(close, at),
  25202. string,
  25203. open,
  25204. close,
  25205. replace
  25206. )
  25207. : "";
  25208. const init = (open, close, replace) =>
  25209. filterEmpty(`\x1b[${open}m`, `\x1b[${close}m`, replace);
  25210. const colors = {
  25211. reset: init(0, 0),
  25212. bold: init(1, 22, "\x1b[22m\x1b[1m"),
  25213. dim: init(2, 22, "\x1b[22m\x1b[2m"),
  25214. italic: init(3, 23),
  25215. underline: init(4, 24),
  25216. inverse: init(7, 27),
  25217. hidden: init(8, 28),
  25218. strikethrough: init(9, 29),
  25219. black: init(30, 39),
  25220. red: init(31, 39),
  25221. green: init(32, 39),
  25222. yellow: init(33, 39),
  25223. blue: init(34, 39),
  25224. magenta: init(35, 39),
  25225. cyan: init(36, 39),
  25226. white: init(37, 39),
  25227. gray: init(90, 39),
  25228. bgBlack: init(40, 49),
  25229. bgRed: init(41, 49),
  25230. bgGreen: init(42, 49),
  25231. bgYellow: init(43, 49),
  25232. bgBlue: init(44, 49),
  25233. bgMagenta: init(45, 49),
  25234. bgCyan: init(46, 49),
  25235. bgWhite: init(47, 49),
  25236. blackBright: init(90, 39),
  25237. redBright: init(91, 39),
  25238. greenBright: init(92, 39),
  25239. yellowBright: init(93, 39),
  25240. blueBright: init(94, 39),
  25241. magentaBright: init(95, 39),
  25242. cyanBright: init(96, 39),
  25243. whiteBright: init(97, 39),
  25244. bgBlackBright: init(100, 49),
  25245. bgRedBright: init(101, 49),
  25246. bgGreenBright: init(102, 49),
  25247. bgYellowBright: init(103, 49),
  25248. bgBlueBright: init(104, 49),
  25249. bgMagentaBright: init(105, 49),
  25250. bgCyanBright: init(106, 49),
  25251. bgWhiteBright: init(107, 49),
  25252. };
  25253. const createColors = ({ useColor = isColorSupported } = {}) =>
  25254. useColor
  25255. ? colors
  25256. : Object.keys(colors).reduce(
  25257. (colors, key) => ({ ...colors, [key]: String }),
  25258. {}
  25259. );
  25260. createColors();
  25261. // @see https://no-color.org
  25262. // @see https://www.npmjs.com/package/chalk
  25263. const { bold, cyan, dim, gray, green, red, underline, yellow } = createColors({
  25264. useColor: env$1.FORCE_COLOR !== '0' && !env$1.NO_COLOR
  25265. });
  25266. // log to stderr to keep `rollup main.js > bundle.js` from breaking
  25267. const stderr = (...parameters) => process$1.stderr.write(`${parameters.join('')}\n`);
  25268. function handleError(error, recover = false) {
  25269. const name = error.name || error.cause?.name;
  25270. const nameSection = name ? `${name}: ` : '';
  25271. const pluginSection = error.plugin ? `(plugin ${error.plugin}) ` : '';
  25272. const message = `${pluginSection}${nameSection}${error.message}`;
  25273. const outputLines = [bold(red(`[!] ${bold(message.toString())}`))];
  25274. if (error.url) {
  25275. outputLines.push(cyan(error.url));
  25276. }
  25277. if (error.loc) {
  25278. outputLines.push(`${relativeId((error.loc.file || error.id))} (${error.loc.line}:${error.loc.column})`);
  25279. }
  25280. else if (error.id) {
  25281. outputLines.push(relativeId(error.id));
  25282. }
  25283. if (error.frame) {
  25284. outputLines.push(dim(error.frame));
  25285. }
  25286. if (error.stack) {
  25287. outputLines.push(dim(error.stack?.replace(`${nameSection}${error.message}\n`, '')));
  25288. }
  25289. outputLines.push('', '');
  25290. stderr(outputLines.join('\n'));
  25291. if (!recover)
  25292. process$1.exit(1);
  25293. }
  25294. const commandAliases = {
  25295. c: 'config',
  25296. d: 'dir',
  25297. e: 'external',
  25298. f: 'format',
  25299. g: 'globals',
  25300. h: 'help',
  25301. i: 'input',
  25302. m: 'sourcemap',
  25303. n: 'name',
  25304. o: 'file',
  25305. p: 'plugin',
  25306. v: 'version',
  25307. w: 'watch'
  25308. };
  25309. const EMPTY_COMMAND_OPTIONS = { external: [], globals: undefined };
  25310. async function mergeOptions(config, watchMode, rawCommandOptions = EMPTY_COMMAND_OPTIONS, printLog) {
  25311. const command = getCommandOptions(rawCommandOptions);
  25312. const plugins = await normalizePluginOption(config.plugins);
  25313. const logLevel = config.logLevel || LOGLEVEL_INFO;
  25314. const onLog = getOnLog(config, logLevel, printLog);
  25315. const log = getLogger(plugins, onLog, watchMode, logLevel);
  25316. const inputOptions = await mergeInputOptions(config, command, plugins, log, onLog);
  25317. if (command.output) {
  25318. Object.assign(command, command.output);
  25319. }
  25320. const outputOptionsArray = ensureArray(config.output);
  25321. if (outputOptionsArray.length === 0)
  25322. outputOptionsArray.push({});
  25323. const outputOptions = await Promise.all(outputOptionsArray.map(singleOutputOptions => mergeOutputOptions(singleOutputOptions, command, log)));
  25324. warnUnknownOptions(command, [
  25325. ...Object.keys(inputOptions),
  25326. ...Object.keys(outputOptions[0]).filter(option => option !== 'sourcemapIgnoreList' && option !== 'sourcemapPathTransform'),
  25327. ...Object.keys(commandAliases),
  25328. 'bundleConfigAsCjs',
  25329. 'config',
  25330. 'environment',
  25331. 'filterLogs',
  25332. 'plugin',
  25333. 'silent',
  25334. 'failAfterWarnings',
  25335. 'stdin',
  25336. 'waitForBundleInput',
  25337. 'configPlugin'
  25338. ], 'CLI flags', log, /^_$|output$|config/);
  25339. inputOptions.output = outputOptions;
  25340. return inputOptions;
  25341. }
  25342. function getCommandOptions(rawCommandOptions) {
  25343. const external = rawCommandOptions.external && typeof rawCommandOptions.external === 'string'
  25344. ? rawCommandOptions.external.split(',')
  25345. : [];
  25346. return {
  25347. ...rawCommandOptions,
  25348. external,
  25349. globals: typeof rawCommandOptions.globals === 'string'
  25350. ? rawCommandOptions.globals.split(',').reduce((globals, globalDefinition) => {
  25351. const [id, variableName] = globalDefinition.split(':');
  25352. globals[id] = variableName;
  25353. if (!external.includes(id)) {
  25354. external.push(id);
  25355. }
  25356. return globals;
  25357. }, Object.create(null))
  25358. : undefined
  25359. };
  25360. }
  25361. function mergeInputOptions(config, overrides, plugins, log, onLog) {
  25362. const getOption = (name) => overrides[name] ?? config[name];
  25363. const inputOptions = {
  25364. acorn: getOption('acorn'),
  25365. acornInjectPlugins: config.acornInjectPlugins,
  25366. cache: config.cache,
  25367. context: getOption('context'),
  25368. experimentalCacheExpiry: getOption('experimentalCacheExpiry'),
  25369. experimentalLogSideEffects: getOption('experimentalLogSideEffects'),
  25370. external: getExternal(config, overrides),
  25371. inlineDynamicImports: getOption('inlineDynamicImports'),
  25372. input: getOption('input') || [],
  25373. logLevel: getOption('logLevel'),
  25374. makeAbsoluteExternalsRelative: getOption('makeAbsoluteExternalsRelative'),
  25375. manualChunks: getOption('manualChunks'),
  25376. maxParallelFileOps: getOption('maxParallelFileOps'),
  25377. maxParallelFileReads: getOption('maxParallelFileReads'),
  25378. moduleContext: getOption('moduleContext'),
  25379. onLog,
  25380. onwarn: undefined,
  25381. perf: getOption('perf'),
  25382. plugins,
  25383. preserveEntrySignatures: getOption('preserveEntrySignatures'),
  25384. preserveModules: getOption('preserveModules'),
  25385. preserveSymlinks: getOption('preserveSymlinks'),
  25386. shimMissingExports: getOption('shimMissingExports'),
  25387. strictDeprecations: getOption('strictDeprecations'),
  25388. treeshake: getObjectOption(config, overrides, 'treeshake', objectifyOptionWithPresets(treeshakePresets, 'treeshake', URL_TREESHAKE, 'false, true, ')),
  25389. watch: getWatch(config, overrides)
  25390. };
  25391. warnUnknownOptions(config, Object.keys(inputOptions), 'input options', log, /^output$/);
  25392. return inputOptions;
  25393. }
  25394. const getExternal = (config, overrides) => {
  25395. const configExternal = config.external;
  25396. return typeof configExternal === 'function'
  25397. ? (source, importer, isResolved) => configExternal(source, importer, isResolved) || overrides.external.includes(source)
  25398. : [...ensureArray(configExternal), ...overrides.external];
  25399. };
  25400. const getObjectOption = (config, overrides, name, objectifyValue = objectifyOption) => {
  25401. const commandOption = normalizeObjectOptionValue(overrides[name], objectifyValue);
  25402. const configOption = normalizeObjectOptionValue(config[name], objectifyValue);
  25403. if (commandOption !== undefined) {
  25404. return commandOption && { ...configOption, ...commandOption };
  25405. }
  25406. return configOption;
  25407. };
  25408. const getWatch = (config, overrides) => config.watch !== false && getObjectOption(config, overrides, 'watch');
  25409. const normalizeObjectOptionValue = (optionValue, objectifyValue) => {
  25410. if (!optionValue) {
  25411. return optionValue;
  25412. }
  25413. if (Array.isArray(optionValue)) {
  25414. return optionValue.reduce((result, value) => value && result && { ...result, ...objectifyValue(value) }, {});
  25415. }
  25416. return objectifyValue(optionValue);
  25417. };
  25418. async function mergeOutputOptions(config, overrides, log) {
  25419. const getOption = (name) => overrides[name] ?? config[name];
  25420. const outputOptions = {
  25421. amd: getObjectOption(config, overrides, 'amd'),
  25422. assetFileNames: getOption('assetFileNames'),
  25423. banner: getOption('banner'),
  25424. chunkFileNames: getOption('chunkFileNames'),
  25425. compact: getOption('compact'),
  25426. dir: getOption('dir'),
  25427. dynamicImportFunction: getOption('dynamicImportFunction'),
  25428. dynamicImportInCjs: getOption('dynamicImportInCjs'),
  25429. entryFileNames: getOption('entryFileNames'),
  25430. esModule: getOption('esModule'),
  25431. experimentalDeepDynamicChunkOptimization: getOption('experimentalDeepDynamicChunkOptimization'),
  25432. experimentalMinChunkSize: getOption('experimentalMinChunkSize'),
  25433. exports: getOption('exports'),
  25434. extend: getOption('extend'),
  25435. externalImportAssertions: getOption('externalImportAssertions'),
  25436. externalLiveBindings: getOption('externalLiveBindings'),
  25437. file: getOption('file'),
  25438. footer: getOption('footer'),
  25439. format: getOption('format'),
  25440. freeze: getOption('freeze'),
  25441. generatedCode: getObjectOption(config, overrides, 'generatedCode', objectifyOptionWithPresets(generatedCodePresets, 'output.generatedCode', URL_OUTPUT_GENERATEDCODE, '')),
  25442. globals: getOption('globals'),
  25443. hoistTransitiveImports: getOption('hoistTransitiveImports'),
  25444. indent: getOption('indent'),
  25445. inlineDynamicImports: getOption('inlineDynamicImports'),
  25446. interop: getOption('interop'),
  25447. intro: getOption('intro'),
  25448. manualChunks: getOption('manualChunks'),
  25449. minifyInternalExports: getOption('minifyInternalExports'),
  25450. name: getOption('name'),
  25451. namespaceToStringTag: getOption('namespaceToStringTag'),
  25452. noConflict: getOption('noConflict'),
  25453. outro: getOption('outro'),
  25454. paths: getOption('paths'),
  25455. plugins: await normalizePluginOption(config.plugins),
  25456. preferConst: getOption('preferConst'),
  25457. preserveModules: getOption('preserveModules'),
  25458. preserveModulesRoot: getOption('preserveModulesRoot'),
  25459. sanitizeFileName: getOption('sanitizeFileName'),
  25460. sourcemap: getOption('sourcemap'),
  25461. sourcemapBaseUrl: getOption('sourcemapBaseUrl'),
  25462. sourcemapExcludeSources: getOption('sourcemapExcludeSources'),
  25463. sourcemapFile: getOption('sourcemapFile'),
  25464. sourcemapFileNames: getOption('sourcemapFileNames'),
  25465. sourcemapIgnoreList: getOption('sourcemapIgnoreList'),
  25466. sourcemapPathTransform: getOption('sourcemapPathTransform'),
  25467. strict: getOption('strict'),
  25468. systemNullSetters: getOption('systemNullSetters'),
  25469. validate: getOption('validate')
  25470. };
  25471. warnUnknownOptions(config, Object.keys(outputOptions), 'output options', log);
  25472. return outputOptions;
  25473. }
  25474. class WatchEmitter {
  25475. constructor() {
  25476. this.currentHandlers = Object.create(null);
  25477. this.persistentHandlers = Object.create(null);
  25478. }
  25479. // Will be overwritten by Rollup
  25480. async close() { }
  25481. emit(event, ...parameters) {
  25482. return Promise.all([...this.getCurrentHandlers(event), ...this.getPersistentHandlers(event)].map(handler => handler(...parameters)));
  25483. }
  25484. off(event, listener) {
  25485. const listeners = this.persistentHandlers[event];
  25486. if (listeners) {
  25487. // A hack stolen from "mitt": ">>> 0" does not change numbers >= 0, but -1
  25488. // (which would remove the last array element if used unchanged) is turned
  25489. // into max_int, which is outside the array and does not change anything.
  25490. listeners.splice(listeners.indexOf(listener) >>> 0, 1);
  25491. }
  25492. return this;
  25493. }
  25494. on(event, listener) {
  25495. this.getPersistentHandlers(event).push(listener);
  25496. return this;
  25497. }
  25498. onCurrentRun(event, listener) {
  25499. this.getCurrentHandlers(event).push(listener);
  25500. return this;
  25501. }
  25502. once(event, listener) {
  25503. const selfRemovingListener = (...parameters) => {
  25504. this.off(event, selfRemovingListener);
  25505. return listener(...parameters);
  25506. };
  25507. this.on(event, selfRemovingListener);
  25508. return this;
  25509. }
  25510. removeAllListeners() {
  25511. this.removeListenersForCurrentRun();
  25512. this.persistentHandlers = Object.create(null);
  25513. return this;
  25514. }
  25515. removeListenersForCurrentRun() {
  25516. this.currentHandlers = Object.create(null);
  25517. return this;
  25518. }
  25519. getCurrentHandlers(event) {
  25520. return this.currentHandlers[event] || (this.currentHandlers[event] = []);
  25521. }
  25522. getPersistentHandlers(event) {
  25523. return this.persistentHandlers[event] || (this.persistentHandlers[event] = []);
  25524. }
  25525. }
  25526. let fsEvents;
  25527. let fsEventsImportError;
  25528. async function loadFsEvents() {
  25529. try {
  25530. ({ default: fsEvents } = await import('fsevents'));
  25531. }
  25532. catch (error) {
  25533. fsEventsImportError = error;
  25534. }
  25535. }
  25536. // A call to this function will be injected into the chokidar code
  25537. function getFsEvents() {
  25538. if (fsEventsImportError)
  25539. throw fsEventsImportError;
  25540. return fsEvents;
  25541. }
  25542. const fseventsImporter = /*#__PURE__*/Object.defineProperty({
  25543. __proto__: null,
  25544. getFsEvents,
  25545. loadFsEvents
  25546. }, Symbol.toStringTag, { value: 'Module' });
  25547. function watch(configs) {
  25548. const emitter = new WatchEmitter();
  25549. watchInternal(configs, emitter).catch(error => {
  25550. handleError(error);
  25551. });
  25552. return emitter;
  25553. }
  25554. async function watchInternal(configs, emitter) {
  25555. const optionsList = await Promise.all(ensureArray(configs).map(config => mergeOptions(config, true)));
  25556. const watchOptionsList = optionsList.filter(config => config.watch !== false);
  25557. if (watchOptionsList.length === 0) {
  25558. return error(logInvalidOption('watch', URL_WATCH, 'there must be at least one config where "watch" is not set to "false"'));
  25559. }
  25560. await loadFsEvents();
  25561. const { Watcher } = await import('./watch.js');
  25562. new Watcher(watchOptionsList, emitter);
  25563. }
  25564. export { createFilter, defineConfig, fseventsImporter, getAugmentedNamespace, picomatch, rollup, rollupInternal, version$1 as version, watch };