node-entry.js 828 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202
  1. /*
  2. @license
  3. Rollup.js v4.24.2
  4. Sun, 27 Oct 2024 15:39:37 GMT - commit 32d0e7dae85121ac0850ec28576a10a6302f84a9
  5. https://github.com/rollup/rollup
  6. Released under the MIT License.
  7. */
  8. import { ExportDefaultDeclaration as ExportDefaultDeclaration$1, CallExpression as CallExpression$1, EMPTY_ARRAY, LOGLEVEL_WARN, logUnusedExternalImports, ANNOTATION_KEY, INVALID_ANNOTATION_KEY, Program as Program$1, logIllegalImportReassignment, BLANK, logRedeclarationError, StaticBlock as StaticBlock$1, CatchClause as CatchClause$1, logDuplicateArgumentNameError, logModuleLevelDirective, ReturnStatement as ReturnStatement$1, VariableDeclarator as VariableDeclarator$1, ExpressionStatement as ExpressionStatement$1, logMissingExport, normalize, getImportPath, logMissingNodeBuiltins, logReservedNamespace, error, logIllegalIdentifierAsName, logMissingNameOptionForIifeExport, logMissingNameOptionForUmdExport, Property as Property$1, logConstVariableReassignError, ArrowFunctionExpression as ArrowFunctionExpression$1, EMPTY_SET, logCannotCallNamespace, logEval, BlockStatement as BlockStatement$1, getRollupError, logParseError, logModuleParseError, LOGLEVEL_INFO, logFirstSideEffect, locate, logInvalidAnnotation, Identifier as Identifier$1, logThisIsUndefined, getAstBuffer, convertAnnotations, FIXED_STRINGS, convertNode as convertNode$1, EMPTY_OBJECT, logImportAttributeIsInvalid, logImportOptionsAreInvalid, logSyntheticNamedExportsNeedNamespaceExport, logMissingEntryExport, logDuplicateExportError, logInvalidSourcemapForError, augmentCodeLocation, logInconsistentImportAttributes, logMissingJsxExport, logNamespaceConflict, logAmbiguousExternalNamespaces, logShimmedExport, parseAst, logCircularReexport, logInvalidFormatForTopLevelAwait, TemplateLiteral as TemplateLiteral$1, Literal as Literal$1, logAddonNotGenerated, logIncompatibleExportOptionValue, logMixedExport, logFailedValidation, isPathFragment, logCyclicCrossChunkReexport, getAliasName, logUnexpectedNamedImport, isAbsolute as isAbsolute$1, relative as relative$1, logUnexpectedNamespaceReexport, logEmptyChunk, logMissingGlobalName, logOptimizeChunkStatus, logSourcemapBroken, logConflictingSourcemapSources, logChunkInvalid, logInvalidOption, URL_OUTPUT_FORMAT, URL_OUTPUT_DIR, URL_OUTPUT_SOURCEMAPFILE, URL_OUTPUT_AMD_ID, logCannotAssignModuleToChunk, logAnonymousPluginCache, logDuplicatePluginName, logUnknownOption, printQuotedStringList, LOGLEVEL_ERROR, logLevelPriority, LOGLEVEL_DEBUG, logInvalidSetAssetSourceCall, logPluginError, logNoTransformMapOrAstWithoutCode, relativeId, logBadLoader, logExternalModulesCannotBeTransformedToModules, logInternalIdCannotBeExternal, isRelative, logUnresolvedImport, logUnresolvedImportTreatedAsExternal, logExternalSyntheticExports, logUnresolvedEntry, logUnresolvedImplicitDependant, logExternalModulesCannotBeIncludedInManualChunks, logEntryCannotBeExternal, logImplicitDependantCannotBeExternal, logNoAssetSourceSet, logFileReferenceIdNotFoundForFilename, logAssetReferenceIdNotFoundForSetSource, logAssetSourceAlreadySet, logInvalidRollupPhaseForChunkEmission, warnDeprecation, URL_GENERATEBUNDLE, logFileNameConflict, logAssetNotFinalisedForFileName, logChunkNotGeneratedForFileName, logInvalidLogPosition, logInputHookInOutputPlugin, logInvalidFunctionPluginHook, logInvalidAddonPluginHook, logImplicitDependantIsNotIncluded, logCircularDependency, augmentLogMessage, URL_JSX, URL_TREESHAKE, URL_TREESHAKE_MODULESIDEEFFECTS, logInvalidExportOptionValue, URL_OUTPUT_INTEROP, isValidUrl, addTrailingSlashIfMissed, URL_OUTPUT_SOURCEMAPBASEURL, URL_OUTPUT_INLINEDYNAMICIMPORTS, URL_PRESERVEENTRYSIGNATURES, URL_OUTPUT_AMD_BASEPATH, URL_OUTPUT_GENERATEDCODE, URL_OUTPUT_MANUALCHUNKS, URL_OUTPUT_EXTERNALIMPORTATTRIBUTES, logAlreadyClosed, logMissingFileOrDirOption, logCannotEmitFromOptionsHook, URL_WATCH } from './parseAst.js';
  9. import { relative, dirname, basename, extname, resolve as resolve$1 } from 'node:path';
  10. import { posix, win32, isAbsolute, resolve } from 'path';
  11. import { parseAsync, xxhashBase64Url, xxhashBase36, xxhashBase16 } from '../../native.js';
  12. import process$1, { env as env$1 } from 'node:process';
  13. import { performance } from 'node:perf_hooks';
  14. import { lstat, realpath, readdir, readFile, mkdir, writeFile } from 'node:fs/promises';
  15. import * as tty from 'tty';
  16. var version = "4.24.2";
  17. const comma = ','.charCodeAt(0);
  18. const semicolon = ';'.charCodeAt(0);
  19. const chars$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  20. const intToChar = new Uint8Array(64); // 64 possible chars.
  21. const charToInt = new Uint8Array(128); // z is 122 in ASCII
  22. for (let i = 0; i < chars$1.length; i++) {
  23. const c = chars$1.charCodeAt(i);
  24. intToChar[i] = c;
  25. charToInt[c] = i;
  26. }
  27. function decodeInteger(reader, relative) {
  28. let value = 0;
  29. let shift = 0;
  30. let integer = 0;
  31. do {
  32. const c = reader.next();
  33. integer = charToInt[c];
  34. value |= (integer & 31) << shift;
  35. shift += 5;
  36. } while (integer & 32);
  37. const shouldNegate = value & 1;
  38. value >>>= 1;
  39. if (shouldNegate) {
  40. value = -0x80000000 | -value;
  41. }
  42. return relative + value;
  43. }
  44. function encodeInteger(builder, num, relative) {
  45. let delta = num - relative;
  46. delta = delta < 0 ? (-delta << 1) | 1 : delta << 1;
  47. do {
  48. let clamped = delta & 0b011111;
  49. delta >>>= 5;
  50. if (delta > 0)
  51. clamped |= 0b100000;
  52. builder.write(intToChar[clamped]);
  53. } while (delta > 0);
  54. return num;
  55. }
  56. function hasMoreVlq(reader, max) {
  57. if (reader.pos >= max)
  58. return false;
  59. return reader.peek() !== comma;
  60. }
  61. const bufLength = 1024 * 16;
  62. // Provide a fallback for older environments.
  63. const td = typeof TextDecoder !== 'undefined'
  64. ? /* #__PURE__ */ new TextDecoder()
  65. : typeof Buffer !== 'undefined'
  66. ? {
  67. decode(buf) {
  68. const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
  69. return out.toString();
  70. },
  71. }
  72. : {
  73. decode(buf) {
  74. let out = '';
  75. for (let i = 0; i < buf.length; i++) {
  76. out += String.fromCharCode(buf[i]);
  77. }
  78. return out;
  79. },
  80. };
  81. class StringWriter {
  82. constructor() {
  83. this.pos = 0;
  84. this.out = '';
  85. this.buffer = new Uint8Array(bufLength);
  86. }
  87. write(v) {
  88. const { buffer } = this;
  89. buffer[this.pos++] = v;
  90. if (this.pos === bufLength) {
  91. this.out += td.decode(buffer);
  92. this.pos = 0;
  93. }
  94. }
  95. flush() {
  96. const { buffer, out, pos } = this;
  97. return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
  98. }
  99. }
  100. class StringReader {
  101. constructor(buffer) {
  102. this.pos = 0;
  103. this.buffer = buffer;
  104. }
  105. next() {
  106. return this.buffer.charCodeAt(this.pos++);
  107. }
  108. peek() {
  109. return this.buffer.charCodeAt(this.pos);
  110. }
  111. indexOf(char) {
  112. const { buffer, pos } = this;
  113. const idx = buffer.indexOf(char, pos);
  114. return idx === -1 ? buffer.length : idx;
  115. }
  116. }
  117. function decode(mappings) {
  118. const { length } = mappings;
  119. const reader = new StringReader(mappings);
  120. const decoded = [];
  121. let genColumn = 0;
  122. let sourcesIndex = 0;
  123. let sourceLine = 0;
  124. let sourceColumn = 0;
  125. let namesIndex = 0;
  126. do {
  127. const semi = reader.indexOf(';');
  128. const line = [];
  129. let sorted = true;
  130. let lastCol = 0;
  131. genColumn = 0;
  132. while (reader.pos < semi) {
  133. let seg;
  134. genColumn = decodeInteger(reader, genColumn);
  135. if (genColumn < lastCol)
  136. sorted = false;
  137. lastCol = genColumn;
  138. if (hasMoreVlq(reader, semi)) {
  139. sourcesIndex = decodeInteger(reader, sourcesIndex);
  140. sourceLine = decodeInteger(reader, sourceLine);
  141. sourceColumn = decodeInteger(reader, sourceColumn);
  142. if (hasMoreVlq(reader, semi)) {
  143. namesIndex = decodeInteger(reader, namesIndex);
  144. seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex];
  145. }
  146. else {
  147. seg = [genColumn, sourcesIndex, sourceLine, sourceColumn];
  148. }
  149. }
  150. else {
  151. seg = [genColumn];
  152. }
  153. line.push(seg);
  154. reader.pos++;
  155. }
  156. if (!sorted)
  157. sort(line);
  158. decoded.push(line);
  159. reader.pos = semi + 1;
  160. } while (reader.pos <= length);
  161. return decoded;
  162. }
  163. function sort(line) {
  164. line.sort(sortComparator);
  165. }
  166. function sortComparator(a, b) {
  167. return a[0] - b[0];
  168. }
  169. function encode(decoded) {
  170. const writer = new StringWriter();
  171. let sourcesIndex = 0;
  172. let sourceLine = 0;
  173. let sourceColumn = 0;
  174. let namesIndex = 0;
  175. for (let i = 0; i < decoded.length; i++) {
  176. const line = decoded[i];
  177. if (i > 0)
  178. writer.write(semicolon);
  179. if (line.length === 0)
  180. continue;
  181. let genColumn = 0;
  182. for (let j = 0; j < line.length; j++) {
  183. const segment = line[j];
  184. if (j > 0)
  185. writer.write(comma);
  186. genColumn = encodeInteger(writer, segment[0], genColumn);
  187. if (segment.length === 1)
  188. continue;
  189. sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
  190. sourceLine = encodeInteger(writer, segment[2], sourceLine);
  191. sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
  192. if (segment.length === 4)
  193. continue;
  194. namesIndex = encodeInteger(writer, segment[4], namesIndex);
  195. }
  196. }
  197. return writer.flush();
  198. }
  199. class BitSet {
  200. constructor(arg) {
  201. this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
  202. }
  203. add(n) {
  204. this.bits[n >> 5] |= 1 << (n & 31);
  205. }
  206. has(n) {
  207. return !!(this.bits[n >> 5] & (1 << (n & 31)));
  208. }
  209. }
  210. let Chunk$1 = class Chunk {
  211. constructor(start, end, content) {
  212. this.start = start;
  213. this.end = end;
  214. this.original = content;
  215. this.intro = '';
  216. this.outro = '';
  217. this.content = content;
  218. this.storeName = false;
  219. this.edited = false;
  220. {
  221. this.previous = null;
  222. this.next = null;
  223. }
  224. }
  225. appendLeft(content) {
  226. this.outro += content;
  227. }
  228. appendRight(content) {
  229. this.intro = this.intro + content;
  230. }
  231. clone() {
  232. const chunk = new Chunk(this.start, this.end, this.original);
  233. chunk.intro = this.intro;
  234. chunk.outro = this.outro;
  235. chunk.content = this.content;
  236. chunk.storeName = this.storeName;
  237. chunk.edited = this.edited;
  238. return chunk;
  239. }
  240. contains(index) {
  241. return this.start < index && index < this.end;
  242. }
  243. eachNext(fn) {
  244. let chunk = this;
  245. while (chunk) {
  246. fn(chunk);
  247. chunk = chunk.next;
  248. }
  249. }
  250. eachPrevious(fn) {
  251. let chunk = this;
  252. while (chunk) {
  253. fn(chunk);
  254. chunk = chunk.previous;
  255. }
  256. }
  257. edit(content, storeName, contentOnly) {
  258. this.content = content;
  259. if (!contentOnly) {
  260. this.intro = '';
  261. this.outro = '';
  262. }
  263. this.storeName = storeName;
  264. this.edited = true;
  265. return this;
  266. }
  267. prependLeft(content) {
  268. this.outro = content + this.outro;
  269. }
  270. prependRight(content) {
  271. this.intro = content + this.intro;
  272. }
  273. reset() {
  274. this.intro = '';
  275. this.outro = '';
  276. if (this.edited) {
  277. this.content = this.original;
  278. this.storeName = false;
  279. this.edited = false;
  280. }
  281. }
  282. split(index) {
  283. const sliceIndex = index - this.start;
  284. const originalBefore = this.original.slice(0, sliceIndex);
  285. const originalAfter = this.original.slice(sliceIndex);
  286. this.original = originalBefore;
  287. const newChunk = new Chunk(index, this.end, originalAfter);
  288. newChunk.outro = this.outro;
  289. this.outro = '';
  290. this.end = index;
  291. if (this.edited) {
  292. // after split we should save the edit content record into the correct chunk
  293. // to make sure sourcemap correct
  294. // For example:
  295. // ' test'.trim()
  296. // split -> ' ' + 'test'
  297. // ✔️ edit -> '' + 'test'
  298. // ✖️ edit -> 'test' + ''
  299. // TODO is this block necessary?...
  300. newChunk.edit('', false);
  301. this.content = '';
  302. } else {
  303. this.content = originalBefore;
  304. }
  305. newChunk.next = this.next;
  306. if (newChunk.next) newChunk.next.previous = newChunk;
  307. newChunk.previous = this;
  308. this.next = newChunk;
  309. return newChunk;
  310. }
  311. toString() {
  312. return this.intro + this.content + this.outro;
  313. }
  314. trimEnd(rx) {
  315. this.outro = this.outro.replace(rx, '');
  316. if (this.outro.length) return true;
  317. const trimmed = this.content.replace(rx, '');
  318. if (trimmed.length) {
  319. if (trimmed !== this.content) {
  320. this.split(this.start + trimmed.length).edit('', undefined, true);
  321. if (this.edited) {
  322. // save the change, if it has been edited
  323. this.edit(trimmed, this.storeName, true);
  324. }
  325. }
  326. return true;
  327. } else {
  328. this.edit('', undefined, true);
  329. this.intro = this.intro.replace(rx, '');
  330. if (this.intro.length) return true;
  331. }
  332. }
  333. trimStart(rx) {
  334. this.intro = this.intro.replace(rx, '');
  335. if (this.intro.length) return true;
  336. const trimmed = this.content.replace(rx, '');
  337. if (trimmed.length) {
  338. if (trimmed !== this.content) {
  339. const newChunk = this.split(this.end - trimmed.length);
  340. if (this.edited) {
  341. // save the change, if it has been edited
  342. newChunk.edit(trimmed, this.storeName, true);
  343. }
  344. this.edit('', undefined, true);
  345. }
  346. return true;
  347. } else {
  348. this.edit('', undefined, true);
  349. this.outro = this.outro.replace(rx, '');
  350. if (this.outro.length) return true;
  351. }
  352. }
  353. };
  354. function getBtoa() {
  355. if (typeof globalThis !== 'undefined' && typeof globalThis.btoa === 'function') {
  356. return (str) => globalThis.btoa(unescape(encodeURIComponent(str)));
  357. } else if (typeof Buffer === 'function') {
  358. return (str) => Buffer.from(str, 'utf-8').toString('base64');
  359. } else {
  360. return () => {
  361. throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
  362. };
  363. }
  364. }
  365. const btoa = /*#__PURE__*/ getBtoa();
  366. class SourceMap {
  367. constructor(properties) {
  368. this.version = 3;
  369. this.file = properties.file;
  370. this.sources = properties.sources;
  371. this.sourcesContent = properties.sourcesContent;
  372. this.names = properties.names;
  373. this.mappings = encode(properties.mappings);
  374. if (typeof properties.x_google_ignoreList !== 'undefined') {
  375. this.x_google_ignoreList = properties.x_google_ignoreList;
  376. }
  377. }
  378. toString() {
  379. return JSON.stringify(this);
  380. }
  381. toUrl() {
  382. return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
  383. }
  384. }
  385. function guessIndent(code) {
  386. const lines = code.split('\n');
  387. const tabbed = lines.filter((line) => /^\t+/.test(line));
  388. const spaced = lines.filter((line) => /^ {2,}/.test(line));
  389. if (tabbed.length === 0 && spaced.length === 0) {
  390. return null;
  391. }
  392. // More lines tabbed than spaced? Assume tabs, and
  393. // default to tabs in the case of a tie (or nothing
  394. // to go on)
  395. if (tabbed.length >= spaced.length) {
  396. return '\t';
  397. }
  398. // Otherwise, we need to guess the multiple
  399. const min = spaced.reduce((previous, current) => {
  400. const numSpaces = /^ +/.exec(current)[0].length;
  401. return Math.min(numSpaces, previous);
  402. }, Infinity);
  403. return new Array(min + 1).join(' ');
  404. }
  405. function getRelativePath(from, to) {
  406. const fromParts = from.split(/[/\\]/);
  407. const toParts = to.split(/[/\\]/);
  408. fromParts.pop(); // get dirname
  409. while (fromParts[0] === toParts[0]) {
  410. fromParts.shift();
  411. toParts.shift();
  412. }
  413. if (fromParts.length) {
  414. let i = fromParts.length;
  415. while (i--) fromParts[i] = '..';
  416. }
  417. return fromParts.concat(toParts).join('/');
  418. }
  419. const toString = Object.prototype.toString;
  420. function isObject(thing) {
  421. return toString.call(thing) === '[object Object]';
  422. }
  423. function getLocator(source) {
  424. const originalLines = source.split('\n');
  425. const lineOffsets = [];
  426. for (let i = 0, pos = 0; i < originalLines.length; i++) {
  427. lineOffsets.push(pos);
  428. pos += originalLines[i].length + 1;
  429. }
  430. return function locate(index) {
  431. let i = 0;
  432. let j = lineOffsets.length;
  433. while (i < j) {
  434. const m = (i + j) >> 1;
  435. if (index < lineOffsets[m]) {
  436. j = m;
  437. } else {
  438. i = m + 1;
  439. }
  440. }
  441. const line = i - 1;
  442. const column = index - lineOffsets[line];
  443. return { line, column };
  444. };
  445. }
  446. const wordRegex = /\w/;
  447. class Mappings {
  448. constructor(hires) {
  449. this.hires = hires;
  450. this.generatedCodeLine = 0;
  451. this.generatedCodeColumn = 0;
  452. this.raw = [];
  453. this.rawSegments = this.raw[this.generatedCodeLine] = [];
  454. this.pending = null;
  455. }
  456. addEdit(sourceIndex, content, loc, nameIndex) {
  457. if (content.length) {
  458. const contentLengthMinusOne = content.length - 1;
  459. let contentLineEnd = content.indexOf('\n', 0);
  460. let previousContentLineEnd = -1;
  461. // Loop through each line in the content and add a segment, but stop if the last line is empty,
  462. // else code afterwards would fill one line too many
  463. while (contentLineEnd >= 0 && contentLengthMinusOne > contentLineEnd) {
  464. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  465. if (nameIndex >= 0) {
  466. segment.push(nameIndex);
  467. }
  468. this.rawSegments.push(segment);
  469. this.generatedCodeLine += 1;
  470. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  471. this.generatedCodeColumn = 0;
  472. previousContentLineEnd = contentLineEnd;
  473. contentLineEnd = content.indexOf('\n', contentLineEnd + 1);
  474. }
  475. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  476. if (nameIndex >= 0) {
  477. segment.push(nameIndex);
  478. }
  479. this.rawSegments.push(segment);
  480. this.advance(content.slice(previousContentLineEnd + 1));
  481. } else if (this.pending) {
  482. this.rawSegments.push(this.pending);
  483. this.advance(content);
  484. }
  485. this.pending = null;
  486. }
  487. addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
  488. let originalCharIndex = chunk.start;
  489. let first = true;
  490. // when iterating each char, check if it's in a word boundary
  491. let charInHiresBoundary = false;
  492. while (originalCharIndex < chunk.end) {
  493. if (original[originalCharIndex] === '\n') {
  494. loc.line += 1;
  495. loc.column = 0;
  496. this.generatedCodeLine += 1;
  497. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  498. this.generatedCodeColumn = 0;
  499. first = true;
  500. } else {
  501. if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
  502. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  503. if (this.hires === 'boundary') {
  504. // in hires "boundary", group segments per word boundary than per char
  505. if (wordRegex.test(original[originalCharIndex])) {
  506. // for first char in the boundary found, start the boundary by pushing a segment
  507. if (!charInHiresBoundary) {
  508. this.rawSegments.push(segment);
  509. charInHiresBoundary = true;
  510. }
  511. } else {
  512. // for non-word char, end the boundary by pushing a segment
  513. this.rawSegments.push(segment);
  514. charInHiresBoundary = false;
  515. }
  516. } else {
  517. this.rawSegments.push(segment);
  518. }
  519. }
  520. loc.column += 1;
  521. this.generatedCodeColumn += 1;
  522. first = false;
  523. }
  524. originalCharIndex += 1;
  525. }
  526. this.pending = null;
  527. }
  528. advance(str) {
  529. if (!str) return;
  530. const lines = str.split('\n');
  531. if (lines.length > 1) {
  532. for (let i = 0; i < lines.length - 1; i++) {
  533. this.generatedCodeLine++;
  534. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  535. }
  536. this.generatedCodeColumn = 0;
  537. }
  538. this.generatedCodeColumn += lines[lines.length - 1].length;
  539. }
  540. }
  541. const n = '\n';
  542. const warned = {
  543. insertLeft: false,
  544. insertRight: false,
  545. storeName: false,
  546. };
  547. class MagicString {
  548. constructor(string, options = {}) {
  549. const chunk = new Chunk$1(0, string.length, string);
  550. Object.defineProperties(this, {
  551. original: { writable: true, value: string },
  552. outro: { writable: true, value: '' },
  553. intro: { writable: true, value: '' },
  554. firstChunk: { writable: true, value: chunk },
  555. lastChunk: { writable: true, value: chunk },
  556. lastSearchedChunk: { writable: true, value: chunk },
  557. byStart: { writable: true, value: {} },
  558. byEnd: { writable: true, value: {} },
  559. filename: { writable: true, value: options.filename },
  560. indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
  561. sourcemapLocations: { writable: true, value: new BitSet() },
  562. storedNames: { writable: true, value: {} },
  563. indentStr: { writable: true, value: undefined },
  564. ignoreList: { writable: true, value: options.ignoreList },
  565. });
  566. this.byStart[0] = chunk;
  567. this.byEnd[string.length] = chunk;
  568. }
  569. addSourcemapLocation(char) {
  570. this.sourcemapLocations.add(char);
  571. }
  572. append(content) {
  573. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  574. this.outro += content;
  575. return this;
  576. }
  577. appendLeft(index, content) {
  578. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  579. this._split(index);
  580. const chunk = this.byEnd[index];
  581. if (chunk) {
  582. chunk.appendLeft(content);
  583. } else {
  584. this.intro += content;
  585. }
  586. return this;
  587. }
  588. appendRight(index, content) {
  589. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  590. this._split(index);
  591. const chunk = this.byStart[index];
  592. if (chunk) {
  593. chunk.appendRight(content);
  594. } else {
  595. this.outro += content;
  596. }
  597. return this;
  598. }
  599. clone() {
  600. const cloned = new MagicString(this.original, { filename: this.filename });
  601. let originalChunk = this.firstChunk;
  602. let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
  603. while (originalChunk) {
  604. cloned.byStart[clonedChunk.start] = clonedChunk;
  605. cloned.byEnd[clonedChunk.end] = clonedChunk;
  606. const nextOriginalChunk = originalChunk.next;
  607. const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
  608. if (nextClonedChunk) {
  609. clonedChunk.next = nextClonedChunk;
  610. nextClonedChunk.previous = clonedChunk;
  611. clonedChunk = nextClonedChunk;
  612. }
  613. originalChunk = nextOriginalChunk;
  614. }
  615. cloned.lastChunk = clonedChunk;
  616. if (this.indentExclusionRanges) {
  617. cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
  618. }
  619. cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
  620. cloned.intro = this.intro;
  621. cloned.outro = this.outro;
  622. return cloned;
  623. }
  624. generateDecodedMap(options) {
  625. options = options || {};
  626. const sourceIndex = 0;
  627. const names = Object.keys(this.storedNames);
  628. const mappings = new Mappings(options.hires);
  629. const locate = getLocator(this.original);
  630. if (this.intro) {
  631. mappings.advance(this.intro);
  632. }
  633. this.firstChunk.eachNext((chunk) => {
  634. const loc = locate(chunk.start);
  635. if (chunk.intro.length) mappings.advance(chunk.intro);
  636. if (chunk.edited) {
  637. mappings.addEdit(
  638. sourceIndex,
  639. chunk.content,
  640. loc,
  641. chunk.storeName ? names.indexOf(chunk.original) : -1,
  642. );
  643. } else {
  644. mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
  645. }
  646. if (chunk.outro.length) mappings.advance(chunk.outro);
  647. });
  648. return {
  649. file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
  650. sources: [
  651. options.source ? getRelativePath(options.file || '', options.source) : options.file || '',
  652. ],
  653. sourcesContent: options.includeContent ? [this.original] : undefined,
  654. names,
  655. mappings: mappings.raw,
  656. x_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined,
  657. };
  658. }
  659. generateMap(options) {
  660. return new SourceMap(this.generateDecodedMap(options));
  661. }
  662. _ensureindentStr() {
  663. if (this.indentStr === undefined) {
  664. this.indentStr = guessIndent(this.original);
  665. }
  666. }
  667. _getRawIndentString() {
  668. this._ensureindentStr();
  669. return this.indentStr;
  670. }
  671. getIndentString() {
  672. this._ensureindentStr();
  673. return this.indentStr === null ? '\t' : this.indentStr;
  674. }
  675. indent(indentStr, options) {
  676. const pattern = /^[^\r\n]/gm;
  677. if (isObject(indentStr)) {
  678. options = indentStr;
  679. indentStr = undefined;
  680. }
  681. if (indentStr === undefined) {
  682. this._ensureindentStr();
  683. indentStr = this.indentStr || '\t';
  684. }
  685. if (indentStr === '') return this; // noop
  686. options = options || {};
  687. // Process exclusion ranges
  688. const isExcluded = {};
  689. if (options.exclude) {
  690. const exclusions =
  691. typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
  692. exclusions.forEach((exclusion) => {
  693. for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
  694. isExcluded[i] = true;
  695. }
  696. });
  697. }
  698. let shouldIndentNextCharacter = options.indentStart !== false;
  699. const replacer = (match) => {
  700. if (shouldIndentNextCharacter) return `${indentStr}${match}`;
  701. shouldIndentNextCharacter = true;
  702. return match;
  703. };
  704. this.intro = this.intro.replace(pattern, replacer);
  705. let charIndex = 0;
  706. let chunk = this.firstChunk;
  707. while (chunk) {
  708. const end = chunk.end;
  709. if (chunk.edited) {
  710. if (!isExcluded[charIndex]) {
  711. chunk.content = chunk.content.replace(pattern, replacer);
  712. if (chunk.content.length) {
  713. shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
  714. }
  715. }
  716. } else {
  717. charIndex = chunk.start;
  718. while (charIndex < end) {
  719. if (!isExcluded[charIndex]) {
  720. const char = this.original[charIndex];
  721. if (char === '\n') {
  722. shouldIndentNextCharacter = true;
  723. } else if (char !== '\r' && shouldIndentNextCharacter) {
  724. shouldIndentNextCharacter = false;
  725. if (charIndex === chunk.start) {
  726. chunk.prependRight(indentStr);
  727. } else {
  728. this._splitChunk(chunk, charIndex);
  729. chunk = chunk.next;
  730. chunk.prependRight(indentStr);
  731. }
  732. }
  733. }
  734. charIndex += 1;
  735. }
  736. }
  737. charIndex = chunk.end;
  738. chunk = chunk.next;
  739. }
  740. this.outro = this.outro.replace(pattern, replacer);
  741. return this;
  742. }
  743. insert() {
  744. throw new Error(
  745. 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)',
  746. );
  747. }
  748. insertLeft(index, content) {
  749. if (!warned.insertLeft) {
  750. console.warn(
  751. 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead',
  752. ); // eslint-disable-line no-console
  753. warned.insertLeft = true;
  754. }
  755. return this.appendLeft(index, content);
  756. }
  757. insertRight(index, content) {
  758. if (!warned.insertRight) {
  759. console.warn(
  760. 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead',
  761. ); // eslint-disable-line no-console
  762. warned.insertRight = true;
  763. }
  764. return this.prependRight(index, content);
  765. }
  766. move(start, end, index) {
  767. if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself');
  768. this._split(start);
  769. this._split(end);
  770. this._split(index);
  771. const first = this.byStart[start];
  772. const last = this.byEnd[end];
  773. const oldLeft = first.previous;
  774. const oldRight = last.next;
  775. const newRight = this.byStart[index];
  776. if (!newRight && last === this.lastChunk) return this;
  777. const newLeft = newRight ? newRight.previous : this.lastChunk;
  778. if (oldLeft) oldLeft.next = oldRight;
  779. if (oldRight) oldRight.previous = oldLeft;
  780. if (newLeft) newLeft.next = first;
  781. if (newRight) newRight.previous = last;
  782. if (!first.previous) this.firstChunk = last.next;
  783. if (!last.next) {
  784. this.lastChunk = first.previous;
  785. this.lastChunk.next = null;
  786. }
  787. first.previous = newLeft;
  788. last.next = newRight || null;
  789. if (!newLeft) this.firstChunk = first;
  790. if (!newRight) this.lastChunk = last;
  791. return this;
  792. }
  793. overwrite(start, end, content, options) {
  794. options = options || {};
  795. return this.update(start, end, content, { ...options, overwrite: !options.contentOnly });
  796. }
  797. update(start, end, content, options) {
  798. if (typeof content !== 'string') throw new TypeError('replacement content must be a string');
  799. if (this.original.length !== 0) {
  800. while (start < 0) start += this.original.length;
  801. while (end < 0) end += this.original.length;
  802. }
  803. if (end > this.original.length) throw new Error('end is out of bounds');
  804. if (start === end)
  805. throw new Error(
  806. 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead',
  807. );
  808. this._split(start);
  809. this._split(end);
  810. if (options === true) {
  811. if (!warned.storeName) {
  812. console.warn(
  813. 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string',
  814. ); // eslint-disable-line no-console
  815. warned.storeName = true;
  816. }
  817. options = { storeName: true };
  818. }
  819. const storeName = options !== undefined ? options.storeName : false;
  820. const overwrite = options !== undefined ? options.overwrite : false;
  821. if (storeName) {
  822. const original = this.original.slice(start, end);
  823. Object.defineProperty(this.storedNames, original, {
  824. writable: true,
  825. value: true,
  826. enumerable: true,
  827. });
  828. }
  829. const first = this.byStart[start];
  830. const last = this.byEnd[end];
  831. if (first) {
  832. let chunk = first;
  833. while (chunk !== last) {
  834. if (chunk.next !== this.byStart[chunk.end]) {
  835. throw new Error('Cannot overwrite across a split point');
  836. }
  837. chunk = chunk.next;
  838. chunk.edit('', false);
  839. }
  840. first.edit(content, storeName, !overwrite);
  841. } else {
  842. // must be inserting at the end
  843. const newChunk = new Chunk$1(start, end, '').edit(content, storeName);
  844. // TODO last chunk in the array may not be the last chunk, if it's moved...
  845. last.next = newChunk;
  846. newChunk.previous = last;
  847. }
  848. return this;
  849. }
  850. prepend(content) {
  851. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  852. this.intro = content + this.intro;
  853. return this;
  854. }
  855. prependLeft(index, content) {
  856. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  857. this._split(index);
  858. const chunk = this.byEnd[index];
  859. if (chunk) {
  860. chunk.prependLeft(content);
  861. } else {
  862. this.intro = content + this.intro;
  863. }
  864. return this;
  865. }
  866. prependRight(index, content) {
  867. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  868. this._split(index);
  869. const chunk = this.byStart[index];
  870. if (chunk) {
  871. chunk.prependRight(content);
  872. } else {
  873. this.outro = content + this.outro;
  874. }
  875. return this;
  876. }
  877. remove(start, end) {
  878. if (this.original.length !== 0) {
  879. while (start < 0) start += this.original.length;
  880. while (end < 0) end += this.original.length;
  881. }
  882. if (start === end) return this;
  883. if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
  884. if (start > end) throw new Error('end must be greater than start');
  885. this._split(start);
  886. this._split(end);
  887. let chunk = this.byStart[start];
  888. while (chunk) {
  889. chunk.intro = '';
  890. chunk.outro = '';
  891. chunk.edit('');
  892. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  893. }
  894. return this;
  895. }
  896. reset(start, end) {
  897. if (this.original.length !== 0) {
  898. while (start < 0) start += this.original.length;
  899. while (end < 0) end += this.original.length;
  900. }
  901. if (start === end) return this;
  902. if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
  903. if (start > end) throw new Error('end must be greater than start');
  904. this._split(start);
  905. this._split(end);
  906. let chunk = this.byStart[start];
  907. while (chunk) {
  908. chunk.reset();
  909. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  910. }
  911. return this;
  912. }
  913. lastChar() {
  914. if (this.outro.length) return this.outro[this.outro.length - 1];
  915. let chunk = this.lastChunk;
  916. do {
  917. if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
  918. if (chunk.content.length) return chunk.content[chunk.content.length - 1];
  919. if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
  920. } while ((chunk = chunk.previous));
  921. if (this.intro.length) return this.intro[this.intro.length - 1];
  922. return '';
  923. }
  924. lastLine() {
  925. let lineIndex = this.outro.lastIndexOf(n);
  926. if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
  927. let lineStr = this.outro;
  928. let chunk = this.lastChunk;
  929. do {
  930. if (chunk.outro.length > 0) {
  931. lineIndex = chunk.outro.lastIndexOf(n);
  932. if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
  933. lineStr = chunk.outro + lineStr;
  934. }
  935. if (chunk.content.length > 0) {
  936. lineIndex = chunk.content.lastIndexOf(n);
  937. if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
  938. lineStr = chunk.content + lineStr;
  939. }
  940. if (chunk.intro.length > 0) {
  941. lineIndex = chunk.intro.lastIndexOf(n);
  942. if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
  943. lineStr = chunk.intro + lineStr;
  944. }
  945. } while ((chunk = chunk.previous));
  946. lineIndex = this.intro.lastIndexOf(n);
  947. if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
  948. return this.intro + lineStr;
  949. }
  950. slice(start = 0, end = this.original.length) {
  951. if (this.original.length !== 0) {
  952. while (start < 0) start += this.original.length;
  953. while (end < 0) end += this.original.length;
  954. }
  955. let result = '';
  956. // find start chunk
  957. let chunk = this.firstChunk;
  958. while (chunk && (chunk.start > start || chunk.end <= start)) {
  959. // found end chunk before start
  960. if (chunk.start < end && chunk.end >= end) {
  961. return result;
  962. }
  963. chunk = chunk.next;
  964. }
  965. if (chunk && chunk.edited && chunk.start !== start)
  966. throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
  967. const startChunk = chunk;
  968. while (chunk) {
  969. if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
  970. result += chunk.intro;
  971. }
  972. const containsEnd = chunk.start < end && chunk.end >= end;
  973. if (containsEnd && chunk.edited && chunk.end !== end)
  974. throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
  975. const sliceStart = startChunk === chunk ? start - chunk.start : 0;
  976. const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
  977. result += chunk.content.slice(sliceStart, sliceEnd);
  978. if (chunk.outro && (!containsEnd || chunk.end === end)) {
  979. result += chunk.outro;
  980. }
  981. if (containsEnd) {
  982. break;
  983. }
  984. chunk = chunk.next;
  985. }
  986. return result;
  987. }
  988. // TODO deprecate this? not really very useful
  989. snip(start, end) {
  990. const clone = this.clone();
  991. clone.remove(0, start);
  992. clone.remove(end, clone.original.length);
  993. return clone;
  994. }
  995. _split(index) {
  996. if (this.byStart[index] || this.byEnd[index]) return;
  997. let chunk = this.lastSearchedChunk;
  998. const searchForward = index > chunk.end;
  999. while (chunk) {
  1000. if (chunk.contains(index)) return this._splitChunk(chunk, index);
  1001. chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
  1002. }
  1003. }
  1004. _splitChunk(chunk, index) {
  1005. if (chunk.edited && chunk.content.length) {
  1006. // zero-length edited chunks are a special case (overlapping replacements)
  1007. const loc = getLocator(this.original)(index);
  1008. throw new Error(
  1009. `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`,
  1010. );
  1011. }
  1012. const newChunk = chunk.split(index);
  1013. this.byEnd[index] = chunk;
  1014. this.byStart[index] = newChunk;
  1015. this.byEnd[newChunk.end] = newChunk;
  1016. if (chunk === this.lastChunk) this.lastChunk = newChunk;
  1017. this.lastSearchedChunk = chunk;
  1018. return true;
  1019. }
  1020. toString() {
  1021. let str = this.intro;
  1022. let chunk = this.firstChunk;
  1023. while (chunk) {
  1024. str += chunk.toString();
  1025. chunk = chunk.next;
  1026. }
  1027. return str + this.outro;
  1028. }
  1029. isEmpty() {
  1030. let chunk = this.firstChunk;
  1031. do {
  1032. if (
  1033. (chunk.intro.length && chunk.intro.trim()) ||
  1034. (chunk.content.length && chunk.content.trim()) ||
  1035. (chunk.outro.length && chunk.outro.trim())
  1036. )
  1037. return false;
  1038. } while ((chunk = chunk.next));
  1039. return true;
  1040. }
  1041. length() {
  1042. let chunk = this.firstChunk;
  1043. let length = 0;
  1044. do {
  1045. length += chunk.intro.length + chunk.content.length + chunk.outro.length;
  1046. } while ((chunk = chunk.next));
  1047. return length;
  1048. }
  1049. trimLines() {
  1050. return this.trim('[\\r\\n]');
  1051. }
  1052. trim(charType) {
  1053. return this.trimStart(charType).trimEnd(charType);
  1054. }
  1055. trimEndAborted(charType) {
  1056. const rx = new RegExp((charType || '\\s') + '+$');
  1057. this.outro = this.outro.replace(rx, '');
  1058. if (this.outro.length) return true;
  1059. let chunk = this.lastChunk;
  1060. do {
  1061. const end = chunk.end;
  1062. const aborted = chunk.trimEnd(rx);
  1063. // if chunk was trimmed, we have a new lastChunk
  1064. if (chunk.end !== end) {
  1065. if (this.lastChunk === chunk) {
  1066. this.lastChunk = chunk.next;
  1067. }
  1068. this.byEnd[chunk.end] = chunk;
  1069. this.byStart[chunk.next.start] = chunk.next;
  1070. this.byEnd[chunk.next.end] = chunk.next;
  1071. }
  1072. if (aborted) return true;
  1073. chunk = chunk.previous;
  1074. } while (chunk);
  1075. return false;
  1076. }
  1077. trimEnd(charType) {
  1078. this.trimEndAborted(charType);
  1079. return this;
  1080. }
  1081. trimStartAborted(charType) {
  1082. const rx = new RegExp('^' + (charType || '\\s') + '+');
  1083. this.intro = this.intro.replace(rx, '');
  1084. if (this.intro.length) return true;
  1085. let chunk = this.firstChunk;
  1086. do {
  1087. const end = chunk.end;
  1088. const aborted = chunk.trimStart(rx);
  1089. if (chunk.end !== end) {
  1090. // special case...
  1091. if (chunk === this.lastChunk) this.lastChunk = chunk.next;
  1092. this.byEnd[chunk.end] = chunk;
  1093. this.byStart[chunk.next.start] = chunk.next;
  1094. this.byEnd[chunk.next.end] = chunk.next;
  1095. }
  1096. if (aborted) return true;
  1097. chunk = chunk.next;
  1098. } while (chunk);
  1099. return false;
  1100. }
  1101. trimStart(charType) {
  1102. this.trimStartAborted(charType);
  1103. return this;
  1104. }
  1105. hasChanged() {
  1106. return this.original !== this.toString();
  1107. }
  1108. _replaceRegexp(searchValue, replacement) {
  1109. function getReplacement(match, str) {
  1110. if (typeof replacement === 'string') {
  1111. return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
  1112. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
  1113. if (i === '$') return '$';
  1114. if (i === '&') return match[0];
  1115. const num = +i;
  1116. if (num < match.length) return match[+i];
  1117. return `$${i}`;
  1118. });
  1119. } else {
  1120. return replacement(...match, match.index, str, match.groups);
  1121. }
  1122. }
  1123. function matchAll(re, str) {
  1124. let match;
  1125. const matches = [];
  1126. while ((match = re.exec(str))) {
  1127. matches.push(match);
  1128. }
  1129. return matches;
  1130. }
  1131. if (searchValue.global) {
  1132. const matches = matchAll(searchValue, this.original);
  1133. matches.forEach((match) => {
  1134. if (match.index != null) {
  1135. const replacement = getReplacement(match, this.original);
  1136. if (replacement !== match[0]) {
  1137. this.overwrite(
  1138. match.index,
  1139. match.index + match[0].length,
  1140. replacement
  1141. );
  1142. }
  1143. }
  1144. });
  1145. } else {
  1146. const match = this.original.match(searchValue);
  1147. if (match && match.index != null) {
  1148. const replacement = getReplacement(match, this.original);
  1149. if (replacement !== match[0]) {
  1150. this.overwrite(
  1151. match.index,
  1152. match.index + match[0].length,
  1153. replacement
  1154. );
  1155. }
  1156. }
  1157. }
  1158. return this;
  1159. }
  1160. _replaceString(string, replacement) {
  1161. const { original } = this;
  1162. const index = original.indexOf(string);
  1163. if (index !== -1) {
  1164. this.overwrite(index, index + string.length, replacement);
  1165. }
  1166. return this;
  1167. }
  1168. replace(searchValue, replacement) {
  1169. if (typeof searchValue === 'string') {
  1170. return this._replaceString(searchValue, replacement);
  1171. }
  1172. return this._replaceRegexp(searchValue, replacement);
  1173. }
  1174. _replaceAllString(string, replacement) {
  1175. const { original } = this;
  1176. const stringLength = string.length;
  1177. for (
  1178. let index = original.indexOf(string);
  1179. index !== -1;
  1180. index = original.indexOf(string, index + stringLength)
  1181. ) {
  1182. const previous = original.slice(index, index + stringLength);
  1183. if (previous !== replacement)
  1184. this.overwrite(index, index + stringLength, replacement);
  1185. }
  1186. return this;
  1187. }
  1188. replaceAll(searchValue, replacement) {
  1189. if (typeof searchValue === 'string') {
  1190. return this._replaceAllString(searchValue, replacement);
  1191. }
  1192. if (!searchValue.global) {
  1193. throw new TypeError(
  1194. 'MagicString.prototype.replaceAll called with a non-global RegExp argument',
  1195. );
  1196. }
  1197. return this._replaceRegexp(searchValue, replacement);
  1198. }
  1199. }
  1200. const hasOwnProp = Object.prototype.hasOwnProperty;
  1201. let Bundle$1 = class Bundle {
  1202. constructor(options = {}) {
  1203. this.intro = options.intro || '';
  1204. this.separator = options.separator !== undefined ? options.separator : '\n';
  1205. this.sources = [];
  1206. this.uniqueSources = [];
  1207. this.uniqueSourceIndexByFilename = {};
  1208. }
  1209. addSource(source) {
  1210. if (source instanceof MagicString) {
  1211. return this.addSource({
  1212. content: source,
  1213. filename: source.filename,
  1214. separator: this.separator,
  1215. });
  1216. }
  1217. if (!isObject(source) || !source.content) {
  1218. throw new Error(
  1219. 'bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`',
  1220. );
  1221. }
  1222. ['filename', 'ignoreList', 'indentExclusionRanges', 'separator'].forEach((option) => {
  1223. if (!hasOwnProp.call(source, option)) source[option] = source.content[option];
  1224. });
  1225. if (source.separator === undefined) {
  1226. // TODO there's a bunch of this sort of thing, needs cleaning up
  1227. source.separator = this.separator;
  1228. }
  1229. if (source.filename) {
  1230. if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {
  1231. this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;
  1232. this.uniqueSources.push({ filename: source.filename, content: source.content.original });
  1233. } else {
  1234. const uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];
  1235. if (source.content.original !== uniqueSource.content) {
  1236. throw new Error(`Illegal source: same filename (${source.filename}), different contents`);
  1237. }
  1238. }
  1239. }
  1240. this.sources.push(source);
  1241. return this;
  1242. }
  1243. append(str, options) {
  1244. this.addSource({
  1245. content: new MagicString(str),
  1246. separator: (options && options.separator) || '',
  1247. });
  1248. return this;
  1249. }
  1250. clone() {
  1251. const bundle = new Bundle({
  1252. intro: this.intro,
  1253. separator: this.separator,
  1254. });
  1255. this.sources.forEach((source) => {
  1256. bundle.addSource({
  1257. filename: source.filename,
  1258. content: source.content.clone(),
  1259. separator: source.separator,
  1260. });
  1261. });
  1262. return bundle;
  1263. }
  1264. generateDecodedMap(options = {}) {
  1265. const names = [];
  1266. let x_google_ignoreList = undefined;
  1267. this.sources.forEach((source) => {
  1268. Object.keys(source.content.storedNames).forEach((name) => {
  1269. if (!~names.indexOf(name)) names.push(name);
  1270. });
  1271. });
  1272. const mappings = new Mappings(options.hires);
  1273. if (this.intro) {
  1274. mappings.advance(this.intro);
  1275. }
  1276. this.sources.forEach((source, i) => {
  1277. if (i > 0) {
  1278. mappings.advance(this.separator);
  1279. }
  1280. const sourceIndex = source.filename ? this.uniqueSourceIndexByFilename[source.filename] : -1;
  1281. const magicString = source.content;
  1282. const locate = getLocator(magicString.original);
  1283. if (magicString.intro) {
  1284. mappings.advance(magicString.intro);
  1285. }
  1286. magicString.firstChunk.eachNext((chunk) => {
  1287. const loc = locate(chunk.start);
  1288. if (chunk.intro.length) mappings.advance(chunk.intro);
  1289. if (source.filename) {
  1290. if (chunk.edited) {
  1291. mappings.addEdit(
  1292. sourceIndex,
  1293. chunk.content,
  1294. loc,
  1295. chunk.storeName ? names.indexOf(chunk.original) : -1,
  1296. );
  1297. } else {
  1298. mappings.addUneditedChunk(
  1299. sourceIndex,
  1300. chunk,
  1301. magicString.original,
  1302. loc,
  1303. magicString.sourcemapLocations,
  1304. );
  1305. }
  1306. } else {
  1307. mappings.advance(chunk.content);
  1308. }
  1309. if (chunk.outro.length) mappings.advance(chunk.outro);
  1310. });
  1311. if (magicString.outro) {
  1312. mappings.advance(magicString.outro);
  1313. }
  1314. if (source.ignoreList && sourceIndex !== -1) {
  1315. if (x_google_ignoreList === undefined) {
  1316. x_google_ignoreList = [];
  1317. }
  1318. x_google_ignoreList.push(sourceIndex);
  1319. }
  1320. });
  1321. return {
  1322. file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
  1323. sources: this.uniqueSources.map((source) => {
  1324. return options.file ? getRelativePath(options.file, source.filename) : source.filename;
  1325. }),
  1326. sourcesContent: this.uniqueSources.map((source) => {
  1327. return options.includeContent ? source.content : null;
  1328. }),
  1329. names,
  1330. mappings: mappings.raw,
  1331. x_google_ignoreList,
  1332. };
  1333. }
  1334. generateMap(options) {
  1335. return new SourceMap(this.generateDecodedMap(options));
  1336. }
  1337. getIndentString() {
  1338. const indentStringCounts = {};
  1339. this.sources.forEach((source) => {
  1340. const indentStr = source.content._getRawIndentString();
  1341. if (indentStr === null) return;
  1342. if (!indentStringCounts[indentStr]) indentStringCounts[indentStr] = 0;
  1343. indentStringCounts[indentStr] += 1;
  1344. });
  1345. return (
  1346. Object.keys(indentStringCounts).sort((a, b) => {
  1347. return indentStringCounts[a] - indentStringCounts[b];
  1348. })[0] || '\t'
  1349. );
  1350. }
  1351. indent(indentStr) {
  1352. if (!arguments.length) {
  1353. indentStr = this.getIndentString();
  1354. }
  1355. if (indentStr === '') return this; // noop
  1356. let trailingNewline = !this.intro || this.intro.slice(-1) === '\n';
  1357. this.sources.forEach((source, i) => {
  1358. const separator = source.separator !== undefined ? source.separator : this.separator;
  1359. const indentStart = trailingNewline || (i > 0 && /\r?\n$/.test(separator));
  1360. source.content.indent(indentStr, {
  1361. exclude: source.indentExclusionRanges,
  1362. indentStart, //: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator )
  1363. });
  1364. trailingNewline = source.content.lastChar() === '\n';
  1365. });
  1366. if (this.intro) {
  1367. this.intro =
  1368. indentStr +
  1369. this.intro.replace(/^[^\n]/gm, (match, index) => {
  1370. return index > 0 ? indentStr + match : match;
  1371. });
  1372. }
  1373. return this;
  1374. }
  1375. prepend(str) {
  1376. this.intro = str + this.intro;
  1377. return this;
  1378. }
  1379. toString() {
  1380. const body = this.sources
  1381. .map((source, i) => {
  1382. const separator = source.separator !== undefined ? source.separator : this.separator;
  1383. const str = (i > 0 ? separator : '') + source.content.toString();
  1384. return str;
  1385. })
  1386. .join('');
  1387. return this.intro + body;
  1388. }
  1389. isEmpty() {
  1390. if (this.intro.length && this.intro.trim()) return false;
  1391. if (this.sources.some((source) => !source.content.isEmpty())) return false;
  1392. return true;
  1393. }
  1394. length() {
  1395. return this.sources.reduce(
  1396. (length, source) => length + source.content.length(),
  1397. this.intro.length,
  1398. );
  1399. }
  1400. trimLines() {
  1401. return this.trim('[\\r\\n]');
  1402. }
  1403. trim(charType) {
  1404. return this.trimStart(charType).trimEnd(charType);
  1405. }
  1406. trimStart(charType) {
  1407. const rx = new RegExp('^' + (charType || '\\s') + '+');
  1408. this.intro = this.intro.replace(rx, '');
  1409. if (!this.intro) {
  1410. let source;
  1411. let i = 0;
  1412. do {
  1413. source = this.sources[i++];
  1414. if (!source) {
  1415. break;
  1416. }
  1417. } while (!source.content.trimStartAborted(charType));
  1418. }
  1419. return this;
  1420. }
  1421. trimEnd(charType) {
  1422. const rx = new RegExp((charType || '\\s') + '+$');
  1423. let source;
  1424. let i = this.sources.length - 1;
  1425. do {
  1426. source = this.sources[i--];
  1427. if (!source) {
  1428. this.intro = this.intro.replace(rx, '');
  1429. break;
  1430. }
  1431. } while (!source.content.trimEndAborted(charType));
  1432. return this;
  1433. }
  1434. };
  1435. function treeshakeNode(node, code, start, end) {
  1436. code.remove(start, end);
  1437. node.removeAnnotations(code);
  1438. }
  1439. const NO_SEMICOLON = { isNoStatement: true };
  1440. // This assumes there are only white-space and comments between start and the string we are looking for
  1441. function findFirstOccurrenceOutsideComment(code, searchString, start = 0) {
  1442. let searchPos, charCodeAfterSlash;
  1443. searchPos = code.indexOf(searchString, start);
  1444. while (true) {
  1445. start = code.indexOf('/', start);
  1446. if (start === -1 || start >= searchPos)
  1447. return searchPos;
  1448. charCodeAfterSlash = code.charCodeAt(++start);
  1449. ++start;
  1450. // With our assumption, '/' always starts a comment. Determine comment type:
  1451. start =
  1452. charCodeAfterSlash === 47 /*"/"*/
  1453. ? code.indexOf('\n', start) + 1
  1454. : code.indexOf('*/', start) + 2;
  1455. if (start > searchPos) {
  1456. searchPos = code.indexOf(searchString, start);
  1457. }
  1458. }
  1459. }
  1460. const NON_WHITESPACE = /\S/g;
  1461. function findNonWhiteSpace(code, index) {
  1462. NON_WHITESPACE.lastIndex = index;
  1463. const result = NON_WHITESPACE.exec(code);
  1464. return result.index;
  1465. }
  1466. const WHITESPACE = /\s/;
  1467. function findLastWhiteSpaceReverse(code, start, end) {
  1468. while (true) {
  1469. if (start >= end) {
  1470. return end;
  1471. }
  1472. if (WHITESPACE.test(code[end - 1])) {
  1473. end--;
  1474. }
  1475. else {
  1476. return end;
  1477. }
  1478. }
  1479. }
  1480. // This assumes "code" only contains white-space and comments
  1481. // Returns position of line-comment if applicable
  1482. function findFirstLineBreakOutsideComment(code) {
  1483. let lineBreakPos, charCodeAfterSlash, start = 0;
  1484. lineBreakPos = code.indexOf('\n', start);
  1485. while (true) {
  1486. start = code.indexOf('/', start);
  1487. if (start === -1 || start > lineBreakPos)
  1488. return [lineBreakPos, lineBreakPos + 1];
  1489. // With our assumption, '/' always starts a comment. Determine comment type:
  1490. charCodeAfterSlash = code.charCodeAt(start + 1);
  1491. if (charCodeAfterSlash === 47 /*"/"*/)
  1492. return [start, lineBreakPos + 1];
  1493. start = code.indexOf('*/', start + 2) + 2;
  1494. if (start > lineBreakPos) {
  1495. lineBreakPos = code.indexOf('\n', start);
  1496. }
  1497. }
  1498. }
  1499. function renderStatementList(statements, code, start, end, options) {
  1500. let currentNode, currentNodeStart, currentNodeNeedsBoundaries, nextNodeStart;
  1501. let nextNode = statements[0];
  1502. let nextNodeNeedsBoundaries = !nextNode.included || nextNode.needsBoundaries;
  1503. if (nextNodeNeedsBoundaries) {
  1504. nextNodeStart =
  1505. start + findFirstLineBreakOutsideComment(code.original.slice(start, nextNode.start))[1];
  1506. }
  1507. for (let nextIndex = 1; nextIndex <= statements.length; nextIndex++) {
  1508. currentNode = nextNode;
  1509. currentNodeStart = nextNodeStart;
  1510. currentNodeNeedsBoundaries = nextNodeNeedsBoundaries;
  1511. nextNode = statements[nextIndex];
  1512. nextNodeNeedsBoundaries =
  1513. nextNode === undefined ? false : !nextNode.included || nextNode.needsBoundaries;
  1514. if (currentNodeNeedsBoundaries || nextNodeNeedsBoundaries) {
  1515. nextNodeStart =
  1516. currentNode.end +
  1517. findFirstLineBreakOutsideComment(code.original.slice(currentNode.end, nextNode === undefined ? end : nextNode.start))[1];
  1518. if (currentNode.included) {
  1519. if (currentNodeNeedsBoundaries) {
  1520. currentNode.render(code, options, {
  1521. end: nextNodeStart,
  1522. start: currentNodeStart
  1523. });
  1524. }
  1525. else {
  1526. currentNode.render(code, options);
  1527. }
  1528. }
  1529. else {
  1530. treeshakeNode(currentNode, code, currentNodeStart, nextNodeStart);
  1531. }
  1532. }
  1533. else {
  1534. currentNode.render(code, options);
  1535. }
  1536. }
  1537. }
  1538. // This assumes that the first character is not part of the first node
  1539. function getCommaSeparatedNodesWithBoundaries(nodes, code, start, end) {
  1540. const splitUpNodes = [];
  1541. let node, nextNodeStart, contentEnd, char;
  1542. let separator = start - 1;
  1543. for (const nextNode of nodes) {
  1544. if (node !== undefined) {
  1545. separator =
  1546. node.end +
  1547. findFirstOccurrenceOutsideComment(code.original.slice(node.end, nextNode.start), ',');
  1548. }
  1549. nextNodeStart = contentEnd =
  1550. separator +
  1551. 1 +
  1552. findFirstLineBreakOutsideComment(code.original.slice(separator + 1, nextNode.start))[1];
  1553. while (((char = code.original.charCodeAt(nextNodeStart)),
  1554. char === 32 /*" "*/ || char === 9 /*"\t"*/ || char === 10 /*"\n"*/ || char === 13) /*"\r"*/)
  1555. nextNodeStart++;
  1556. if (node !== undefined) {
  1557. splitUpNodes.push({
  1558. contentEnd,
  1559. end: nextNodeStart,
  1560. node,
  1561. separator,
  1562. start
  1563. });
  1564. }
  1565. node = nextNode;
  1566. start = nextNodeStart;
  1567. }
  1568. splitUpNodes.push({
  1569. contentEnd: end,
  1570. end,
  1571. node: node,
  1572. separator: null,
  1573. start
  1574. });
  1575. return splitUpNodes;
  1576. }
  1577. // This assumes there are only white-space and comments between start and end
  1578. function removeLineBreaks(code, start, end) {
  1579. while (true) {
  1580. const [removeStart, removeEnd] = findFirstLineBreakOutsideComment(code.original.slice(start, end));
  1581. if (removeStart === -1) {
  1582. break;
  1583. }
  1584. code.remove(start + removeStart, (start += removeEnd));
  1585. }
  1586. }
  1587. function getSystemExportStatement(exportedVariables, { exportNamesByVariable, snippets: { _, getObject, getPropertyAccess } }, modifier = '') {
  1588. if (exportedVariables.length === 1 &&
  1589. exportNamesByVariable.get(exportedVariables[0]).length === 1) {
  1590. const variable = exportedVariables[0];
  1591. return `exports(${JSON.stringify(exportNamesByVariable.get(variable)[0])},${_}${variable.getName(getPropertyAccess)}${modifier})`;
  1592. }
  1593. else {
  1594. const fields = [];
  1595. for (const variable of exportedVariables) {
  1596. for (const exportName of exportNamesByVariable.get(variable)) {
  1597. fields.push([exportName, variable.getName(getPropertyAccess) + modifier]);
  1598. }
  1599. }
  1600. return `exports(${getObject(fields, { lineBreakIndent: null })})`;
  1601. }
  1602. }
  1603. // This is only invoked if there is exactly one export name
  1604. function renderSystemExportExpression(exportedVariable, expressionStart, expressionEnd, code, { exportNamesByVariable, snippets: { _ } }) {
  1605. code.prependRight(expressionStart, `exports(${JSON.stringify(exportNamesByVariable.get(exportedVariable)[0])},${_}`);
  1606. code.appendLeft(expressionEnd, ')');
  1607. }
  1608. function renderSystemExportFunction(exportedVariables, expressionStart, expressionEnd, needsParens, code, options) {
  1609. const { _, getDirectReturnIifeLeft } = options.snippets;
  1610. code.prependRight(expressionStart, getDirectReturnIifeLeft(['v'], `${getSystemExportStatement(exportedVariables, options)},${_}v`, { needsArrowReturnParens: true, needsWrappedFunction: needsParens }));
  1611. code.appendLeft(expressionEnd, ')');
  1612. }
  1613. function renderSystemExportSequenceAfterExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options) {
  1614. const { _, getPropertyAccess } = options.snippets;
  1615. code.appendLeft(expressionEnd, `,${_}${getSystemExportStatement([exportedVariable], options)},${_}${exportedVariable.getName(getPropertyAccess)}`);
  1616. if (needsParens) {
  1617. code.prependRight(expressionStart, '(');
  1618. code.appendLeft(expressionEnd, ')');
  1619. }
  1620. }
  1621. function renderSystemExportSequenceBeforeExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options, modifier) {
  1622. const { _ } = options.snippets;
  1623. code.prependRight(expressionStart, `${getSystemExportStatement([exportedVariable], options, modifier)},${_}`);
  1624. if (needsParens) {
  1625. code.prependRight(expressionStart, '(');
  1626. code.appendLeft(expressionEnd, ')');
  1627. }
  1628. }
  1629. /** @typedef { import('estree').Node} Node */
  1630. /** @typedef {Node | {
  1631. * type: 'PropertyDefinition';
  1632. * computed: boolean;
  1633. * value: Node
  1634. * }} NodeWithPropertyDefinition */
  1635. /**
  1636. *
  1637. * @param {NodeWithPropertyDefinition} node
  1638. * @param {NodeWithPropertyDefinition} parent
  1639. * @returns {boolean}
  1640. */
  1641. function is_reference (node, parent) {
  1642. if (node.type === 'MemberExpression') {
  1643. return !node.computed && is_reference(node.object, node);
  1644. }
  1645. if (node.type === 'Identifier') {
  1646. if (!parent) return true;
  1647. switch (parent.type) {
  1648. // disregard `bar` in `foo.bar`
  1649. case 'MemberExpression': return parent.computed || node === parent.object;
  1650. // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}`
  1651. case 'MethodDefinition': return parent.computed;
  1652. // disregard the `foo` in `class {foo=bar}` but keep it in `class {[foo]=bar}` and `class {bar=foo}`
  1653. case 'PropertyDefinition': return parent.computed || node === parent.value;
  1654. // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
  1655. case 'Property': return parent.computed || node === parent.value;
  1656. // disregard the `bar` in `export { foo as bar }` or
  1657. // the foo in `import { foo as bar }`
  1658. case 'ExportSpecifier':
  1659. case 'ImportSpecifier': return node === parent.local;
  1660. // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}`
  1661. case 'LabeledStatement':
  1662. case 'BreakStatement':
  1663. case 'ContinueStatement': return false;
  1664. default: return true;
  1665. }
  1666. }
  1667. return false;
  1668. }
  1669. const PureFunctionKey = Symbol('PureFunction');
  1670. const getPureFunctions = ({ treeshake }) => {
  1671. const pureFunctions = Object.create(null);
  1672. for (const functionName of treeshake ? treeshake.manualPureFunctions : []) {
  1673. let currentFunctions = pureFunctions;
  1674. for (const pathSegment of functionName.split('.')) {
  1675. currentFunctions = currentFunctions[pathSegment] ||= Object.create(null);
  1676. }
  1677. currentFunctions[PureFunctionKey] = true;
  1678. }
  1679. return pureFunctions;
  1680. };
  1681. function getOrCreate(map, key, init) {
  1682. const existing = map.get(key);
  1683. if (existing !== undefined) {
  1684. return existing;
  1685. }
  1686. const value = init();
  1687. map.set(key, value);
  1688. return value;
  1689. }
  1690. function getNewSet() {
  1691. return new Set();
  1692. }
  1693. function getNewArray() {
  1694. return [];
  1695. }
  1696. const UnknownKey = Symbol('Unknown Key');
  1697. const UnknownNonAccessorKey = Symbol('Unknown Non-Accessor Key');
  1698. const UnknownInteger = Symbol('Unknown Integer');
  1699. const SymbolToStringTag = Symbol('Symbol.toStringTag');
  1700. const EMPTY_PATH = [];
  1701. const UNKNOWN_PATH = [UnknownKey];
  1702. // For deoptimizations, this means we are modifying an unknown property but did
  1703. // not lose track of the object or are creating a setter/getter;
  1704. // For assignment effects it means we do not check for setter/getter effects
  1705. // but only if something is mutated that is included, which is relevant for
  1706. // Object.defineProperty
  1707. const UNKNOWN_NON_ACCESSOR_PATH = [UnknownNonAccessorKey];
  1708. const UNKNOWN_INTEGER_PATH = [UnknownInteger];
  1709. const EntitiesKey = Symbol('Entities');
  1710. class PathTracker {
  1711. constructor() {
  1712. this.entityPaths = Object.create(null, {
  1713. [EntitiesKey]: { value: new Set() }
  1714. });
  1715. }
  1716. trackEntityAtPathAndGetIfTracked(path, entity) {
  1717. const trackedEntities = this.getEntities(path);
  1718. if (trackedEntities.has(entity))
  1719. return true;
  1720. trackedEntities.add(entity);
  1721. return false;
  1722. }
  1723. withTrackedEntityAtPath(path, entity, onUntracked, returnIfTracked) {
  1724. const trackedEntities = this.getEntities(path);
  1725. if (trackedEntities.has(entity))
  1726. return returnIfTracked;
  1727. trackedEntities.add(entity);
  1728. const result = onUntracked();
  1729. trackedEntities.delete(entity);
  1730. return result;
  1731. }
  1732. getEntities(path) {
  1733. let currentPaths = this.entityPaths;
  1734. for (const pathSegment of path) {
  1735. currentPaths = currentPaths[pathSegment] =
  1736. currentPaths[pathSegment] ||
  1737. Object.create(null, { [EntitiesKey]: { value: new Set() } });
  1738. }
  1739. return currentPaths[EntitiesKey];
  1740. }
  1741. }
  1742. const SHARED_RECURSION_TRACKER = new PathTracker();
  1743. class DiscriminatedPathTracker {
  1744. constructor() {
  1745. this.entityPaths = Object.create(null, {
  1746. [EntitiesKey]: { value: new Map() }
  1747. });
  1748. }
  1749. trackEntityAtPathAndGetIfTracked(path, discriminator, entity) {
  1750. let currentPaths = this.entityPaths;
  1751. for (const pathSegment of path) {
  1752. currentPaths = currentPaths[pathSegment] =
  1753. currentPaths[pathSegment] ||
  1754. Object.create(null, { [EntitiesKey]: { value: new Map() } });
  1755. }
  1756. const trackedEntities = getOrCreate(currentPaths[EntitiesKey], discriminator, (getNewSet));
  1757. if (trackedEntities.has(entity))
  1758. return true;
  1759. trackedEntities.add(entity);
  1760. return false;
  1761. }
  1762. }
  1763. function isFlagSet(flags, flag) {
  1764. return (flags & flag) !== 0;
  1765. }
  1766. function setFlag(flags, flag, value) {
  1767. return (flags & ~flag) | (-value & flag);
  1768. }
  1769. const UnknownValue = Symbol('Unknown Value');
  1770. const UnknownTruthyValue = Symbol('Unknown Truthy Value');
  1771. class ExpressionEntity {
  1772. constructor() {
  1773. this.flags = 0;
  1774. }
  1775. get included() {
  1776. return isFlagSet(this.flags, 1 /* Flag.included */);
  1777. }
  1778. set included(value) {
  1779. this.flags = setFlag(this.flags, 1 /* Flag.included */, value);
  1780. }
  1781. deoptimizeArgumentsOnInteractionAtPath(interaction, _path, _recursionTracker) {
  1782. deoptimizeInteraction(interaction);
  1783. }
  1784. deoptimizePath(_path) { }
  1785. /**
  1786. * If possible it returns a stringifyable literal value for this node that
  1787. * can be used for inlining or comparing values. Otherwise, it should return
  1788. * UnknownValue.
  1789. */
  1790. getLiteralValueAtPath(_path, _recursionTracker, _origin) {
  1791. return UnknownValue;
  1792. }
  1793. getReturnExpressionWhenCalledAtPath(_path, _interaction, _recursionTracker, _origin) {
  1794. return UNKNOWN_RETURN_EXPRESSION;
  1795. }
  1796. hasEffectsOnInteractionAtPath(_path, _interaction, _context) {
  1797. return true;
  1798. }
  1799. include(_context, _includeChildrenRecursively, _options) {
  1800. this.included = true;
  1801. }
  1802. includeCallArguments(context, parameters) {
  1803. for (const argument of parameters) {
  1804. argument.include(context, false);
  1805. }
  1806. }
  1807. shouldBeIncluded(_context) {
  1808. return true;
  1809. }
  1810. }
  1811. const UNKNOWN_EXPRESSION = new (class UnknownExpression extends ExpressionEntity {
  1812. })();
  1813. const UNKNOWN_RETURN_EXPRESSION = [
  1814. UNKNOWN_EXPRESSION,
  1815. false
  1816. ];
  1817. const deoptimizeInteraction = (interaction) => {
  1818. for (const argument of interaction.args) {
  1819. argument?.deoptimizePath(UNKNOWN_PATH);
  1820. }
  1821. };
  1822. const INTERACTION_ACCESSED = 0;
  1823. const INTERACTION_ASSIGNED = 1;
  1824. const INTERACTION_CALLED = 2;
  1825. const NODE_INTERACTION_UNKNOWN_ACCESS = {
  1826. args: [null],
  1827. type: INTERACTION_ACCESSED
  1828. };
  1829. const NODE_INTERACTION_UNKNOWN_ASSIGNMENT = {
  1830. args: [null, UNKNOWN_EXPRESSION],
  1831. type: INTERACTION_ASSIGNED
  1832. };
  1833. // While this is technically a call without arguments, we can compare against
  1834. // this reference in places where precise values or this argument would make a
  1835. // difference
  1836. const NODE_INTERACTION_UNKNOWN_CALL = {
  1837. args: [null],
  1838. type: INTERACTION_CALLED,
  1839. withNew: false
  1840. };
  1841. class Variable extends ExpressionEntity {
  1842. markReassigned() {
  1843. this.isReassigned = true;
  1844. }
  1845. constructor(name) {
  1846. super();
  1847. this.name = name;
  1848. this.alwaysRendered = false;
  1849. this.forbiddenNames = null;
  1850. this.globalName = null;
  1851. this.initReached = false;
  1852. this.isId = false;
  1853. this.kind = null;
  1854. this.renderBaseName = null;
  1855. this.renderName = null;
  1856. this.isReassigned = false;
  1857. this.onlyFunctionCallUsed = true;
  1858. }
  1859. /**
  1860. * Binds identifiers that reference this variable to this variable.
  1861. * Necessary to be able to change variable names.
  1862. */
  1863. addReference(_identifier) { }
  1864. /**
  1865. * Check if the identifier variable is only used as function call
  1866. * @returns true if the variable is only used as function call
  1867. */
  1868. getOnlyFunctionCallUsed() {
  1869. return this.onlyFunctionCallUsed;
  1870. }
  1871. /**
  1872. * Collect the places where the identifier variable is used
  1873. * @param usedPlace Where the variable is used
  1874. */
  1875. addUsedPlace(usedPlace) {
  1876. const isFunctionCall = usedPlace.parent.type === CallExpression$1 &&
  1877. usedPlace.parent.callee === usedPlace;
  1878. if (!isFunctionCall && usedPlace.parent.type !== ExportDefaultDeclaration$1) {
  1879. this.onlyFunctionCallUsed = false;
  1880. }
  1881. }
  1882. /**
  1883. * Prevent this variable from being renamed to this name to avoid name
  1884. * collisions
  1885. */
  1886. forbidName(name) {
  1887. (this.forbiddenNames ||= new Set()).add(name);
  1888. }
  1889. getBaseVariableName() {
  1890. return (this.renderedLikeHoisted?.getBaseVariableName() ||
  1891. this.renderBaseName ||
  1892. this.renderName ||
  1893. this.name);
  1894. }
  1895. getName(getPropertyAccess, useOriginalName) {
  1896. if (this.globalName) {
  1897. return this.globalName;
  1898. }
  1899. if (useOriginalName?.(this)) {
  1900. return this.name;
  1901. }
  1902. if (this.renderedLikeHoisted) {
  1903. return this.renderedLikeHoisted.getName(getPropertyAccess, useOriginalName);
  1904. }
  1905. const name = this.renderName || this.name;
  1906. return this.renderBaseName ? `${this.renderBaseName}${getPropertyAccess(name)}` : name;
  1907. }
  1908. hasEffectsOnInteractionAtPath(path, { type }, _context) {
  1909. return type !== INTERACTION_ACCESSED || path.length > 0;
  1910. }
  1911. /**
  1912. * Marks this variable as being part of the bundle, which is usually the case
  1913. * when one of its identifiers becomes part of the bundle. Returns true if it
  1914. * has not been included previously. Once a variable is included, it should
  1915. * take care all its declarations are included.
  1916. */
  1917. include() {
  1918. this.included = true;
  1919. this.renderedLikeHoisted?.include();
  1920. }
  1921. /**
  1922. * Links the rendered name of this variable to another variable and includes
  1923. * this variable if the other variable is included.
  1924. */
  1925. renderLikeHoisted(variable) {
  1926. this.renderedLikeHoisted = variable;
  1927. }
  1928. markCalledFromTryStatement() { }
  1929. setRenderNames(baseName, name) {
  1930. this.renderBaseName = baseName;
  1931. this.renderName = name;
  1932. }
  1933. }
  1934. class ExternalVariable extends Variable {
  1935. constructor(module, name) {
  1936. super(name);
  1937. this.referenced = false;
  1938. this.module = module;
  1939. this.isNamespace = name === '*';
  1940. }
  1941. addReference(identifier) {
  1942. this.referenced = true;
  1943. if (this.name === 'default' || this.name === '*') {
  1944. this.module.suggestName(identifier.name);
  1945. }
  1946. }
  1947. hasEffectsOnInteractionAtPath(path, { type }) {
  1948. return type !== INTERACTION_ACCESSED || path.length > (this.isNamespace ? 1 : 0);
  1949. }
  1950. include() {
  1951. super.include();
  1952. this.module.used = true;
  1953. }
  1954. }
  1955. function cacheObjectGetters(object, getterProperties) {
  1956. for (const property of getterProperties) {
  1957. const propertyGetter = Object.getOwnPropertyDescriptor(object, property).get;
  1958. Object.defineProperty(object, property, {
  1959. get() {
  1960. const value = propertyGetter.call(object);
  1961. // This replaces the getter with a fixed value for subsequent calls
  1962. Object.defineProperty(object, property, { value });
  1963. return value;
  1964. }
  1965. });
  1966. }
  1967. }
  1968. const RESERVED_NAMES = new Set([
  1969. 'await',
  1970. 'break',
  1971. 'case',
  1972. 'catch',
  1973. 'class',
  1974. 'const',
  1975. 'continue',
  1976. 'debugger',
  1977. 'default',
  1978. 'delete',
  1979. 'do',
  1980. 'else',
  1981. 'enum',
  1982. 'eval',
  1983. 'export',
  1984. 'extends',
  1985. 'false',
  1986. 'finally',
  1987. 'for',
  1988. 'function',
  1989. 'if',
  1990. 'implements',
  1991. 'import',
  1992. 'in',
  1993. 'instanceof',
  1994. 'interface',
  1995. 'let',
  1996. 'NaN',
  1997. 'new',
  1998. 'null',
  1999. 'package',
  2000. 'private',
  2001. 'protected',
  2002. 'public',
  2003. 'return',
  2004. 'static',
  2005. 'super',
  2006. 'switch',
  2007. 'this',
  2008. 'throw',
  2009. 'true',
  2010. 'try',
  2011. 'typeof',
  2012. 'undefined',
  2013. 'var',
  2014. 'void',
  2015. 'while',
  2016. 'with',
  2017. 'yield'
  2018. ]);
  2019. const illegalCharacters = /[^\w$]/g;
  2020. const startsWithDigit = (value) => /\d/.test(value[0]);
  2021. const needsEscape = (value) => startsWithDigit(value) || RESERVED_NAMES.has(value) || value === 'arguments';
  2022. function isLegal(value) {
  2023. if (needsEscape(value)) {
  2024. return false;
  2025. }
  2026. return !illegalCharacters.test(value);
  2027. }
  2028. function makeLegal(value) {
  2029. value = value
  2030. .replace(/-(\w)/g, (_, letter) => letter.toUpperCase())
  2031. .replace(illegalCharacters, '_');
  2032. if (needsEscape(value))
  2033. value = `_${value}`;
  2034. return value || '_';
  2035. }
  2036. const VALID_IDENTIFIER_REGEXP = /^[$_\p{ID_Start}][$\u200C\u200D\p{ID_Continue}]*$/u;
  2037. const NUMBER_REGEXP = /^(?:0|[1-9]\d*)$/;
  2038. function stringifyObjectKeyIfNeeded(key) {
  2039. if (VALID_IDENTIFIER_REGEXP.test(key)) {
  2040. return key === '__proto__' ? '["__proto__"]' : key;
  2041. }
  2042. if (NUMBER_REGEXP.test(key) && +key <= Number.MAX_SAFE_INTEGER) {
  2043. return key;
  2044. }
  2045. return JSON.stringify(key);
  2046. }
  2047. function stringifyIdentifierIfNeeded(key) {
  2048. if (VALID_IDENTIFIER_REGEXP.test(key)) {
  2049. return key;
  2050. }
  2051. return JSON.stringify(key);
  2052. }
  2053. class ExternalModule {
  2054. constructor(options, id, moduleSideEffects, meta, renormalizeRenderPath, attributes) {
  2055. this.options = options;
  2056. this.id = id;
  2057. this.renormalizeRenderPath = renormalizeRenderPath;
  2058. this.dynamicImporters = [];
  2059. this.execIndex = Infinity;
  2060. this.exportedVariables = new Map();
  2061. this.importers = [];
  2062. this.reexported = false;
  2063. this.used = false;
  2064. this.declarations = new Map();
  2065. this.mostCommonSuggestion = 0;
  2066. this.nameSuggestions = new Map();
  2067. this.suggestedVariableName = makeLegal(id.split(/[/\\]/).pop());
  2068. const { importers, dynamicImporters } = this;
  2069. this.info = {
  2070. ast: null,
  2071. attributes,
  2072. code: null,
  2073. dynamicallyImportedIdResolutions: EMPTY_ARRAY,
  2074. dynamicallyImportedIds: EMPTY_ARRAY,
  2075. get dynamicImporters() {
  2076. return dynamicImporters.sort();
  2077. },
  2078. exportedBindings: null,
  2079. exports: null,
  2080. hasDefaultExport: null,
  2081. id,
  2082. implicitlyLoadedAfterOneOf: EMPTY_ARRAY,
  2083. implicitlyLoadedBefore: EMPTY_ARRAY,
  2084. importedIdResolutions: EMPTY_ARRAY,
  2085. importedIds: EMPTY_ARRAY,
  2086. get importers() {
  2087. return importers.sort();
  2088. },
  2089. isEntry: false,
  2090. isExternal: true,
  2091. isIncluded: null,
  2092. meta,
  2093. moduleSideEffects,
  2094. syntheticNamedExports: false
  2095. };
  2096. }
  2097. cacheInfoGetters() {
  2098. cacheObjectGetters(this.info, ['dynamicImporters', 'importers']);
  2099. }
  2100. getVariableForExportName(name) {
  2101. const declaration = this.declarations.get(name);
  2102. if (declaration)
  2103. return [declaration];
  2104. const externalVariable = new ExternalVariable(this, name);
  2105. this.declarations.set(name, externalVariable);
  2106. this.exportedVariables.set(externalVariable, name);
  2107. return [externalVariable];
  2108. }
  2109. suggestName(name) {
  2110. const value = (this.nameSuggestions.get(name) ?? 0) + 1;
  2111. this.nameSuggestions.set(name, value);
  2112. if (value > this.mostCommonSuggestion) {
  2113. this.mostCommonSuggestion = value;
  2114. this.suggestedVariableName = name;
  2115. }
  2116. }
  2117. warnUnusedImports() {
  2118. const unused = [...this.declarations]
  2119. .filter(([name, declaration]) => name !== '*' && !declaration.included && !this.reexported && !declaration.referenced)
  2120. .map(([name]) => name);
  2121. if (unused.length === 0)
  2122. return;
  2123. const importersSet = new Set();
  2124. for (const name of unused) {
  2125. for (const importer of this.declarations.get(name).module.importers) {
  2126. importersSet.add(importer);
  2127. }
  2128. }
  2129. const importersArray = [...importersSet];
  2130. this.options.onLog(LOGLEVEL_WARN, logUnusedExternalImports(this.id, unused, importersArray));
  2131. }
  2132. }
  2133. function markModuleAndImpureDependenciesAsExecuted(baseModule) {
  2134. baseModule.isExecuted = true;
  2135. const modules = [baseModule];
  2136. const visitedModules = new Set();
  2137. for (const module of modules) {
  2138. for (const dependency of [...module.dependencies, ...module.implicitlyLoadedBefore]) {
  2139. if (!(dependency instanceof ExternalModule) &&
  2140. !dependency.isExecuted &&
  2141. (dependency.info.moduleSideEffects || module.implicitlyLoadedBefore.has(dependency)) &&
  2142. !visitedModules.has(dependency.id)) {
  2143. dependency.isExecuted = true;
  2144. visitedModules.add(dependency.id);
  2145. modules.push(dependency);
  2146. }
  2147. }
  2148. }
  2149. }
  2150. const doNothing = () => { };
  2151. function assembleMemberDescriptions(memberDescriptions, inheritedDescriptions = null) {
  2152. return Object.create(inheritedDescriptions, memberDescriptions);
  2153. }
  2154. const UNDEFINED_EXPRESSION = new (class UndefinedExpression extends ExpressionEntity {
  2155. getLiteralValueAtPath() {
  2156. return undefined;
  2157. }
  2158. })();
  2159. const returnsUnknown = {
  2160. value: {
  2161. hasEffectsWhenCalled: null,
  2162. returns: UNKNOWN_EXPRESSION
  2163. }
  2164. };
  2165. const UNKNOWN_LITERAL_BOOLEAN = new (class UnknownBoolean extends ExpressionEntity {
  2166. getReturnExpressionWhenCalledAtPath(path) {
  2167. if (path.length === 1) {
  2168. return getMemberReturnExpressionWhenCalled(literalBooleanMembers, path[0]);
  2169. }
  2170. return UNKNOWN_RETURN_EXPRESSION;
  2171. }
  2172. hasEffectsOnInteractionAtPath(path, interaction, context) {
  2173. if (interaction.type === INTERACTION_ACCESSED) {
  2174. return path.length > 1;
  2175. }
  2176. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  2177. return hasMemberEffectWhenCalled(literalBooleanMembers, path[0], interaction, context);
  2178. }
  2179. return true;
  2180. }
  2181. })();
  2182. const returnsBoolean = {
  2183. value: {
  2184. hasEffectsWhenCalled: null,
  2185. returns: UNKNOWN_LITERAL_BOOLEAN
  2186. }
  2187. };
  2188. const UNKNOWN_LITERAL_NUMBER = new (class UnknownNumber extends ExpressionEntity {
  2189. getReturnExpressionWhenCalledAtPath(path) {
  2190. if (path.length === 1) {
  2191. return getMemberReturnExpressionWhenCalled(literalNumberMembers, path[0]);
  2192. }
  2193. return UNKNOWN_RETURN_EXPRESSION;
  2194. }
  2195. hasEffectsOnInteractionAtPath(path, interaction, context) {
  2196. if (interaction.type === INTERACTION_ACCESSED) {
  2197. return path.length > 1;
  2198. }
  2199. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  2200. return hasMemberEffectWhenCalled(literalNumberMembers, path[0], interaction, context);
  2201. }
  2202. return true;
  2203. }
  2204. })();
  2205. const returnsNumber = {
  2206. value: {
  2207. hasEffectsWhenCalled: null,
  2208. returns: UNKNOWN_LITERAL_NUMBER
  2209. }
  2210. };
  2211. const UNKNOWN_LITERAL_STRING = new (class UnknownString extends ExpressionEntity {
  2212. getReturnExpressionWhenCalledAtPath(path) {
  2213. if (path.length === 1) {
  2214. return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
  2215. }
  2216. return UNKNOWN_RETURN_EXPRESSION;
  2217. }
  2218. hasEffectsOnInteractionAtPath(path, interaction, context) {
  2219. if (interaction.type === INTERACTION_ACCESSED) {
  2220. return path.length > 1;
  2221. }
  2222. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  2223. return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
  2224. }
  2225. return true;
  2226. }
  2227. })();
  2228. const returnsString = {
  2229. value: {
  2230. hasEffectsWhenCalled: null,
  2231. returns: UNKNOWN_LITERAL_STRING
  2232. }
  2233. };
  2234. const stringReplace = {
  2235. value: {
  2236. hasEffectsWhenCalled({ args }, context) {
  2237. const argument1 = args[2];
  2238. return (args.length < 3 ||
  2239. (typeof argument1.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, {
  2240. deoptimizeCache() { }
  2241. }) === 'symbol' &&
  2242. argument1.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)));
  2243. },
  2244. returns: UNKNOWN_LITERAL_STRING
  2245. }
  2246. };
  2247. const objectMembers = assembleMemberDescriptions({
  2248. hasOwnProperty: returnsBoolean,
  2249. isPrototypeOf: returnsBoolean,
  2250. propertyIsEnumerable: returnsBoolean,
  2251. toLocaleString: returnsString,
  2252. toString: returnsString,
  2253. valueOf: returnsUnknown
  2254. });
  2255. const literalBooleanMembers = assembleMemberDescriptions({
  2256. valueOf: returnsBoolean
  2257. }, objectMembers);
  2258. const literalNumberMembers = assembleMemberDescriptions({
  2259. toExponential: returnsString,
  2260. toFixed: returnsString,
  2261. toLocaleString: returnsString,
  2262. toPrecision: returnsString,
  2263. valueOf: returnsNumber
  2264. }, objectMembers);
  2265. /**
  2266. * RegExp are stateful when they have the global or sticky flags set.
  2267. * But if we actually don't use them, the side effect does not matter.
  2268. * the check logic in `hasEffectsOnInteractionAtPath`.
  2269. */
  2270. const literalRegExpMembers = assembleMemberDescriptions({
  2271. exec: returnsUnknown,
  2272. test: returnsBoolean
  2273. }, objectMembers);
  2274. const literalStringMembers = assembleMemberDescriptions({
  2275. anchor: returnsString,
  2276. at: returnsUnknown,
  2277. big: returnsString,
  2278. blink: returnsString,
  2279. bold: returnsString,
  2280. charAt: returnsString,
  2281. charCodeAt: returnsNumber,
  2282. codePointAt: returnsUnknown,
  2283. concat: returnsString,
  2284. endsWith: returnsBoolean,
  2285. fixed: returnsString,
  2286. fontcolor: returnsString,
  2287. fontsize: returnsString,
  2288. includes: returnsBoolean,
  2289. indexOf: returnsNumber,
  2290. italics: returnsString,
  2291. lastIndexOf: returnsNumber,
  2292. link: returnsString,
  2293. localeCompare: returnsNumber,
  2294. match: returnsUnknown,
  2295. matchAll: returnsUnknown,
  2296. normalize: returnsString,
  2297. padEnd: returnsString,
  2298. padStart: returnsString,
  2299. repeat: returnsString,
  2300. replace: stringReplace,
  2301. replaceAll: stringReplace,
  2302. search: returnsNumber,
  2303. slice: returnsString,
  2304. small: returnsString,
  2305. split: returnsUnknown,
  2306. startsWith: returnsBoolean,
  2307. strike: returnsString,
  2308. sub: returnsString,
  2309. substr: returnsString,
  2310. substring: returnsString,
  2311. sup: returnsString,
  2312. toLocaleLowerCase: returnsString,
  2313. toLocaleUpperCase: returnsString,
  2314. toLowerCase: returnsString,
  2315. toString: returnsString, // overrides the toString() method of the Object object; it does not inherit Object.prototype.toString()
  2316. toUpperCase: returnsString,
  2317. trim: returnsString,
  2318. trimEnd: returnsString,
  2319. trimLeft: returnsString,
  2320. trimRight: returnsString,
  2321. trimStart: returnsString,
  2322. valueOf: returnsString
  2323. }, objectMembers);
  2324. function getLiteralMembersForValue(value) {
  2325. if (value instanceof RegExp) {
  2326. return literalRegExpMembers;
  2327. }
  2328. switch (typeof value) {
  2329. case 'boolean': {
  2330. return literalBooleanMembers;
  2331. }
  2332. case 'number': {
  2333. return literalNumberMembers;
  2334. }
  2335. case 'string': {
  2336. return literalStringMembers;
  2337. }
  2338. }
  2339. return Object.create(null);
  2340. }
  2341. function hasMemberEffectWhenCalled(members, memberName, interaction, context) {
  2342. if (typeof memberName !== 'string' || !members[memberName]) {
  2343. return true;
  2344. }
  2345. return members[memberName].hasEffectsWhenCalled?.(interaction, context) || false;
  2346. }
  2347. function getMemberReturnExpressionWhenCalled(members, memberName) {
  2348. if (typeof memberName !== 'string' || !members[memberName])
  2349. return UNKNOWN_RETURN_EXPRESSION;
  2350. return [members[memberName].returns, false];
  2351. }
  2352. // This file is generated by scripts/generate-child-node-keys.js.
  2353. // Do not edit this file directly.
  2354. const childNodeKeys = {
  2355. ArrayExpression: ['elements'],
  2356. ArrayPattern: ['elements'],
  2357. ArrowFunctionExpression: ['params', 'body'],
  2358. AssignmentExpression: ['left', 'right'],
  2359. AssignmentPattern: ['left', 'right'],
  2360. AwaitExpression: ['argument'],
  2361. BinaryExpression: ['left', 'right'],
  2362. BlockStatement: ['body'],
  2363. BreakStatement: ['label'],
  2364. CallExpression: ['callee', 'arguments'],
  2365. CatchClause: ['param', 'body'],
  2366. ChainExpression: ['expression'],
  2367. ClassBody: ['body'],
  2368. ClassDeclaration: ['decorators', 'id', 'superClass', 'body'],
  2369. ClassExpression: ['decorators', 'id', 'superClass', 'body'],
  2370. ConditionalExpression: ['test', 'consequent', 'alternate'],
  2371. ContinueStatement: ['label'],
  2372. DebuggerStatement: [],
  2373. Decorator: ['expression'],
  2374. DoWhileStatement: ['body', 'test'],
  2375. EmptyStatement: [],
  2376. ExportAllDeclaration: ['exported', 'source', 'attributes'],
  2377. ExportDefaultDeclaration: ['declaration'],
  2378. ExportNamedDeclaration: ['specifiers', 'source', 'attributes', 'declaration'],
  2379. ExportSpecifier: ['local', 'exported'],
  2380. ExpressionStatement: ['expression'],
  2381. ForInStatement: ['left', 'right', 'body'],
  2382. ForOfStatement: ['left', 'right', 'body'],
  2383. ForStatement: ['init', 'test', 'update', 'body'],
  2384. FunctionDeclaration: ['id', 'params', 'body'],
  2385. FunctionExpression: ['id', 'params', 'body'],
  2386. Identifier: [],
  2387. IfStatement: ['test', 'consequent', 'alternate'],
  2388. ImportAttribute: ['key', 'value'],
  2389. ImportDeclaration: ['specifiers', 'source', 'attributes'],
  2390. ImportDefaultSpecifier: ['local'],
  2391. ImportExpression: ['source', 'options'],
  2392. ImportNamespaceSpecifier: ['local'],
  2393. ImportSpecifier: ['imported', 'local'],
  2394. JSXAttribute: ['name', 'value'],
  2395. JSXClosingElement: ['name'],
  2396. JSXClosingFragment: [],
  2397. JSXElement: ['openingElement', 'children', 'closingElement'],
  2398. JSXEmptyExpression: [],
  2399. JSXExpressionContainer: ['expression'],
  2400. JSXFragment: ['openingFragment', 'children', 'closingFragment'],
  2401. JSXIdentifier: [],
  2402. JSXMemberExpression: ['object', 'property'],
  2403. JSXNamespacedName: ['namespace', 'name'],
  2404. JSXOpeningElement: ['name', 'attributes'],
  2405. JSXOpeningFragment: [],
  2406. JSXSpreadAttribute: ['argument'],
  2407. JSXSpreadChild: ['expression'],
  2408. JSXText: [],
  2409. LabeledStatement: ['label', 'body'],
  2410. Literal: [],
  2411. LogicalExpression: ['left', 'right'],
  2412. MemberExpression: ['object', 'property'],
  2413. MetaProperty: ['meta', 'property'],
  2414. MethodDefinition: ['decorators', 'key', 'value'],
  2415. NewExpression: ['callee', 'arguments'],
  2416. ObjectExpression: ['properties'],
  2417. ObjectPattern: ['properties'],
  2418. PanicError: [],
  2419. ParseError: [],
  2420. PrivateIdentifier: [],
  2421. Program: ['body'],
  2422. Property: ['key', 'value'],
  2423. PropertyDefinition: ['decorators', 'key', 'value'],
  2424. RestElement: ['argument'],
  2425. ReturnStatement: ['argument'],
  2426. SequenceExpression: ['expressions'],
  2427. SpreadElement: ['argument'],
  2428. StaticBlock: ['body'],
  2429. Super: [],
  2430. SwitchCase: ['test', 'consequent'],
  2431. SwitchStatement: ['discriminant', 'cases'],
  2432. TaggedTemplateExpression: ['tag', 'quasi'],
  2433. TemplateElement: [],
  2434. TemplateLiteral: ['quasis', 'expressions'],
  2435. ThisExpression: [],
  2436. ThrowStatement: ['argument'],
  2437. TryStatement: ['block', 'handler', 'finalizer'],
  2438. UnaryExpression: ['argument'],
  2439. UpdateExpression: ['argument'],
  2440. VariableDeclaration: ['declarations'],
  2441. VariableDeclarator: ['id', 'init'],
  2442. WhileStatement: ['test', 'body'],
  2443. YieldExpression: ['argument']
  2444. };
  2445. function createInclusionContext() {
  2446. return {
  2447. brokenFlow: false,
  2448. hasBreak: false,
  2449. hasContinue: false,
  2450. includedCallArguments: new Set(),
  2451. includedLabels: new Set()
  2452. };
  2453. }
  2454. function createHasEffectsContext() {
  2455. return {
  2456. accessed: new PathTracker(),
  2457. assigned: new PathTracker(),
  2458. brokenFlow: false,
  2459. called: new DiscriminatedPathTracker(),
  2460. hasBreak: false,
  2461. hasContinue: false,
  2462. ignore: {
  2463. breaks: false,
  2464. continues: false,
  2465. labels: new Set(),
  2466. returnYield: false,
  2467. this: false
  2468. },
  2469. includedLabels: new Set(),
  2470. instantiated: new DiscriminatedPathTracker(),
  2471. replacedVariableInits: new Map()
  2472. };
  2473. }
  2474. const INCLUDE_PARAMETERS = 'variables';
  2475. const IS_SKIPPED_CHAIN = Symbol('IS_SKIPPED_CHAIN');
  2476. class NodeBase extends ExpressionEntity {
  2477. /**
  2478. * Nodes can apply custom deoptimizations once they become part of the
  2479. * executed code. To do this, they must initialize this as false, implement
  2480. * applyDeoptimizations and call this from include and hasEffects if they have
  2481. * custom handlers
  2482. */
  2483. get deoptimized() {
  2484. return isFlagSet(this.flags, 2 /* Flag.deoptimized */);
  2485. }
  2486. set deoptimized(value) {
  2487. this.flags = setFlag(this.flags, 2 /* Flag.deoptimized */, value);
  2488. }
  2489. constructor(parent, parentScope) {
  2490. super();
  2491. this.parent = parent;
  2492. this.scope = parentScope;
  2493. this.createScope(parentScope);
  2494. }
  2495. addExportedVariables(_variables, _exportNamesByVariable) { }
  2496. /**
  2497. * Override this to bind assignments to variables and do any initialisations
  2498. * that require the scopes to be populated with variables.
  2499. */
  2500. bind() {
  2501. for (const key of childNodeKeys[this.type]) {
  2502. const value = this[key];
  2503. if (Array.isArray(value)) {
  2504. for (const child of value) {
  2505. child?.bind();
  2506. }
  2507. }
  2508. else if (value) {
  2509. value.bind();
  2510. }
  2511. }
  2512. }
  2513. /**
  2514. * Override if this node should receive a different scope than the parent
  2515. * scope.
  2516. */
  2517. createScope(parentScope) {
  2518. this.scope = parentScope;
  2519. }
  2520. hasEffects(context) {
  2521. if (!this.deoptimized)
  2522. this.applyDeoptimizations();
  2523. for (const key of childNodeKeys[this.type]) {
  2524. const value = this[key];
  2525. if (value === null)
  2526. continue;
  2527. if (Array.isArray(value)) {
  2528. for (const child of value) {
  2529. if (child?.hasEffects(context))
  2530. return true;
  2531. }
  2532. }
  2533. else if (value.hasEffects(context))
  2534. return true;
  2535. }
  2536. return false;
  2537. }
  2538. hasEffectsAsAssignmentTarget(context, _checkAccess) {
  2539. return (this.hasEffects(context) ||
  2540. this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
  2541. }
  2542. include(context, includeChildrenRecursively, _options) {
  2543. if (!this.deoptimized)
  2544. this.applyDeoptimizations();
  2545. this.included = true;
  2546. for (const key of childNodeKeys[this.type]) {
  2547. const value = this[key];
  2548. if (value === null)
  2549. continue;
  2550. if (Array.isArray(value)) {
  2551. for (const child of value) {
  2552. child?.include(context, includeChildrenRecursively);
  2553. }
  2554. }
  2555. else {
  2556. value.include(context, includeChildrenRecursively);
  2557. }
  2558. }
  2559. }
  2560. includeAsAssignmentTarget(context, includeChildrenRecursively, _deoptimizeAccess) {
  2561. this.include(context, includeChildrenRecursively);
  2562. }
  2563. /**
  2564. * Override to perform special initialisation steps after the scope is
  2565. * initialised
  2566. */
  2567. initialise() {
  2568. this.scope.context.magicString.addSourcemapLocation(this.start);
  2569. this.scope.context.magicString.addSourcemapLocation(this.end);
  2570. }
  2571. parseNode(esTreeNode) {
  2572. for (const [key, value] of Object.entries(esTreeNode)) {
  2573. // Skip properties defined on the class already.
  2574. // This way, we can override this function to add custom initialisation and then call super.parseNode
  2575. // Note: this doesn't skip properties with defined getters/setters which we use to pack wrap booleans
  2576. // in bitfields. Those are still assigned from the value in the esTreeNode.
  2577. if (this.hasOwnProperty(key))
  2578. continue;
  2579. if (key.charCodeAt(0) === 95 /* _ */) {
  2580. if (key === ANNOTATION_KEY) {
  2581. this.annotations = value;
  2582. }
  2583. else if (key === INVALID_ANNOTATION_KEY) {
  2584. this.invalidAnnotations = value;
  2585. }
  2586. }
  2587. else if (typeof value !== 'object' || value === null) {
  2588. this[key] = value;
  2589. }
  2590. else if (Array.isArray(value)) {
  2591. this[key] = [];
  2592. for (const child of value) {
  2593. this[key].push(child === null
  2594. ? null
  2595. : new (this.scope.context.getNodeConstructor(child.type))(this, this.scope).parseNode(child));
  2596. }
  2597. }
  2598. else {
  2599. this[key] = new (this.scope.context.getNodeConstructor(value.type))(this, this.scope).parseNode(value);
  2600. }
  2601. }
  2602. // extend child keys for unknown node types
  2603. childNodeKeys[esTreeNode.type] ||= createChildNodeKeysForNode(esTreeNode);
  2604. this.initialise();
  2605. return this;
  2606. }
  2607. removeAnnotations(code) {
  2608. if (this.annotations) {
  2609. for (const annotation of this.annotations) {
  2610. code.remove(annotation.start, annotation.end);
  2611. }
  2612. }
  2613. }
  2614. render(code, options) {
  2615. for (const key of childNodeKeys[this.type]) {
  2616. const value = this[key];
  2617. if (value === null)
  2618. continue;
  2619. if (Array.isArray(value)) {
  2620. for (const child of value) {
  2621. child?.render(code, options);
  2622. }
  2623. }
  2624. else {
  2625. value.render(code, options);
  2626. }
  2627. }
  2628. }
  2629. setAssignedValue(value) {
  2630. this.assignmentInteraction = { args: [null, value], type: INTERACTION_ASSIGNED };
  2631. }
  2632. shouldBeIncluded(context) {
  2633. return this.included || (!context.brokenFlow && this.hasEffects(createHasEffectsContext()));
  2634. }
  2635. /**
  2636. * Just deoptimize everything by default so that when e.g. we do not track
  2637. * something properly, it is deoptimized.
  2638. * @protected
  2639. */
  2640. applyDeoptimizations() {
  2641. this.deoptimized = true;
  2642. for (const key of childNodeKeys[this.type]) {
  2643. const value = this[key];
  2644. if (value === null)
  2645. continue;
  2646. if (Array.isArray(value)) {
  2647. for (const child of value) {
  2648. child?.deoptimizePath(UNKNOWN_PATH);
  2649. }
  2650. }
  2651. else {
  2652. value.deoptimizePath(UNKNOWN_PATH);
  2653. }
  2654. }
  2655. this.scope.context.requestTreeshakingPass();
  2656. }
  2657. }
  2658. function createChildNodeKeysForNode(esTreeNode) {
  2659. return Object.keys(esTreeNode).filter(key => typeof esTreeNode[key] === 'object' && key.charCodeAt(0) !== 95 /* _ */);
  2660. }
  2661. class SpreadElement extends NodeBase {
  2662. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  2663. if (path.length > 0) {
  2664. this.argument.deoptimizeArgumentsOnInteractionAtPath(interaction, [UnknownKey, ...path], recursionTracker);
  2665. }
  2666. }
  2667. hasEffects(context) {
  2668. if (!this.deoptimized)
  2669. this.applyDeoptimizations();
  2670. const { propertyReadSideEffects } = this.scope.context.options
  2671. .treeshake;
  2672. return (this.argument.hasEffects(context) ||
  2673. (propertyReadSideEffects &&
  2674. (propertyReadSideEffects === 'always' ||
  2675. this.argument.hasEffectsOnInteractionAtPath(UNKNOWN_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context))));
  2676. }
  2677. applyDeoptimizations() {
  2678. this.deoptimized = true;
  2679. // Only properties of properties of the argument could become subject to reassignment
  2680. // This will also reassign the return values of iterators
  2681. this.argument.deoptimizePath([UnknownKey, UnknownKey]);
  2682. this.scope.context.requestTreeshakingPass();
  2683. }
  2684. }
  2685. class Method extends ExpressionEntity {
  2686. constructor(description) {
  2687. super();
  2688. this.description = description;
  2689. }
  2690. deoptimizeArgumentsOnInteractionAtPath({ args, type }, path) {
  2691. if (type === INTERACTION_CALLED && path.length === 0) {
  2692. if (this.description.mutatesSelfAsArray) {
  2693. args[0]?.deoptimizePath(UNKNOWN_INTEGER_PATH);
  2694. }
  2695. if (this.description.mutatesArgs) {
  2696. for (let index = 1; index < args.length; index++) {
  2697. args[index].deoptimizePath(UNKNOWN_PATH);
  2698. }
  2699. }
  2700. }
  2701. }
  2702. getReturnExpressionWhenCalledAtPath(path, { args }) {
  2703. if (path.length > 0) {
  2704. return UNKNOWN_RETURN_EXPRESSION;
  2705. }
  2706. return [
  2707. this.description.returnsPrimitive ||
  2708. (this.description.returns === 'self'
  2709. ? args[0] || UNKNOWN_EXPRESSION
  2710. : this.description.returns()),
  2711. false
  2712. ];
  2713. }
  2714. hasEffectsOnInteractionAtPath(path, interaction, context) {
  2715. const { type } = interaction;
  2716. if (path.length > (type === INTERACTION_ACCESSED ? 1 : 0)) {
  2717. return true;
  2718. }
  2719. if (type === INTERACTION_CALLED) {
  2720. const { args } = interaction;
  2721. if (this.description.mutatesSelfAsArray === true &&
  2722. args[0]?.hasEffectsOnInteractionAtPath(UNKNOWN_INTEGER_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context)) {
  2723. return true;
  2724. }
  2725. if (this.description.callsArgs) {
  2726. for (const argumentIndex of this.description.callsArgs) {
  2727. if (args[argumentIndex + 1]?.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)) {
  2728. return true;
  2729. }
  2730. }
  2731. }
  2732. }
  2733. return false;
  2734. }
  2735. }
  2736. const METHOD_RETURNS_BOOLEAN = [
  2737. new Method({
  2738. callsArgs: null,
  2739. mutatesArgs: false,
  2740. mutatesSelfAsArray: false,
  2741. returns: null,
  2742. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  2743. })
  2744. ];
  2745. const METHOD_RETURNS_STRING = [
  2746. new Method({
  2747. callsArgs: null,
  2748. mutatesArgs: false,
  2749. mutatesSelfAsArray: false,
  2750. returns: null,
  2751. returnsPrimitive: UNKNOWN_LITERAL_STRING
  2752. })
  2753. ];
  2754. const METHOD_RETURNS_NUMBER = [
  2755. new Method({
  2756. callsArgs: null,
  2757. mutatesArgs: false,
  2758. mutatesSelfAsArray: false,
  2759. returns: null,
  2760. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  2761. })
  2762. ];
  2763. const METHOD_RETURNS_UNKNOWN = [
  2764. new Method({
  2765. callsArgs: null,
  2766. mutatesArgs: false,
  2767. mutatesSelfAsArray: false,
  2768. returns: null,
  2769. returnsPrimitive: UNKNOWN_EXPRESSION
  2770. })
  2771. ];
  2772. const INTEGER_REG_EXP = /^\d+$/;
  2773. class ObjectEntity extends ExpressionEntity {
  2774. get hasLostTrack() {
  2775. return isFlagSet(this.flags, 2048 /* Flag.hasLostTrack */);
  2776. }
  2777. set hasLostTrack(value) {
  2778. this.flags = setFlag(this.flags, 2048 /* Flag.hasLostTrack */, value);
  2779. }
  2780. get hasUnknownDeoptimizedInteger() {
  2781. return isFlagSet(this.flags, 4096 /* Flag.hasUnknownDeoptimizedInteger */);
  2782. }
  2783. set hasUnknownDeoptimizedInteger(value) {
  2784. this.flags = setFlag(this.flags, 4096 /* Flag.hasUnknownDeoptimizedInteger */, value);
  2785. }
  2786. get hasUnknownDeoptimizedProperty() {
  2787. return isFlagSet(this.flags, 8192 /* Flag.hasUnknownDeoptimizedProperty */);
  2788. }
  2789. set hasUnknownDeoptimizedProperty(value) {
  2790. this.flags = setFlag(this.flags, 8192 /* Flag.hasUnknownDeoptimizedProperty */, value);
  2791. }
  2792. // If a PropertyMap is used, this will be taken as propertiesAndGettersByKey
  2793. // and we assume there are no setters or getters
  2794. constructor(properties, prototypeExpression, immutable = false) {
  2795. super();
  2796. this.prototypeExpression = prototypeExpression;
  2797. this.immutable = immutable;
  2798. this.additionalExpressionsToBeDeoptimized = new Set();
  2799. this.allProperties = [];
  2800. this.deoptimizedPaths = Object.create(null);
  2801. this.expressionsToBeDeoptimizedByKey = Object.create(null);
  2802. this.gettersByKey = Object.create(null);
  2803. this.propertiesAndGettersByKey = Object.create(null);
  2804. this.propertiesAndSettersByKey = Object.create(null);
  2805. this.settersByKey = Object.create(null);
  2806. this.unknownIntegerProps = [];
  2807. this.unmatchableGetters = [];
  2808. this.unmatchablePropertiesAndGetters = [];
  2809. this.unmatchableSetters = [];
  2810. if (Array.isArray(properties)) {
  2811. this.buildPropertyMaps(properties);
  2812. }
  2813. else {
  2814. this.propertiesAndGettersByKey = this.propertiesAndSettersByKey = properties;
  2815. for (const propertiesForKey of Object.values(properties)) {
  2816. this.allProperties.push(...propertiesForKey);
  2817. }
  2818. }
  2819. }
  2820. deoptimizeAllProperties(noAccessors) {
  2821. const isDeoptimized = this.hasLostTrack || this.hasUnknownDeoptimizedProperty;
  2822. if (noAccessors) {
  2823. this.hasUnknownDeoptimizedProperty = true;
  2824. }
  2825. else {
  2826. this.hasLostTrack = true;
  2827. }
  2828. if (isDeoptimized) {
  2829. return;
  2830. }
  2831. for (const properties of [
  2832. ...Object.values(this.propertiesAndGettersByKey),
  2833. ...Object.values(this.settersByKey)
  2834. ]) {
  2835. for (const property of properties) {
  2836. property.deoptimizePath(UNKNOWN_PATH);
  2837. }
  2838. }
  2839. // While the prototype itself cannot be mutated, each property can
  2840. this.prototypeExpression?.deoptimizePath([UnknownKey, UnknownKey]);
  2841. this.deoptimizeCachedEntities();
  2842. }
  2843. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  2844. const [key, ...subPath] = path;
  2845. const { args, type } = interaction;
  2846. if (this.hasLostTrack ||
  2847. // single paths that are deoptimized will not become getters or setters
  2848. ((type === INTERACTION_CALLED || path.length > 1) &&
  2849. (this.hasUnknownDeoptimizedProperty ||
  2850. (typeof key === 'string' && this.deoptimizedPaths[key])))) {
  2851. deoptimizeInteraction(interaction);
  2852. return;
  2853. }
  2854. const [propertiesForExactMatchByKey, relevantPropertiesByKey, relevantUnmatchableProperties] = type === INTERACTION_CALLED || path.length > 1
  2855. ? [
  2856. this.propertiesAndGettersByKey,
  2857. this.propertiesAndGettersByKey,
  2858. this.unmatchablePropertiesAndGetters
  2859. ]
  2860. : type === INTERACTION_ACCESSED
  2861. ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters]
  2862. : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters];
  2863. if (typeof key === 'string') {
  2864. if (propertiesForExactMatchByKey[key]) {
  2865. const properties = relevantPropertiesByKey[key];
  2866. if (properties) {
  2867. for (const property of properties) {
  2868. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  2869. }
  2870. }
  2871. if (!this.immutable) {
  2872. for (const argument of args) {
  2873. if (argument) {
  2874. this.additionalExpressionsToBeDeoptimized.add(argument);
  2875. }
  2876. }
  2877. }
  2878. return;
  2879. }
  2880. for (const property of relevantUnmatchableProperties) {
  2881. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  2882. }
  2883. if (INTEGER_REG_EXP.test(key)) {
  2884. for (const property of this.unknownIntegerProps) {
  2885. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  2886. }
  2887. }
  2888. }
  2889. else {
  2890. for (const properties of [
  2891. ...Object.values(relevantPropertiesByKey),
  2892. relevantUnmatchableProperties
  2893. ]) {
  2894. for (const property of properties) {
  2895. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  2896. }
  2897. }
  2898. for (const property of this.unknownIntegerProps) {
  2899. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  2900. }
  2901. }
  2902. if (!this.immutable) {
  2903. for (const argument of args) {
  2904. if (argument) {
  2905. this.additionalExpressionsToBeDeoptimized.add(argument);
  2906. }
  2907. }
  2908. }
  2909. this.prototypeExpression?.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  2910. }
  2911. deoptimizeIntegerProperties() {
  2912. if (this.hasLostTrack ||
  2913. this.hasUnknownDeoptimizedProperty ||
  2914. this.hasUnknownDeoptimizedInteger) {
  2915. return;
  2916. }
  2917. this.hasUnknownDeoptimizedInteger = true;
  2918. for (const [key, propertiesAndGetters] of Object.entries(this.propertiesAndGettersByKey)) {
  2919. if (INTEGER_REG_EXP.test(key)) {
  2920. for (const property of propertiesAndGetters) {
  2921. property.deoptimizePath(UNKNOWN_PATH);
  2922. }
  2923. }
  2924. }
  2925. this.deoptimizeCachedIntegerEntities();
  2926. }
  2927. // Assumption: If only a specific path is deoptimized, no accessors are created
  2928. deoptimizePath(path) {
  2929. if (this.hasLostTrack || this.immutable) {
  2930. return;
  2931. }
  2932. const key = path[0];
  2933. if (path.length === 1) {
  2934. if (key === UnknownInteger) {
  2935. return this.deoptimizeIntegerProperties();
  2936. }
  2937. else if (typeof key !== 'string') {
  2938. return this.deoptimizeAllProperties(key === UnknownNonAccessorKey);
  2939. }
  2940. if (!this.deoptimizedPaths[key]) {
  2941. this.deoptimizedPaths[key] = true;
  2942. // we only deoptimizeCache exact matches as in all other cases,
  2943. // we do not return a literal value or return expression
  2944. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimizedByKey[key];
  2945. if (expressionsToBeDeoptimized) {
  2946. for (const expression of expressionsToBeDeoptimized) {
  2947. expression.deoptimizeCache();
  2948. }
  2949. }
  2950. }
  2951. }
  2952. const subPath = path.length === 1 ? UNKNOWN_PATH : path.slice(1);
  2953. for (const property of typeof key === 'string'
  2954. ? [
  2955. ...(this.propertiesAndGettersByKey[key] || this.unmatchablePropertiesAndGetters),
  2956. ...(this.settersByKey[key] || this.unmatchableSetters)
  2957. ]
  2958. : this.allProperties) {
  2959. property.deoptimizePath(subPath);
  2960. }
  2961. this.prototypeExpression?.deoptimizePath(path.length === 1 ? [...path, UnknownKey] : path);
  2962. }
  2963. getLiteralValueAtPath(path, recursionTracker, origin) {
  2964. if (path.length === 0) {
  2965. return UnknownTruthyValue;
  2966. }
  2967. const key = path[0];
  2968. const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
  2969. if (expressionAtPath) {
  2970. return expressionAtPath.getLiteralValueAtPath(path.slice(1), recursionTracker, origin);
  2971. }
  2972. if (this.prototypeExpression) {
  2973. return this.prototypeExpression.getLiteralValueAtPath(path, recursionTracker, origin);
  2974. }
  2975. if (path.length === 1) {
  2976. return undefined;
  2977. }
  2978. return UnknownValue;
  2979. }
  2980. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  2981. if (path.length === 0) {
  2982. return UNKNOWN_RETURN_EXPRESSION;
  2983. }
  2984. const [key, ...subPath] = path;
  2985. const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
  2986. if (expressionAtPath) {
  2987. return expressionAtPath.getReturnExpressionWhenCalledAtPath(subPath, interaction, recursionTracker, origin);
  2988. }
  2989. if (this.prototypeExpression) {
  2990. return this.prototypeExpression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  2991. }
  2992. return UNKNOWN_RETURN_EXPRESSION;
  2993. }
  2994. hasEffectsOnInteractionAtPath(path, interaction, context) {
  2995. const [key, ...subPath] = path;
  2996. if (subPath.length > 0 || interaction.type === INTERACTION_CALLED) {
  2997. const expressionAtPath = this.getMemberExpression(key);
  2998. if (expressionAtPath) {
  2999. return expressionAtPath.hasEffectsOnInteractionAtPath(subPath, interaction, context);
  3000. }
  3001. if (this.prototypeExpression) {
  3002. return this.prototypeExpression.hasEffectsOnInteractionAtPath(path, interaction, context);
  3003. }
  3004. return true;
  3005. }
  3006. if (key === UnknownNonAccessorKey)
  3007. return false;
  3008. if (this.hasLostTrack)
  3009. return true;
  3010. const [propertiesAndAccessorsByKey, accessorsByKey, unmatchableAccessors] = interaction.type === INTERACTION_ACCESSED
  3011. ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters]
  3012. : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters];
  3013. if (typeof key === 'string') {
  3014. if (propertiesAndAccessorsByKey[key]) {
  3015. const accessors = accessorsByKey[key];
  3016. if (accessors) {
  3017. for (const accessor of accessors) {
  3018. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context))
  3019. return true;
  3020. }
  3021. }
  3022. return false;
  3023. }
  3024. for (const accessor of unmatchableAccessors) {
  3025. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context)) {
  3026. return true;
  3027. }
  3028. }
  3029. }
  3030. else {
  3031. for (const accessors of [...Object.values(accessorsByKey), unmatchableAccessors]) {
  3032. for (const accessor of accessors) {
  3033. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context))
  3034. return true;
  3035. }
  3036. }
  3037. }
  3038. if (this.prototypeExpression) {
  3039. return this.prototypeExpression.hasEffectsOnInteractionAtPath(path, interaction, context);
  3040. }
  3041. return false;
  3042. }
  3043. buildPropertyMaps(properties) {
  3044. const { allProperties, propertiesAndGettersByKey, propertiesAndSettersByKey, settersByKey, gettersByKey, unknownIntegerProps, unmatchablePropertiesAndGetters, unmatchableGetters, unmatchableSetters } = this;
  3045. const unmatchablePropertiesAndSetters = [];
  3046. for (let index = properties.length - 1; index >= 0; index--) {
  3047. const { key, kind, property } = properties[index];
  3048. allProperties.push(property);
  3049. if (typeof key === 'string') {
  3050. if (kind === 'set') {
  3051. if (!propertiesAndSettersByKey[key]) {
  3052. propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters];
  3053. settersByKey[key] = [property, ...unmatchableSetters];
  3054. }
  3055. }
  3056. else if (kind === 'get') {
  3057. if (!propertiesAndGettersByKey[key]) {
  3058. propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters];
  3059. gettersByKey[key] = [property, ...unmatchableGetters];
  3060. }
  3061. }
  3062. else {
  3063. if (!propertiesAndSettersByKey[key]) {
  3064. propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters];
  3065. }
  3066. if (!propertiesAndGettersByKey[key]) {
  3067. propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters];
  3068. }
  3069. }
  3070. }
  3071. else {
  3072. if (key === UnknownInteger) {
  3073. unknownIntegerProps.push(property);
  3074. continue;
  3075. }
  3076. if (kind === 'set')
  3077. unmatchableSetters.push(property);
  3078. if (kind === 'get')
  3079. unmatchableGetters.push(property);
  3080. if (kind !== 'get')
  3081. unmatchablePropertiesAndSetters.push(property);
  3082. if (kind !== 'set')
  3083. unmatchablePropertiesAndGetters.push(property);
  3084. }
  3085. }
  3086. }
  3087. deoptimizeCachedEntities() {
  3088. for (const expressionsToBeDeoptimized of Object.values(this.expressionsToBeDeoptimizedByKey)) {
  3089. for (const expression of expressionsToBeDeoptimized) {
  3090. expression.deoptimizeCache();
  3091. }
  3092. }
  3093. for (const expression of this.additionalExpressionsToBeDeoptimized) {
  3094. expression.deoptimizePath(UNKNOWN_PATH);
  3095. }
  3096. }
  3097. deoptimizeCachedIntegerEntities() {
  3098. for (const [key, expressionsToBeDeoptimized] of Object.entries(this.expressionsToBeDeoptimizedByKey)) {
  3099. if (INTEGER_REG_EXP.test(key)) {
  3100. for (const expression of expressionsToBeDeoptimized) {
  3101. expression.deoptimizeCache();
  3102. }
  3103. }
  3104. }
  3105. for (const expression of this.additionalExpressionsToBeDeoptimized) {
  3106. expression.deoptimizePath(UNKNOWN_INTEGER_PATH);
  3107. }
  3108. }
  3109. getMemberExpression(key) {
  3110. if (this.hasLostTrack ||
  3111. this.hasUnknownDeoptimizedProperty ||
  3112. typeof key !== 'string' ||
  3113. (this.hasUnknownDeoptimizedInteger && INTEGER_REG_EXP.test(key)) ||
  3114. this.deoptimizedPaths[key]) {
  3115. return UNKNOWN_EXPRESSION;
  3116. }
  3117. const properties = this.propertiesAndGettersByKey[key];
  3118. if (properties?.length === 1) {
  3119. return properties[0];
  3120. }
  3121. if (properties ||
  3122. this.unmatchablePropertiesAndGetters.length > 0 ||
  3123. (this.unknownIntegerProps.length > 0 && INTEGER_REG_EXP.test(key))) {
  3124. return UNKNOWN_EXPRESSION;
  3125. }
  3126. return null;
  3127. }
  3128. getMemberExpressionAndTrackDeopt(key, origin) {
  3129. if (typeof key !== 'string') {
  3130. return UNKNOWN_EXPRESSION;
  3131. }
  3132. const expression = this.getMemberExpression(key);
  3133. if (!(expression === UNKNOWN_EXPRESSION || this.immutable)) {
  3134. const expressionsToBeDeoptimized = (this.expressionsToBeDeoptimizedByKey[key] =
  3135. this.expressionsToBeDeoptimizedByKey[key] || []);
  3136. expressionsToBeDeoptimized.push(origin);
  3137. }
  3138. return expression;
  3139. }
  3140. }
  3141. const isInteger = (property) => typeof property === 'string' && /^\d+$/.test(property);
  3142. // This makes sure unknown properties are not handled as "undefined" but as
  3143. // "unknown" but without access side effects. An exception is done for numeric
  3144. // properties as we do not expect new builtin properties to be numbers, this
  3145. // will improve tree-shaking for out-of-bounds array properties
  3146. const OBJECT_PROTOTYPE_FALLBACK = new (class ObjectPrototypeFallbackExpression extends ExpressionEntity {
  3147. deoptimizeArgumentsOnInteractionAtPath(interaction, path) {
  3148. if (interaction.type === INTERACTION_CALLED && path.length === 1 && !isInteger(path[0])) {
  3149. deoptimizeInteraction(interaction);
  3150. }
  3151. }
  3152. getLiteralValueAtPath(path) {
  3153. // We ignore number properties as we do not expect new properties to be
  3154. // numbers and also want to keep handling out-of-bound array elements as
  3155. // "undefined"
  3156. return path.length === 1 && isInteger(path[0]) ? undefined : UnknownValue;
  3157. }
  3158. hasEffectsOnInteractionAtPath(path, { type }) {
  3159. return path.length > 1 || type === INTERACTION_CALLED;
  3160. }
  3161. })();
  3162. const OBJECT_PROTOTYPE = new ObjectEntity({
  3163. __proto__: null,
  3164. hasOwnProperty: METHOD_RETURNS_BOOLEAN,
  3165. isPrototypeOf: METHOD_RETURNS_BOOLEAN,
  3166. propertyIsEnumerable: METHOD_RETURNS_BOOLEAN,
  3167. toLocaleString: METHOD_RETURNS_STRING,
  3168. toString: METHOD_RETURNS_STRING,
  3169. valueOf: METHOD_RETURNS_UNKNOWN
  3170. }, OBJECT_PROTOTYPE_FALLBACK, true);
  3171. const NEW_ARRAY_PROPERTIES = [
  3172. { key: UnknownInteger, kind: 'init', property: UNKNOWN_EXPRESSION },
  3173. { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
  3174. ];
  3175. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN = [
  3176. new Method({
  3177. callsArgs: [0],
  3178. mutatesArgs: false,
  3179. mutatesSelfAsArray: 'deopt-only',
  3180. returns: null,
  3181. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  3182. })
  3183. ];
  3184. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER = [
  3185. new Method({
  3186. callsArgs: [0],
  3187. mutatesArgs: false,
  3188. mutatesSelfAsArray: 'deopt-only',
  3189. returns: null,
  3190. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  3191. })
  3192. ];
  3193. const METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY = [
  3194. new Method({
  3195. callsArgs: null,
  3196. mutatesArgs: false,
  3197. mutatesSelfAsArray: true,
  3198. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  3199. returnsPrimitive: null
  3200. })
  3201. ];
  3202. const METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
  3203. new Method({
  3204. callsArgs: null,
  3205. mutatesArgs: false,
  3206. mutatesSelfAsArray: 'deopt-only',
  3207. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  3208. returnsPrimitive: null
  3209. })
  3210. ];
  3211. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
  3212. new Method({
  3213. callsArgs: [0],
  3214. mutatesArgs: false,
  3215. mutatesSelfAsArray: 'deopt-only',
  3216. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  3217. returnsPrimitive: null
  3218. })
  3219. ];
  3220. const METHOD_MUTATES_SELF_AND_ARGS_RETURNS_NUMBER = [
  3221. new Method({
  3222. callsArgs: null,
  3223. mutatesArgs: true,
  3224. mutatesSelfAsArray: true,
  3225. returns: null,
  3226. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  3227. })
  3228. ];
  3229. const METHOD_MUTATES_SELF_RETURNS_UNKNOWN = [
  3230. new Method({
  3231. callsArgs: null,
  3232. mutatesArgs: false,
  3233. mutatesSelfAsArray: true,
  3234. returns: null,
  3235. returnsPrimitive: UNKNOWN_EXPRESSION
  3236. })
  3237. ];
  3238. const METHOD_DEOPTS_SELF_RETURNS_UNKNOWN = [
  3239. new Method({
  3240. callsArgs: null,
  3241. mutatesArgs: false,
  3242. mutatesSelfAsArray: 'deopt-only',
  3243. returns: null,
  3244. returnsPrimitive: UNKNOWN_EXPRESSION
  3245. })
  3246. ];
  3247. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN = [
  3248. new Method({
  3249. callsArgs: [0],
  3250. mutatesArgs: false,
  3251. mutatesSelfAsArray: 'deopt-only',
  3252. returns: null,
  3253. returnsPrimitive: UNKNOWN_EXPRESSION
  3254. })
  3255. ];
  3256. const METHOD_MUTATES_SELF_RETURNS_SELF = [
  3257. new Method({
  3258. callsArgs: null,
  3259. mutatesArgs: false,
  3260. mutatesSelfAsArray: true,
  3261. returns: 'self',
  3262. returnsPrimitive: null
  3263. })
  3264. ];
  3265. const METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF = [
  3266. new Method({
  3267. callsArgs: [0],
  3268. mutatesArgs: false,
  3269. mutatesSelfAsArray: true,
  3270. returns: 'self',
  3271. returnsPrimitive: null
  3272. })
  3273. ];
  3274. const ARRAY_PROTOTYPE = new ObjectEntity({
  3275. __proto__: null,
  3276. // We assume that accessors have effects as we do not track the accessed value afterwards
  3277. at: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN,
  3278. concat: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  3279. copyWithin: METHOD_MUTATES_SELF_RETURNS_SELF,
  3280. entries: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  3281. every: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN,
  3282. fill: METHOD_MUTATES_SELF_RETURNS_SELF,
  3283. filter: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  3284. find: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  3285. findIndex: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER,
  3286. findLast: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  3287. findLastIndex: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER,
  3288. flat: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  3289. flatMap: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  3290. forEach: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  3291. includes: METHOD_RETURNS_BOOLEAN,
  3292. indexOf: METHOD_RETURNS_NUMBER,
  3293. join: METHOD_RETURNS_STRING,
  3294. keys: METHOD_RETURNS_UNKNOWN,
  3295. lastIndexOf: METHOD_RETURNS_NUMBER,
  3296. map: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  3297. pop: METHOD_MUTATES_SELF_RETURNS_UNKNOWN,
  3298. push: METHOD_MUTATES_SELF_AND_ARGS_RETURNS_NUMBER,
  3299. reduce: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  3300. reduceRight: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  3301. reverse: METHOD_MUTATES_SELF_RETURNS_SELF,
  3302. shift: METHOD_MUTATES_SELF_RETURNS_UNKNOWN,
  3303. slice: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  3304. some: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN,
  3305. sort: METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF,
  3306. splice: METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY,
  3307. toLocaleString: METHOD_RETURNS_STRING,
  3308. toString: METHOD_RETURNS_STRING,
  3309. unshift: METHOD_MUTATES_SELF_AND_ARGS_RETURNS_NUMBER,
  3310. values: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN
  3311. }, OBJECT_PROTOTYPE, true);
  3312. class ArrayExpression extends NodeBase {
  3313. constructor() {
  3314. super(...arguments);
  3315. this.objectEntity = null;
  3316. }
  3317. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  3318. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  3319. }
  3320. deoptimizePath(path) {
  3321. this.getObjectEntity().deoptimizePath(path);
  3322. }
  3323. getLiteralValueAtPath(path, recursionTracker, origin) {
  3324. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  3325. }
  3326. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  3327. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  3328. }
  3329. hasEffectsOnInteractionAtPath(path, interaction, context) {
  3330. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  3331. }
  3332. applyDeoptimizations() {
  3333. this.deoptimized = true;
  3334. let hasSpread = false;
  3335. for (let index = 0; index < this.elements.length; index++) {
  3336. const element = this.elements[index];
  3337. if (element && (hasSpread || element instanceof SpreadElement)) {
  3338. hasSpread = true;
  3339. element.deoptimizePath(UNKNOWN_PATH);
  3340. }
  3341. }
  3342. this.scope.context.requestTreeshakingPass();
  3343. }
  3344. getObjectEntity() {
  3345. if (this.objectEntity !== null) {
  3346. return this.objectEntity;
  3347. }
  3348. const properties = [
  3349. { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
  3350. ];
  3351. let hasSpread = false;
  3352. for (let index = 0; index < this.elements.length; index++) {
  3353. const element = this.elements[index];
  3354. if (hasSpread || element instanceof SpreadElement) {
  3355. if (element) {
  3356. hasSpread = true;
  3357. properties.unshift({ key: UnknownInteger, kind: 'init', property: element });
  3358. }
  3359. }
  3360. else if (element) {
  3361. properties.push({ key: String(index), kind: 'init', property: element });
  3362. }
  3363. else {
  3364. properties.push({ key: String(index), kind: 'init', property: UNDEFINED_EXPRESSION });
  3365. }
  3366. }
  3367. return (this.objectEntity = new ObjectEntity(properties, ARRAY_PROTOTYPE));
  3368. }
  3369. }
  3370. /* eslint sort-keys: "off" */
  3371. const ValueProperties = Symbol('Value Properties');
  3372. const getTruthyLiteralValue = () => UnknownTruthyValue;
  3373. const returnFalse = () => false;
  3374. const returnTrue = () => true;
  3375. const PURE = {
  3376. deoptimizeArgumentsOnCall: doNothing,
  3377. getLiteralValue: getTruthyLiteralValue,
  3378. hasEffectsWhenCalled: returnFalse
  3379. };
  3380. const IMPURE = {
  3381. deoptimizeArgumentsOnCall: doNothing,
  3382. getLiteralValue: getTruthyLiteralValue,
  3383. hasEffectsWhenCalled: returnTrue
  3384. };
  3385. const PURE_WITH_ARRAY = {
  3386. deoptimizeArgumentsOnCall: doNothing,
  3387. getLiteralValue: getTruthyLiteralValue,
  3388. hasEffectsWhenCalled({ args }) {
  3389. return args.length > 1 && !(args[1] instanceof ArrayExpression);
  3390. }
  3391. };
  3392. const GETTER_ACCESS = {
  3393. deoptimizeArgumentsOnCall: doNothing,
  3394. getLiteralValue: getTruthyLiteralValue,
  3395. hasEffectsWhenCalled({ args }, context) {
  3396. const [_thisArgument, firstArgument] = args;
  3397. return (!(firstArgument instanceof ExpressionEntity) ||
  3398. firstArgument.hasEffectsOnInteractionAtPath(UNKNOWN_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context));
  3399. }
  3400. };
  3401. // We use shortened variables to reduce file size here
  3402. /* OBJECT */
  3403. const O = {
  3404. __proto__: null,
  3405. [ValueProperties]: IMPURE
  3406. };
  3407. /* PURE FUNCTION */
  3408. const PF = {
  3409. __proto__: null,
  3410. [ValueProperties]: PURE
  3411. };
  3412. /* PURE FUNCTION IF FIRST ARG DOES NOT CONTAIN A GETTER */
  3413. const PF_NO_GETTER = {
  3414. __proto__: null,
  3415. [ValueProperties]: GETTER_ACCESS
  3416. };
  3417. /* FUNCTION THAT MUTATES FIRST ARG WITHOUT TRIGGERING ACCESSORS */
  3418. const MUTATES_ARG_WITHOUT_ACCESSOR = {
  3419. __proto__: null,
  3420. [ValueProperties]: {
  3421. deoptimizeArgumentsOnCall({ args: [, firstArgument] }) {
  3422. firstArgument?.deoptimizePath(UNKNOWN_PATH);
  3423. },
  3424. getLiteralValue: getTruthyLiteralValue,
  3425. hasEffectsWhenCalled({ args }, context) {
  3426. return (args.length <= 1 ||
  3427. args[1].hasEffectsOnInteractionAtPath(UNKNOWN_NON_ACCESSOR_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context));
  3428. }
  3429. }
  3430. };
  3431. /* CONSTRUCTOR */
  3432. const C = {
  3433. __proto__: null,
  3434. [ValueProperties]: IMPURE,
  3435. prototype: O
  3436. };
  3437. /* PURE CONSTRUCTOR */
  3438. const PC = {
  3439. __proto__: null,
  3440. [ValueProperties]: PURE,
  3441. prototype: O
  3442. };
  3443. const PC_WITH_ARRAY = {
  3444. __proto__: null,
  3445. [ValueProperties]: PURE_WITH_ARRAY,
  3446. prototype: O
  3447. };
  3448. const ARRAY_TYPE = {
  3449. __proto__: null,
  3450. [ValueProperties]: PURE,
  3451. from: O,
  3452. of: PF,
  3453. prototype: O
  3454. };
  3455. const INTL_MEMBER = {
  3456. __proto__: null,
  3457. [ValueProperties]: PURE,
  3458. supportedLocalesOf: PC
  3459. };
  3460. const knownGlobals = {
  3461. // Placeholders for global objects to avoid shape mutations
  3462. global: O,
  3463. globalThis: O,
  3464. self: O,
  3465. window: O,
  3466. // Common globals
  3467. __proto__: null,
  3468. [ValueProperties]: IMPURE,
  3469. Array: {
  3470. __proto__: null,
  3471. [ValueProperties]: IMPURE,
  3472. from: O,
  3473. isArray: PF,
  3474. of: PF,
  3475. prototype: O
  3476. },
  3477. ArrayBuffer: {
  3478. __proto__: null,
  3479. [ValueProperties]: PURE,
  3480. isView: PF,
  3481. prototype: O
  3482. },
  3483. AggregateError: PC_WITH_ARRAY,
  3484. Atomics: O,
  3485. BigInt: C,
  3486. BigInt64Array: C,
  3487. BigUint64Array: C,
  3488. Boolean: PC,
  3489. constructor: C,
  3490. DataView: PC,
  3491. Date: {
  3492. __proto__: null,
  3493. [ValueProperties]: PURE,
  3494. now: PF,
  3495. parse: PF,
  3496. prototype: O,
  3497. UTC: PF
  3498. },
  3499. decodeURI: PF,
  3500. decodeURIComponent: PF,
  3501. encodeURI: PF,
  3502. encodeURIComponent: PF,
  3503. Error: PC,
  3504. escape: PF,
  3505. eval: O,
  3506. EvalError: PC,
  3507. FinalizationRegistry: C,
  3508. Float32Array: ARRAY_TYPE,
  3509. Float64Array: ARRAY_TYPE,
  3510. Function: C,
  3511. hasOwnProperty: O,
  3512. Infinity: O,
  3513. Int16Array: ARRAY_TYPE,
  3514. Int32Array: ARRAY_TYPE,
  3515. Int8Array: ARRAY_TYPE,
  3516. isFinite: PF,
  3517. isNaN: PF,
  3518. isPrototypeOf: O,
  3519. JSON: O,
  3520. Map: PC_WITH_ARRAY,
  3521. Math: {
  3522. __proto__: null,
  3523. [ValueProperties]: IMPURE,
  3524. abs: PF,
  3525. acos: PF,
  3526. acosh: PF,
  3527. asin: PF,
  3528. asinh: PF,
  3529. atan: PF,
  3530. atan2: PF,
  3531. atanh: PF,
  3532. cbrt: PF,
  3533. ceil: PF,
  3534. clz32: PF,
  3535. cos: PF,
  3536. cosh: PF,
  3537. exp: PF,
  3538. expm1: PF,
  3539. floor: PF,
  3540. fround: PF,
  3541. hypot: PF,
  3542. imul: PF,
  3543. log: PF,
  3544. log10: PF,
  3545. log1p: PF,
  3546. log2: PF,
  3547. max: PF,
  3548. min: PF,
  3549. pow: PF,
  3550. random: PF,
  3551. round: PF,
  3552. sign: PF,
  3553. sin: PF,
  3554. sinh: PF,
  3555. sqrt: PF,
  3556. tan: PF,
  3557. tanh: PF,
  3558. trunc: PF
  3559. },
  3560. NaN: O,
  3561. Number: {
  3562. __proto__: null,
  3563. [ValueProperties]: PURE,
  3564. isFinite: PF,
  3565. isInteger: PF,
  3566. isNaN: PF,
  3567. isSafeInteger: PF,
  3568. parseFloat: PF,
  3569. parseInt: PF,
  3570. prototype: O
  3571. },
  3572. Object: {
  3573. __proto__: null,
  3574. [ValueProperties]: PURE,
  3575. create: PF,
  3576. // Technically those can throw in certain situations, but we ignore this as
  3577. // code that relies on this will hopefully wrap this in a try-catch, which
  3578. // deoptimizes everything anyway
  3579. defineProperty: MUTATES_ARG_WITHOUT_ACCESSOR,
  3580. defineProperties: MUTATES_ARG_WITHOUT_ACCESSOR,
  3581. freeze: MUTATES_ARG_WITHOUT_ACCESSOR,
  3582. getOwnPropertyDescriptor: PF,
  3583. getOwnPropertyDescriptors: PF,
  3584. getOwnPropertyNames: PF,
  3585. getOwnPropertySymbols: PF,
  3586. getPrototypeOf: PF,
  3587. hasOwn: PF,
  3588. is: PF,
  3589. isExtensible: PF,
  3590. isFrozen: PF,
  3591. isSealed: PF,
  3592. keys: PF,
  3593. fromEntries: O,
  3594. entries: PF_NO_GETTER,
  3595. values: PF_NO_GETTER,
  3596. prototype: O
  3597. },
  3598. parseFloat: PF,
  3599. parseInt: PF,
  3600. Promise: {
  3601. __proto__: null,
  3602. [ValueProperties]: IMPURE,
  3603. all: O,
  3604. allSettled: O,
  3605. any: O,
  3606. prototype: O,
  3607. race: O,
  3608. reject: O,
  3609. resolve: O
  3610. },
  3611. propertyIsEnumerable: O,
  3612. Proxy: O,
  3613. RangeError: PC,
  3614. ReferenceError: PC,
  3615. Reflect: O,
  3616. RegExp: PC,
  3617. Set: PC_WITH_ARRAY,
  3618. SharedArrayBuffer: C,
  3619. String: {
  3620. __proto__: null,
  3621. [ValueProperties]: PURE,
  3622. fromCharCode: PF,
  3623. fromCodePoint: PF,
  3624. prototype: O,
  3625. raw: PF
  3626. },
  3627. Symbol: {
  3628. __proto__: null,
  3629. [ValueProperties]: PURE,
  3630. for: PF,
  3631. keyFor: PF,
  3632. prototype: O,
  3633. toStringTag: {
  3634. __proto__: null,
  3635. [ValueProperties]: {
  3636. deoptimizeArgumentsOnCall: doNothing,
  3637. getLiteralValue() {
  3638. return SymbolToStringTag;
  3639. },
  3640. hasEffectsWhenCalled: returnTrue
  3641. }
  3642. }
  3643. },
  3644. SyntaxError: PC,
  3645. toLocaleString: O,
  3646. toString: O,
  3647. TypeError: PC,
  3648. Uint16Array: ARRAY_TYPE,
  3649. Uint32Array: ARRAY_TYPE,
  3650. Uint8Array: ARRAY_TYPE,
  3651. Uint8ClampedArray: ARRAY_TYPE,
  3652. // Technically, this is a global, but it needs special handling
  3653. // undefined: ?,
  3654. unescape: PF,
  3655. URIError: PC,
  3656. valueOf: O,
  3657. WeakMap: PC_WITH_ARRAY,
  3658. WeakRef: C,
  3659. WeakSet: PC_WITH_ARRAY,
  3660. // Additional globals shared by Node and Browser that are not strictly part of the language
  3661. clearInterval: C,
  3662. clearTimeout: C,
  3663. console: {
  3664. __proto__: null,
  3665. [ValueProperties]: IMPURE,
  3666. assert: C,
  3667. clear: C,
  3668. count: C,
  3669. countReset: C,
  3670. debug: C,
  3671. dir: C,
  3672. dirxml: C,
  3673. error: C,
  3674. exception: C,
  3675. group: C,
  3676. groupCollapsed: C,
  3677. groupEnd: C,
  3678. info: C,
  3679. log: C,
  3680. table: C,
  3681. time: C,
  3682. timeEnd: C,
  3683. timeLog: C,
  3684. trace: C,
  3685. warn: C
  3686. },
  3687. Intl: {
  3688. __proto__: null,
  3689. [ValueProperties]: IMPURE,
  3690. Collator: INTL_MEMBER,
  3691. DateTimeFormat: INTL_MEMBER,
  3692. DisplayNames: INTL_MEMBER,
  3693. ListFormat: INTL_MEMBER,
  3694. Locale: INTL_MEMBER,
  3695. NumberFormat: INTL_MEMBER,
  3696. PluralRules: INTL_MEMBER,
  3697. RelativeTimeFormat: INTL_MEMBER,
  3698. Segmenter: INTL_MEMBER
  3699. },
  3700. setInterval: C,
  3701. setTimeout: C,
  3702. TextDecoder: C,
  3703. TextEncoder: C,
  3704. URL: {
  3705. __proto__: null,
  3706. [ValueProperties]: IMPURE,
  3707. prototype: O,
  3708. canParse: PF
  3709. },
  3710. URLSearchParams: C,
  3711. // Browser specific globals
  3712. AbortController: C,
  3713. AbortSignal: C,
  3714. addEventListener: O,
  3715. alert: O,
  3716. AnalyserNode: C,
  3717. Animation: C,
  3718. AnimationEvent: C,
  3719. applicationCache: O,
  3720. ApplicationCache: C,
  3721. ApplicationCacheErrorEvent: C,
  3722. atob: O,
  3723. Attr: C,
  3724. Audio: C,
  3725. AudioBuffer: C,
  3726. AudioBufferSourceNode: C,
  3727. AudioContext: C,
  3728. AudioDestinationNode: C,
  3729. AudioListener: C,
  3730. AudioNode: C,
  3731. AudioParam: C,
  3732. AudioProcessingEvent: C,
  3733. AudioScheduledSourceNode: C,
  3734. AudioWorkletNode: C,
  3735. BarProp: C,
  3736. BaseAudioContext: C,
  3737. BatteryManager: C,
  3738. BeforeUnloadEvent: C,
  3739. BiquadFilterNode: C,
  3740. Blob: C,
  3741. BlobEvent: C,
  3742. blur: O,
  3743. BroadcastChannel: C,
  3744. btoa: O,
  3745. ByteLengthQueuingStrategy: C,
  3746. Cache: C,
  3747. caches: O,
  3748. CacheStorage: C,
  3749. cancelAnimationFrame: O,
  3750. cancelIdleCallback: O,
  3751. CanvasCaptureMediaStreamTrack: C,
  3752. CanvasGradient: C,
  3753. CanvasPattern: C,
  3754. CanvasRenderingContext2D: C,
  3755. ChannelMergerNode: C,
  3756. ChannelSplitterNode: C,
  3757. CharacterData: C,
  3758. clientInformation: O,
  3759. ClipboardEvent: C,
  3760. close: O,
  3761. closed: O,
  3762. CloseEvent: C,
  3763. Comment: C,
  3764. CompositionEvent: C,
  3765. confirm: O,
  3766. ConstantSourceNode: C,
  3767. ConvolverNode: C,
  3768. CountQueuingStrategy: C,
  3769. createImageBitmap: O,
  3770. Credential: C,
  3771. CredentialsContainer: C,
  3772. crypto: O,
  3773. Crypto: C,
  3774. CryptoKey: C,
  3775. CSS: C,
  3776. CSSConditionRule: C,
  3777. CSSFontFaceRule: C,
  3778. CSSGroupingRule: C,
  3779. CSSImportRule: C,
  3780. CSSKeyframeRule: C,
  3781. CSSKeyframesRule: C,
  3782. CSSMediaRule: C,
  3783. CSSNamespaceRule: C,
  3784. CSSPageRule: C,
  3785. CSSRule: C,
  3786. CSSRuleList: C,
  3787. CSSStyleDeclaration: C,
  3788. CSSStyleRule: C,
  3789. CSSStyleSheet: C,
  3790. CSSSupportsRule: C,
  3791. CustomElementRegistry: C,
  3792. customElements: O,
  3793. CustomEvent: {
  3794. __proto__: null,
  3795. [ValueProperties]: {
  3796. deoptimizeArgumentsOnCall({ args }) {
  3797. args[2]?.deoptimizePath(['detail']);
  3798. },
  3799. getLiteralValue: getTruthyLiteralValue,
  3800. hasEffectsWhenCalled: returnFalse
  3801. },
  3802. prototype: O
  3803. },
  3804. DataTransfer: C,
  3805. DataTransferItem: C,
  3806. DataTransferItemList: C,
  3807. defaultstatus: O,
  3808. defaultStatus: O,
  3809. DelayNode: C,
  3810. DeviceMotionEvent: C,
  3811. DeviceOrientationEvent: C,
  3812. devicePixelRatio: O,
  3813. dispatchEvent: O,
  3814. document: O,
  3815. Document: C,
  3816. DocumentFragment: C,
  3817. DocumentType: C,
  3818. DOMError: C,
  3819. DOMException: C,
  3820. DOMImplementation: C,
  3821. DOMMatrix: C,
  3822. DOMMatrixReadOnly: C,
  3823. DOMParser: C,
  3824. DOMPoint: C,
  3825. DOMPointReadOnly: C,
  3826. DOMQuad: C,
  3827. DOMRect: C,
  3828. DOMRectReadOnly: C,
  3829. DOMStringList: C,
  3830. DOMStringMap: C,
  3831. DOMTokenList: C,
  3832. DragEvent: C,
  3833. DynamicsCompressorNode: C,
  3834. Element: C,
  3835. ErrorEvent: C,
  3836. Event: C,
  3837. EventSource: C,
  3838. EventTarget: C,
  3839. external: O,
  3840. fetch: O,
  3841. File: C,
  3842. FileList: C,
  3843. FileReader: C,
  3844. find: O,
  3845. focus: O,
  3846. FocusEvent: C,
  3847. FontFace: C,
  3848. FontFaceSetLoadEvent: C,
  3849. FormData: C,
  3850. frames: O,
  3851. GainNode: C,
  3852. Gamepad: C,
  3853. GamepadButton: C,
  3854. GamepadEvent: C,
  3855. getComputedStyle: O,
  3856. getSelection: O,
  3857. HashChangeEvent: C,
  3858. Headers: C,
  3859. history: O,
  3860. History: C,
  3861. HTMLAllCollection: C,
  3862. HTMLAnchorElement: C,
  3863. HTMLAreaElement: C,
  3864. HTMLAudioElement: C,
  3865. HTMLBaseElement: C,
  3866. HTMLBodyElement: C,
  3867. HTMLBRElement: C,
  3868. HTMLButtonElement: C,
  3869. HTMLCanvasElement: C,
  3870. HTMLCollection: C,
  3871. HTMLContentElement: C,
  3872. HTMLDataElement: C,
  3873. HTMLDataListElement: C,
  3874. HTMLDetailsElement: C,
  3875. HTMLDialogElement: C,
  3876. HTMLDirectoryElement: C,
  3877. HTMLDivElement: C,
  3878. HTMLDListElement: C,
  3879. HTMLDocument: C,
  3880. HTMLElement: C,
  3881. HTMLEmbedElement: C,
  3882. HTMLFieldSetElement: C,
  3883. HTMLFontElement: C,
  3884. HTMLFormControlsCollection: C,
  3885. HTMLFormElement: C,
  3886. HTMLFrameElement: C,
  3887. HTMLFrameSetElement: C,
  3888. HTMLHeadElement: C,
  3889. HTMLHeadingElement: C,
  3890. HTMLHRElement: C,
  3891. HTMLHtmlElement: C,
  3892. HTMLIFrameElement: C,
  3893. HTMLImageElement: C,
  3894. HTMLInputElement: C,
  3895. HTMLLabelElement: C,
  3896. HTMLLegendElement: C,
  3897. HTMLLIElement: C,
  3898. HTMLLinkElement: C,
  3899. HTMLMapElement: C,
  3900. HTMLMarqueeElement: C,
  3901. HTMLMediaElement: C,
  3902. HTMLMenuElement: C,
  3903. HTMLMetaElement: C,
  3904. HTMLMeterElement: C,
  3905. HTMLModElement: C,
  3906. HTMLObjectElement: C,
  3907. HTMLOListElement: C,
  3908. HTMLOptGroupElement: C,
  3909. HTMLOptionElement: C,
  3910. HTMLOptionsCollection: C,
  3911. HTMLOutputElement: C,
  3912. HTMLParagraphElement: C,
  3913. HTMLParamElement: C,
  3914. HTMLPictureElement: C,
  3915. HTMLPreElement: C,
  3916. HTMLProgressElement: C,
  3917. HTMLQuoteElement: C,
  3918. HTMLScriptElement: C,
  3919. HTMLSelectElement: C,
  3920. HTMLShadowElement: C,
  3921. HTMLSlotElement: C,
  3922. HTMLSourceElement: C,
  3923. HTMLSpanElement: C,
  3924. HTMLStyleElement: C,
  3925. HTMLTableCaptionElement: C,
  3926. HTMLTableCellElement: C,
  3927. HTMLTableColElement: C,
  3928. HTMLTableElement: C,
  3929. HTMLTableRowElement: C,
  3930. HTMLTableSectionElement: C,
  3931. HTMLTemplateElement: C,
  3932. HTMLTextAreaElement: C,
  3933. HTMLTimeElement: C,
  3934. HTMLTitleElement: C,
  3935. HTMLTrackElement: C,
  3936. HTMLUListElement: C,
  3937. HTMLUnknownElement: C,
  3938. HTMLVideoElement: C,
  3939. IDBCursor: C,
  3940. IDBCursorWithValue: C,
  3941. IDBDatabase: C,
  3942. IDBFactory: C,
  3943. IDBIndex: C,
  3944. IDBKeyRange: C,
  3945. IDBObjectStore: C,
  3946. IDBOpenDBRequest: C,
  3947. IDBRequest: C,
  3948. IDBTransaction: C,
  3949. IDBVersionChangeEvent: C,
  3950. IdleDeadline: C,
  3951. IIRFilterNode: C,
  3952. Image: C,
  3953. ImageBitmap: C,
  3954. ImageBitmapRenderingContext: C,
  3955. ImageCapture: C,
  3956. ImageData: C,
  3957. indexedDB: O,
  3958. innerHeight: O,
  3959. innerWidth: O,
  3960. InputEvent: C,
  3961. IntersectionObserver: C,
  3962. IntersectionObserverEntry: C,
  3963. isSecureContext: O,
  3964. KeyboardEvent: C,
  3965. KeyframeEffect: C,
  3966. length: O,
  3967. localStorage: O,
  3968. location: O,
  3969. Location: C,
  3970. locationbar: O,
  3971. matchMedia: O,
  3972. MediaDeviceInfo: C,
  3973. MediaDevices: C,
  3974. MediaElementAudioSourceNode: C,
  3975. MediaEncryptedEvent: C,
  3976. MediaError: C,
  3977. MediaKeyMessageEvent: C,
  3978. MediaKeySession: C,
  3979. MediaKeyStatusMap: C,
  3980. MediaKeySystemAccess: C,
  3981. MediaList: C,
  3982. MediaQueryList: C,
  3983. MediaQueryListEvent: C,
  3984. MediaRecorder: C,
  3985. MediaSettingsRange: C,
  3986. MediaSource: C,
  3987. MediaStream: C,
  3988. MediaStreamAudioDestinationNode: C,
  3989. MediaStreamAudioSourceNode: C,
  3990. MediaStreamEvent: C,
  3991. MediaStreamTrack: C,
  3992. MediaStreamTrackEvent: C,
  3993. menubar: O,
  3994. MessageChannel: C,
  3995. MessageEvent: C,
  3996. MessagePort: C,
  3997. MIDIAccess: C,
  3998. MIDIConnectionEvent: C,
  3999. MIDIInput: C,
  4000. MIDIInputMap: C,
  4001. MIDIMessageEvent: C,
  4002. MIDIOutput: C,
  4003. MIDIOutputMap: C,
  4004. MIDIPort: C,
  4005. MimeType: C,
  4006. MimeTypeArray: C,
  4007. MouseEvent: C,
  4008. moveBy: O,
  4009. moveTo: O,
  4010. MutationEvent: C,
  4011. MutationObserver: C,
  4012. MutationRecord: C,
  4013. name: O,
  4014. NamedNodeMap: C,
  4015. NavigationPreloadManager: C,
  4016. navigator: O,
  4017. Navigator: C,
  4018. NetworkInformation: C,
  4019. Node: C,
  4020. NodeFilter: O,
  4021. NodeIterator: C,
  4022. NodeList: C,
  4023. Notification: C,
  4024. OfflineAudioCompletionEvent: C,
  4025. OfflineAudioContext: C,
  4026. offscreenBuffering: O,
  4027. OffscreenCanvas: C,
  4028. open: O,
  4029. openDatabase: O,
  4030. Option: C,
  4031. origin: O,
  4032. OscillatorNode: C,
  4033. outerHeight: O,
  4034. outerWidth: O,
  4035. PageTransitionEvent: C,
  4036. pageXOffset: O,
  4037. pageYOffset: O,
  4038. PannerNode: C,
  4039. parent: O,
  4040. Path2D: C,
  4041. PaymentAddress: C,
  4042. PaymentRequest: C,
  4043. PaymentRequestUpdateEvent: C,
  4044. PaymentResponse: C,
  4045. performance: O,
  4046. Performance: C,
  4047. PerformanceEntry: C,
  4048. PerformanceLongTaskTiming: C,
  4049. PerformanceMark: C,
  4050. PerformanceMeasure: C,
  4051. PerformanceNavigation: C,
  4052. PerformanceNavigationTiming: C,
  4053. PerformanceObserver: C,
  4054. PerformanceObserverEntryList: C,
  4055. PerformancePaintTiming: C,
  4056. PerformanceResourceTiming: C,
  4057. PerformanceTiming: C,
  4058. PeriodicWave: C,
  4059. Permissions: C,
  4060. PermissionStatus: C,
  4061. personalbar: O,
  4062. PhotoCapabilities: C,
  4063. Plugin: C,
  4064. PluginArray: C,
  4065. PointerEvent: C,
  4066. PopStateEvent: C,
  4067. postMessage: O,
  4068. Presentation: C,
  4069. PresentationAvailability: C,
  4070. PresentationConnection: C,
  4071. PresentationConnectionAvailableEvent: C,
  4072. PresentationConnectionCloseEvent: C,
  4073. PresentationConnectionList: C,
  4074. PresentationReceiver: C,
  4075. PresentationRequest: C,
  4076. print: O,
  4077. ProcessingInstruction: C,
  4078. ProgressEvent: C,
  4079. PromiseRejectionEvent: C,
  4080. prompt: O,
  4081. PushManager: C,
  4082. PushSubscription: C,
  4083. PushSubscriptionOptions: C,
  4084. queueMicrotask: O,
  4085. RadioNodeList: C,
  4086. Range: C,
  4087. ReadableStream: C,
  4088. RemotePlayback: C,
  4089. removeEventListener: O,
  4090. Request: C,
  4091. requestAnimationFrame: O,
  4092. requestIdleCallback: O,
  4093. resizeBy: O,
  4094. ResizeObserver: C,
  4095. ResizeObserverEntry: C,
  4096. resizeTo: O,
  4097. Response: C,
  4098. RTCCertificate: C,
  4099. RTCDataChannel: C,
  4100. RTCDataChannelEvent: C,
  4101. RTCDtlsTransport: C,
  4102. RTCIceCandidate: C,
  4103. RTCIceTransport: C,
  4104. RTCPeerConnection: C,
  4105. RTCPeerConnectionIceEvent: C,
  4106. RTCRtpReceiver: C,
  4107. RTCRtpSender: C,
  4108. RTCSctpTransport: C,
  4109. RTCSessionDescription: C,
  4110. RTCStatsReport: C,
  4111. RTCTrackEvent: C,
  4112. screen: O,
  4113. Screen: C,
  4114. screenLeft: O,
  4115. ScreenOrientation: C,
  4116. screenTop: O,
  4117. screenX: O,
  4118. screenY: O,
  4119. ScriptProcessorNode: C,
  4120. scroll: O,
  4121. scrollbars: O,
  4122. scrollBy: O,
  4123. scrollTo: O,
  4124. scrollX: O,
  4125. scrollY: O,
  4126. SecurityPolicyViolationEvent: C,
  4127. Selection: C,
  4128. ServiceWorker: C,
  4129. ServiceWorkerContainer: C,
  4130. ServiceWorkerRegistration: C,
  4131. sessionStorage: O,
  4132. ShadowRoot: C,
  4133. SharedWorker: C,
  4134. SourceBuffer: C,
  4135. SourceBufferList: C,
  4136. speechSynthesis: O,
  4137. SpeechSynthesisEvent: C,
  4138. SpeechSynthesisUtterance: C,
  4139. StaticRange: C,
  4140. status: O,
  4141. statusbar: O,
  4142. StereoPannerNode: C,
  4143. stop: O,
  4144. Storage: C,
  4145. StorageEvent: C,
  4146. StorageManager: C,
  4147. styleMedia: O,
  4148. StyleSheet: C,
  4149. StyleSheetList: C,
  4150. SubtleCrypto: C,
  4151. SVGAElement: C,
  4152. SVGAngle: C,
  4153. SVGAnimatedAngle: C,
  4154. SVGAnimatedBoolean: C,
  4155. SVGAnimatedEnumeration: C,
  4156. SVGAnimatedInteger: C,
  4157. SVGAnimatedLength: C,
  4158. SVGAnimatedLengthList: C,
  4159. SVGAnimatedNumber: C,
  4160. SVGAnimatedNumberList: C,
  4161. SVGAnimatedPreserveAspectRatio: C,
  4162. SVGAnimatedRect: C,
  4163. SVGAnimatedString: C,
  4164. SVGAnimatedTransformList: C,
  4165. SVGAnimateElement: C,
  4166. SVGAnimateMotionElement: C,
  4167. SVGAnimateTransformElement: C,
  4168. SVGAnimationElement: C,
  4169. SVGCircleElement: C,
  4170. SVGClipPathElement: C,
  4171. SVGComponentTransferFunctionElement: C,
  4172. SVGDefsElement: C,
  4173. SVGDescElement: C,
  4174. SVGDiscardElement: C,
  4175. SVGElement: C,
  4176. SVGEllipseElement: C,
  4177. SVGFEBlendElement: C,
  4178. SVGFEColorMatrixElement: C,
  4179. SVGFEComponentTransferElement: C,
  4180. SVGFECompositeElement: C,
  4181. SVGFEConvolveMatrixElement: C,
  4182. SVGFEDiffuseLightingElement: C,
  4183. SVGFEDisplacementMapElement: C,
  4184. SVGFEDistantLightElement: C,
  4185. SVGFEDropShadowElement: C,
  4186. SVGFEFloodElement: C,
  4187. SVGFEFuncAElement: C,
  4188. SVGFEFuncBElement: C,
  4189. SVGFEFuncGElement: C,
  4190. SVGFEFuncRElement: C,
  4191. SVGFEGaussianBlurElement: C,
  4192. SVGFEImageElement: C,
  4193. SVGFEMergeElement: C,
  4194. SVGFEMergeNodeElement: C,
  4195. SVGFEMorphologyElement: C,
  4196. SVGFEOffsetElement: C,
  4197. SVGFEPointLightElement: C,
  4198. SVGFESpecularLightingElement: C,
  4199. SVGFESpotLightElement: C,
  4200. SVGFETileElement: C,
  4201. SVGFETurbulenceElement: C,
  4202. SVGFilterElement: C,
  4203. SVGForeignObjectElement: C,
  4204. SVGGElement: C,
  4205. SVGGeometryElement: C,
  4206. SVGGradientElement: C,
  4207. SVGGraphicsElement: C,
  4208. SVGImageElement: C,
  4209. SVGLength: C,
  4210. SVGLengthList: C,
  4211. SVGLinearGradientElement: C,
  4212. SVGLineElement: C,
  4213. SVGMarkerElement: C,
  4214. SVGMaskElement: C,
  4215. SVGMatrix: C,
  4216. SVGMetadataElement: C,
  4217. SVGMPathElement: C,
  4218. SVGNumber: C,
  4219. SVGNumberList: C,
  4220. SVGPathElement: C,
  4221. SVGPatternElement: C,
  4222. SVGPoint: C,
  4223. SVGPointList: C,
  4224. SVGPolygonElement: C,
  4225. SVGPolylineElement: C,
  4226. SVGPreserveAspectRatio: C,
  4227. SVGRadialGradientElement: C,
  4228. SVGRect: C,
  4229. SVGRectElement: C,
  4230. SVGScriptElement: C,
  4231. SVGSetElement: C,
  4232. SVGStopElement: C,
  4233. SVGStringList: C,
  4234. SVGStyleElement: C,
  4235. SVGSVGElement: C,
  4236. SVGSwitchElement: C,
  4237. SVGSymbolElement: C,
  4238. SVGTextContentElement: C,
  4239. SVGTextElement: C,
  4240. SVGTextPathElement: C,
  4241. SVGTextPositioningElement: C,
  4242. SVGTitleElement: C,
  4243. SVGTransform: C,
  4244. SVGTransformList: C,
  4245. SVGTSpanElement: C,
  4246. SVGUnitTypes: C,
  4247. SVGUseElement: C,
  4248. SVGViewElement: C,
  4249. TaskAttributionTiming: C,
  4250. Text: C,
  4251. TextEvent: C,
  4252. TextMetrics: C,
  4253. TextTrack: C,
  4254. TextTrackCue: C,
  4255. TextTrackCueList: C,
  4256. TextTrackList: C,
  4257. TimeRanges: C,
  4258. toolbar: O,
  4259. top: O,
  4260. Touch: C,
  4261. TouchEvent: C,
  4262. TouchList: C,
  4263. TrackEvent: C,
  4264. TransitionEvent: C,
  4265. TreeWalker: C,
  4266. UIEvent: C,
  4267. ValidityState: C,
  4268. visualViewport: O,
  4269. VisualViewport: C,
  4270. VTTCue: C,
  4271. WaveShaperNode: C,
  4272. WebAssembly: O,
  4273. WebGL2RenderingContext: C,
  4274. WebGLActiveInfo: C,
  4275. WebGLBuffer: C,
  4276. WebGLContextEvent: C,
  4277. WebGLFramebuffer: C,
  4278. WebGLProgram: C,
  4279. WebGLQuery: C,
  4280. WebGLRenderbuffer: C,
  4281. WebGLRenderingContext: C,
  4282. WebGLSampler: C,
  4283. WebGLShader: C,
  4284. WebGLShaderPrecisionFormat: C,
  4285. WebGLSync: C,
  4286. WebGLTexture: C,
  4287. WebGLTransformFeedback: C,
  4288. WebGLUniformLocation: C,
  4289. WebGLVertexArrayObject: C,
  4290. WebSocket: C,
  4291. WheelEvent: C,
  4292. Window: C,
  4293. Worker: C,
  4294. WritableStream: C,
  4295. XMLDocument: C,
  4296. XMLHttpRequest: C,
  4297. XMLHttpRequestEventTarget: C,
  4298. XMLHttpRequestUpload: C,
  4299. XMLSerializer: C,
  4300. XPathEvaluator: C,
  4301. XPathExpression: C,
  4302. XPathResult: C,
  4303. XSLTProcessor: C
  4304. };
  4305. for (const global of ['window', 'global', 'self', 'globalThis']) {
  4306. knownGlobals[global] = knownGlobals;
  4307. }
  4308. function getGlobalAtPath(path) {
  4309. let currentGlobal = knownGlobals;
  4310. for (const pathSegment of path) {
  4311. if (typeof pathSegment !== 'string') {
  4312. return null;
  4313. }
  4314. currentGlobal = currentGlobal[pathSegment];
  4315. if (!currentGlobal) {
  4316. return null;
  4317. }
  4318. }
  4319. return currentGlobal[ValueProperties];
  4320. }
  4321. class GlobalVariable extends Variable {
  4322. constructor(name) {
  4323. super(name);
  4324. // Ensure we use live-bindings for globals as we do not know if they have
  4325. // been reassigned
  4326. this.markReassigned();
  4327. }
  4328. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  4329. switch (interaction.type) {
  4330. // While there is no point in testing these cases as at the moment, they
  4331. // are also covered via other means, we keep them for completeness
  4332. case INTERACTION_ACCESSED:
  4333. case INTERACTION_ASSIGNED: {
  4334. if (!getGlobalAtPath([this.name, ...path].slice(0, -1))) {
  4335. super.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  4336. }
  4337. return;
  4338. }
  4339. case INTERACTION_CALLED: {
  4340. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  4341. if (globalAtPath) {
  4342. globalAtPath.deoptimizeArgumentsOnCall(interaction);
  4343. }
  4344. else {
  4345. super.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  4346. }
  4347. return;
  4348. }
  4349. }
  4350. }
  4351. getLiteralValueAtPath(path, _recursionTracker, _origin) {
  4352. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  4353. return globalAtPath ? globalAtPath.getLiteralValue() : UnknownValue;
  4354. }
  4355. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4356. switch (interaction.type) {
  4357. case INTERACTION_ACCESSED: {
  4358. if (path.length === 0) {
  4359. // Technically, "undefined" is a global variable of sorts
  4360. return this.name !== 'undefined' && !getGlobalAtPath([this.name]);
  4361. }
  4362. return !getGlobalAtPath([this.name, ...path].slice(0, -1));
  4363. }
  4364. case INTERACTION_ASSIGNED: {
  4365. return true;
  4366. }
  4367. case INTERACTION_CALLED: {
  4368. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  4369. return !globalAtPath || globalAtPath.hasEffectsWhenCalled(interaction, context);
  4370. }
  4371. }
  4372. }
  4373. }
  4374. class LocalVariable extends Variable {
  4375. constructor(name, declarator, init, context, kind) {
  4376. super(name);
  4377. this.init = init;
  4378. this.calledFromTryStatement = false;
  4379. this.additionalInitializers = null;
  4380. this.expressionsToBeDeoptimized = [];
  4381. this.declarations = declarator ? [declarator] : [];
  4382. this.deoptimizationTracker = context.deoptimizationTracker;
  4383. this.module = context.module;
  4384. this.kind = kind;
  4385. }
  4386. addDeclaration(identifier, init) {
  4387. this.declarations.push(identifier);
  4388. this.markInitializersForDeoptimization().push(init);
  4389. }
  4390. consolidateInitializers() {
  4391. if (this.additionalInitializers) {
  4392. for (const initializer of this.additionalInitializers) {
  4393. initializer.deoptimizePath(UNKNOWN_PATH);
  4394. }
  4395. this.additionalInitializers = null;
  4396. }
  4397. }
  4398. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  4399. if (this.isReassigned) {
  4400. deoptimizeInteraction(interaction);
  4401. return;
  4402. }
  4403. recursionTracker.withTrackedEntityAtPath(path, this.init, () => this.init.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker), undefined);
  4404. }
  4405. deoptimizePath(path) {
  4406. if (this.isReassigned ||
  4407. this.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  4408. return;
  4409. }
  4410. if (path.length === 0) {
  4411. this.markReassigned();
  4412. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
  4413. this.expressionsToBeDeoptimized = EMPTY_ARRAY;
  4414. for (const expression of expressionsToBeDeoptimized) {
  4415. expression.deoptimizeCache();
  4416. }
  4417. this.init.deoptimizePath(UNKNOWN_PATH);
  4418. }
  4419. else {
  4420. this.init.deoptimizePath(path);
  4421. }
  4422. }
  4423. getLiteralValueAtPath(path, recursionTracker, origin) {
  4424. if (this.isReassigned) {
  4425. return UnknownValue;
  4426. }
  4427. return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  4428. this.expressionsToBeDeoptimized.push(origin);
  4429. return this.init.getLiteralValueAtPath(path, recursionTracker, origin);
  4430. }, UnknownValue);
  4431. }
  4432. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  4433. if (this.isReassigned) {
  4434. return UNKNOWN_RETURN_EXPRESSION;
  4435. }
  4436. return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  4437. this.expressionsToBeDeoptimized.push(origin);
  4438. return this.init.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  4439. }, UNKNOWN_RETURN_EXPRESSION);
  4440. }
  4441. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4442. switch (interaction.type) {
  4443. case INTERACTION_ACCESSED: {
  4444. if (this.isReassigned)
  4445. return true;
  4446. return (!context.accessed.trackEntityAtPathAndGetIfTracked(path, this) &&
  4447. this.init.hasEffectsOnInteractionAtPath(path, interaction, context));
  4448. }
  4449. case INTERACTION_ASSIGNED: {
  4450. if (this.included)
  4451. return true;
  4452. if (path.length === 0)
  4453. return false;
  4454. if (this.isReassigned)
  4455. return true;
  4456. return (!context.assigned.trackEntityAtPathAndGetIfTracked(path, this) &&
  4457. this.init.hasEffectsOnInteractionAtPath(path, interaction, context));
  4458. }
  4459. case INTERACTION_CALLED: {
  4460. if (this.isReassigned)
  4461. return true;
  4462. return (!(interaction.withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, interaction.args, this) &&
  4463. this.init.hasEffectsOnInteractionAtPath(path, interaction, context));
  4464. }
  4465. }
  4466. }
  4467. include() {
  4468. if (!this.included) {
  4469. super.include();
  4470. for (const declaration of this.declarations) {
  4471. // If node is a default export, it can save a tree-shaking run to include the full declaration now
  4472. if (!declaration.included)
  4473. declaration.include(createInclusionContext(), false);
  4474. let node = declaration.parent;
  4475. while (!node.included) {
  4476. // We do not want to properly include parents in case they are part of a dead branch
  4477. // in which case .include() might pull in more dead code
  4478. node.included = true;
  4479. if (node.type === Program$1)
  4480. break;
  4481. node = node.parent;
  4482. }
  4483. }
  4484. }
  4485. }
  4486. includeCallArguments(context, parameters) {
  4487. if (this.isReassigned || context.includedCallArguments.has(this.init)) {
  4488. for (const argument of parameters) {
  4489. argument.include(context, false);
  4490. }
  4491. }
  4492. else {
  4493. context.includedCallArguments.add(this.init);
  4494. this.init.includeCallArguments(context, parameters);
  4495. context.includedCallArguments.delete(this.init);
  4496. }
  4497. }
  4498. markCalledFromTryStatement() {
  4499. this.calledFromTryStatement = true;
  4500. }
  4501. markInitializersForDeoptimization() {
  4502. if (this.additionalInitializers === null) {
  4503. this.additionalInitializers = [this.init];
  4504. this.init = UNKNOWN_EXPRESSION;
  4505. this.markReassigned();
  4506. }
  4507. return this.additionalInitializers;
  4508. }
  4509. }
  4510. const tdzVariableKinds = new Set(['class', 'const', 'let', 'var', 'using', 'await using']);
  4511. class IdentifierBase extends NodeBase {
  4512. constructor() {
  4513. super(...arguments);
  4514. this.variable = null;
  4515. this.isVariableReference = false;
  4516. }
  4517. get isTDZAccess() {
  4518. if (!isFlagSet(this.flags, 4 /* Flag.tdzAccessDefined */)) {
  4519. return null;
  4520. }
  4521. return isFlagSet(this.flags, 8 /* Flag.tdzAccess */);
  4522. }
  4523. set isTDZAccess(value) {
  4524. this.flags = setFlag(this.flags, 4 /* Flag.tdzAccessDefined */, true);
  4525. this.flags = setFlag(this.flags, 8 /* Flag.tdzAccess */, value);
  4526. }
  4527. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  4528. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  4529. }
  4530. deoptimizePath(path) {
  4531. if (path.length === 0 && !this.scope.contains(this.name)) {
  4532. this.disallowImportReassignment();
  4533. }
  4534. // We keep conditional chaining because an unknown Node could have an
  4535. // Identifier as property that might be deoptimized by default
  4536. this.variable?.deoptimizePath(path);
  4537. }
  4538. getLiteralValueAtPath(path, recursionTracker, origin) {
  4539. return this.getVariableRespectingTDZ().getLiteralValueAtPath(path, recursionTracker, origin);
  4540. }
  4541. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  4542. const [expression, isPure] = this.getVariableRespectingTDZ().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  4543. return [expression, isPure || this.isPureFunction(path)];
  4544. }
  4545. hasEffects(context) {
  4546. if (!this.deoptimized)
  4547. this.applyDeoptimizations();
  4548. if (this.isPossibleTDZ() && this.variable.kind !== 'var') {
  4549. return true;
  4550. }
  4551. return (this.scope.context.options.treeshake
  4552. .unknownGlobalSideEffects &&
  4553. this.variable instanceof GlobalVariable &&
  4554. !this.isPureFunction(EMPTY_PATH) &&
  4555. this.variable.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context));
  4556. }
  4557. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4558. switch (interaction.type) {
  4559. case INTERACTION_ACCESSED: {
  4560. return (this.variable !== null &&
  4561. !this.isPureFunction(path) &&
  4562. this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context));
  4563. }
  4564. case INTERACTION_ASSIGNED: {
  4565. return (path.length > 0 ? this.getVariableRespectingTDZ() : this.variable).hasEffectsOnInteractionAtPath(path, interaction, context);
  4566. }
  4567. case INTERACTION_CALLED: {
  4568. return (!this.isPureFunction(path) &&
  4569. this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context));
  4570. }
  4571. }
  4572. }
  4573. include() {
  4574. if (!this.deoptimized)
  4575. this.applyDeoptimizations();
  4576. if (!this.included) {
  4577. this.included = true;
  4578. if (this.variable !== null) {
  4579. this.scope.context.includeVariableInModule(this.variable);
  4580. }
  4581. }
  4582. }
  4583. includeCallArguments(context, parameters) {
  4584. this.variable.includeCallArguments(context, parameters);
  4585. }
  4586. isPossibleTDZ() {
  4587. // return cached value to avoid issues with the next tree-shaking pass
  4588. const cachedTdzAccess = this.isTDZAccess;
  4589. if (cachedTdzAccess !== null)
  4590. return cachedTdzAccess;
  4591. if (!(this.variable instanceof LocalVariable &&
  4592. this.variable.kind &&
  4593. tdzVariableKinds.has(this.variable.kind) &&
  4594. // We ignore modules that did not receive a treeshaking pass yet as that
  4595. // causes many false positives due to circular dependencies or disabled
  4596. // moduleSideEffects.
  4597. this.variable.module.hasTreeShakingPassStarted)) {
  4598. return (this.isTDZAccess = false);
  4599. }
  4600. let decl_id;
  4601. if (this.variable.declarations &&
  4602. this.variable.declarations.length === 1 &&
  4603. (decl_id = this.variable.declarations[0]) &&
  4604. this.start < decl_id.start &&
  4605. closestParentFunctionOrProgram(this) === closestParentFunctionOrProgram(decl_id)) {
  4606. // a variable accessed before its declaration
  4607. // in the same function or at top level of module
  4608. return (this.isTDZAccess = true);
  4609. }
  4610. if (!this.variable.initReached) {
  4611. // Either a const/let TDZ violation or
  4612. // var use before declaration was encountered.
  4613. return (this.isTDZAccess = true);
  4614. }
  4615. return (this.isTDZAccess = false);
  4616. }
  4617. applyDeoptimizations() {
  4618. this.deoptimized = true;
  4619. if (this.variable instanceof LocalVariable) {
  4620. // When accessing a variable from a module without side effects, this
  4621. // means we use an export of that module and therefore need to potentially
  4622. // include it in the bundle.
  4623. if (!this.variable.module.isExecuted) {
  4624. markModuleAndImpureDependenciesAsExecuted(this.variable.module);
  4625. }
  4626. this.variable.consolidateInitializers();
  4627. this.scope.context.requestTreeshakingPass();
  4628. }
  4629. if (this.isVariableReference) {
  4630. this.variable.addUsedPlace(this);
  4631. this.scope.context.requestTreeshakingPass();
  4632. }
  4633. }
  4634. disallowImportReassignment() {
  4635. return this.scope.context.error(logIllegalImportReassignment(this.name, this.scope.context.module.id), this.start);
  4636. }
  4637. getVariableRespectingTDZ() {
  4638. if (this.isPossibleTDZ()) {
  4639. return UNKNOWN_EXPRESSION;
  4640. }
  4641. return this.variable;
  4642. }
  4643. isPureFunction(path) {
  4644. let currentPureFunction = this.scope.context.manualPureFunctions[this.name];
  4645. for (const segment of path) {
  4646. if (currentPureFunction) {
  4647. if (currentPureFunction[PureFunctionKey]) {
  4648. return true;
  4649. }
  4650. currentPureFunction = currentPureFunction[segment];
  4651. }
  4652. else {
  4653. return false;
  4654. }
  4655. }
  4656. return currentPureFunction?.[PureFunctionKey];
  4657. }
  4658. }
  4659. function closestParentFunctionOrProgram(node) {
  4660. while (node && !/^Program|Function/.test(node.type)) {
  4661. node = node.parent;
  4662. }
  4663. // one of: ArrowFunctionExpression, FunctionDeclaration, FunctionExpression or Program
  4664. return node;
  4665. }
  4666. class Identifier extends IdentifierBase {
  4667. constructor() {
  4668. super(...arguments);
  4669. this.variable = null;
  4670. }
  4671. addExportedVariables(variables, exportNamesByVariable) {
  4672. if (exportNamesByVariable.has(this.variable)) {
  4673. variables.push(this.variable);
  4674. }
  4675. }
  4676. bind() {
  4677. if (!this.variable && is_reference(this, this.parent)) {
  4678. this.variable = this.scope.findVariable(this.name);
  4679. this.variable.addReference(this);
  4680. this.isVariableReference = true;
  4681. }
  4682. }
  4683. declare(kind, init) {
  4684. let variable;
  4685. const { treeshake } = this.scope.context.options;
  4686. switch (kind) {
  4687. case 'var': {
  4688. variable = this.scope.addDeclaration(this, this.scope.context, init, kind);
  4689. if (treeshake && treeshake.correctVarValueBeforeDeclaration) {
  4690. // Necessary to make sure the init is deoptimized. We cannot call deoptimizePath here.
  4691. variable.markInitializersForDeoptimization();
  4692. }
  4693. break;
  4694. }
  4695. case 'function': {
  4696. // in strict mode, functions are only hoisted within a scope but not across block scopes
  4697. variable = this.scope.addDeclaration(this, this.scope.context, init, kind);
  4698. break;
  4699. }
  4700. case 'let':
  4701. case 'const':
  4702. case 'using':
  4703. case 'await using':
  4704. case 'class': {
  4705. variable = this.scope.addDeclaration(this, this.scope.context, init, kind);
  4706. break;
  4707. }
  4708. case 'parameter': {
  4709. variable = this.scope.addParameterDeclaration(this);
  4710. break;
  4711. }
  4712. /* istanbul ignore next */
  4713. default: {
  4714. /* istanbul ignore next */
  4715. throw new Error(`Internal Error: Unexpected identifier kind ${kind}.`);
  4716. }
  4717. }
  4718. return [(this.variable = variable)];
  4719. }
  4720. markDeclarationReached() {
  4721. this.variable.initReached = true;
  4722. }
  4723. render(code, { snippets: { getPropertyAccess }, useOriginalName }, { renderedParentType, isCalleeOfRenderedParent, isShorthandProperty } = BLANK) {
  4724. if (this.variable) {
  4725. const name = this.variable.getName(getPropertyAccess, useOriginalName);
  4726. if (name !== this.name) {
  4727. code.overwrite(this.start, this.end, name, {
  4728. contentOnly: true,
  4729. storeName: true
  4730. });
  4731. if (isShorthandProperty) {
  4732. code.prependRight(this.start, `${this.name}: `);
  4733. }
  4734. }
  4735. // In strict mode, any variable named "eval" must be the actual "eval" function
  4736. if (name === 'eval' &&
  4737. renderedParentType === CallExpression$1 &&
  4738. isCalleeOfRenderedParent) {
  4739. code.appendRight(this.start, '0, ');
  4740. }
  4741. }
  4742. }
  4743. }
  4744. const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
  4745. const base = 64;
  4746. function toBase64(value) {
  4747. let outString = '';
  4748. do {
  4749. const currentDigit = value % base;
  4750. value = (value / base) | 0;
  4751. outString = chars[currentDigit] + outString;
  4752. } while (value !== 0);
  4753. return outString;
  4754. }
  4755. function getSafeName(baseName, usedNames, forbiddenNames) {
  4756. let safeName = baseName;
  4757. let count = 1;
  4758. while (usedNames.has(safeName) || RESERVED_NAMES.has(safeName) || forbiddenNames?.has(safeName)) {
  4759. safeName = `${baseName}$${toBase64(count++)}`;
  4760. }
  4761. usedNames.add(safeName);
  4762. return safeName;
  4763. }
  4764. class Scope {
  4765. constructor() {
  4766. this.children = [];
  4767. this.variables = new Map();
  4768. }
  4769. /*
  4770. Redeclaration rules:
  4771. - var can redeclare var
  4772. - in function scopes, function and var can redeclare function and var
  4773. - var is hoisted across scopes, function remains in the scope it is declared
  4774. - var and function can redeclare function parameters, but parameters cannot redeclare parameters
  4775. - function cannot redeclare catch scope parameters
  4776. - var can redeclare catch scope parameters in a way
  4777. - if the parameter is an identifier and not a pattern
  4778. - then the variable is still declared in the hoisted outer scope, but the initializer is assigned to the parameter
  4779. - const, let, class, and function except in the cases above cannot redeclare anything
  4780. */
  4781. addDeclaration(identifier, context, init, kind) {
  4782. const name = identifier.name;
  4783. const existingVariable = this.hoistedVariables?.get(name) || this.variables.get(name);
  4784. if (existingVariable) {
  4785. const existingKind = existingVariable.kind;
  4786. if (kind === 'var' && existingKind === 'var') {
  4787. existingVariable.addDeclaration(identifier, init);
  4788. return existingVariable;
  4789. }
  4790. context.error(logRedeclarationError(name), identifier.start);
  4791. }
  4792. const newVariable = new LocalVariable(identifier.name, identifier, init, context, kind);
  4793. this.variables.set(name, newVariable);
  4794. return newVariable;
  4795. }
  4796. addHoistedVariable(name, variable) {
  4797. (this.hoistedVariables ||= new Map()).set(name, variable);
  4798. }
  4799. contains(name) {
  4800. return this.variables.has(name);
  4801. }
  4802. findVariable(_name) {
  4803. /* istanbul ignore next */
  4804. throw new Error('Internal Error: findVariable needs to be implemented by a subclass');
  4805. }
  4806. }
  4807. class ChildScope extends Scope {
  4808. constructor(parent, context) {
  4809. super();
  4810. this.parent = parent;
  4811. this.context = context;
  4812. this.accessedOutsideVariables = new Map();
  4813. parent.children.push(this);
  4814. }
  4815. addAccessedDynamicImport(importExpression) {
  4816. (this.accessedDynamicImports || (this.accessedDynamicImports = new Set())).add(importExpression);
  4817. if (this.parent instanceof ChildScope) {
  4818. this.parent.addAccessedDynamicImport(importExpression);
  4819. }
  4820. }
  4821. addAccessedGlobals(globals, accessedGlobalsByScope) {
  4822. const accessedGlobals = accessedGlobalsByScope.get(this) || new Set();
  4823. for (const name of globals) {
  4824. accessedGlobals.add(name);
  4825. }
  4826. accessedGlobalsByScope.set(this, accessedGlobals);
  4827. if (this.parent instanceof ChildScope) {
  4828. this.parent.addAccessedGlobals(globals, accessedGlobalsByScope);
  4829. }
  4830. }
  4831. addNamespaceMemberAccess(name, variable) {
  4832. this.accessedOutsideVariables.set(name, variable);
  4833. this.parent.addNamespaceMemberAccess(name, variable);
  4834. }
  4835. addReturnExpression(expression) {
  4836. if (this.parent instanceof ChildScope) {
  4837. this.parent.addReturnExpression(expression);
  4838. }
  4839. }
  4840. addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope) {
  4841. for (const variable of this.accessedOutsideVariables.values()) {
  4842. if (variable.included) {
  4843. usedNames.add(variable.getBaseVariableName());
  4844. if (format === 'system' && exportNamesByVariable.has(variable)) {
  4845. usedNames.add('exports');
  4846. }
  4847. }
  4848. }
  4849. const accessedGlobals = accessedGlobalsByScope.get(this);
  4850. if (accessedGlobals) {
  4851. for (const name of accessedGlobals) {
  4852. usedNames.add(name);
  4853. }
  4854. }
  4855. }
  4856. contains(name) {
  4857. return this.variables.has(name) || this.parent.contains(name);
  4858. }
  4859. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  4860. const usedNames = new Set();
  4861. this.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
  4862. if (this.accessedDynamicImports) {
  4863. for (const importExpression of this.accessedDynamicImports) {
  4864. if (importExpression.inlineNamespace) {
  4865. usedNames.add(importExpression.inlineNamespace.getBaseVariableName());
  4866. }
  4867. }
  4868. }
  4869. for (const [name, variable] of this.variables) {
  4870. if (variable.included || variable.alwaysRendered) {
  4871. variable.setRenderNames(null, getSafeName(name, usedNames, variable.forbiddenNames));
  4872. }
  4873. }
  4874. for (const scope of this.children) {
  4875. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  4876. }
  4877. }
  4878. findLexicalBoundary() {
  4879. return this.parent.findLexicalBoundary();
  4880. }
  4881. findGlobal(name) {
  4882. const variable = this.parent.findVariable(name);
  4883. this.accessedOutsideVariables.set(name, variable);
  4884. return variable;
  4885. }
  4886. findVariable(name) {
  4887. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  4888. if (knownVariable) {
  4889. return knownVariable;
  4890. }
  4891. const variable = this.parent.findVariable(name);
  4892. this.accessedOutsideVariables.set(name, variable);
  4893. return variable;
  4894. }
  4895. }
  4896. function checkEffectForNodes(nodes, context) {
  4897. for (const node of nodes) {
  4898. if (node.hasEffects(context)) {
  4899. return true;
  4900. }
  4901. }
  4902. return false;
  4903. }
  4904. class MethodBase extends NodeBase {
  4905. constructor() {
  4906. super(...arguments);
  4907. this.accessedValue = null;
  4908. }
  4909. get computed() {
  4910. return isFlagSet(this.flags, 1024 /* Flag.computed */);
  4911. }
  4912. set computed(value) {
  4913. this.flags = setFlag(this.flags, 1024 /* Flag.computed */, value);
  4914. }
  4915. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  4916. if (interaction.type === INTERACTION_ACCESSED && this.kind === 'get' && path.length === 0) {
  4917. return this.value.deoptimizeArgumentsOnInteractionAtPath({
  4918. args: interaction.args,
  4919. type: INTERACTION_CALLED,
  4920. withNew: false
  4921. }, EMPTY_PATH, recursionTracker);
  4922. }
  4923. if (interaction.type === INTERACTION_ASSIGNED && this.kind === 'set' && path.length === 0) {
  4924. return this.value.deoptimizeArgumentsOnInteractionAtPath({
  4925. args: interaction.args,
  4926. type: INTERACTION_CALLED,
  4927. withNew: false
  4928. }, EMPTY_PATH, recursionTracker);
  4929. }
  4930. this.getAccessedValue()[0].deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  4931. }
  4932. // As getter properties directly receive their values from fixed function
  4933. // expressions, there is no known situation where a getter is deoptimized.
  4934. deoptimizeCache() { }
  4935. deoptimizePath(path) {
  4936. this.getAccessedValue()[0].deoptimizePath(path);
  4937. }
  4938. getLiteralValueAtPath(path, recursionTracker, origin) {
  4939. return this.getAccessedValue()[0].getLiteralValueAtPath(path, recursionTracker, origin);
  4940. }
  4941. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  4942. return this.getAccessedValue()[0].getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  4943. }
  4944. hasEffects(context) {
  4945. return this.key.hasEffects(context);
  4946. }
  4947. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4948. if (this.kind === 'get' && interaction.type === INTERACTION_ACCESSED && path.length === 0) {
  4949. return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
  4950. args: interaction.args,
  4951. type: INTERACTION_CALLED,
  4952. withNew: false
  4953. }, context);
  4954. }
  4955. // setters are only called for empty paths
  4956. if (this.kind === 'set' && interaction.type === INTERACTION_ASSIGNED) {
  4957. return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
  4958. args: interaction.args,
  4959. type: INTERACTION_CALLED,
  4960. withNew: false
  4961. }, context);
  4962. }
  4963. return this.getAccessedValue()[0].hasEffectsOnInteractionAtPath(path, interaction, context);
  4964. }
  4965. applyDeoptimizations() { }
  4966. getAccessedValue() {
  4967. if (this.accessedValue === null) {
  4968. if (this.kind === 'get') {
  4969. this.accessedValue = UNKNOWN_RETURN_EXPRESSION;
  4970. return (this.accessedValue = this.value.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, SHARED_RECURSION_TRACKER, this));
  4971. }
  4972. else {
  4973. return (this.accessedValue = [this.value, false]);
  4974. }
  4975. }
  4976. return this.accessedValue;
  4977. }
  4978. }
  4979. class MethodDefinition extends MethodBase {
  4980. hasEffects(context) {
  4981. return super.hasEffects(context) || checkEffectForNodes(this.decorators, context);
  4982. }
  4983. applyDeoptimizations() { }
  4984. }
  4985. class BlockScope extends ChildScope {
  4986. constructor(parent) {
  4987. super(parent, parent.context);
  4988. }
  4989. addDeclaration(identifier, context, init, kind) {
  4990. if (kind === 'var') {
  4991. const name = identifier.name;
  4992. const existingVariable = this.hoistedVariables?.get(name) || this.variables.get(name);
  4993. if (existingVariable) {
  4994. if (existingVariable.kind === 'var' ||
  4995. (kind === 'var' && existingVariable.kind === 'parameter')) {
  4996. existingVariable.addDeclaration(identifier, init);
  4997. return existingVariable;
  4998. }
  4999. return context.error(logRedeclarationError(name), identifier.start);
  5000. }
  5001. const declaredVariable = this.parent.addDeclaration(identifier, context, init, kind);
  5002. // Necessary to make sure the init is deoptimized for conditional declarations.
  5003. // We cannot call deoptimizePath here.
  5004. declaredVariable.markInitializersForDeoptimization();
  5005. // We add the variable to this and all parent scopes to reliably detect conflicts
  5006. this.addHoistedVariable(name, declaredVariable);
  5007. return declaredVariable;
  5008. }
  5009. return super.addDeclaration(identifier, context, init, kind);
  5010. }
  5011. }
  5012. class StaticBlock extends NodeBase {
  5013. createScope(parentScope) {
  5014. this.scope = new BlockScope(parentScope);
  5015. }
  5016. hasEffects(context) {
  5017. for (const node of this.body) {
  5018. if (node.hasEffects(context))
  5019. return true;
  5020. }
  5021. return false;
  5022. }
  5023. include(context, includeChildrenRecursively) {
  5024. this.included = true;
  5025. for (const node of this.body) {
  5026. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  5027. node.include(context, includeChildrenRecursively);
  5028. }
  5029. }
  5030. render(code, options) {
  5031. if (this.body.length > 0) {
  5032. const bodyStartPos = findFirstOccurrenceOutsideComment(code.original.slice(this.start, this.end), '{') + 1;
  5033. renderStatementList(this.body, code, this.start + bodyStartPos, this.end - 1, options);
  5034. }
  5035. else {
  5036. super.render(code, options);
  5037. }
  5038. }
  5039. }
  5040. function isStaticBlock(statement) {
  5041. return statement.type === StaticBlock$1;
  5042. }
  5043. class ObjectMember extends ExpressionEntity {
  5044. constructor(object, key) {
  5045. super();
  5046. this.object = object;
  5047. this.key = key;
  5048. }
  5049. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  5050. this.object.deoptimizeArgumentsOnInteractionAtPath(interaction, [this.key, ...path], recursionTracker);
  5051. }
  5052. deoptimizePath(path) {
  5053. this.object.deoptimizePath([this.key, ...path]);
  5054. }
  5055. getLiteralValueAtPath(path, recursionTracker, origin) {
  5056. return this.object.getLiteralValueAtPath([this.key, ...path], recursionTracker, origin);
  5057. }
  5058. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  5059. return this.object.getReturnExpressionWhenCalledAtPath([this.key, ...path], interaction, recursionTracker, origin);
  5060. }
  5061. hasEffectsOnInteractionAtPath(path, interaction, context) {
  5062. return this.object.hasEffectsOnInteractionAtPath([this.key, ...path], interaction, context);
  5063. }
  5064. }
  5065. class ClassNode extends NodeBase {
  5066. constructor() {
  5067. super(...arguments);
  5068. this.objectEntity = null;
  5069. }
  5070. createScope(parentScope) {
  5071. this.scope = new ChildScope(parentScope, parentScope.context);
  5072. }
  5073. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  5074. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  5075. }
  5076. deoptimizeCache() {
  5077. this.getObjectEntity().deoptimizeAllProperties();
  5078. }
  5079. deoptimizePath(path) {
  5080. this.getObjectEntity().deoptimizePath(path);
  5081. }
  5082. getLiteralValueAtPath(path, recursionTracker, origin) {
  5083. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  5084. }
  5085. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  5086. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  5087. }
  5088. hasEffects(context) {
  5089. if (!this.deoptimized)
  5090. this.applyDeoptimizations();
  5091. const initEffect = this.superClass?.hasEffects(context) || this.body.hasEffects(context);
  5092. this.id?.markDeclarationReached();
  5093. return initEffect || super.hasEffects(context) || checkEffectForNodes(this.decorators, context);
  5094. }
  5095. hasEffectsOnInteractionAtPath(path, interaction, context) {
  5096. return interaction.type === INTERACTION_CALLED && path.length === 0
  5097. ? !interaction.withNew ||
  5098. (this.classConstructor === null
  5099. ? this.superClass?.hasEffectsOnInteractionAtPath(path, interaction, context)
  5100. : this.classConstructor.hasEffectsOnInteractionAtPath(path, interaction, context)) ||
  5101. false
  5102. : this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  5103. }
  5104. include(context, includeChildrenRecursively) {
  5105. if (!this.deoptimized)
  5106. this.applyDeoptimizations();
  5107. this.included = true;
  5108. this.superClass?.include(context, includeChildrenRecursively);
  5109. this.body.include(context, includeChildrenRecursively);
  5110. for (const decorator of this.decorators)
  5111. decorator.include(context, includeChildrenRecursively);
  5112. if (this.id) {
  5113. this.id.markDeclarationReached();
  5114. this.id.include();
  5115. }
  5116. }
  5117. initialise() {
  5118. super.initialise();
  5119. this.id?.declare('class', this);
  5120. for (const method of this.body.body) {
  5121. if (method instanceof MethodDefinition && method.kind === 'constructor') {
  5122. this.classConstructor = method;
  5123. return;
  5124. }
  5125. }
  5126. this.classConstructor = null;
  5127. }
  5128. applyDeoptimizations() {
  5129. this.deoptimized = true;
  5130. for (const definition of this.body.body) {
  5131. if (!isStaticBlock(definition) &&
  5132. !(definition.static ||
  5133. (definition instanceof MethodDefinition && definition.kind === 'constructor'))) {
  5134. // Calls to methods are not tracked, ensure that the return value is deoptimized
  5135. definition.deoptimizePath(UNKNOWN_PATH);
  5136. }
  5137. }
  5138. this.scope.context.requestTreeshakingPass();
  5139. }
  5140. getObjectEntity() {
  5141. if (this.objectEntity !== null) {
  5142. return this.objectEntity;
  5143. }
  5144. const staticProperties = [];
  5145. const dynamicMethods = [];
  5146. for (const definition of this.body.body) {
  5147. if (isStaticBlock(definition))
  5148. continue;
  5149. const properties = definition.static ? staticProperties : dynamicMethods;
  5150. const definitionKind = definition.kind;
  5151. // Note that class fields do not end up on the prototype
  5152. if (properties === dynamicMethods && !definitionKind)
  5153. continue;
  5154. const kind = definitionKind === 'set' || definitionKind === 'get' ? definitionKind : 'init';
  5155. let key;
  5156. if (definition.computed) {
  5157. const keyValue = definition.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  5158. if (typeof keyValue === 'symbol') {
  5159. properties.push({ key: UnknownKey, kind, property: definition });
  5160. continue;
  5161. }
  5162. else {
  5163. key = String(keyValue);
  5164. }
  5165. }
  5166. else {
  5167. key =
  5168. definition.key instanceof Identifier
  5169. ? definition.key.name
  5170. : String(definition.key.value);
  5171. }
  5172. properties.push({ key, kind, property: definition });
  5173. }
  5174. staticProperties.unshift({
  5175. key: 'prototype',
  5176. kind: 'init',
  5177. property: new ObjectEntity(dynamicMethods, this.superClass ? new ObjectMember(this.superClass, 'prototype') : OBJECT_PROTOTYPE)
  5178. });
  5179. return (this.objectEntity = new ObjectEntity(staticProperties, this.superClass || OBJECT_PROTOTYPE));
  5180. }
  5181. }
  5182. class ClassDeclaration extends ClassNode {
  5183. initialise() {
  5184. super.initialise();
  5185. if (this.id !== null) {
  5186. this.id.variable.isId = true;
  5187. }
  5188. }
  5189. parseNode(esTreeNode) {
  5190. if (esTreeNode.id !== null) {
  5191. this.id = new Identifier(this, this.scope.parent).parseNode(esTreeNode.id);
  5192. }
  5193. return super.parseNode(esTreeNode);
  5194. }
  5195. render(code, options) {
  5196. const { exportNamesByVariable, format, snippets: { _, getPropertyAccess } } = options;
  5197. if (this.id) {
  5198. const { variable, name } = this.id;
  5199. if (format === 'system' && exportNamesByVariable.has(variable)) {
  5200. code.appendLeft(this.end, `${_}${getSystemExportStatement([variable], options)};`);
  5201. }
  5202. const renderedVariable = variable.getName(getPropertyAccess);
  5203. if (renderedVariable !== name) {
  5204. this.decorators.map(decorator => decorator.render(code, options));
  5205. this.superClass?.render(code, options);
  5206. this.body.render(code, {
  5207. ...options,
  5208. useOriginalName: (_variable) => _variable === variable
  5209. });
  5210. code.prependRight(this.start, `let ${renderedVariable}${_}=${_}`);
  5211. code.prependLeft(this.end, ';');
  5212. return;
  5213. }
  5214. }
  5215. super.render(code, options);
  5216. }
  5217. applyDeoptimizations() {
  5218. super.applyDeoptimizations();
  5219. const { id, scope } = this;
  5220. if (id) {
  5221. const { name, variable } = id;
  5222. for (const accessedVariable of scope.accessedOutsideVariables.values()) {
  5223. if (accessedVariable !== variable) {
  5224. accessedVariable.forbidName(name);
  5225. }
  5226. }
  5227. }
  5228. }
  5229. }
  5230. class ArgumentsVariable extends LocalVariable {
  5231. constructor(context) {
  5232. super('arguments', null, UNKNOWN_EXPRESSION, context, 'other');
  5233. this.deoptimizedArguments = [];
  5234. }
  5235. addArgumentToBeDeoptimized(argument) {
  5236. if (this.included) {
  5237. argument.deoptimizePath(UNKNOWN_PATH);
  5238. }
  5239. else {
  5240. this.deoptimizedArguments.push(argument);
  5241. }
  5242. }
  5243. hasEffectsOnInteractionAtPath(path, { type }) {
  5244. return type !== INTERACTION_ACCESSED || path.length > 1;
  5245. }
  5246. include() {
  5247. super.include();
  5248. for (const argument of this.deoptimizedArguments) {
  5249. argument.deoptimizePath(UNKNOWN_PATH);
  5250. }
  5251. this.deoptimizedArguments.length = 0;
  5252. }
  5253. }
  5254. const MAX_TRACKED_INTERACTIONS = 20;
  5255. const NO_INTERACTIONS = EMPTY_ARRAY;
  5256. const UNKNOWN_DEOPTIMIZED_FIELD = new Set([UnknownKey]);
  5257. const EMPTY_PATH_TRACKER = new PathTracker();
  5258. const UNKNOWN_DEOPTIMIZED_ENTITY = new Set([UNKNOWN_EXPRESSION]);
  5259. class ParameterVariable extends LocalVariable {
  5260. constructor(name, declarator, context) {
  5261. super(name, declarator, UNKNOWN_EXPRESSION, context, 'parameter');
  5262. this.deoptimizationInteractions = [];
  5263. this.deoptimizations = new PathTracker();
  5264. this.deoptimizedFields = new Set();
  5265. this.entitiesToBeDeoptimized = new Set();
  5266. this.expressionsUseTheKnownValue = [];
  5267. this.knownValue = null;
  5268. this.knownValueLiteral = UnknownValue;
  5269. this.frozenValue = null;
  5270. }
  5271. addEntityToBeDeoptimized(entity) {
  5272. if (entity === UNKNOWN_EXPRESSION) {
  5273. // As unknown expressions fully deoptimize all interactions, we can clear
  5274. // the interaction cache at this point provided we keep this optimization
  5275. // in mind when adding new interactions
  5276. if (!this.entitiesToBeDeoptimized.has(UNKNOWN_EXPRESSION)) {
  5277. this.entitiesToBeDeoptimized.add(UNKNOWN_EXPRESSION);
  5278. for (const { interaction } of this.deoptimizationInteractions) {
  5279. deoptimizeInteraction(interaction);
  5280. }
  5281. this.deoptimizationInteractions = NO_INTERACTIONS;
  5282. }
  5283. }
  5284. else if (this.deoptimizedFields.has(UnknownKey)) {
  5285. // This means that we already deoptimized all interactions and no longer
  5286. // track them
  5287. entity.deoptimizePath(UNKNOWN_PATH);
  5288. }
  5289. else if (!this.entitiesToBeDeoptimized.has(entity)) {
  5290. this.entitiesToBeDeoptimized.add(entity);
  5291. for (const field of this.deoptimizedFields) {
  5292. entity.deoptimizePath([field]);
  5293. }
  5294. for (const { interaction, path } of this.deoptimizationInteractions) {
  5295. entity.deoptimizeArgumentsOnInteractionAtPath(interaction, path, SHARED_RECURSION_TRACKER);
  5296. }
  5297. }
  5298. }
  5299. markReassigned() {
  5300. if (this.isReassigned) {
  5301. return;
  5302. }
  5303. super.markReassigned();
  5304. for (const expression of this.expressionsUseTheKnownValue) {
  5305. expression.deoptimizeCache();
  5306. }
  5307. this.expressionsUseTheKnownValue = EMPTY_ARRAY;
  5308. }
  5309. deoptimizeCache() {
  5310. this.markReassigned();
  5311. }
  5312. /**
  5313. * Update the known value of the parameter variable.
  5314. * Must be called for every function call, so it can track all the arguments,
  5315. * and deoptimizeCache itself to mark reassigned if the argument is changed.
  5316. * @param argument The argument of the function call
  5317. */
  5318. updateKnownValue(argument) {
  5319. if (this.isReassigned) {
  5320. return;
  5321. }
  5322. if (this.knownValue === null) {
  5323. this.knownValue = argument;
  5324. this.knownValueLiteral = argument.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  5325. return;
  5326. }
  5327. // the same literal or identifier, do nothing
  5328. if (this.knownValue === argument ||
  5329. (this.knownValue instanceof Identifier &&
  5330. argument instanceof Identifier &&
  5331. this.knownValue.variable === argument.variable)) {
  5332. return;
  5333. }
  5334. const oldValue = this.knownValueLiteral;
  5335. if (typeof oldValue === 'symbol') {
  5336. this.markReassigned();
  5337. return;
  5338. }
  5339. // add tracking for the new argument
  5340. const newValue = argument.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  5341. if (newValue !== oldValue) {
  5342. this.markReassigned();
  5343. }
  5344. }
  5345. /**
  5346. * This function freezes the known value of the parameter variable,
  5347. * so the optimization starts with a certain ExpressionEntity.
  5348. * The optimization can be undone by calling `markReassigned`.
  5349. * @returns the frozen value
  5350. */
  5351. getKnownValue() {
  5352. if (this.frozenValue === null) {
  5353. this.frozenValue = this.knownValue || UNKNOWN_EXPRESSION;
  5354. }
  5355. return this.frozenValue;
  5356. }
  5357. getLiteralValueAtPath(path, recursionTracker, origin) {
  5358. if (this.isReassigned) {
  5359. return UnknownValue;
  5360. }
  5361. const knownValue = this.getKnownValue();
  5362. this.expressionsUseTheKnownValue.push(origin);
  5363. return recursionTracker.withTrackedEntityAtPath(path, knownValue, () => knownValue.getLiteralValueAtPath(path, recursionTracker, origin), UnknownValue);
  5364. }
  5365. hasEffectsOnInteractionAtPath(path, interaction, context) {
  5366. if (this.isReassigned || interaction.type === INTERACTION_ASSIGNED) {
  5367. return super.hasEffectsOnInteractionAtPath(path, interaction, context);
  5368. }
  5369. const knownValue = this.getKnownValue();
  5370. return knownValue.hasEffectsOnInteractionAtPath(path, interaction, context);
  5371. }
  5372. deoptimizeArgumentsOnInteractionAtPath(interaction, path) {
  5373. // For performance reasons, we fully deoptimize all deeper interactions
  5374. if (path.length >= 2 ||
  5375. this.entitiesToBeDeoptimized.has(UNKNOWN_EXPRESSION) ||
  5376. this.deoptimizationInteractions.length >= MAX_TRACKED_INTERACTIONS ||
  5377. (path.length === 1 &&
  5378. (this.deoptimizedFields.has(UnknownKey) ||
  5379. (interaction.type === INTERACTION_CALLED && this.deoptimizedFields.has(path[0]))))) {
  5380. deoptimizeInteraction(interaction);
  5381. return;
  5382. }
  5383. if (!this.deoptimizations.trackEntityAtPathAndGetIfTracked(path, interaction.args)) {
  5384. for (const entity of this.entitiesToBeDeoptimized) {
  5385. entity.deoptimizeArgumentsOnInteractionAtPath(interaction, path, SHARED_RECURSION_TRACKER);
  5386. }
  5387. if (!this.entitiesToBeDeoptimized.has(UNKNOWN_EXPRESSION)) {
  5388. this.deoptimizationInteractions.push({
  5389. interaction,
  5390. path
  5391. });
  5392. }
  5393. }
  5394. }
  5395. deoptimizePath(path) {
  5396. if (path.length === 0) {
  5397. this.markReassigned();
  5398. return;
  5399. }
  5400. if (this.deoptimizedFields.has(UnknownKey)) {
  5401. return;
  5402. }
  5403. const key = path[0];
  5404. if (this.deoptimizedFields.has(key)) {
  5405. return;
  5406. }
  5407. this.deoptimizedFields.add(key);
  5408. for (const entity of this.entitiesToBeDeoptimized) {
  5409. // We do not need a recursion tracker here as we already track whether
  5410. // this field is deoptimized
  5411. entity.deoptimizePath([key]);
  5412. }
  5413. if (key === UnknownKey) {
  5414. // save some memory
  5415. this.deoptimizationInteractions = NO_INTERACTIONS;
  5416. this.deoptimizations = EMPTY_PATH_TRACKER;
  5417. this.deoptimizedFields = UNKNOWN_DEOPTIMIZED_FIELD;
  5418. this.entitiesToBeDeoptimized = UNKNOWN_DEOPTIMIZED_ENTITY;
  5419. }
  5420. }
  5421. getReturnExpressionWhenCalledAtPath(path) {
  5422. // We deoptimize everything that is called as that will trivially deoptimize
  5423. // the corresponding return expressions as well and avoid badly performing
  5424. // and complicated alternatives
  5425. if (path.length === 0) {
  5426. this.deoptimizePath(UNKNOWN_PATH);
  5427. }
  5428. else if (!this.deoptimizedFields.has(path[0])) {
  5429. this.deoptimizePath([path[0]]);
  5430. }
  5431. return UNKNOWN_RETURN_EXPRESSION;
  5432. }
  5433. }
  5434. class ThisVariable extends ParameterVariable {
  5435. constructor(context) {
  5436. super('this', null, context);
  5437. }
  5438. hasEffectsOnInteractionAtPath(path, interaction, context) {
  5439. return (context.replacedVariableInits.get(this) || UNKNOWN_EXPRESSION).hasEffectsOnInteractionAtPath(path, interaction, context);
  5440. }
  5441. }
  5442. class CatchBodyScope extends ChildScope {
  5443. constructor(parent) {
  5444. super(parent, parent.context);
  5445. this.parent = parent;
  5446. }
  5447. addDeclaration(identifier, context, init, kind) {
  5448. if (kind === 'var') {
  5449. const name = identifier.name;
  5450. const existingVariable = this.hoistedVariables?.get(name) || this.variables.get(name);
  5451. if (existingVariable) {
  5452. const existingKind = existingVariable.kind;
  5453. if (existingKind === 'parameter' &&
  5454. // If this is a destructured parameter, it is forbidden to redeclare
  5455. existingVariable.declarations[0].parent.type === CatchClause$1) {
  5456. // If this is a var with the same name as the catch scope parameter,
  5457. // the assignment actually goes to the parameter and the var is
  5458. // hoisted without assignment. Locally, it is shadowed by the
  5459. // parameter
  5460. const declaredVariable = this.parent.parent.addDeclaration(identifier, context, UNDEFINED_EXPRESSION, kind);
  5461. // To avoid the need to rewrite the declaration, we link the variable
  5462. // names. If we ever implement a logic that splits initialization and
  5463. // assignment for hoisted vars, the "renderLikeHoisted" logic can be
  5464. // removed again.
  5465. // We do not need to check whether there already is a linked
  5466. // variable because then declaredVariable would be that linked
  5467. // variable.
  5468. existingVariable.renderLikeHoisted(declaredVariable);
  5469. this.addHoistedVariable(name, declaredVariable);
  5470. return declaredVariable;
  5471. }
  5472. if (existingKind === 'var') {
  5473. existingVariable.addDeclaration(identifier, init);
  5474. return existingVariable;
  5475. }
  5476. return context.error(logRedeclarationError(name), identifier.start);
  5477. }
  5478. // We only add parameters to parameter scopes
  5479. const declaredVariable = this.parent.parent.addDeclaration(identifier, context, init, kind);
  5480. // Necessary to make sure the init is deoptimized for conditional declarations.
  5481. // We cannot call deoptimizePath here.
  5482. declaredVariable.markInitializersForDeoptimization();
  5483. // We add the variable to this and all parent scopes to reliably detect conflicts
  5484. this.addHoistedVariable(name, declaredVariable);
  5485. return declaredVariable;
  5486. }
  5487. return super.addDeclaration(identifier, context, init, kind);
  5488. }
  5489. }
  5490. class FunctionBodyScope extends ChildScope {
  5491. constructor(parent) {
  5492. super(parent, parent.context);
  5493. }
  5494. // There is stuff that is only allowed in function scopes, i.e. functions can
  5495. // be redeclared, functions and var can redeclare each other
  5496. addDeclaration(identifier, context, init, kind) {
  5497. const name = identifier.name;
  5498. const existingVariable = this.hoistedVariables?.get(name) || this.variables.get(name);
  5499. if (existingVariable) {
  5500. const existingKind = existingVariable.kind;
  5501. if ((kind === 'var' || kind === 'function') &&
  5502. (existingKind === 'var' || existingKind === 'function' || existingKind === 'parameter')) {
  5503. existingVariable.addDeclaration(identifier, init);
  5504. return existingVariable;
  5505. }
  5506. context.error(logRedeclarationError(name), identifier.start);
  5507. }
  5508. const newVariable = new LocalVariable(identifier.name, identifier, init, context, kind);
  5509. this.variables.set(name, newVariable);
  5510. return newVariable;
  5511. }
  5512. }
  5513. class ParameterScope extends ChildScope {
  5514. constructor(parent, isCatchScope) {
  5515. super(parent, parent.context);
  5516. this.parameters = [];
  5517. this.hasRest = false;
  5518. this.bodyScope = isCatchScope ? new CatchBodyScope(this) : new FunctionBodyScope(this);
  5519. }
  5520. /**
  5521. * Adds a parameter to this scope. Parameters must be added in the correct
  5522. * order, i.e. from left to right.
  5523. */
  5524. addParameterDeclaration(identifier) {
  5525. const { name, start } = identifier;
  5526. const existingParameter = this.variables.get(name);
  5527. if (existingParameter) {
  5528. return this.context.error(logDuplicateArgumentNameError(name), start);
  5529. }
  5530. const variable = new ParameterVariable(name, identifier, this.context);
  5531. this.variables.set(name, variable);
  5532. // We also add it to the body scope to detect name conflicts with local
  5533. // variables. We still need the intermediate scope, though, as parameter
  5534. // defaults are NOT taken from the body scope but from the parameters or
  5535. // outside scope.
  5536. this.bodyScope.addHoistedVariable(name, variable);
  5537. return variable;
  5538. }
  5539. addParameterVariables(parameters, hasRest) {
  5540. this.parameters = parameters;
  5541. for (const parameterList of parameters) {
  5542. for (const parameter of parameterList) {
  5543. parameter.alwaysRendered = true;
  5544. }
  5545. }
  5546. this.hasRest = hasRest;
  5547. }
  5548. includeCallArguments(context, parameters) {
  5549. let calledFromTryStatement = false;
  5550. let argumentIncluded = false;
  5551. const restParameter = this.hasRest && this.parameters[this.parameters.length - 1];
  5552. for (const checkedArgument of parameters) {
  5553. if (checkedArgument instanceof SpreadElement) {
  5554. for (const argument of parameters) {
  5555. argument.include(context, false);
  5556. }
  5557. break;
  5558. }
  5559. }
  5560. for (let index = parameters.length - 1; index >= 0; index--) {
  5561. const parameterVariables = this.parameters[index] || restParameter;
  5562. const argument = parameters[index];
  5563. if (parameterVariables) {
  5564. calledFromTryStatement = false;
  5565. if (parameterVariables.length === 0) {
  5566. // handle empty destructuring
  5567. argumentIncluded = true;
  5568. }
  5569. else {
  5570. for (const variable of parameterVariables) {
  5571. if (variable.included) {
  5572. argumentIncluded = true;
  5573. }
  5574. if (variable.calledFromTryStatement) {
  5575. calledFromTryStatement = true;
  5576. }
  5577. }
  5578. }
  5579. }
  5580. if (!argumentIncluded && argument.shouldBeIncluded(context)) {
  5581. argumentIncluded = true;
  5582. }
  5583. if (argumentIncluded) {
  5584. argument.include(context, calledFromTryStatement);
  5585. }
  5586. }
  5587. }
  5588. }
  5589. class ReturnValueScope extends ParameterScope {
  5590. constructor() {
  5591. super(...arguments);
  5592. this.returnExpression = null;
  5593. this.returnExpressions = [];
  5594. }
  5595. addReturnExpression(expression) {
  5596. this.returnExpressions.push(expression);
  5597. }
  5598. getReturnExpression() {
  5599. if (this.returnExpression === null)
  5600. this.updateReturnExpression();
  5601. return this.returnExpression;
  5602. }
  5603. updateReturnExpression() {
  5604. if (this.returnExpressions.length === 1) {
  5605. this.returnExpression = this.returnExpressions[0];
  5606. }
  5607. else {
  5608. this.returnExpression = UNKNOWN_EXPRESSION;
  5609. for (const expression of this.returnExpressions) {
  5610. expression.deoptimizePath(UNKNOWN_PATH);
  5611. }
  5612. }
  5613. }
  5614. }
  5615. class FunctionScope extends ReturnValueScope {
  5616. constructor(parent) {
  5617. const { context } = parent;
  5618. super(parent, false);
  5619. this.variables.set('arguments', (this.argumentsVariable = new ArgumentsVariable(context)));
  5620. this.variables.set('this', (this.thisVariable = new ThisVariable(context)));
  5621. }
  5622. findLexicalBoundary() {
  5623. return this;
  5624. }
  5625. includeCallArguments(context, parameters) {
  5626. super.includeCallArguments(context, parameters);
  5627. if (this.argumentsVariable.included) {
  5628. for (const argument of parameters) {
  5629. if (!argument.included) {
  5630. argument.include(context, false);
  5631. }
  5632. }
  5633. }
  5634. }
  5635. }
  5636. class ExpressionStatement extends NodeBase {
  5637. initialise() {
  5638. super.initialise();
  5639. if (this.directive &&
  5640. this.directive !== 'use strict' &&
  5641. this.parent.type === Program$1) {
  5642. this.scope.context.log(LOGLEVEL_WARN,
  5643. // This is necessary, because either way (deleting or not) can lead to errors.
  5644. logModuleLevelDirective(this.directive, this.scope.context.module.id), this.start);
  5645. }
  5646. }
  5647. removeAnnotations(code) {
  5648. this.expression.removeAnnotations(code);
  5649. }
  5650. render(code, options) {
  5651. super.render(code, options);
  5652. if (code.original[this.end - 1] !== ';') {
  5653. code.appendLeft(this.end, ';');
  5654. }
  5655. }
  5656. shouldBeIncluded(context) {
  5657. if (this.directive && this.directive !== 'use strict')
  5658. return this.parent.type !== Program$1;
  5659. return super.shouldBeIncluded(context);
  5660. }
  5661. applyDeoptimizations() { }
  5662. }
  5663. class BlockStatement extends NodeBase {
  5664. get deoptimizeBody() {
  5665. return isFlagSet(this.flags, 32768 /* Flag.deoptimizeBody */);
  5666. }
  5667. set deoptimizeBody(value) {
  5668. this.flags = setFlag(this.flags, 32768 /* Flag.deoptimizeBody */, value);
  5669. }
  5670. get directlyIncluded() {
  5671. return isFlagSet(this.flags, 16384 /* Flag.directlyIncluded */);
  5672. }
  5673. set directlyIncluded(value) {
  5674. this.flags = setFlag(this.flags, 16384 /* Flag.directlyIncluded */, value);
  5675. }
  5676. addImplicitReturnExpressionToScope() {
  5677. const lastStatement = this.body[this.body.length - 1];
  5678. if (!lastStatement || lastStatement.type !== ReturnStatement$1) {
  5679. this.scope.addReturnExpression(UNKNOWN_EXPRESSION);
  5680. }
  5681. }
  5682. createScope(parentScope) {
  5683. this.scope = this.parent.preventChildBlockScope
  5684. ? parentScope
  5685. : new BlockScope(parentScope);
  5686. }
  5687. hasEffects(context) {
  5688. if (this.deoptimizeBody)
  5689. return true;
  5690. for (const node of this.body) {
  5691. if (context.brokenFlow)
  5692. break;
  5693. if (node.hasEffects(context))
  5694. return true;
  5695. }
  5696. return false;
  5697. }
  5698. include(context, includeChildrenRecursively) {
  5699. if (!(this.deoptimizeBody && this.directlyIncluded)) {
  5700. this.included = true;
  5701. this.directlyIncluded = true;
  5702. if (this.deoptimizeBody)
  5703. includeChildrenRecursively = true;
  5704. for (const node of this.body) {
  5705. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  5706. node.include(context, includeChildrenRecursively);
  5707. }
  5708. }
  5709. }
  5710. initialise() {
  5711. super.initialise();
  5712. const firstBodyStatement = this.body[0];
  5713. this.deoptimizeBody =
  5714. firstBodyStatement instanceof ExpressionStatement &&
  5715. firstBodyStatement.directive === 'use asm';
  5716. }
  5717. render(code, options) {
  5718. if (this.body.length > 0) {
  5719. renderStatementList(this.body, code, this.start + 1, this.end - 1, options);
  5720. }
  5721. else {
  5722. super.render(code, options);
  5723. }
  5724. }
  5725. }
  5726. class RestElement extends NodeBase {
  5727. constructor() {
  5728. super(...arguments);
  5729. this.declarationInit = null;
  5730. }
  5731. addExportedVariables(variables, exportNamesByVariable) {
  5732. this.argument.addExportedVariables(variables, exportNamesByVariable);
  5733. }
  5734. declare(kind, init) {
  5735. this.declarationInit = init;
  5736. return this.argument.declare(kind, UNKNOWN_EXPRESSION);
  5737. }
  5738. deoptimizePath(path) {
  5739. if (path.length === 0) {
  5740. this.argument.deoptimizePath(EMPTY_PATH);
  5741. }
  5742. }
  5743. hasEffectsOnInteractionAtPath(path, interaction, context) {
  5744. return (path.length > 0 ||
  5745. this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context));
  5746. }
  5747. markDeclarationReached() {
  5748. this.argument.markDeclarationReached();
  5749. }
  5750. applyDeoptimizations() {
  5751. this.deoptimized = true;
  5752. if (this.declarationInit !== null) {
  5753. this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
  5754. this.scope.context.requestTreeshakingPass();
  5755. }
  5756. }
  5757. }
  5758. class FunctionBase extends NodeBase {
  5759. constructor() {
  5760. super(...arguments);
  5761. this.objectEntity = null;
  5762. this.parameterVariableValuesDeoptimized = false;
  5763. }
  5764. get async() {
  5765. return isFlagSet(this.flags, 256 /* Flag.async */);
  5766. }
  5767. set async(value) {
  5768. this.flags = setFlag(this.flags, 256 /* Flag.async */, value);
  5769. }
  5770. get deoptimizedReturn() {
  5771. return isFlagSet(this.flags, 512 /* Flag.deoptimizedReturn */);
  5772. }
  5773. set deoptimizedReturn(value) {
  5774. this.flags = setFlag(this.flags, 512 /* Flag.deoptimizedReturn */, value);
  5775. }
  5776. get generator() {
  5777. return isFlagSet(this.flags, 4194304 /* Flag.generator */);
  5778. }
  5779. set generator(value) {
  5780. this.flags = setFlag(this.flags, 4194304 /* Flag.generator */, value);
  5781. }
  5782. updateParameterVariableValues(_arguments) {
  5783. for (let position = 0; position < this.params.length; position++) {
  5784. const parameter = this.params[position];
  5785. if (!(parameter instanceof Identifier)) {
  5786. continue;
  5787. }
  5788. const parameterVariable = parameter.variable;
  5789. const argument = _arguments[position + 1] ?? UNDEFINED_EXPRESSION;
  5790. parameterVariable.updateKnownValue(argument);
  5791. }
  5792. }
  5793. deoptimizeParameterVariableValues() {
  5794. for (const parameter of this.params) {
  5795. if (parameter instanceof Identifier) {
  5796. const parameterVariable = parameter.variable;
  5797. parameterVariable.markReassigned();
  5798. }
  5799. }
  5800. }
  5801. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  5802. if (interaction.type === INTERACTION_CALLED) {
  5803. const { parameters } = this.scope;
  5804. const { args } = interaction;
  5805. let hasRest = false;
  5806. for (let position = 0; position < args.length - 1; position++) {
  5807. const parameter = this.params[position];
  5808. // Only the "this" argument arg[0] can be null
  5809. const argument = args[position + 1];
  5810. if (argument instanceof SpreadElement) {
  5811. this.deoptimizeParameterVariableValues();
  5812. }
  5813. if (hasRest || parameter instanceof RestElement) {
  5814. hasRest = true;
  5815. argument.deoptimizePath(UNKNOWN_PATH);
  5816. }
  5817. else if (parameter instanceof Identifier) {
  5818. parameters[position][0].addEntityToBeDeoptimized(argument);
  5819. this.addArgumentToBeDeoptimized(argument);
  5820. }
  5821. else if (parameter) {
  5822. argument.deoptimizePath(UNKNOWN_PATH);
  5823. }
  5824. else {
  5825. this.addArgumentToBeDeoptimized(argument);
  5826. }
  5827. }
  5828. this.updateParameterVariableValues(args);
  5829. }
  5830. else {
  5831. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  5832. }
  5833. }
  5834. deoptimizePath(path) {
  5835. this.getObjectEntity().deoptimizePath(path);
  5836. if (path.length === 1 && path[0] === UnknownKey) {
  5837. // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
  5838. // which means the return expression and parameters need to be reassigned
  5839. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  5840. for (const parameterList of this.scope.parameters) {
  5841. for (const parameter of parameterList) {
  5842. parameter.deoptimizePath(UNKNOWN_PATH);
  5843. parameter.markReassigned();
  5844. }
  5845. }
  5846. }
  5847. }
  5848. getLiteralValueAtPath(path, recursionTracker, origin) {
  5849. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  5850. }
  5851. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  5852. if (path.length > 0) {
  5853. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  5854. }
  5855. if (this.async) {
  5856. if (!this.deoptimizedReturn) {
  5857. this.deoptimizedReturn = true;
  5858. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  5859. this.scope.context.requestTreeshakingPass();
  5860. }
  5861. return UNKNOWN_RETURN_EXPRESSION;
  5862. }
  5863. return [this.scope.getReturnExpression(), false];
  5864. }
  5865. hasEffectsOnInteractionAtPath(path, interaction, context) {
  5866. if (path.length > 0 || interaction.type !== INTERACTION_CALLED) {
  5867. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  5868. }
  5869. if (this.annotationNoSideEffects) {
  5870. return false;
  5871. }
  5872. if (this.async) {
  5873. const { propertyReadSideEffects } = this.scope.context.options
  5874. .treeshake;
  5875. const returnExpression = this.scope.getReturnExpression();
  5876. if (returnExpression.hasEffectsOnInteractionAtPath(['then'], NODE_INTERACTION_UNKNOWN_CALL, context) ||
  5877. (propertyReadSideEffects &&
  5878. (propertyReadSideEffects === 'always' ||
  5879. returnExpression.hasEffectsOnInteractionAtPath(['then'], NODE_INTERACTION_UNKNOWN_ACCESS, context)))) {
  5880. return true;
  5881. }
  5882. }
  5883. for (const parameter of this.params) {
  5884. if (parameter.hasEffects(context))
  5885. return true;
  5886. }
  5887. return false;
  5888. }
  5889. /**
  5890. * If the function (expression or declaration) is only used as function calls
  5891. */
  5892. onlyFunctionCallUsed() {
  5893. let variable = null;
  5894. if (this.parent.type === VariableDeclarator$1) {
  5895. variable = this.parent.id.variable ?? null;
  5896. }
  5897. if (this.parent.type === ExportDefaultDeclaration$1) {
  5898. variable = this.parent.variable;
  5899. }
  5900. return variable?.getOnlyFunctionCallUsed() ?? false;
  5901. }
  5902. include(context, includeChildrenRecursively) {
  5903. if (!this.parameterVariableValuesDeoptimized && !this.onlyFunctionCallUsed()) {
  5904. this.parameterVariableValuesDeoptimized = true;
  5905. this.deoptimizeParameterVariableValues();
  5906. }
  5907. if (!this.deoptimized)
  5908. this.applyDeoptimizations();
  5909. this.included = true;
  5910. const { brokenFlow } = context;
  5911. context.brokenFlow = false;
  5912. this.body.include(context, includeChildrenRecursively);
  5913. context.brokenFlow = brokenFlow;
  5914. }
  5915. includeCallArguments(context, parameters) {
  5916. this.scope.includeCallArguments(context, parameters);
  5917. }
  5918. initialise() {
  5919. super.initialise();
  5920. if (this.body instanceof BlockStatement) {
  5921. this.body.addImplicitReturnExpressionToScope();
  5922. }
  5923. else {
  5924. this.scope.addReturnExpression(this.body);
  5925. }
  5926. if (this.annotations &&
  5927. this.scope.context.options.treeshake.annotations) {
  5928. this.annotationNoSideEffects = this.annotations.some(comment => comment.type === 'noSideEffects');
  5929. }
  5930. }
  5931. parseNode(esTreeNode) {
  5932. const { body, params } = esTreeNode;
  5933. const { scope } = this;
  5934. const { bodyScope, context } = scope;
  5935. // We need to ensure that parameters are declared before the body is parsed
  5936. // so that the scope already knows all parameters and can detect conflicts
  5937. // when parsing the body.
  5938. const parameters = (this.params = params.map((parameter) => new (context.getNodeConstructor(parameter.type))(this, scope).parseNode(parameter)));
  5939. scope.addParameterVariables(parameters.map(parameter => parameter.declare('parameter', UNKNOWN_EXPRESSION)), parameters[parameters.length - 1] instanceof RestElement);
  5940. this.body = new (context.getNodeConstructor(body.type))(this, bodyScope).parseNode(body);
  5941. return super.parseNode(esTreeNode);
  5942. }
  5943. addArgumentToBeDeoptimized(_argument) { }
  5944. applyDeoptimizations() { }
  5945. }
  5946. FunctionBase.prototype.preventChildBlockScope = true;
  5947. class FunctionNode extends FunctionBase {
  5948. constructor() {
  5949. super(...arguments);
  5950. this.objectEntity = null;
  5951. }
  5952. createScope(parentScope) {
  5953. this.scope = new FunctionScope(parentScope);
  5954. this.constructedEntity = new ObjectEntity(Object.create(null), OBJECT_PROTOTYPE);
  5955. // This makes sure that all deoptimizations of "this" are applied to the
  5956. // constructed entity.
  5957. this.scope.thisVariable.addEntityToBeDeoptimized(this.constructedEntity);
  5958. }
  5959. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  5960. super.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  5961. if (interaction.type === INTERACTION_CALLED && path.length === 0 && interaction.args[0]) {
  5962. // args[0] is the "this" argument
  5963. this.scope.thisVariable.addEntityToBeDeoptimized(interaction.args[0]);
  5964. }
  5965. }
  5966. hasEffects(context) {
  5967. if (!this.deoptimized)
  5968. this.applyDeoptimizations();
  5969. if (this.annotationNoSideEffects) {
  5970. return false;
  5971. }
  5972. return !!this.id?.hasEffects(context);
  5973. }
  5974. hasEffectsOnInteractionAtPath(path, interaction, context) {
  5975. if (super.hasEffectsOnInteractionAtPath(path, interaction, context))
  5976. return true;
  5977. if (this.annotationNoSideEffects) {
  5978. return false;
  5979. }
  5980. if (interaction.type === INTERACTION_CALLED) {
  5981. const thisInit = context.replacedVariableInits.get(this.scope.thisVariable);
  5982. context.replacedVariableInits.set(this.scope.thisVariable, interaction.withNew ? this.constructedEntity : UNKNOWN_EXPRESSION);
  5983. const { brokenFlow, ignore, replacedVariableInits } = context;
  5984. context.ignore = {
  5985. breaks: false,
  5986. continues: false,
  5987. labels: new Set(),
  5988. returnYield: true,
  5989. this: interaction.withNew
  5990. };
  5991. if (this.body.hasEffects(context))
  5992. return true;
  5993. context.brokenFlow = brokenFlow;
  5994. if (thisInit) {
  5995. replacedVariableInits.set(this.scope.thisVariable, thisInit);
  5996. }
  5997. else {
  5998. replacedVariableInits.delete(this.scope.thisVariable);
  5999. }
  6000. context.ignore = ignore;
  6001. }
  6002. return false;
  6003. }
  6004. include(context, includeChildrenRecursively) {
  6005. super.include(context, includeChildrenRecursively);
  6006. this.id?.include();
  6007. const hasArguments = this.scope.argumentsVariable.included;
  6008. for (const parameter of this.params) {
  6009. if (!(parameter instanceof Identifier) || hasArguments) {
  6010. parameter.include(context, includeChildrenRecursively);
  6011. }
  6012. }
  6013. }
  6014. initialise() {
  6015. super.initialise();
  6016. this.id?.declare('function', this);
  6017. }
  6018. addArgumentToBeDeoptimized(argument) {
  6019. this.scope.argumentsVariable.addArgumentToBeDeoptimized(argument);
  6020. }
  6021. getObjectEntity() {
  6022. if (this.objectEntity !== null) {
  6023. return this.objectEntity;
  6024. }
  6025. return (this.objectEntity = new ObjectEntity([
  6026. {
  6027. key: 'prototype',
  6028. kind: 'init',
  6029. property: new ObjectEntity([], OBJECT_PROTOTYPE)
  6030. }
  6031. ], OBJECT_PROTOTYPE));
  6032. }
  6033. }
  6034. class FunctionDeclaration extends FunctionNode {
  6035. initialise() {
  6036. super.initialise();
  6037. if (this.id !== null) {
  6038. this.id.variable.isId = true;
  6039. }
  6040. }
  6041. onlyFunctionCallUsed() {
  6042. // call super.onlyFunctionCallUsed for export default anonymous function
  6043. return this.id?.variable.getOnlyFunctionCallUsed() ?? super.onlyFunctionCallUsed();
  6044. }
  6045. parseNode(esTreeNode) {
  6046. if (esTreeNode.id !== null) {
  6047. this.id = new Identifier(this, this.scope.parent).parseNode(esTreeNode.id);
  6048. }
  6049. return super.parseNode(esTreeNode);
  6050. }
  6051. }
  6052. // The header ends at the first non-white-space after "default"
  6053. function getDeclarationStart(code, start) {
  6054. return findNonWhiteSpace(code, findFirstOccurrenceOutsideComment(code, 'default', start) + 7);
  6055. }
  6056. function getFunctionIdInsertPosition(code, start) {
  6057. const declarationEnd = findFirstOccurrenceOutsideComment(code, 'function', start) + 'function'.length;
  6058. code = code.slice(declarationEnd, findFirstOccurrenceOutsideComment(code, '(', declarationEnd));
  6059. const generatorStarPos = findFirstOccurrenceOutsideComment(code, '*');
  6060. if (generatorStarPos === -1) {
  6061. return declarationEnd;
  6062. }
  6063. return declarationEnd + generatorStarPos + 1;
  6064. }
  6065. class ExportDefaultDeclaration extends NodeBase {
  6066. include(context, includeChildrenRecursively) {
  6067. super.include(context, includeChildrenRecursively);
  6068. if (includeChildrenRecursively) {
  6069. this.scope.context.includeVariableInModule(this.variable);
  6070. }
  6071. }
  6072. initialise() {
  6073. super.initialise();
  6074. const declaration = this.declaration;
  6075. this.declarationName =
  6076. (declaration.id && declaration.id.name) || this.declaration.name;
  6077. this.variable = this.scope.addExportDefaultDeclaration(this.declarationName || this.scope.context.getModuleName(), this, this.scope.context);
  6078. this.scope.context.addExport(this);
  6079. }
  6080. removeAnnotations(code) {
  6081. this.declaration.removeAnnotations(code);
  6082. }
  6083. render(code, options, nodeRenderOptions) {
  6084. const { start, end } = nodeRenderOptions;
  6085. const declarationStart = getDeclarationStart(code.original, this.start);
  6086. if (this.declaration instanceof FunctionDeclaration) {
  6087. this.renderNamedDeclaration(code, declarationStart, this.declaration.id === null
  6088. ? getFunctionIdInsertPosition(code.original, declarationStart)
  6089. : null, options);
  6090. }
  6091. else if (this.declaration instanceof ClassDeclaration) {
  6092. this.renderNamedDeclaration(code, declarationStart, this.declaration.id === null
  6093. ? findFirstOccurrenceOutsideComment(code.original, 'class', start) + 'class'.length
  6094. : null, options);
  6095. }
  6096. else if (this.variable.getOriginalVariable() !== this.variable) {
  6097. // Remove altogether to prevent re-declaring the same variable
  6098. treeshakeNode(this, code, start, end);
  6099. return;
  6100. }
  6101. else if (this.variable.included) {
  6102. this.renderVariableDeclaration(code, declarationStart, options);
  6103. }
  6104. else {
  6105. code.remove(this.start, declarationStart);
  6106. this.declaration.render(code, options, {
  6107. renderedSurroundingElement: ExpressionStatement$1
  6108. });
  6109. if (code.original[this.end - 1] !== ';') {
  6110. code.appendLeft(this.end, ';');
  6111. }
  6112. return;
  6113. }
  6114. this.declaration.render(code, options);
  6115. }
  6116. applyDeoptimizations() { }
  6117. renderNamedDeclaration(code, declarationStart, idInsertPosition, options) {
  6118. const { exportNamesByVariable, format, snippets: { getPropertyAccess } } = options;
  6119. const name = this.variable.getName(getPropertyAccess);
  6120. // Remove `export default`
  6121. code.remove(this.start, declarationStart);
  6122. if (idInsertPosition !== null) {
  6123. code.appendLeft(idInsertPosition, ` ${name}`);
  6124. }
  6125. if (format === 'system' &&
  6126. this.declaration instanceof ClassDeclaration &&
  6127. exportNamesByVariable.has(this.variable)) {
  6128. code.appendLeft(this.end, ` ${getSystemExportStatement([this.variable], options)};`);
  6129. }
  6130. }
  6131. renderVariableDeclaration(code, declarationStart, { format, exportNamesByVariable, snippets: { cnst, getPropertyAccess } }) {
  6132. const hasTrailingSemicolon = code.original.charCodeAt(this.end - 1) === 59; /*";"*/
  6133. const systemExportNames = format === 'system' && exportNamesByVariable.get(this.variable);
  6134. if (systemExportNames) {
  6135. code.overwrite(this.start, declarationStart, `${cnst} ${this.variable.getName(getPropertyAccess)} = exports(${JSON.stringify(systemExportNames[0])}, `);
  6136. code.appendRight(hasTrailingSemicolon ? this.end - 1 : this.end, ')' + (hasTrailingSemicolon ? '' : ';'));
  6137. }
  6138. else {
  6139. code.overwrite(this.start, declarationStart, `${cnst} ${this.variable.getName(getPropertyAccess)} = `);
  6140. if (!hasTrailingSemicolon) {
  6141. code.appendLeft(this.end, ';');
  6142. }
  6143. }
  6144. }
  6145. }
  6146. ExportDefaultDeclaration.prototype.needsBoundaries = true;
  6147. const needsEscapeRegEx = /[\n\r'\\\u2028\u2029]/;
  6148. const quoteNewlineRegEx = /([\n\r'\u2028\u2029])/g;
  6149. const backSlashRegEx = /\\/g;
  6150. function escapeId(id) {
  6151. if (!needsEscapeRegEx.test(id))
  6152. return id;
  6153. return id.replace(backSlashRegEx, '\\\\').replace(quoteNewlineRegEx, '\\$1');
  6154. }
  6155. const INTEROP_DEFAULT_VARIABLE = '_interopDefault';
  6156. const INTEROP_DEFAULT_COMPAT_VARIABLE = '_interopDefaultCompat';
  6157. const INTEROP_NAMESPACE_VARIABLE = '_interopNamespace';
  6158. const INTEROP_NAMESPACE_COMPAT_VARIABLE = '_interopNamespaceCompat';
  6159. const INTEROP_NAMESPACE_DEFAULT_VARIABLE = '_interopNamespaceDefault';
  6160. const INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE = '_interopNamespaceDefaultOnly';
  6161. const MERGE_NAMESPACES_VARIABLE = '_mergeNamespaces';
  6162. const DOCUMENT_CURRENT_SCRIPT = '_documentCurrentScript';
  6163. const defaultInteropHelpersByInteropType = {
  6164. auto: INTEROP_DEFAULT_VARIABLE,
  6165. compat: INTEROP_DEFAULT_COMPAT_VARIABLE,
  6166. default: null,
  6167. defaultOnly: null,
  6168. esModule: null
  6169. };
  6170. const isDefaultAProperty = (interopType, externalLiveBindings) => interopType === 'esModule' ||
  6171. (externalLiveBindings && (interopType === 'auto' || interopType === 'compat'));
  6172. const namespaceInteropHelpersByInteropType = {
  6173. auto: INTEROP_NAMESPACE_VARIABLE,
  6174. compat: INTEROP_NAMESPACE_COMPAT_VARIABLE,
  6175. default: INTEROP_NAMESPACE_DEFAULT_VARIABLE,
  6176. defaultOnly: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE,
  6177. esModule: null
  6178. };
  6179. const canDefaultBeTakenFromNamespace = (interopType, externalLiveBindings) => interopType !== 'esModule' && isDefaultAProperty(interopType, externalLiveBindings);
  6180. const getHelpersBlock = (additionalHelpers, accessedGlobals, indent, snippets, liveBindings, freeze, symbols) => {
  6181. const usedHelpers = new Set(additionalHelpers);
  6182. for (const variable of HELPER_NAMES) {
  6183. if (accessedGlobals.has(variable)) {
  6184. usedHelpers.add(variable);
  6185. }
  6186. }
  6187. return HELPER_NAMES.map(variable => usedHelpers.has(variable)
  6188. ? HELPER_GENERATORS[variable](indent, snippets, liveBindings, freeze, symbols, usedHelpers)
  6189. : '').join('');
  6190. };
  6191. const HELPER_GENERATORS = {
  6192. [DOCUMENT_CURRENT_SCRIPT](_t, { _, n }) {
  6193. return `var ${DOCUMENT_CURRENT_SCRIPT}${_}=${_}typeof document${_}!==${_}'undefined'${_}?${_}document.currentScript${_}:${_}null;${n}`;
  6194. },
  6195. [INTEROP_DEFAULT_COMPAT_VARIABLE](_t, snippets, liveBindings) {
  6196. const { _, getDirectReturnFunction, n } = snippets;
  6197. const [left, right] = getDirectReturnFunction(['e'], {
  6198. functionReturn: true,
  6199. lineBreakIndent: null,
  6200. name: INTEROP_DEFAULT_COMPAT_VARIABLE
  6201. });
  6202. return (`${left}${getIsCompatNamespace(snippets)}${_}?${_}` +
  6203. `${liveBindings ? getDefaultLiveBinding(snippets) : getDefaultStatic(snippets)}${right}${n}${n}`);
  6204. },
  6205. [INTEROP_DEFAULT_VARIABLE](_t, snippets, liveBindings) {
  6206. const { _, getDirectReturnFunction, n } = snippets;
  6207. const [left, right] = getDirectReturnFunction(['e'], {
  6208. functionReturn: true,
  6209. lineBreakIndent: null,
  6210. name: INTEROP_DEFAULT_VARIABLE
  6211. });
  6212. return (`${left}e${_}&&${_}e.__esModule${_}?${_}` +
  6213. `${liveBindings ? getDefaultLiveBinding(snippets) : getDefaultStatic(snippets)}${right}${n}${n}`);
  6214. },
  6215. [INTEROP_NAMESPACE_COMPAT_VARIABLE](t, snippets, liveBindings, freeze, symbols, usedHelpers) {
  6216. const { _, getDirectReturnFunction, n } = snippets;
  6217. if (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)) {
  6218. const [left, right] = getDirectReturnFunction(['e'], {
  6219. functionReturn: true,
  6220. lineBreakIndent: null,
  6221. name: INTEROP_NAMESPACE_COMPAT_VARIABLE
  6222. });
  6223. return `${left}${getIsCompatNamespace(snippets)}${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${right}${n}${n}`;
  6224. }
  6225. return (`function ${INTEROP_NAMESPACE_COMPAT_VARIABLE}(e)${_}{${n}` +
  6226. `${t}if${_}(${getIsCompatNamespace(snippets)})${_}return e;${n}` +
  6227. createNamespaceObject(t, t, snippets, liveBindings, freeze, symbols) +
  6228. `}${n}${n}`);
  6229. },
  6230. [INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE](_t, snippets, _liveBindings, freeze, symbols) {
  6231. const { getDirectReturnFunction, getObject, n, _ } = snippets;
  6232. const [left, right] = getDirectReturnFunction(['e'], {
  6233. functionReturn: true,
  6234. lineBreakIndent: null,
  6235. name: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE
  6236. });
  6237. return `${left}${getFrozen(freeze, getWithToStringTag(symbols, getObject([
  6238. [null, `__proto__:${_}null`],
  6239. ['default', 'e']
  6240. ], { lineBreakIndent: null }), snippets))}${right}${n}${n}`;
  6241. },
  6242. [INTEROP_NAMESPACE_DEFAULT_VARIABLE](t, snippets, liveBindings, freeze, symbols) {
  6243. const { _, n } = snippets;
  6244. return (`function ${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${_}{${n}` +
  6245. createNamespaceObject(t, t, snippets, liveBindings, freeze, symbols) +
  6246. `}${n}${n}`);
  6247. },
  6248. [INTEROP_NAMESPACE_VARIABLE](t, snippets, liveBindings, freeze, symbols, usedHelpers) {
  6249. const { _, getDirectReturnFunction, n } = snippets;
  6250. if (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)) {
  6251. const [left, right] = getDirectReturnFunction(['e'], {
  6252. functionReturn: true,
  6253. lineBreakIndent: null,
  6254. name: INTEROP_NAMESPACE_VARIABLE
  6255. });
  6256. return `${left}e${_}&&${_}e.__esModule${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${right}${n}${n}`;
  6257. }
  6258. return (`function ${INTEROP_NAMESPACE_VARIABLE}(e)${_}{${n}` +
  6259. `${t}if${_}(e${_}&&${_}e.__esModule)${_}return e;${n}` +
  6260. createNamespaceObject(t, t, snippets, liveBindings, freeze, symbols) +
  6261. `}${n}${n}`);
  6262. },
  6263. [MERGE_NAMESPACES_VARIABLE](t, snippets, liveBindings, freeze, symbols) {
  6264. const { _, cnst, n } = snippets;
  6265. const useForEach = cnst === 'var' && liveBindings;
  6266. return (`function ${MERGE_NAMESPACES_VARIABLE}(n, m)${_}{${n}` +
  6267. `${t}${loopOverNamespaces(`{${n}` +
  6268. `${t}${t}${t}if${_}(k${_}!==${_}'default'${_}&&${_}!(k in n))${_}{${n}` +
  6269. (liveBindings
  6270. ? useForEach
  6271. ? copyOwnPropertyLiveBinding
  6272. : copyPropertyLiveBinding
  6273. : copyPropertyStatic)(t, t + t + t + t, snippets) +
  6274. `${t}${t}${t}}${n}` +
  6275. `${t}${t}}`, useForEach, t, snippets)}${n}` +
  6276. `${t}return ${getFrozen(freeze, getWithToStringTag(symbols, 'n', snippets))};${n}` +
  6277. `}${n}${n}`);
  6278. }
  6279. };
  6280. const getDefaultLiveBinding = ({ _, getObject }) => `e${_}:${_}${getObject([['default', 'e']], { lineBreakIndent: null })}`;
  6281. const getDefaultStatic = ({ _, getPropertyAccess }) => `e${getPropertyAccess('default')}${_}:${_}e`;
  6282. const getIsCompatNamespace = ({ _ }) => `e${_}&&${_}typeof e${_}===${_}'object'${_}&&${_}'default'${_}in e`;
  6283. const createNamespaceObject = (t, index, snippets, liveBindings, freeze, symbols) => {
  6284. const { _, cnst, getObject, getPropertyAccess, n, s } = snippets;
  6285. const copyProperty = `{${n}` +
  6286. (liveBindings ? copyNonDefaultOwnPropertyLiveBinding : copyPropertyStatic)(t, index + t + t, snippets) +
  6287. `${index}${t}}`;
  6288. return (`${index}${cnst} n${_}=${_}Object.create(null${symbols ? `,${_}{${_}[Symbol.toStringTag]:${_}${getToStringTagValue(getObject)}${_}}` : ''});${n}` +
  6289. `${index}if${_}(e)${_}{${n}` +
  6290. `${index}${t}${loopOverKeys(copyProperty, !liveBindings, snippets)}${n}` +
  6291. `${index}}${n}` +
  6292. `${index}n${getPropertyAccess('default')}${_}=${_}e;${n}` +
  6293. `${index}return ${getFrozen(freeze, 'n')}${s}${n}`);
  6294. };
  6295. const loopOverKeys = (body, allowVariableLoopVariable, { _, cnst, getFunctionIntro, s }) => cnst !== 'var' || allowVariableLoopVariable
  6296. ? `for${_}(${cnst} k in e)${_}${body}`
  6297. : `Object.keys(e).forEach(${getFunctionIntro(['k'], {
  6298. isAsync: false,
  6299. name: null
  6300. })}${body})${s}`;
  6301. const loopOverNamespaces = (body, useForEach, t, { _, cnst, getDirectReturnFunction, getFunctionIntro, n }) => {
  6302. if (useForEach) {
  6303. const [left, right] = getDirectReturnFunction(['e'], {
  6304. functionReturn: false,
  6305. lineBreakIndent: { base: t, t },
  6306. name: null
  6307. });
  6308. return (`m.forEach(${left}` +
  6309. `e${_}&&${_}typeof e${_}!==${_}'string'${_}&&${_}!Array.isArray(e)${_}&&${_}Object.keys(e).forEach(${getFunctionIntro(['k'], {
  6310. isAsync: false,
  6311. name: null
  6312. })}${body})${right});`);
  6313. }
  6314. return (`for${_}(var i${_}=${_}0;${_}i${_}<${_}m.length;${_}i++)${_}{${n}` +
  6315. `${t}${t}${cnst} e${_}=${_}m[i];${n}` +
  6316. `${t}${t}if${_}(typeof e${_}!==${_}'string'${_}&&${_}!Array.isArray(e))${_}{${_}for${_}(${cnst} k in e)${_}${body}${_}}${n}${t}}`);
  6317. };
  6318. const copyNonDefaultOwnPropertyLiveBinding = (t, index, snippets) => {
  6319. const { _, n } = snippets;
  6320. return (`${index}if${_}(k${_}!==${_}'default')${_}{${n}` +
  6321. copyOwnPropertyLiveBinding(t, index + t, snippets) +
  6322. `${index}}${n}`);
  6323. };
  6324. const copyOwnPropertyLiveBinding = (t, index, { _, cnst, getDirectReturnFunction, n }) => {
  6325. const [left, right] = getDirectReturnFunction([], {
  6326. functionReturn: true,
  6327. lineBreakIndent: null,
  6328. name: null
  6329. });
  6330. return (`${index}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
  6331. `${index}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
  6332. `${index}${t}enumerable:${_}true,${n}` +
  6333. `${index}${t}get:${_}${left}e[k]${right}${n}` +
  6334. `${index}});${n}`);
  6335. };
  6336. const copyPropertyLiveBinding = (t, index, { _, cnst, getDirectReturnFunction, n }) => {
  6337. const [left, right] = getDirectReturnFunction([], {
  6338. functionReturn: true,
  6339. lineBreakIndent: null,
  6340. name: null
  6341. });
  6342. return (`${index}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
  6343. `${index}if${_}(d)${_}{${n}` +
  6344. `${index}${t}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
  6345. `${index}${t}${t}enumerable:${_}true,${n}` +
  6346. `${index}${t}${t}get:${_}${left}e[k]${right}${n}` +
  6347. `${index}${t}});${n}` +
  6348. `${index}}${n}`);
  6349. };
  6350. const copyPropertyStatic = (_t, index, { _, n }) => `${index}n[k]${_}=${_}e[k];${n}`;
  6351. const getFrozen = (freeze, fragment) => freeze ? `Object.freeze(${fragment})` : fragment;
  6352. const getWithToStringTag = (symbols, fragment, { _, getObject }) => symbols
  6353. ? `Object.defineProperty(${fragment},${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)})`
  6354. : fragment;
  6355. const HELPER_NAMES = Object.keys(HELPER_GENERATORS);
  6356. function getToStringTagValue(getObject) {
  6357. return getObject([['value', "'Module'"]], {
  6358. lineBreakIndent: null
  6359. });
  6360. }
  6361. class Literal extends NodeBase {
  6362. deoptimizeArgumentsOnInteractionAtPath() { }
  6363. getLiteralValueAtPath(path) {
  6364. if (path.length > 0 ||
  6365. // unknown literals can also be null but do not start with an "n"
  6366. (this.value === null && this.scope.context.code.charCodeAt(this.start) !== 110) ||
  6367. typeof this.value === 'bigint' ||
  6368. // to support shims for regular expressions
  6369. this.scope.context.code.charCodeAt(this.start) === 47) {
  6370. return UnknownValue;
  6371. }
  6372. return this.value;
  6373. }
  6374. getReturnExpressionWhenCalledAtPath(path) {
  6375. if (path.length !== 1)
  6376. return UNKNOWN_RETURN_EXPRESSION;
  6377. return getMemberReturnExpressionWhenCalled(this.members, path[0]);
  6378. }
  6379. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6380. switch (interaction.type) {
  6381. case INTERACTION_ACCESSED: {
  6382. return path.length > (this.value === null ? 0 : 1);
  6383. }
  6384. case INTERACTION_ASSIGNED: {
  6385. return true;
  6386. }
  6387. case INTERACTION_CALLED: {
  6388. if (this.included &&
  6389. this.value instanceof RegExp &&
  6390. (this.value.global || this.value.sticky)) {
  6391. return true;
  6392. }
  6393. return (path.length !== 1 ||
  6394. hasMemberEffectWhenCalled(this.members, path[0], interaction, context));
  6395. }
  6396. }
  6397. }
  6398. initialise() {
  6399. super.initialise();
  6400. this.members = getLiteralMembersForValue(this.value);
  6401. }
  6402. parseNode(esTreeNode) {
  6403. this.value = esTreeNode.value;
  6404. this.regex = esTreeNode.regex;
  6405. return super.parseNode(esTreeNode);
  6406. }
  6407. render(code) {
  6408. if (typeof this.value === 'string') {
  6409. code.indentExclusionRanges.push([this.start + 1, this.end - 1]);
  6410. }
  6411. }
  6412. }
  6413. function getChainElementLiteralValueAtPath(element, object, path, recursionTracker, origin) {
  6414. if ('getLiteralValueAtPathAsChainElement' in object) {
  6415. const calleeValue = object.getLiteralValueAtPathAsChainElement(EMPTY_PATH, SHARED_RECURSION_TRACKER, origin);
  6416. if (calleeValue === IS_SKIPPED_CHAIN || (element.optional && calleeValue == null)) {
  6417. return IS_SKIPPED_CHAIN;
  6418. }
  6419. }
  6420. else if (element.optional &&
  6421. object.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, origin) == null) {
  6422. return IS_SKIPPED_CHAIN;
  6423. }
  6424. return element.getLiteralValueAtPath(path, recursionTracker, origin);
  6425. }
  6426. // To avoid infinite recursions
  6427. const MAX_PATH_DEPTH = 7;
  6428. function getResolvablePropertyKey(memberExpression) {
  6429. return memberExpression.computed
  6430. ? getResolvableComputedPropertyKey(memberExpression.property)
  6431. : memberExpression.property.name;
  6432. }
  6433. function getResolvableComputedPropertyKey(propertyKey) {
  6434. if (propertyKey instanceof Literal) {
  6435. return String(propertyKey.value);
  6436. }
  6437. return null;
  6438. }
  6439. function getPathIfNotComputed(memberExpression) {
  6440. const nextPathKey = memberExpression.propertyKey;
  6441. const object = memberExpression.object;
  6442. if (typeof nextPathKey === 'string') {
  6443. if (object instanceof Identifier) {
  6444. return [
  6445. { key: object.name, pos: object.start },
  6446. { key: nextPathKey, pos: memberExpression.property.start }
  6447. ];
  6448. }
  6449. if (object instanceof MemberExpression) {
  6450. const parentPath = getPathIfNotComputed(object);
  6451. return (parentPath && [...parentPath, { key: nextPathKey, pos: memberExpression.property.start }]);
  6452. }
  6453. }
  6454. return null;
  6455. }
  6456. function getStringFromPath(path) {
  6457. let pathString = path[0].key;
  6458. for (let index = 1; index < path.length; index++) {
  6459. pathString += '.' + path[index].key;
  6460. }
  6461. return pathString;
  6462. }
  6463. class MemberExpression extends NodeBase {
  6464. constructor() {
  6465. super(...arguments);
  6466. this.variable = null;
  6467. this.expressionsToBeDeoptimized = [];
  6468. }
  6469. get computed() {
  6470. return isFlagSet(this.flags, 1024 /* Flag.computed */);
  6471. }
  6472. set computed(value) {
  6473. this.flags = setFlag(this.flags, 1024 /* Flag.computed */, value);
  6474. }
  6475. get optional() {
  6476. return isFlagSet(this.flags, 128 /* Flag.optional */);
  6477. }
  6478. set optional(value) {
  6479. this.flags = setFlag(this.flags, 128 /* Flag.optional */, value);
  6480. }
  6481. get assignmentDeoptimized() {
  6482. return isFlagSet(this.flags, 16 /* Flag.assignmentDeoptimized */);
  6483. }
  6484. set assignmentDeoptimized(value) {
  6485. this.flags = setFlag(this.flags, 16 /* Flag.assignmentDeoptimized */, value);
  6486. }
  6487. get bound() {
  6488. return isFlagSet(this.flags, 32 /* Flag.bound */);
  6489. }
  6490. set bound(value) {
  6491. this.flags = setFlag(this.flags, 32 /* Flag.bound */, value);
  6492. }
  6493. get isUndefined() {
  6494. return isFlagSet(this.flags, 64 /* Flag.isUndefined */);
  6495. }
  6496. set isUndefined(value) {
  6497. this.flags = setFlag(this.flags, 64 /* Flag.isUndefined */, value);
  6498. }
  6499. bind() {
  6500. this.bound = true;
  6501. const path = getPathIfNotComputed(this);
  6502. const baseVariable = path && this.scope.findVariable(path[0].key);
  6503. if (baseVariable?.isNamespace) {
  6504. const resolvedVariable = resolveNamespaceVariables(baseVariable, path.slice(1), this.scope.context);
  6505. if (!resolvedVariable) {
  6506. super.bind();
  6507. }
  6508. else if (resolvedVariable === 'undefined') {
  6509. this.isUndefined = true;
  6510. }
  6511. else {
  6512. this.variable = resolvedVariable;
  6513. this.scope.addNamespaceMemberAccess(getStringFromPath(path), resolvedVariable);
  6514. }
  6515. }
  6516. else {
  6517. super.bind();
  6518. }
  6519. }
  6520. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  6521. if (this.variable) {
  6522. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  6523. }
  6524. else if (!this.isUndefined) {
  6525. if (path.length < MAX_PATH_DEPTH) {
  6526. this.object.deoptimizeArgumentsOnInteractionAtPath(interaction, [this.getPropertyKey(), ...path], recursionTracker);
  6527. }
  6528. else {
  6529. deoptimizeInteraction(interaction);
  6530. }
  6531. }
  6532. }
  6533. deoptimizeCache() {
  6534. const { expressionsToBeDeoptimized, object } = this;
  6535. this.expressionsToBeDeoptimized = EMPTY_ARRAY;
  6536. this.propertyKey = UnknownKey;
  6537. object.deoptimizePath(UNKNOWN_PATH);
  6538. for (const expression of expressionsToBeDeoptimized) {
  6539. expression.deoptimizeCache();
  6540. }
  6541. }
  6542. deoptimizePath(path) {
  6543. if (path.length === 0)
  6544. this.disallowNamespaceReassignment();
  6545. if (this.variable) {
  6546. this.variable.deoptimizePath(path);
  6547. }
  6548. else if (!this.isUndefined && path.length < MAX_PATH_DEPTH) {
  6549. const propertyKey = this.getPropertyKey();
  6550. this.object.deoptimizePath([
  6551. propertyKey === UnknownKey ? UnknownNonAccessorKey : propertyKey,
  6552. ...path
  6553. ]);
  6554. }
  6555. }
  6556. getLiteralValueAtPath(path, recursionTracker, origin) {
  6557. if (this.variable) {
  6558. return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
  6559. }
  6560. if (this.isUndefined) {
  6561. return undefined;
  6562. }
  6563. if (this.propertyKey !== UnknownKey && path.length < MAX_PATH_DEPTH) {
  6564. this.expressionsToBeDeoptimized.push(origin);
  6565. return this.object.getLiteralValueAtPath([this.getPropertyKey(), ...path], recursionTracker, origin);
  6566. }
  6567. return UnknownValue;
  6568. }
  6569. getLiteralValueAtPathAsChainElement(path, recursionTracker, origin) {
  6570. if (this.variable) {
  6571. return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
  6572. }
  6573. if (this.isUndefined) {
  6574. return undefined;
  6575. }
  6576. return getChainElementLiteralValueAtPath(this, this.object, path, recursionTracker, origin);
  6577. }
  6578. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  6579. if (this.variable) {
  6580. return this.variable.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  6581. }
  6582. if (this.isUndefined) {
  6583. return [UNDEFINED_EXPRESSION, false];
  6584. }
  6585. if (this.propertyKey !== UnknownKey && path.length < MAX_PATH_DEPTH) {
  6586. this.expressionsToBeDeoptimized.push(origin);
  6587. return this.object.getReturnExpressionWhenCalledAtPath([this.getPropertyKey(), ...path], interaction, recursionTracker, origin);
  6588. }
  6589. return UNKNOWN_RETURN_EXPRESSION;
  6590. }
  6591. hasEffects(context) {
  6592. if (!this.deoptimized)
  6593. this.applyDeoptimizations();
  6594. return (this.property.hasEffects(context) ||
  6595. this.object.hasEffects(context) ||
  6596. this.hasAccessEffect(context));
  6597. }
  6598. hasEffectsAsChainElement(context) {
  6599. if (this.variable || this.isUndefined)
  6600. return this.hasEffects(context);
  6601. const objectHasEffects = 'hasEffectsAsChainElement' in this.object
  6602. ? this.object.hasEffectsAsChainElement(context)
  6603. : this.object.hasEffects(context);
  6604. if (objectHasEffects === IS_SKIPPED_CHAIN)
  6605. return IS_SKIPPED_CHAIN;
  6606. if (this.optional &&
  6607. this.object.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) == null) {
  6608. return objectHasEffects || IS_SKIPPED_CHAIN;
  6609. }
  6610. // We only apply deoptimizations lazily once we know we are not skipping
  6611. if (!this.deoptimized)
  6612. this.applyDeoptimizations();
  6613. return objectHasEffects || this.property.hasEffects(context) || this.hasAccessEffect(context);
  6614. }
  6615. hasEffectsAsAssignmentTarget(context, checkAccess) {
  6616. if (checkAccess && !this.deoptimized)
  6617. this.applyDeoptimizations();
  6618. if (!this.assignmentDeoptimized)
  6619. this.applyAssignmentDeoptimization();
  6620. return (this.property.hasEffects(context) ||
  6621. this.object.hasEffects(context) ||
  6622. (checkAccess && this.hasAccessEffect(context)) ||
  6623. this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
  6624. }
  6625. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6626. if (this.variable) {
  6627. return this.variable.hasEffectsOnInteractionAtPath(path, interaction, context);
  6628. }
  6629. if (this.isUndefined) {
  6630. return true;
  6631. }
  6632. if (path.length < MAX_PATH_DEPTH) {
  6633. return this.object.hasEffectsOnInteractionAtPath([this.getPropertyKey(), ...path], interaction, context);
  6634. }
  6635. return true;
  6636. }
  6637. include(context, includeChildrenRecursively) {
  6638. if (!this.deoptimized)
  6639. this.applyDeoptimizations();
  6640. this.includeProperties(context, includeChildrenRecursively);
  6641. }
  6642. includeAsAssignmentTarget(context, includeChildrenRecursively, deoptimizeAccess) {
  6643. if (!this.assignmentDeoptimized)
  6644. this.applyAssignmentDeoptimization();
  6645. if (deoptimizeAccess) {
  6646. this.include(context, includeChildrenRecursively);
  6647. }
  6648. else {
  6649. this.includeProperties(context, includeChildrenRecursively);
  6650. }
  6651. }
  6652. includeCallArguments(context, parameters) {
  6653. if (this.variable) {
  6654. this.variable.includeCallArguments(context, parameters);
  6655. }
  6656. else {
  6657. super.includeCallArguments(context, parameters);
  6658. }
  6659. }
  6660. initialise() {
  6661. super.initialise();
  6662. this.propertyKey = getResolvablePropertyKey(this);
  6663. this.accessInteraction = { args: [this.object], type: INTERACTION_ACCESSED };
  6664. }
  6665. render(code, options, { renderedParentType, isCalleeOfRenderedParent, renderedSurroundingElement } = BLANK) {
  6666. if (this.variable || this.isUndefined) {
  6667. const { snippets: { getPropertyAccess } } = options;
  6668. let replacement = this.variable ? this.variable.getName(getPropertyAccess) : 'undefined';
  6669. if (renderedParentType && isCalleeOfRenderedParent)
  6670. replacement = '0, ' + replacement;
  6671. code.overwrite(this.start, this.end, replacement, {
  6672. contentOnly: true,
  6673. storeName: true
  6674. });
  6675. }
  6676. else {
  6677. if (renderedParentType && isCalleeOfRenderedParent) {
  6678. code.appendRight(this.start, '0, ');
  6679. }
  6680. this.object.render(code, options, { renderedSurroundingElement });
  6681. this.property.render(code, options);
  6682. }
  6683. }
  6684. setAssignedValue(value) {
  6685. this.assignmentInteraction = {
  6686. args: [this.object, value],
  6687. type: INTERACTION_ASSIGNED
  6688. };
  6689. }
  6690. applyDeoptimizations() {
  6691. this.deoptimized = true;
  6692. const { propertyReadSideEffects } = this.scope.context.options
  6693. .treeshake;
  6694. if (
  6695. // Namespaces are not bound and should not be deoptimized
  6696. this.bound &&
  6697. propertyReadSideEffects &&
  6698. !(this.variable || this.isUndefined)) {
  6699. const propertyKey = this.getPropertyKey();
  6700. this.object.deoptimizeArgumentsOnInteractionAtPath(this.accessInteraction, [propertyKey], SHARED_RECURSION_TRACKER);
  6701. this.scope.context.requestTreeshakingPass();
  6702. }
  6703. if (this.variable) {
  6704. this.variable.addUsedPlace(this);
  6705. this.scope.context.requestTreeshakingPass();
  6706. }
  6707. }
  6708. applyAssignmentDeoptimization() {
  6709. this.assignmentDeoptimized = true;
  6710. const { propertyReadSideEffects } = this.scope.context.options
  6711. .treeshake;
  6712. if (
  6713. // Namespaces are not bound and should not be deoptimized
  6714. this.bound &&
  6715. propertyReadSideEffects &&
  6716. !(this.variable || this.isUndefined)) {
  6717. this.object.deoptimizeArgumentsOnInteractionAtPath(this.assignmentInteraction, [this.getPropertyKey()], SHARED_RECURSION_TRACKER);
  6718. this.scope.context.requestTreeshakingPass();
  6719. }
  6720. }
  6721. disallowNamespaceReassignment() {
  6722. if (this.object instanceof Identifier) {
  6723. const variable = this.scope.findVariable(this.object.name);
  6724. if (variable.isNamespace) {
  6725. if (this.variable) {
  6726. this.scope.context.includeVariableInModule(this.variable);
  6727. }
  6728. this.scope.context.log(LOGLEVEL_WARN, logIllegalImportReassignment(this.object.name, this.scope.context.module.id), this.start);
  6729. }
  6730. }
  6731. }
  6732. getPropertyKey() {
  6733. if (this.propertyKey === null) {
  6734. this.propertyKey = UnknownKey;
  6735. const value = this.property.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  6736. return (this.propertyKey =
  6737. value === SymbolToStringTag
  6738. ? value
  6739. : typeof value === 'symbol'
  6740. ? UnknownKey
  6741. : String(value));
  6742. }
  6743. return this.propertyKey;
  6744. }
  6745. hasAccessEffect(context) {
  6746. const { propertyReadSideEffects } = this.scope.context.options
  6747. .treeshake;
  6748. return (!(this.variable || this.isUndefined) &&
  6749. propertyReadSideEffects &&
  6750. (propertyReadSideEffects === 'always' ||
  6751. this.object.hasEffectsOnInteractionAtPath([this.getPropertyKey()], this.accessInteraction, context)));
  6752. }
  6753. includeProperties(context, includeChildrenRecursively) {
  6754. if (!this.included) {
  6755. this.included = true;
  6756. if (this.variable) {
  6757. this.scope.context.includeVariableInModule(this.variable);
  6758. }
  6759. }
  6760. this.object.include(context, includeChildrenRecursively);
  6761. this.property.include(context, includeChildrenRecursively);
  6762. }
  6763. }
  6764. function resolveNamespaceVariables(baseVariable, path, astContext) {
  6765. if (path.length === 0)
  6766. return baseVariable;
  6767. if (!baseVariable.isNamespace || baseVariable instanceof ExternalVariable)
  6768. return null;
  6769. const exportName = path[0].key;
  6770. const variable = baseVariable.context.traceExport(exportName);
  6771. if (!variable) {
  6772. if (path.length === 1) {
  6773. const fileName = baseVariable.context.fileName;
  6774. astContext.log(LOGLEVEL_WARN, logMissingExport(exportName, astContext.module.id, fileName), path[0].pos);
  6775. return 'undefined';
  6776. }
  6777. return null;
  6778. }
  6779. return resolveNamespaceVariables(variable, path.slice(1), astContext);
  6780. }
  6781. const FILE_PREFIX = 'ROLLUP_FILE_URL_';
  6782. const IMPORT = 'import';
  6783. class MetaProperty extends NodeBase {
  6784. constructor() {
  6785. super(...arguments);
  6786. this.metaProperty = null;
  6787. this.preliminaryChunkId = null;
  6788. this.referenceId = null;
  6789. }
  6790. getReferencedFileName(outputPluginDriver) {
  6791. const { meta: { name }, metaProperty } = this;
  6792. if (name === IMPORT && metaProperty?.startsWith(FILE_PREFIX)) {
  6793. return outputPluginDriver.getFileName(metaProperty.slice(FILE_PREFIX.length));
  6794. }
  6795. return null;
  6796. }
  6797. hasEffects() {
  6798. return false;
  6799. }
  6800. hasEffectsOnInteractionAtPath(path, { type }) {
  6801. return path.length > 1 || type !== INTERACTION_ACCESSED;
  6802. }
  6803. include() {
  6804. if (!this.included) {
  6805. this.included = true;
  6806. if (this.meta.name === IMPORT) {
  6807. this.scope.context.addImportMeta(this);
  6808. const parent = this.parent;
  6809. const metaProperty = (this.metaProperty =
  6810. parent instanceof MemberExpression && typeof parent.propertyKey === 'string'
  6811. ? parent.propertyKey
  6812. : null);
  6813. if (metaProperty?.startsWith(FILE_PREFIX)) {
  6814. this.referenceId = metaProperty.slice(FILE_PREFIX.length);
  6815. }
  6816. }
  6817. }
  6818. }
  6819. render(code, renderOptions) {
  6820. const { format, pluginDriver, snippets } = renderOptions;
  6821. const { scope: { context: { module } }, meta: { name }, metaProperty, parent, preliminaryChunkId, referenceId, start, end } = this;
  6822. const { id: moduleId } = module;
  6823. if (name !== IMPORT)
  6824. return;
  6825. const chunkId = preliminaryChunkId;
  6826. if (referenceId) {
  6827. const fileName = pluginDriver.getFileName(referenceId);
  6828. const relativePath = normalize(relative(dirname(chunkId), fileName));
  6829. const replacement = pluginDriver.hookFirstSync('resolveFileUrl', [
  6830. { chunkId, fileName, format, moduleId, referenceId, relativePath }
  6831. ]) || relativeUrlMechanisms[format](relativePath);
  6832. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  6833. return;
  6834. }
  6835. let replacement = pluginDriver.hookFirstSync('resolveImportMeta', [
  6836. metaProperty,
  6837. { chunkId, format, moduleId }
  6838. ]);
  6839. if (!replacement) {
  6840. replacement = importMetaMechanisms[format]?.(metaProperty, { chunkId, snippets });
  6841. renderOptions.accessedDocumentCurrentScript ||=
  6842. formatsMaybeAccessDocumentCurrentScript.includes(format) && replacement !== 'undefined';
  6843. }
  6844. if (typeof replacement === 'string') {
  6845. if (parent instanceof MemberExpression) {
  6846. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  6847. }
  6848. else {
  6849. code.overwrite(start, end, replacement, { contentOnly: true });
  6850. }
  6851. }
  6852. }
  6853. setResolution(format, accessedGlobalsByScope, preliminaryChunkId) {
  6854. this.preliminaryChunkId = preliminaryChunkId;
  6855. const accessedGlobals = (this.metaProperty?.startsWith(FILE_PREFIX) ? accessedFileUrlGlobals : accessedMetaUrlGlobals)[format];
  6856. if (accessedGlobals.length > 0) {
  6857. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  6858. }
  6859. }
  6860. }
  6861. const formatsMaybeAccessDocumentCurrentScript = ['cjs', 'iife', 'umd'];
  6862. const accessedMetaUrlGlobals = {
  6863. amd: ['document', 'module', 'URL'],
  6864. cjs: ['document', 'require', 'URL', DOCUMENT_CURRENT_SCRIPT],
  6865. es: [],
  6866. iife: ['document', 'URL', DOCUMENT_CURRENT_SCRIPT],
  6867. system: ['module'],
  6868. umd: ['document', 'require', 'URL', DOCUMENT_CURRENT_SCRIPT]
  6869. };
  6870. const accessedFileUrlGlobals = {
  6871. amd: ['document', 'require', 'URL'],
  6872. cjs: ['document', 'require', 'URL'],
  6873. es: [],
  6874. iife: ['document', 'URL'],
  6875. system: ['module', 'URL'],
  6876. umd: ['document', 'require', 'URL']
  6877. };
  6878. const getResolveUrl = (path, URL = 'URL') => `new ${URL}(${path}).href`;
  6879. 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`);
  6880. const getGenericImportMetaMechanism = (getUrl) => (property, { chunkId }) => {
  6881. const urlMechanism = getUrl(chunkId);
  6882. return property === null
  6883. ? `({ url: ${urlMechanism} })`
  6884. : property === 'url'
  6885. ? urlMechanism
  6886. : 'undefined';
  6887. };
  6888. const getFileUrlFromFullPath = (path) => `require('u' + 'rl').pathToFileURL(${path}).href`;
  6889. const getFileUrlFromRelativePath = (path) => getFileUrlFromFullPath(`__dirname + '/${escapeId(path)}'`);
  6890. 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)`;
  6891. const relativeUrlMechanisms = {
  6892. amd: relativePath => {
  6893. if (relativePath[0] !== '.')
  6894. relativePath = './' + relativePath;
  6895. return getResolveUrl(`require.toUrl('${escapeId(relativePath)}'), document.baseURI`);
  6896. },
  6897. cjs: relativePath => `(typeof document === 'undefined' ? ${getFileUrlFromRelativePath(relativePath)} : ${getRelativeUrlFromDocument(relativePath)})`,
  6898. es: relativePath => getResolveUrl(`'${escapeId(relativePath)}', import.meta.url`),
  6899. iife: relativePath => getRelativeUrlFromDocument(relativePath),
  6900. system: relativePath => getResolveUrl(`'${escapeId(relativePath)}', module.meta.url`),
  6901. umd: relativePath => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getFileUrlFromRelativePath(relativePath)} : ${getRelativeUrlFromDocument(relativePath, true)})`
  6902. };
  6903. const importMetaMechanisms = {
  6904. amd: getGenericImportMetaMechanism(() => getResolveUrl(`module.uri, document.baseURI`)),
  6905. cjs: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' ? ${getFileUrlFromFullPath('__filename')} : ${getUrlFromDocument(chunkId)})`),
  6906. iife: getGenericImportMetaMechanism(chunkId => getUrlFromDocument(chunkId)),
  6907. system: (property, { snippets: { getPropertyAccess } }) => property === null ? `module.meta` : `module.meta${getPropertyAccess(property)}`,
  6908. umd: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getFileUrlFromFullPath('__filename')} : ${getUrlFromDocument(chunkId, true)})`)
  6909. };
  6910. class UndefinedVariable extends Variable {
  6911. constructor() {
  6912. super('undefined');
  6913. }
  6914. getLiteralValueAtPath() {
  6915. return undefined;
  6916. }
  6917. }
  6918. class ExportDefaultVariable extends LocalVariable {
  6919. constructor(name, exportDefaultDeclaration, context) {
  6920. super(name, exportDefaultDeclaration, exportDefaultDeclaration.declaration, context, 'other');
  6921. this.hasId = false;
  6922. this.originalId = null;
  6923. this.originalVariable = null;
  6924. const declaration = exportDefaultDeclaration.declaration;
  6925. if ((declaration instanceof FunctionDeclaration || declaration instanceof ClassDeclaration) &&
  6926. declaration.id) {
  6927. this.hasId = true;
  6928. this.originalId = declaration.id;
  6929. }
  6930. else if (declaration instanceof Identifier) {
  6931. this.originalId = declaration;
  6932. }
  6933. }
  6934. addReference(identifier) {
  6935. if (!this.hasId) {
  6936. this.name = identifier.name;
  6937. }
  6938. }
  6939. addUsedPlace(usedPlace) {
  6940. const original = this.getOriginalVariable();
  6941. if (original === this) {
  6942. super.addUsedPlace(usedPlace);
  6943. }
  6944. else {
  6945. original.addUsedPlace(usedPlace);
  6946. }
  6947. }
  6948. forbidName(name) {
  6949. const original = this.getOriginalVariable();
  6950. if (original === this) {
  6951. super.forbidName(name);
  6952. }
  6953. else {
  6954. original.forbidName(name);
  6955. }
  6956. }
  6957. getAssignedVariableName() {
  6958. return (this.originalId && this.originalId.name) || null;
  6959. }
  6960. getBaseVariableName() {
  6961. const original = this.getOriginalVariable();
  6962. return original === this ? super.getBaseVariableName() : original.getBaseVariableName();
  6963. }
  6964. getDirectOriginalVariable() {
  6965. return this.originalId &&
  6966. (this.hasId ||
  6967. !(this.originalId.isPossibleTDZ() ||
  6968. this.originalId.variable.isReassigned ||
  6969. this.originalId.variable instanceof UndefinedVariable ||
  6970. // this avoids a circular dependency
  6971. 'syntheticNamespace' in this.originalId.variable))
  6972. ? this.originalId.variable
  6973. : null;
  6974. }
  6975. getName(getPropertyAccess) {
  6976. const original = this.getOriginalVariable();
  6977. return original === this
  6978. ? super.getName(getPropertyAccess)
  6979. : original.getName(getPropertyAccess);
  6980. }
  6981. getOriginalVariable() {
  6982. if (this.originalVariable)
  6983. return this.originalVariable;
  6984. // eslint-disable-next-line @typescript-eslint/no-this-alias
  6985. let original = this;
  6986. let currentVariable;
  6987. const checkedVariables = new Set();
  6988. do {
  6989. checkedVariables.add(original);
  6990. currentVariable = original;
  6991. original = currentVariable.getDirectOriginalVariable();
  6992. } while (original instanceof ExportDefaultVariable && !checkedVariables.has(original));
  6993. return (this.originalVariable = original || currentVariable);
  6994. }
  6995. }
  6996. class NamespaceVariable extends Variable {
  6997. constructor(context) {
  6998. super(context.getModuleName());
  6999. this.memberVariables = null;
  7000. this.mergedNamespaces = [];
  7001. this.referencedEarly = false;
  7002. this.references = [];
  7003. this.context = context;
  7004. this.module = context.module;
  7005. }
  7006. addReference(identifier) {
  7007. this.references.push(identifier);
  7008. this.name = identifier.name;
  7009. }
  7010. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  7011. if (path.length > 1 || (path.length === 1 && interaction.type === INTERACTION_CALLED)) {
  7012. const key = path[0];
  7013. if (typeof key === 'string') {
  7014. this.getMemberVariables()[key]?.deoptimizeArgumentsOnInteractionAtPath(interaction, path.slice(1), recursionTracker);
  7015. }
  7016. else {
  7017. deoptimizeInteraction(interaction);
  7018. }
  7019. }
  7020. }
  7021. deoptimizePath(path) {
  7022. if (path.length > 1) {
  7023. const key = path[0];
  7024. if (typeof key === 'string') {
  7025. this.getMemberVariables()[key]?.deoptimizePath(path.slice(1));
  7026. }
  7027. }
  7028. }
  7029. getLiteralValueAtPath(path) {
  7030. if (path[0] === SymbolToStringTag) {
  7031. return 'Module';
  7032. }
  7033. return UnknownValue;
  7034. }
  7035. getMemberVariables() {
  7036. if (this.memberVariables) {
  7037. return this.memberVariables;
  7038. }
  7039. const memberVariables = Object.create(null);
  7040. const sortedExports = [...this.context.getExports(), ...this.context.getReexports()].sort();
  7041. for (const name of sortedExports) {
  7042. if (name[0] !== '*' && name !== this.module.info.syntheticNamedExports) {
  7043. const exportedVariable = this.context.traceExport(name);
  7044. if (exportedVariable) {
  7045. memberVariables[name] = exportedVariable;
  7046. }
  7047. }
  7048. }
  7049. return (this.memberVariables = memberVariables);
  7050. }
  7051. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7052. const { type } = interaction;
  7053. if (path.length === 0) {
  7054. // This can only be a call anyway
  7055. return true;
  7056. }
  7057. if (path.length === 1 && type !== INTERACTION_CALLED) {
  7058. return type === INTERACTION_ASSIGNED;
  7059. }
  7060. const key = path[0];
  7061. if (typeof key !== 'string') {
  7062. return true;
  7063. }
  7064. const memberVariable = this.getMemberVariables()[key];
  7065. return (!memberVariable ||
  7066. memberVariable.hasEffectsOnInteractionAtPath(path.slice(1), interaction, context));
  7067. }
  7068. include() {
  7069. super.include();
  7070. this.context.includeAllExports();
  7071. }
  7072. prepare(accessedGlobalsByScope) {
  7073. if (this.mergedNamespaces.length > 0) {
  7074. this.module.scope.addAccessedGlobals([MERGE_NAMESPACES_VARIABLE], accessedGlobalsByScope);
  7075. }
  7076. }
  7077. renderBlock(options) {
  7078. const { exportNamesByVariable, format, freeze, indent: t, symbols, snippets: { _, cnst, getObject, getPropertyAccess, n, s } } = options;
  7079. const memberVariables = this.getMemberVariables();
  7080. const members = Object.entries(memberVariables)
  7081. .filter(([_, variable]) => variable.included)
  7082. .map(([name, variable]) => {
  7083. if (this.referencedEarly || variable.isReassigned || variable === this) {
  7084. return [
  7085. null,
  7086. `get ${stringifyObjectKeyIfNeeded(name)}${_}()${_}{${_}return ${variable.getName(getPropertyAccess)}${s}${_}}`
  7087. ];
  7088. }
  7089. return [name, variable.getName(getPropertyAccess)];
  7090. });
  7091. members.unshift([null, `__proto__:${_}null`]);
  7092. let output = getObject(members, { lineBreakIndent: { base: '', t } });
  7093. if (this.mergedNamespaces.length > 0) {
  7094. const assignmentArguments = this.mergedNamespaces.map(variable => variable.getName(getPropertyAccess));
  7095. output = `/*#__PURE__*/${MERGE_NAMESPACES_VARIABLE}(${output},${_}[${assignmentArguments.join(`,${_}`)}])`;
  7096. }
  7097. else {
  7098. // The helper to merge namespaces will also take care of freezing and toStringTag
  7099. if (symbols) {
  7100. output = `/*#__PURE__*/Object.defineProperty(${output},${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)})`;
  7101. }
  7102. if (freeze) {
  7103. output = `/*#__PURE__*/Object.freeze(${output})`;
  7104. }
  7105. }
  7106. const name = this.getName(getPropertyAccess);
  7107. output = `${cnst} ${name}${_}=${_}${output};`;
  7108. if (format === 'system' && exportNamesByVariable.has(this)) {
  7109. output += `${n}${getSystemExportStatement([this], options)};`;
  7110. }
  7111. return output;
  7112. }
  7113. renderFirst() {
  7114. return this.referencedEarly;
  7115. }
  7116. setMergedNamespaces(mergedNamespaces) {
  7117. this.mergedNamespaces = mergedNamespaces;
  7118. const moduleExecIndex = this.context.getModuleExecIndex();
  7119. for (const identifier of this.references) {
  7120. const { context } = identifier.scope;
  7121. if (context.getModuleExecIndex() <= moduleExecIndex) {
  7122. this.referencedEarly = true;
  7123. break;
  7124. }
  7125. }
  7126. }
  7127. }
  7128. NamespaceVariable.prototype.isNamespace = true;
  7129. class SyntheticNamedExportVariable extends Variable {
  7130. constructor(context, name, syntheticNamespace) {
  7131. super(name);
  7132. this.baseVariable = null;
  7133. this.context = context;
  7134. this.module = context.module;
  7135. this.syntheticNamespace = syntheticNamespace;
  7136. }
  7137. getBaseVariable() {
  7138. if (this.baseVariable)
  7139. return this.baseVariable;
  7140. let baseVariable = this.syntheticNamespace;
  7141. while (baseVariable instanceof ExportDefaultVariable ||
  7142. baseVariable instanceof SyntheticNamedExportVariable) {
  7143. if (baseVariable instanceof ExportDefaultVariable) {
  7144. const original = baseVariable.getOriginalVariable();
  7145. if (original === baseVariable)
  7146. break;
  7147. baseVariable = original;
  7148. }
  7149. if (baseVariable instanceof SyntheticNamedExportVariable) {
  7150. baseVariable = baseVariable.syntheticNamespace;
  7151. }
  7152. }
  7153. return (this.baseVariable = baseVariable);
  7154. }
  7155. getBaseVariableName() {
  7156. return this.syntheticNamespace.getBaseVariableName();
  7157. }
  7158. getName(getPropertyAccess) {
  7159. return `${this.syntheticNamespace.getName(getPropertyAccess)}${getPropertyAccess(this.name)}`;
  7160. }
  7161. include() {
  7162. super.include();
  7163. this.context.includeVariableInModule(this.syntheticNamespace);
  7164. }
  7165. setRenderNames(baseName, name) {
  7166. super.setRenderNames(baseName, name);
  7167. }
  7168. }
  7169. class ExternalChunk {
  7170. constructor(module, options, inputBase) {
  7171. this.options = options;
  7172. this.inputBase = inputBase;
  7173. this.defaultVariableName = '';
  7174. this.namespaceVariableName = '';
  7175. this.variableName = '';
  7176. this.fileName = null;
  7177. this.importAttributes = null;
  7178. this.id = module.id;
  7179. this.moduleInfo = module.info;
  7180. this.renormalizeRenderPath = module.renormalizeRenderPath;
  7181. this.suggestedVariableName = module.suggestedVariableName;
  7182. }
  7183. getFileName() {
  7184. if (this.fileName) {
  7185. return this.fileName;
  7186. }
  7187. const { paths } = this.options;
  7188. return (this.fileName =
  7189. (typeof paths === 'function' ? paths(this.id) : paths[this.id]) ||
  7190. (this.renormalizeRenderPath ? normalize(relative(this.inputBase, this.id)) : this.id));
  7191. }
  7192. getImportAttributes(snippets) {
  7193. return (this.importAttributes ||= formatAttributes(this.options.format === 'es' &&
  7194. this.options.externalImportAttributes &&
  7195. this.moduleInfo.attributes, snippets));
  7196. }
  7197. getImportPath(importer) {
  7198. return escapeId(this.renormalizeRenderPath
  7199. ? getImportPath(importer, this.getFileName(), this.options.format === 'amd', false)
  7200. : this.getFileName());
  7201. }
  7202. }
  7203. function formatAttributes(attributes, { getObject }) {
  7204. if (!attributes) {
  7205. return null;
  7206. }
  7207. const assertionEntries = Object.entries(attributes).map(([key, value]) => [key, `'${value}'`]);
  7208. if (assertionEntries.length > 0) {
  7209. return getObject(assertionEntries, { lineBreakIndent: null });
  7210. }
  7211. return null;
  7212. }
  7213. function removeJsExtension(name) {
  7214. return name.endsWith('.js') ? name.slice(0, -3) : name;
  7215. }
  7216. function getCompleteAmdId(options, chunkId) {
  7217. if (options.autoId) {
  7218. return `${options.basePath ? options.basePath + '/' : ''}${removeJsExtension(chunkId)}`;
  7219. }
  7220. return options.id ?? '';
  7221. }
  7222. function getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal, mechanism = 'return ') {
  7223. const { _, getDirectReturnFunction, getFunctionIntro, getPropertyAccess, n, s } = snippets;
  7224. if (!namedExportsMode) {
  7225. return `${n}${n}${mechanism}${getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings, getPropertyAccess)};`;
  7226. }
  7227. let exportBlock = '';
  7228. if (namedExportsMode) {
  7229. for (const { defaultVariableName, importPath, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  7230. if (!reexports) {
  7231. continue;
  7232. }
  7233. for (const specifier of reexports) {
  7234. if (specifier.reexported !== '*') {
  7235. const importName = getReexportedImportName(name, specifier.imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, importPath, externalLiveBindings, getPropertyAccess);
  7236. if (exportBlock)
  7237. exportBlock += n;
  7238. if (specifier.imported !== '*' && specifier.needsLiveBinding) {
  7239. const [left, right] = getDirectReturnFunction([], {
  7240. functionReturn: true,
  7241. lineBreakIndent: null,
  7242. name: null
  7243. });
  7244. exportBlock +=
  7245. `Object.defineProperty(exports,${_}${JSON.stringify(specifier.reexported)},${_}{${n}` +
  7246. `${t}enumerable:${_}true,${n}` +
  7247. `${t}get:${_}${left}${importName}${right}${n}});`;
  7248. }
  7249. else if (specifier.reexported === '__proto__') {
  7250. exportBlock +=
  7251. `Object.defineProperty(exports,${_}"__proto__",${_}{${n}` +
  7252. `${t}enumerable:${_}true,${n}` +
  7253. `${t}value:${_}${importName}${n}});`;
  7254. }
  7255. else {
  7256. exportBlock += `exports${getPropertyAccess(specifier.reexported)}${_}=${_}${importName};`;
  7257. }
  7258. }
  7259. }
  7260. }
  7261. }
  7262. for (const { exported, local } of exports) {
  7263. const lhs = `exports${getPropertyAccess(exported)}`;
  7264. const rhs = local;
  7265. if (lhs !== rhs) {
  7266. if (exportBlock)
  7267. exportBlock += n;
  7268. exportBlock +=
  7269. exported === '__proto__'
  7270. ? `Object.defineProperty(exports,${_}"__proto__",${_}{${n}` +
  7271. `${t}enumerable:${_}true,${n}` +
  7272. `${t}value:${_}${rhs}${n}});`
  7273. : `${lhs}${_}=${_}${rhs};`;
  7274. }
  7275. }
  7276. if (namedExportsMode) {
  7277. for (const { name, reexports } of dependencies) {
  7278. if (!reexports) {
  7279. continue;
  7280. }
  7281. for (const specifier of reexports) {
  7282. if (specifier.reexported === '*') {
  7283. if (exportBlock)
  7284. exportBlock += n;
  7285. if (!specifier.needsLiveBinding && reexportProtoFromExternal) {
  7286. const protoString = "'__proto__'";
  7287. exportBlock +=
  7288. `Object.prototype.hasOwnProperty.call(${name},${_}${protoString})${_}&&${n}` +
  7289. `${t}!Object.prototype.hasOwnProperty.call(exports,${_}${protoString})${_}&&${n}` +
  7290. `${t}Object.defineProperty(exports,${_}${protoString},${_}{${n}` +
  7291. `${t}${t}enumerable:${_}true,${n}` +
  7292. `${t}${t}value:${_}${name}[${protoString}]${n}` +
  7293. `${t}});${n}${n}`;
  7294. }
  7295. const copyPropertyIfNecessary = `{${n}${t}if${_}(k${_}!==${_}'default'${_}&&${_}!Object.prototype.hasOwnProperty.call(exports,${_}k))${_}${getDefineProperty(name, specifier.needsLiveBinding, t, snippets)}${s}${n}}`;
  7296. exportBlock += `Object.keys(${name}).forEach(${getFunctionIntro(['k'], {
  7297. isAsync: false,
  7298. name: null
  7299. })}${copyPropertyIfNecessary});`;
  7300. }
  7301. }
  7302. }
  7303. }
  7304. if (exportBlock) {
  7305. return `${n}${n}${exportBlock}`;
  7306. }
  7307. return '';
  7308. }
  7309. function getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings, getPropertyAccess) {
  7310. if (exports.length > 0) {
  7311. return exports[0].local;
  7312. }
  7313. else {
  7314. for (const { defaultVariableName, importPath, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  7315. if (reexports) {
  7316. return getReexportedImportName(name, reexports[0].imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, importPath, externalLiveBindings, getPropertyAccess);
  7317. }
  7318. }
  7319. }
  7320. }
  7321. function getReexportedImportName(moduleVariableName, imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, moduleId, externalLiveBindings, getPropertyAccess) {
  7322. if (imported === 'default') {
  7323. if (!isChunk) {
  7324. const moduleInterop = interop(moduleId);
  7325. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  7326. ? defaultVariableName
  7327. : moduleVariableName;
  7328. return isDefaultAProperty(moduleInterop, externalLiveBindings)
  7329. ? `${variableName}${getPropertyAccess('default')}`
  7330. : variableName;
  7331. }
  7332. return depNamedExportsMode
  7333. ? `${moduleVariableName}${getPropertyAccess('default')}`
  7334. : moduleVariableName;
  7335. }
  7336. if (imported === '*') {
  7337. return (isChunk ? !depNamedExportsMode : namespaceInteropHelpersByInteropType[interop(moduleId)])
  7338. ? namespaceVariableName
  7339. : moduleVariableName;
  7340. }
  7341. return `${moduleVariableName}${getPropertyAccess(imported)}`;
  7342. }
  7343. function getEsModuleValue(getObject) {
  7344. return getObject([['value', 'true']], {
  7345. lineBreakIndent: null
  7346. });
  7347. }
  7348. function getNamespaceMarkers(hasNamedExports, addEsModule, addNamespaceToStringTag, { _, getObject }) {
  7349. if (hasNamedExports) {
  7350. if (addEsModule) {
  7351. if (addNamespaceToStringTag) {
  7352. return `Object.defineProperties(exports,${_}${getObject([
  7353. ['__esModule', getEsModuleValue(getObject)],
  7354. [null, `[Symbol.toStringTag]:${_}${getToStringTagValue(getObject)}`]
  7355. ], {
  7356. lineBreakIndent: null
  7357. })});`;
  7358. }
  7359. return `Object.defineProperty(exports,${_}'__esModule',${_}${getEsModuleValue(getObject)});`;
  7360. }
  7361. if (addNamespaceToStringTag) {
  7362. return `Object.defineProperty(exports,${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)});`;
  7363. }
  7364. }
  7365. return '';
  7366. }
  7367. const getDefineProperty = (name, needsLiveBinding, t, { _, getDirectReturnFunction, n }) => {
  7368. if (needsLiveBinding) {
  7369. const [left, right] = getDirectReturnFunction([], {
  7370. functionReturn: true,
  7371. lineBreakIndent: null,
  7372. name: null
  7373. });
  7374. return (`Object.defineProperty(exports,${_}k,${_}{${n}` +
  7375. `${t}${t}enumerable:${_}true,${n}` +
  7376. `${t}${t}get:${_}${left}${name}[k]${right}${n}${t}})`);
  7377. }
  7378. return `exports[k]${_}=${_}${name}[k]`;
  7379. };
  7380. function getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, indent, snippets) {
  7381. const { _, cnst, n } = snippets;
  7382. const neededInteropHelpers = new Set();
  7383. const interopStatements = [];
  7384. const addInteropStatement = (helperVariableName, helper, dependencyVariableName) => {
  7385. neededInteropHelpers.add(helper);
  7386. interopStatements.push(`${cnst} ${helperVariableName}${_}=${_}/*#__PURE__*/${helper}(${dependencyVariableName});`);
  7387. };
  7388. for (const { defaultVariableName, imports, importPath, isChunk, name, namedExportsMode, namespaceVariableName, reexports } of dependencies) {
  7389. if (isChunk) {
  7390. for (const { imported, reexported } of [
  7391. ...(imports || []),
  7392. ...(reexports || [])
  7393. ]) {
  7394. if (imported === '*' && reexported !== '*') {
  7395. if (!namedExportsMode) {
  7396. addInteropStatement(namespaceVariableName, INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE, name);
  7397. }
  7398. break;
  7399. }
  7400. }
  7401. }
  7402. else {
  7403. const moduleInterop = interop(importPath);
  7404. let hasDefault = false;
  7405. let hasNamespace = false;
  7406. for (const { imported, reexported } of [
  7407. ...(imports || []),
  7408. ...(reexports || [])
  7409. ]) {
  7410. let helper;
  7411. let variableName;
  7412. if (imported === 'default') {
  7413. if (!hasDefault) {
  7414. hasDefault = true;
  7415. if (defaultVariableName !== namespaceVariableName) {
  7416. variableName = defaultVariableName;
  7417. helper = defaultInteropHelpersByInteropType[moduleInterop];
  7418. }
  7419. }
  7420. }
  7421. else if (imported === '*' && reexported !== '*' && !hasNamespace) {
  7422. hasNamespace = true;
  7423. helper = namespaceInteropHelpersByInteropType[moduleInterop];
  7424. variableName = namespaceVariableName;
  7425. }
  7426. if (helper) {
  7427. addInteropStatement(variableName, helper, name);
  7428. }
  7429. }
  7430. }
  7431. }
  7432. return `${getHelpersBlock(neededInteropHelpers, accessedGlobals, indent, snippets, externalLiveBindings, freeze, symbols)}${interopStatements.length > 0 ? `${interopStatements.join(n)}${n}${n}` : ''}`;
  7433. }
  7434. function addJsExtension(name) {
  7435. return name.endsWith('.js') ? name : name + '.js';
  7436. }
  7437. // AMD resolution will only respect the AMD baseUrl if the .js extension is omitted.
  7438. // The assumption is that this makes sense for all relative ids:
  7439. // https://requirejs.org/docs/api.html#jsfiles
  7440. function updateExtensionForRelativeAmdId(id, forceJsExtensionForImports) {
  7441. if (id[0] !== '.') {
  7442. return id;
  7443. }
  7444. return forceJsExtensionForImports ? addJsExtension(id) : removeJsExtension(id);
  7445. }
  7446. const builtinModules = [
  7447. "assert",
  7448. "assert/strict",
  7449. "async_hooks",
  7450. "buffer",
  7451. "child_process",
  7452. "cluster",
  7453. "console",
  7454. "constants",
  7455. "crypto",
  7456. "dgram",
  7457. "diagnostics_channel",
  7458. "dns",
  7459. "dns/promises",
  7460. "domain",
  7461. "events",
  7462. "fs",
  7463. "fs/promises",
  7464. "http",
  7465. "http2",
  7466. "https",
  7467. "inspector",
  7468. "inspector/promises",
  7469. "module",
  7470. "net",
  7471. "os",
  7472. "path",
  7473. "path/posix",
  7474. "path/win32",
  7475. "perf_hooks",
  7476. "process",
  7477. "punycode",
  7478. "querystring",
  7479. "readline",
  7480. "readline/promises",
  7481. "repl",
  7482. "stream",
  7483. "stream/consumers",
  7484. "stream/promises",
  7485. "stream/web",
  7486. "string_decoder",
  7487. "timers",
  7488. "timers/promises",
  7489. "tls",
  7490. "trace_events",
  7491. "tty",
  7492. "url",
  7493. "util",
  7494. "util/types",
  7495. "v8",
  7496. "vm",
  7497. "wasi",
  7498. "worker_threads",
  7499. "zlib"
  7500. ];
  7501. const nodeBuiltins = new Set(builtinModules);
  7502. function warnOnBuiltins(log, dependencies) {
  7503. const externalBuiltins = dependencies
  7504. .map(({ importPath }) => importPath)
  7505. .filter(importPath => nodeBuiltins.has(importPath) || importPath.startsWith('node:'));
  7506. if (externalBuiltins.length === 0)
  7507. return;
  7508. log(LOGLEVEL_WARN, logMissingNodeBuiltins(externalBuiltins));
  7509. }
  7510. function amd(magicString, { accessedGlobals, dependencies, exports, hasDefaultExport, hasExports, id, indent: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, log, outro, snippets }, { amd, esModule, externalLiveBindings, freeze, generatedCode: { symbols }, interop, reexportProtoFromExternal, strict }) {
  7511. warnOnBuiltins(log, dependencies);
  7512. const deps = dependencies.map(m => `'${updateExtensionForRelativeAmdId(m.importPath, amd.forceJsExtensionForImports)}'`);
  7513. const parameters = dependencies.map(m => m.name);
  7514. const { n, getNonArrowFunctionIntro, _ } = snippets;
  7515. if (namedExportsMode && hasExports) {
  7516. parameters.unshift(`exports`);
  7517. deps.unshift(`'exports'`);
  7518. }
  7519. if (accessedGlobals.has('require')) {
  7520. parameters.unshift('require');
  7521. deps.unshift(`'require'`);
  7522. }
  7523. if (accessedGlobals.has('module')) {
  7524. parameters.unshift('module');
  7525. deps.unshift(`'module'`);
  7526. }
  7527. const completeAmdId = getCompleteAmdId(amd, id);
  7528. const defineParameters = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
  7529. (deps.length > 0 ? `[${deps.join(`,${_}`)}],${_}` : ``);
  7530. const useStrict = strict ? `${_}'use strict';` : '';
  7531. magicString.prepend(`${intro}${getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, t, snippets)}`);
  7532. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal);
  7533. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && (esModule === true || (esModule === 'if-default-prop' && hasDefaultExport)), isModuleFacade && symbols, snippets);
  7534. if (namespaceMarkers) {
  7535. namespaceMarkers = n + n + namespaceMarkers;
  7536. }
  7537. magicString
  7538. .append(`${exportBlock}${namespaceMarkers}${outro}`)
  7539. .indent(t)
  7540. // factory function should be wrapped by parentheses to avoid lazy parsing,
  7541. // cf. https://v8.dev/blog/preparser#pife
  7542. .prepend(`${amd.define}(${defineParameters}(${getNonArrowFunctionIntro(parameters, {
  7543. isAsync: false,
  7544. name: null
  7545. })}{${useStrict}${n}${n}`)
  7546. .append(`${n}${n}}));`);
  7547. }
  7548. function cjs(magicString, { accessedGlobals, dependencies, exports, hasDefaultExport, hasExports, indent: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, outro, snippets }, { compact, esModule, externalLiveBindings, freeze, interop, generatedCode: { symbols }, reexportProtoFromExternal, strict }) {
  7549. const { _, n } = snippets;
  7550. const useStrict = strict ? `'use strict';${n}${n}` : '';
  7551. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && (esModule === true || (esModule === 'if-default-prop' && hasDefaultExport)), isModuleFacade && symbols, snippets);
  7552. if (namespaceMarkers) {
  7553. namespaceMarkers += n + n;
  7554. }
  7555. const importBlock = getImportBlock$1(dependencies, snippets, compact);
  7556. const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, t, snippets);
  7557. magicString.prepend(`${useStrict}${intro}${namespaceMarkers}${importBlock}${interopBlock}`);
  7558. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal, `module.exports${_}=${_}`);
  7559. magicString.append(`${exportBlock}${outro}`);
  7560. }
  7561. function getImportBlock$1(dependencies, { _, cnst, n }, compact) {
  7562. let importBlock = '';
  7563. let definingVariable = false;
  7564. for (const { importPath, name, reexports, imports } of dependencies) {
  7565. if (!reexports && !imports) {
  7566. if (importBlock) {
  7567. importBlock += compact && !definingVariable ? ',' : `;${n}`;
  7568. }
  7569. definingVariable = false;
  7570. importBlock += `require('${importPath}')`;
  7571. }
  7572. else {
  7573. importBlock += compact && definingVariable ? ',' : `${importBlock ? `;${n}` : ''}${cnst} `;
  7574. definingVariable = true;
  7575. importBlock += `${name}${_}=${_}require('${importPath}')`;
  7576. }
  7577. }
  7578. if (importBlock) {
  7579. return `${importBlock};${n}${n}`;
  7580. }
  7581. return '';
  7582. }
  7583. function es(magicString, { accessedGlobals, indent: t, intro, outro, dependencies, exports, snippets }, { externalLiveBindings, freeze, generatedCode: { symbols }, importAttributesKey }) {
  7584. const { n } = snippets;
  7585. const importBlock = getImportBlock(dependencies, importAttributesKey, snippets);
  7586. if (importBlock.length > 0)
  7587. intro += importBlock.join(n) + n + n;
  7588. intro += getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, symbols);
  7589. if (intro)
  7590. magicString.prepend(intro);
  7591. const exportBlock = getExportBlock(exports, snippets);
  7592. if (exportBlock.length > 0)
  7593. magicString.append(n + n + exportBlock.join(n).trim());
  7594. if (outro)
  7595. magicString.append(outro);
  7596. magicString.trim();
  7597. }
  7598. function getImportBlock(dependencies, importAttributesKey, { _ }) {
  7599. const importBlock = [];
  7600. for (const { importPath, reexports, imports, name, attributes } of dependencies) {
  7601. const assertion = attributes ? `${_}${importAttributesKey}${_}${attributes}` : '';
  7602. const pathWithAssertion = `'${importPath}'${assertion};`;
  7603. if (!reexports && !imports) {
  7604. importBlock.push(`import${_}${pathWithAssertion}`);
  7605. continue;
  7606. }
  7607. if (imports) {
  7608. let defaultImport = null;
  7609. let starImport = null;
  7610. const importedNames = [];
  7611. for (const specifier of imports) {
  7612. if (specifier.imported === 'default') {
  7613. defaultImport = specifier;
  7614. }
  7615. else if (specifier.imported === '*') {
  7616. starImport = specifier;
  7617. }
  7618. else {
  7619. importedNames.push(specifier);
  7620. }
  7621. }
  7622. if (starImport) {
  7623. importBlock.push(`import${_}*${_}as ${starImport.local} from${_}${pathWithAssertion}`);
  7624. }
  7625. if (defaultImport && importedNames.length === 0) {
  7626. importBlock.push(`import ${defaultImport.local} from${_}${pathWithAssertion}`);
  7627. }
  7628. else if (importedNames.length > 0) {
  7629. importBlock.push(`import ${defaultImport ? `${defaultImport.local},${_}` : ''}{${_}${importedNames
  7630. .map(specifier => specifier.imported === specifier.local
  7631. ? specifier.imported
  7632. : `${stringifyIdentifierIfNeeded(specifier.imported)} as ${specifier.local}`)
  7633. .join(`,${_}`)}${_}}${_}from${_}${pathWithAssertion}`);
  7634. }
  7635. }
  7636. if (reexports) {
  7637. let starExport = null;
  7638. const namespaceReexports = [];
  7639. const namedReexports = [];
  7640. for (const specifier of reexports) {
  7641. if (specifier.reexported === '*') {
  7642. starExport = specifier;
  7643. }
  7644. else if (specifier.imported === '*') {
  7645. namespaceReexports.push(specifier);
  7646. }
  7647. else {
  7648. namedReexports.push(specifier);
  7649. }
  7650. }
  7651. if (starExport) {
  7652. importBlock.push(`export${_}*${_}from${_}${pathWithAssertion}`);
  7653. }
  7654. if (namespaceReexports.length > 0) {
  7655. if (!imports ||
  7656. !imports.some(specifier => specifier.imported === '*' && specifier.local === name)) {
  7657. importBlock.push(`import${_}*${_}as ${name} from${_}${pathWithAssertion}`);
  7658. }
  7659. for (const specifier of namespaceReexports) {
  7660. importBlock.push(`export${_}{${_}${name === specifier.reexported
  7661. ? name
  7662. : `${name} as ${stringifyIdentifierIfNeeded(specifier.reexported)}`} };`);
  7663. }
  7664. }
  7665. if (namedReexports.length > 0) {
  7666. importBlock.push(`export${_}{${_}${namedReexports
  7667. .map(specifier => specifier.imported === specifier.reexported
  7668. ? stringifyIdentifierIfNeeded(specifier.imported)
  7669. : `${stringifyIdentifierIfNeeded(specifier.imported)} as ${stringifyIdentifierIfNeeded(specifier.reexported)}`)
  7670. .join(`,${_}`)}${_}}${_}from${_}${pathWithAssertion}`);
  7671. }
  7672. }
  7673. }
  7674. return importBlock;
  7675. }
  7676. function getExportBlock(exports, { _, cnst }) {
  7677. const exportBlock = [];
  7678. const exportDeclaration = [];
  7679. for (const specifier of exports) {
  7680. if (specifier.expression) {
  7681. exportBlock.push(`${cnst} ${specifier.local}${_}=${_}${specifier.expression};`);
  7682. }
  7683. exportDeclaration.push(specifier.exported === specifier.local
  7684. ? specifier.local
  7685. : `${specifier.local} as ${stringifyIdentifierIfNeeded(specifier.exported)}`);
  7686. }
  7687. if (exportDeclaration.length > 0) {
  7688. exportBlock.push(`export${_}{${_}${exportDeclaration.join(`,${_}`)}${_}};`);
  7689. }
  7690. return exportBlock;
  7691. }
  7692. const keypath = (keypath, getPropertyAccess) => keypath.split('.').map(getPropertyAccess).join('');
  7693. function setupNamespace(name, root, globals, { _, getPropertyAccess, s }, compact, log) {
  7694. const parts = name.split('.');
  7695. // Check if the key exists in the object's prototype.
  7696. const isReserved = parts[0] in Object.prototype;
  7697. if (log && isReserved) {
  7698. log(LOGLEVEL_WARN, logReservedNamespace(parts[0]));
  7699. }
  7700. parts[0] =
  7701. (typeof globals === 'function'
  7702. ? globals(parts[0])
  7703. : isReserved
  7704. ? parts[0]
  7705. : globals[parts[0]]) || parts[0];
  7706. parts.pop();
  7707. let propertyPath = root;
  7708. return (parts
  7709. .map(part => {
  7710. propertyPath += getPropertyAccess(part);
  7711. return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}${s}`;
  7712. })
  7713. .join(compact ? ',' : '\n') + (compact && parts.length > 0 ? ';' : '\n'));
  7714. }
  7715. function assignToDeepVariable(deepName, root, globals, assignment, { _, getPropertyAccess }, log) {
  7716. const parts = deepName.split('.');
  7717. // Check if the key exists in the object's prototype.
  7718. const isReserved = parts[0] in Object.prototype;
  7719. if (log && isReserved) {
  7720. log(LOGLEVEL_WARN, logReservedNamespace(parts[0]));
  7721. }
  7722. parts[0] =
  7723. (typeof globals === 'function'
  7724. ? globals(parts[0])
  7725. : isReserved
  7726. ? parts[0]
  7727. : globals[parts[0]]) || parts[0];
  7728. const last = parts.pop();
  7729. let propertyPath = root;
  7730. let deepAssignment = [
  7731. ...parts.map(part => {
  7732. propertyPath += getPropertyAccess(part);
  7733. return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}`;
  7734. }),
  7735. `${propertyPath}${getPropertyAccess(last)}`
  7736. ].join(`,${_}`) + `${_}=${_}${assignment}`;
  7737. if (parts.length > 0) {
  7738. deepAssignment = `(${deepAssignment})`;
  7739. }
  7740. return deepAssignment;
  7741. }
  7742. function trimEmptyImports(dependencies) {
  7743. let index = dependencies.length;
  7744. while (index--) {
  7745. const { imports, reexports } = dependencies[index];
  7746. if (imports || reexports) {
  7747. return dependencies.slice(0, index + 1);
  7748. }
  7749. }
  7750. return [];
  7751. }
  7752. function iife(magicString, { accessedGlobals, dependencies, exports, hasDefaultExport, hasExports, indent: t, intro, namedExportsMode, log, outro, snippets }, { compact, esModule, extend, freeze, externalLiveBindings, reexportProtoFromExternal, globals, interop, name, generatedCode: { symbols }, strict }) {
  7753. const { _, getNonArrowFunctionIntro, getPropertyAccess, n } = snippets;
  7754. const isNamespaced = name && name.includes('.');
  7755. const useVariableAssignment = !extend && !isNamespaced;
  7756. if (name && useVariableAssignment && !isLegal(name)) {
  7757. return error(logIllegalIdentifierAsName(name));
  7758. }
  7759. warnOnBuiltins(log, dependencies);
  7760. const external = trimEmptyImports(dependencies);
  7761. const deps = external.map(dep => dep.globalName || 'null');
  7762. const parameters = external.map(m => m.name);
  7763. if (hasExports && !name) {
  7764. log(LOGLEVEL_WARN, logMissingNameOptionForIifeExport());
  7765. }
  7766. if (namedExportsMode && hasExports) {
  7767. if (extend) {
  7768. deps.unshift(`this${keypath(name, getPropertyAccess)}${_}=${_}this${keypath(name, getPropertyAccess)}${_}||${_}{}`);
  7769. parameters.unshift('exports');
  7770. }
  7771. else {
  7772. deps.unshift('{}');
  7773. parameters.unshift('exports');
  7774. }
  7775. }
  7776. const useStrict = strict ? `${t}'use strict';${n}` : '';
  7777. const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, t, snippets);
  7778. magicString.prepend(`${intro}${interopBlock}`);
  7779. let wrapperIntro = `(${getNonArrowFunctionIntro(parameters, {
  7780. isAsync: false,
  7781. name: null
  7782. })}{${n}${useStrict}${n}`;
  7783. if (hasExports) {
  7784. if (name && !(extend && namedExportsMode)) {
  7785. wrapperIntro =
  7786. (useVariableAssignment ? `var ${name}` : `this${keypath(name, getPropertyAccess)}`) +
  7787. `${_}=${_}${wrapperIntro}`;
  7788. }
  7789. if (isNamespaced) {
  7790. wrapperIntro = setupNamespace(name, 'this', globals, snippets, compact, log) + wrapperIntro;
  7791. }
  7792. }
  7793. let wrapperOutro = `${n}${n}})(${deps.join(`,${_}`)});`;
  7794. if (hasExports && !extend && namedExportsMode) {
  7795. wrapperOutro = `${n}${n}${t}return exports;${wrapperOutro}`;
  7796. }
  7797. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal);
  7798. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule === true || (esModule === 'if-default-prop' && hasDefaultExport), symbols, snippets);
  7799. if (namespaceMarkers) {
  7800. namespaceMarkers = n + n + namespaceMarkers;
  7801. }
  7802. magicString
  7803. .append(`${exportBlock}${namespaceMarkers}${outro}`)
  7804. .indent(t)
  7805. .prepend(wrapperIntro)
  7806. .append(wrapperOutro);
  7807. }
  7808. const MISSING_EXPORT_SHIM_VARIABLE = '_missingExportShim';
  7809. function system(magicString, { accessedGlobals, dependencies, exports, hasExports, indent: t, intro, snippets, outro, usesTopLevelAwait }, { externalLiveBindings, freeze, name, generatedCode: { symbols }, strict, systemNullSetters }) {
  7810. const { _, getFunctionIntro, getNonArrowFunctionIntro, n, s } = snippets;
  7811. const { importBindings, setters, starExcludes } = analyzeDependencies(dependencies, exports, t, snippets);
  7812. const registeredName = name ? `'${name}',${_}` : '';
  7813. const wrapperParameters = accessedGlobals.has('module')
  7814. ? ['exports', 'module']
  7815. : hasExports
  7816. ? ['exports']
  7817. : [];
  7818. // factory function should be wrapped by parentheses to avoid lazy parsing,
  7819. // cf. https://v8.dev/blog/preparser#pife
  7820. let wrapperStart = `System.register(${registeredName}[` +
  7821. dependencies.map(({ importPath }) => `'${importPath}'`).join(`,${_}`) +
  7822. `],${_}(${getNonArrowFunctionIntro(wrapperParameters, {
  7823. isAsync: false,
  7824. name: null
  7825. })}{${n}${t}${strict ? "'use strict';" : ''}` +
  7826. getStarExcludesBlock(starExcludes, t, snippets) +
  7827. getImportBindingsBlock(importBindings, t, snippets) +
  7828. `${n}${t}return${_}{${setters.length > 0
  7829. ? `${n}${t}${t}setters:${_}[${setters
  7830. .map(setter => setter
  7831. ? `${getFunctionIntro(['module'], {
  7832. isAsync: false,
  7833. name: null
  7834. })}{${n}${t}${t}${t}${setter}${n}${t}${t}}`
  7835. : systemNullSetters
  7836. ? `null`
  7837. : `${getFunctionIntro([], { isAsync: false, name: null })}{}`)
  7838. .join(`,${_}`)}],`
  7839. : ''}${n}`;
  7840. wrapperStart += `${t}${t}execute:${_}(${getNonArrowFunctionIntro([], {
  7841. isAsync: usesTopLevelAwait,
  7842. name: null
  7843. })}{${n}${n}`;
  7844. const wrapperEnd = `${t}${t}})${n}${t}}${s}${n}}));`;
  7845. magicString
  7846. .prepend(intro +
  7847. getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, symbols) +
  7848. getHoistedExportsBlock(exports, t, snippets))
  7849. .append(`${outro}${n}${n}` +
  7850. getSyntheticExportsBlock(exports, t, snippets) +
  7851. getMissingExportsBlock(exports, t, snippets))
  7852. .indent(`${t}${t}${t}`)
  7853. .append(wrapperEnd)
  7854. .prepend(wrapperStart);
  7855. }
  7856. function analyzeDependencies(dependencies, exports, t, { _, cnst, getObject, getPropertyAccess, n }) {
  7857. const importBindings = [];
  7858. const setters = [];
  7859. let starExcludes = null;
  7860. for (const { imports, reexports } of dependencies) {
  7861. const setter = [];
  7862. if (imports) {
  7863. for (const specifier of imports) {
  7864. importBindings.push(specifier.local);
  7865. if (specifier.imported === '*') {
  7866. setter.push(`${specifier.local}${_}=${_}module;`);
  7867. }
  7868. else {
  7869. setter.push(`${specifier.local}${_}=${_}module${getPropertyAccess(specifier.imported)};`);
  7870. }
  7871. }
  7872. }
  7873. if (reexports) {
  7874. const reexportedNames = [];
  7875. let hasStarReexport = false;
  7876. for (const { imported, reexported } of reexports) {
  7877. if (reexported === '*') {
  7878. hasStarReexport = true;
  7879. }
  7880. else {
  7881. reexportedNames.push([
  7882. reexported,
  7883. imported === '*' ? 'module' : `module${getPropertyAccess(imported)}`
  7884. ]);
  7885. }
  7886. }
  7887. if (reexportedNames.length > 1 || hasStarReexport) {
  7888. if (hasStarReexport) {
  7889. if (!starExcludes) {
  7890. starExcludes = getStarExcludes({ dependencies, exports });
  7891. }
  7892. reexportedNames.unshift([null, `__proto__:${_}null`]);
  7893. const exportMapping = getObject(reexportedNames, { lineBreakIndent: null });
  7894. setter.push(`${cnst} setter${_}=${_}${exportMapping};`, `for${_}(${cnst} name in module)${_}{`, `${t}if${_}(!_starExcludes[name])${_}setter[name]${_}=${_}module[name];`, '}', 'exports(setter);');
  7895. }
  7896. else {
  7897. const exportMapping = getObject(reexportedNames, { lineBreakIndent: null });
  7898. setter.push(`exports(${exportMapping});`);
  7899. }
  7900. }
  7901. else {
  7902. const [key, value] = reexportedNames[0];
  7903. setter.push(`exports(${JSON.stringify(key)},${_}${value});`);
  7904. }
  7905. }
  7906. setters.push(setter.join(`${n}${t}${t}${t}`));
  7907. }
  7908. return { importBindings, setters, starExcludes };
  7909. }
  7910. const getStarExcludes = ({ dependencies, exports }) => {
  7911. const starExcludes = new Set(exports.map(expt => expt.exported));
  7912. starExcludes.add('default');
  7913. for (const { reexports } of dependencies) {
  7914. if (reexports) {
  7915. for (const reexport of reexports) {
  7916. if (reexport.reexported !== '*')
  7917. starExcludes.add(reexport.reexported);
  7918. }
  7919. }
  7920. }
  7921. return starExcludes;
  7922. };
  7923. const getStarExcludesBlock = (starExcludes, t, { _, cnst, getObject, n }) => {
  7924. if (starExcludes) {
  7925. const fields = [...starExcludes].map(property => [
  7926. property,
  7927. '1'
  7928. ]);
  7929. fields.unshift([null, `__proto__:${_}null`]);
  7930. return `${n}${t}${cnst} _starExcludes${_}=${_}${getObject(fields, {
  7931. lineBreakIndent: { base: t, t }
  7932. })};`;
  7933. }
  7934. return '';
  7935. };
  7936. const getImportBindingsBlock = (importBindings, t, { _, n }) => (importBindings.length > 0 ? `${n}${t}var ${importBindings.join(`,${_}`)};` : '');
  7937. const getHoistedExportsBlock = (exports, t, snippets) => getExportsBlock(exports.filter(expt => expt.hoisted).map(expt => ({ name: expt.exported, value: expt.local })), t, snippets);
  7938. function getExportsBlock(exports, t, { _, n }) {
  7939. if (exports.length === 0) {
  7940. return '';
  7941. }
  7942. if (exports.length === 1) {
  7943. return `exports(${JSON.stringify(exports[0].name)},${_}${exports[0].value});${n}${n}`;
  7944. }
  7945. return (`exports({${n}` +
  7946. exports
  7947. .map(({ name, value }) => `${t}${stringifyObjectKeyIfNeeded(name)}:${_}${value}`)
  7948. .join(`,${n}`) +
  7949. `${n}});${n}${n}`);
  7950. }
  7951. const getSyntheticExportsBlock = (exports, t, snippets) => getExportsBlock(exports
  7952. .filter(expt => expt.expression)
  7953. .map(expt => ({ name: expt.exported, value: expt.local })), t, snippets);
  7954. const getMissingExportsBlock = (exports, t, snippets) => getExportsBlock(exports
  7955. .filter(expt => expt.local === MISSING_EXPORT_SHIM_VARIABLE)
  7956. .map(expt => ({ name: expt.exported, value: MISSING_EXPORT_SHIM_VARIABLE })), t, snippets);
  7957. function globalProperty(name, globalVariable, getPropertyAccess) {
  7958. if (!name)
  7959. return 'null';
  7960. return `${globalVariable}${keypath(name, getPropertyAccess)}`;
  7961. }
  7962. function safeAccess(name, globalVariable, { _, getPropertyAccess }) {
  7963. let propertyPath = globalVariable;
  7964. return name
  7965. .split('.')
  7966. .map(part => (propertyPath += getPropertyAccess(part)))
  7967. .join(`${_}&&${_}`);
  7968. }
  7969. function umd(magicString, { accessedGlobals, dependencies, exports, hasDefaultExport, hasExports, id, indent: t, intro, namedExportsMode, log, outro, snippets }, { amd, compact, esModule, extend, externalLiveBindings, freeze, interop, name, generatedCode: { symbols }, globals, noConflict, reexportProtoFromExternal, strict }) {
  7970. const { _, cnst, getFunctionIntro, getNonArrowFunctionIntro, getPropertyAccess, n, s } = snippets;
  7971. const factoryVariable = compact ? 'f' : 'factory';
  7972. const globalVariable = compact ? 'g' : 'global';
  7973. if (hasExports && !name) {
  7974. return error(logMissingNameOptionForUmdExport());
  7975. }
  7976. warnOnBuiltins(log, dependencies);
  7977. const amdDeps = dependencies.map(m => `'${updateExtensionForRelativeAmdId(m.importPath, amd.forceJsExtensionForImports)}'`);
  7978. const cjsDeps = dependencies.map(m => `require('${m.importPath}')`);
  7979. const trimmedImports = trimEmptyImports(dependencies);
  7980. const globalDeps = trimmedImports.map(module => globalProperty(module.globalName, globalVariable, getPropertyAccess));
  7981. const factoryParameters = trimmedImports.map(m => m.name);
  7982. if (namedExportsMode && (hasExports || noConflict)) {
  7983. amdDeps.unshift(`'exports'`);
  7984. cjsDeps.unshift(`exports`);
  7985. globalDeps.unshift(assignToDeepVariable(name, globalVariable, globals, `${extend ? `${globalProperty(name, globalVariable, getPropertyAccess)}${_}||${_}` : ''}{}`, snippets, log));
  7986. factoryParameters.unshift('exports');
  7987. }
  7988. const completeAmdId = getCompleteAmdId(amd, id);
  7989. const amdParameters = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
  7990. (amdDeps.length > 0 ? `[${amdDeps.join(`,${_}`)}],${_}` : ``);
  7991. const define = amd.define;
  7992. const cjsExport = !namedExportsMode && hasExports ? `module.exports${_}=${_}` : ``;
  7993. const useStrict = strict ? `${_}'use strict';${n}` : ``;
  7994. let iifeExport;
  7995. if (noConflict) {
  7996. const noConflictExportsVariable = compact ? 'e' : 'exports';
  7997. let factory;
  7998. if (!namedExportsMode && hasExports) {
  7999. factory = `${cnst} ${noConflictExportsVariable}${_}=${_}${assignToDeepVariable(name, globalVariable, globals, `${factoryVariable}(${globalDeps.join(`,${_}`)})`, snippets, log)};`;
  8000. }
  8001. else {
  8002. const module = globalDeps.shift();
  8003. factory =
  8004. `${cnst} ${noConflictExportsVariable}${_}=${_}${module};${n}` +
  8005. `${t}${t}${factoryVariable}(${[noConflictExportsVariable, ...globalDeps].join(`,${_}`)});`;
  8006. }
  8007. iifeExport =
  8008. `(${getFunctionIntro([], { isAsync: false, name: null })}{${n}` +
  8009. `${t}${t}${cnst} current${_}=${_}${safeAccess(name, globalVariable, snippets)};${n}` +
  8010. `${t}${t}${factory}${n}` +
  8011. `${t}${t}${noConflictExportsVariable}.noConflict${_}=${_}${getFunctionIntro([], {
  8012. isAsync: false,
  8013. name: null
  8014. })}{${_}` +
  8015. `${globalProperty(name, globalVariable, getPropertyAccess)}${_}=${_}current;${_}return ${noConflictExportsVariable}${s}${_}};${n}` +
  8016. `${t}})()`;
  8017. }
  8018. else {
  8019. iifeExport = `${factoryVariable}(${globalDeps.join(`,${_}`)})`;
  8020. if (!namedExportsMode && hasExports) {
  8021. iifeExport = assignToDeepVariable(name, globalVariable, globals, iifeExport, snippets, log);
  8022. }
  8023. }
  8024. const iifeNeedsGlobal = hasExports || (noConflict && namedExportsMode) || globalDeps.length > 0;
  8025. const wrapperParameters = [factoryVariable];
  8026. if (iifeNeedsGlobal) {
  8027. wrapperParameters.unshift(globalVariable);
  8028. }
  8029. const globalArgument = iifeNeedsGlobal ? `this,${_}` : '';
  8030. const iifeStart = iifeNeedsGlobal
  8031. ? `(${globalVariable}${_}=${_}typeof globalThis${_}!==${_}'undefined'${_}?${_}globalThis${_}:${_}${globalVariable}${_}||${_}self,${_}`
  8032. : '';
  8033. const iifeEnd = iifeNeedsGlobal ? ')' : '';
  8034. const cjsIntro = iifeNeedsGlobal
  8035. ? `${t}typeof exports${_}===${_}'object'${_}&&${_}typeof module${_}!==${_}'undefined'${_}?` +
  8036. `${_}${cjsExport}${factoryVariable}(${cjsDeps.join(`,${_}`)})${_}:${n}`
  8037. : '';
  8038. const wrapperIntro = `(${getNonArrowFunctionIntro(wrapperParameters, { isAsync: false, name: null })}{${n}` +
  8039. cjsIntro +
  8040. `${t}typeof ${define}${_}===${_}'function'${_}&&${_}${define}.amd${_}?${_}${define}(${amdParameters}${factoryVariable})${_}:${n}` +
  8041. `${t}${iifeStart}${iifeExport}${iifeEnd};${n}` +
  8042. // factory function should be wrapped by parentheses to avoid lazy parsing,
  8043. // cf. https://v8.dev/blog/preparser#pife
  8044. `})(${globalArgument}(${getNonArrowFunctionIntro(factoryParameters, {
  8045. isAsync: false,
  8046. name: null
  8047. })}{${useStrict}${n}`;
  8048. const wrapperOutro = n + n + '}));';
  8049. magicString.prepend(`${intro}${getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, t, snippets)}`);
  8050. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal);
  8051. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule === true || (esModule === 'if-default-prop' && hasDefaultExport), symbols, snippets);
  8052. if (namespaceMarkers) {
  8053. namespaceMarkers = n + n + namespaceMarkers;
  8054. }
  8055. magicString
  8056. .append(`${exportBlock}${namespaceMarkers}${outro}`)
  8057. .trim()
  8058. .indent(t)
  8059. .append(wrapperOutro)
  8060. .prepend(wrapperIntro);
  8061. }
  8062. const finalisers = { amd, cjs, es, iife, system, umd };
  8063. function getDefaultExportFromCjs (x) {
  8064. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  8065. }
  8066. function getAugmentedNamespace(n) {
  8067. if (n.__esModule) return n;
  8068. var f = n.default;
  8069. if (typeof f == "function") {
  8070. var a = function a () {
  8071. if (this instanceof a) {
  8072. return Reflect.construct(f, arguments, this.constructor);
  8073. }
  8074. return f.apply(this, arguments);
  8075. };
  8076. a.prototype = f.prototype;
  8077. } else a = {};
  8078. Object.defineProperty(a, '__esModule', {value: true});
  8079. Object.keys(n).forEach(function (k) {
  8080. var d = Object.getOwnPropertyDescriptor(n, k);
  8081. Object.defineProperty(a, k, d.get ? d : {
  8082. enumerable: true,
  8083. get: function () {
  8084. return n[k];
  8085. }
  8086. });
  8087. });
  8088. return a;
  8089. }
  8090. var utils = {};
  8091. var constants;
  8092. var hasRequiredConstants;
  8093. function requireConstants () {
  8094. if (hasRequiredConstants) return constants;
  8095. hasRequiredConstants = 1;
  8096. const WIN_SLASH = '\\\\/';
  8097. const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
  8098. /**
  8099. * Posix glob regex
  8100. */
  8101. const DOT_LITERAL = '\\.';
  8102. const PLUS_LITERAL = '\\+';
  8103. const QMARK_LITERAL = '\\?';
  8104. const SLASH_LITERAL = '\\/';
  8105. const ONE_CHAR = '(?=.)';
  8106. const QMARK = '[^/]';
  8107. const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
  8108. const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
  8109. const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
  8110. const NO_DOT = `(?!${DOT_LITERAL})`;
  8111. const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
  8112. const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
  8113. const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
  8114. const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
  8115. const STAR = `${QMARK}*?`;
  8116. const SEP = '/';
  8117. const POSIX_CHARS = {
  8118. DOT_LITERAL,
  8119. PLUS_LITERAL,
  8120. QMARK_LITERAL,
  8121. SLASH_LITERAL,
  8122. ONE_CHAR,
  8123. QMARK,
  8124. END_ANCHOR,
  8125. DOTS_SLASH,
  8126. NO_DOT,
  8127. NO_DOTS,
  8128. NO_DOT_SLASH,
  8129. NO_DOTS_SLASH,
  8130. QMARK_NO_DOT,
  8131. STAR,
  8132. START_ANCHOR,
  8133. SEP
  8134. };
  8135. /**
  8136. * Windows glob regex
  8137. */
  8138. const WINDOWS_CHARS = {
  8139. ...POSIX_CHARS,
  8140. SLASH_LITERAL: `[${WIN_SLASH}]`,
  8141. QMARK: WIN_NO_SLASH,
  8142. STAR: `${WIN_NO_SLASH}*?`,
  8143. DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
  8144. NO_DOT: `(?!${DOT_LITERAL})`,
  8145. NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  8146. NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
  8147. NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  8148. QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
  8149. START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
  8150. END_ANCHOR: `(?:[${WIN_SLASH}]|$)`,
  8151. SEP: '\\'
  8152. };
  8153. /**
  8154. * POSIX Bracket Regex
  8155. */
  8156. const POSIX_REGEX_SOURCE = {
  8157. alnum: 'a-zA-Z0-9',
  8158. alpha: 'a-zA-Z',
  8159. ascii: '\\x00-\\x7F',
  8160. blank: ' \\t',
  8161. cntrl: '\\x00-\\x1F\\x7F',
  8162. digit: '0-9',
  8163. graph: '\\x21-\\x7E',
  8164. lower: 'a-z',
  8165. print: '\\x20-\\x7E ',
  8166. punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
  8167. space: ' \\t\\r\\n\\v\\f',
  8168. upper: 'A-Z',
  8169. word: 'A-Za-z0-9_',
  8170. xdigit: 'A-Fa-f0-9'
  8171. };
  8172. constants = {
  8173. MAX_LENGTH: 1024 * 64,
  8174. POSIX_REGEX_SOURCE,
  8175. // regular expressions
  8176. REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
  8177. REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
  8178. REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
  8179. REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
  8180. REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
  8181. REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
  8182. // Replace globs with equivalent patterns to reduce parsing time.
  8183. REPLACEMENTS: {
  8184. '***': '*',
  8185. '**/**': '**',
  8186. '**/**/**': '**'
  8187. },
  8188. // Digits
  8189. CHAR_0: 48, /* 0 */
  8190. CHAR_9: 57, /* 9 */
  8191. // Alphabet chars.
  8192. CHAR_UPPERCASE_A: 65, /* A */
  8193. CHAR_LOWERCASE_A: 97, /* a */
  8194. CHAR_UPPERCASE_Z: 90, /* Z */
  8195. CHAR_LOWERCASE_Z: 122, /* z */
  8196. CHAR_LEFT_PARENTHESES: 40, /* ( */
  8197. CHAR_RIGHT_PARENTHESES: 41, /* ) */
  8198. CHAR_ASTERISK: 42, /* * */
  8199. // Non-alphabetic chars.
  8200. CHAR_AMPERSAND: 38, /* & */
  8201. CHAR_AT: 64, /* @ */
  8202. CHAR_BACKWARD_SLASH: 92, /* \ */
  8203. CHAR_CARRIAGE_RETURN: 13, /* \r */
  8204. CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */
  8205. CHAR_COLON: 58, /* : */
  8206. CHAR_COMMA: 44, /* , */
  8207. CHAR_DOT: 46, /* . */
  8208. CHAR_DOUBLE_QUOTE: 34, /* " */
  8209. CHAR_EQUAL: 61, /* = */
  8210. CHAR_EXCLAMATION_MARK: 33, /* ! */
  8211. CHAR_FORM_FEED: 12, /* \f */
  8212. CHAR_FORWARD_SLASH: 47, /* / */
  8213. CHAR_GRAVE_ACCENT: 96, /* ` */
  8214. CHAR_HASH: 35, /* # */
  8215. CHAR_HYPHEN_MINUS: 45, /* - */
  8216. CHAR_LEFT_ANGLE_BRACKET: 60, /* < */
  8217. CHAR_LEFT_CURLY_BRACE: 123, /* { */
  8218. CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */
  8219. CHAR_LINE_FEED: 10, /* \n */
  8220. CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
  8221. CHAR_PERCENT: 37, /* % */
  8222. CHAR_PLUS: 43, /* + */
  8223. CHAR_QUESTION_MARK: 63, /* ? */
  8224. CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */
  8225. CHAR_RIGHT_CURLY_BRACE: 125, /* } */
  8226. CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */
  8227. CHAR_SEMICOLON: 59, /* ; */
  8228. CHAR_SINGLE_QUOTE: 39, /* ' */
  8229. CHAR_SPACE: 32, /* */
  8230. CHAR_TAB: 9, /* \t */
  8231. CHAR_UNDERSCORE: 95, /* _ */
  8232. CHAR_VERTICAL_LINE: 124, /* | */
  8233. CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
  8234. /**
  8235. * Create EXTGLOB_CHARS
  8236. */
  8237. extglobChars(chars) {
  8238. return {
  8239. '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
  8240. '?': { type: 'qmark', open: '(?:', close: ')?' },
  8241. '+': { type: 'plus', open: '(?:', close: ')+' },
  8242. '*': { type: 'star', open: '(?:', close: ')*' },
  8243. '@': { type: 'at', open: '(?:', close: ')' }
  8244. };
  8245. },
  8246. /**
  8247. * Create GLOB_CHARS
  8248. */
  8249. globChars(win32) {
  8250. return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
  8251. }
  8252. };
  8253. return constants;
  8254. }
  8255. /*global navigator*/
  8256. var hasRequiredUtils;
  8257. function requireUtils () {
  8258. if (hasRequiredUtils) return utils;
  8259. hasRequiredUtils = 1;
  8260. (function (exports) {
  8261. const {
  8262. REGEX_BACKSLASH,
  8263. REGEX_REMOVE_BACKSLASH,
  8264. REGEX_SPECIAL_CHARS,
  8265. REGEX_SPECIAL_CHARS_GLOBAL
  8266. } = /*@__PURE__*/ requireConstants();
  8267. exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  8268. exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
  8269. exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
  8270. exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
  8271. exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
  8272. exports.isWindows = () => {
  8273. if (typeof navigator !== 'undefined' && navigator.platform) {
  8274. const platform = navigator.platform.toLowerCase();
  8275. return platform === 'win32' || platform === 'windows';
  8276. }
  8277. if (typeof process !== 'undefined' && process.platform) {
  8278. return process.platform === 'win32';
  8279. }
  8280. return false;
  8281. };
  8282. exports.removeBackslashes = str => {
  8283. return str.replace(REGEX_REMOVE_BACKSLASH, match => {
  8284. return match === '\\' ? '' : match;
  8285. });
  8286. };
  8287. exports.escapeLast = (input, char, lastIdx) => {
  8288. const idx = input.lastIndexOf(char, lastIdx);
  8289. if (idx === -1) return input;
  8290. if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
  8291. return `${input.slice(0, idx)}\\${input.slice(idx)}`;
  8292. };
  8293. exports.removePrefix = (input, state = {}) => {
  8294. let output = input;
  8295. if (output.startsWith('./')) {
  8296. output = output.slice(2);
  8297. state.prefix = './';
  8298. }
  8299. return output;
  8300. };
  8301. exports.wrapOutput = (input, state = {}, options = {}) => {
  8302. const prepend = options.contains ? '' : '^';
  8303. const append = options.contains ? '' : '$';
  8304. let output = `${prepend}(?:${input})${append}`;
  8305. if (state.negated === true) {
  8306. output = `(?:^(?!${output}).*$)`;
  8307. }
  8308. return output;
  8309. };
  8310. exports.basename = (path, { windows } = {}) => {
  8311. const segs = path.split(windows ? /[\\/]/ : '/');
  8312. const last = segs[segs.length - 1];
  8313. if (last === '') {
  8314. return segs[segs.length - 2];
  8315. }
  8316. return last;
  8317. };
  8318. } (utils));
  8319. return utils;
  8320. }
  8321. var scan_1;
  8322. var hasRequiredScan;
  8323. function requireScan () {
  8324. if (hasRequiredScan) return scan_1;
  8325. hasRequiredScan = 1;
  8326. const utils = /*@__PURE__*/ requireUtils();
  8327. const {
  8328. CHAR_ASTERISK, /* * */
  8329. CHAR_AT, /* @ */
  8330. CHAR_BACKWARD_SLASH, /* \ */
  8331. CHAR_COMMA, /* , */
  8332. CHAR_DOT, /* . */
  8333. CHAR_EXCLAMATION_MARK, /* ! */
  8334. CHAR_FORWARD_SLASH, /* / */
  8335. CHAR_LEFT_CURLY_BRACE, /* { */
  8336. CHAR_LEFT_PARENTHESES, /* ( */
  8337. CHAR_LEFT_SQUARE_BRACKET, /* [ */
  8338. CHAR_PLUS, /* + */
  8339. CHAR_QUESTION_MARK, /* ? */
  8340. CHAR_RIGHT_CURLY_BRACE, /* } */
  8341. CHAR_RIGHT_PARENTHESES, /* ) */
  8342. CHAR_RIGHT_SQUARE_BRACKET /* ] */
  8343. } = /*@__PURE__*/ requireConstants();
  8344. const isPathSeparator = code => {
  8345. return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
  8346. };
  8347. const depth = token => {
  8348. if (token.isPrefix !== true) {
  8349. token.depth = token.isGlobstar ? Infinity : 1;
  8350. }
  8351. };
  8352. /**
  8353. * Quickly scans a glob pattern and returns an object with a handful of
  8354. * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
  8355. * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
  8356. * with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
  8357. *
  8358. * ```js
  8359. * const pm = require('picomatch');
  8360. * console.log(pm.scan('foo/bar/*.js'));
  8361. * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
  8362. * ```
  8363. * @param {String} `str`
  8364. * @param {Object} `options`
  8365. * @return {Object} Returns an object with tokens and regex source string.
  8366. * @api public
  8367. */
  8368. const scan = (input, options) => {
  8369. const opts = options || {};
  8370. const length = input.length - 1;
  8371. const scanToEnd = opts.parts === true || opts.scanToEnd === true;
  8372. const slashes = [];
  8373. const tokens = [];
  8374. const parts = [];
  8375. let str = input;
  8376. let index = -1;
  8377. let start = 0;
  8378. let lastIndex = 0;
  8379. let isBrace = false;
  8380. let isBracket = false;
  8381. let isGlob = false;
  8382. let isExtglob = false;
  8383. let isGlobstar = false;
  8384. let braceEscaped = false;
  8385. let backslashes = false;
  8386. let negated = false;
  8387. let negatedExtglob = false;
  8388. let finished = false;
  8389. let braces = 0;
  8390. let prev;
  8391. let code;
  8392. let token = { value: '', depth: 0, isGlob: false };
  8393. const eos = () => index >= length;
  8394. const peek = () => str.charCodeAt(index + 1);
  8395. const advance = () => {
  8396. prev = code;
  8397. return str.charCodeAt(++index);
  8398. };
  8399. while (index < length) {
  8400. code = advance();
  8401. let next;
  8402. if (code === CHAR_BACKWARD_SLASH) {
  8403. backslashes = token.backslashes = true;
  8404. code = advance();
  8405. if (code === CHAR_LEFT_CURLY_BRACE) {
  8406. braceEscaped = true;
  8407. }
  8408. continue;
  8409. }
  8410. if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
  8411. braces++;
  8412. while (eos() !== true && (code = advance())) {
  8413. if (code === CHAR_BACKWARD_SLASH) {
  8414. backslashes = token.backslashes = true;
  8415. advance();
  8416. continue;
  8417. }
  8418. if (code === CHAR_LEFT_CURLY_BRACE) {
  8419. braces++;
  8420. continue;
  8421. }
  8422. if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
  8423. isBrace = token.isBrace = true;
  8424. isGlob = token.isGlob = true;
  8425. finished = true;
  8426. if (scanToEnd === true) {
  8427. continue;
  8428. }
  8429. break;
  8430. }
  8431. if (braceEscaped !== true && code === CHAR_COMMA) {
  8432. isBrace = token.isBrace = true;
  8433. isGlob = token.isGlob = true;
  8434. finished = true;
  8435. if (scanToEnd === true) {
  8436. continue;
  8437. }
  8438. break;
  8439. }
  8440. if (code === CHAR_RIGHT_CURLY_BRACE) {
  8441. braces--;
  8442. if (braces === 0) {
  8443. braceEscaped = false;
  8444. isBrace = token.isBrace = true;
  8445. finished = true;
  8446. break;
  8447. }
  8448. }
  8449. }
  8450. if (scanToEnd === true) {
  8451. continue;
  8452. }
  8453. break;
  8454. }
  8455. if (code === CHAR_FORWARD_SLASH) {
  8456. slashes.push(index);
  8457. tokens.push(token);
  8458. token = { value: '', depth: 0, isGlob: false };
  8459. if (finished === true) continue;
  8460. if (prev === CHAR_DOT && index === (start + 1)) {
  8461. start += 2;
  8462. continue;
  8463. }
  8464. lastIndex = index + 1;
  8465. continue;
  8466. }
  8467. if (opts.noext !== true) {
  8468. const isExtglobChar = code === CHAR_PLUS
  8469. || code === CHAR_AT
  8470. || code === CHAR_ASTERISK
  8471. || code === CHAR_QUESTION_MARK
  8472. || code === CHAR_EXCLAMATION_MARK;
  8473. if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
  8474. isGlob = token.isGlob = true;
  8475. isExtglob = token.isExtglob = true;
  8476. finished = true;
  8477. if (code === CHAR_EXCLAMATION_MARK && index === start) {
  8478. negatedExtglob = true;
  8479. }
  8480. if (scanToEnd === true) {
  8481. while (eos() !== true && (code = advance())) {
  8482. if (code === CHAR_BACKWARD_SLASH) {
  8483. backslashes = token.backslashes = true;
  8484. code = advance();
  8485. continue;
  8486. }
  8487. if (code === CHAR_RIGHT_PARENTHESES) {
  8488. isGlob = token.isGlob = true;
  8489. finished = true;
  8490. break;
  8491. }
  8492. }
  8493. continue;
  8494. }
  8495. break;
  8496. }
  8497. }
  8498. if (code === CHAR_ASTERISK) {
  8499. if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
  8500. isGlob = token.isGlob = true;
  8501. finished = true;
  8502. if (scanToEnd === true) {
  8503. continue;
  8504. }
  8505. break;
  8506. }
  8507. if (code === CHAR_QUESTION_MARK) {
  8508. isGlob = token.isGlob = true;
  8509. finished = true;
  8510. if (scanToEnd === true) {
  8511. continue;
  8512. }
  8513. break;
  8514. }
  8515. if (code === CHAR_LEFT_SQUARE_BRACKET) {
  8516. while (eos() !== true && (next = advance())) {
  8517. if (next === CHAR_BACKWARD_SLASH) {
  8518. backslashes = token.backslashes = true;
  8519. advance();
  8520. continue;
  8521. }
  8522. if (next === CHAR_RIGHT_SQUARE_BRACKET) {
  8523. isBracket = token.isBracket = true;
  8524. isGlob = token.isGlob = true;
  8525. finished = true;
  8526. break;
  8527. }
  8528. }
  8529. if (scanToEnd === true) {
  8530. continue;
  8531. }
  8532. break;
  8533. }
  8534. if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
  8535. negated = token.negated = true;
  8536. start++;
  8537. continue;
  8538. }
  8539. if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
  8540. isGlob = token.isGlob = true;
  8541. if (scanToEnd === true) {
  8542. while (eos() !== true && (code = advance())) {
  8543. if (code === CHAR_LEFT_PARENTHESES) {
  8544. backslashes = token.backslashes = true;
  8545. code = advance();
  8546. continue;
  8547. }
  8548. if (code === CHAR_RIGHT_PARENTHESES) {
  8549. finished = true;
  8550. break;
  8551. }
  8552. }
  8553. continue;
  8554. }
  8555. break;
  8556. }
  8557. if (isGlob === true) {
  8558. finished = true;
  8559. if (scanToEnd === true) {
  8560. continue;
  8561. }
  8562. break;
  8563. }
  8564. }
  8565. if (opts.noext === true) {
  8566. isExtglob = false;
  8567. isGlob = false;
  8568. }
  8569. let base = str;
  8570. let prefix = '';
  8571. let glob = '';
  8572. if (start > 0) {
  8573. prefix = str.slice(0, start);
  8574. str = str.slice(start);
  8575. lastIndex -= start;
  8576. }
  8577. if (base && isGlob === true && lastIndex > 0) {
  8578. base = str.slice(0, lastIndex);
  8579. glob = str.slice(lastIndex);
  8580. } else if (isGlob === true) {
  8581. base = '';
  8582. glob = str;
  8583. } else {
  8584. base = str;
  8585. }
  8586. if (base && base !== '' && base !== '/' && base !== str) {
  8587. if (isPathSeparator(base.charCodeAt(base.length - 1))) {
  8588. base = base.slice(0, -1);
  8589. }
  8590. }
  8591. if (opts.unescape === true) {
  8592. if (glob) glob = utils.removeBackslashes(glob);
  8593. if (base && backslashes === true) {
  8594. base = utils.removeBackslashes(base);
  8595. }
  8596. }
  8597. const state = {
  8598. prefix,
  8599. input,
  8600. start,
  8601. base,
  8602. glob,
  8603. isBrace,
  8604. isBracket,
  8605. isGlob,
  8606. isExtglob,
  8607. isGlobstar,
  8608. negated,
  8609. negatedExtglob
  8610. };
  8611. if (opts.tokens === true) {
  8612. state.maxDepth = 0;
  8613. if (!isPathSeparator(code)) {
  8614. tokens.push(token);
  8615. }
  8616. state.tokens = tokens;
  8617. }
  8618. if (opts.parts === true || opts.tokens === true) {
  8619. let prevIndex;
  8620. for (let idx = 0; idx < slashes.length; idx++) {
  8621. const n = prevIndex ? prevIndex + 1 : start;
  8622. const i = slashes[idx];
  8623. const value = input.slice(n, i);
  8624. if (opts.tokens) {
  8625. if (idx === 0 && start !== 0) {
  8626. tokens[idx].isPrefix = true;
  8627. tokens[idx].value = prefix;
  8628. } else {
  8629. tokens[idx].value = value;
  8630. }
  8631. depth(tokens[idx]);
  8632. state.maxDepth += tokens[idx].depth;
  8633. }
  8634. if (idx !== 0 || value !== '') {
  8635. parts.push(value);
  8636. }
  8637. prevIndex = i;
  8638. }
  8639. if (prevIndex && prevIndex + 1 < input.length) {
  8640. const value = input.slice(prevIndex + 1);
  8641. parts.push(value);
  8642. if (opts.tokens) {
  8643. tokens[tokens.length - 1].value = value;
  8644. depth(tokens[tokens.length - 1]);
  8645. state.maxDepth += tokens[tokens.length - 1].depth;
  8646. }
  8647. }
  8648. state.slashes = slashes;
  8649. state.parts = parts;
  8650. }
  8651. return state;
  8652. };
  8653. scan_1 = scan;
  8654. return scan_1;
  8655. }
  8656. var parse_1;
  8657. var hasRequiredParse;
  8658. function requireParse () {
  8659. if (hasRequiredParse) return parse_1;
  8660. hasRequiredParse = 1;
  8661. const constants = /*@__PURE__*/ requireConstants();
  8662. const utils = /*@__PURE__*/ requireUtils();
  8663. /**
  8664. * Constants
  8665. */
  8666. const {
  8667. MAX_LENGTH,
  8668. POSIX_REGEX_SOURCE,
  8669. REGEX_NON_SPECIAL_CHARS,
  8670. REGEX_SPECIAL_CHARS_BACKREF,
  8671. REPLACEMENTS
  8672. } = constants;
  8673. /**
  8674. * Helpers
  8675. */
  8676. const expandRange = (args, options) => {
  8677. if (typeof options.expandRange === 'function') {
  8678. return options.expandRange(...args, options);
  8679. }
  8680. args.sort();
  8681. const value = `[${args.join('-')}]`;
  8682. return value;
  8683. };
  8684. /**
  8685. * Create the message for a syntax error
  8686. */
  8687. const syntaxError = (type, char) => {
  8688. return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
  8689. };
  8690. /**
  8691. * Parse the given input string.
  8692. * @param {String} input
  8693. * @param {Object} options
  8694. * @return {Object}
  8695. */
  8696. const parse = (input, options) => {
  8697. if (typeof input !== 'string') {
  8698. throw new TypeError('Expected a string');
  8699. }
  8700. input = REPLACEMENTS[input] || input;
  8701. const opts = { ...options };
  8702. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  8703. let len = input.length;
  8704. if (len > max) {
  8705. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  8706. }
  8707. const bos = { type: 'bos', value: '', output: opts.prepend || '' };
  8708. const tokens = [bos];
  8709. const capture = opts.capture ? '' : '?:';
  8710. // create constants based on platform, for windows or posix
  8711. const PLATFORM_CHARS = constants.globChars(opts.windows);
  8712. const EXTGLOB_CHARS = constants.extglobChars(PLATFORM_CHARS);
  8713. const {
  8714. DOT_LITERAL,
  8715. PLUS_LITERAL,
  8716. SLASH_LITERAL,
  8717. ONE_CHAR,
  8718. DOTS_SLASH,
  8719. NO_DOT,
  8720. NO_DOT_SLASH,
  8721. NO_DOTS_SLASH,
  8722. QMARK,
  8723. QMARK_NO_DOT,
  8724. STAR,
  8725. START_ANCHOR
  8726. } = PLATFORM_CHARS;
  8727. const globstar = opts => {
  8728. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  8729. };
  8730. const nodot = opts.dot ? '' : NO_DOT;
  8731. const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
  8732. let star = opts.bash === true ? globstar(opts) : STAR;
  8733. if (opts.capture) {
  8734. star = `(${star})`;
  8735. }
  8736. // minimatch options support
  8737. if (typeof opts.noext === 'boolean') {
  8738. opts.noextglob = opts.noext;
  8739. }
  8740. const state = {
  8741. input,
  8742. index: -1,
  8743. start: 0,
  8744. dot: opts.dot === true,
  8745. consumed: '',
  8746. output: '',
  8747. prefix: '',
  8748. backtrack: false,
  8749. negated: false,
  8750. brackets: 0,
  8751. braces: 0,
  8752. parens: 0,
  8753. quotes: 0,
  8754. globstar: false,
  8755. tokens
  8756. };
  8757. input = utils.removePrefix(input, state);
  8758. len = input.length;
  8759. const extglobs = [];
  8760. const braces = [];
  8761. const stack = [];
  8762. let prev = bos;
  8763. let value;
  8764. /**
  8765. * Tokenizing helpers
  8766. */
  8767. const eos = () => state.index === len - 1;
  8768. const peek = state.peek = (n = 1) => input[state.index + n];
  8769. const advance = state.advance = () => input[++state.index] || '';
  8770. const remaining = () => input.slice(state.index + 1);
  8771. const consume = (value = '', num = 0) => {
  8772. state.consumed += value;
  8773. state.index += num;
  8774. };
  8775. const append = token => {
  8776. state.output += token.output != null ? token.output : token.value;
  8777. consume(token.value);
  8778. };
  8779. const negate = () => {
  8780. let count = 1;
  8781. while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
  8782. advance();
  8783. state.start++;
  8784. count++;
  8785. }
  8786. if (count % 2 === 0) {
  8787. return false;
  8788. }
  8789. state.negated = true;
  8790. state.start++;
  8791. return true;
  8792. };
  8793. const increment = type => {
  8794. state[type]++;
  8795. stack.push(type);
  8796. };
  8797. const decrement = type => {
  8798. state[type]--;
  8799. stack.pop();
  8800. };
  8801. /**
  8802. * Push tokens onto the tokens array. This helper speeds up
  8803. * tokenizing by 1) helping us avoid backtracking as much as possible,
  8804. * and 2) helping us avoid creating extra tokens when consecutive
  8805. * characters are plain text. This improves performance and simplifies
  8806. * lookbehinds.
  8807. */
  8808. const push = tok => {
  8809. if (prev.type === 'globstar') {
  8810. const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
  8811. const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));
  8812. if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
  8813. state.output = state.output.slice(0, -prev.output.length);
  8814. prev.type = 'star';
  8815. prev.value = '*';
  8816. prev.output = star;
  8817. state.output += prev.output;
  8818. }
  8819. }
  8820. if (extglobs.length && tok.type !== 'paren') {
  8821. extglobs[extglobs.length - 1].inner += tok.value;
  8822. }
  8823. if (tok.value || tok.output) append(tok);
  8824. if (prev && prev.type === 'text' && tok.type === 'text') {
  8825. prev.output = (prev.output || prev.value) + tok.value;
  8826. prev.value += tok.value;
  8827. return;
  8828. }
  8829. tok.prev = prev;
  8830. tokens.push(tok);
  8831. prev = tok;
  8832. };
  8833. const extglobOpen = (type, value) => {
  8834. const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };
  8835. token.prev = prev;
  8836. token.parens = state.parens;
  8837. token.output = state.output;
  8838. const output = (opts.capture ? '(' : '') + token.open;
  8839. increment('parens');
  8840. push({ type, value, output: state.output ? '' : ONE_CHAR });
  8841. push({ type: 'paren', extglob: true, value: advance(), output });
  8842. extglobs.push(token);
  8843. };
  8844. const extglobClose = token => {
  8845. let output = token.close + (opts.capture ? ')' : '');
  8846. let rest;
  8847. if (token.type === 'negate') {
  8848. let extglobStar = star;
  8849. if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
  8850. extglobStar = globstar(opts);
  8851. }
  8852. if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
  8853. output = token.close = `)$))${extglobStar}`;
  8854. }
  8855. if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
  8856. // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis.
  8857. // In this case, we need to parse the string and use it in the output of the original pattern.
  8858. // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`.
  8859. //
  8860. // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`.
  8861. const expression = parse(rest, { ...options, fastpaths: false }).output;
  8862. output = token.close = `)${expression})${extglobStar})`;
  8863. }
  8864. if (token.prev.type === 'bos') {
  8865. state.negatedExtglob = true;
  8866. }
  8867. }
  8868. push({ type: 'paren', extglob: true, value, output });
  8869. decrement('parens');
  8870. };
  8871. /**
  8872. * Fast paths
  8873. */
  8874. if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
  8875. let backslashes = false;
  8876. let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
  8877. if (first === '\\') {
  8878. backslashes = true;
  8879. return m;
  8880. }
  8881. if (first === '?') {
  8882. if (esc) {
  8883. return esc + first + (rest ? QMARK.repeat(rest.length) : '');
  8884. }
  8885. if (index === 0) {
  8886. return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
  8887. }
  8888. return QMARK.repeat(chars.length);
  8889. }
  8890. if (first === '.') {
  8891. return DOT_LITERAL.repeat(chars.length);
  8892. }
  8893. if (first === '*') {
  8894. if (esc) {
  8895. return esc + first + (rest ? star : '');
  8896. }
  8897. return star;
  8898. }
  8899. return esc ? m : `\\${m}`;
  8900. });
  8901. if (backslashes === true) {
  8902. if (opts.unescape === true) {
  8903. output = output.replace(/\\/g, '');
  8904. } else {
  8905. output = output.replace(/\\+/g, m => {
  8906. return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
  8907. });
  8908. }
  8909. }
  8910. if (output === input && opts.contains === true) {
  8911. state.output = input;
  8912. return state;
  8913. }
  8914. state.output = utils.wrapOutput(output, state, options);
  8915. return state;
  8916. }
  8917. /**
  8918. * Tokenize input until we reach end-of-string
  8919. */
  8920. while (!eos()) {
  8921. value = advance();
  8922. if (value === '\u0000') {
  8923. continue;
  8924. }
  8925. /**
  8926. * Escaped characters
  8927. */
  8928. if (value === '\\') {
  8929. const next = peek();
  8930. if (next === '/' && opts.bash !== true) {
  8931. continue;
  8932. }
  8933. if (next === '.' || next === ';') {
  8934. continue;
  8935. }
  8936. if (!next) {
  8937. value += '\\';
  8938. push({ type: 'text', value });
  8939. continue;
  8940. }
  8941. // collapse slashes to reduce potential for exploits
  8942. const match = /^\\+/.exec(remaining());
  8943. let slashes = 0;
  8944. if (match && match[0].length > 2) {
  8945. slashes = match[0].length;
  8946. state.index += slashes;
  8947. if (slashes % 2 !== 0) {
  8948. value += '\\';
  8949. }
  8950. }
  8951. if (opts.unescape === true) {
  8952. value = advance();
  8953. } else {
  8954. value += advance();
  8955. }
  8956. if (state.brackets === 0) {
  8957. push({ type: 'text', value });
  8958. continue;
  8959. }
  8960. }
  8961. /**
  8962. * If we're inside a regex character class, continue
  8963. * until we reach the closing bracket.
  8964. */
  8965. if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
  8966. if (opts.posix !== false && value === ':') {
  8967. const inner = prev.value.slice(1);
  8968. if (inner.includes('[')) {
  8969. prev.posix = true;
  8970. if (inner.includes(':')) {
  8971. const idx = prev.value.lastIndexOf('[');
  8972. const pre = prev.value.slice(0, idx);
  8973. const rest = prev.value.slice(idx + 2);
  8974. const posix = POSIX_REGEX_SOURCE[rest];
  8975. if (posix) {
  8976. prev.value = pre + posix;
  8977. state.backtrack = true;
  8978. advance();
  8979. if (!bos.output && tokens.indexOf(prev) === 1) {
  8980. bos.output = ONE_CHAR;
  8981. }
  8982. continue;
  8983. }
  8984. }
  8985. }
  8986. }
  8987. if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
  8988. value = `\\${value}`;
  8989. }
  8990. if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
  8991. value = `\\${value}`;
  8992. }
  8993. if (opts.posix === true && value === '!' && prev.value === '[') {
  8994. value = '^';
  8995. }
  8996. prev.value += value;
  8997. append({ value });
  8998. continue;
  8999. }
  9000. /**
  9001. * If we're inside a quoted string, continue
  9002. * until we reach the closing double quote.
  9003. */
  9004. if (state.quotes === 1 && value !== '"') {
  9005. value = utils.escapeRegex(value);
  9006. prev.value += value;
  9007. append({ value });
  9008. continue;
  9009. }
  9010. /**
  9011. * Double quotes
  9012. */
  9013. if (value === '"') {
  9014. state.quotes = state.quotes === 1 ? 0 : 1;
  9015. if (opts.keepQuotes === true) {
  9016. push({ type: 'text', value });
  9017. }
  9018. continue;
  9019. }
  9020. /**
  9021. * Parentheses
  9022. */
  9023. if (value === '(') {
  9024. increment('parens');
  9025. push({ type: 'paren', value });
  9026. continue;
  9027. }
  9028. if (value === ')') {
  9029. if (state.parens === 0 && opts.strictBrackets === true) {
  9030. throw new SyntaxError(syntaxError('opening', '('));
  9031. }
  9032. const extglob = extglobs[extglobs.length - 1];
  9033. if (extglob && state.parens === extglob.parens + 1) {
  9034. extglobClose(extglobs.pop());
  9035. continue;
  9036. }
  9037. push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
  9038. decrement('parens');
  9039. continue;
  9040. }
  9041. /**
  9042. * Square brackets
  9043. */
  9044. if (value === '[') {
  9045. if (opts.nobracket === true || !remaining().includes(']')) {
  9046. if (opts.nobracket !== true && opts.strictBrackets === true) {
  9047. throw new SyntaxError(syntaxError('closing', ']'));
  9048. }
  9049. value = `\\${value}`;
  9050. } else {
  9051. increment('brackets');
  9052. }
  9053. push({ type: 'bracket', value });
  9054. continue;
  9055. }
  9056. if (value === ']') {
  9057. if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
  9058. push({ type: 'text', value, output: `\\${value}` });
  9059. continue;
  9060. }
  9061. if (state.brackets === 0) {
  9062. if (opts.strictBrackets === true) {
  9063. throw new SyntaxError(syntaxError('opening', '['));
  9064. }
  9065. push({ type: 'text', value, output: `\\${value}` });
  9066. continue;
  9067. }
  9068. decrement('brackets');
  9069. const prevValue = prev.value.slice(1);
  9070. if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
  9071. value = `/${value}`;
  9072. }
  9073. prev.value += value;
  9074. append({ value });
  9075. // when literal brackets are explicitly disabled
  9076. // assume we should match with a regex character class
  9077. if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) {
  9078. continue;
  9079. }
  9080. const escaped = utils.escapeRegex(prev.value);
  9081. state.output = state.output.slice(0, -prev.value.length);
  9082. // when literal brackets are explicitly enabled
  9083. // assume we should escape the brackets to match literal characters
  9084. if (opts.literalBrackets === true) {
  9085. state.output += escaped;
  9086. prev.value = escaped;
  9087. continue;
  9088. }
  9089. // when the user specifies nothing, try to match both
  9090. prev.value = `(${capture}${escaped}|${prev.value})`;
  9091. state.output += prev.value;
  9092. continue;
  9093. }
  9094. /**
  9095. * Braces
  9096. */
  9097. if (value === '{' && opts.nobrace !== true) {
  9098. increment('braces');
  9099. const open = {
  9100. type: 'brace',
  9101. value,
  9102. output: '(',
  9103. outputIndex: state.output.length,
  9104. tokensIndex: state.tokens.length
  9105. };
  9106. braces.push(open);
  9107. push(open);
  9108. continue;
  9109. }
  9110. if (value === '}') {
  9111. const brace = braces[braces.length - 1];
  9112. if (opts.nobrace === true || !brace) {
  9113. push({ type: 'text', value, output: value });
  9114. continue;
  9115. }
  9116. let output = ')';
  9117. if (brace.dots === true) {
  9118. const arr = tokens.slice();
  9119. const range = [];
  9120. for (let i = arr.length - 1; i >= 0; i--) {
  9121. tokens.pop();
  9122. if (arr[i].type === 'brace') {
  9123. break;
  9124. }
  9125. if (arr[i].type !== 'dots') {
  9126. range.unshift(arr[i].value);
  9127. }
  9128. }
  9129. output = expandRange(range, opts);
  9130. state.backtrack = true;
  9131. }
  9132. if (brace.comma !== true && brace.dots !== true) {
  9133. const out = state.output.slice(0, brace.outputIndex);
  9134. const toks = state.tokens.slice(brace.tokensIndex);
  9135. brace.value = brace.output = '\\{';
  9136. value = output = '\\}';
  9137. state.output = out;
  9138. for (const t of toks) {
  9139. state.output += (t.output || t.value);
  9140. }
  9141. }
  9142. push({ type: 'brace', value, output });
  9143. decrement('braces');
  9144. braces.pop();
  9145. continue;
  9146. }
  9147. /**
  9148. * Pipes
  9149. */
  9150. if (value === '|') {
  9151. if (extglobs.length > 0) {
  9152. extglobs[extglobs.length - 1].conditions++;
  9153. }
  9154. push({ type: 'text', value });
  9155. continue;
  9156. }
  9157. /**
  9158. * Commas
  9159. */
  9160. if (value === ',') {
  9161. let output = value;
  9162. const brace = braces[braces.length - 1];
  9163. if (brace && stack[stack.length - 1] === 'braces') {
  9164. brace.comma = true;
  9165. output = '|';
  9166. }
  9167. push({ type: 'comma', value, output });
  9168. continue;
  9169. }
  9170. /**
  9171. * Slashes
  9172. */
  9173. if (value === '/') {
  9174. // if the beginning of the glob is "./", advance the start
  9175. // to the current index, and don't add the "./" characters
  9176. // to the state. This greatly simplifies lookbehinds when
  9177. // checking for BOS characters like "!" and "." (not "./")
  9178. if (prev.type === 'dot' && state.index === state.start + 1) {
  9179. state.start = state.index + 1;
  9180. state.consumed = '';
  9181. state.output = '';
  9182. tokens.pop();
  9183. prev = bos; // reset "prev" to the first token
  9184. continue;
  9185. }
  9186. push({ type: 'slash', value, output: SLASH_LITERAL });
  9187. continue;
  9188. }
  9189. /**
  9190. * Dots
  9191. */
  9192. if (value === '.') {
  9193. if (state.braces > 0 && prev.type === 'dot') {
  9194. if (prev.value === '.') prev.output = DOT_LITERAL;
  9195. const brace = braces[braces.length - 1];
  9196. prev.type = 'dots';
  9197. prev.output += value;
  9198. prev.value += value;
  9199. brace.dots = true;
  9200. continue;
  9201. }
  9202. if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
  9203. push({ type: 'text', value, output: DOT_LITERAL });
  9204. continue;
  9205. }
  9206. push({ type: 'dot', value, output: DOT_LITERAL });
  9207. continue;
  9208. }
  9209. /**
  9210. * Question marks
  9211. */
  9212. if (value === '?') {
  9213. const isGroup = prev && prev.value === '(';
  9214. if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  9215. extglobOpen('qmark', value);
  9216. continue;
  9217. }
  9218. if (prev && prev.type === 'paren') {
  9219. const next = peek();
  9220. let output = value;
  9221. if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {
  9222. output = `\\${value}`;
  9223. }
  9224. push({ type: 'text', value, output });
  9225. continue;
  9226. }
  9227. if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
  9228. push({ type: 'qmark', value, output: QMARK_NO_DOT });
  9229. continue;
  9230. }
  9231. push({ type: 'qmark', value, output: QMARK });
  9232. continue;
  9233. }
  9234. /**
  9235. * Exclamation
  9236. */
  9237. if (value === '!') {
  9238. if (opts.noextglob !== true && peek() === '(') {
  9239. if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
  9240. extglobOpen('negate', value);
  9241. continue;
  9242. }
  9243. }
  9244. if (opts.nonegate !== true && state.index === 0) {
  9245. negate();
  9246. continue;
  9247. }
  9248. }
  9249. /**
  9250. * Plus
  9251. */
  9252. if (value === '+') {
  9253. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  9254. extglobOpen('plus', value);
  9255. continue;
  9256. }
  9257. if ((prev && prev.value === '(') || opts.regex === false) {
  9258. push({ type: 'plus', value, output: PLUS_LITERAL });
  9259. continue;
  9260. }
  9261. if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {
  9262. push({ type: 'plus', value });
  9263. continue;
  9264. }
  9265. push({ type: 'plus', value: PLUS_LITERAL });
  9266. continue;
  9267. }
  9268. /**
  9269. * Plain text
  9270. */
  9271. if (value === '@') {
  9272. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  9273. push({ type: 'at', extglob: true, value, output: '' });
  9274. continue;
  9275. }
  9276. push({ type: 'text', value });
  9277. continue;
  9278. }
  9279. /**
  9280. * Plain text
  9281. */
  9282. if (value !== '*') {
  9283. if (value === '$' || value === '^') {
  9284. value = `\\${value}`;
  9285. }
  9286. const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
  9287. if (match) {
  9288. value += match[0];
  9289. state.index += match[0].length;
  9290. }
  9291. push({ type: 'text', value });
  9292. continue;
  9293. }
  9294. /**
  9295. * Stars
  9296. */
  9297. if (prev && (prev.type === 'globstar' || prev.star === true)) {
  9298. prev.type = 'star';
  9299. prev.star = true;
  9300. prev.value += value;
  9301. prev.output = star;
  9302. state.backtrack = true;
  9303. state.globstar = true;
  9304. consume(value);
  9305. continue;
  9306. }
  9307. let rest = remaining();
  9308. if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
  9309. extglobOpen('star', value);
  9310. continue;
  9311. }
  9312. if (prev.type === 'star') {
  9313. if (opts.noglobstar === true) {
  9314. consume(value);
  9315. continue;
  9316. }
  9317. const prior = prev.prev;
  9318. const before = prior.prev;
  9319. const isStart = prior.type === 'slash' || prior.type === 'bos';
  9320. const afterStar = before && (before.type === 'star' || before.type === 'globstar');
  9321. if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {
  9322. push({ type: 'star', value, output: '' });
  9323. continue;
  9324. }
  9325. const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
  9326. const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
  9327. if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
  9328. push({ type: 'star', value, output: '' });
  9329. continue;
  9330. }
  9331. // strip consecutive `/**/`
  9332. while (rest.slice(0, 3) === '/**') {
  9333. const after = input[state.index + 4];
  9334. if (after && after !== '/') {
  9335. break;
  9336. }
  9337. rest = rest.slice(3);
  9338. consume('/**', 3);
  9339. }
  9340. if (prior.type === 'bos' && eos()) {
  9341. prev.type = 'globstar';
  9342. prev.value += value;
  9343. prev.output = globstar(opts);
  9344. state.output = prev.output;
  9345. state.globstar = true;
  9346. consume(value);
  9347. continue;
  9348. }
  9349. if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
  9350. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  9351. prior.output = `(?:${prior.output}`;
  9352. prev.type = 'globstar';
  9353. prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
  9354. prev.value += value;
  9355. state.globstar = true;
  9356. state.output += prior.output + prev.output;
  9357. consume(value);
  9358. continue;
  9359. }
  9360. if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
  9361. const end = rest[1] !== void 0 ? '|$' : '';
  9362. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  9363. prior.output = `(?:${prior.output}`;
  9364. prev.type = 'globstar';
  9365. prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
  9366. prev.value += value;
  9367. state.output += prior.output + prev.output;
  9368. state.globstar = true;
  9369. consume(value + advance());
  9370. push({ type: 'slash', value: '/', output: '' });
  9371. continue;
  9372. }
  9373. if (prior.type === 'bos' && rest[0] === '/') {
  9374. prev.type = 'globstar';
  9375. prev.value += value;
  9376. prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
  9377. state.output = prev.output;
  9378. state.globstar = true;
  9379. consume(value + advance());
  9380. push({ type: 'slash', value: '/', output: '' });
  9381. continue;
  9382. }
  9383. // remove single star from output
  9384. state.output = state.output.slice(0, -prev.output.length);
  9385. // reset previous token to globstar
  9386. prev.type = 'globstar';
  9387. prev.output = globstar(opts);
  9388. prev.value += value;
  9389. // reset output with globstar
  9390. state.output += prev.output;
  9391. state.globstar = true;
  9392. consume(value);
  9393. continue;
  9394. }
  9395. const token = { type: 'star', value, output: star };
  9396. if (opts.bash === true) {
  9397. token.output = '.*?';
  9398. if (prev.type === 'bos' || prev.type === 'slash') {
  9399. token.output = nodot + token.output;
  9400. }
  9401. push(token);
  9402. continue;
  9403. }
  9404. if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
  9405. token.output = value;
  9406. push(token);
  9407. continue;
  9408. }
  9409. if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
  9410. if (prev.type === 'dot') {
  9411. state.output += NO_DOT_SLASH;
  9412. prev.output += NO_DOT_SLASH;
  9413. } else if (opts.dot === true) {
  9414. state.output += NO_DOTS_SLASH;
  9415. prev.output += NO_DOTS_SLASH;
  9416. } else {
  9417. state.output += nodot;
  9418. prev.output += nodot;
  9419. }
  9420. if (peek() !== '*') {
  9421. state.output += ONE_CHAR;
  9422. prev.output += ONE_CHAR;
  9423. }
  9424. }
  9425. push(token);
  9426. }
  9427. while (state.brackets > 0) {
  9428. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
  9429. state.output = utils.escapeLast(state.output, '[');
  9430. decrement('brackets');
  9431. }
  9432. while (state.parens > 0) {
  9433. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
  9434. state.output = utils.escapeLast(state.output, '(');
  9435. decrement('parens');
  9436. }
  9437. while (state.braces > 0) {
  9438. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
  9439. state.output = utils.escapeLast(state.output, '{');
  9440. decrement('braces');
  9441. }
  9442. if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
  9443. push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
  9444. }
  9445. // rebuild the output if we had to backtrack at any point
  9446. if (state.backtrack === true) {
  9447. state.output = '';
  9448. for (const token of state.tokens) {
  9449. state.output += token.output != null ? token.output : token.value;
  9450. if (token.suffix) {
  9451. state.output += token.suffix;
  9452. }
  9453. }
  9454. }
  9455. return state;
  9456. };
  9457. /**
  9458. * Fast paths for creating regular expressions for common glob patterns.
  9459. * This can significantly speed up processing and has very little downside
  9460. * impact when none of the fast paths match.
  9461. */
  9462. parse.fastpaths = (input, options) => {
  9463. const opts = { ...options };
  9464. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  9465. const len = input.length;
  9466. if (len > max) {
  9467. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  9468. }
  9469. input = REPLACEMENTS[input] || input;
  9470. // create constants based on platform, for windows or posix
  9471. const {
  9472. DOT_LITERAL,
  9473. SLASH_LITERAL,
  9474. ONE_CHAR,
  9475. DOTS_SLASH,
  9476. NO_DOT,
  9477. NO_DOTS,
  9478. NO_DOTS_SLASH,
  9479. STAR,
  9480. START_ANCHOR
  9481. } = constants.globChars(opts.windows);
  9482. const nodot = opts.dot ? NO_DOTS : NO_DOT;
  9483. const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
  9484. const capture = opts.capture ? '' : '?:';
  9485. const state = { negated: false, prefix: '' };
  9486. let star = opts.bash === true ? '.*?' : STAR;
  9487. if (opts.capture) {
  9488. star = `(${star})`;
  9489. }
  9490. const globstar = opts => {
  9491. if (opts.noglobstar === true) return star;
  9492. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  9493. };
  9494. const create = str => {
  9495. switch (str) {
  9496. case '*':
  9497. return `${nodot}${ONE_CHAR}${star}`;
  9498. case '.*':
  9499. return `${DOT_LITERAL}${ONE_CHAR}${star}`;
  9500. case '*.*':
  9501. return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  9502. case '*/*':
  9503. return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
  9504. case '**':
  9505. return nodot + globstar(opts);
  9506. case '**/*':
  9507. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
  9508. case '**/*.*':
  9509. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  9510. case '**/.*':
  9511. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
  9512. default: {
  9513. const match = /^(.*?)\.(\w+)$/.exec(str);
  9514. if (!match) return;
  9515. const source = create(match[1]);
  9516. if (!source) return;
  9517. return source + DOT_LITERAL + match[2];
  9518. }
  9519. }
  9520. };
  9521. const output = utils.removePrefix(input, state);
  9522. let source = create(output);
  9523. if (source && opts.strictSlashes !== true) {
  9524. source += `${SLASH_LITERAL}?`;
  9525. }
  9526. return source;
  9527. };
  9528. parse_1 = parse;
  9529. return parse_1;
  9530. }
  9531. var picomatch_1$1;
  9532. var hasRequiredPicomatch$1;
  9533. function requirePicomatch$1 () {
  9534. if (hasRequiredPicomatch$1) return picomatch_1$1;
  9535. hasRequiredPicomatch$1 = 1;
  9536. const scan = /*@__PURE__*/ requireScan();
  9537. const parse = /*@__PURE__*/ requireParse();
  9538. const utils = /*@__PURE__*/ requireUtils();
  9539. const constants = /*@__PURE__*/ requireConstants();
  9540. const isObject = val => val && typeof val === 'object' && !Array.isArray(val);
  9541. /**
  9542. * Creates a matcher function from one or more glob patterns. The
  9543. * returned function takes a string to match as its first argument,
  9544. * and returns true if the string is a match. The returned matcher
  9545. * function also takes a boolean as the second argument that, when true,
  9546. * returns an object with additional information.
  9547. *
  9548. * ```js
  9549. * const picomatch = require('picomatch');
  9550. * // picomatch(glob[, options]);
  9551. *
  9552. * const isMatch = picomatch('*.!(*a)');
  9553. * console.log(isMatch('a.a')); //=> false
  9554. * console.log(isMatch('a.b')); //=> true
  9555. * ```
  9556. * @name picomatch
  9557. * @param {String|Array} `globs` One or more glob patterns.
  9558. * @param {Object=} `options`
  9559. * @return {Function=} Returns a matcher function.
  9560. * @api public
  9561. */
  9562. const picomatch = (glob, options, returnState = false) => {
  9563. if (Array.isArray(glob)) {
  9564. const fns = glob.map(input => picomatch(input, options, returnState));
  9565. const arrayMatcher = str => {
  9566. for (const isMatch of fns) {
  9567. const state = isMatch(str);
  9568. if (state) return state;
  9569. }
  9570. return false;
  9571. };
  9572. return arrayMatcher;
  9573. }
  9574. const isState = isObject(glob) && glob.tokens && glob.input;
  9575. if (glob === '' || (typeof glob !== 'string' && !isState)) {
  9576. throw new TypeError('Expected pattern to be a non-empty string');
  9577. }
  9578. const opts = options || {};
  9579. const posix = opts.windows;
  9580. const regex = isState
  9581. ? picomatch.compileRe(glob, options)
  9582. : picomatch.makeRe(glob, options, false, true);
  9583. const state = regex.state;
  9584. delete regex.state;
  9585. let isIgnored = () => false;
  9586. if (opts.ignore) {
  9587. const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
  9588. isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
  9589. }
  9590. const matcher = (input, returnObject = false) => {
  9591. const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix });
  9592. const result = { glob, state, regex, posix, input, output, match, isMatch };
  9593. if (typeof opts.onResult === 'function') {
  9594. opts.onResult(result);
  9595. }
  9596. if (isMatch === false) {
  9597. result.isMatch = false;
  9598. return returnObject ? result : false;
  9599. }
  9600. if (isIgnored(input)) {
  9601. if (typeof opts.onIgnore === 'function') {
  9602. opts.onIgnore(result);
  9603. }
  9604. result.isMatch = false;
  9605. return returnObject ? result : false;
  9606. }
  9607. if (typeof opts.onMatch === 'function') {
  9608. opts.onMatch(result);
  9609. }
  9610. return returnObject ? result : true;
  9611. };
  9612. if (returnState) {
  9613. matcher.state = state;
  9614. }
  9615. return matcher;
  9616. };
  9617. /**
  9618. * Test `input` with the given `regex`. This is used by the main
  9619. * `picomatch()` function to test the input string.
  9620. *
  9621. * ```js
  9622. * const picomatch = require('picomatch');
  9623. * // picomatch.test(input, regex[, options]);
  9624. *
  9625. * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
  9626. * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
  9627. * ```
  9628. * @param {String} `input` String to test.
  9629. * @param {RegExp} `regex`
  9630. * @return {Object} Returns an object with matching info.
  9631. * @api public
  9632. */
  9633. picomatch.test = (input, regex, options, { glob, posix } = {}) => {
  9634. if (typeof input !== 'string') {
  9635. throw new TypeError('Expected input to be a string');
  9636. }
  9637. if (input === '') {
  9638. return { isMatch: false, output: '' };
  9639. }
  9640. const opts = options || {};
  9641. const format = opts.format || (posix ? utils.toPosixSlashes : null);
  9642. let match = input === glob;
  9643. let output = (match && format) ? format(input) : input;
  9644. if (match === false) {
  9645. output = format ? format(input) : input;
  9646. match = output === glob;
  9647. }
  9648. if (match === false || opts.capture === true) {
  9649. if (opts.matchBase === true || opts.basename === true) {
  9650. match = picomatch.matchBase(input, regex, options, posix);
  9651. } else {
  9652. match = regex.exec(output);
  9653. }
  9654. }
  9655. return { isMatch: Boolean(match), match, output };
  9656. };
  9657. /**
  9658. * Match the basename of a filepath.
  9659. *
  9660. * ```js
  9661. * const picomatch = require('picomatch');
  9662. * // picomatch.matchBase(input, glob[, options]);
  9663. * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
  9664. * ```
  9665. * @param {String} `input` String to test.
  9666. * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
  9667. * @return {Boolean}
  9668. * @api public
  9669. */
  9670. picomatch.matchBase = (input, glob, options) => {
  9671. const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
  9672. return regex.test(utils.basename(input));
  9673. };
  9674. /**
  9675. * Returns true if **any** of the given glob `patterns` match the specified `string`.
  9676. *
  9677. * ```js
  9678. * const picomatch = require('picomatch');
  9679. * // picomatch.isMatch(string, patterns[, options]);
  9680. *
  9681. * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
  9682. * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
  9683. * ```
  9684. * @param {String|Array} str The string to test.
  9685. * @param {String|Array} patterns One or more glob patterns to use for matching.
  9686. * @param {Object} [options] See available [options](#options).
  9687. * @return {Boolean} Returns true if any patterns match `str`
  9688. * @api public
  9689. */
  9690. picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
  9691. /**
  9692. * Parse a glob pattern to create the source string for a regular
  9693. * expression.
  9694. *
  9695. * ```js
  9696. * const picomatch = require('picomatch');
  9697. * const result = picomatch.parse(pattern[, options]);
  9698. * ```
  9699. * @param {String} `pattern`
  9700. * @param {Object} `options`
  9701. * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
  9702. * @api public
  9703. */
  9704. picomatch.parse = (pattern, options) => {
  9705. if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options));
  9706. return parse(pattern, { ...options, fastpaths: false });
  9707. };
  9708. /**
  9709. * Scan a glob pattern to separate the pattern into segments.
  9710. *
  9711. * ```js
  9712. * const picomatch = require('picomatch');
  9713. * // picomatch.scan(input[, options]);
  9714. *
  9715. * const result = picomatch.scan('!./foo/*.js');
  9716. * console.log(result);
  9717. * { prefix: '!./',
  9718. * input: '!./foo/*.js',
  9719. * start: 3,
  9720. * base: 'foo',
  9721. * glob: '*.js',
  9722. * isBrace: false,
  9723. * isBracket: false,
  9724. * isGlob: true,
  9725. * isExtglob: false,
  9726. * isGlobstar: false,
  9727. * negated: true }
  9728. * ```
  9729. * @param {String} `input` Glob pattern to scan.
  9730. * @param {Object} `options`
  9731. * @return {Object} Returns an object with
  9732. * @api public
  9733. */
  9734. picomatch.scan = (input, options) => scan(input, options);
  9735. /**
  9736. * Compile a regular expression from the `state` object returned by the
  9737. * [parse()](#parse) method.
  9738. *
  9739. * @param {Object} `state`
  9740. * @param {Object} `options`
  9741. * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
  9742. * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
  9743. * @return {RegExp}
  9744. * @api public
  9745. */
  9746. picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => {
  9747. if (returnOutput === true) {
  9748. return state.output;
  9749. }
  9750. const opts = options || {};
  9751. const prepend = opts.contains ? '' : '^';
  9752. const append = opts.contains ? '' : '$';
  9753. let source = `${prepend}(?:${state.output})${append}`;
  9754. if (state && state.negated === true) {
  9755. source = `^(?!${source}).*$`;
  9756. }
  9757. const regex = picomatch.toRegex(source, options);
  9758. if (returnState === true) {
  9759. regex.state = state;
  9760. }
  9761. return regex;
  9762. };
  9763. /**
  9764. * Create a regular expression from a parsed glob pattern.
  9765. *
  9766. * ```js
  9767. * const picomatch = require('picomatch');
  9768. * const state = picomatch.parse('*.js');
  9769. * // picomatch.compileRe(state[, options]);
  9770. *
  9771. * console.log(picomatch.compileRe(state));
  9772. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  9773. * ```
  9774. * @param {String} `state` The object returned from the `.parse` method.
  9775. * @param {Object} `options`
  9776. * @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.
  9777. * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
  9778. * @return {RegExp} Returns a regex created from the given pattern.
  9779. * @api public
  9780. */
  9781. picomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
  9782. if (!input || typeof input !== 'string') {
  9783. throw new TypeError('Expected a non-empty string');
  9784. }
  9785. let parsed = { negated: false, fastpaths: true };
  9786. if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
  9787. parsed.output = parse.fastpaths(input, options);
  9788. }
  9789. if (!parsed.output) {
  9790. parsed = parse(input, options);
  9791. }
  9792. return picomatch.compileRe(parsed, options, returnOutput, returnState);
  9793. };
  9794. /**
  9795. * Create a regular expression from the given regex source string.
  9796. *
  9797. * ```js
  9798. * const picomatch = require('picomatch');
  9799. * // picomatch.toRegex(source[, options]);
  9800. *
  9801. * const { output } = picomatch.parse('*.js');
  9802. * console.log(picomatch.toRegex(output));
  9803. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  9804. * ```
  9805. * @param {String} `source` Regular expression source string.
  9806. * @param {Object} `options`
  9807. * @return {RegExp}
  9808. * @api public
  9809. */
  9810. picomatch.toRegex = (source, options) => {
  9811. try {
  9812. const opts = options || {};
  9813. return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
  9814. } catch (err) {
  9815. if (options && options.debug === true) throw err;
  9816. return /$^/;
  9817. }
  9818. };
  9819. /**
  9820. * Picomatch constants.
  9821. * @return {Object}
  9822. */
  9823. picomatch.constants = constants;
  9824. /**
  9825. * Expose "picomatch"
  9826. */
  9827. picomatch_1$1 = picomatch;
  9828. return picomatch_1$1;
  9829. }
  9830. var picomatch_1;
  9831. var hasRequiredPicomatch;
  9832. function requirePicomatch () {
  9833. if (hasRequiredPicomatch) return picomatch_1;
  9834. hasRequiredPicomatch = 1;
  9835. const pico = /*@__PURE__*/ requirePicomatch$1();
  9836. const utils = /*@__PURE__*/ requireUtils();
  9837. function picomatch(glob, options, returnState = false) {
  9838. // default to os.platform()
  9839. if (options && (options.windows === null || options.windows === undefined)) {
  9840. // don't mutate the original options object
  9841. options = { ...options, windows: utils.isWindows() };
  9842. }
  9843. return pico(glob, options, returnState);
  9844. }
  9845. Object.assign(picomatch, pico);
  9846. picomatch_1 = picomatch;
  9847. return picomatch_1;
  9848. }
  9849. var picomatchExports = /*@__PURE__*/ requirePicomatch();
  9850. const pm = /*@__PURE__*/getDefaultExportFromCjs(picomatchExports);
  9851. const extractors = {
  9852. ArrayPattern(names, param) {
  9853. for (const element of param.elements) {
  9854. if (element)
  9855. extractors[element.type](names, element);
  9856. }
  9857. },
  9858. AssignmentPattern(names, param) {
  9859. extractors[param.left.type](names, param.left);
  9860. },
  9861. Identifier(names, param) {
  9862. names.push(param.name);
  9863. },
  9864. MemberExpression() { },
  9865. ObjectPattern(names, param) {
  9866. for (const prop of param.properties) {
  9867. // @ts-ignore Typescript reports that this is not a valid type
  9868. if (prop.type === 'RestElement') {
  9869. extractors.RestElement(names, prop);
  9870. }
  9871. else {
  9872. extractors[prop.value.type](names, prop.value);
  9873. }
  9874. }
  9875. },
  9876. RestElement(names, param) {
  9877. extractors[param.argument.type](names, param.argument);
  9878. }
  9879. };
  9880. const extractAssignedNames = function extractAssignedNames(param) {
  9881. const names = [];
  9882. extractors[param.type](names, param);
  9883. return names;
  9884. };
  9885. // Helper since Typescript can't detect readonly arrays with Array.isArray
  9886. function isArray(arg) {
  9887. return Array.isArray(arg);
  9888. }
  9889. function ensureArray$1(thing) {
  9890. if (isArray(thing))
  9891. return thing;
  9892. if (thing == null)
  9893. return [];
  9894. return [thing];
  9895. }
  9896. const normalizePathRegExp = new RegExp(`\\${win32.sep}`, 'g');
  9897. const normalizePath = function normalizePath(filename) {
  9898. return filename.replace(normalizePathRegExp, posix.sep);
  9899. };
  9900. function getMatcherString(id, resolutionBase) {
  9901. if (resolutionBase === false || isAbsolute(id) || id.startsWith('**')) {
  9902. return normalizePath(id);
  9903. }
  9904. // resolve('') is valid and will default to process.cwd()
  9905. const basePath = normalizePath(resolve(resolutionBase || ''))
  9906. // escape all possible (posix + win) path characters that might interfere with regex
  9907. .replace(/[-^$*+?.()|[\]{}]/g, '\\$&');
  9908. // Note that we use posix.join because:
  9909. // 1. the basePath has been normalized to use /
  9910. // 2. the incoming glob (id) matcher, also uses /
  9911. // otherwise Node will force backslash (\) on windows
  9912. return posix.join(basePath, normalizePath(id));
  9913. }
  9914. const createFilter = function createFilter(include, exclude, options) {
  9915. const resolutionBase = options && options.resolve;
  9916. const getMatcher = (id) => id instanceof RegExp
  9917. ? id
  9918. : {
  9919. test: (what) => {
  9920. // this refactor is a tad overly verbose but makes for easy debugging
  9921. const pattern = getMatcherString(id, resolutionBase);
  9922. const fn = pm(pattern, { dot: true });
  9923. const result = fn(what);
  9924. return result;
  9925. }
  9926. };
  9927. const includeMatchers = ensureArray$1(include).map(getMatcher);
  9928. const excludeMatchers = ensureArray$1(exclude).map(getMatcher);
  9929. if (!includeMatchers.length && !excludeMatchers.length)
  9930. return (id) => typeof id === 'string' && !id.includes('\0');
  9931. return function result(id) {
  9932. if (typeof id !== 'string')
  9933. return false;
  9934. if (id.includes('\0'))
  9935. return false;
  9936. const pathId = normalizePath(id);
  9937. for (let i = 0; i < excludeMatchers.length; ++i) {
  9938. const matcher = excludeMatchers[i];
  9939. if (matcher.test(pathId))
  9940. return false;
  9941. }
  9942. for (let i = 0; i < includeMatchers.length; ++i) {
  9943. const matcher = includeMatchers[i];
  9944. if (matcher.test(pathId))
  9945. return true;
  9946. }
  9947. return !includeMatchers.length;
  9948. };
  9949. };
  9950. const reservedWords = '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';
  9951. 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';
  9952. const forbiddenIdentifiers = new Set(`${reservedWords} ${builtins}`.split(' '));
  9953. forbiddenIdentifiers.add('');
  9954. class ArrayPattern extends NodeBase {
  9955. addExportedVariables(variables, exportNamesByVariable) {
  9956. for (const element of this.elements) {
  9957. element?.addExportedVariables(variables, exportNamesByVariable);
  9958. }
  9959. }
  9960. declare(kind) {
  9961. const variables = [];
  9962. for (const element of this.elements) {
  9963. if (element !== null) {
  9964. variables.push(...element.declare(kind, UNKNOWN_EXPRESSION));
  9965. }
  9966. }
  9967. return variables;
  9968. }
  9969. // Patterns can only be deoptimized at the empty path at the moment
  9970. deoptimizePath() {
  9971. for (const element of this.elements) {
  9972. element?.deoptimizePath(EMPTY_PATH);
  9973. }
  9974. }
  9975. // Patterns are only checked at the empty path at the moment
  9976. hasEffectsOnInteractionAtPath(_path, interaction, context) {
  9977. for (const element of this.elements) {
  9978. if (element?.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context))
  9979. return true;
  9980. }
  9981. return false;
  9982. }
  9983. markDeclarationReached() {
  9984. for (const element of this.elements) {
  9985. element?.markDeclarationReached();
  9986. }
  9987. }
  9988. }
  9989. class ArrowFunctionExpression extends FunctionBase {
  9990. constructor() {
  9991. super(...arguments);
  9992. this.objectEntity = null;
  9993. }
  9994. get expression() {
  9995. return isFlagSet(this.flags, 8388608 /* Flag.expression */);
  9996. }
  9997. set expression(value) {
  9998. this.flags = setFlag(this.flags, 8388608 /* Flag.expression */, value);
  9999. }
  10000. createScope(parentScope) {
  10001. this.scope = new ReturnValueScope(parentScope, false);
  10002. }
  10003. hasEffects() {
  10004. if (!this.deoptimized)
  10005. this.applyDeoptimizations();
  10006. return false;
  10007. }
  10008. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10009. if (super.hasEffectsOnInteractionAtPath(path, interaction, context)) {
  10010. return true;
  10011. }
  10012. if (this.annotationNoSideEffects) {
  10013. return false;
  10014. }
  10015. if (interaction.type === INTERACTION_CALLED) {
  10016. const { ignore, brokenFlow } = context;
  10017. context.ignore = {
  10018. breaks: false,
  10019. continues: false,
  10020. labels: new Set(),
  10021. returnYield: true,
  10022. this: false
  10023. };
  10024. if (this.body.hasEffects(context))
  10025. return true;
  10026. context.ignore = ignore;
  10027. context.brokenFlow = brokenFlow;
  10028. }
  10029. return false;
  10030. }
  10031. onlyFunctionCallUsed() {
  10032. const isIIFE = this.parent.type === CallExpression$1 &&
  10033. this.parent.callee === this;
  10034. return isIIFE || super.onlyFunctionCallUsed();
  10035. }
  10036. include(context, includeChildrenRecursively) {
  10037. super.include(context, includeChildrenRecursively);
  10038. for (const parameter of this.params) {
  10039. if (!(parameter instanceof Identifier)) {
  10040. parameter.include(context, includeChildrenRecursively);
  10041. }
  10042. }
  10043. }
  10044. getObjectEntity() {
  10045. if (this.objectEntity !== null) {
  10046. return this.objectEntity;
  10047. }
  10048. return (this.objectEntity = new ObjectEntity([], OBJECT_PROTOTYPE));
  10049. }
  10050. }
  10051. class ObjectPattern extends NodeBase {
  10052. addExportedVariables(variables, exportNamesByVariable) {
  10053. for (const property of this.properties) {
  10054. if (property.type === Property$1) {
  10055. property.value.addExportedVariables(variables, exportNamesByVariable);
  10056. }
  10057. else {
  10058. property.argument.addExportedVariables(variables, exportNamesByVariable);
  10059. }
  10060. }
  10061. }
  10062. declare(kind, init) {
  10063. const variables = [];
  10064. for (const property of this.properties) {
  10065. variables.push(...property.declare(kind, init));
  10066. }
  10067. return variables;
  10068. }
  10069. deoptimizePath(path) {
  10070. if (path.length === 0) {
  10071. for (const property of this.properties) {
  10072. property.deoptimizePath(path);
  10073. }
  10074. }
  10075. }
  10076. hasEffectsOnInteractionAtPath(
  10077. // At the moment, this is only triggered for assignment left-hand sides,
  10078. // where the path is empty
  10079. _path, interaction, context) {
  10080. for (const property of this.properties) {
  10081. if (property.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context))
  10082. return true;
  10083. }
  10084. return false;
  10085. }
  10086. markDeclarationReached() {
  10087. for (const property of this.properties) {
  10088. property.markDeclarationReached();
  10089. }
  10090. }
  10091. }
  10092. class AssignmentExpression extends NodeBase {
  10093. hasEffects(context) {
  10094. const { deoptimized, left, operator, right } = this;
  10095. if (!deoptimized)
  10096. this.applyDeoptimizations();
  10097. // MemberExpressions do not access the property before assignments if the
  10098. // operator is '='.
  10099. return (right.hasEffects(context) || left.hasEffectsAsAssignmentTarget(context, operator !== '='));
  10100. }
  10101. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10102. return this.right.hasEffectsOnInteractionAtPath(path, interaction, context);
  10103. }
  10104. include(context, includeChildrenRecursively) {
  10105. const { deoptimized, left, right, operator } = this;
  10106. if (!deoptimized)
  10107. this.applyDeoptimizations();
  10108. this.included = true;
  10109. if (includeChildrenRecursively ||
  10110. operator !== '=' ||
  10111. left.included ||
  10112. left.hasEffectsAsAssignmentTarget(createHasEffectsContext(), false)) {
  10113. left.includeAsAssignmentTarget(context, includeChildrenRecursively, operator !== '=');
  10114. }
  10115. right.include(context, includeChildrenRecursively);
  10116. }
  10117. initialise() {
  10118. super.initialise();
  10119. if (this.left instanceof Identifier) {
  10120. const variable = this.scope.variables.get(this.left.name);
  10121. if (variable?.kind === 'const') {
  10122. this.scope.context.error(logConstVariableReassignError(), this.left.start);
  10123. }
  10124. }
  10125. this.left.setAssignedValue(this.right);
  10126. }
  10127. render(code, options, { preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  10128. const { left, right, start, end, parent } = this;
  10129. if (left.included) {
  10130. left.render(code, options);
  10131. right.render(code, options);
  10132. }
  10133. else {
  10134. const inclusionStart = findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, '=', left.end) + 1);
  10135. code.remove(start, inclusionStart);
  10136. if (preventASI) {
  10137. removeLineBreaks(code, inclusionStart, right.start);
  10138. }
  10139. right.render(code, options, {
  10140. renderedParentType: renderedParentType || parent.type,
  10141. renderedSurroundingElement: renderedSurroundingElement || parent.type
  10142. });
  10143. }
  10144. if (options.format === 'system') {
  10145. if (left instanceof Identifier) {
  10146. const variable = left.variable;
  10147. const exportNames = options.exportNamesByVariable.get(variable);
  10148. if (exportNames) {
  10149. if (exportNames.length === 1) {
  10150. renderSystemExportExpression(variable, start, end, code, options);
  10151. }
  10152. else {
  10153. renderSystemExportSequenceAfterExpression(variable, start, end, parent.type !== ExpressionStatement$1, code, options);
  10154. }
  10155. return;
  10156. }
  10157. }
  10158. else {
  10159. const systemPatternExports = [];
  10160. left.addExportedVariables(systemPatternExports, options.exportNamesByVariable);
  10161. if (systemPatternExports.length > 0) {
  10162. renderSystemExportFunction(systemPatternExports, start, end, renderedSurroundingElement === ExpressionStatement$1, code, options);
  10163. return;
  10164. }
  10165. }
  10166. }
  10167. if (left.included &&
  10168. left instanceof ObjectPattern &&
  10169. (renderedSurroundingElement === ExpressionStatement$1 ||
  10170. renderedSurroundingElement === ArrowFunctionExpression$1)) {
  10171. code.appendRight(start, '(');
  10172. code.prependLeft(end, ')');
  10173. }
  10174. }
  10175. applyDeoptimizations() {
  10176. this.deoptimized = true;
  10177. this.left.deoptimizePath(EMPTY_PATH);
  10178. this.right.deoptimizePath(UNKNOWN_PATH);
  10179. this.scope.context.requestTreeshakingPass();
  10180. }
  10181. }
  10182. class AssignmentPattern extends NodeBase {
  10183. addExportedVariables(variables, exportNamesByVariable) {
  10184. this.left.addExportedVariables(variables, exportNamesByVariable);
  10185. }
  10186. declare(kind, init) {
  10187. return this.left.declare(kind, init);
  10188. }
  10189. deoptimizePath(path) {
  10190. if (path.length === 0) {
  10191. this.left.deoptimizePath(path);
  10192. }
  10193. }
  10194. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10195. return (path.length > 0 || this.left.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context));
  10196. }
  10197. markDeclarationReached() {
  10198. this.left.markDeclarationReached();
  10199. }
  10200. render(code, options, { isShorthandProperty } = BLANK) {
  10201. this.left.render(code, options, { isShorthandProperty });
  10202. this.right.render(code, options);
  10203. }
  10204. applyDeoptimizations() {
  10205. this.deoptimized = true;
  10206. this.left.deoptimizePath(EMPTY_PATH);
  10207. this.right.deoptimizePath(UNKNOWN_PATH);
  10208. this.scope.context.requestTreeshakingPass();
  10209. }
  10210. }
  10211. class AwaitExpression extends NodeBase {
  10212. hasEffects() {
  10213. if (!this.deoptimized)
  10214. this.applyDeoptimizations();
  10215. return true;
  10216. }
  10217. include(context, includeChildrenRecursively) {
  10218. if (!this.deoptimized)
  10219. this.applyDeoptimizations();
  10220. if (!this.included) {
  10221. this.included = true;
  10222. checkTopLevelAwait: if (!this.scope.context.usesTopLevelAwait) {
  10223. let parent = this.parent;
  10224. do {
  10225. if (parent instanceof FunctionNode || parent instanceof ArrowFunctionExpression)
  10226. break checkTopLevelAwait;
  10227. } while ((parent = parent.parent));
  10228. this.scope.context.usesTopLevelAwait = true;
  10229. }
  10230. }
  10231. this.argument.include(context, includeChildrenRecursively);
  10232. }
  10233. }
  10234. const binaryOperators = {
  10235. '!=': (left, right) => left != right,
  10236. '!==': (left, right) => left !== right,
  10237. '%': (left, right) => left % right,
  10238. '&': (left, right) => left & right,
  10239. '*': (left, right) => left * right,
  10240. // At the moment, "**" will be transpiled to Math.pow
  10241. '**': (left, right) => left ** right,
  10242. '+': (left, right) => left + right,
  10243. '-': (left, right) => left - right,
  10244. '/': (left, right) => left / right,
  10245. '<': (left, right) => left < right,
  10246. '<<': (left, right) => left << right,
  10247. '<=': (left, right) => left <= right,
  10248. '==': (left, right) => left == right,
  10249. '===': (left, right) => left === right,
  10250. '>': (left, right) => left > right,
  10251. '>=': (left, right) => left >= right,
  10252. '>>': (left, right) => left >> right,
  10253. '>>>': (left, right) => left >>> right,
  10254. '^': (left, right) => left ^ right,
  10255. '|': (left, right) => left | right
  10256. // We use the fallback for cases where we return something unknown
  10257. // in: () => UnknownValue,
  10258. // instanceof: () => UnknownValue,
  10259. };
  10260. class BinaryExpression extends NodeBase {
  10261. deoptimizeCache() { }
  10262. getLiteralValueAtPath(path, recursionTracker, origin) {
  10263. if (path.length > 0)
  10264. return UnknownValue;
  10265. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  10266. if (typeof leftValue === 'symbol')
  10267. return UnknownValue;
  10268. const rightValue = this.right.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  10269. if (typeof rightValue === 'symbol')
  10270. return UnknownValue;
  10271. const operatorFunction = binaryOperators[this.operator];
  10272. if (!operatorFunction)
  10273. return UnknownValue;
  10274. return operatorFunction(leftValue, rightValue);
  10275. }
  10276. hasEffects(context) {
  10277. // support some implicit type coercion runtime errors
  10278. if (this.operator === '+' &&
  10279. this.parent instanceof ExpressionStatement &&
  10280. this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) === '') {
  10281. return true;
  10282. }
  10283. return super.hasEffects(context);
  10284. }
  10285. hasEffectsOnInteractionAtPath(path, { type }) {
  10286. return type !== INTERACTION_ACCESSED || path.length > 1;
  10287. }
  10288. removeAnnotations(code) {
  10289. this.left.removeAnnotations(code);
  10290. }
  10291. render(code, options, { renderedSurroundingElement } = BLANK) {
  10292. this.left.render(code, options, { renderedSurroundingElement });
  10293. this.right.render(code, options);
  10294. }
  10295. }
  10296. class BreakStatement extends NodeBase {
  10297. hasEffects(context) {
  10298. if (this.label) {
  10299. if (!context.ignore.labels.has(this.label.name))
  10300. return true;
  10301. context.includedLabels.add(this.label.name);
  10302. }
  10303. else {
  10304. if (!context.ignore.breaks)
  10305. return true;
  10306. context.hasBreak = true;
  10307. }
  10308. context.brokenFlow = true;
  10309. return false;
  10310. }
  10311. include(context) {
  10312. this.included = true;
  10313. if (this.label) {
  10314. this.label.include();
  10315. context.includedLabels.add(this.label.name);
  10316. }
  10317. else {
  10318. context.hasBreak = true;
  10319. }
  10320. context.brokenFlow = true;
  10321. }
  10322. }
  10323. function renderCallArguments(code, options, node) {
  10324. if (node.arguments.length > 0) {
  10325. if (node.arguments[node.arguments.length - 1].included) {
  10326. for (const argument of node.arguments) {
  10327. argument.render(code, options);
  10328. }
  10329. }
  10330. else {
  10331. let lastIncludedIndex = node.arguments.length - 2;
  10332. while (lastIncludedIndex >= 0 && !node.arguments[lastIncludedIndex].included) {
  10333. lastIncludedIndex--;
  10334. }
  10335. if (lastIncludedIndex >= 0) {
  10336. for (let index = 0; index <= lastIncludedIndex; index++) {
  10337. node.arguments[index].render(code, options);
  10338. }
  10339. code.remove(findFirstOccurrenceOutsideComment(code.original, ',', node.arguments[lastIncludedIndex].end), node.end - 1);
  10340. }
  10341. else {
  10342. code.remove(findFirstOccurrenceOutsideComment(code.original, '(', node.callee.end) + 1, node.end - 1);
  10343. }
  10344. }
  10345. }
  10346. }
  10347. class CallExpressionBase extends NodeBase {
  10348. constructor() {
  10349. super(...arguments);
  10350. this.returnExpression = null;
  10351. this.deoptimizableDependentExpressions = [];
  10352. this.expressionsToBeDeoptimized = new Set();
  10353. }
  10354. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  10355. const { args } = interaction;
  10356. const [returnExpression, isPure] = this.getReturnExpression(recursionTracker);
  10357. if (isPure)
  10358. return;
  10359. const deoptimizedExpressions = args.filter(expression => !!expression && expression !== UNKNOWN_EXPRESSION);
  10360. if (deoptimizedExpressions.length === 0)
  10361. return;
  10362. if (returnExpression === UNKNOWN_EXPRESSION) {
  10363. for (const expression of deoptimizedExpressions) {
  10364. expression.deoptimizePath(UNKNOWN_PATH);
  10365. }
  10366. }
  10367. else {
  10368. recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  10369. for (const expression of deoptimizedExpressions) {
  10370. this.expressionsToBeDeoptimized.add(expression);
  10371. }
  10372. returnExpression.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  10373. }, null);
  10374. }
  10375. }
  10376. deoptimizeCache() {
  10377. if (this.returnExpression?.[0] !== UNKNOWN_EXPRESSION) {
  10378. this.returnExpression = UNKNOWN_RETURN_EXPRESSION;
  10379. const { deoptimizableDependentExpressions, expressionsToBeDeoptimized } = this;
  10380. this.expressionsToBeDeoptimized = EMPTY_SET;
  10381. this.deoptimizableDependentExpressions = EMPTY_ARRAY;
  10382. for (const expression of deoptimizableDependentExpressions) {
  10383. expression.deoptimizeCache();
  10384. }
  10385. for (const expression of expressionsToBeDeoptimized) {
  10386. expression.deoptimizePath(UNKNOWN_PATH);
  10387. }
  10388. }
  10389. }
  10390. deoptimizePath(path) {
  10391. if (path.length === 0 ||
  10392. this.scope.context.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  10393. return;
  10394. }
  10395. const [returnExpression] = this.getReturnExpression();
  10396. if (returnExpression !== UNKNOWN_EXPRESSION) {
  10397. returnExpression.deoptimizePath(path);
  10398. }
  10399. }
  10400. getLiteralValueAtPath(path, recursionTracker, origin) {
  10401. const [returnExpression] = this.getReturnExpression(recursionTracker);
  10402. if (returnExpression === UNKNOWN_EXPRESSION) {
  10403. return UnknownValue;
  10404. }
  10405. return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  10406. this.deoptimizableDependentExpressions.push(origin);
  10407. return returnExpression.getLiteralValueAtPath(path, recursionTracker, origin);
  10408. }, UnknownValue);
  10409. }
  10410. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  10411. const returnExpression = this.getReturnExpression(recursionTracker);
  10412. if (returnExpression[0] === UNKNOWN_EXPRESSION) {
  10413. return returnExpression;
  10414. }
  10415. return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  10416. this.deoptimizableDependentExpressions.push(origin);
  10417. const [expression, isPure] = returnExpression[0].getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  10418. return [expression, isPure || returnExpression[1]];
  10419. }, UNKNOWN_RETURN_EXPRESSION);
  10420. }
  10421. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10422. const { type } = interaction;
  10423. if (type === INTERACTION_CALLED) {
  10424. const { args, withNew } = interaction;
  10425. if ((withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, args, this)) {
  10426. return false;
  10427. }
  10428. }
  10429. else if ((type === INTERACTION_ASSIGNED
  10430. ? context.assigned
  10431. : context.accessed).trackEntityAtPathAndGetIfTracked(path, this)) {
  10432. return false;
  10433. }
  10434. const [returnExpression, isPure] = this.getReturnExpression();
  10435. return ((type === INTERACTION_ASSIGNED || !isPure) &&
  10436. returnExpression.hasEffectsOnInteractionAtPath(path, interaction, context));
  10437. }
  10438. }
  10439. class CallExpression extends CallExpressionBase {
  10440. get optional() {
  10441. return isFlagSet(this.flags, 128 /* Flag.optional */);
  10442. }
  10443. set optional(value) {
  10444. this.flags = setFlag(this.flags, 128 /* Flag.optional */, value);
  10445. }
  10446. bind() {
  10447. super.bind();
  10448. if (this.callee instanceof Identifier) {
  10449. const variable = this.scope.findVariable(this.callee.name);
  10450. if (variable.isNamespace) {
  10451. this.scope.context.log(LOGLEVEL_WARN, logCannotCallNamespace(this.callee.name), this.start);
  10452. }
  10453. if (this.callee.name === 'eval') {
  10454. this.scope.context.log(LOGLEVEL_WARN, logEval(this.scope.context.module.id), this.start);
  10455. }
  10456. }
  10457. this.interaction = {
  10458. args: [
  10459. this.callee instanceof MemberExpression && !this.callee.variable
  10460. ? this.callee.object
  10461. : null,
  10462. ...this.arguments
  10463. ],
  10464. type: INTERACTION_CALLED,
  10465. withNew: false
  10466. };
  10467. }
  10468. getLiteralValueAtPathAsChainElement(path, recursionTracker, origin) {
  10469. return getChainElementLiteralValueAtPath(this, this.callee, path, recursionTracker, origin);
  10470. }
  10471. hasEffects(context) {
  10472. if (!this.deoptimized)
  10473. this.applyDeoptimizations();
  10474. for (const argument of this.arguments) {
  10475. if (argument.hasEffects(context))
  10476. return true;
  10477. }
  10478. if (this.annotationPure) {
  10479. return false;
  10480. }
  10481. return (this.callee.hasEffects(context) ||
  10482. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  10483. }
  10484. hasEffectsAsChainElement(context) {
  10485. const calleeHasEffects = 'hasEffectsAsChainElement' in this.callee
  10486. ? this.callee.hasEffectsAsChainElement(context)
  10487. : this.callee.hasEffects(context);
  10488. if (calleeHasEffects === IS_SKIPPED_CHAIN)
  10489. return IS_SKIPPED_CHAIN;
  10490. if (this.optional &&
  10491. this.callee.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) == null) {
  10492. return (!this.annotationPure && calleeHasEffects) || IS_SKIPPED_CHAIN;
  10493. }
  10494. // We only apply deoptimizations lazily once we know we are not skipping
  10495. if (!this.deoptimized)
  10496. this.applyDeoptimizations();
  10497. for (const argument of this.arguments) {
  10498. if (argument.hasEffects(context))
  10499. return true;
  10500. }
  10501. return (!this.annotationPure &&
  10502. (calleeHasEffects ||
  10503. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context)));
  10504. }
  10505. include(context, includeChildrenRecursively) {
  10506. if (!this.deoptimized)
  10507. this.applyDeoptimizations();
  10508. if (includeChildrenRecursively) {
  10509. super.include(context, includeChildrenRecursively);
  10510. if (includeChildrenRecursively === INCLUDE_PARAMETERS &&
  10511. this.callee instanceof Identifier &&
  10512. this.callee.variable) {
  10513. this.callee.variable.markCalledFromTryStatement();
  10514. }
  10515. }
  10516. else {
  10517. this.included = true;
  10518. this.callee.include(context, false);
  10519. }
  10520. this.callee.includeCallArguments(context, this.arguments);
  10521. }
  10522. initialise() {
  10523. super.initialise();
  10524. if (this.annotations &&
  10525. this.scope.context.options.treeshake.annotations) {
  10526. this.annotationPure = this.annotations.some(comment => comment.type === 'pure');
  10527. }
  10528. }
  10529. render(code, options, { renderedSurroundingElement } = BLANK) {
  10530. this.callee.render(code, options, {
  10531. isCalleeOfRenderedParent: true,
  10532. renderedSurroundingElement
  10533. });
  10534. renderCallArguments(code, options, this);
  10535. }
  10536. applyDeoptimizations() {
  10537. this.deoptimized = true;
  10538. this.callee.deoptimizeArgumentsOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  10539. this.scope.context.requestTreeshakingPass();
  10540. }
  10541. getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) {
  10542. if (this.returnExpression === null) {
  10543. this.returnExpression = UNKNOWN_RETURN_EXPRESSION;
  10544. return (this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.interaction, recursionTracker, this));
  10545. }
  10546. return this.returnExpression;
  10547. }
  10548. }
  10549. class CatchClause extends NodeBase {
  10550. createScope(parentScope) {
  10551. this.scope = new ParameterScope(parentScope, true);
  10552. }
  10553. parseNode(esTreeNode) {
  10554. const { body, param, type } = esTreeNode;
  10555. this.type = type;
  10556. if (param) {
  10557. this.param = new (this.scope.context.getNodeConstructor(param.type))(this, this.scope).parseNode(param);
  10558. this.param.declare('parameter', UNKNOWN_EXPRESSION);
  10559. }
  10560. this.body = new BlockStatement(this, this.scope.bodyScope).parseNode(body);
  10561. return super.parseNode(esTreeNode);
  10562. }
  10563. }
  10564. CatchClause.prototype.preventChildBlockScope = true;
  10565. class ChainExpression extends NodeBase {
  10566. // deoptimizations are not relevant as we are not caching values
  10567. deoptimizeCache() { }
  10568. getLiteralValueAtPath(path, recursionTracker, origin) {
  10569. const literalValue = this.expression.getLiteralValueAtPathAsChainElement(path, recursionTracker, origin);
  10570. return literalValue === IS_SKIPPED_CHAIN ? undefined : literalValue;
  10571. }
  10572. hasEffects(context) {
  10573. return this.expression.hasEffectsAsChainElement(context) === true;
  10574. }
  10575. removeAnnotations(code) {
  10576. this.expression.removeAnnotations(code);
  10577. }
  10578. applyDeoptimizations() { }
  10579. }
  10580. class ClassBodyScope extends ChildScope {
  10581. constructor(parent, classNode) {
  10582. const { context } = parent;
  10583. super(parent, context);
  10584. this.variables.set('this', (this.thisVariable = new LocalVariable('this', null, classNode, context, 'other')));
  10585. this.instanceScope = new ChildScope(this, context);
  10586. this.instanceScope.variables.set('this', new ThisVariable(context));
  10587. }
  10588. findLexicalBoundary() {
  10589. return this;
  10590. }
  10591. }
  10592. class ClassBody extends NodeBase {
  10593. createScope(parentScope) {
  10594. this.scope = new ClassBodyScope(parentScope, this.parent);
  10595. }
  10596. include(context, includeChildrenRecursively) {
  10597. this.included = true;
  10598. this.scope.context.includeVariableInModule(this.scope.thisVariable);
  10599. for (const definition of this.body) {
  10600. definition.include(context, includeChildrenRecursively);
  10601. }
  10602. }
  10603. parseNode(esTreeNode) {
  10604. const body = (this.body = []);
  10605. for (const definition of esTreeNode.body) {
  10606. body.push(new (this.scope.context.getNodeConstructor(definition.type))(this, definition.static ? this.scope : this.scope.instanceScope).parseNode(definition));
  10607. }
  10608. return super.parseNode(esTreeNode);
  10609. }
  10610. applyDeoptimizations() { }
  10611. }
  10612. class ClassExpression extends ClassNode {
  10613. render(code, options, { renderedSurroundingElement } = BLANK) {
  10614. super.render(code, options);
  10615. if (renderedSurroundingElement === ExpressionStatement$1) {
  10616. code.appendRight(this.start, '(');
  10617. code.prependLeft(this.end, ')');
  10618. }
  10619. }
  10620. }
  10621. class MultiExpression extends ExpressionEntity {
  10622. constructor(expressions) {
  10623. super();
  10624. this.expressions = expressions;
  10625. }
  10626. deoptimizePath(path) {
  10627. for (const expression of this.expressions) {
  10628. expression.deoptimizePath(path);
  10629. }
  10630. }
  10631. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  10632. return [
  10633. new MultiExpression(this.expressions.map(expression => expression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0])),
  10634. false
  10635. ];
  10636. }
  10637. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10638. for (const expression of this.expressions) {
  10639. if (expression.hasEffectsOnInteractionAtPath(path, interaction, context))
  10640. return true;
  10641. }
  10642. return false;
  10643. }
  10644. }
  10645. class ConditionalExpression extends NodeBase {
  10646. constructor() {
  10647. super(...arguments);
  10648. this.expressionsToBeDeoptimized = [];
  10649. this.usedBranch = null;
  10650. }
  10651. get isBranchResolutionAnalysed() {
  10652. return isFlagSet(this.flags, 65536 /* Flag.isBranchResolutionAnalysed */);
  10653. }
  10654. set isBranchResolutionAnalysed(value) {
  10655. this.flags = setFlag(this.flags, 65536 /* Flag.isBranchResolutionAnalysed */, value);
  10656. }
  10657. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  10658. this.consequent.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  10659. this.alternate.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  10660. }
  10661. deoptimizeCache() {
  10662. if (this.usedBranch !== null) {
  10663. const unusedBranch = this.usedBranch === this.consequent ? this.alternate : this.consequent;
  10664. this.usedBranch = null;
  10665. unusedBranch.deoptimizePath(UNKNOWN_PATH);
  10666. const { expressionsToBeDeoptimized } = this;
  10667. this.expressionsToBeDeoptimized = EMPTY_ARRAY;
  10668. for (const expression of expressionsToBeDeoptimized) {
  10669. expression.deoptimizeCache();
  10670. }
  10671. }
  10672. }
  10673. deoptimizePath(path) {
  10674. const usedBranch = this.getUsedBranch();
  10675. if (usedBranch) {
  10676. usedBranch.deoptimizePath(path);
  10677. }
  10678. else {
  10679. this.consequent.deoptimizePath(path);
  10680. this.alternate.deoptimizePath(path);
  10681. }
  10682. }
  10683. getLiteralValueAtPath(path, recursionTracker, origin) {
  10684. const usedBranch = this.getUsedBranch();
  10685. if (!usedBranch)
  10686. return UnknownValue;
  10687. this.expressionsToBeDeoptimized.push(origin);
  10688. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  10689. }
  10690. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  10691. const usedBranch = this.getUsedBranch();
  10692. if (!usedBranch)
  10693. return [
  10694. new MultiExpression([
  10695. this.consequent.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0],
  10696. this.alternate.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0]
  10697. ]),
  10698. false
  10699. ];
  10700. this.expressionsToBeDeoptimized.push(origin);
  10701. return usedBranch.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  10702. }
  10703. hasEffects(context) {
  10704. if (this.test.hasEffects(context))
  10705. return true;
  10706. const usedBranch = this.getUsedBranch();
  10707. if (!usedBranch) {
  10708. return this.consequent.hasEffects(context) || this.alternate.hasEffects(context);
  10709. }
  10710. return usedBranch.hasEffects(context);
  10711. }
  10712. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10713. const usedBranch = this.getUsedBranch();
  10714. if (!usedBranch) {
  10715. return (this.consequent.hasEffectsOnInteractionAtPath(path, interaction, context) ||
  10716. this.alternate.hasEffectsOnInteractionAtPath(path, interaction, context));
  10717. }
  10718. return usedBranch.hasEffectsOnInteractionAtPath(path, interaction, context);
  10719. }
  10720. include(context, includeChildrenRecursively) {
  10721. this.included = true;
  10722. const usedBranch = this.getUsedBranch();
  10723. if (includeChildrenRecursively || this.test.shouldBeIncluded(context) || usedBranch === null) {
  10724. this.test.include(context, includeChildrenRecursively);
  10725. this.consequent.include(context, includeChildrenRecursively);
  10726. this.alternate.include(context, includeChildrenRecursively);
  10727. }
  10728. else {
  10729. usedBranch.include(context, includeChildrenRecursively);
  10730. }
  10731. }
  10732. includeCallArguments(context, parameters) {
  10733. const usedBranch = this.getUsedBranch();
  10734. if (usedBranch) {
  10735. usedBranch.includeCallArguments(context, parameters);
  10736. }
  10737. else {
  10738. this.consequent.includeCallArguments(context, parameters);
  10739. this.alternate.includeCallArguments(context, parameters);
  10740. }
  10741. }
  10742. removeAnnotations(code) {
  10743. this.test.removeAnnotations(code);
  10744. }
  10745. render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  10746. const usedBranch = this.getUsedBranch();
  10747. if (this.test.included) {
  10748. this.test.render(code, options, { renderedSurroundingElement });
  10749. this.consequent.render(code, options);
  10750. this.alternate.render(code, options);
  10751. }
  10752. else {
  10753. const colonPos = findFirstOccurrenceOutsideComment(code.original, ':', this.consequent.end);
  10754. const inclusionStart = findNonWhiteSpace(code.original, (this.consequent.included
  10755. ? findFirstOccurrenceOutsideComment(code.original, '?', this.test.end)
  10756. : colonPos) + 1);
  10757. if (preventASI) {
  10758. removeLineBreaks(code, inclusionStart, usedBranch.start);
  10759. }
  10760. code.remove(this.start, inclusionStart);
  10761. if (this.consequent.included) {
  10762. code.remove(colonPos, this.end);
  10763. }
  10764. this.test.removeAnnotations(code);
  10765. usedBranch.render(code, options, {
  10766. isCalleeOfRenderedParent,
  10767. preventASI: true,
  10768. renderedParentType: renderedParentType || this.parent.type,
  10769. renderedSurroundingElement: renderedSurroundingElement || this.parent.type
  10770. });
  10771. }
  10772. }
  10773. getUsedBranch() {
  10774. if (this.isBranchResolutionAnalysed) {
  10775. return this.usedBranch;
  10776. }
  10777. this.isBranchResolutionAnalysed = true;
  10778. const testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  10779. return typeof testValue === 'symbol'
  10780. ? null
  10781. : (this.usedBranch = testValue ? this.consequent : this.alternate);
  10782. }
  10783. }
  10784. class ContinueStatement extends NodeBase {
  10785. hasEffects(context) {
  10786. if (this.label) {
  10787. if (!context.ignore.labels.has(this.label.name))
  10788. return true;
  10789. context.includedLabels.add(this.label.name);
  10790. }
  10791. else {
  10792. if (!context.ignore.continues)
  10793. return true;
  10794. context.hasContinue = true;
  10795. }
  10796. context.brokenFlow = true;
  10797. return false;
  10798. }
  10799. include(context) {
  10800. this.included = true;
  10801. if (this.label) {
  10802. this.label.include();
  10803. context.includedLabels.add(this.label.name);
  10804. }
  10805. else {
  10806. context.hasContinue = true;
  10807. }
  10808. context.brokenFlow = true;
  10809. }
  10810. }
  10811. class DebuggerStatement extends NodeBase {
  10812. hasEffects() {
  10813. return true;
  10814. }
  10815. }
  10816. class Decorator extends NodeBase {
  10817. hasEffects(context) {
  10818. return (this.expression.hasEffects(context) ||
  10819. this.expression.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context));
  10820. }
  10821. }
  10822. function hasLoopBodyEffects(context, body) {
  10823. const { brokenFlow, hasBreak, hasContinue, ignore } = context;
  10824. const { breaks, continues } = ignore;
  10825. ignore.breaks = true;
  10826. ignore.continues = true;
  10827. context.hasBreak = false;
  10828. context.hasContinue = false;
  10829. if (body.hasEffects(context))
  10830. return true;
  10831. ignore.breaks = breaks;
  10832. ignore.continues = continues;
  10833. context.hasBreak = hasBreak;
  10834. context.hasContinue = hasContinue;
  10835. context.brokenFlow = brokenFlow;
  10836. return false;
  10837. }
  10838. function includeLoopBody(context, body, includeChildrenRecursively) {
  10839. const { brokenFlow, hasBreak, hasContinue } = context;
  10840. context.hasBreak = false;
  10841. context.hasContinue = false;
  10842. body.include(context, includeChildrenRecursively, { asSingleStatement: true });
  10843. context.hasBreak = hasBreak;
  10844. context.hasContinue = hasContinue;
  10845. context.brokenFlow = brokenFlow;
  10846. }
  10847. class DoWhileStatement extends NodeBase {
  10848. hasEffects(context) {
  10849. if (this.test.hasEffects(context))
  10850. return true;
  10851. return hasLoopBodyEffects(context, this.body);
  10852. }
  10853. include(context, includeChildrenRecursively) {
  10854. this.included = true;
  10855. this.test.include(context, includeChildrenRecursively);
  10856. includeLoopBody(context, this.body, includeChildrenRecursively);
  10857. }
  10858. }
  10859. class EmptyStatement extends NodeBase {
  10860. hasEffects() {
  10861. return false;
  10862. }
  10863. }
  10864. class ExportAllDeclaration extends NodeBase {
  10865. hasEffects() {
  10866. return false;
  10867. }
  10868. initialise() {
  10869. super.initialise();
  10870. this.scope.context.addExport(this);
  10871. }
  10872. render(code, _options, nodeRenderOptions) {
  10873. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  10874. }
  10875. applyDeoptimizations() { }
  10876. }
  10877. ExportAllDeclaration.prototype.needsBoundaries = true;
  10878. class ExportNamedDeclaration extends NodeBase {
  10879. bind() {
  10880. // Do not bind specifiers
  10881. this.declaration?.bind();
  10882. }
  10883. hasEffects(context) {
  10884. return !!this.declaration?.hasEffects(context);
  10885. }
  10886. initialise() {
  10887. super.initialise();
  10888. this.scope.context.addExport(this);
  10889. }
  10890. removeAnnotations(code) {
  10891. this.declaration?.removeAnnotations(code);
  10892. }
  10893. render(code, options, nodeRenderOptions) {
  10894. const { start, end } = nodeRenderOptions;
  10895. if (this.declaration === null) {
  10896. code.remove(start, end);
  10897. }
  10898. else {
  10899. code.remove(this.start, this.declaration.start);
  10900. this.declaration.render(code, options, { end, start });
  10901. }
  10902. }
  10903. applyDeoptimizations() { }
  10904. }
  10905. ExportNamedDeclaration.prototype.needsBoundaries = true;
  10906. class ExportSpecifier extends NodeBase {
  10907. applyDeoptimizations() { }
  10908. }
  10909. class ForInStatement extends NodeBase {
  10910. createScope(parentScope) {
  10911. this.scope = new BlockScope(parentScope);
  10912. }
  10913. hasEffects(context) {
  10914. const { body, deoptimized, left, right } = this;
  10915. if (!deoptimized)
  10916. this.applyDeoptimizations();
  10917. if (left.hasEffectsAsAssignmentTarget(context, false) || right.hasEffects(context))
  10918. return true;
  10919. return hasLoopBodyEffects(context, body);
  10920. }
  10921. include(context, includeChildrenRecursively) {
  10922. const { body, deoptimized, left, right } = this;
  10923. if (!deoptimized)
  10924. this.applyDeoptimizations();
  10925. this.included = true;
  10926. left.includeAsAssignmentTarget(context, includeChildrenRecursively || true, false);
  10927. right.include(context, includeChildrenRecursively);
  10928. includeLoopBody(context, body, includeChildrenRecursively);
  10929. }
  10930. initialise() {
  10931. super.initialise();
  10932. this.left.setAssignedValue(UNKNOWN_EXPRESSION);
  10933. }
  10934. render(code, options) {
  10935. this.left.render(code, options, NO_SEMICOLON);
  10936. this.right.render(code, options, NO_SEMICOLON);
  10937. // handle no space between "in" and the right side
  10938. if (code.original.charCodeAt(this.right.start - 1) === 110 /* n */) {
  10939. code.prependLeft(this.right.start, ' ');
  10940. }
  10941. this.body.render(code, options);
  10942. }
  10943. applyDeoptimizations() {
  10944. this.deoptimized = true;
  10945. this.left.deoptimizePath(EMPTY_PATH);
  10946. this.scope.context.requestTreeshakingPass();
  10947. }
  10948. }
  10949. class ForOfStatement extends NodeBase {
  10950. get await() {
  10951. return isFlagSet(this.flags, 131072 /* Flag.await */);
  10952. }
  10953. set await(value) {
  10954. this.flags = setFlag(this.flags, 131072 /* Flag.await */, value);
  10955. }
  10956. createScope(parentScope) {
  10957. this.scope = new BlockScope(parentScope);
  10958. }
  10959. hasEffects() {
  10960. if (!this.deoptimized)
  10961. this.applyDeoptimizations();
  10962. // Placeholder until proper Symbol.Iterator support
  10963. return true;
  10964. }
  10965. include(context, includeChildrenRecursively) {
  10966. const { body, deoptimized, left, right } = this;
  10967. if (!deoptimized)
  10968. this.applyDeoptimizations();
  10969. this.included = true;
  10970. left.includeAsAssignmentTarget(context, includeChildrenRecursively || true, false);
  10971. right.include(context, includeChildrenRecursively);
  10972. includeLoopBody(context, body, includeChildrenRecursively);
  10973. }
  10974. initialise() {
  10975. super.initialise();
  10976. this.left.setAssignedValue(UNKNOWN_EXPRESSION);
  10977. }
  10978. render(code, options) {
  10979. this.left.render(code, options, NO_SEMICOLON);
  10980. this.right.render(code, options, NO_SEMICOLON);
  10981. // handle no space between "of" and the right side
  10982. if (code.original.charCodeAt(this.right.start - 1) === 102 /* f */) {
  10983. code.prependLeft(this.right.start, ' ');
  10984. }
  10985. this.body.render(code, options);
  10986. }
  10987. applyDeoptimizations() {
  10988. this.deoptimized = true;
  10989. this.left.deoptimizePath(EMPTY_PATH);
  10990. this.right.deoptimizePath(UNKNOWN_PATH);
  10991. this.scope.context.requestTreeshakingPass();
  10992. }
  10993. }
  10994. class ForStatement extends NodeBase {
  10995. createScope(parentScope) {
  10996. this.scope = new BlockScope(parentScope);
  10997. }
  10998. hasEffects(context) {
  10999. if (this.init?.hasEffects(context) ||
  11000. this.test?.hasEffects(context) ||
  11001. this.update?.hasEffects(context)) {
  11002. return true;
  11003. }
  11004. return hasLoopBodyEffects(context, this.body);
  11005. }
  11006. include(context, includeChildrenRecursively) {
  11007. this.included = true;
  11008. this.init?.include(context, includeChildrenRecursively, { asSingleStatement: true });
  11009. this.test?.include(context, includeChildrenRecursively);
  11010. this.update?.include(context, includeChildrenRecursively);
  11011. includeLoopBody(context, this.body, includeChildrenRecursively);
  11012. }
  11013. render(code, options) {
  11014. this.init?.render(code, options, NO_SEMICOLON);
  11015. this.test?.render(code, options, NO_SEMICOLON);
  11016. this.update?.render(code, options, NO_SEMICOLON);
  11017. this.body.render(code, options);
  11018. }
  11019. }
  11020. class FunctionExpression extends FunctionNode {
  11021. createScope(parentScope) {
  11022. super.createScope((this.idScope = new ChildScope(parentScope, parentScope.context)));
  11023. }
  11024. parseNode(esTreeNode) {
  11025. if (esTreeNode.id !== null) {
  11026. this.id = new Identifier(this, this.idScope).parseNode(esTreeNode.id);
  11027. }
  11028. return super.parseNode(esTreeNode);
  11029. }
  11030. onlyFunctionCallUsed() {
  11031. const isIIFE = this.parent.type === CallExpression$1 &&
  11032. this.parent.callee === this &&
  11033. (this.id === null || this.id.variable.getOnlyFunctionCallUsed());
  11034. return isIIFE || super.onlyFunctionCallUsed();
  11035. }
  11036. render(code, options, { renderedSurroundingElement } = BLANK) {
  11037. super.render(code, options);
  11038. if (renderedSurroundingElement === ExpressionStatement$1) {
  11039. code.appendRight(this.start, '(');
  11040. code.prependLeft(this.end, ')');
  11041. }
  11042. }
  11043. }
  11044. class TrackingScope extends BlockScope {
  11045. constructor() {
  11046. super(...arguments);
  11047. this.hoistedDeclarations = [];
  11048. }
  11049. addDeclaration(identifier, context, init, kind) {
  11050. this.hoistedDeclarations.push(identifier);
  11051. return super.addDeclaration(identifier, context, init, kind);
  11052. }
  11053. }
  11054. const unset = Symbol('unset');
  11055. class IfStatement extends NodeBase {
  11056. constructor() {
  11057. super(...arguments);
  11058. this.testValue = unset;
  11059. }
  11060. deoptimizeCache() {
  11061. this.testValue = UnknownValue;
  11062. }
  11063. hasEffects(context) {
  11064. if (this.test.hasEffects(context)) {
  11065. return true;
  11066. }
  11067. const testValue = this.getTestValue();
  11068. if (typeof testValue === 'symbol') {
  11069. const { brokenFlow } = context;
  11070. if (this.consequent.hasEffects(context))
  11071. return true;
  11072. const consequentBrokenFlow = context.brokenFlow;
  11073. context.brokenFlow = brokenFlow;
  11074. if (this.alternate === null)
  11075. return false;
  11076. if (this.alternate.hasEffects(context))
  11077. return true;
  11078. context.brokenFlow = context.brokenFlow && consequentBrokenFlow;
  11079. return false;
  11080. }
  11081. return testValue ? this.consequent.hasEffects(context) : !!this.alternate?.hasEffects(context);
  11082. }
  11083. include(context, includeChildrenRecursively) {
  11084. this.included = true;
  11085. if (includeChildrenRecursively) {
  11086. this.includeRecursively(includeChildrenRecursively, context);
  11087. }
  11088. else {
  11089. const testValue = this.getTestValue();
  11090. if (typeof testValue === 'symbol') {
  11091. this.includeUnknownTest(context);
  11092. }
  11093. else {
  11094. this.includeKnownTest(context, testValue);
  11095. }
  11096. }
  11097. }
  11098. parseNode(esTreeNode) {
  11099. this.consequent = new (this.scope.context.getNodeConstructor(esTreeNode.consequent.type))(this, (this.consequentScope = new TrackingScope(this.scope))).parseNode(esTreeNode.consequent);
  11100. if (esTreeNode.alternate) {
  11101. this.alternate = new (this.scope.context.getNodeConstructor(esTreeNode.alternate.type))(this, (this.alternateScope = new TrackingScope(this.scope))).parseNode(esTreeNode.alternate);
  11102. }
  11103. return super.parseNode(esTreeNode);
  11104. }
  11105. render(code, options) {
  11106. const { snippets: { getPropertyAccess } } = options;
  11107. // Note that unknown test values are always included
  11108. const testValue = this.getTestValue();
  11109. const hoistedDeclarations = [];
  11110. const includesIfElse = this.test.included;
  11111. const noTreeshake = !this.scope.context.options.treeshake;
  11112. if (includesIfElse) {
  11113. this.test.render(code, options);
  11114. }
  11115. else {
  11116. code.remove(this.start, this.consequent.start);
  11117. }
  11118. if (this.consequent.included && (noTreeshake || typeof testValue === 'symbol' || testValue)) {
  11119. this.consequent.render(code, options);
  11120. }
  11121. else {
  11122. code.overwrite(this.consequent.start, this.consequent.end, includesIfElse ? ';' : '');
  11123. hoistedDeclarations.push(...this.consequentScope.hoistedDeclarations);
  11124. }
  11125. if (this.alternate) {
  11126. if (this.alternate.included && (noTreeshake || typeof testValue === 'symbol' || !testValue)) {
  11127. if (includesIfElse) {
  11128. if (code.original.charCodeAt(this.alternate.start - 1) === 101) {
  11129. code.prependLeft(this.alternate.start, ' ');
  11130. }
  11131. }
  11132. else {
  11133. code.remove(this.consequent.end, this.alternate.start);
  11134. }
  11135. this.alternate.render(code, options);
  11136. }
  11137. else {
  11138. if (includesIfElse && this.shouldKeepAlternateBranch()) {
  11139. code.overwrite(this.alternate.start, this.end, ';');
  11140. }
  11141. else {
  11142. code.remove(this.consequent.end, this.end);
  11143. }
  11144. hoistedDeclarations.push(...this.alternateScope.hoistedDeclarations);
  11145. }
  11146. }
  11147. this.renderHoistedDeclarations(hoistedDeclarations, code, getPropertyAccess);
  11148. }
  11149. applyDeoptimizations() { }
  11150. getTestValue() {
  11151. if (this.testValue === unset) {
  11152. return (this.testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this));
  11153. }
  11154. return this.testValue;
  11155. }
  11156. includeKnownTest(context, testValue) {
  11157. if (this.test.shouldBeIncluded(context)) {
  11158. this.test.include(context, false);
  11159. }
  11160. if (testValue && this.consequent.shouldBeIncluded(context)) {
  11161. this.consequent.include(context, false, { asSingleStatement: true });
  11162. }
  11163. if (!testValue && this.alternate?.shouldBeIncluded(context)) {
  11164. this.alternate.include(context, false, { asSingleStatement: true });
  11165. }
  11166. }
  11167. includeRecursively(includeChildrenRecursively, context) {
  11168. this.test.include(context, includeChildrenRecursively);
  11169. this.consequent.include(context, includeChildrenRecursively);
  11170. this.alternate?.include(context, includeChildrenRecursively);
  11171. }
  11172. includeUnknownTest(context) {
  11173. this.test.include(context, false);
  11174. const { brokenFlow } = context;
  11175. let consequentBrokenFlow = false;
  11176. if (this.consequent.shouldBeIncluded(context)) {
  11177. this.consequent.include(context, false, { asSingleStatement: true });
  11178. consequentBrokenFlow = context.brokenFlow;
  11179. context.brokenFlow = brokenFlow;
  11180. }
  11181. if (this.alternate?.shouldBeIncluded(context)) {
  11182. this.alternate.include(context, false, { asSingleStatement: true });
  11183. context.brokenFlow = context.brokenFlow && consequentBrokenFlow;
  11184. }
  11185. }
  11186. renderHoistedDeclarations(hoistedDeclarations, code, getPropertyAccess) {
  11187. const hoistedVariables = [
  11188. ...new Set(hoistedDeclarations.map(identifier => {
  11189. const variable = identifier.variable;
  11190. return variable.included ? variable.getName(getPropertyAccess) : '';
  11191. }))
  11192. ]
  11193. .filter(Boolean)
  11194. .join(', ');
  11195. if (hoistedVariables) {
  11196. const parentType = this.parent.type;
  11197. const needsBraces = parentType !== Program$1 && parentType !== BlockStatement$1;
  11198. code.prependRight(this.start, `${needsBraces ? '{ ' : ''}var ${hoistedVariables}; `);
  11199. if (needsBraces) {
  11200. code.appendLeft(this.end, ` }`);
  11201. }
  11202. }
  11203. }
  11204. shouldKeepAlternateBranch() {
  11205. let currentParent = this.parent;
  11206. do {
  11207. if (currentParent instanceof IfStatement && currentParent.alternate) {
  11208. return true;
  11209. }
  11210. if (currentParent instanceof BlockStatement) {
  11211. return false;
  11212. }
  11213. currentParent = currentParent.parent;
  11214. } while (currentParent);
  11215. return false;
  11216. }
  11217. }
  11218. class ImportAttribute extends NodeBase {
  11219. }
  11220. class ImportDeclaration extends NodeBase {
  11221. // Do not bind specifiers or attributes
  11222. bind() { }
  11223. hasEffects() {
  11224. return false;
  11225. }
  11226. initialise() {
  11227. super.initialise();
  11228. this.scope.context.addImport(this);
  11229. }
  11230. render(code, _options, nodeRenderOptions) {
  11231. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  11232. }
  11233. applyDeoptimizations() { }
  11234. }
  11235. ImportDeclaration.prototype.needsBoundaries = true;
  11236. class ImportDefaultSpecifier extends NodeBase {
  11237. applyDeoptimizations() { }
  11238. }
  11239. function isReassignedExportsMember(variable, exportNamesByVariable) {
  11240. return (variable.renderBaseName !== null && exportNamesByVariable.has(variable) && variable.isReassigned);
  11241. }
  11242. class VariableDeclarator extends NodeBase {
  11243. declareDeclarator(kind, isUsingDeclaration) {
  11244. this.isUsingDeclaration = isUsingDeclaration;
  11245. this.id.declare(kind, this.init || UNDEFINED_EXPRESSION);
  11246. }
  11247. deoptimizePath(path) {
  11248. this.id.deoptimizePath(path);
  11249. }
  11250. hasEffects(context) {
  11251. if (!this.deoptimized)
  11252. this.applyDeoptimizations();
  11253. const initEffect = this.init?.hasEffects(context);
  11254. this.id.markDeclarationReached();
  11255. return initEffect || this.id.hasEffects(context) || this.isUsingDeclaration;
  11256. }
  11257. include(context, includeChildrenRecursively) {
  11258. const { deoptimized, id, init } = this;
  11259. if (!deoptimized)
  11260. this.applyDeoptimizations();
  11261. this.included = true;
  11262. init?.include(context, includeChildrenRecursively);
  11263. id.markDeclarationReached();
  11264. if (includeChildrenRecursively || id.shouldBeIncluded(context)) {
  11265. id.include(context, includeChildrenRecursively);
  11266. }
  11267. }
  11268. removeAnnotations(code) {
  11269. this.init?.removeAnnotations(code);
  11270. }
  11271. render(code, options) {
  11272. const { exportNamesByVariable, snippets: { _, getPropertyAccess } } = options;
  11273. const { end, id, init, start } = this;
  11274. const renderId = id.included || this.isUsingDeclaration;
  11275. if (renderId) {
  11276. id.render(code, options);
  11277. }
  11278. else {
  11279. const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', id.end);
  11280. code.remove(start, findNonWhiteSpace(code.original, operatorPos + 1));
  11281. }
  11282. if (init) {
  11283. if (id instanceof Identifier && init instanceof ClassExpression && !init.id) {
  11284. const renderedVariable = id.variable.getName(getPropertyAccess);
  11285. if (renderedVariable !== id.name) {
  11286. code.appendLeft(init.start + 5, ` ${id.name}`);
  11287. }
  11288. }
  11289. init.render(code, options, renderId ? BLANK : { renderedSurroundingElement: ExpressionStatement$1 });
  11290. }
  11291. else if (id instanceof Identifier &&
  11292. isReassignedExportsMember(id.variable, exportNamesByVariable)) {
  11293. code.appendLeft(end, `${_}=${_}void 0`);
  11294. }
  11295. }
  11296. applyDeoptimizations() {
  11297. this.deoptimized = true;
  11298. const { id, init } = this;
  11299. if (init && id instanceof Identifier && init instanceof ClassExpression && !init.id) {
  11300. const { name, variable } = id;
  11301. for (const accessedVariable of init.scope.accessedOutsideVariables.values()) {
  11302. if (accessedVariable !== variable) {
  11303. accessedVariable.forbidName(name);
  11304. }
  11305. }
  11306. }
  11307. }
  11308. }
  11309. class ImportExpression extends NodeBase {
  11310. constructor() {
  11311. super(...arguments);
  11312. this.inlineNamespace = null;
  11313. this.attributes = null;
  11314. this.mechanism = null;
  11315. this.namespaceExportName = undefined;
  11316. this.resolution = null;
  11317. this.resolutionString = null;
  11318. }
  11319. // Do not bind attributes
  11320. bind() {
  11321. this.source.bind();
  11322. }
  11323. /**
  11324. * Get imported variables for deterministic usage, valid cases are:
  11325. *
  11326. * - `const { foo } = await import('bar')`.
  11327. * - `(await import('bar')).foo`
  11328. * - `import('bar').then(({ foo }) => {})`
  11329. *
  11330. * Returns empty array if it's side-effect only import.
  11331. * Returns undefined if it's not fully deterministic.
  11332. */
  11333. getDeterministicImportedNames() {
  11334. const parent1 = this.parent;
  11335. // Side-effect only: import('bar')
  11336. if (parent1 instanceof ExpressionStatement) {
  11337. return EMPTY_ARRAY;
  11338. }
  11339. if (parent1 instanceof AwaitExpression) {
  11340. const parent2 = parent1.parent;
  11341. // Side-effect only: await import('bar')
  11342. if (parent2 instanceof ExpressionStatement) {
  11343. return EMPTY_ARRAY;
  11344. }
  11345. // Case 1: const { foo } = await import('bar')
  11346. if (parent2 instanceof VariableDeclarator) {
  11347. const declaration = parent2.id;
  11348. return declaration instanceof ObjectPattern
  11349. ? getDeterministicObjectDestructure(declaration)
  11350. : undefined;
  11351. }
  11352. // Case 2: (await import('bar')).foo
  11353. if (parent2 instanceof MemberExpression) {
  11354. const id = parent2.property;
  11355. if (!parent2.computed && id instanceof Identifier) {
  11356. return [id.name];
  11357. }
  11358. }
  11359. return;
  11360. }
  11361. // Case 3: import('bar').then(({ foo }) => {})
  11362. if (parent1 instanceof MemberExpression) {
  11363. const callExpression = parent1.parent;
  11364. const property = parent1.property;
  11365. if (!(callExpression instanceof CallExpression) || !(property instanceof Identifier)) {
  11366. return;
  11367. }
  11368. const memberName = property.name;
  11369. // side-effect only, when only chaining .catch or .finally
  11370. if (callExpression.parent instanceof ExpressionStatement &&
  11371. ['catch', 'finally'].includes(memberName)) {
  11372. return EMPTY_ARRAY;
  11373. }
  11374. if (memberName !== 'then')
  11375. return;
  11376. // Side-effect only: import('bar').then()
  11377. if (callExpression.arguments.length === 0) {
  11378. return EMPTY_ARRAY;
  11379. }
  11380. const argument = callExpression.arguments[0];
  11381. if (callExpression.arguments.length !== 1 ||
  11382. !(argument instanceof ArrowFunctionExpression || argument instanceof FunctionExpression)) {
  11383. return;
  11384. }
  11385. // Side-effect only: import('bar').then(() => {})
  11386. if (argument.params.length === 0) {
  11387. return EMPTY_ARRAY;
  11388. }
  11389. const declaration = argument.params[0];
  11390. if (argument.params.length === 1 && declaration instanceof ObjectPattern) {
  11391. return getDeterministicObjectDestructure(declaration);
  11392. }
  11393. return;
  11394. }
  11395. }
  11396. hasEffects() {
  11397. return true;
  11398. }
  11399. include(context, includeChildrenRecursively) {
  11400. if (!this.included) {
  11401. this.included = true;
  11402. this.scope.context.includeDynamicImport(this);
  11403. this.scope.addAccessedDynamicImport(this);
  11404. }
  11405. this.source.include(context, includeChildrenRecursively);
  11406. }
  11407. initialise() {
  11408. super.initialise();
  11409. this.scope.context.addDynamicImport(this);
  11410. }
  11411. parseNode(esTreeNode) {
  11412. this.sourceAstNode = esTreeNode.source;
  11413. return super.parseNode(esTreeNode);
  11414. }
  11415. render(code, options) {
  11416. const { snippets: { _, getDirectReturnFunction, getObject, getPropertyAccess } } = options;
  11417. if (this.inlineNamespace) {
  11418. const [left, right] = getDirectReturnFunction([], {
  11419. functionReturn: true,
  11420. lineBreakIndent: null,
  11421. name: null
  11422. });
  11423. code.overwrite(this.start, this.end, `Promise.resolve().then(${left}${this.inlineNamespace.getName(getPropertyAccess)}${right})`);
  11424. return;
  11425. }
  11426. if (this.mechanism) {
  11427. code.overwrite(this.start, findFirstOccurrenceOutsideComment(code.original, '(', this.start + 6) + 1, this.mechanism.left);
  11428. code.overwrite(this.end - 1, this.end, this.mechanism.right);
  11429. }
  11430. if (this.resolutionString) {
  11431. code.overwrite(this.source.start, this.source.end, this.resolutionString);
  11432. if (this.namespaceExportName) {
  11433. const [left, right] = getDirectReturnFunction(['n'], {
  11434. functionReturn: true,
  11435. lineBreakIndent: null,
  11436. name: null
  11437. });
  11438. code.prependLeft(this.end, `.then(${left}n.${this.namespaceExportName}${right})`);
  11439. }
  11440. }
  11441. else {
  11442. this.source.render(code, options);
  11443. }
  11444. if (this.attributes !== true) {
  11445. if (this.options) {
  11446. code.overwrite(this.source.end, this.end - 1, '', { contentOnly: true });
  11447. }
  11448. if (this.attributes) {
  11449. code.appendLeft(this.end - 1, `,${_}${getObject([['assert', this.attributes]], {
  11450. lineBreakIndent: null
  11451. })}`);
  11452. }
  11453. }
  11454. }
  11455. setExternalResolution(exportMode, resolution, options, snippets, pluginDriver, accessedGlobalsByScope, resolutionString, namespaceExportName, attributes) {
  11456. const { format } = options;
  11457. this.inlineNamespace = null;
  11458. this.resolution = resolution;
  11459. this.resolutionString = resolutionString;
  11460. this.namespaceExportName = namespaceExportName;
  11461. this.attributes = attributes;
  11462. const accessedGlobals = [...(accessedImportGlobals[format] || [])];
  11463. let helper;
  11464. ({ helper, mechanism: this.mechanism } = this.getDynamicImportMechanismAndHelper(resolution, exportMode, options, snippets, pluginDriver));
  11465. if (helper) {
  11466. accessedGlobals.push(helper);
  11467. }
  11468. if (accessedGlobals.length > 0) {
  11469. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  11470. }
  11471. }
  11472. setInternalResolution(inlineNamespace) {
  11473. this.inlineNamespace = inlineNamespace;
  11474. }
  11475. applyDeoptimizations() { }
  11476. getDynamicImportMechanismAndHelper(resolution, exportMode, { compact, dynamicImportInCjs, format, generatedCode: { arrowFunctions }, interop }, { _, getDirectReturnFunction, getDirectReturnIifeLeft }, pluginDriver) {
  11477. const mechanism = pluginDriver.hookFirstSync('renderDynamicImport', [
  11478. {
  11479. customResolution: typeof this.resolution === 'string' ? this.resolution : null,
  11480. format,
  11481. moduleId: this.scope.context.module.id,
  11482. targetModuleId: this.resolution && typeof this.resolution !== 'string' ? this.resolution.id : null
  11483. }
  11484. ]);
  11485. if (mechanism) {
  11486. return { helper: null, mechanism };
  11487. }
  11488. const hasDynamicTarget = !this.resolution || typeof this.resolution === 'string';
  11489. switch (format) {
  11490. case 'cjs': {
  11491. if (dynamicImportInCjs &&
  11492. (!resolution || typeof resolution === 'string' || resolution instanceof ExternalModule)) {
  11493. return { helper: null, mechanism: null };
  11494. }
  11495. const helper = getInteropHelper(resolution, exportMode, interop);
  11496. let left = `require(`;
  11497. let right = `)`;
  11498. if (helper) {
  11499. left = `/*#__PURE__*/${helper}(${left}`;
  11500. right += ')';
  11501. }
  11502. const [functionLeft, functionRight] = getDirectReturnFunction([], {
  11503. functionReturn: true,
  11504. lineBreakIndent: null,
  11505. name: null
  11506. });
  11507. left = `Promise.resolve().then(${functionLeft}${left}`;
  11508. right += `${functionRight})`;
  11509. if (!arrowFunctions && hasDynamicTarget) {
  11510. left = getDirectReturnIifeLeft(['t'], `${left}t${right}`, {
  11511. needsArrowReturnParens: false,
  11512. needsWrappedFunction: true
  11513. });
  11514. right = ')';
  11515. }
  11516. return {
  11517. helper,
  11518. mechanism: { left, right }
  11519. };
  11520. }
  11521. case 'amd': {
  11522. const resolve = compact ? 'c' : 'resolve';
  11523. const reject = compact ? 'e' : 'reject';
  11524. const helper = getInteropHelper(resolution, exportMode, interop);
  11525. const [resolveLeft, resolveRight] = getDirectReturnFunction(['m'], {
  11526. functionReturn: false,
  11527. lineBreakIndent: null,
  11528. name: null
  11529. });
  11530. const resolveNamespace = helper
  11531. ? `${resolveLeft}${resolve}(/*#__PURE__*/${helper}(m))${resolveRight}`
  11532. : resolve;
  11533. const [handlerLeft, handlerRight] = getDirectReturnFunction([resolve, reject], {
  11534. functionReturn: false,
  11535. lineBreakIndent: null,
  11536. name: null
  11537. });
  11538. let left = `new Promise(${handlerLeft}require([`;
  11539. let right = `],${_}${resolveNamespace},${_}${reject})${handlerRight})`;
  11540. if (!arrowFunctions && hasDynamicTarget) {
  11541. left = getDirectReturnIifeLeft(['t'], `${left}t${right}`, {
  11542. needsArrowReturnParens: false,
  11543. needsWrappedFunction: true
  11544. });
  11545. right = ')';
  11546. }
  11547. return {
  11548. helper,
  11549. mechanism: { left, right }
  11550. };
  11551. }
  11552. case 'system': {
  11553. return {
  11554. helper: null,
  11555. mechanism: {
  11556. left: 'module.import(',
  11557. right: ')'
  11558. }
  11559. };
  11560. }
  11561. }
  11562. return { helper: null, mechanism: null };
  11563. }
  11564. }
  11565. function getInteropHelper(resolution, exportMode, interop) {
  11566. return exportMode === 'external'
  11567. ? namespaceInteropHelpersByInteropType[interop(resolution instanceof ExternalModule ? resolution.id : null)]
  11568. : exportMode === 'default'
  11569. ? INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE
  11570. : null;
  11571. }
  11572. const accessedImportGlobals = {
  11573. amd: ['require'],
  11574. cjs: ['require'],
  11575. system: ['module']
  11576. };
  11577. function getDeterministicObjectDestructure(objectPattern) {
  11578. const variables = [];
  11579. for (const property of objectPattern.properties) {
  11580. if (property.type === 'RestElement' || property.computed || property.key.type !== 'Identifier')
  11581. return;
  11582. variables.push(property.key.name);
  11583. }
  11584. return variables;
  11585. }
  11586. class ImportNamespaceSpecifier extends NodeBase {
  11587. applyDeoptimizations() { }
  11588. }
  11589. class ImportSpecifier extends NodeBase {
  11590. applyDeoptimizations() { }
  11591. }
  11592. class JSXIdentifier extends IdentifierBase {
  11593. constructor() {
  11594. super(...arguments);
  11595. this.isNativeElement = false;
  11596. }
  11597. bind() {
  11598. const type = this.getType();
  11599. if (type === 0 /* IdentifierType.Reference */) {
  11600. this.variable = this.scope.findVariable(this.name);
  11601. this.variable.addReference(this);
  11602. }
  11603. else if (type === 1 /* IdentifierType.NativeElementName */) {
  11604. this.isNativeElement = true;
  11605. }
  11606. }
  11607. render(code, { snippets: { getPropertyAccess }, useOriginalName }) {
  11608. if (this.variable) {
  11609. const name = this.variable.getName(getPropertyAccess, useOriginalName);
  11610. if (name !== this.name) {
  11611. code.overwrite(this.start, this.end, name, {
  11612. contentOnly: true,
  11613. storeName: true
  11614. });
  11615. }
  11616. }
  11617. else if (this.isNativeElement &&
  11618. this.scope.context.options.jsx.mode !== 'preserve') {
  11619. code.update(this.start, this.end, JSON.stringify(this.name));
  11620. }
  11621. }
  11622. getType() {
  11623. switch (this.parent.type) {
  11624. case 'JSXOpeningElement':
  11625. case 'JSXClosingElement': {
  11626. return this.name.startsWith(this.name.charAt(0).toUpperCase())
  11627. ? 0 /* IdentifierType.Reference */
  11628. : 1 /* IdentifierType.NativeElementName */;
  11629. }
  11630. case 'JSXMemberExpression': {
  11631. return this.parent.object === this
  11632. ? 0 /* IdentifierType.Reference */
  11633. : 2 /* IdentifierType.Other */;
  11634. }
  11635. case 'JSXAttribute':
  11636. case 'JSXNamespacedName': {
  11637. return 2 /* IdentifierType.Other */;
  11638. }
  11639. default: {
  11640. /* istanbul ignore next */
  11641. throw new Error(`Unexpected parent node type for JSXIdentifier: ${this.parent.type}`);
  11642. }
  11643. }
  11644. }
  11645. }
  11646. class JSXAttribute extends NodeBase {
  11647. render(code, options, { jsxMode } = BLANK) {
  11648. super.render(code, options);
  11649. if (['classic', 'automatic'].includes(jsxMode)) {
  11650. const { name, value } = this;
  11651. const key = name instanceof JSXIdentifier ? name.name : `${name.namespace.name}:${name.name.name}`;
  11652. if (!(jsxMode === 'automatic' && key === 'key')) {
  11653. const safeKey = stringifyObjectKeyIfNeeded(key);
  11654. if (key !== safeKey) {
  11655. code.overwrite(name.start, name.end, safeKey, { contentOnly: true });
  11656. }
  11657. if (value) {
  11658. code.overwrite(name.end, value.start, ': ', { contentOnly: true });
  11659. }
  11660. else {
  11661. code.appendLeft(name.end, ': true');
  11662. }
  11663. }
  11664. }
  11665. }
  11666. }
  11667. class JSXClosingBase extends NodeBase {
  11668. render(code, options) {
  11669. const { mode } = this.scope.context.options.jsx;
  11670. if (mode !== 'preserve') {
  11671. code.overwrite(this.start, this.end, ')', { contentOnly: true });
  11672. }
  11673. else {
  11674. super.render(code, options);
  11675. }
  11676. }
  11677. }
  11678. class JSXClosingElement extends JSXClosingBase {
  11679. }
  11680. class JSXClosingFragment extends JSXClosingBase {
  11681. }
  11682. class JSXSpreadAttribute extends NodeBase {
  11683. render(code, options) {
  11684. this.argument.render(code, options);
  11685. const { mode } = this.scope.context.options.jsx;
  11686. if (mode !== 'preserve') {
  11687. code.overwrite(this.start, this.argument.start, '', { contentOnly: true });
  11688. code.overwrite(this.argument.end, this.end, '', { contentOnly: true });
  11689. }
  11690. }
  11691. }
  11692. class JSXEmptyExpression extends NodeBase {
  11693. }
  11694. class JSXExpressionContainer extends NodeBase {
  11695. render(code, options) {
  11696. const { mode } = this.scope.context.options.jsx;
  11697. if (mode !== 'preserve') {
  11698. code.remove(this.start, this.expression.start);
  11699. code.remove(this.expression.end, this.end);
  11700. }
  11701. this.expression.render(code, options);
  11702. }
  11703. }
  11704. function getRenderedJsxChildren(children) {
  11705. let renderedChildren = 0;
  11706. for (const child of children) {
  11707. if (!(child instanceof JSXExpressionContainer && child.expression instanceof JSXEmptyExpression)) {
  11708. renderedChildren++;
  11709. }
  11710. }
  11711. return renderedChildren;
  11712. }
  11713. function getAndIncludeFactoryVariable(factory, preserve, importSource, node) {
  11714. const [baseName, nestedName] = factory.split('.');
  11715. let factoryVariable;
  11716. if (importSource) {
  11717. factoryVariable = node.scope.context.getImportedJsxFactoryVariable(nestedName ? 'default' : baseName, node.start, importSource);
  11718. if (preserve) {
  11719. // This pretends we are accessing an included global variable of the same name
  11720. const globalVariable = node.scope.findGlobal(baseName);
  11721. globalVariable.include();
  11722. // This excludes this variable from renaming
  11723. factoryVariable.globalName = baseName;
  11724. }
  11725. }
  11726. else {
  11727. factoryVariable = node.scope.findGlobal(baseName);
  11728. }
  11729. node.scope.context.includeVariableInModule(factoryVariable);
  11730. if (factoryVariable instanceof LocalVariable) {
  11731. factoryVariable.consolidateInitializers();
  11732. factoryVariable.addUsedPlace(node);
  11733. node.scope.context.requestTreeshakingPass();
  11734. }
  11735. return factoryVariable;
  11736. }
  11737. class JSXElementBase extends NodeBase {
  11738. constructor() {
  11739. super(...arguments);
  11740. this.factoryVariable = null;
  11741. this.factory = null;
  11742. }
  11743. initialise() {
  11744. super.initialise();
  11745. const { importSource } = (this.jsxMode = this.getRenderingMode());
  11746. if (importSource) {
  11747. this.scope.context.addImportSource(importSource);
  11748. }
  11749. }
  11750. include(context, includeChildrenRecursively) {
  11751. if (!this.included) {
  11752. const { factory, importSource, mode } = this.jsxMode;
  11753. if (factory) {
  11754. this.factory = factory;
  11755. this.factoryVariable = getAndIncludeFactoryVariable(factory, mode === 'preserve', importSource, this);
  11756. }
  11757. }
  11758. super.include(context, includeChildrenRecursively);
  11759. }
  11760. applyDeoptimizations() { }
  11761. getRenderingMode() {
  11762. const jsx = this.scope.context.options.jsx;
  11763. const { mode, factory, importSource } = jsx;
  11764. if (mode === 'automatic') {
  11765. return {
  11766. factory: getRenderedJsxChildren(this.children) > 1 ? 'jsxs' : 'jsx',
  11767. importSource: jsx.jsxImportSource,
  11768. mode
  11769. };
  11770. }
  11771. return { factory, importSource, mode };
  11772. }
  11773. renderChildren(code, options, openingEnd) {
  11774. const { children } = this;
  11775. let hasMultipleChildren = false;
  11776. let childrenEnd = openingEnd;
  11777. let firstChild = null;
  11778. for (const child of children) {
  11779. if (child instanceof JSXExpressionContainer &&
  11780. child.expression instanceof JSXEmptyExpression) {
  11781. code.remove(childrenEnd, child.end);
  11782. }
  11783. else {
  11784. code.appendLeft(childrenEnd, ', ');
  11785. child.render(code, options);
  11786. if (firstChild) {
  11787. hasMultipleChildren = true;
  11788. }
  11789. else {
  11790. firstChild = child;
  11791. }
  11792. }
  11793. childrenEnd = child.end;
  11794. }
  11795. return { childrenEnd, firstChild, hasMultipleChildren };
  11796. }
  11797. }
  11798. class JSXElement extends JSXElementBase {
  11799. render(code, options) {
  11800. switch (this.jsxMode.mode) {
  11801. case 'classic': {
  11802. this.renderClassicMode(code, options);
  11803. break;
  11804. }
  11805. case 'automatic': {
  11806. this.renderAutomaticMode(code, options);
  11807. break;
  11808. }
  11809. default: {
  11810. super.render(code, options);
  11811. }
  11812. }
  11813. }
  11814. getRenderingMode() {
  11815. const jsx = this.scope.context.options.jsx;
  11816. const { mode, factory, importSource } = jsx;
  11817. if (mode === 'automatic') {
  11818. // In the case there is a key after a spread attribute, we fall back to
  11819. // classic mode, see https://github.com/facebook/react/issues/20031#issuecomment-710346866
  11820. // for reasoning.
  11821. let hasSpread = false;
  11822. for (const attribute of this.openingElement.attributes) {
  11823. if (attribute instanceof JSXSpreadAttribute) {
  11824. hasSpread = true;
  11825. }
  11826. else if (hasSpread && attribute.name.name === 'key') {
  11827. return { factory, importSource, mode: 'classic' };
  11828. }
  11829. }
  11830. }
  11831. return super.getRenderingMode();
  11832. }
  11833. renderClassicMode(code, options) {
  11834. const { snippets: { getPropertyAccess }, useOriginalName } = options;
  11835. const { closingElement, end, factory, factoryVariable, openingElement: { end: openingEnd, selfClosing } } = this;
  11836. const [, ...nestedName] = factory.split('.');
  11837. const { firstAttribute, hasAttributes, hasSpread, inObject, previousEnd } = this.renderAttributes(code, options, [factoryVariable.getName(getPropertyAccess, useOriginalName), ...nestedName].join('.'), false);
  11838. this.wrapAttributes(code, inObject, hasAttributes, hasSpread, firstAttribute, 'null', previousEnd);
  11839. this.renderChildren(code, options, openingEnd);
  11840. if (selfClosing) {
  11841. code.appendLeft(end, ')');
  11842. }
  11843. else {
  11844. closingElement.render(code, options);
  11845. }
  11846. }
  11847. renderAutomaticMode(code, options) {
  11848. const { snippets: { getPropertyAccess }, useOriginalName } = options;
  11849. const { closingElement, end, factoryVariable, openingElement: { end: openindEnd, selfClosing } } = this;
  11850. let { firstAttribute, hasAttributes, hasSpread, inObject, keyAttribute, previousEnd } = this.renderAttributes(code, options, factoryVariable.getName(getPropertyAccess, useOriginalName), true);
  11851. const { firstChild, hasMultipleChildren, childrenEnd } = this.renderChildren(code, options, openindEnd);
  11852. if (firstChild) {
  11853. code.prependRight(firstChild.start, `children: ${hasMultipleChildren ? '[' : ''}`);
  11854. if (!inObject) {
  11855. code.prependRight(firstChild.start, '{ ');
  11856. inObject = true;
  11857. }
  11858. previousEnd = closingElement.start;
  11859. if (hasMultipleChildren) {
  11860. code.appendLeft(previousEnd, ']');
  11861. }
  11862. }
  11863. this.wrapAttributes(code, inObject, hasAttributes || !!firstChild, hasSpread, firstAttribute || firstChild, '{}', childrenEnd);
  11864. if (keyAttribute) {
  11865. const { value } = keyAttribute;
  11866. // This will appear to the left of the moved code...
  11867. code.appendLeft(childrenEnd, ', ');
  11868. if (value) {
  11869. code.move(value.start, value.end, childrenEnd);
  11870. }
  11871. else {
  11872. code.appendLeft(childrenEnd, 'true');
  11873. }
  11874. }
  11875. if (selfClosing) {
  11876. // Moving the key attribute will also move the parenthesis to the right position
  11877. code.appendLeft(keyAttribute?.value?.end || end, ')');
  11878. }
  11879. else {
  11880. closingElement.render(code, options);
  11881. }
  11882. }
  11883. renderAttributes(code, options, factoryName, extractKeyAttribute) {
  11884. const { jsxMode: { mode }, openingElement } = this;
  11885. const { attributes, end: openingEnd, start: openingStart, name: { start: nameStart, end: nameEnd } } = openingElement;
  11886. code.update(openingStart, nameStart, `/*#__PURE__*/${factoryName}(`);
  11887. openingElement.render(code, options, { jsxMode: mode });
  11888. let keyAttribute = null;
  11889. let hasSpread = false;
  11890. let inObject = false;
  11891. let previousEnd = nameEnd;
  11892. let hasAttributes = false;
  11893. let firstAttribute = null;
  11894. for (const attribute of attributes) {
  11895. if (attribute instanceof JSXAttribute) {
  11896. if (extractKeyAttribute && attribute.name.name === 'key') {
  11897. keyAttribute = attribute;
  11898. code.remove(previousEnd, attribute.value?.start || attribute.end);
  11899. continue;
  11900. }
  11901. code.appendLeft(previousEnd, ',');
  11902. if (!inObject) {
  11903. code.prependRight(attribute.start, '{ ');
  11904. inObject = true;
  11905. }
  11906. hasAttributes = true;
  11907. }
  11908. else {
  11909. if (inObject) {
  11910. if (hasAttributes) {
  11911. code.appendLeft(previousEnd, ' ');
  11912. }
  11913. code.appendLeft(previousEnd, '},');
  11914. inObject = false;
  11915. }
  11916. else {
  11917. code.appendLeft(previousEnd, ',');
  11918. }
  11919. hasSpread = true;
  11920. }
  11921. previousEnd = attribute.end;
  11922. if (!firstAttribute) {
  11923. firstAttribute = attribute;
  11924. }
  11925. }
  11926. code.remove(attributes.at(-1)?.end || previousEnd, openingEnd);
  11927. return { firstAttribute, hasAttributes, hasSpread, inObject, keyAttribute, previousEnd };
  11928. }
  11929. wrapAttributes(code, inObject, hasAttributes, hasSpread, firstAttribute, missingAttributesFallback, attributesEnd) {
  11930. if (inObject) {
  11931. code.appendLeft(attributesEnd, ' }');
  11932. }
  11933. if (hasSpread) {
  11934. if (hasAttributes) {
  11935. const { start } = firstAttribute;
  11936. if (firstAttribute instanceof JSXSpreadAttribute) {
  11937. code.prependRight(start, '{}, ');
  11938. }
  11939. code.prependRight(start, 'Object.assign(');
  11940. code.appendLeft(attributesEnd, ')');
  11941. }
  11942. }
  11943. else if (!hasAttributes) {
  11944. code.appendLeft(attributesEnd, `, ${missingAttributesFallback}`);
  11945. }
  11946. }
  11947. }
  11948. class JSXFragment extends JSXElementBase {
  11949. render(code, options) {
  11950. switch (this.jsxMode.mode) {
  11951. case 'classic': {
  11952. this.renderClassicMode(code, options);
  11953. break;
  11954. }
  11955. case 'automatic': {
  11956. this.renderAutomaticMode(code, options);
  11957. break;
  11958. }
  11959. default: {
  11960. super.render(code, options);
  11961. }
  11962. }
  11963. }
  11964. renderClassicMode(code, options) {
  11965. const { snippets: { getPropertyAccess }, useOriginalName } = options;
  11966. const { closingFragment, factory, factoryVariable, openingFragment, start } = this;
  11967. const [, ...nestedName] = factory.split('.');
  11968. openingFragment.render(code, options);
  11969. code.prependRight(start, `/*#__PURE__*/${[
  11970. factoryVariable.getName(getPropertyAccess, useOriginalName),
  11971. ...nestedName
  11972. ].join('.')}(`);
  11973. code.appendLeft(openingFragment.end, ', null');
  11974. this.renderChildren(code, options, openingFragment.end);
  11975. closingFragment.render(code, options);
  11976. }
  11977. renderAutomaticMode(code, options) {
  11978. const { snippets: { getPropertyAccess }, useOriginalName } = options;
  11979. const { closingFragment, factoryVariable, openingFragment, start } = this;
  11980. openingFragment.render(code, options);
  11981. code.prependRight(start, `/*#__PURE__*/${factoryVariable.getName(getPropertyAccess, useOriginalName)}(`);
  11982. const { firstChild, hasMultipleChildren, childrenEnd } = this.renderChildren(code, options, openingFragment.end);
  11983. if (firstChild) {
  11984. code.prependRight(firstChild.start, `{ children: ${hasMultipleChildren ? '[' : ''}`);
  11985. if (hasMultipleChildren) {
  11986. code.appendLeft(closingFragment.start, ']');
  11987. }
  11988. code.appendLeft(childrenEnd, ' }');
  11989. }
  11990. else {
  11991. code.appendLeft(openingFragment.end, ', {}');
  11992. }
  11993. closingFragment.render(code, options);
  11994. }
  11995. }
  11996. class JSXMemberExpression extends NodeBase {
  11997. }
  11998. class JSXNamespacedName extends NodeBase {
  11999. }
  12000. class JSXOpeningElement extends NodeBase {
  12001. render(code, options, { jsxMode = this.scope.context.options.jsx.mode } = {}) {
  12002. this.name.render(code, options);
  12003. for (const attribute of this.attributes) {
  12004. attribute.render(code, options, { jsxMode });
  12005. }
  12006. }
  12007. }
  12008. class JSXOpeningFragment extends NodeBase {
  12009. constructor() {
  12010. super(...arguments);
  12011. this.fragment = null;
  12012. this.fragmentVariable = null;
  12013. }
  12014. include(context, includeChildrenRecursively) {
  12015. if (!this.included) {
  12016. const jsx = this.scope.context.options.jsx;
  12017. if (jsx.mode === 'automatic') {
  12018. this.fragment = 'Fragment';
  12019. this.fragmentVariable = getAndIncludeFactoryVariable('Fragment', false, jsx.jsxImportSource, this);
  12020. }
  12021. else {
  12022. const { fragment, importSource, mode } = jsx;
  12023. if (fragment != null) {
  12024. this.fragment = fragment;
  12025. this.fragmentVariable = getAndIncludeFactoryVariable(fragment, mode === 'preserve', importSource, this);
  12026. }
  12027. }
  12028. }
  12029. super.include(context, includeChildrenRecursively);
  12030. }
  12031. render(code, options) {
  12032. const { mode } = this.scope.context.options.jsx;
  12033. if (mode !== 'preserve') {
  12034. const { snippets: { getPropertyAccess }, useOriginalName } = options;
  12035. const [, ...nestedFragment] = this.fragment.split('.');
  12036. const fragment = [
  12037. this.fragmentVariable.getName(getPropertyAccess, useOriginalName),
  12038. ...nestedFragment
  12039. ].join('.');
  12040. code.update(this.start, this.end, fragment);
  12041. }
  12042. }
  12043. }
  12044. class JSXSpreadChild extends NodeBase {
  12045. render(code, options) {
  12046. super.render(code, options);
  12047. const { mode } = this.scope.context.options.jsx;
  12048. if (mode !== 'preserve') {
  12049. code.overwrite(this.start, this.expression.start, '...', { contentOnly: true });
  12050. code.overwrite(this.expression.end, this.end, '', { contentOnly: true });
  12051. }
  12052. }
  12053. }
  12054. class JSXText extends NodeBase {
  12055. render(code) {
  12056. const { mode } = this.scope.context.options.jsx;
  12057. if (mode !== 'preserve') {
  12058. code.overwrite(this.start, this.end, JSON.stringify(this.value), {
  12059. contentOnly: true
  12060. });
  12061. }
  12062. }
  12063. }
  12064. class LabeledStatement extends NodeBase {
  12065. hasEffects(context) {
  12066. const { brokenFlow, includedLabels } = context;
  12067. context.ignore.labels.add(this.label.name);
  12068. context.includedLabels = new Set();
  12069. let bodyHasEffects = false;
  12070. if (this.body.hasEffects(context)) {
  12071. bodyHasEffects = true;
  12072. }
  12073. else {
  12074. context.ignore.labels.delete(this.label.name);
  12075. if (context.includedLabels.has(this.label.name)) {
  12076. context.includedLabels.delete(this.label.name);
  12077. context.brokenFlow = brokenFlow;
  12078. }
  12079. }
  12080. context.includedLabels = new Set([...includedLabels, ...context.includedLabels]);
  12081. return bodyHasEffects;
  12082. }
  12083. include(context, includeChildrenRecursively) {
  12084. this.included = true;
  12085. const { brokenFlow, includedLabels } = context;
  12086. context.includedLabels = new Set();
  12087. this.body.include(context, includeChildrenRecursively);
  12088. if (includeChildrenRecursively || context.includedLabels.has(this.label.name)) {
  12089. this.label.include();
  12090. context.includedLabels.delete(this.label.name);
  12091. context.brokenFlow = brokenFlow;
  12092. }
  12093. context.includedLabels = new Set([...includedLabels, ...context.includedLabels]);
  12094. }
  12095. render(code, options) {
  12096. if (this.label.included) {
  12097. this.label.render(code, options);
  12098. }
  12099. else {
  12100. code.remove(this.start, findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, ':', this.label.end) + 1));
  12101. }
  12102. this.body.render(code, options);
  12103. }
  12104. }
  12105. class LogicalExpression extends NodeBase {
  12106. constructor() {
  12107. super(...arguments);
  12108. // We collect deoptimization information if usedBranch !== null
  12109. this.expressionsToBeDeoptimized = [];
  12110. this.usedBranch = null;
  12111. }
  12112. //private isBranchResolutionAnalysed = false;
  12113. get isBranchResolutionAnalysed() {
  12114. return isFlagSet(this.flags, 65536 /* Flag.isBranchResolutionAnalysed */);
  12115. }
  12116. set isBranchResolutionAnalysed(value) {
  12117. this.flags = setFlag(this.flags, 65536 /* Flag.isBranchResolutionAnalysed */, value);
  12118. }
  12119. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  12120. this.left.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  12121. this.right.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  12122. }
  12123. deoptimizeCache() {
  12124. if (this.usedBranch) {
  12125. const unusedBranch = this.usedBranch === this.left ? this.right : this.left;
  12126. this.usedBranch = null;
  12127. unusedBranch.deoptimizePath(UNKNOWN_PATH);
  12128. const { scope: { context }, expressionsToBeDeoptimized } = this;
  12129. this.expressionsToBeDeoptimized = EMPTY_ARRAY;
  12130. for (const expression of expressionsToBeDeoptimized) {
  12131. expression.deoptimizeCache();
  12132. }
  12133. // Request another pass because we need to ensure "include" runs again if
  12134. // it is rendered
  12135. context.requestTreeshakingPass();
  12136. }
  12137. }
  12138. deoptimizePath(path) {
  12139. const usedBranch = this.getUsedBranch();
  12140. if (usedBranch) {
  12141. usedBranch.deoptimizePath(path);
  12142. }
  12143. else {
  12144. this.left.deoptimizePath(path);
  12145. this.right.deoptimizePath(path);
  12146. }
  12147. }
  12148. getLiteralValueAtPath(path, recursionTracker, origin) {
  12149. const usedBranch = this.getUsedBranch();
  12150. if (!usedBranch)
  12151. return UnknownValue;
  12152. this.expressionsToBeDeoptimized.push(origin);
  12153. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  12154. }
  12155. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  12156. const usedBranch = this.getUsedBranch();
  12157. if (!usedBranch)
  12158. return [
  12159. new MultiExpression([
  12160. this.left.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0],
  12161. this.right.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0]
  12162. ]),
  12163. false
  12164. ];
  12165. this.expressionsToBeDeoptimized.push(origin);
  12166. return usedBranch.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  12167. }
  12168. hasEffects(context) {
  12169. if (this.left.hasEffects(context)) {
  12170. return true;
  12171. }
  12172. if (this.getUsedBranch() !== this.left) {
  12173. return this.right.hasEffects(context);
  12174. }
  12175. return false;
  12176. }
  12177. hasEffectsOnInteractionAtPath(path, interaction, context) {
  12178. const usedBranch = this.getUsedBranch();
  12179. if (!usedBranch) {
  12180. return (this.left.hasEffectsOnInteractionAtPath(path, interaction, context) ||
  12181. this.right.hasEffectsOnInteractionAtPath(path, interaction, context));
  12182. }
  12183. return usedBranch.hasEffectsOnInteractionAtPath(path, interaction, context);
  12184. }
  12185. include(context, includeChildrenRecursively) {
  12186. this.included = true;
  12187. const usedBranch = this.getUsedBranch();
  12188. if (includeChildrenRecursively ||
  12189. (usedBranch === this.right && this.left.shouldBeIncluded(context)) ||
  12190. !usedBranch) {
  12191. this.left.include(context, includeChildrenRecursively);
  12192. this.right.include(context, includeChildrenRecursively);
  12193. }
  12194. else {
  12195. usedBranch.include(context, includeChildrenRecursively);
  12196. }
  12197. }
  12198. removeAnnotations(code) {
  12199. this.left.removeAnnotations(code);
  12200. }
  12201. render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  12202. if (!this.left.included || !this.right.included) {
  12203. const operatorPos = findFirstOccurrenceOutsideComment(code.original, this.operator, this.left.end);
  12204. if (this.right.included) {
  12205. const removePos = findNonWhiteSpace(code.original, operatorPos + 2);
  12206. code.remove(this.start, removePos);
  12207. if (preventASI) {
  12208. removeLineBreaks(code, removePos, this.right.start);
  12209. }
  12210. this.left.removeAnnotations(code);
  12211. }
  12212. else {
  12213. code.remove(findLastWhiteSpaceReverse(code.original, this.left.end, operatorPos), this.end);
  12214. }
  12215. this.getUsedBranch().render(code, options, {
  12216. isCalleeOfRenderedParent,
  12217. preventASI,
  12218. renderedParentType: renderedParentType || this.parent.type,
  12219. renderedSurroundingElement: renderedSurroundingElement || this.parent.type
  12220. });
  12221. }
  12222. else {
  12223. this.left.render(code, options, {
  12224. preventASI,
  12225. renderedSurroundingElement
  12226. });
  12227. this.right.render(code, options);
  12228. }
  12229. }
  12230. getUsedBranch() {
  12231. if (!this.isBranchResolutionAnalysed) {
  12232. this.isBranchResolutionAnalysed = true;
  12233. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  12234. if (typeof leftValue === 'symbol') {
  12235. return null;
  12236. }
  12237. else {
  12238. this.usedBranch =
  12239. (this.operator === '||' && leftValue) ||
  12240. (this.operator === '&&' && !leftValue) ||
  12241. (this.operator === '??' && leftValue != null)
  12242. ? this.left
  12243. : this.right;
  12244. }
  12245. }
  12246. return this.usedBranch;
  12247. }
  12248. }
  12249. class NewExpression extends NodeBase {
  12250. hasEffects(context) {
  12251. if (!this.deoptimized)
  12252. this.applyDeoptimizations();
  12253. for (const argument of this.arguments) {
  12254. if (argument.hasEffects(context))
  12255. return true;
  12256. }
  12257. if (this.annotationPure) {
  12258. return false;
  12259. }
  12260. return (this.callee.hasEffects(context) ||
  12261. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  12262. }
  12263. hasEffectsOnInteractionAtPath(path, { type }) {
  12264. return path.length > 0 || type !== INTERACTION_ACCESSED;
  12265. }
  12266. include(context, includeChildrenRecursively) {
  12267. if (!this.deoptimized)
  12268. this.applyDeoptimizations();
  12269. if (includeChildrenRecursively) {
  12270. super.include(context, includeChildrenRecursively);
  12271. }
  12272. else {
  12273. this.included = true;
  12274. this.callee.include(context, false);
  12275. }
  12276. this.callee.includeCallArguments(context, this.arguments);
  12277. }
  12278. initialise() {
  12279. super.initialise();
  12280. this.interaction = {
  12281. args: [null, ...this.arguments],
  12282. type: INTERACTION_CALLED,
  12283. withNew: true
  12284. };
  12285. if (this.annotations &&
  12286. this.scope.context.options.treeshake.annotations) {
  12287. this.annotationPure = this.annotations.some(comment => comment.type === 'pure');
  12288. }
  12289. }
  12290. render(code, options) {
  12291. this.callee.render(code, options);
  12292. renderCallArguments(code, options, this);
  12293. }
  12294. applyDeoptimizations() {
  12295. this.deoptimized = true;
  12296. this.callee.deoptimizeArgumentsOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  12297. this.scope.context.requestTreeshakingPass();
  12298. }
  12299. }
  12300. class ObjectExpression extends NodeBase {
  12301. constructor() {
  12302. super(...arguments);
  12303. this.objectEntity = null;
  12304. }
  12305. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  12306. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  12307. }
  12308. deoptimizeCache() {
  12309. this.getObjectEntity().deoptimizeAllProperties();
  12310. }
  12311. deoptimizePath(path) {
  12312. this.getObjectEntity().deoptimizePath(path);
  12313. }
  12314. getLiteralValueAtPath(path, recursionTracker, origin) {
  12315. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  12316. }
  12317. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  12318. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  12319. }
  12320. hasEffectsOnInteractionAtPath(path, interaction, context) {
  12321. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  12322. }
  12323. render(code, options, { renderedSurroundingElement } = BLANK) {
  12324. super.render(code, options);
  12325. if (renderedSurroundingElement === ExpressionStatement$1 ||
  12326. renderedSurroundingElement === ArrowFunctionExpression$1) {
  12327. code.appendRight(this.start, '(');
  12328. code.prependLeft(this.end, ')');
  12329. }
  12330. }
  12331. applyDeoptimizations() { }
  12332. getObjectEntity() {
  12333. if (this.objectEntity !== null) {
  12334. return this.objectEntity;
  12335. }
  12336. let prototype = OBJECT_PROTOTYPE;
  12337. const properties = [];
  12338. for (const property of this.properties) {
  12339. if (property instanceof SpreadElement) {
  12340. properties.push({ key: UnknownKey, kind: 'init', property });
  12341. continue;
  12342. }
  12343. let key;
  12344. if (property.computed) {
  12345. const keyValue = property.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  12346. if (typeof keyValue === 'symbol') {
  12347. properties.push({ key: UnknownKey, kind: property.kind, property });
  12348. continue;
  12349. }
  12350. else {
  12351. key = String(keyValue);
  12352. }
  12353. }
  12354. else {
  12355. key =
  12356. property.key instanceof Identifier
  12357. ? property.key.name
  12358. : String(property.key.value);
  12359. if (key === '__proto__' && property.kind === 'init') {
  12360. prototype =
  12361. property.value instanceof Literal && property.value.value === null
  12362. ? null
  12363. : property.value;
  12364. continue;
  12365. }
  12366. }
  12367. properties.push({ key, kind: property.kind, property });
  12368. }
  12369. return (this.objectEntity = new ObjectEntity(properties, prototype));
  12370. }
  12371. }
  12372. class PanicError extends NodeBase {
  12373. initialise() {
  12374. const id = this.scope.context.module.id;
  12375. // This simulates the current nested error structure. We could also just
  12376. // replace it with a flat error.
  12377. const parseError = getRollupError(logParseError(this.message));
  12378. const moduleParseError = logModuleParseError(parseError, id);
  12379. return error(moduleParseError);
  12380. }
  12381. }
  12382. class ParseError extends NodeBase {
  12383. initialise() {
  12384. const pos = this.start;
  12385. const id = this.scope.context.module.id;
  12386. // This simulates the current nested error structure. We could also just
  12387. // replace it with a flat error.
  12388. const parseError = getRollupError(logParseError(this.message, pos));
  12389. const moduleParseError = logModuleParseError(parseError, id);
  12390. this.scope.context.error(moduleParseError, pos);
  12391. }
  12392. }
  12393. class PrivateIdentifier extends NodeBase {
  12394. }
  12395. class Program extends NodeBase {
  12396. constructor() {
  12397. super(...arguments);
  12398. this.hasCachedEffect = null;
  12399. this.hasLoggedEffect = false;
  12400. }
  12401. hasCachedEffects() {
  12402. if (!this.included) {
  12403. return false;
  12404. }
  12405. return this.hasCachedEffect === null
  12406. ? (this.hasCachedEffect = this.hasEffects(createHasEffectsContext()))
  12407. : this.hasCachedEffect;
  12408. }
  12409. hasEffects(context) {
  12410. for (const node of this.body) {
  12411. if (node.hasEffects(context)) {
  12412. if (this.scope.context.options.experimentalLogSideEffects && !this.hasLoggedEffect) {
  12413. this.hasLoggedEffect = true;
  12414. const { code, log, module } = this.scope.context;
  12415. log(LOGLEVEL_INFO, logFirstSideEffect(code, module.id, locate(code, node.start, { offsetLine: 1 })), node.start);
  12416. }
  12417. return (this.hasCachedEffect = true);
  12418. }
  12419. }
  12420. return false;
  12421. }
  12422. include(context, includeChildrenRecursively) {
  12423. this.included = true;
  12424. for (const node of this.body) {
  12425. if (includeChildrenRecursively || node.shouldBeIncluded(context)) {
  12426. node.include(context, includeChildrenRecursively);
  12427. }
  12428. }
  12429. }
  12430. initialise() {
  12431. super.initialise();
  12432. if (this.invalidAnnotations)
  12433. for (const { start, end, type } of this.invalidAnnotations) {
  12434. this.scope.context.magicString.remove(start, end);
  12435. if (type === 'pure' || type === 'noSideEffects') {
  12436. this.scope.context.log(LOGLEVEL_WARN, logInvalidAnnotation(this.scope.context.code.slice(start, end), this.scope.context.module.id, type), start);
  12437. }
  12438. }
  12439. }
  12440. render(code, options) {
  12441. let start = this.start;
  12442. if (code.original.startsWith('#!')) {
  12443. start = Math.min(code.original.indexOf('\n') + 1, this.end);
  12444. code.remove(0, start);
  12445. }
  12446. if (this.body.length > 0) {
  12447. // Keep all consecutive lines that start with a comment
  12448. while (code.original[start] === '/' && /[*/]/.test(code.original[start + 1])) {
  12449. const firstLineBreak = findFirstLineBreakOutsideComment(code.original.slice(start, this.body[0].start));
  12450. if (firstLineBreak[0] === -1) {
  12451. break;
  12452. }
  12453. start += firstLineBreak[1];
  12454. }
  12455. renderStatementList(this.body, code, start, this.end, options);
  12456. }
  12457. else {
  12458. super.render(code, options);
  12459. }
  12460. }
  12461. applyDeoptimizations() { }
  12462. }
  12463. class Property extends MethodBase {
  12464. constructor() {
  12465. super(...arguments);
  12466. this.declarationInit = null;
  12467. }
  12468. //declare method: boolean;
  12469. get method() {
  12470. return isFlagSet(this.flags, 262144 /* Flag.method */);
  12471. }
  12472. set method(value) {
  12473. this.flags = setFlag(this.flags, 262144 /* Flag.method */, value);
  12474. }
  12475. //declare shorthand: boolean;
  12476. get shorthand() {
  12477. return isFlagSet(this.flags, 524288 /* Flag.shorthand */);
  12478. }
  12479. set shorthand(value) {
  12480. this.flags = setFlag(this.flags, 524288 /* Flag.shorthand */, value);
  12481. }
  12482. declare(kind, init) {
  12483. this.declarationInit = init;
  12484. return this.value.declare(kind, UNKNOWN_EXPRESSION);
  12485. }
  12486. hasEffects(context) {
  12487. if (!this.deoptimized)
  12488. this.applyDeoptimizations();
  12489. const propertyReadSideEffects = this.scope.context.options.treeshake.propertyReadSideEffects;
  12490. return ((this.parent.type === 'ObjectPattern' && propertyReadSideEffects === 'always') ||
  12491. this.key.hasEffects(context) ||
  12492. this.value.hasEffects(context));
  12493. }
  12494. markDeclarationReached() {
  12495. this.value.markDeclarationReached();
  12496. }
  12497. render(code, options) {
  12498. if (!this.shorthand) {
  12499. this.key.render(code, options);
  12500. }
  12501. this.value.render(code, options, { isShorthandProperty: this.shorthand });
  12502. }
  12503. applyDeoptimizations() {
  12504. this.deoptimized = true;
  12505. if (this.declarationInit !== null) {
  12506. this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
  12507. this.scope.context.requestTreeshakingPass();
  12508. }
  12509. }
  12510. }
  12511. class PropertyDefinition extends NodeBase {
  12512. get computed() {
  12513. return isFlagSet(this.flags, 1024 /* Flag.computed */);
  12514. }
  12515. set computed(value) {
  12516. this.flags = setFlag(this.flags, 1024 /* Flag.computed */, value);
  12517. }
  12518. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  12519. this.value?.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  12520. }
  12521. deoptimizePath(path) {
  12522. this.value?.deoptimizePath(path);
  12523. }
  12524. getLiteralValueAtPath(path, recursionTracker, origin) {
  12525. return this.value
  12526. ? this.value.getLiteralValueAtPath(path, recursionTracker, origin)
  12527. : UnknownValue;
  12528. }
  12529. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  12530. return this.value
  12531. ? this.value.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)
  12532. : UNKNOWN_RETURN_EXPRESSION;
  12533. }
  12534. hasEffects(context) {
  12535. return (this.key.hasEffects(context) ||
  12536. (this.static && !!this.value?.hasEffects(context)) ||
  12537. checkEffectForNodes(this.decorators, context));
  12538. }
  12539. hasEffectsOnInteractionAtPath(path, interaction, context) {
  12540. return !this.value || this.value.hasEffectsOnInteractionAtPath(path, interaction, context);
  12541. }
  12542. applyDeoptimizations() { }
  12543. }
  12544. class ReturnStatement extends NodeBase {
  12545. hasEffects(context) {
  12546. if (!context.ignore.returnYield || this.argument?.hasEffects(context))
  12547. return true;
  12548. context.brokenFlow = true;
  12549. return false;
  12550. }
  12551. include(context, includeChildrenRecursively) {
  12552. this.included = true;
  12553. this.argument?.include(context, includeChildrenRecursively);
  12554. context.brokenFlow = true;
  12555. }
  12556. initialise() {
  12557. super.initialise();
  12558. this.scope.addReturnExpression(this.argument || UNKNOWN_EXPRESSION);
  12559. }
  12560. render(code, options) {
  12561. if (this.argument) {
  12562. this.argument.render(code, options, { preventASI: true });
  12563. if (this.argument.start === this.start + 6 /* 'return'.length */) {
  12564. code.prependLeft(this.start + 6, ' ');
  12565. }
  12566. }
  12567. }
  12568. }
  12569. class SequenceExpression extends NodeBase {
  12570. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  12571. this.expressions[this.expressions.length - 1].deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  12572. }
  12573. deoptimizePath(path) {
  12574. this.expressions[this.expressions.length - 1].deoptimizePath(path);
  12575. }
  12576. getLiteralValueAtPath(path, recursionTracker, origin) {
  12577. return this.expressions[this.expressions.length - 1].getLiteralValueAtPath(path, recursionTracker, origin);
  12578. }
  12579. hasEffects(context) {
  12580. for (const expression of this.expressions) {
  12581. if (expression.hasEffects(context))
  12582. return true;
  12583. }
  12584. return false;
  12585. }
  12586. hasEffectsOnInteractionAtPath(path, interaction, context) {
  12587. return this.expressions[this.expressions.length - 1].hasEffectsOnInteractionAtPath(path, interaction, context);
  12588. }
  12589. include(context, includeChildrenRecursively) {
  12590. this.included = true;
  12591. const lastExpression = this.expressions[this.expressions.length - 1];
  12592. for (const expression of this.expressions) {
  12593. if (includeChildrenRecursively ||
  12594. (expression === lastExpression && !(this.parent instanceof ExpressionStatement)) ||
  12595. expression.shouldBeIncluded(context))
  12596. expression.include(context, includeChildrenRecursively);
  12597. }
  12598. }
  12599. removeAnnotations(code) {
  12600. this.expressions[0].removeAnnotations(code);
  12601. }
  12602. render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
  12603. let includedNodes = 0;
  12604. let lastSeparatorPos = null;
  12605. const lastNode = this.expressions[this.expressions.length - 1];
  12606. for (const { node, separator, start, end } of getCommaSeparatedNodesWithBoundaries(this.expressions, code, this.start, this.end)) {
  12607. if (!node.included) {
  12608. treeshakeNode(node, code, start, end);
  12609. continue;
  12610. }
  12611. includedNodes++;
  12612. lastSeparatorPos = separator;
  12613. if (includedNodes === 1 && preventASI) {
  12614. removeLineBreaks(code, start, node.start);
  12615. }
  12616. if (includedNodes === 1) {
  12617. const parentType = renderedParentType || this.parent.type;
  12618. node.render(code, options, {
  12619. isCalleeOfRenderedParent: isCalleeOfRenderedParent && node === lastNode,
  12620. renderedParentType: parentType,
  12621. renderedSurroundingElement: parentType
  12622. });
  12623. }
  12624. else {
  12625. node.render(code, options);
  12626. }
  12627. }
  12628. if (lastSeparatorPos) {
  12629. code.remove(lastSeparatorPos, this.end);
  12630. }
  12631. }
  12632. }
  12633. class Super extends NodeBase {
  12634. bind() {
  12635. this.variable = this.scope.findVariable('this');
  12636. }
  12637. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  12638. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  12639. }
  12640. deoptimizePath(path) {
  12641. this.variable.deoptimizePath(path);
  12642. }
  12643. include() {
  12644. if (!this.included) {
  12645. this.included = true;
  12646. this.scope.context.includeVariableInModule(this.variable);
  12647. }
  12648. }
  12649. }
  12650. class SwitchCase extends NodeBase {
  12651. hasEffects(context) {
  12652. if (this.test?.hasEffects(context))
  12653. return true;
  12654. for (const node of this.consequent) {
  12655. if (context.brokenFlow)
  12656. break;
  12657. if (node.hasEffects(context))
  12658. return true;
  12659. }
  12660. return false;
  12661. }
  12662. include(context, includeChildrenRecursively) {
  12663. this.included = true;
  12664. this.test?.include(context, includeChildrenRecursively);
  12665. for (const node of this.consequent) {
  12666. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  12667. node.include(context, includeChildrenRecursively);
  12668. }
  12669. }
  12670. render(code, options, nodeRenderOptions) {
  12671. if (this.consequent.length > 0) {
  12672. if (this.test) {
  12673. this.test.render(code, options);
  12674. }
  12675. const testEnd = this.test
  12676. ? this.test.end
  12677. : findFirstOccurrenceOutsideComment(code.original, 'default', this.start) + 7;
  12678. const consequentStart = findFirstOccurrenceOutsideComment(code.original, ':', testEnd) + 1;
  12679. renderStatementList(this.consequent, code, consequentStart, nodeRenderOptions.end, options);
  12680. }
  12681. else {
  12682. super.render(code, options);
  12683. }
  12684. }
  12685. }
  12686. SwitchCase.prototype.needsBoundaries = true;
  12687. class SwitchStatement extends NodeBase {
  12688. createScope(parentScope) {
  12689. this.parentScope = parentScope;
  12690. this.scope = new BlockScope(parentScope);
  12691. }
  12692. hasEffects(context) {
  12693. if (this.discriminant.hasEffects(context))
  12694. return true;
  12695. const { brokenFlow, hasBreak, ignore } = context;
  12696. const { breaks } = ignore;
  12697. ignore.breaks = true;
  12698. context.hasBreak = false;
  12699. let onlyHasBrokenFlow = true;
  12700. for (const switchCase of this.cases) {
  12701. if (switchCase.hasEffects(context))
  12702. return true;
  12703. onlyHasBrokenFlow &&= context.brokenFlow && !context.hasBreak;
  12704. context.hasBreak = false;
  12705. context.brokenFlow = brokenFlow;
  12706. }
  12707. if (this.defaultCase !== null) {
  12708. context.brokenFlow = onlyHasBrokenFlow;
  12709. }
  12710. ignore.breaks = breaks;
  12711. context.hasBreak = hasBreak;
  12712. return false;
  12713. }
  12714. include(context, includeChildrenRecursively) {
  12715. this.included = true;
  12716. this.discriminant.include(context, includeChildrenRecursively);
  12717. const { brokenFlow, hasBreak } = context;
  12718. context.hasBreak = false;
  12719. let onlyHasBrokenFlow = true;
  12720. let isCaseIncluded = includeChildrenRecursively ||
  12721. (this.defaultCase !== null && this.defaultCase < this.cases.length - 1);
  12722. for (let caseIndex = this.cases.length - 1; caseIndex >= 0; caseIndex--) {
  12723. const switchCase = this.cases[caseIndex];
  12724. if (switchCase.included) {
  12725. isCaseIncluded = true;
  12726. }
  12727. if (!isCaseIncluded) {
  12728. const hasEffectsContext = createHasEffectsContext();
  12729. hasEffectsContext.ignore.breaks = true;
  12730. isCaseIncluded = switchCase.hasEffects(hasEffectsContext);
  12731. }
  12732. if (isCaseIncluded) {
  12733. switchCase.include(context, includeChildrenRecursively);
  12734. onlyHasBrokenFlow &&= context.brokenFlow && !context.hasBreak;
  12735. context.hasBreak = false;
  12736. context.brokenFlow = brokenFlow;
  12737. }
  12738. else {
  12739. onlyHasBrokenFlow = brokenFlow;
  12740. }
  12741. }
  12742. if (isCaseIncluded && this.defaultCase !== null) {
  12743. context.brokenFlow = onlyHasBrokenFlow;
  12744. }
  12745. context.hasBreak = hasBreak;
  12746. }
  12747. initialise() {
  12748. super.initialise();
  12749. for (let caseIndex = 0; caseIndex < this.cases.length; caseIndex++) {
  12750. if (this.cases[caseIndex].test === null) {
  12751. this.defaultCase = caseIndex;
  12752. return;
  12753. }
  12754. }
  12755. this.defaultCase = null;
  12756. }
  12757. parseNode(esTreeNode) {
  12758. this.discriminant = new (this.scope.context.getNodeConstructor(esTreeNode.discriminant.type))(this, this.parentScope).parseNode(esTreeNode.discriminant);
  12759. return super.parseNode(esTreeNode);
  12760. }
  12761. render(code, options) {
  12762. this.discriminant.render(code, options);
  12763. if (this.cases.length > 0) {
  12764. renderStatementList(this.cases, code, this.cases[0].start, this.end - 1, options);
  12765. }
  12766. }
  12767. }
  12768. class TaggedTemplateExpression extends CallExpressionBase {
  12769. bind() {
  12770. super.bind();
  12771. if (this.tag.type === Identifier$1) {
  12772. const name = this.tag.name;
  12773. const variable = this.scope.findVariable(name);
  12774. if (variable.isNamespace) {
  12775. this.scope.context.log(LOGLEVEL_WARN, logCannotCallNamespace(name), this.start);
  12776. }
  12777. }
  12778. }
  12779. hasEffects(context) {
  12780. if (!this.deoptimized)
  12781. this.applyDeoptimizations();
  12782. for (const argument of this.quasi.expressions) {
  12783. if (argument.hasEffects(context))
  12784. return true;
  12785. }
  12786. return (this.tag.hasEffects(context) ||
  12787. this.tag.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  12788. }
  12789. include(context, includeChildrenRecursively) {
  12790. if (!this.deoptimized)
  12791. this.applyDeoptimizations();
  12792. if (includeChildrenRecursively) {
  12793. super.include(context, includeChildrenRecursively);
  12794. }
  12795. else {
  12796. this.included = true;
  12797. this.tag.include(context, includeChildrenRecursively);
  12798. this.quasi.include(context, includeChildrenRecursively);
  12799. }
  12800. this.tag.includeCallArguments(context, this.args);
  12801. const [returnExpression] = this.getReturnExpression();
  12802. if (!returnExpression.included) {
  12803. returnExpression.include(context, false);
  12804. }
  12805. }
  12806. initialise() {
  12807. super.initialise();
  12808. this.args = [UNKNOWN_EXPRESSION, ...this.quasi.expressions];
  12809. this.interaction = {
  12810. args: [
  12811. this.tag instanceof MemberExpression && !this.tag.variable ? this.tag.object : null,
  12812. ...this.args
  12813. ],
  12814. type: INTERACTION_CALLED,
  12815. withNew: false
  12816. };
  12817. }
  12818. render(code, options) {
  12819. this.tag.render(code, options, { isCalleeOfRenderedParent: true });
  12820. this.quasi.render(code, options);
  12821. }
  12822. applyDeoptimizations() {
  12823. this.deoptimized = true;
  12824. this.tag.deoptimizeArgumentsOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  12825. this.scope.context.requestTreeshakingPass();
  12826. }
  12827. getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) {
  12828. if (this.returnExpression === null) {
  12829. this.returnExpression = UNKNOWN_RETURN_EXPRESSION;
  12830. return (this.returnExpression = this.tag.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.interaction, recursionTracker, this));
  12831. }
  12832. return this.returnExpression;
  12833. }
  12834. }
  12835. class TemplateElement extends NodeBase {
  12836. get tail() {
  12837. return isFlagSet(this.flags, 1048576 /* Flag.tail */);
  12838. }
  12839. set tail(value) {
  12840. this.flags = setFlag(this.flags, 1048576 /* Flag.tail */, value);
  12841. }
  12842. // Do not try to bind value
  12843. bind() { }
  12844. hasEffects() {
  12845. return false;
  12846. }
  12847. include() {
  12848. this.included = true;
  12849. }
  12850. parseNode(esTreeNode) {
  12851. this.value = esTreeNode.value;
  12852. return super.parseNode(esTreeNode);
  12853. }
  12854. render() { }
  12855. }
  12856. class TemplateLiteral extends NodeBase {
  12857. deoptimizeArgumentsOnInteractionAtPath() { }
  12858. getLiteralValueAtPath(path) {
  12859. if (path.length > 0 || this.quasis.length !== 1) {
  12860. return UnknownValue;
  12861. }
  12862. return this.quasis[0].value.cooked;
  12863. }
  12864. getReturnExpressionWhenCalledAtPath(path) {
  12865. if (path.length !== 1) {
  12866. return UNKNOWN_RETURN_EXPRESSION;
  12867. }
  12868. return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
  12869. }
  12870. hasEffectsOnInteractionAtPath(path, interaction, context) {
  12871. if (interaction.type === INTERACTION_ACCESSED) {
  12872. return path.length > 1;
  12873. }
  12874. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  12875. return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
  12876. }
  12877. return true;
  12878. }
  12879. render(code, options) {
  12880. code.indentExclusionRanges.push([this.start, this.end]);
  12881. super.render(code, options);
  12882. }
  12883. }
  12884. class ModuleScope extends ChildScope {
  12885. constructor(parent, context) {
  12886. super(parent, context);
  12887. this.variables.set('this', new LocalVariable('this', null, UNDEFINED_EXPRESSION, context, 'other'));
  12888. }
  12889. addDeclaration(identifier, context, init, kind) {
  12890. if (this.context.module.importDescriptions.has(identifier.name)) {
  12891. context.error(logRedeclarationError(identifier.name), identifier.start);
  12892. }
  12893. return super.addDeclaration(identifier, context, init, kind);
  12894. }
  12895. addExportDefaultDeclaration(name, exportDefaultDeclaration, context) {
  12896. const variable = new ExportDefaultVariable(name, exportDefaultDeclaration, context);
  12897. this.variables.set('default', variable);
  12898. return variable;
  12899. }
  12900. addNamespaceMemberAccess() { }
  12901. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  12902. // all module level variables are already deconflicted when deconflicting the chunk
  12903. for (const scope of this.children)
  12904. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  12905. }
  12906. findLexicalBoundary() {
  12907. return this;
  12908. }
  12909. findVariable(name) {
  12910. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  12911. if (knownVariable) {
  12912. return knownVariable;
  12913. }
  12914. const variable = this.context.traceVariable(name) || this.parent.findVariable(name);
  12915. if (variable instanceof GlobalVariable) {
  12916. this.accessedOutsideVariables.set(name, variable);
  12917. }
  12918. return variable;
  12919. }
  12920. }
  12921. class ThisExpression extends NodeBase {
  12922. bind() {
  12923. this.variable = this.scope.findVariable('this');
  12924. }
  12925. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  12926. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  12927. }
  12928. deoptimizePath(path) {
  12929. this.variable.deoptimizePath(path);
  12930. }
  12931. hasEffectsOnInteractionAtPath(path, interaction, context) {
  12932. if (path.length === 0) {
  12933. return interaction.type !== INTERACTION_ACCESSED;
  12934. }
  12935. return this.variable.hasEffectsOnInteractionAtPath(path, interaction, context);
  12936. }
  12937. include() {
  12938. if (!this.included) {
  12939. this.included = true;
  12940. this.scope.context.includeVariableInModule(this.variable);
  12941. }
  12942. }
  12943. initialise() {
  12944. super.initialise();
  12945. this.alias =
  12946. this.scope.findLexicalBoundary() instanceof ModuleScope
  12947. ? this.scope.context.moduleContext
  12948. : null;
  12949. if (this.alias === 'undefined') {
  12950. this.scope.context.log(LOGLEVEL_WARN, logThisIsUndefined(), this.start);
  12951. }
  12952. }
  12953. render(code) {
  12954. if (this.alias !== null) {
  12955. code.overwrite(this.start, this.end, this.alias, {
  12956. contentOnly: false,
  12957. storeName: true
  12958. });
  12959. }
  12960. }
  12961. }
  12962. class ThrowStatement extends NodeBase {
  12963. hasEffects() {
  12964. return true;
  12965. }
  12966. include(context, includeChildrenRecursively) {
  12967. this.included = true;
  12968. this.argument.include(context, includeChildrenRecursively);
  12969. context.brokenFlow = true;
  12970. }
  12971. render(code, options) {
  12972. this.argument.render(code, options, { preventASI: true });
  12973. if (this.argument.start === this.start + 5 /* 'throw'.length */) {
  12974. code.prependLeft(this.start + 5, ' ');
  12975. }
  12976. }
  12977. }
  12978. class TryStatement extends NodeBase {
  12979. constructor() {
  12980. super(...arguments);
  12981. this.directlyIncluded = false;
  12982. this.includedLabelsAfterBlock = null;
  12983. }
  12984. hasEffects(context) {
  12985. return ((this.scope.context.options.treeshake.tryCatchDeoptimization
  12986. ? this.block.body.length > 0
  12987. : this.block.hasEffects(context)) || !!this.finalizer?.hasEffects(context));
  12988. }
  12989. include(context, includeChildrenRecursively) {
  12990. const tryCatchDeoptimization = this.scope.context.options.treeshake?.tryCatchDeoptimization;
  12991. const { brokenFlow, includedLabels } = context;
  12992. if (!this.directlyIncluded || !tryCatchDeoptimization) {
  12993. this.included = true;
  12994. this.directlyIncluded = true;
  12995. this.block.include(context, tryCatchDeoptimization ? INCLUDE_PARAMETERS : includeChildrenRecursively);
  12996. if (includedLabels.size > 0) {
  12997. this.includedLabelsAfterBlock = [...includedLabels];
  12998. }
  12999. context.brokenFlow = brokenFlow;
  13000. }
  13001. else if (this.includedLabelsAfterBlock) {
  13002. for (const label of this.includedLabelsAfterBlock) {
  13003. includedLabels.add(label);
  13004. }
  13005. }
  13006. if (this.handler !== null) {
  13007. this.handler.include(context, includeChildrenRecursively);
  13008. context.brokenFlow = brokenFlow;
  13009. }
  13010. this.finalizer?.include(context, includeChildrenRecursively);
  13011. }
  13012. }
  13013. const unaryOperators = {
  13014. '!': value => !value,
  13015. '+': value => +value,
  13016. '-': value => -value,
  13017. delete: () => UnknownValue,
  13018. typeof: value => typeof value,
  13019. void: () => undefined,
  13020. '~': value => ~value
  13021. };
  13022. class UnaryExpression extends NodeBase {
  13023. get prefix() {
  13024. return isFlagSet(this.flags, 2097152 /* Flag.prefix */);
  13025. }
  13026. set prefix(value) {
  13027. this.flags = setFlag(this.flags, 2097152 /* Flag.prefix */, value);
  13028. }
  13029. getLiteralValueAtPath(path, recursionTracker, origin) {
  13030. if (path.length > 0)
  13031. return UnknownValue;
  13032. const argumentValue = this.argument.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  13033. if (typeof argumentValue === 'symbol')
  13034. return UnknownValue;
  13035. return unaryOperators[this.operator](argumentValue);
  13036. }
  13037. hasEffects(context) {
  13038. if (!this.deoptimized)
  13039. this.applyDeoptimizations();
  13040. if (this.operator === 'typeof' && this.argument instanceof Identifier)
  13041. return false;
  13042. return (this.argument.hasEffects(context) ||
  13043. (this.operator === 'delete' &&
  13044. this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context)));
  13045. }
  13046. hasEffectsOnInteractionAtPath(path, { type }) {
  13047. return type !== INTERACTION_ACCESSED || path.length > (this.operator === 'void' ? 0 : 1);
  13048. }
  13049. applyDeoptimizations() {
  13050. this.deoptimized = true;
  13051. if (this.operator === 'delete') {
  13052. this.argument.deoptimizePath(EMPTY_PATH);
  13053. this.scope.context.requestTreeshakingPass();
  13054. }
  13055. }
  13056. }
  13057. class UpdateExpression extends NodeBase {
  13058. hasEffects(context) {
  13059. if (!this.deoptimized)
  13060. this.applyDeoptimizations();
  13061. return this.argument.hasEffectsAsAssignmentTarget(context, true);
  13062. }
  13063. hasEffectsOnInteractionAtPath(path, { type }) {
  13064. return path.length > 1 || type !== INTERACTION_ACCESSED;
  13065. }
  13066. include(context, includeChildrenRecursively) {
  13067. if (!this.deoptimized)
  13068. this.applyDeoptimizations();
  13069. this.included = true;
  13070. this.argument.includeAsAssignmentTarget(context, includeChildrenRecursively, true);
  13071. }
  13072. initialise() {
  13073. super.initialise();
  13074. this.argument.setAssignedValue(UNKNOWN_EXPRESSION);
  13075. }
  13076. render(code, options) {
  13077. const { exportNamesByVariable, format, snippets: { _ } } = options;
  13078. this.argument.render(code, options);
  13079. if (format === 'system') {
  13080. const variable = this.argument.variable;
  13081. const exportNames = exportNamesByVariable.get(variable);
  13082. if (exportNames) {
  13083. if (this.prefix) {
  13084. if (exportNames.length === 1) {
  13085. renderSystemExportExpression(variable, this.start, this.end, code, options);
  13086. }
  13087. else {
  13088. renderSystemExportSequenceAfterExpression(variable, this.start, this.end, this.parent.type !== ExpressionStatement$1, code, options);
  13089. }
  13090. }
  13091. else {
  13092. const operator = this.operator[0];
  13093. renderSystemExportSequenceBeforeExpression(variable, this.start, this.end, this.parent.type !== ExpressionStatement$1, code, options, `${_}${operator}${_}1`);
  13094. }
  13095. }
  13096. }
  13097. }
  13098. applyDeoptimizations() {
  13099. this.deoptimized = true;
  13100. this.argument.deoptimizePath(EMPTY_PATH);
  13101. if (this.argument instanceof Identifier) {
  13102. const variable = this.scope.findVariable(this.argument.name);
  13103. variable.markReassigned();
  13104. }
  13105. this.scope.context.requestTreeshakingPass();
  13106. }
  13107. }
  13108. function areAllDeclarationsIncludedAndNotExported(declarations, exportNamesByVariable) {
  13109. for (const declarator of declarations) {
  13110. if (!declarator.id.included)
  13111. return false;
  13112. if (declarator.id.type === Identifier$1) {
  13113. if (exportNamesByVariable.has(declarator.id.variable))
  13114. return false;
  13115. }
  13116. else {
  13117. const exportedVariables = [];
  13118. declarator.id.addExportedVariables(exportedVariables, exportNamesByVariable);
  13119. if (exportedVariables.length > 0)
  13120. return false;
  13121. }
  13122. }
  13123. return true;
  13124. }
  13125. class VariableDeclaration extends NodeBase {
  13126. deoptimizePath() {
  13127. for (const declarator of this.declarations) {
  13128. declarator.deoptimizePath(EMPTY_PATH);
  13129. }
  13130. }
  13131. hasEffectsOnInteractionAtPath() {
  13132. return false;
  13133. }
  13134. include(context, includeChildrenRecursively, { asSingleStatement } = BLANK) {
  13135. this.included = true;
  13136. for (const declarator of this.declarations) {
  13137. if (includeChildrenRecursively || declarator.shouldBeIncluded(context))
  13138. declarator.include(context, includeChildrenRecursively);
  13139. const { id, init } = declarator;
  13140. if (asSingleStatement) {
  13141. id.include(context, includeChildrenRecursively);
  13142. }
  13143. if (init &&
  13144. id.included &&
  13145. !init.included &&
  13146. (id instanceof ObjectPattern || id instanceof ArrayPattern)) {
  13147. init.include(context, includeChildrenRecursively);
  13148. }
  13149. }
  13150. }
  13151. initialise() {
  13152. super.initialise();
  13153. this.isUsingDeclaration = this.kind === 'await using' || this.kind === 'using';
  13154. for (const declarator of this.declarations) {
  13155. declarator.declareDeclarator(this.kind, this.isUsingDeclaration);
  13156. }
  13157. }
  13158. removeAnnotations(code) {
  13159. this.declarations[0].removeAnnotations(code);
  13160. }
  13161. render(code, options, nodeRenderOptions = BLANK) {
  13162. if (this.isUsingDeclaration ||
  13163. areAllDeclarationsIncludedAndNotExported(this.declarations, options.exportNamesByVariable)) {
  13164. for (const declarator of this.declarations) {
  13165. declarator.render(code, options);
  13166. }
  13167. if (!nodeRenderOptions.isNoStatement &&
  13168. code.original.charCodeAt(this.end - 1) !== 59 /*";"*/) {
  13169. code.appendLeft(this.end, ';');
  13170. }
  13171. }
  13172. else {
  13173. this.renderReplacedDeclarations(code, options);
  13174. }
  13175. }
  13176. applyDeoptimizations() { }
  13177. renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, systemPatternExports, options) {
  13178. if (code.original.charCodeAt(this.end - 1) === 59 /*";"*/) {
  13179. code.remove(this.end - 1, this.end);
  13180. }
  13181. separatorString += ';';
  13182. if (lastSeparatorPos === null) {
  13183. code.appendLeft(renderedContentEnd, separatorString);
  13184. }
  13185. else {
  13186. if (code.original.charCodeAt(actualContentEnd - 1) === 10 /*"\n"*/ &&
  13187. (code.original.charCodeAt(this.end) === 10 /*"\n"*/ ||
  13188. code.original.charCodeAt(this.end) === 13) /*"\r"*/) {
  13189. actualContentEnd--;
  13190. if (code.original.charCodeAt(actualContentEnd) === 13 /*"\r"*/) {
  13191. actualContentEnd--;
  13192. }
  13193. }
  13194. if (actualContentEnd === lastSeparatorPos + 1) {
  13195. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString);
  13196. }
  13197. else {
  13198. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  13199. code.remove(actualContentEnd, renderedContentEnd);
  13200. }
  13201. }
  13202. if (systemPatternExports.length > 0) {
  13203. code.appendLeft(renderedContentEnd, ` ${getSystemExportStatement(systemPatternExports, options)};`);
  13204. }
  13205. }
  13206. renderReplacedDeclarations(code, options) {
  13207. const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.declarations, code, this.start + this.kind.length, this.end - (code.original.charCodeAt(this.end - 1) === 59 /*";"*/ ? 1 : 0));
  13208. let actualContentEnd, renderedContentEnd;
  13209. renderedContentEnd = findNonWhiteSpace(code.original, this.start + this.kind.length);
  13210. let lastSeparatorPos = renderedContentEnd - 1;
  13211. code.remove(this.start, lastSeparatorPos);
  13212. let isInDeclaration = false;
  13213. let hasRenderedContent = false;
  13214. let separatorString = '', leadingString, nextSeparatorString;
  13215. const aggregatedSystemExports = [];
  13216. const singleSystemExport = gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports);
  13217. for (const { node, start, separator, contentEnd, end } of separatedNodes) {
  13218. if (!node.included) {
  13219. code.remove(start, end);
  13220. node.removeAnnotations(code);
  13221. continue;
  13222. }
  13223. node.render(code, options);
  13224. leadingString = '';
  13225. nextSeparatorString = '';
  13226. if (!node.id.included ||
  13227. (node.id instanceof Identifier &&
  13228. isReassignedExportsMember(node.id.variable, options.exportNamesByVariable))) {
  13229. if (hasRenderedContent) {
  13230. separatorString += ';';
  13231. }
  13232. isInDeclaration = false;
  13233. }
  13234. else {
  13235. if (singleSystemExport && singleSystemExport === node.id.variable) {
  13236. const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', node.id.end);
  13237. renderSystemExportExpression(singleSystemExport, findNonWhiteSpace(code.original, operatorPos + 1), separator === null ? contentEnd : separator, code, options);
  13238. }
  13239. if (isInDeclaration) {
  13240. separatorString += ',';
  13241. }
  13242. else {
  13243. if (hasRenderedContent) {
  13244. separatorString += ';';
  13245. }
  13246. leadingString += `${this.kind} `;
  13247. isInDeclaration = true;
  13248. }
  13249. }
  13250. if (renderedContentEnd === lastSeparatorPos + 1) {
  13251. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString + leadingString);
  13252. }
  13253. else {
  13254. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  13255. code.appendLeft(renderedContentEnd, leadingString);
  13256. }
  13257. actualContentEnd = contentEnd;
  13258. renderedContentEnd = end;
  13259. hasRenderedContent = true;
  13260. lastSeparatorPos = separator;
  13261. separatorString = nextSeparatorString;
  13262. }
  13263. this.renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, aggregatedSystemExports, options);
  13264. }
  13265. }
  13266. function gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports) {
  13267. let singleSystemExport = null;
  13268. if (options.format === 'system') {
  13269. for (const { node } of separatedNodes) {
  13270. if (node.id instanceof Identifier &&
  13271. node.init &&
  13272. aggregatedSystemExports.length === 0 &&
  13273. options.exportNamesByVariable.get(node.id.variable)?.length === 1) {
  13274. singleSystemExport = node.id.variable;
  13275. aggregatedSystemExports.push(singleSystemExport);
  13276. }
  13277. else {
  13278. node.id.addExportedVariables(aggregatedSystemExports, options.exportNamesByVariable);
  13279. }
  13280. }
  13281. if (aggregatedSystemExports.length > 1) {
  13282. singleSystemExport = null;
  13283. }
  13284. else if (singleSystemExport) {
  13285. aggregatedSystemExports.length = 0;
  13286. }
  13287. }
  13288. return singleSystemExport;
  13289. }
  13290. class WhileStatement extends NodeBase {
  13291. hasEffects(context) {
  13292. if (this.test.hasEffects(context))
  13293. return true;
  13294. return hasLoopBodyEffects(context, this.body);
  13295. }
  13296. include(context, includeChildrenRecursively) {
  13297. this.included = true;
  13298. this.test.include(context, includeChildrenRecursively);
  13299. includeLoopBody(context, this.body, includeChildrenRecursively);
  13300. }
  13301. }
  13302. class YieldExpression extends NodeBase {
  13303. hasEffects(context) {
  13304. if (!this.deoptimized)
  13305. this.applyDeoptimizations();
  13306. return !(context.ignore.returnYield && !this.argument?.hasEffects(context));
  13307. }
  13308. render(code, options) {
  13309. if (this.argument) {
  13310. this.argument.render(code, options, { preventASI: true });
  13311. if (this.argument.start === this.start + 5 /* 'yield'.length */) {
  13312. code.prependLeft(this.start + 5, ' ');
  13313. }
  13314. }
  13315. }
  13316. }
  13317. // This file is generated by scripts/generate-buffer-parsers.js.
  13318. // Do not edit this file directly.
  13319. function convertProgram(buffer, parent, parentScope) {
  13320. return convertNode(parent, parentScope, 0, getAstBuffer(buffer));
  13321. }
  13322. const nodeTypeStrings = [
  13323. 'PanicError',
  13324. 'ParseError',
  13325. 'ArrayExpression',
  13326. 'ArrayPattern',
  13327. 'ArrowFunctionExpression',
  13328. 'AssignmentExpression',
  13329. 'AssignmentPattern',
  13330. 'AwaitExpression',
  13331. 'BinaryExpression',
  13332. 'BlockStatement',
  13333. 'BreakStatement',
  13334. 'CallExpression',
  13335. 'CatchClause',
  13336. 'ChainExpression',
  13337. 'ClassBody',
  13338. 'ClassDeclaration',
  13339. 'ClassExpression',
  13340. 'ConditionalExpression',
  13341. 'ContinueStatement',
  13342. 'DebuggerStatement',
  13343. 'Decorator',
  13344. 'ExpressionStatement',
  13345. 'DoWhileStatement',
  13346. 'EmptyStatement',
  13347. 'ExportAllDeclaration',
  13348. 'ExportDefaultDeclaration',
  13349. 'ExportNamedDeclaration',
  13350. 'ExportSpecifier',
  13351. 'ExpressionStatement',
  13352. 'ForInStatement',
  13353. 'ForOfStatement',
  13354. 'ForStatement',
  13355. 'FunctionDeclaration',
  13356. 'FunctionExpression',
  13357. 'Identifier',
  13358. 'IfStatement',
  13359. 'ImportAttribute',
  13360. 'ImportDeclaration',
  13361. 'ImportDefaultSpecifier',
  13362. 'ImportExpression',
  13363. 'ImportNamespaceSpecifier',
  13364. 'ImportSpecifier',
  13365. 'JSXAttribute',
  13366. 'JSXClosingElement',
  13367. 'JSXClosingFragment',
  13368. 'JSXElement',
  13369. 'JSXEmptyExpression',
  13370. 'JSXExpressionContainer',
  13371. 'JSXFragment',
  13372. 'JSXIdentifier',
  13373. 'JSXMemberExpression',
  13374. 'JSXNamespacedName',
  13375. 'JSXOpeningElement',
  13376. 'JSXOpeningFragment',
  13377. 'JSXSpreadAttribute',
  13378. 'JSXSpreadChild',
  13379. 'JSXText',
  13380. 'LabeledStatement',
  13381. 'Literal',
  13382. 'Literal',
  13383. 'Literal',
  13384. 'Literal',
  13385. 'Literal',
  13386. 'Literal',
  13387. 'LogicalExpression',
  13388. 'MemberExpression',
  13389. 'MetaProperty',
  13390. 'MethodDefinition',
  13391. 'NewExpression',
  13392. 'ObjectExpression',
  13393. 'ObjectPattern',
  13394. 'PrivateIdentifier',
  13395. 'Program',
  13396. 'Property',
  13397. 'PropertyDefinition',
  13398. 'RestElement',
  13399. 'ReturnStatement',
  13400. 'SequenceExpression',
  13401. 'SpreadElement',
  13402. 'StaticBlock',
  13403. 'Super',
  13404. 'SwitchCase',
  13405. 'SwitchStatement',
  13406. 'TaggedTemplateExpression',
  13407. 'TemplateElement',
  13408. 'TemplateLiteral',
  13409. 'ThisExpression',
  13410. 'ThrowStatement',
  13411. 'TryStatement',
  13412. 'UnaryExpression',
  13413. 'UpdateExpression',
  13414. 'VariableDeclaration',
  13415. 'VariableDeclarator',
  13416. 'WhileStatement',
  13417. 'YieldExpression'
  13418. ];
  13419. const nodeConstructors$1 = [
  13420. PanicError,
  13421. ParseError,
  13422. ArrayExpression,
  13423. ArrayPattern,
  13424. ArrowFunctionExpression,
  13425. AssignmentExpression,
  13426. AssignmentPattern,
  13427. AwaitExpression,
  13428. BinaryExpression,
  13429. BlockStatement,
  13430. BreakStatement,
  13431. CallExpression,
  13432. CatchClause,
  13433. ChainExpression,
  13434. ClassBody,
  13435. ClassDeclaration,
  13436. ClassExpression,
  13437. ConditionalExpression,
  13438. ContinueStatement,
  13439. DebuggerStatement,
  13440. Decorator,
  13441. ExpressionStatement,
  13442. DoWhileStatement,
  13443. EmptyStatement,
  13444. ExportAllDeclaration,
  13445. ExportDefaultDeclaration,
  13446. ExportNamedDeclaration,
  13447. ExportSpecifier,
  13448. ExpressionStatement,
  13449. ForInStatement,
  13450. ForOfStatement,
  13451. ForStatement,
  13452. FunctionDeclaration,
  13453. FunctionExpression,
  13454. Identifier,
  13455. IfStatement,
  13456. ImportAttribute,
  13457. ImportDeclaration,
  13458. ImportDefaultSpecifier,
  13459. ImportExpression,
  13460. ImportNamespaceSpecifier,
  13461. ImportSpecifier,
  13462. JSXAttribute,
  13463. JSXClosingElement,
  13464. JSXClosingFragment,
  13465. JSXElement,
  13466. JSXEmptyExpression,
  13467. JSXExpressionContainer,
  13468. JSXFragment,
  13469. JSXIdentifier,
  13470. JSXMemberExpression,
  13471. JSXNamespacedName,
  13472. JSXOpeningElement,
  13473. JSXOpeningFragment,
  13474. JSXSpreadAttribute,
  13475. JSXSpreadChild,
  13476. JSXText,
  13477. LabeledStatement,
  13478. Literal,
  13479. Literal,
  13480. Literal,
  13481. Literal,
  13482. Literal,
  13483. Literal,
  13484. LogicalExpression,
  13485. MemberExpression,
  13486. MetaProperty,
  13487. MethodDefinition,
  13488. NewExpression,
  13489. ObjectExpression,
  13490. ObjectPattern,
  13491. PrivateIdentifier,
  13492. Program,
  13493. Property,
  13494. PropertyDefinition,
  13495. RestElement,
  13496. ReturnStatement,
  13497. SequenceExpression,
  13498. SpreadElement,
  13499. StaticBlock,
  13500. Super,
  13501. SwitchCase,
  13502. SwitchStatement,
  13503. TaggedTemplateExpression,
  13504. TemplateElement,
  13505. TemplateLiteral,
  13506. ThisExpression,
  13507. ThrowStatement,
  13508. TryStatement,
  13509. UnaryExpression,
  13510. UpdateExpression,
  13511. VariableDeclaration,
  13512. VariableDeclarator,
  13513. WhileStatement,
  13514. YieldExpression
  13515. ];
  13516. const bufferParsers = [
  13517. function panicError(node, position, buffer) {
  13518. node.message = buffer.convertString(buffer[position]);
  13519. },
  13520. function parseError(node, position, buffer) {
  13521. node.message = buffer.convertString(buffer[position]);
  13522. },
  13523. function arrayExpression(node, position, buffer) {
  13524. const { scope } = node;
  13525. node.elements = convertNodeList(node, scope, buffer[position], buffer);
  13526. },
  13527. function arrayPattern(node, position, buffer) {
  13528. const { scope } = node;
  13529. node.elements = convertNodeList(node, scope, buffer[position], buffer);
  13530. },
  13531. function arrowFunctionExpression(node, position, buffer) {
  13532. const { scope } = node;
  13533. const flags = buffer[position];
  13534. node.async = (flags & 1) === 1;
  13535. node.expression = (flags & 2) === 2;
  13536. node.generator = (flags & 4) === 4;
  13537. const annotations = (node.annotations = convertAnnotations(buffer[position + 1], buffer));
  13538. node.annotationNoSideEffects = annotations.some(comment => comment.type === 'noSideEffects');
  13539. const parameters = (node.params = convertNodeList(node, scope, buffer[position + 2], buffer));
  13540. scope.addParameterVariables(parameters.map(parameter => parameter.declare('parameter', UNKNOWN_EXPRESSION)), parameters[parameters.length - 1] instanceof RestElement);
  13541. node.body = convertNode(node, scope.bodyScope, buffer[position + 3], buffer);
  13542. },
  13543. function assignmentExpression(node, position, buffer) {
  13544. const { scope } = node;
  13545. node.operator = FIXED_STRINGS[buffer[position]];
  13546. node.left = convertNode(node, scope, buffer[position + 1], buffer);
  13547. node.right = convertNode(node, scope, buffer[position + 2], buffer);
  13548. },
  13549. function assignmentPattern(node, position, buffer) {
  13550. const { scope } = node;
  13551. node.left = convertNode(node, scope, buffer[position], buffer);
  13552. node.right = convertNode(node, scope, buffer[position + 1], buffer);
  13553. },
  13554. function awaitExpression(node, position, buffer) {
  13555. const { scope } = node;
  13556. node.argument = convertNode(node, scope, buffer[position], buffer);
  13557. },
  13558. function binaryExpression(node, position, buffer) {
  13559. const { scope } = node;
  13560. node.operator = FIXED_STRINGS[buffer[position]];
  13561. node.left = convertNode(node, scope, buffer[position + 1], buffer);
  13562. node.right = convertNode(node, scope, buffer[position + 2], buffer);
  13563. },
  13564. function blockStatement(node, position, buffer) {
  13565. const { scope } = node;
  13566. node.body = convertNodeList(node, scope, buffer[position], buffer);
  13567. },
  13568. function breakStatement(node, position, buffer) {
  13569. const { scope } = node;
  13570. const labelPosition = buffer[position];
  13571. node.label = labelPosition === 0 ? null : convertNode(node, scope, labelPosition, buffer);
  13572. },
  13573. function callExpression(node, position, buffer) {
  13574. const { scope } = node;
  13575. const flags = buffer[position];
  13576. node.optional = (flags & 1) === 1;
  13577. node.annotations = convertAnnotations(buffer[position + 1], buffer);
  13578. node.callee = convertNode(node, scope, buffer[position + 2], buffer);
  13579. node.arguments = convertNodeList(node, scope, buffer[position + 3], buffer);
  13580. },
  13581. function catchClause(node, position, buffer) {
  13582. const { scope } = node;
  13583. const parameterPosition = buffer[position];
  13584. const parameter = (node.param =
  13585. parameterPosition === 0 ? null : convertNode(node, scope, parameterPosition, buffer));
  13586. parameter?.declare('parameter', UNKNOWN_EXPRESSION);
  13587. node.body = convertNode(node, scope.bodyScope, buffer[position + 1], buffer);
  13588. },
  13589. function chainExpression(node, position, buffer) {
  13590. const { scope } = node;
  13591. node.expression = convertNode(node, scope, buffer[position], buffer);
  13592. },
  13593. function classBody(node, position, buffer) {
  13594. const { scope } = node;
  13595. const bodyPosition = buffer[position];
  13596. const body = (node.body = []);
  13597. if (bodyPosition) {
  13598. const length = buffer[bodyPosition];
  13599. for (let index = 0; index < length; index++) {
  13600. const nodePosition = buffer[bodyPosition + 1 + index];
  13601. body.push(convertNode(node, (buffer[nodePosition + 3] & 1) === 0 ? scope.instanceScope : scope, nodePosition, buffer));
  13602. }
  13603. }
  13604. },
  13605. function classDeclaration(node, position, buffer) {
  13606. const { scope } = node;
  13607. node.decorators = convertNodeList(node, scope, buffer[position], buffer);
  13608. const idPosition = buffer[position + 1];
  13609. node.id =
  13610. idPosition === 0 ? null : convertNode(node, scope.parent, idPosition, buffer);
  13611. const superClassPosition = buffer[position + 2];
  13612. node.superClass =
  13613. superClassPosition === 0 ? null : convertNode(node, scope, superClassPosition, buffer);
  13614. node.body = convertNode(node, scope, buffer[position + 3], buffer);
  13615. },
  13616. function classExpression(node, position, buffer) {
  13617. const { scope } = node;
  13618. node.decorators = convertNodeList(node, scope, buffer[position], buffer);
  13619. const idPosition = buffer[position + 1];
  13620. node.id = idPosition === 0 ? null : convertNode(node, scope, idPosition, buffer);
  13621. const superClassPosition = buffer[position + 2];
  13622. node.superClass =
  13623. superClassPosition === 0 ? null : convertNode(node, scope, superClassPosition, buffer);
  13624. node.body = convertNode(node, scope, buffer[position + 3], buffer);
  13625. },
  13626. function conditionalExpression(node, position, buffer) {
  13627. const { scope } = node;
  13628. node.test = convertNode(node, scope, buffer[position], buffer);
  13629. node.consequent = convertNode(node, scope, buffer[position + 1], buffer);
  13630. node.alternate = convertNode(node, scope, buffer[position + 2], buffer);
  13631. },
  13632. function continueStatement(node, position, buffer) {
  13633. const { scope } = node;
  13634. const labelPosition = buffer[position];
  13635. node.label = labelPosition === 0 ? null : convertNode(node, scope, labelPosition, buffer);
  13636. },
  13637. function debuggerStatement() { },
  13638. function decorator(node, position, buffer) {
  13639. const { scope } = node;
  13640. node.expression = convertNode(node, scope, buffer[position], buffer);
  13641. },
  13642. function directive(node, position, buffer) {
  13643. const { scope } = node;
  13644. node.directive = buffer.convertString(buffer[position]);
  13645. node.expression = convertNode(node, scope, buffer[position + 1], buffer);
  13646. },
  13647. function doWhileStatement(node, position, buffer) {
  13648. const { scope } = node;
  13649. node.body = convertNode(node, scope, buffer[position], buffer);
  13650. node.test = convertNode(node, scope, buffer[position + 1], buffer);
  13651. },
  13652. function emptyStatement() { },
  13653. function exportAllDeclaration(node, position, buffer) {
  13654. const { scope } = node;
  13655. const exportedPosition = buffer[position];
  13656. node.exported =
  13657. exportedPosition === 0 ? null : convertNode(node, scope, exportedPosition, buffer);
  13658. node.source = convertNode(node, scope, buffer[position + 1], buffer);
  13659. node.attributes = convertNodeList(node, scope, buffer[position + 2], buffer);
  13660. },
  13661. function exportDefaultDeclaration(node, position, buffer) {
  13662. const { scope } = node;
  13663. node.declaration = convertNode(node, scope, buffer[position], buffer);
  13664. },
  13665. function exportNamedDeclaration(node, position, buffer) {
  13666. const { scope } = node;
  13667. node.specifiers = convertNodeList(node, scope, buffer[position], buffer);
  13668. const sourcePosition = buffer[position + 1];
  13669. node.source = sourcePosition === 0 ? null : convertNode(node, scope, sourcePosition, buffer);
  13670. node.attributes = convertNodeList(node, scope, buffer[position + 2], buffer);
  13671. const declarationPosition = buffer[position + 3];
  13672. node.declaration =
  13673. declarationPosition === 0 ? null : convertNode(node, scope, declarationPosition, buffer);
  13674. },
  13675. function exportSpecifier(node, position, buffer) {
  13676. const { scope } = node;
  13677. node.local = convertNode(node, scope, buffer[position], buffer);
  13678. const exportedPosition = buffer[position + 1];
  13679. node.exported =
  13680. exportedPosition === 0 ? node.local : convertNode(node, scope, exportedPosition, buffer);
  13681. },
  13682. function expressionStatement(node, position, buffer) {
  13683. const { scope } = node;
  13684. node.expression = convertNode(node, scope, buffer[position], buffer);
  13685. },
  13686. function forInStatement(node, position, buffer) {
  13687. const { scope } = node;
  13688. node.left = convertNode(node, scope, buffer[position], buffer);
  13689. node.right = convertNode(node, scope, buffer[position + 1], buffer);
  13690. node.body = convertNode(node, scope, buffer[position + 2], buffer);
  13691. },
  13692. function forOfStatement(node, position, buffer) {
  13693. const { scope } = node;
  13694. const flags = buffer[position];
  13695. node.await = (flags & 1) === 1;
  13696. node.left = convertNode(node, scope, buffer[position + 1], buffer);
  13697. node.right = convertNode(node, scope, buffer[position + 2], buffer);
  13698. node.body = convertNode(node, scope, buffer[position + 3], buffer);
  13699. },
  13700. function forStatement(node, position, buffer) {
  13701. const { scope } = node;
  13702. const initPosition = buffer[position];
  13703. node.init = initPosition === 0 ? null : convertNode(node, scope, initPosition, buffer);
  13704. const testPosition = buffer[position + 1];
  13705. node.test = testPosition === 0 ? null : convertNode(node, scope, testPosition, buffer);
  13706. const updatePosition = buffer[position + 2];
  13707. node.update = updatePosition === 0 ? null : convertNode(node, scope, updatePosition, buffer);
  13708. node.body = convertNode(node, scope, buffer[position + 3], buffer);
  13709. },
  13710. function functionDeclaration(node, position, buffer) {
  13711. const { scope } = node;
  13712. const flags = buffer[position];
  13713. node.async = (flags & 1) === 1;
  13714. node.generator = (flags & 2) === 2;
  13715. const annotations = (node.annotations = convertAnnotations(buffer[position + 1], buffer));
  13716. node.annotationNoSideEffects = annotations.some(comment => comment.type === 'noSideEffects');
  13717. const idPosition = buffer[position + 2];
  13718. node.id =
  13719. idPosition === 0 ? null : convertNode(node, scope.parent, idPosition, buffer);
  13720. const parameters = (node.params = convertNodeList(node, scope, buffer[position + 3], buffer));
  13721. scope.addParameterVariables(parameters.map(parameter => parameter.declare('parameter', UNKNOWN_EXPRESSION)), parameters[parameters.length - 1] instanceof RestElement);
  13722. node.body = convertNode(node, scope.bodyScope, buffer[position + 4], buffer);
  13723. },
  13724. function functionExpression(node, position, buffer) {
  13725. const { scope } = node;
  13726. const flags = buffer[position];
  13727. node.async = (flags & 1) === 1;
  13728. node.generator = (flags & 2) === 2;
  13729. const annotations = (node.annotations = convertAnnotations(buffer[position + 1], buffer));
  13730. node.annotationNoSideEffects = annotations.some(comment => comment.type === 'noSideEffects');
  13731. const idPosition = buffer[position + 2];
  13732. node.id = idPosition === 0 ? null : convertNode(node, node.idScope, idPosition, buffer);
  13733. const parameters = (node.params = convertNodeList(node, scope, buffer[position + 3], buffer));
  13734. scope.addParameterVariables(parameters.map(parameter => parameter.declare('parameter', UNKNOWN_EXPRESSION)), parameters[parameters.length - 1] instanceof RestElement);
  13735. node.body = convertNode(node, scope.bodyScope, buffer[position + 4], buffer);
  13736. },
  13737. function identifier(node, position, buffer) {
  13738. node.name = buffer.convertString(buffer[position]);
  13739. },
  13740. function ifStatement(node, position, buffer) {
  13741. const { scope } = node;
  13742. node.test = convertNode(node, scope, buffer[position], buffer);
  13743. node.consequent = convertNode(node, (node.consequentScope = new TrackingScope(scope)), buffer[position + 1], buffer);
  13744. const alternatePosition = buffer[position + 2];
  13745. node.alternate =
  13746. alternatePosition === 0
  13747. ? null
  13748. : convertNode(node, (node.alternateScope = new TrackingScope(scope)), alternatePosition, buffer);
  13749. },
  13750. function importAttribute(node, position, buffer) {
  13751. const { scope } = node;
  13752. node.key = convertNode(node, scope, buffer[position], buffer);
  13753. node.value = convertNode(node, scope, buffer[position + 1], buffer);
  13754. },
  13755. function importDeclaration(node, position, buffer) {
  13756. const { scope } = node;
  13757. node.specifiers = convertNodeList(node, scope, buffer[position], buffer);
  13758. node.source = convertNode(node, scope, buffer[position + 1], buffer);
  13759. node.attributes = convertNodeList(node, scope, buffer[position + 2], buffer);
  13760. },
  13761. function importDefaultSpecifier(node, position, buffer) {
  13762. const { scope } = node;
  13763. node.local = convertNode(node, scope, buffer[position], buffer);
  13764. },
  13765. function importExpression(node, position, buffer) {
  13766. const { scope } = node;
  13767. node.source = convertNode(node, scope, buffer[position], buffer);
  13768. node.sourceAstNode = convertNode$1(buffer[position], buffer);
  13769. const optionsPosition = buffer[position + 1];
  13770. node.options = optionsPosition === 0 ? null : convertNode(node, scope, optionsPosition, buffer);
  13771. },
  13772. function importNamespaceSpecifier(node, position, buffer) {
  13773. const { scope } = node;
  13774. node.local = convertNode(node, scope, buffer[position], buffer);
  13775. },
  13776. function importSpecifier(node, position, buffer) {
  13777. const { scope } = node;
  13778. const importedPosition = buffer[position];
  13779. node.local = convertNode(node, scope, buffer[position + 1], buffer);
  13780. node.imported =
  13781. importedPosition === 0 ? node.local : convertNode(node, scope, importedPosition, buffer);
  13782. },
  13783. function jsxAttribute(node, position, buffer) {
  13784. const { scope } = node;
  13785. node.name = convertNode(node, scope, buffer[position], buffer);
  13786. const valuePosition = buffer[position + 1];
  13787. node.value = valuePosition === 0 ? null : convertNode(node, scope, valuePosition, buffer);
  13788. },
  13789. function jsxClosingElement(node, position, buffer) {
  13790. const { scope } = node;
  13791. node.name = convertNode(node, scope, buffer[position], buffer);
  13792. },
  13793. function jsxClosingFragment() { },
  13794. function jsxElement(node, position, buffer) {
  13795. const { scope } = node;
  13796. node.openingElement = convertNode(node, scope, buffer[position], buffer);
  13797. node.children = convertNodeList(node, scope, buffer[position + 1], buffer);
  13798. const closingElementPosition = buffer[position + 2];
  13799. node.closingElement =
  13800. closingElementPosition === 0
  13801. ? null
  13802. : convertNode(node, scope, closingElementPosition, buffer);
  13803. },
  13804. function jsxEmptyExpression() { },
  13805. function jsxExpressionContainer(node, position, buffer) {
  13806. const { scope } = node;
  13807. node.expression = convertNode(node, scope, buffer[position], buffer);
  13808. },
  13809. function jsxFragment(node, position, buffer) {
  13810. const { scope } = node;
  13811. node.openingFragment = convertNode(node, scope, buffer[position], buffer);
  13812. node.children = convertNodeList(node, scope, buffer[position + 1], buffer);
  13813. node.closingFragment = convertNode(node, scope, buffer[position + 2], buffer);
  13814. },
  13815. function jsxIdentifier(node, position, buffer) {
  13816. node.name = buffer.convertString(buffer[position]);
  13817. },
  13818. function jsxMemberExpression(node, position, buffer) {
  13819. const { scope } = node;
  13820. node.object = convertNode(node, scope, buffer[position], buffer);
  13821. node.property = convertNode(node, scope, buffer[position + 1], buffer);
  13822. },
  13823. function jsxNamespacedName(node, position, buffer) {
  13824. const { scope } = node;
  13825. node.namespace = convertNode(node, scope, buffer[position], buffer);
  13826. node.name = convertNode(node, scope, buffer[position + 1], buffer);
  13827. },
  13828. function jsxOpeningElement(node, position, buffer) {
  13829. const { scope } = node;
  13830. const flags = buffer[position];
  13831. node.selfClosing = (flags & 1) === 1;
  13832. node.name = convertNode(node, scope, buffer[position + 1], buffer);
  13833. node.attributes = convertNodeList(node, scope, buffer[position + 2], buffer);
  13834. },
  13835. function jsxOpeningFragment(node) {
  13836. node.attributes = [];
  13837. node.selfClosing = false;
  13838. },
  13839. function jsxSpreadAttribute(node, position, buffer) {
  13840. const { scope } = node;
  13841. node.argument = convertNode(node, scope, buffer[position], buffer);
  13842. },
  13843. function jsxSpreadChild(node, position, buffer) {
  13844. const { scope } = node;
  13845. node.expression = convertNode(node, scope, buffer[position], buffer);
  13846. },
  13847. function jsxText(node, position, buffer) {
  13848. node.value = buffer.convertString(buffer[position]);
  13849. node.raw = buffer.convertString(buffer[position + 1]);
  13850. },
  13851. function labeledStatement(node, position, buffer) {
  13852. const { scope } = node;
  13853. node.label = convertNode(node, scope, buffer[position], buffer);
  13854. node.body = convertNode(node, scope, buffer[position + 1], buffer);
  13855. },
  13856. function literalBigInt(node, position, buffer) {
  13857. const bigint = (node.bigint = buffer.convertString(buffer[position]));
  13858. node.raw = buffer.convertString(buffer[position + 1]);
  13859. node.value = BigInt(bigint);
  13860. },
  13861. function literalBoolean(node, position, buffer) {
  13862. const flags = buffer[position];
  13863. const value = (node.value = (flags & 1) === 1);
  13864. node.raw = value ? 'true' : 'false';
  13865. },
  13866. function literalNull(node) {
  13867. node.value = null;
  13868. },
  13869. function literalNumber(node, position, buffer) {
  13870. const rawPosition = buffer[position];
  13871. node.raw = rawPosition === 0 ? undefined : buffer.convertString(rawPosition);
  13872. node.value = new DataView(buffer.buffer).getFloat64((position + 1) << 2, true);
  13873. },
  13874. function literalRegExp(node, position, buffer) {
  13875. const flags = buffer.convertString(buffer[position]);
  13876. const pattern = buffer.convertString(buffer[position + 1]);
  13877. node.raw = `/${pattern}/${flags}`;
  13878. node.regex = { flags, pattern };
  13879. node.value = new RegExp(pattern, flags);
  13880. },
  13881. function literalString(node, position, buffer) {
  13882. node.value = buffer.convertString(buffer[position]);
  13883. const rawPosition = buffer[position + 1];
  13884. node.raw = rawPosition === 0 ? undefined : buffer.convertString(rawPosition);
  13885. },
  13886. function logicalExpression(node, position, buffer) {
  13887. const { scope } = node;
  13888. node.operator = FIXED_STRINGS[buffer[position]];
  13889. node.left = convertNode(node, scope, buffer[position + 1], buffer);
  13890. node.right = convertNode(node, scope, buffer[position + 2], buffer);
  13891. },
  13892. function memberExpression(node, position, buffer) {
  13893. const { scope } = node;
  13894. const flags = buffer[position];
  13895. node.computed = (flags & 1) === 1;
  13896. node.optional = (flags & 2) === 2;
  13897. node.object = convertNode(node, scope, buffer[position + 1], buffer);
  13898. node.property = convertNode(node, scope, buffer[position + 2], buffer);
  13899. },
  13900. function metaProperty(node, position, buffer) {
  13901. const { scope } = node;
  13902. node.meta = convertNode(node, scope, buffer[position], buffer);
  13903. node.property = convertNode(node, scope, buffer[position + 1], buffer);
  13904. },
  13905. function methodDefinition(node, position, buffer) {
  13906. const { scope } = node;
  13907. const flags = buffer[position];
  13908. node.static = (flags & 1) === 1;
  13909. node.computed = (flags & 2) === 2;
  13910. node.decorators = convertNodeList(node, scope, buffer[position + 1], buffer);
  13911. node.key = convertNode(node, scope, buffer[position + 2], buffer);
  13912. node.value = convertNode(node, scope, buffer[position + 3], buffer);
  13913. node.kind = FIXED_STRINGS[buffer[position + 4]];
  13914. },
  13915. function newExpression(node, position, buffer) {
  13916. const { scope } = node;
  13917. node.annotations = convertAnnotations(buffer[position], buffer);
  13918. node.callee = convertNode(node, scope, buffer[position + 1], buffer);
  13919. node.arguments = convertNodeList(node, scope, buffer[position + 2], buffer);
  13920. },
  13921. function objectExpression(node, position, buffer) {
  13922. const { scope } = node;
  13923. node.properties = convertNodeList(node, scope, buffer[position], buffer);
  13924. },
  13925. function objectPattern(node, position, buffer) {
  13926. const { scope } = node;
  13927. node.properties = convertNodeList(node, scope, buffer[position], buffer);
  13928. },
  13929. function privateIdentifier(node, position, buffer) {
  13930. node.name = buffer.convertString(buffer[position]);
  13931. },
  13932. function program(node, position, buffer) {
  13933. const { scope } = node;
  13934. node.body = convertNodeList(node, scope, buffer[position], buffer);
  13935. node.invalidAnnotations = convertAnnotations(buffer[position + 1], buffer);
  13936. },
  13937. function property(node, position, buffer) {
  13938. const { scope } = node;
  13939. const flags = buffer[position];
  13940. node.method = (flags & 1) === 1;
  13941. node.shorthand = (flags & 2) === 2;
  13942. node.computed = (flags & 4) === 4;
  13943. const keyPosition = buffer[position + 1];
  13944. node.value = convertNode(node, scope, buffer[position + 2], buffer);
  13945. node.kind = FIXED_STRINGS[buffer[position + 3]];
  13946. node.key = keyPosition === 0 ? node.value : convertNode(node, scope, keyPosition, buffer);
  13947. },
  13948. function propertyDefinition(node, position, buffer) {
  13949. const { scope } = node;
  13950. const flags = buffer[position];
  13951. node.static = (flags & 1) === 1;
  13952. node.computed = (flags & 2) === 2;
  13953. node.decorators = convertNodeList(node, scope, buffer[position + 1], buffer);
  13954. node.key = convertNode(node, scope, buffer[position + 2], buffer);
  13955. const valuePosition = buffer[position + 3];
  13956. node.value = valuePosition === 0 ? null : convertNode(node, scope, valuePosition, buffer);
  13957. },
  13958. function restElement(node, position, buffer) {
  13959. const { scope } = node;
  13960. node.argument = convertNode(node, scope, buffer[position], buffer);
  13961. },
  13962. function returnStatement(node, position, buffer) {
  13963. const { scope } = node;
  13964. const argumentPosition = buffer[position];
  13965. node.argument =
  13966. argumentPosition === 0 ? null : convertNode(node, scope, argumentPosition, buffer);
  13967. },
  13968. function sequenceExpression(node, position, buffer) {
  13969. const { scope } = node;
  13970. node.expressions = convertNodeList(node, scope, buffer[position], buffer);
  13971. },
  13972. function spreadElement(node, position, buffer) {
  13973. const { scope } = node;
  13974. node.argument = convertNode(node, scope, buffer[position], buffer);
  13975. },
  13976. function staticBlock(node, position, buffer) {
  13977. const { scope } = node;
  13978. node.body = convertNodeList(node, scope, buffer[position], buffer);
  13979. },
  13980. function superElement() { },
  13981. function switchCase(node, position, buffer) {
  13982. const { scope } = node;
  13983. const testPosition = buffer[position];
  13984. node.test = testPosition === 0 ? null : convertNode(node, scope, testPosition, buffer);
  13985. node.consequent = convertNodeList(node, scope, buffer[position + 1], buffer);
  13986. },
  13987. function switchStatement(node, position, buffer) {
  13988. const { scope } = node;
  13989. node.discriminant = convertNode(node, node.parentScope, buffer[position], buffer);
  13990. node.cases = convertNodeList(node, scope, buffer[position + 1], buffer);
  13991. },
  13992. function taggedTemplateExpression(node, position, buffer) {
  13993. const { scope } = node;
  13994. node.tag = convertNode(node, scope, buffer[position], buffer);
  13995. node.quasi = convertNode(node, scope, buffer[position + 1], buffer);
  13996. },
  13997. function templateElement(node, position, buffer) {
  13998. const flags = buffer[position];
  13999. node.tail = (flags & 1) === 1;
  14000. const cookedPosition = buffer[position + 1];
  14001. const cooked = cookedPosition === 0 ? undefined : buffer.convertString(cookedPosition);
  14002. const raw = buffer.convertString(buffer[position + 2]);
  14003. node.value = { cooked, raw };
  14004. },
  14005. function templateLiteral(node, position, buffer) {
  14006. const { scope } = node;
  14007. node.quasis = convertNodeList(node, scope, buffer[position], buffer);
  14008. node.expressions = convertNodeList(node, scope, buffer[position + 1], buffer);
  14009. },
  14010. function thisExpression() { },
  14011. function throwStatement(node, position, buffer) {
  14012. const { scope } = node;
  14013. node.argument = convertNode(node, scope, buffer[position], buffer);
  14014. },
  14015. function tryStatement(node, position, buffer) {
  14016. const { scope } = node;
  14017. node.block = convertNode(node, scope, buffer[position], buffer);
  14018. const handlerPosition = buffer[position + 1];
  14019. node.handler = handlerPosition === 0 ? null : convertNode(node, scope, handlerPosition, buffer);
  14020. const finalizerPosition = buffer[position + 2];
  14021. node.finalizer =
  14022. finalizerPosition === 0 ? null : convertNode(node, scope, finalizerPosition, buffer);
  14023. },
  14024. function unaryExpression(node, position, buffer) {
  14025. const { scope } = node;
  14026. node.operator = FIXED_STRINGS[buffer[position]];
  14027. node.argument = convertNode(node, scope, buffer[position + 1], buffer);
  14028. },
  14029. function updateExpression(node, position, buffer) {
  14030. const { scope } = node;
  14031. const flags = buffer[position];
  14032. node.prefix = (flags & 1) === 1;
  14033. node.operator = FIXED_STRINGS[buffer[position + 1]];
  14034. node.argument = convertNode(node, scope, buffer[position + 2], buffer);
  14035. },
  14036. function variableDeclaration(node, position, buffer) {
  14037. const { scope } = node;
  14038. node.kind = FIXED_STRINGS[buffer[position]];
  14039. node.declarations = convertNodeList(node, scope, buffer[position + 1], buffer);
  14040. },
  14041. function variableDeclarator(node, position, buffer) {
  14042. const { scope } = node;
  14043. node.id = convertNode(node, scope, buffer[position], buffer);
  14044. const initPosition = buffer[position + 1];
  14045. node.init = initPosition === 0 ? null : convertNode(node, scope, initPosition, buffer);
  14046. },
  14047. function whileStatement(node, position, buffer) {
  14048. const { scope } = node;
  14049. node.test = convertNode(node, scope, buffer[position], buffer);
  14050. node.body = convertNode(node, scope, buffer[position + 1], buffer);
  14051. },
  14052. function yieldExpression(node, position, buffer) {
  14053. const { scope } = node;
  14054. const flags = buffer[position];
  14055. node.delegate = (flags & 1) === 1;
  14056. const argumentPosition = buffer[position + 1];
  14057. node.argument =
  14058. argumentPosition === 0 ? null : convertNode(node, scope, argumentPosition, buffer);
  14059. }
  14060. ];
  14061. function convertNode(parent, parentScope, position, buffer) {
  14062. const nodeType = buffer[position];
  14063. const NodeConstructor = nodeConstructors$1[nodeType];
  14064. /* istanbul ignore if: This should never be executed but is a safeguard against faulty buffers */
  14065. if (!NodeConstructor) {
  14066. console.trace();
  14067. throw new Error(`Unknown node type: ${nodeType}`);
  14068. }
  14069. const node = new NodeConstructor(parent, parentScope);
  14070. node.type = nodeTypeStrings[nodeType];
  14071. node.start = buffer[position + 1];
  14072. node.end = buffer[position + 2];
  14073. bufferParsers[nodeType](node, position + 3, buffer);
  14074. node.initialise();
  14075. return node;
  14076. }
  14077. function convertNodeList(parent, parentScope, position, buffer) {
  14078. if (position === 0)
  14079. return EMPTY_ARRAY;
  14080. const length = buffer[position++];
  14081. const list = [];
  14082. for (let index = 0; index < length; index++) {
  14083. const nodePosition = buffer[position++];
  14084. list.push(nodePosition ? convertNode(parent, parentScope, nodePosition, buffer) : null);
  14085. }
  14086. return list;
  14087. }
  14088. class UnknownNode extends NodeBase {
  14089. hasEffects() {
  14090. return true;
  14091. }
  14092. include(context) {
  14093. super.include(context, true);
  14094. }
  14095. }
  14096. // This file is generated by scripts/generate-node-index.js.
  14097. // Do not edit this file directly.
  14098. const nodeConstructors = {
  14099. ArrayExpression,
  14100. ArrayPattern,
  14101. ArrowFunctionExpression,
  14102. AssignmentExpression,
  14103. AssignmentPattern,
  14104. AwaitExpression,
  14105. BinaryExpression,
  14106. BlockStatement,
  14107. BreakStatement,
  14108. CallExpression,
  14109. CatchClause,
  14110. ChainExpression,
  14111. ClassBody,
  14112. ClassDeclaration,
  14113. ClassExpression,
  14114. ConditionalExpression,
  14115. ContinueStatement,
  14116. DebuggerStatement,
  14117. Decorator,
  14118. DoWhileStatement,
  14119. EmptyStatement,
  14120. ExportAllDeclaration,
  14121. ExportDefaultDeclaration,
  14122. ExportNamedDeclaration,
  14123. ExportSpecifier,
  14124. ExpressionStatement,
  14125. ForInStatement,
  14126. ForOfStatement,
  14127. ForStatement,
  14128. FunctionDeclaration,
  14129. FunctionExpression,
  14130. Identifier,
  14131. IfStatement,
  14132. ImportAttribute,
  14133. ImportDeclaration,
  14134. ImportDefaultSpecifier,
  14135. ImportExpression,
  14136. ImportNamespaceSpecifier,
  14137. ImportSpecifier,
  14138. JSXAttribute,
  14139. JSXClosingElement,
  14140. JSXClosingFragment,
  14141. JSXElement,
  14142. JSXEmptyExpression,
  14143. JSXExpressionContainer,
  14144. JSXFragment,
  14145. JSXIdentifier,
  14146. JSXMemberExpression,
  14147. JSXNamespacedName,
  14148. JSXOpeningElement,
  14149. JSXOpeningFragment,
  14150. JSXSpreadAttribute,
  14151. JSXSpreadChild,
  14152. JSXText,
  14153. LabeledStatement,
  14154. Literal,
  14155. LogicalExpression,
  14156. MemberExpression,
  14157. MetaProperty,
  14158. MethodDefinition,
  14159. NewExpression,
  14160. ObjectExpression,
  14161. ObjectPattern,
  14162. PanicError,
  14163. ParseError,
  14164. PrivateIdentifier,
  14165. Program,
  14166. Property,
  14167. PropertyDefinition,
  14168. RestElement,
  14169. ReturnStatement,
  14170. SequenceExpression,
  14171. SpreadElement,
  14172. StaticBlock,
  14173. Super,
  14174. SwitchCase,
  14175. SwitchStatement,
  14176. TaggedTemplateExpression,
  14177. TemplateElement,
  14178. TemplateLiteral,
  14179. ThisExpression,
  14180. ThrowStatement,
  14181. TryStatement,
  14182. UnaryExpression,
  14183. UnknownNode,
  14184. UpdateExpression,
  14185. VariableDeclaration,
  14186. VariableDeclarator,
  14187. WhileStatement,
  14188. YieldExpression
  14189. };
  14190. class ExportShimVariable extends Variable {
  14191. constructor(module) {
  14192. super(MISSING_EXPORT_SHIM_VARIABLE);
  14193. this.module = module;
  14194. }
  14195. include() {
  14196. super.include();
  14197. this.module.needsExportShim = true;
  14198. }
  14199. }
  14200. var BuildPhase;
  14201. (function (BuildPhase) {
  14202. BuildPhase[BuildPhase["LOAD_AND_PARSE"] = 0] = "LOAD_AND_PARSE";
  14203. BuildPhase[BuildPhase["ANALYSE"] = 1] = "ANALYSE";
  14204. BuildPhase[BuildPhase["GENERATE"] = 2] = "GENERATE";
  14205. })(BuildPhase || (BuildPhase = {}));
  14206. const sourceMapCache = new WeakMap();
  14207. /**
  14208. * This clears the decoded array and falls back to the encoded string form.
  14209. * Sourcemap mappings arrays can be very large and holding on to them for longer
  14210. * than is necessary leads to poor heap utilization.
  14211. */
  14212. function resetCacheToEncoded(cache) {
  14213. if (cache.encodedMappings === undefined && cache.decodedMappings) {
  14214. cache.encodedMappings = encode(cache.decodedMappings);
  14215. }
  14216. cache.decodedMappings = undefined;
  14217. }
  14218. function resetSourcemapCache(map, sourcemapChain) {
  14219. if (map) {
  14220. const cache = sourceMapCache.get(map);
  14221. if (cache) {
  14222. resetCacheToEncoded(cache);
  14223. }
  14224. }
  14225. if (!sourcemapChain) {
  14226. return;
  14227. }
  14228. for (const map of sourcemapChain) {
  14229. if (map.missing)
  14230. continue;
  14231. resetSourcemapCache(map);
  14232. }
  14233. }
  14234. function decodedSourcemap(map) {
  14235. if (!map)
  14236. return null;
  14237. if (typeof map === 'string') {
  14238. map = JSON.parse(map);
  14239. }
  14240. if (!map.mappings) {
  14241. return {
  14242. mappings: [],
  14243. names: [],
  14244. sources: [],
  14245. version: 3
  14246. };
  14247. }
  14248. const originalMappings = map.mappings;
  14249. const isAlreadyDecoded = Array.isArray(originalMappings);
  14250. const cache = {
  14251. decodedMappings: isAlreadyDecoded ? originalMappings : undefined,
  14252. encodedMappings: isAlreadyDecoded ? undefined : originalMappings
  14253. };
  14254. const decodedMap = {
  14255. ...map,
  14256. // By moving mappings behind an accessor, we can avoid unneeded computation for cases
  14257. // where the mappings field is never actually accessed. This appears to greatly reduce
  14258. // the overhead of sourcemap decoding in terms of both compute time and memory usage.
  14259. get mappings() {
  14260. if (cache.decodedMappings) {
  14261. return cache.decodedMappings;
  14262. }
  14263. // If decodedMappings doesn't exist then encodedMappings should.
  14264. // The only scenario where cache.encodedMappings should be undefined is if the map
  14265. // this was constructed from was already decoded, or if mappings was set to a new
  14266. // decoded string. In either case, this line shouldn't get hit.
  14267. cache.decodedMappings = cache.encodedMappings ? decode(cache.encodedMappings) : [];
  14268. cache.encodedMappings = undefined;
  14269. return cache.decodedMappings;
  14270. }
  14271. };
  14272. sourceMapCache.set(decodedMap, cache);
  14273. return decodedMap;
  14274. }
  14275. function getId(m) {
  14276. return m.id;
  14277. }
  14278. function getOriginalLocation(sourcemapChain, location) {
  14279. const filteredSourcemapChain = sourcemapChain.filter((sourcemap) => !sourcemap.missing);
  14280. traceSourcemap: while (filteredSourcemapChain.length > 0) {
  14281. const sourcemap = filteredSourcemapChain.pop();
  14282. const line = sourcemap.mappings[location.line - 1];
  14283. if (line) {
  14284. const filteredLine = line.filter((segment) => segment.length > 1);
  14285. const lastSegment = filteredLine[filteredLine.length - 1];
  14286. for (const segment of filteredLine) {
  14287. if (segment[0] >= location.column || segment === lastSegment) {
  14288. location = {
  14289. column: segment[3],
  14290. line: segment[2] + 1
  14291. };
  14292. continue traceSourcemap;
  14293. }
  14294. }
  14295. }
  14296. throw new Error("Can't resolve original location of error.");
  14297. }
  14298. return location;
  14299. }
  14300. const ATTRIBUTE_KEYWORDS = new Set(['assert', 'with']);
  14301. function getAttributesFromImportExpression(node) {
  14302. const { scope: { context }, options, start } = node;
  14303. if (!(options instanceof ObjectExpression)) {
  14304. if (options) {
  14305. context.module.log(LOGLEVEL_WARN, logImportAttributeIsInvalid(context.module.id), start);
  14306. }
  14307. return EMPTY_OBJECT;
  14308. }
  14309. const assertProperty = options.properties.find((property) => ATTRIBUTE_KEYWORDS.has(getPropertyKey(property)))?.value;
  14310. if (!assertProperty) {
  14311. return EMPTY_OBJECT;
  14312. }
  14313. if (!(assertProperty instanceof ObjectExpression)) {
  14314. context.module.log(LOGLEVEL_WARN, logImportOptionsAreInvalid(context.module.id), start);
  14315. return EMPTY_OBJECT;
  14316. }
  14317. const assertFields = assertProperty.properties
  14318. .map(property => {
  14319. const key = getPropertyKey(property);
  14320. if (typeof key === 'string' &&
  14321. typeof property.value.value === 'string') {
  14322. return [key, property.value.value];
  14323. }
  14324. context.module.log(LOGLEVEL_WARN, logImportAttributeIsInvalid(context.module.id), property.start);
  14325. return null;
  14326. })
  14327. .filter((property) => !!property);
  14328. if (assertFields.length > 0) {
  14329. return Object.fromEntries(assertFields);
  14330. }
  14331. return EMPTY_OBJECT;
  14332. }
  14333. const getPropertyKey = (property) => {
  14334. const key = property.key;
  14335. return (key &&
  14336. !property.computed &&
  14337. (key.name || key.value));
  14338. };
  14339. function getAttributesFromImportExportDeclaration(attributes) {
  14340. return attributes?.length
  14341. ? Object.fromEntries(attributes.map(assertion => [getPropertyKey(assertion), assertion.value.value]))
  14342. : EMPTY_OBJECT;
  14343. }
  14344. function doAttributesDiffer(assertionA, assertionB) {
  14345. const keysA = Object.keys(assertionA);
  14346. return (keysA.length !== Object.keys(assertionB).length ||
  14347. keysA.some(key => assertionA[key] !== assertionB[key]));
  14348. }
  14349. let timers = new Map();
  14350. function getPersistedLabel(label, level) {
  14351. switch (level) {
  14352. case 1: {
  14353. return `# ${label}`;
  14354. }
  14355. case 2: {
  14356. return `## ${label}`;
  14357. }
  14358. case 3: {
  14359. return label;
  14360. }
  14361. default: {
  14362. return `- ${label}`;
  14363. }
  14364. }
  14365. }
  14366. function timeStartImpl(label, level = 3) {
  14367. label = getPersistedLabel(label, level);
  14368. const startMemory = process$1.memoryUsage().heapUsed;
  14369. const startTime = performance.now();
  14370. const timer = timers.get(label);
  14371. if (timer === undefined) {
  14372. timers.set(label, {
  14373. memory: 0,
  14374. startMemory,
  14375. startTime,
  14376. time: 0,
  14377. totalMemory: 0
  14378. });
  14379. }
  14380. else {
  14381. timer.startMemory = startMemory;
  14382. timer.startTime = startTime;
  14383. }
  14384. }
  14385. function timeEndImpl(label, level = 3) {
  14386. label = getPersistedLabel(label, level);
  14387. const timer = timers.get(label);
  14388. if (timer !== undefined) {
  14389. const currentMemory = process$1.memoryUsage().heapUsed;
  14390. timer.memory += currentMemory - timer.startMemory;
  14391. timer.time += performance.now() - timer.startTime;
  14392. timer.totalMemory = Math.max(timer.totalMemory, currentMemory);
  14393. }
  14394. }
  14395. function getTimings() {
  14396. const newTimings = {};
  14397. for (const [label, { memory, time, totalMemory }] of timers) {
  14398. newTimings[label] = [time, memory, totalMemory];
  14399. }
  14400. return newTimings;
  14401. }
  14402. let timeStart = doNothing;
  14403. let timeEnd = doNothing;
  14404. const TIMED_PLUGIN_HOOKS = [
  14405. 'augmentChunkHash',
  14406. 'buildEnd',
  14407. 'buildStart',
  14408. 'generateBundle',
  14409. 'load',
  14410. 'moduleParsed',
  14411. 'options',
  14412. 'outputOptions',
  14413. 'renderChunk',
  14414. 'renderDynamicImport',
  14415. 'renderStart',
  14416. 'resolveDynamicImport',
  14417. 'resolveFileUrl',
  14418. 'resolveId',
  14419. 'resolveImportMeta',
  14420. 'shouldTransformCachedModule',
  14421. 'transform',
  14422. 'writeBundle'
  14423. ];
  14424. function getPluginWithTimers(plugin, index) {
  14425. if (plugin._hasTimer)
  14426. return plugin;
  14427. plugin._hasTimer = true;
  14428. for (const hook of TIMED_PLUGIN_HOOKS) {
  14429. if (hook in plugin) {
  14430. let timerLabel = `plugin ${index}`;
  14431. if (plugin.name) {
  14432. timerLabel += ` (${plugin.name})`;
  14433. }
  14434. timerLabel += ` - ${hook}`;
  14435. const handler = function (...parameters) {
  14436. timeStart(timerLabel, 4);
  14437. const result = hookFunction.apply(this, parameters);
  14438. timeEnd(timerLabel, 4);
  14439. return result;
  14440. };
  14441. let hookFunction;
  14442. if (typeof plugin[hook].handler === 'function') {
  14443. hookFunction = plugin[hook].handler;
  14444. plugin[hook].handler = handler;
  14445. }
  14446. else {
  14447. hookFunction = plugin[hook];
  14448. plugin[hook] = handler;
  14449. }
  14450. }
  14451. }
  14452. return plugin;
  14453. }
  14454. function initialiseTimers(inputOptions) {
  14455. if (inputOptions.perf) {
  14456. timers = new Map();
  14457. timeStart = timeStartImpl;
  14458. timeEnd = timeEndImpl;
  14459. inputOptions.plugins = inputOptions.plugins.map(getPluginWithTimers);
  14460. }
  14461. else {
  14462. timeStart = doNothing;
  14463. timeEnd = doNothing;
  14464. }
  14465. }
  14466. const MISSING_EXPORT_SHIM_DESCRIPTION = {
  14467. identifier: null,
  14468. localName: MISSING_EXPORT_SHIM_VARIABLE
  14469. };
  14470. function getVariableForExportNameRecursive(target, name, importerForSideEffects, isExportAllSearch, searchedNamesAndModules = new Map()) {
  14471. const searchedModules = searchedNamesAndModules.get(name);
  14472. if (searchedModules) {
  14473. if (searchedModules.has(target)) {
  14474. return isExportAllSearch ? [null] : error(logCircularReexport(name, target.id));
  14475. }
  14476. searchedModules.add(target);
  14477. }
  14478. else {
  14479. searchedNamesAndModules.set(name, new Set([target]));
  14480. }
  14481. return target.getVariableForExportName(name, {
  14482. importerForSideEffects,
  14483. isExportAllSearch,
  14484. searchedNamesAndModules
  14485. });
  14486. }
  14487. function getAndExtendSideEffectModules(variable, module) {
  14488. const sideEffectModules = getOrCreate(module.sideEffectDependenciesByVariable, variable, (getNewSet));
  14489. let currentVariable = variable;
  14490. const referencedVariables = new Set([currentVariable]);
  14491. while (true) {
  14492. const importingModule = currentVariable.module;
  14493. currentVariable =
  14494. currentVariable instanceof ExportDefaultVariable
  14495. ? currentVariable.getDirectOriginalVariable()
  14496. : currentVariable instanceof SyntheticNamedExportVariable
  14497. ? currentVariable.syntheticNamespace
  14498. : null;
  14499. if (!currentVariable || referencedVariables.has(currentVariable)) {
  14500. break;
  14501. }
  14502. referencedVariables.add(currentVariable);
  14503. sideEffectModules.add(importingModule);
  14504. const originalSideEffects = importingModule.sideEffectDependenciesByVariable.get(currentVariable);
  14505. if (originalSideEffects) {
  14506. for (const module of originalSideEffects) {
  14507. sideEffectModules.add(module);
  14508. }
  14509. }
  14510. }
  14511. return sideEffectModules;
  14512. }
  14513. class Module {
  14514. constructor(graph, id, options, isEntry, moduleSideEffects, syntheticNamedExports, meta, attributes) {
  14515. this.graph = graph;
  14516. this.id = id;
  14517. this.options = options;
  14518. this.alternativeReexportModules = new Map();
  14519. this.chunkFileNames = new Set();
  14520. this.chunkNames = [];
  14521. this.cycles = new Set();
  14522. this.dependencies = new Set();
  14523. this.dynamicDependencies = new Set();
  14524. this.dynamicImporters = [];
  14525. this.dynamicImports = [];
  14526. this.execIndex = Infinity;
  14527. this.hasTreeShakingPassStarted = false;
  14528. this.implicitlyLoadedAfter = new Set();
  14529. this.implicitlyLoadedBefore = new Set();
  14530. this.importDescriptions = new Map();
  14531. this.importMetas = [];
  14532. this.importedFromNotTreeshaken = false;
  14533. this.importers = [];
  14534. this.includedDynamicImporters = [];
  14535. this.includedImports = new Set();
  14536. this.isExecuted = false;
  14537. this.isUserDefinedEntryPoint = false;
  14538. this.needsExportShim = false;
  14539. this.sideEffectDependenciesByVariable = new Map();
  14540. this.sourcesWithAttributes = new Map();
  14541. this.allExportNames = null;
  14542. this.ast = null;
  14543. this.exportAllModules = [];
  14544. this.exportAllSources = new Set();
  14545. this.exportNamesByVariable = null;
  14546. this.exportShimVariable = new ExportShimVariable(this);
  14547. this.exports = new Map();
  14548. this.namespaceReexportsByName = new Map();
  14549. this.reexportDescriptions = new Map();
  14550. this.relevantDependencies = null;
  14551. this.syntheticExports = new Map();
  14552. this.syntheticNamespace = null;
  14553. this.transformDependencies = [];
  14554. this.transitiveReexports = null;
  14555. this.excludeFromSourcemap = /\0/.test(id);
  14556. this.context = options.moduleContext(id);
  14557. this.preserveSignature = this.options.preserveEntrySignatures;
  14558. // eslint-disable-next-line @typescript-eslint/no-this-alias
  14559. const module = this;
  14560. const { dynamicImports, dynamicImporters, exportAllSources, exports, implicitlyLoadedAfter, implicitlyLoadedBefore, importers, reexportDescriptions, sourcesWithAttributes } = this;
  14561. this.info = {
  14562. ast: null,
  14563. attributes,
  14564. code: null,
  14565. get dynamicallyImportedIdResolutions() {
  14566. return dynamicImports
  14567. .map(({ argument }) => typeof argument === 'string' && module.resolvedIds[argument])
  14568. .filter(Boolean);
  14569. },
  14570. get dynamicallyImportedIds() {
  14571. // We cannot use this.dynamicDependencies because this is needed before
  14572. // dynamicDependencies are populated
  14573. return dynamicImports.map(({ id }) => id).filter((id) => id != null);
  14574. },
  14575. get dynamicImporters() {
  14576. return dynamicImporters.sort();
  14577. },
  14578. get exportedBindings() {
  14579. const exportBindings = { '.': [...exports.keys()] };
  14580. for (const [name, { source }] of reexportDescriptions) {
  14581. (exportBindings[source] ??= []).push(name);
  14582. }
  14583. for (const source of exportAllSources) {
  14584. (exportBindings[source] ??= []).push('*');
  14585. }
  14586. return exportBindings;
  14587. },
  14588. get exports() {
  14589. return [
  14590. ...exports.keys(),
  14591. ...reexportDescriptions.keys(),
  14592. ...[...exportAllSources].map(() => '*')
  14593. ];
  14594. },
  14595. get hasDefaultExport() {
  14596. // This information is only valid after parsing
  14597. if (!module.ast) {
  14598. return null;
  14599. }
  14600. return module.exports.has('default') || reexportDescriptions.has('default');
  14601. },
  14602. id,
  14603. get implicitlyLoadedAfterOneOf() {
  14604. return Array.from(implicitlyLoadedAfter, getId).sort();
  14605. },
  14606. get implicitlyLoadedBefore() {
  14607. return Array.from(implicitlyLoadedBefore, getId).sort();
  14608. },
  14609. get importedIdResolutions() {
  14610. return Array.from(sourcesWithAttributes.keys(), source => module.resolvedIds[source]).filter(Boolean);
  14611. },
  14612. get importedIds() {
  14613. // We cannot use this.dependencies because this is needed before
  14614. // dependencies are populated
  14615. return Array.from(sourcesWithAttributes.keys(), source => module.resolvedIds[source]?.id).filter(Boolean);
  14616. },
  14617. get importers() {
  14618. return importers.sort();
  14619. },
  14620. isEntry,
  14621. isExternal: false,
  14622. get isIncluded() {
  14623. if (graph.phase !== BuildPhase.GENERATE) {
  14624. return null;
  14625. }
  14626. return module.isIncluded();
  14627. },
  14628. meta: { ...meta },
  14629. moduleSideEffects,
  14630. syntheticNamedExports
  14631. };
  14632. }
  14633. basename() {
  14634. const base = basename(this.id);
  14635. const extension = extname(this.id);
  14636. return makeLegal(extension ? base.slice(0, -extension.length) : base);
  14637. }
  14638. bindReferences() {
  14639. this.ast.bind();
  14640. }
  14641. cacheInfoGetters() {
  14642. cacheObjectGetters(this.info, [
  14643. 'dynamicallyImportedIdResolutions',
  14644. 'dynamicallyImportedIds',
  14645. 'dynamicImporters',
  14646. 'exportedBindings',
  14647. 'exports',
  14648. 'hasDefaultExport',
  14649. 'implicitlyLoadedAfterOneOf',
  14650. 'implicitlyLoadedBefore',
  14651. 'importedIdResolutions',
  14652. 'importedIds',
  14653. 'importers'
  14654. ]);
  14655. }
  14656. error(properties, pos) {
  14657. if (pos !== undefined) {
  14658. this.addLocationToLogProps(properties, pos);
  14659. }
  14660. return error(properties);
  14661. }
  14662. // sum up the length of all ast nodes that are included
  14663. estimateSize() {
  14664. let size = 0;
  14665. for (const node of this.ast.body) {
  14666. if (node.included) {
  14667. size += node.end - node.start;
  14668. }
  14669. }
  14670. return size;
  14671. }
  14672. getAllExportNames() {
  14673. if (this.allExportNames) {
  14674. return this.allExportNames;
  14675. }
  14676. this.allExportNames = new Set([...this.exports.keys(), ...this.reexportDescriptions.keys()]);
  14677. for (const module of this.exportAllModules) {
  14678. if (module instanceof ExternalModule) {
  14679. this.allExportNames.add(`*${module.id}`);
  14680. continue;
  14681. }
  14682. for (const name of module.getAllExportNames()) {
  14683. if (name !== 'default')
  14684. this.allExportNames.add(name);
  14685. }
  14686. }
  14687. // We do not count the synthetic namespace as a regular export to hide it
  14688. // from entry signatures and namespace objects
  14689. if (typeof this.info.syntheticNamedExports === 'string') {
  14690. this.allExportNames.delete(this.info.syntheticNamedExports);
  14691. }
  14692. return this.allExportNames;
  14693. }
  14694. getDependenciesToBeIncluded() {
  14695. if (this.relevantDependencies)
  14696. return this.relevantDependencies;
  14697. this.relevantDependencies = new Set();
  14698. const necessaryDependencies = new Set();
  14699. const alwaysCheckedDependencies = new Set();
  14700. const dependencyVariables = new Set(this.includedImports);
  14701. if (this.info.isEntry ||
  14702. this.includedDynamicImporters.length > 0 ||
  14703. this.namespace.included ||
  14704. this.implicitlyLoadedAfter.size > 0) {
  14705. for (const exportName of [...this.getReexports(), ...this.getExports()]) {
  14706. const [exportedVariable] = this.getVariableForExportName(exportName);
  14707. if (exportedVariable?.included) {
  14708. dependencyVariables.add(exportedVariable);
  14709. }
  14710. }
  14711. }
  14712. for (let variable of dependencyVariables) {
  14713. const sideEffectDependencies = this.sideEffectDependenciesByVariable.get(variable);
  14714. if (sideEffectDependencies) {
  14715. for (const module of sideEffectDependencies) {
  14716. alwaysCheckedDependencies.add(module);
  14717. }
  14718. }
  14719. if (variable instanceof SyntheticNamedExportVariable) {
  14720. variable = variable.getBaseVariable();
  14721. }
  14722. else if (variable instanceof ExportDefaultVariable) {
  14723. variable = variable.getOriginalVariable();
  14724. }
  14725. necessaryDependencies.add(variable.module);
  14726. }
  14727. if (!this.options.treeshake || this.info.moduleSideEffects === 'no-treeshake') {
  14728. for (const dependency of this.dependencies) {
  14729. this.relevantDependencies.add(dependency);
  14730. }
  14731. }
  14732. else {
  14733. this.addRelevantSideEffectDependencies(this.relevantDependencies, necessaryDependencies, alwaysCheckedDependencies);
  14734. }
  14735. for (const dependency of necessaryDependencies) {
  14736. this.relevantDependencies.add(dependency);
  14737. }
  14738. return this.relevantDependencies;
  14739. }
  14740. getExportNamesByVariable() {
  14741. if (this.exportNamesByVariable) {
  14742. return this.exportNamesByVariable;
  14743. }
  14744. const exportNamesByVariable = new Map();
  14745. for (const exportName of this.getAllExportNames()) {
  14746. let [tracedVariable] = this.getVariableForExportName(exportName);
  14747. if (tracedVariable instanceof ExportDefaultVariable) {
  14748. tracedVariable = tracedVariable.getOriginalVariable();
  14749. }
  14750. if (!tracedVariable ||
  14751. !(tracedVariable.included || tracedVariable instanceof ExternalVariable)) {
  14752. continue;
  14753. }
  14754. const existingExportNames = exportNamesByVariable.get(tracedVariable);
  14755. if (existingExportNames) {
  14756. existingExportNames.push(exportName);
  14757. }
  14758. else {
  14759. exportNamesByVariable.set(tracedVariable, [exportName]);
  14760. }
  14761. }
  14762. return (this.exportNamesByVariable = exportNamesByVariable);
  14763. }
  14764. getExports() {
  14765. return [...this.exports.keys()];
  14766. }
  14767. getReexports() {
  14768. if (this.transitiveReexports) {
  14769. return this.transitiveReexports;
  14770. }
  14771. // to avoid infinite recursion when using circular `export * from X`
  14772. this.transitiveReexports = [];
  14773. const reexports = new Set(this.reexportDescriptions.keys());
  14774. for (const module of this.exportAllModules) {
  14775. if (module instanceof ExternalModule) {
  14776. reexports.add(`*${module.id}`);
  14777. }
  14778. else {
  14779. for (const name of [...module.getReexports(), ...module.getExports()]) {
  14780. if (name !== 'default')
  14781. reexports.add(name);
  14782. }
  14783. }
  14784. }
  14785. return (this.transitiveReexports = [...reexports]);
  14786. }
  14787. getRenderedExports() {
  14788. // only direct exports are counted here, not reexports at all
  14789. const renderedExports = [];
  14790. const removedExports = [];
  14791. for (const exportName of this.exports.keys()) {
  14792. const [variable] = this.getVariableForExportName(exportName);
  14793. (variable?.included ? renderedExports : removedExports).push(exportName);
  14794. }
  14795. return { removedExports, renderedExports };
  14796. }
  14797. getSyntheticNamespace() {
  14798. if (this.syntheticNamespace === null) {
  14799. this.syntheticNamespace = undefined;
  14800. [this.syntheticNamespace] = this.getVariableForExportName(typeof this.info.syntheticNamedExports === 'string'
  14801. ? this.info.syntheticNamedExports
  14802. : 'default', { onlyExplicit: true });
  14803. }
  14804. if (!this.syntheticNamespace) {
  14805. return error(logSyntheticNamedExportsNeedNamespaceExport(this.id, this.info.syntheticNamedExports));
  14806. }
  14807. return this.syntheticNamespace;
  14808. }
  14809. getVariableForExportName(name, { importerForSideEffects, isExportAllSearch, onlyExplicit, searchedNamesAndModules } = EMPTY_OBJECT) {
  14810. if (name[0] === '*') {
  14811. if (name.length === 1) {
  14812. // export * from './other'
  14813. return [this.namespace];
  14814. }
  14815. // export * from 'external'
  14816. const module = this.graph.modulesById.get(name.slice(1));
  14817. return module.getVariableForExportName('*');
  14818. }
  14819. // export { foo } from './other'
  14820. const reexportDeclaration = this.reexportDescriptions.get(name);
  14821. if (reexportDeclaration) {
  14822. const [variable] = getVariableForExportNameRecursive(reexportDeclaration.module, reexportDeclaration.localName, importerForSideEffects, false, searchedNamesAndModules);
  14823. if (!variable) {
  14824. return this.error(logMissingExport(reexportDeclaration.localName, this.id, reexportDeclaration.module.id), reexportDeclaration.start);
  14825. }
  14826. if (importerForSideEffects) {
  14827. setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
  14828. if (this.info.moduleSideEffects) {
  14829. getOrCreate(importerForSideEffects.sideEffectDependenciesByVariable, variable, (getNewSet)).add(this);
  14830. }
  14831. }
  14832. return [variable];
  14833. }
  14834. const exportDeclaration = this.exports.get(name);
  14835. if (exportDeclaration) {
  14836. if (exportDeclaration === MISSING_EXPORT_SHIM_DESCRIPTION) {
  14837. return [this.exportShimVariable];
  14838. }
  14839. const name = exportDeclaration.localName;
  14840. const variable = this.traceVariable(name, {
  14841. importerForSideEffects,
  14842. searchedNamesAndModules
  14843. });
  14844. if (importerForSideEffects) {
  14845. setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
  14846. getOrCreate(importerForSideEffects.sideEffectDependenciesByVariable, variable, (getNewSet)).add(this);
  14847. }
  14848. return [variable];
  14849. }
  14850. if (onlyExplicit) {
  14851. return [null];
  14852. }
  14853. if (name !== 'default') {
  14854. const foundNamespaceReexport = this.namespaceReexportsByName.get(name) ??
  14855. this.getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules);
  14856. this.namespaceReexportsByName.set(name, foundNamespaceReexport);
  14857. if (foundNamespaceReexport[0]) {
  14858. return foundNamespaceReexport;
  14859. }
  14860. }
  14861. if (this.info.syntheticNamedExports) {
  14862. return [
  14863. getOrCreate(this.syntheticExports, name, () => new SyntheticNamedExportVariable(this.astContext, name, this.getSyntheticNamespace()))
  14864. ];
  14865. }
  14866. // we don't want to create shims when we are just
  14867. // probing export * modules for exports
  14868. if (!isExportAllSearch && this.options.shimMissingExports) {
  14869. this.shimMissingExport(name);
  14870. return [this.exportShimVariable];
  14871. }
  14872. return [null];
  14873. }
  14874. hasEffects() {
  14875. return this.info.moduleSideEffects === 'no-treeshake' || this.ast.hasCachedEffects();
  14876. }
  14877. include() {
  14878. const context = createInclusionContext();
  14879. if (this.ast.shouldBeIncluded(context))
  14880. this.ast.include(context, false);
  14881. }
  14882. includeAllExports(includeNamespaceMembers) {
  14883. if (!this.isExecuted) {
  14884. markModuleAndImpureDependenciesAsExecuted(this);
  14885. this.graph.needsTreeshakingPass = true;
  14886. }
  14887. for (const exportName of this.exports.keys()) {
  14888. if (includeNamespaceMembers || exportName !== this.info.syntheticNamedExports) {
  14889. const variable = this.getVariableForExportName(exportName)[0];
  14890. if (!variable) {
  14891. return error(logMissingEntryExport(exportName, this.id));
  14892. }
  14893. variable.deoptimizePath(UNKNOWN_PATH);
  14894. if (!variable.included) {
  14895. this.includeVariable(variable);
  14896. }
  14897. }
  14898. }
  14899. for (const name of this.getReexports()) {
  14900. const [variable] = this.getVariableForExportName(name);
  14901. if (variable) {
  14902. variable.deoptimizePath(UNKNOWN_PATH);
  14903. if (!variable.included) {
  14904. this.includeVariable(variable);
  14905. }
  14906. if (variable instanceof ExternalVariable) {
  14907. variable.module.reexported = true;
  14908. }
  14909. }
  14910. }
  14911. if (includeNamespaceMembers) {
  14912. this.namespace.setMergedNamespaces(this.includeAndGetAdditionalMergedNamespaces());
  14913. }
  14914. }
  14915. includeAllInBundle() {
  14916. this.ast.include(createInclusionContext(), true);
  14917. this.includeAllExports(false);
  14918. }
  14919. includeExportsByNames(names) {
  14920. if (!this.isExecuted) {
  14921. markModuleAndImpureDependenciesAsExecuted(this);
  14922. this.graph.needsTreeshakingPass = true;
  14923. }
  14924. let includeNamespaceMembers = false;
  14925. for (const name of names) {
  14926. const variable = this.getVariableForExportName(name)[0];
  14927. if (variable) {
  14928. variable.deoptimizePath(UNKNOWN_PATH);
  14929. if (!variable.included) {
  14930. this.includeVariable(variable);
  14931. }
  14932. }
  14933. if (!this.exports.has(name) && !this.reexportDescriptions.has(name)) {
  14934. includeNamespaceMembers = true;
  14935. }
  14936. }
  14937. if (includeNamespaceMembers) {
  14938. this.namespace.setMergedNamespaces(this.includeAndGetAdditionalMergedNamespaces());
  14939. }
  14940. }
  14941. isIncluded() {
  14942. // Modules where this.ast is missing have been loaded via this.load and are
  14943. // not yet fully processed, hence they cannot be included.
  14944. return (this.ast &&
  14945. (this.ast.included ||
  14946. this.namespace.included ||
  14947. this.importedFromNotTreeshaken ||
  14948. this.exportShimVariable.included));
  14949. }
  14950. linkImports() {
  14951. this.addModulesToImportDescriptions(this.importDescriptions);
  14952. this.addModulesToImportDescriptions(this.reexportDescriptions);
  14953. const externalExportAllModules = [];
  14954. for (const source of this.exportAllSources) {
  14955. const module = this.graph.modulesById.get(this.resolvedIds[source].id);
  14956. if (module instanceof ExternalModule) {
  14957. externalExportAllModules.push(module);
  14958. continue;
  14959. }
  14960. this.exportAllModules.push(module);
  14961. }
  14962. this.exportAllModules.push(...externalExportAllModules);
  14963. }
  14964. log(level, properties, pos) {
  14965. this.addLocationToLogProps(properties, pos);
  14966. this.options.onLog(level, properties);
  14967. }
  14968. render(options) {
  14969. const source = this.magicString.clone();
  14970. this.ast.render(source, options);
  14971. source.trim();
  14972. const { usesTopLevelAwait } = this.astContext;
  14973. if (usesTopLevelAwait && options.format !== 'es' && options.format !== 'system') {
  14974. return error(logInvalidFormatForTopLevelAwait(this.id, options.format));
  14975. }
  14976. return { source, usesTopLevelAwait };
  14977. }
  14978. async setSource({ ast, code, customTransformCache, originalCode, originalSourcemap, resolvedIds, sourcemapChain, transformDependencies, transformFiles, ...moduleOptions }) {
  14979. timeStart('generate ast', 3);
  14980. if (code.startsWith('#!')) {
  14981. const shebangEndPosition = code.indexOf('\n');
  14982. this.shebang = code.slice(2, shebangEndPosition);
  14983. }
  14984. this.info.code = code;
  14985. this.originalCode = originalCode;
  14986. // We need to call decodedSourcemap on the input in case they were hydrated from json in the cache and don't
  14987. // have the lazy evaluation cache configured. Right now this isn't enforced by the type system because the
  14988. // RollupCache stores `ExistingDecodedSourcemap` instead of `ExistingRawSourcemap`
  14989. this.originalSourcemap = decodedSourcemap(originalSourcemap);
  14990. this.sourcemapChain = sourcemapChain.map(mapOrMissing => mapOrMissing.missing ? mapOrMissing : decodedSourcemap(mapOrMissing));
  14991. // If coming from cache and this value is already fully decoded, we want to re-encode here to save memory.
  14992. resetSourcemapCache(this.originalSourcemap, this.sourcemapChain);
  14993. if (transformFiles) {
  14994. this.transformFiles = transformFiles;
  14995. }
  14996. this.transformDependencies = transformDependencies;
  14997. this.customTransformCache = customTransformCache;
  14998. this.updateOptions(moduleOptions);
  14999. this.resolvedIds = resolvedIds ?? Object.create(null);
  15000. // By default, `id` is the file name. Custom resolvers and loaders
  15001. // can change that, but it makes sense to use it for the source file name
  15002. const fileName = this.id;
  15003. this.magicString = new MagicString(code, {
  15004. filename: (this.excludeFromSourcemap ? null : fileName), // don't include plugin helpers in sourcemap
  15005. indentExclusionRanges: []
  15006. });
  15007. this.astContext = {
  15008. addDynamicImport: this.addDynamicImport.bind(this),
  15009. addExport: this.addExport.bind(this),
  15010. addImport: this.addImport.bind(this),
  15011. addImportMeta: this.addImportMeta.bind(this),
  15012. addImportSource: this.addImportSource.bind(this),
  15013. code, // Only needed for debugging
  15014. deoptimizationTracker: this.graph.deoptimizationTracker,
  15015. error: this.error.bind(this),
  15016. fileName, // Needed for warnings
  15017. getExports: this.getExports.bind(this),
  15018. getImportedJsxFactoryVariable: this.getImportedJsxFactoryVariable.bind(this),
  15019. getModuleExecIndex: () => this.execIndex,
  15020. getModuleName: this.basename.bind(this),
  15021. getNodeConstructor: (name) => nodeConstructors[name] || nodeConstructors.UnknownNode,
  15022. getReexports: this.getReexports.bind(this),
  15023. importDescriptions: this.importDescriptions,
  15024. includeAllExports: () => this.includeAllExports(true),
  15025. includeDynamicImport: this.includeDynamicImport.bind(this),
  15026. includeVariableInModule: this.includeVariableInModule.bind(this),
  15027. log: this.log.bind(this),
  15028. magicString: this.magicString,
  15029. manualPureFunctions: this.graph.pureFunctions,
  15030. module: this,
  15031. moduleContext: this.context,
  15032. options: this.options,
  15033. requestTreeshakingPass: () => (this.graph.needsTreeshakingPass = true),
  15034. traceExport: (name) => this.getVariableForExportName(name)[0],
  15035. traceVariable: this.traceVariable.bind(this),
  15036. usesTopLevelAwait: false
  15037. };
  15038. this.scope = new ModuleScope(this.graph.scope, this.astContext);
  15039. this.namespace = new NamespaceVariable(this.astContext);
  15040. const programParent = { context: this.astContext, type: 'Module' };
  15041. if (ast) {
  15042. this.ast = new nodeConstructors[ast.type](programParent, this.scope).parseNode(ast);
  15043. this.info.ast = ast;
  15044. }
  15045. else {
  15046. // Measuring asynchronous code does not provide reasonable results
  15047. timeEnd('generate ast', 3);
  15048. const astBuffer = await parseAsync(code, false, this.options.jsx !== false);
  15049. timeStart('generate ast', 3);
  15050. this.ast = convertProgram(astBuffer, programParent, this.scope);
  15051. // Make lazy and apply LRU cache to not hog the memory
  15052. Object.defineProperty(this.info, 'ast', {
  15053. get: () => {
  15054. if (this.graph.astLru.has(fileName)) {
  15055. return this.graph.astLru.get(fileName);
  15056. }
  15057. else {
  15058. const parsedAst = this.tryParse();
  15059. // If the cache is not disabled, we need to keep the AST in memory
  15060. // until the end when the cache is generated
  15061. if (this.options.cache !== false) {
  15062. Object.defineProperty(this.info, 'ast', {
  15063. value: parsedAst
  15064. });
  15065. return parsedAst;
  15066. }
  15067. // Otherwise, we keep it in a small LRU cache to not hog too much
  15068. // memory but allow the same AST to be requested several times.
  15069. this.graph.astLru.set(fileName, parsedAst);
  15070. return parsedAst;
  15071. }
  15072. }
  15073. });
  15074. }
  15075. timeEnd('generate ast', 3);
  15076. }
  15077. toJSON() {
  15078. return {
  15079. ast: this.info.ast,
  15080. attributes: this.info.attributes,
  15081. code: this.info.code,
  15082. customTransformCache: this.customTransformCache,
  15083. dependencies: Array.from(this.dependencies, getId),
  15084. id: this.id,
  15085. meta: this.info.meta,
  15086. moduleSideEffects: this.info.moduleSideEffects,
  15087. originalCode: this.originalCode,
  15088. originalSourcemap: this.originalSourcemap,
  15089. resolvedIds: this.resolvedIds,
  15090. sourcemapChain: this.sourcemapChain,
  15091. syntheticNamedExports: this.info.syntheticNamedExports,
  15092. transformDependencies: this.transformDependencies,
  15093. transformFiles: this.transformFiles
  15094. };
  15095. }
  15096. traceVariable(name, { importerForSideEffects, isExportAllSearch, searchedNamesAndModules } = EMPTY_OBJECT) {
  15097. const localVariable = this.scope.variables.get(name);
  15098. if (localVariable) {
  15099. return localVariable;
  15100. }
  15101. const importDescription = this.importDescriptions.get(name);
  15102. if (importDescription) {
  15103. const otherModule = importDescription.module;
  15104. if (otherModule instanceof Module && importDescription.name === '*') {
  15105. return otherModule.namespace;
  15106. }
  15107. const [declaration] = getVariableForExportNameRecursive(otherModule, importDescription.name, importerForSideEffects || this, isExportAllSearch, searchedNamesAndModules);
  15108. if (!declaration) {
  15109. return this.error(logMissingExport(importDescription.name, this.id, otherModule.id), importDescription.start);
  15110. }
  15111. return declaration;
  15112. }
  15113. return null;
  15114. }
  15115. updateOptions({ meta, moduleSideEffects, syntheticNamedExports }) {
  15116. if (moduleSideEffects != null) {
  15117. this.info.moduleSideEffects = moduleSideEffects;
  15118. }
  15119. if (syntheticNamedExports != null) {
  15120. this.info.syntheticNamedExports = syntheticNamedExports;
  15121. }
  15122. if (meta != null) {
  15123. Object.assign(this.info.meta, meta);
  15124. }
  15125. }
  15126. addDynamicImport(node) {
  15127. let argument = node.sourceAstNode;
  15128. if (argument.type === TemplateLiteral$1) {
  15129. if (argument.quasis.length === 1 &&
  15130. typeof argument.quasis[0].value.cooked === 'string') {
  15131. argument = argument.quasis[0].value.cooked;
  15132. }
  15133. }
  15134. else if (argument.type === Literal$1 &&
  15135. typeof argument.value === 'string') {
  15136. argument = argument.value;
  15137. }
  15138. this.dynamicImports.push({ argument, id: null, node, resolution: null });
  15139. }
  15140. assertUniqueExportName(name, nodeStart) {
  15141. if (this.exports.has(name) || this.reexportDescriptions.has(name)) {
  15142. this.error(logDuplicateExportError(name), nodeStart);
  15143. }
  15144. }
  15145. addExport(node) {
  15146. if (node instanceof ExportDefaultDeclaration) {
  15147. // export default foo;
  15148. this.assertUniqueExportName('default', node.start);
  15149. this.exports.set('default', {
  15150. identifier: node.variable.getAssignedVariableName(),
  15151. localName: 'default'
  15152. });
  15153. }
  15154. else if (node instanceof ExportAllDeclaration) {
  15155. const source = node.source.value;
  15156. this.addSource(source, node);
  15157. if (node.exported) {
  15158. // export * as name from './other'
  15159. const name = node.exported instanceof Literal ? node.exported.value : node.exported.name;
  15160. this.assertUniqueExportName(name, node.exported.start);
  15161. this.reexportDescriptions.set(name, {
  15162. localName: '*',
  15163. module: null, // filled in later,
  15164. source,
  15165. start: node.start
  15166. });
  15167. }
  15168. else {
  15169. // export * from './other'
  15170. this.exportAllSources.add(source);
  15171. }
  15172. }
  15173. else if (node.source instanceof Literal) {
  15174. // export { name } from './other'
  15175. const source = node.source.value;
  15176. this.addSource(source, node);
  15177. for (const { exported, local, start } of node.specifiers) {
  15178. const name = exported instanceof Literal ? exported.value : exported.name;
  15179. this.assertUniqueExportName(name, start);
  15180. this.reexportDescriptions.set(name, {
  15181. localName: local instanceof Literal ? local.value : local.name,
  15182. module: null, // filled in later,
  15183. source,
  15184. start
  15185. });
  15186. }
  15187. }
  15188. else if (node.declaration) {
  15189. const declaration = node.declaration;
  15190. if (declaration instanceof VariableDeclaration) {
  15191. // export var { foo, bar } = ...
  15192. // export var foo = 1, bar = 2;
  15193. for (const declarator of declaration.declarations) {
  15194. for (const localName of extractAssignedNames(declarator.id)) {
  15195. this.assertUniqueExportName(localName, declarator.id.start);
  15196. this.exports.set(localName, { identifier: null, localName });
  15197. }
  15198. }
  15199. }
  15200. else {
  15201. // export function foo () {}
  15202. const localName = declaration.id.name;
  15203. this.assertUniqueExportName(localName, declaration.id.start);
  15204. this.exports.set(localName, { identifier: null, localName });
  15205. }
  15206. }
  15207. else {
  15208. // export { foo, bar, baz }
  15209. for (const { local, exported } of node.specifiers) {
  15210. // except for reexports, local must be an Identifier
  15211. const localName = local.name;
  15212. const exportedName = exported instanceof Identifier ? exported.name : exported.value;
  15213. this.assertUniqueExportName(exportedName, exported.start);
  15214. this.exports.set(exportedName, { identifier: null, localName });
  15215. }
  15216. }
  15217. }
  15218. addImport(node) {
  15219. const source = node.source.value;
  15220. this.addSource(source, node);
  15221. for (const specifier of node.specifiers) {
  15222. const localName = specifier.local.name;
  15223. if (this.scope.variables.has(localName) || this.importDescriptions.has(localName)) {
  15224. this.error(logRedeclarationError(localName), specifier.local.start);
  15225. }
  15226. const name = specifier instanceof ImportDefaultSpecifier
  15227. ? 'default'
  15228. : specifier instanceof ImportNamespaceSpecifier
  15229. ? '*'
  15230. : specifier.imported instanceof Identifier
  15231. ? specifier.imported.name
  15232. : specifier.imported.value;
  15233. this.importDescriptions.set(localName, {
  15234. module: null, // filled in later
  15235. name,
  15236. source,
  15237. start: specifier.start
  15238. });
  15239. }
  15240. }
  15241. addImportSource(importSource) {
  15242. if (importSource && !this.sourcesWithAttributes.has(importSource)) {
  15243. this.sourcesWithAttributes.set(importSource, EMPTY_OBJECT);
  15244. }
  15245. }
  15246. addImportMeta(node) {
  15247. this.importMetas.push(node);
  15248. }
  15249. addLocationToLogProps(properties, pos) {
  15250. properties.id = this.id;
  15251. properties.pos = pos;
  15252. let code = this.info.code;
  15253. const location = locate(code, pos, { offsetLine: 1 });
  15254. if (location) {
  15255. let { column, line } = location;
  15256. try {
  15257. ({ column, line } = getOriginalLocation(this.sourcemapChain, { column, line }));
  15258. code = this.originalCode;
  15259. }
  15260. catch (error_) {
  15261. this.options.onLog(LOGLEVEL_WARN, logInvalidSourcemapForError(error_, this.id, column, line, pos));
  15262. }
  15263. augmentCodeLocation(properties, { column, line }, code, this.id);
  15264. }
  15265. }
  15266. addModulesToImportDescriptions(importDescription) {
  15267. for (const specifier of importDescription.values()) {
  15268. const { id } = this.resolvedIds[specifier.source];
  15269. specifier.module = this.graph.modulesById.get(id);
  15270. }
  15271. }
  15272. addRelevantSideEffectDependencies(relevantDependencies, necessaryDependencies, alwaysCheckedDependencies) {
  15273. const handledDependencies = new Set();
  15274. const addSideEffectDependencies = (possibleDependencies) => {
  15275. for (const dependency of possibleDependencies) {
  15276. if (handledDependencies.has(dependency)) {
  15277. continue;
  15278. }
  15279. handledDependencies.add(dependency);
  15280. if (necessaryDependencies.has(dependency)) {
  15281. relevantDependencies.add(dependency);
  15282. continue;
  15283. }
  15284. if (!(dependency.info.moduleSideEffects || alwaysCheckedDependencies.has(dependency))) {
  15285. continue;
  15286. }
  15287. if (dependency instanceof ExternalModule || dependency.hasEffects()) {
  15288. relevantDependencies.add(dependency);
  15289. continue;
  15290. }
  15291. addSideEffectDependencies(dependency.dependencies);
  15292. }
  15293. };
  15294. addSideEffectDependencies(this.dependencies);
  15295. addSideEffectDependencies(alwaysCheckedDependencies);
  15296. }
  15297. addSource(source, declaration) {
  15298. const parsedAttributes = getAttributesFromImportExportDeclaration(declaration.attributes);
  15299. const existingAttributes = this.sourcesWithAttributes.get(source);
  15300. if (existingAttributes) {
  15301. if (doAttributesDiffer(existingAttributes, parsedAttributes)) {
  15302. this.log(LOGLEVEL_WARN, logInconsistentImportAttributes(existingAttributes, parsedAttributes, source, this.id), declaration.start);
  15303. }
  15304. }
  15305. else {
  15306. this.sourcesWithAttributes.set(source, parsedAttributes);
  15307. }
  15308. }
  15309. getImportedJsxFactoryVariable(baseName, nodeStart, importSource) {
  15310. const { id } = this.resolvedIds[importSource];
  15311. const module = this.graph.modulesById.get(id);
  15312. const [variable] = module.getVariableForExportName(baseName);
  15313. if (!variable) {
  15314. return this.error(logMissingJsxExport(baseName, id, this.id), nodeStart);
  15315. }
  15316. return variable;
  15317. }
  15318. getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules) {
  15319. let foundSyntheticDeclaration = null;
  15320. const foundInternalDeclarations = new Map();
  15321. const foundExternalDeclarations = new Set();
  15322. for (const module of this.exportAllModules) {
  15323. // Synthetic namespaces should not hide "regular" exports of the same name
  15324. if (module.info.syntheticNamedExports === name) {
  15325. continue;
  15326. }
  15327. const [variable, indirectExternal] = getVariableForExportNameRecursive(module, name, importerForSideEffects, true,
  15328. // We are creating a copy to handle the case where the same binding is
  15329. // imported through different namespace reexports gracefully
  15330. copyNameToModulesMap(searchedNamesAndModules));
  15331. if (module instanceof ExternalModule || indirectExternal) {
  15332. foundExternalDeclarations.add(variable);
  15333. }
  15334. else if (variable instanceof SyntheticNamedExportVariable) {
  15335. if (!foundSyntheticDeclaration) {
  15336. foundSyntheticDeclaration = variable;
  15337. }
  15338. }
  15339. else if (variable) {
  15340. foundInternalDeclarations.set(variable, module);
  15341. }
  15342. }
  15343. if (foundInternalDeclarations.size > 0) {
  15344. const foundDeclarationList = [...foundInternalDeclarations];
  15345. const usedDeclaration = foundDeclarationList[0][0];
  15346. if (foundDeclarationList.length === 1) {
  15347. return [usedDeclaration];
  15348. }
  15349. this.options.onLog(LOGLEVEL_WARN, logNamespaceConflict(name, this.id, foundDeclarationList.map(([, module]) => module.id)));
  15350. // TODO we are pretending it was not found while it should behave like "undefined"
  15351. return [null];
  15352. }
  15353. if (foundExternalDeclarations.size > 0) {
  15354. const foundDeclarationList = [...foundExternalDeclarations];
  15355. const usedDeclaration = foundDeclarationList[0];
  15356. if (foundDeclarationList.length > 1) {
  15357. this.options.onLog(LOGLEVEL_WARN, logAmbiguousExternalNamespaces(name, this.id, usedDeclaration.module.id, foundDeclarationList.map(declaration => declaration.module.id)));
  15358. }
  15359. return [usedDeclaration, true];
  15360. }
  15361. if (foundSyntheticDeclaration) {
  15362. return [foundSyntheticDeclaration];
  15363. }
  15364. return [null];
  15365. }
  15366. includeAndGetAdditionalMergedNamespaces() {
  15367. const externalNamespaces = new Set();
  15368. const syntheticNamespaces = new Set();
  15369. for (const module of [this, ...this.exportAllModules]) {
  15370. if (module instanceof ExternalModule) {
  15371. const [externalVariable] = module.getVariableForExportName('*');
  15372. externalVariable.include();
  15373. this.includedImports.add(externalVariable);
  15374. externalNamespaces.add(externalVariable);
  15375. }
  15376. else if (module.info.syntheticNamedExports) {
  15377. const syntheticNamespace = module.getSyntheticNamespace();
  15378. syntheticNamespace.include();
  15379. this.includedImports.add(syntheticNamespace);
  15380. syntheticNamespaces.add(syntheticNamespace);
  15381. }
  15382. }
  15383. return [...syntheticNamespaces, ...externalNamespaces];
  15384. }
  15385. includeDynamicImport(node) {
  15386. const resolution = this.dynamicImports.find(dynamicImport => dynamicImport.node === node).resolution;
  15387. if (resolution instanceof Module) {
  15388. resolution.includedDynamicImporters.push(this);
  15389. const importedNames = this.options.treeshake
  15390. ? node.getDeterministicImportedNames()
  15391. : undefined;
  15392. if (importedNames) {
  15393. resolution.includeExportsByNames(importedNames);
  15394. }
  15395. else {
  15396. resolution.includeAllExports(true);
  15397. }
  15398. }
  15399. }
  15400. includeVariable(variable) {
  15401. const variableModule = variable.module;
  15402. if (variable.included) {
  15403. if (variableModule instanceof Module && variableModule !== this) {
  15404. getAndExtendSideEffectModules(variable, this);
  15405. }
  15406. }
  15407. else {
  15408. variable.include();
  15409. this.graph.needsTreeshakingPass = true;
  15410. if (variableModule instanceof Module) {
  15411. if (!variableModule.isExecuted) {
  15412. markModuleAndImpureDependenciesAsExecuted(variableModule);
  15413. }
  15414. if (variableModule !== this) {
  15415. const sideEffectModules = getAndExtendSideEffectModules(variable, this);
  15416. for (const module of sideEffectModules) {
  15417. if (!module.isExecuted) {
  15418. markModuleAndImpureDependenciesAsExecuted(module);
  15419. }
  15420. }
  15421. }
  15422. }
  15423. }
  15424. }
  15425. includeVariableInModule(variable) {
  15426. this.includeVariable(variable);
  15427. const variableModule = variable.module;
  15428. if (variableModule && variableModule !== this) {
  15429. this.includedImports.add(variable);
  15430. }
  15431. }
  15432. shimMissingExport(name) {
  15433. this.options.onLog(LOGLEVEL_WARN, logShimmedExport(this.id, name));
  15434. this.exports.set(name, MISSING_EXPORT_SHIM_DESCRIPTION);
  15435. }
  15436. tryParse() {
  15437. try {
  15438. return parseAst(this.info.code, { jsx: this.options.jsx !== false });
  15439. }
  15440. catch (error_) {
  15441. return this.error(logModuleParseError(error_, this.id), error_.pos);
  15442. }
  15443. }
  15444. }
  15445. // if there is a cyclic import in the reexport chain, we should not
  15446. // import from the original module but from the cyclic module to not
  15447. // mess up execution order.
  15448. function setAlternativeExporterIfCyclic(variable, importer, reexporter) {
  15449. if (variable.module instanceof Module && variable.module !== reexporter) {
  15450. const exporterCycles = variable.module.cycles;
  15451. if (exporterCycles.size > 0) {
  15452. const importerCycles = reexporter.cycles;
  15453. for (const cycleSymbol of importerCycles) {
  15454. if (exporterCycles.has(cycleSymbol)) {
  15455. importer.alternativeReexportModules.set(variable, reexporter);
  15456. break;
  15457. }
  15458. }
  15459. }
  15460. }
  15461. }
  15462. const copyNameToModulesMap = (searchedNamesAndModules) => searchedNamesAndModules &&
  15463. new Map(Array.from(searchedNamesAndModules, ([name, modules]) => [name, new Set(modules)]));
  15464. const concatSeparator = (out, next) => (next ? `${out}\n${next}` : out);
  15465. const concatDblSeparator = (out, next) => (next ? `${out}\n\n${next}` : out);
  15466. async function createAddons(options, outputPluginDriver, chunk) {
  15467. try {
  15468. let [banner, footer, intro, outro] = await Promise.all([
  15469. outputPluginDriver.hookReduceValue('banner', options.banner(chunk), [chunk], concatSeparator),
  15470. outputPluginDriver.hookReduceValue('footer', options.footer(chunk), [chunk], concatSeparator),
  15471. outputPluginDriver.hookReduceValue('intro', options.intro(chunk), [chunk], concatDblSeparator),
  15472. outputPluginDriver.hookReduceValue('outro', options.outro(chunk), [chunk], concatDblSeparator)
  15473. ]);
  15474. if (intro)
  15475. intro += '\n\n';
  15476. if (outro)
  15477. outro = `\n\n${outro}`;
  15478. if (banner)
  15479. banner += '\n';
  15480. if (footer)
  15481. footer = '\n' + footer;
  15482. return { banner, footer, intro, outro };
  15483. }
  15484. catch (error_) {
  15485. return error(logAddonNotGenerated(error_.message, error_.hook, error_.plugin));
  15486. }
  15487. }
  15488. const DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT = {
  15489. amd: deconflictImportsOther,
  15490. cjs: deconflictImportsOther,
  15491. es: deconflictImportsEsmOrSystem,
  15492. iife: deconflictImportsOther,
  15493. system: deconflictImportsEsmOrSystem,
  15494. umd: deconflictImportsOther
  15495. };
  15496. function deconflictChunk(modules, dependenciesToBeDeconflicted, imports, usedNames, format, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports, exportNamesByVariable, accessedGlobalsByScope, includedNamespaces) {
  15497. const reversedModules = [...modules].reverse();
  15498. for (const module of reversedModules) {
  15499. module.scope.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
  15500. }
  15501. deconflictTopLevelVariables(usedNames, reversedModules, includedNamespaces);
  15502. DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT[format](usedNames, imports, dependenciesToBeDeconflicted, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports);
  15503. for (const module of reversedModules) {
  15504. module.scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  15505. }
  15506. }
  15507. function deconflictImportsEsmOrSystem(usedNames, imports, dependenciesToBeDeconflicted, _interop, preserveModules, _externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports) {
  15508. // This is needed for namespace reexports
  15509. for (const dependency of dependenciesToBeDeconflicted.dependencies) {
  15510. if (preserveModules || dependency instanceof ExternalChunk) {
  15511. dependency.variableName = getSafeName(dependency.suggestedVariableName, usedNames, null);
  15512. }
  15513. }
  15514. for (const variable of imports) {
  15515. const module = variable.module;
  15516. const name = variable.name;
  15517. if (variable.isNamespace && (preserveModules || module instanceof ExternalModule)) {
  15518. variable.setRenderNames(null, (module instanceof ExternalModule
  15519. ? externalChunkByModule.get(module)
  15520. : chunkByModule.get(module)).variableName);
  15521. }
  15522. else if (module instanceof ExternalModule && name === 'default') {
  15523. variable.setRenderNames(null, getSafeName([...module.exportedVariables].some(([exportedVariable, exportedName]) => exportedName === '*' && exportedVariable.included)
  15524. ? module.suggestedVariableName + '__default'
  15525. : module.suggestedVariableName, usedNames, variable.forbiddenNames));
  15526. }
  15527. else {
  15528. variable.setRenderNames(null, getSafeName(makeLegal(name), usedNames, variable.forbiddenNames));
  15529. }
  15530. }
  15531. for (const variable of syntheticExports) {
  15532. variable.setRenderNames(null, getSafeName(variable.name, usedNames, variable.forbiddenNames));
  15533. }
  15534. }
  15535. function deconflictImportsOther(usedNames, imports, { deconflictedDefault, deconflictedNamespace, dependencies }, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule) {
  15536. for (const chunk of dependencies) {
  15537. chunk.variableName = getSafeName(chunk.suggestedVariableName, usedNames, null);
  15538. }
  15539. for (const chunk of deconflictedNamespace) {
  15540. chunk.namespaceVariableName = getSafeName(`${chunk.suggestedVariableName}__namespace`, usedNames, null);
  15541. }
  15542. for (const externalModule of deconflictedDefault) {
  15543. externalModule.defaultVariableName =
  15544. deconflictedNamespace.has(externalModule) &&
  15545. canDefaultBeTakenFromNamespace(interop(externalModule.id), externalLiveBindings)
  15546. ? externalModule.namespaceVariableName
  15547. : getSafeName(`${externalModule.suggestedVariableName}__default`, usedNames, null);
  15548. }
  15549. for (const variable of imports) {
  15550. const module = variable.module;
  15551. if (module instanceof ExternalModule) {
  15552. const chunk = externalChunkByModule.get(module);
  15553. const name = variable.name;
  15554. if (name === 'default') {
  15555. const moduleInterop = interop(module.id);
  15556. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  15557. ? chunk.defaultVariableName
  15558. : chunk.variableName;
  15559. if (isDefaultAProperty(moduleInterop, externalLiveBindings)) {
  15560. variable.setRenderNames(variableName, 'default');
  15561. }
  15562. else {
  15563. variable.setRenderNames(null, variableName);
  15564. }
  15565. }
  15566. else if (name === '*') {
  15567. variable.setRenderNames(null, namespaceInteropHelpersByInteropType[interop(module.id)]
  15568. ? chunk.namespaceVariableName
  15569. : chunk.variableName);
  15570. }
  15571. else {
  15572. // if the second parameter is `null`, it uses its "name" for the property name
  15573. variable.setRenderNames(chunk.variableName, null);
  15574. }
  15575. }
  15576. else {
  15577. const chunk = chunkByModule.get(module);
  15578. if (preserveModules && variable.isNamespace) {
  15579. variable.setRenderNames(null, chunk.exportMode === 'default' ? chunk.namespaceVariableName : chunk.variableName);
  15580. }
  15581. else if (chunk.exportMode === 'default') {
  15582. variable.setRenderNames(null, chunk.variableName);
  15583. }
  15584. else {
  15585. variable.setRenderNames(chunk.variableName, chunk.getVariableExportName(variable));
  15586. }
  15587. }
  15588. }
  15589. }
  15590. function deconflictTopLevelVariables(usedNames, modules, includedNamespaces) {
  15591. for (const module of modules) {
  15592. for (const variable of module.scope.variables.values()) {
  15593. if (variable.included &&
  15594. // this will only happen for exports in some formats
  15595. !(variable.renderBaseName ||
  15596. (variable instanceof ExportDefaultVariable && variable.getOriginalVariable() !== variable))) {
  15597. variable.setRenderNames(null, getSafeName(variable.name, usedNames, variable.forbiddenNames));
  15598. }
  15599. }
  15600. if (includedNamespaces.has(module)) {
  15601. const namespace = module.namespace;
  15602. namespace.setRenderNames(null, getSafeName(namespace.name, usedNames, namespace.forbiddenNames));
  15603. }
  15604. }
  15605. }
  15606. function assignExportsToMangledNames(exports, exportsByName, exportNamesByVariable) {
  15607. let nameIndex = 0;
  15608. for (const variable of exports) {
  15609. let [exportName] = variable.name;
  15610. if (exportsByName.has(exportName)) {
  15611. do {
  15612. exportName = toBase64(++nameIndex);
  15613. // skip past leading number identifiers
  15614. if (exportName.charCodeAt(0) === 49 /* '1' */) {
  15615. nameIndex += 9 * 64 ** (exportName.length - 1);
  15616. exportName = toBase64(nameIndex);
  15617. }
  15618. } while (RESERVED_NAMES.has(exportName) || exportsByName.has(exportName));
  15619. }
  15620. exportsByName.set(exportName, variable);
  15621. exportNamesByVariable.set(variable, [exportName]);
  15622. }
  15623. }
  15624. function assignExportsToNames(exports, exportsByName, exportNamesByVariable) {
  15625. for (const variable of exports) {
  15626. let nameIndex = 0;
  15627. let exportName = variable.name;
  15628. while (exportsByName.has(exportName)) {
  15629. exportName = variable.name + '$' + ++nameIndex;
  15630. }
  15631. exportsByName.set(exportName, variable);
  15632. exportNamesByVariable.set(variable, [exportName]);
  15633. }
  15634. }
  15635. function getExportMode(chunk, { exports: exportMode, name, format }, facadeModuleId, log) {
  15636. const exportKeys = chunk.getExportNames();
  15637. if (exportMode === 'default') {
  15638. if (exportKeys.length !== 1 || exportKeys[0] !== 'default') {
  15639. return error(logIncompatibleExportOptionValue('default', exportKeys, facadeModuleId));
  15640. }
  15641. }
  15642. else if (exportMode === 'none' && exportKeys.length > 0) {
  15643. return error(logIncompatibleExportOptionValue('none', exportKeys, facadeModuleId));
  15644. }
  15645. if (exportMode === 'auto') {
  15646. if (exportKeys.length === 0) {
  15647. exportMode = 'none';
  15648. }
  15649. else if (exportKeys.length === 1 && exportKeys[0] === 'default') {
  15650. exportMode = 'default';
  15651. }
  15652. else {
  15653. if (format !== 'es' && format !== 'system' && exportKeys.includes('default')) {
  15654. log(LOGLEVEL_WARN, logMixedExport(facadeModuleId, name));
  15655. }
  15656. exportMode = 'named';
  15657. }
  15658. }
  15659. return exportMode;
  15660. }
  15661. function guessIndentString(code) {
  15662. const lines = code.split('\n');
  15663. const tabbed = lines.filter(line => /^\t+/.test(line));
  15664. const spaced = lines.filter(line => /^ {2,}/.test(line));
  15665. if (tabbed.length === 0 && spaced.length === 0) {
  15666. return null;
  15667. }
  15668. // More lines tabbed than spaced? Assume tabs, and
  15669. // default to tabs in the case of a tie (or nothing
  15670. // to go on)
  15671. if (tabbed.length >= spaced.length) {
  15672. return '\t';
  15673. }
  15674. // Otherwise, we need to guess the multiple
  15675. const min = spaced.reduce((previous, current) => {
  15676. const numberSpaces = /^ +/.exec(current)[0].length;
  15677. return Math.min(numberSpaces, previous);
  15678. }, Infinity);
  15679. return ' '.repeat(min);
  15680. }
  15681. function getIndentString(modules, options) {
  15682. if (options.indent !== true)
  15683. return options.indent;
  15684. for (const module of modules) {
  15685. const indent = guessIndentString(module.originalCode);
  15686. if (indent !== null)
  15687. return indent;
  15688. }
  15689. return '\t';
  15690. }
  15691. function getStaticDependencies(chunk, orderedModules, chunkByModule, externalChunkByModule) {
  15692. const staticDependencyBlocks = [];
  15693. const handledDependencies = new Set();
  15694. for (let modulePos = orderedModules.length - 1; modulePos >= 0; modulePos--) {
  15695. const module = orderedModules[modulePos];
  15696. if (!handledDependencies.has(module)) {
  15697. const staticDependencies = [];
  15698. addStaticDependencies(module, staticDependencies, handledDependencies, chunk, chunkByModule, externalChunkByModule);
  15699. staticDependencyBlocks.unshift(staticDependencies);
  15700. }
  15701. }
  15702. const dependencies = new Set();
  15703. for (const block of staticDependencyBlocks) {
  15704. for (const dependency of block) {
  15705. dependencies.add(dependency);
  15706. }
  15707. }
  15708. return dependencies;
  15709. }
  15710. function addStaticDependencies(module, staticDependencies, handledModules, chunk, chunkByModule, externalChunkByModule) {
  15711. const dependencies = module.getDependenciesToBeIncluded();
  15712. for (const dependency of dependencies) {
  15713. if (dependency instanceof ExternalModule) {
  15714. staticDependencies.push(externalChunkByModule.get(dependency));
  15715. continue;
  15716. }
  15717. const dependencyChunk = chunkByModule.get(dependency);
  15718. if (dependencyChunk !== chunk) {
  15719. staticDependencies.push(dependencyChunk);
  15720. continue;
  15721. }
  15722. if (!handledModules.has(dependency)) {
  15723. handledModules.add(dependency);
  15724. addStaticDependencies(dependency, staticDependencies, handledModules, chunk, chunkByModule, externalChunkByModule);
  15725. }
  15726. }
  15727. }
  15728. // Four random characters from the private use area to minimize risk of
  15729. // conflicts
  15730. const hashPlaceholderLeft = '!~{';
  15731. const hashPlaceholderRight = '}~';
  15732. const hashPlaceholderOverhead = hashPlaceholderLeft.length + hashPlaceholderRight.length;
  15733. // This is the size of a 128-bits xxhash with base64url encoding
  15734. const MAX_HASH_SIZE = 22;
  15735. const DEFAULT_HASH_SIZE = 8;
  15736. const getHashPlaceholderGenerator = () => {
  15737. let nextIndex = 0;
  15738. return (optionName, hashSize) => {
  15739. if (hashSize > MAX_HASH_SIZE) {
  15740. return error(logFailedValidation(`Hashes cannot be longer than ${MAX_HASH_SIZE} characters, received ${hashSize}. Check the "${optionName}" option.`));
  15741. }
  15742. const placeholder = `${hashPlaceholderLeft}${toBase64(++nextIndex).padStart(hashSize - hashPlaceholderOverhead, '0')}${hashPlaceholderRight}`;
  15743. if (placeholder.length > hashSize) {
  15744. 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.`));
  15745. }
  15746. return placeholder;
  15747. };
  15748. };
  15749. const REPLACER_REGEX = new RegExp(`${hashPlaceholderLeft}[0-9a-zA-Z_$]{1,${MAX_HASH_SIZE - hashPlaceholderOverhead}}${hashPlaceholderRight}`, 'g');
  15750. const replacePlaceholders = (code, hashesByPlaceholder) => code.replace(REPLACER_REGEX, placeholder => hashesByPlaceholder.get(placeholder) || placeholder);
  15751. const replaceSinglePlaceholder = (code, placeholder, value) => code.replace(REPLACER_REGEX, match => (match === placeholder ? value : match));
  15752. const replacePlaceholdersWithDefaultAndGetContainedPlaceholders = (code, placeholders) => {
  15753. const containedPlaceholders = new Set();
  15754. const transformedCode = code.replace(REPLACER_REGEX, placeholder => {
  15755. if (placeholders.has(placeholder)) {
  15756. containedPlaceholders.add(placeholder);
  15757. return `${hashPlaceholderLeft}${'0'.repeat(placeholder.length - hashPlaceholderOverhead)}${hashPlaceholderRight}`;
  15758. }
  15759. return placeholder;
  15760. });
  15761. return { containedPlaceholders, transformedCode };
  15762. };
  15763. const lowercaseBundleKeys = Symbol('bundleKeys');
  15764. const FILE_PLACEHOLDER = {
  15765. type: 'placeholder'
  15766. };
  15767. const getOutputBundle = (outputBundleBase) => {
  15768. const reservedLowercaseBundleKeys = new Set();
  15769. return new Proxy(outputBundleBase, {
  15770. deleteProperty(target, key) {
  15771. if (typeof key === 'string') {
  15772. reservedLowercaseBundleKeys.delete(key.toLowerCase());
  15773. }
  15774. return Reflect.deleteProperty(target, key);
  15775. },
  15776. get(target, key) {
  15777. if (key === lowercaseBundleKeys) {
  15778. return reservedLowercaseBundleKeys;
  15779. }
  15780. return Reflect.get(target, key);
  15781. },
  15782. set(target, key, value) {
  15783. if (typeof key === 'string') {
  15784. reservedLowercaseBundleKeys.add(key.toLowerCase());
  15785. }
  15786. return Reflect.set(target, key, value);
  15787. }
  15788. });
  15789. };
  15790. const removeUnreferencedAssets = (outputBundle) => {
  15791. const unreferencedAssets = new Set();
  15792. const bundleEntries = Object.values(outputBundle);
  15793. for (const asset of bundleEntries) {
  15794. if (asset.type === 'asset' && asset.needsCodeReference) {
  15795. unreferencedAssets.add(asset.fileName);
  15796. }
  15797. }
  15798. for (const chunk of bundleEntries) {
  15799. if (chunk.type === 'chunk') {
  15800. for (const referencedFile of chunk.referencedFiles) {
  15801. if (unreferencedAssets.has(referencedFile)) {
  15802. unreferencedAssets.delete(referencedFile);
  15803. }
  15804. }
  15805. }
  15806. }
  15807. for (const file of unreferencedAssets) {
  15808. delete outputBundle[file];
  15809. }
  15810. };
  15811. function renderNamePattern(pattern, patternName, replacements) {
  15812. if (isPathFragment(pattern))
  15813. 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.`));
  15814. return pattern.replace(/\[(\w+)(:\d+)?]/g, (_match, type, size) => {
  15815. if (!replacements.hasOwnProperty(type) || (size && type !== 'hash')) {
  15816. return error(logFailedValidation(`"[${type}${size || ''}]" is not a valid placeholder in the "${patternName}" pattern.`));
  15817. }
  15818. const replacement = replacements[type](size && Number.parseInt(size.slice(1)));
  15819. if (isPathFragment(replacement))
  15820. return error(logFailedValidation(`Invalid substitution "${replacement}" for placeholder "[${type}]" in "${patternName}" pattern, can be neither absolute nor relative path.`));
  15821. return replacement;
  15822. });
  15823. }
  15824. function makeUnique(name, { [lowercaseBundleKeys]: reservedLowercaseBundleKeys }) {
  15825. if (!reservedLowercaseBundleKeys.has(name.toLowerCase()))
  15826. return name;
  15827. const extension = extname(name);
  15828. name = name.slice(0, Math.max(0, name.length - extension.length));
  15829. let uniqueName, uniqueIndex = 1;
  15830. while (reservedLowercaseBundleKeys.has((uniqueName = name + ++uniqueIndex + extension).toLowerCase()))
  15831. ;
  15832. return uniqueName;
  15833. }
  15834. const NON_ASSET_EXTENSIONS = new Set([
  15835. '.js',
  15836. '.jsx',
  15837. '.ts',
  15838. '.tsx',
  15839. '.mjs',
  15840. '.mts',
  15841. '.cjs',
  15842. '.cts'
  15843. ]);
  15844. function getGlobalName(chunk, globals, hasExports, log) {
  15845. const globalName = typeof globals === 'function' ? globals(chunk.id) : globals[chunk.id];
  15846. if (globalName) {
  15847. return globalName;
  15848. }
  15849. if (hasExports) {
  15850. log(LOGLEVEL_WARN, logMissingGlobalName(chunk.id, chunk.variableName));
  15851. return chunk.variableName;
  15852. }
  15853. }
  15854. class Chunk {
  15855. constructor(orderedModules, inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, manualChunkAlias, getPlaceholder, bundle, inputBase, snippets) {
  15856. this.orderedModules = orderedModules;
  15857. this.inputOptions = inputOptions;
  15858. this.outputOptions = outputOptions;
  15859. this.unsetOptions = unsetOptions;
  15860. this.pluginDriver = pluginDriver;
  15861. this.modulesById = modulesById;
  15862. this.chunkByModule = chunkByModule;
  15863. this.externalChunkByModule = externalChunkByModule;
  15864. this.facadeChunkByModule = facadeChunkByModule;
  15865. this.includedNamespaces = includedNamespaces;
  15866. this.manualChunkAlias = manualChunkAlias;
  15867. this.getPlaceholder = getPlaceholder;
  15868. this.bundle = bundle;
  15869. this.inputBase = inputBase;
  15870. this.snippets = snippets;
  15871. this.entryModules = [];
  15872. this.exportMode = 'named';
  15873. this.facadeModule = null;
  15874. this.namespaceVariableName = '';
  15875. this.variableName = '';
  15876. this.accessedGlobalsByScope = new Map();
  15877. this.dependencies = new Set();
  15878. this.dynamicEntryModules = [];
  15879. this.dynamicName = null;
  15880. this.exportNamesByVariable = new Map();
  15881. this.exports = new Set();
  15882. this.exportsByName = new Map();
  15883. this.fileName = null;
  15884. this.implicitEntryModules = [];
  15885. this.implicitlyLoadedBefore = new Set();
  15886. this.imports = new Set();
  15887. this.includedDynamicImports = null;
  15888. this.includedReexportsByModule = new Map();
  15889. // This may be updated in the constructor
  15890. this.isEmpty = true;
  15891. this.name = null;
  15892. this.needsExportsShim = false;
  15893. this.preRenderedChunkInfo = null;
  15894. this.preliminaryFileName = null;
  15895. this.preliminarySourcemapFileName = null;
  15896. this.renderedChunkInfo = null;
  15897. this.renderedDependencies = null;
  15898. this.renderedModules = Object.create(null);
  15899. this.sortedExportNames = null;
  15900. this.strictFacade = false;
  15901. this.execIndex = orderedModules.length > 0 ? orderedModules[0].execIndex : Infinity;
  15902. const chunkModules = new Set(orderedModules);
  15903. for (const module of orderedModules) {
  15904. chunkByModule.set(module, this);
  15905. if (module.namespace.included && !outputOptions.preserveModules) {
  15906. includedNamespaces.add(module);
  15907. }
  15908. if (this.isEmpty && module.isIncluded()) {
  15909. this.isEmpty = false;
  15910. }
  15911. if (module.info.isEntry || outputOptions.preserveModules) {
  15912. this.entryModules.push(module);
  15913. }
  15914. for (const importer of module.includedDynamicImporters) {
  15915. if (!chunkModules.has(importer)) {
  15916. this.dynamicEntryModules.push(module);
  15917. // Modules with synthetic exports need an artificial namespace for dynamic imports
  15918. if (module.info.syntheticNamedExports) {
  15919. includedNamespaces.add(module);
  15920. this.exports.add(module.namespace);
  15921. }
  15922. }
  15923. }
  15924. if (module.implicitlyLoadedAfter.size > 0) {
  15925. this.implicitEntryModules.push(module);
  15926. }
  15927. }
  15928. this.suggestedVariableName = makeLegal(this.generateVariableName());
  15929. }
  15930. static generateFacade(inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, facadedModule, facadeName, getPlaceholder, bundle, inputBase, snippets) {
  15931. const chunk = new Chunk([], inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, null, getPlaceholder, bundle, inputBase, snippets);
  15932. chunk.assignFacadeName(facadeName, facadedModule);
  15933. if (!facadeChunkByModule.has(facadedModule)) {
  15934. facadeChunkByModule.set(facadedModule, chunk);
  15935. }
  15936. for (const dependency of facadedModule.getDependenciesToBeIncluded()) {
  15937. chunk.dependencies.add(dependency instanceof Module
  15938. ? chunkByModule.get(dependency)
  15939. : externalChunkByModule.get(dependency));
  15940. }
  15941. if (!chunk.dependencies.has(chunkByModule.get(facadedModule)) &&
  15942. facadedModule.info.moduleSideEffects &&
  15943. facadedModule.hasEffects()) {
  15944. chunk.dependencies.add(chunkByModule.get(facadedModule));
  15945. }
  15946. chunk.ensureReexportsAreAvailableForModule(facadedModule);
  15947. chunk.facadeModule = facadedModule;
  15948. chunk.strictFacade = true;
  15949. return chunk;
  15950. }
  15951. canModuleBeFacade(module, exposedVariables) {
  15952. const moduleExportNamesByVariable = module.getExportNamesByVariable();
  15953. // All exports of this chunk need to be exposed by the candidate module
  15954. for (const exposedVariable of this.exports) {
  15955. if (!moduleExportNamesByVariable.has(exposedVariable)) {
  15956. return false;
  15957. }
  15958. }
  15959. // Additionally, we need to expose namespaces of dynamic entries that are not the facade module and exports from other entry modules
  15960. for (const exposedVariable of exposedVariables) {
  15961. if (!(exposedVariable.module === module ||
  15962. moduleExportNamesByVariable.has(exposedVariable) ||
  15963. (exposedVariable instanceof SyntheticNamedExportVariable &&
  15964. moduleExportNamesByVariable.has(exposedVariable.getBaseVariable())))) {
  15965. return false;
  15966. }
  15967. }
  15968. return true;
  15969. }
  15970. finalizeChunk(code, map, sourcemapFileName, hashesByPlaceholder) {
  15971. const renderedChunkInfo = this.getRenderedChunkInfo();
  15972. const finalize = (code) => replacePlaceholders(code, hashesByPlaceholder);
  15973. const preliminaryFileName = renderedChunkInfo.fileName;
  15974. const fileName = (this.fileName = finalize(preliminaryFileName));
  15975. return {
  15976. ...renderedChunkInfo,
  15977. code,
  15978. dynamicImports: renderedChunkInfo.dynamicImports.map(finalize),
  15979. fileName,
  15980. implicitlyLoadedBefore: renderedChunkInfo.implicitlyLoadedBefore.map(finalize),
  15981. importedBindings: Object.fromEntries(Object.entries(renderedChunkInfo.importedBindings).map(([fileName, bindings]) => [
  15982. finalize(fileName),
  15983. bindings
  15984. ])),
  15985. imports: renderedChunkInfo.imports.map(finalize),
  15986. map,
  15987. preliminaryFileName,
  15988. referencedFiles: renderedChunkInfo.referencedFiles.map(finalize),
  15989. sourcemapFileName
  15990. };
  15991. }
  15992. generateExports() {
  15993. this.sortedExportNames = null;
  15994. const remainingExports = new Set(this.exports);
  15995. if (this.facadeModule !== null &&
  15996. (this.facadeModule.preserveSignature !== false || this.strictFacade)) {
  15997. const exportNamesByVariable = this.facadeModule.getExportNamesByVariable();
  15998. for (const [variable, exportNames] of exportNamesByVariable) {
  15999. this.exportNamesByVariable.set(variable, [...exportNames]);
  16000. for (const exportName of exportNames) {
  16001. this.exportsByName.set(exportName, variable);
  16002. }
  16003. remainingExports.delete(variable);
  16004. }
  16005. }
  16006. if (this.outputOptions.minifyInternalExports) {
  16007. assignExportsToMangledNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  16008. }
  16009. else {
  16010. assignExportsToNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  16011. }
  16012. if (this.outputOptions.preserveModules || (this.facadeModule && this.facadeModule.info.isEntry))
  16013. this.exportMode = getExportMode(this, this.outputOptions, this.facadeModule.id, this.inputOptions.onLog);
  16014. }
  16015. generateFacades() {
  16016. const facades = [];
  16017. const entryModules = new Set([...this.entryModules, ...this.implicitEntryModules]);
  16018. const exposedVariables = new Set(this.dynamicEntryModules.map(({ namespace }) => namespace));
  16019. for (const module of entryModules) {
  16020. if (module.preserveSignature) {
  16021. for (const exportedVariable of module.getExportNamesByVariable().keys()) {
  16022. // We need to expose all entry exports from this chunk
  16023. if (this.chunkByModule.get(exportedVariable.module) === this) {
  16024. exposedVariables.add(exportedVariable);
  16025. }
  16026. }
  16027. }
  16028. }
  16029. for (const module of entryModules) {
  16030. const requiredFacades = Array.from(new Set(module.chunkNames.filter(({ isUserDefined }) => isUserDefined).map(({ name }) => name)),
  16031. // mapping must run after Set 'name' dedupe
  16032. name => ({
  16033. name
  16034. }));
  16035. if (requiredFacades.length === 0 && module.isUserDefinedEntryPoint) {
  16036. requiredFacades.push({});
  16037. }
  16038. requiredFacades.push(...Array.from(module.chunkFileNames, fileName => ({ fileName })));
  16039. if (requiredFacades.length === 0) {
  16040. requiredFacades.push({});
  16041. }
  16042. if (!this.facadeModule) {
  16043. const needsStrictFacade = !this.outputOptions.preserveModules &&
  16044. (module.preserveSignature === 'strict' ||
  16045. (module.preserveSignature === 'exports-only' &&
  16046. module.getExportNamesByVariable().size > 0));
  16047. if (!needsStrictFacade || this.canModuleBeFacade(module, exposedVariables)) {
  16048. this.facadeModule = module;
  16049. this.facadeChunkByModule.set(module, this);
  16050. if (module.preserveSignature) {
  16051. this.strictFacade = needsStrictFacade;
  16052. }
  16053. this.assignFacadeName(requiredFacades.shift(), module, this.outputOptions.preserveModules);
  16054. }
  16055. }
  16056. for (const facadeName of requiredFacades) {
  16057. 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));
  16058. }
  16059. }
  16060. for (const module of this.dynamicEntryModules) {
  16061. if (module.info.syntheticNamedExports)
  16062. continue;
  16063. if (!this.facadeModule && this.canModuleBeFacade(module, exposedVariables)) {
  16064. this.facadeModule = module;
  16065. this.facadeChunkByModule.set(module, this);
  16066. this.strictFacade = true;
  16067. this.dynamicName = getChunkNameFromModule(module);
  16068. }
  16069. else if (this.facadeModule === module &&
  16070. !this.strictFacade &&
  16071. this.canModuleBeFacade(module, exposedVariables)) {
  16072. this.strictFacade = true;
  16073. }
  16074. else if (!this.facadeChunkByModule.get(module)?.strictFacade) {
  16075. this.includedNamespaces.add(module);
  16076. this.exports.add(module.namespace);
  16077. }
  16078. }
  16079. if (!this.outputOptions.preserveModules) {
  16080. this.addNecessaryImportsForFacades();
  16081. }
  16082. return facades;
  16083. }
  16084. getChunkName() {
  16085. return (this.name ??= this.outputOptions.sanitizeFileName(this.getFallbackChunkName()));
  16086. }
  16087. getExportNames() {
  16088. return (this.sortedExportNames ??= [...this.exportsByName.keys()].sort());
  16089. }
  16090. getFileName() {
  16091. return this.fileName || this.getPreliminaryFileName().fileName;
  16092. }
  16093. getImportPath(importer) {
  16094. return escapeId(getImportPath(importer, this.getFileName(), this.outputOptions.format === 'amd' && !this.outputOptions.amd.forceJsExtensionForImports, true));
  16095. }
  16096. getPreliminaryFileName() {
  16097. if (this.preliminaryFileName) {
  16098. return this.preliminaryFileName;
  16099. }
  16100. let fileName;
  16101. let hashPlaceholder = null;
  16102. const { chunkFileNames, entryFileNames, file, format, preserveModules } = this.outputOptions;
  16103. if (file) {
  16104. fileName = basename(file);
  16105. }
  16106. else if (this.fileName === null) {
  16107. const [pattern, patternName] = preserveModules || this.facadeModule?.isUserDefinedEntryPoint
  16108. ? [entryFileNames, 'output.entryFileNames']
  16109. : [chunkFileNames, 'output.chunkFileNames'];
  16110. fileName = renderNamePattern(typeof pattern === 'function' ? pattern(this.getPreRenderedChunkInfo()) : pattern, patternName, {
  16111. format: () => format,
  16112. hash: size => hashPlaceholder ||
  16113. (hashPlaceholder = this.getPlaceholder(patternName, size || DEFAULT_HASH_SIZE)),
  16114. name: () => this.getChunkName()
  16115. });
  16116. if (!hashPlaceholder) {
  16117. fileName = makeUnique(fileName, this.bundle);
  16118. }
  16119. }
  16120. else {
  16121. fileName = this.fileName;
  16122. }
  16123. if (!hashPlaceholder) {
  16124. this.bundle[fileName] = FILE_PLACEHOLDER;
  16125. }
  16126. // Caching is essential to not conflict with the file name reservation above
  16127. return (this.preliminaryFileName = { fileName, hashPlaceholder });
  16128. }
  16129. getPreliminarySourcemapFileName() {
  16130. if (this.preliminarySourcemapFileName) {
  16131. return this.preliminarySourcemapFileName;
  16132. }
  16133. let sourcemapFileName = null;
  16134. let hashPlaceholder = null;
  16135. const { sourcemapFileNames, format } = this.outputOptions;
  16136. if (sourcemapFileNames) {
  16137. const [pattern, patternName] = [sourcemapFileNames, 'output.sourcemapFileNames'];
  16138. sourcemapFileName = renderNamePattern(typeof pattern === 'function' ? pattern(this.getPreRenderedChunkInfo()) : pattern, patternName, {
  16139. chunkhash: () => this.getPreliminaryFileName().hashPlaceholder || '',
  16140. format: () => format,
  16141. hash: size => hashPlaceholder ||
  16142. (hashPlaceholder = this.getPlaceholder(patternName, size || DEFAULT_HASH_SIZE)),
  16143. name: () => this.getChunkName()
  16144. });
  16145. if (!hashPlaceholder) {
  16146. sourcemapFileName = makeUnique(sourcemapFileName, this.bundle);
  16147. }
  16148. }
  16149. else {
  16150. return null;
  16151. }
  16152. return (this.preliminarySourcemapFileName = { fileName: sourcemapFileName, hashPlaceholder });
  16153. }
  16154. getRenderedChunkInfo() {
  16155. if (this.renderedChunkInfo) {
  16156. return this.renderedChunkInfo;
  16157. }
  16158. return (this.renderedChunkInfo = {
  16159. ...this.getPreRenderedChunkInfo(),
  16160. dynamicImports: this.getDynamicDependencies().map(resolveFileName),
  16161. fileName: this.getFileName(),
  16162. implicitlyLoadedBefore: Array.from(this.implicitlyLoadedBefore, resolveFileName),
  16163. importedBindings: getImportedBindingsPerDependency(this.getRenderedDependencies(), resolveFileName),
  16164. imports: Array.from(this.dependencies, resolveFileName),
  16165. modules: this.renderedModules,
  16166. referencedFiles: this.getReferencedFiles()
  16167. });
  16168. }
  16169. getVariableExportName(variable) {
  16170. if (this.outputOptions.preserveModules && variable instanceof NamespaceVariable) {
  16171. return '*';
  16172. }
  16173. return this.exportNamesByVariable.get(variable)[0];
  16174. }
  16175. link() {
  16176. this.dependencies = getStaticDependencies(this, this.orderedModules, this.chunkByModule, this.externalChunkByModule);
  16177. for (const module of this.orderedModules) {
  16178. this.addImplicitlyLoadedBeforeFromModule(module);
  16179. this.setUpChunkImportsAndExportsForModule(module);
  16180. }
  16181. }
  16182. async render() {
  16183. const { dependencies, exportMode, facadeModule, inputOptions: { onLog }, outputOptions, pluginDriver, snippets } = this;
  16184. const { format, hoistTransitiveImports, preserveModules } = outputOptions;
  16185. // for static and dynamic entry points, add transitive dependencies to this
  16186. // chunk's dependencies to avoid loading latency
  16187. if (hoistTransitiveImports && !preserveModules && facadeModule !== null) {
  16188. for (const dep of dependencies) {
  16189. if (dep instanceof Chunk)
  16190. this.inlineChunkDependencies(dep);
  16191. }
  16192. }
  16193. const preliminaryFileName = this.getPreliminaryFileName();
  16194. const preliminarySourcemapFileName = this.getPreliminarySourcemapFileName();
  16195. const { accessedGlobals, indent, magicString, renderedSource, usedModules, usesTopLevelAwait } = this.renderModules(preliminaryFileName.fileName);
  16196. const renderedDependencies = [...this.getRenderedDependencies().values()];
  16197. const renderedExports = exportMode === 'none' ? [] : this.getChunkExportDeclarations(format);
  16198. let hasExports = renderedExports.length > 0;
  16199. let hasDefaultExport = false;
  16200. for (const renderedDependency of renderedDependencies) {
  16201. const { reexports } = renderedDependency;
  16202. if (reexports?.length) {
  16203. hasExports = true;
  16204. if (!hasDefaultExport && reexports.some(reexport => reexport.reexported === 'default')) {
  16205. hasDefaultExport = true;
  16206. }
  16207. if (format === 'es') {
  16208. renderedDependency.reexports = reexports.filter(({ reexported }) => !renderedExports.find(({ exported }) => exported === reexported));
  16209. }
  16210. }
  16211. }
  16212. if (!hasDefaultExport) {
  16213. for (const { exported } of renderedExports) {
  16214. if (exported === 'default') {
  16215. hasDefaultExport = true;
  16216. break;
  16217. }
  16218. }
  16219. }
  16220. const { intro, outro, banner, footer } = await createAddons(outputOptions, pluginDriver, this.getRenderedChunkInfo());
  16221. finalisers[format](renderedSource, {
  16222. accessedGlobals,
  16223. dependencies: renderedDependencies,
  16224. exports: renderedExports,
  16225. hasDefaultExport,
  16226. hasExports,
  16227. id: preliminaryFileName.fileName,
  16228. indent,
  16229. intro,
  16230. isEntryFacade: preserveModules || (facadeModule !== null && facadeModule.info.isEntry),
  16231. isModuleFacade: facadeModule !== null,
  16232. log: onLog,
  16233. namedExportsMode: exportMode !== 'default',
  16234. outro,
  16235. snippets,
  16236. usesTopLevelAwait
  16237. }, outputOptions);
  16238. if (banner)
  16239. magicString.prepend(banner);
  16240. if (format === 'es' || format === 'cjs') {
  16241. const shebang = facadeModule !== null && facadeModule.info.isEntry && facadeModule.shebang;
  16242. if (shebang) {
  16243. magicString.prepend(`#!${shebang}\n`);
  16244. }
  16245. }
  16246. if (footer)
  16247. magicString.append(footer);
  16248. return {
  16249. chunk: this,
  16250. magicString,
  16251. preliminaryFileName,
  16252. preliminarySourcemapFileName,
  16253. usedModules
  16254. };
  16255. }
  16256. addImplicitlyLoadedBeforeFromModule(baseModule) {
  16257. const { chunkByModule, implicitlyLoadedBefore } = this;
  16258. for (const module of baseModule.implicitlyLoadedBefore) {
  16259. const chunk = chunkByModule.get(module);
  16260. if (chunk && chunk !== this) {
  16261. implicitlyLoadedBefore.add(chunk);
  16262. }
  16263. }
  16264. }
  16265. addNecessaryImportsForFacades() {
  16266. for (const [module, variables] of this.includedReexportsByModule) {
  16267. if (this.includedNamespaces.has(module)) {
  16268. for (const variable of variables) {
  16269. this.imports.add(variable);
  16270. }
  16271. }
  16272. }
  16273. }
  16274. assignFacadeName({ fileName, name }, facadedModule, preservePath) {
  16275. if (fileName) {
  16276. this.fileName = fileName;
  16277. }
  16278. else {
  16279. this.name = this.outputOptions.sanitizeFileName(name ||
  16280. (preservePath
  16281. ? this.getPreserveModulesChunkNameFromModule(facadedModule)
  16282. : getChunkNameFromModule(facadedModule)));
  16283. }
  16284. }
  16285. checkCircularDependencyImport(variable, importingModule) {
  16286. const variableModule = variable.module;
  16287. if (variableModule instanceof Module) {
  16288. const exportChunk = this.chunkByModule.get(variableModule);
  16289. let alternativeReexportModule;
  16290. do {
  16291. alternativeReexportModule = importingModule.alternativeReexportModules.get(variable);
  16292. if (alternativeReexportModule) {
  16293. const exportingChunk = this.chunkByModule.get(alternativeReexportModule);
  16294. if (exportingChunk !== exportChunk) {
  16295. this.inputOptions.onLog(LOGLEVEL_WARN, logCyclicCrossChunkReexport(
  16296. // Namespaces do not have an export name
  16297. variableModule.getExportNamesByVariable().get(variable)?.[0] || '*', variableModule.id, alternativeReexportModule.id, importingModule.id, this.outputOptions.preserveModules));
  16298. }
  16299. importingModule = alternativeReexportModule;
  16300. }
  16301. } while (alternativeReexportModule);
  16302. }
  16303. }
  16304. ensureReexportsAreAvailableForModule(module) {
  16305. const includedReexports = [];
  16306. const map = module.getExportNamesByVariable();
  16307. for (const exportedVariable of map.keys()) {
  16308. const isSynthetic = exportedVariable instanceof SyntheticNamedExportVariable;
  16309. const importedVariable = isSynthetic ? exportedVariable.getBaseVariable() : exportedVariable;
  16310. this.checkCircularDependencyImport(importedVariable, module);
  16311. // When preserving modules, we do not create namespace objects but directly
  16312. // use the actual namespaces, which would be broken by this logic.
  16313. if (!(importedVariable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
  16314. const exportingModule = importedVariable.module;
  16315. if (exportingModule instanceof Module) {
  16316. const chunk = this.chunkByModule.get(exportingModule);
  16317. if (chunk && chunk !== this) {
  16318. chunk.exports.add(importedVariable);
  16319. includedReexports.push(importedVariable);
  16320. if (isSynthetic) {
  16321. this.imports.add(importedVariable);
  16322. }
  16323. }
  16324. }
  16325. }
  16326. }
  16327. if (includedReexports.length > 0) {
  16328. this.includedReexportsByModule.set(module, includedReexports);
  16329. }
  16330. }
  16331. generateVariableName() {
  16332. if (this.manualChunkAlias) {
  16333. return this.manualChunkAlias;
  16334. }
  16335. const moduleForNaming = this.entryModules[0] ||
  16336. this.implicitEntryModules[0] ||
  16337. this.dynamicEntryModules[0] ||
  16338. this.orderedModules[this.orderedModules.length - 1];
  16339. if (moduleForNaming) {
  16340. return getChunkNameFromModule(moduleForNaming);
  16341. }
  16342. return 'chunk';
  16343. }
  16344. getChunkExportDeclarations(format) {
  16345. const exports = [];
  16346. for (const exportName of this.getExportNames()) {
  16347. if (exportName[0] === '*')
  16348. continue;
  16349. const variable = this.exportsByName.get(exportName);
  16350. if (!(variable instanceof SyntheticNamedExportVariable)) {
  16351. const module = variable.module;
  16352. if (module) {
  16353. const chunk = this.chunkByModule.get(module);
  16354. if (chunk !== this) {
  16355. if (!chunk || format !== 'es') {
  16356. continue;
  16357. }
  16358. const chunkDep = this.renderedDependencies.get(chunk);
  16359. if (!chunkDep) {
  16360. continue;
  16361. }
  16362. const { imports, reexports } = chunkDep;
  16363. const importedByReexported = reexports?.find(({ reexported }) => reexported === exportName);
  16364. const isImported = imports?.find(({ imported }) => imported === importedByReexported?.imported);
  16365. if (!isImported) {
  16366. continue;
  16367. }
  16368. }
  16369. }
  16370. }
  16371. let expression = null;
  16372. let hoisted = false;
  16373. let local = variable.getName(this.snippets.getPropertyAccess);
  16374. if (variable instanceof LocalVariable) {
  16375. for (const declaration of variable.declarations) {
  16376. if (declaration.parent instanceof FunctionDeclaration ||
  16377. (declaration instanceof ExportDefaultDeclaration &&
  16378. declaration.declaration instanceof FunctionDeclaration)) {
  16379. hoisted = true;
  16380. break;
  16381. }
  16382. }
  16383. }
  16384. else if (variable instanceof SyntheticNamedExportVariable) {
  16385. expression = local;
  16386. if (format === 'es') {
  16387. local = variable.renderName;
  16388. }
  16389. }
  16390. exports.push({
  16391. exported: exportName,
  16392. expression,
  16393. hoisted,
  16394. local
  16395. });
  16396. }
  16397. return exports;
  16398. }
  16399. getDependenciesToBeDeconflicted(addNonNamespacesAndInteropHelpers, addDependenciesWithoutBindings, interop) {
  16400. const dependencies = new Set();
  16401. const deconflictedDefault = new Set();
  16402. const deconflictedNamespace = new Set();
  16403. for (const variable of [...this.exportNamesByVariable.keys(), ...this.imports]) {
  16404. if (addNonNamespacesAndInteropHelpers || variable.isNamespace) {
  16405. const module = variable.module;
  16406. if (module instanceof ExternalModule) {
  16407. const chunk = this.externalChunkByModule.get(module);
  16408. dependencies.add(chunk);
  16409. if (addNonNamespacesAndInteropHelpers) {
  16410. if (variable.name === 'default') {
  16411. if (defaultInteropHelpersByInteropType[interop(module.id)]) {
  16412. deconflictedDefault.add(chunk);
  16413. }
  16414. }
  16415. else if (variable.isNamespace &&
  16416. namespaceInteropHelpersByInteropType[interop(module.id)] &&
  16417. (this.imports.has(variable) ||
  16418. !this.exportNamesByVariable.get(variable)?.every(name => name.startsWith('*')))) {
  16419. // We only need to deconflict it if the namespace is actually
  16420. // created as a variable, i.e. because it is used internally or
  16421. // because it is reexported as an object
  16422. deconflictedNamespace.add(chunk);
  16423. }
  16424. }
  16425. }
  16426. else {
  16427. const chunk = this.chunkByModule.get(module);
  16428. if (chunk !== this) {
  16429. dependencies.add(chunk);
  16430. if (addNonNamespacesAndInteropHelpers &&
  16431. chunk.exportMode === 'default' &&
  16432. variable.isNamespace) {
  16433. deconflictedNamespace.add(chunk);
  16434. }
  16435. }
  16436. }
  16437. }
  16438. }
  16439. if (addDependenciesWithoutBindings) {
  16440. for (const dependency of this.dependencies) {
  16441. dependencies.add(dependency);
  16442. }
  16443. }
  16444. return { deconflictedDefault, deconflictedNamespace, dependencies };
  16445. }
  16446. getDynamicDependencies() {
  16447. return this.getIncludedDynamicImports()
  16448. .map(resolvedDynamicImport => resolvedDynamicImport.facadeChunk ||
  16449. resolvedDynamicImport.chunk ||
  16450. resolvedDynamicImport.externalChunk ||
  16451. resolvedDynamicImport.resolution)
  16452. .filter((resolution) => resolution !== this &&
  16453. (resolution instanceof Chunk || resolution instanceof ExternalChunk));
  16454. }
  16455. getDynamicImportStringAndAttributes(resolution, fileName) {
  16456. if (resolution instanceof ExternalModule) {
  16457. const chunk = this.externalChunkByModule.get(resolution);
  16458. return [`'${chunk.getImportPath(fileName)}'`, chunk.getImportAttributes(this.snippets)];
  16459. }
  16460. return [
  16461. resolution || '',
  16462. (this.outputOptions.format === 'es' && this.outputOptions.externalImportAttributes) || null
  16463. ];
  16464. }
  16465. getFallbackChunkName() {
  16466. if (this.manualChunkAlias) {
  16467. return this.manualChunkAlias;
  16468. }
  16469. if (this.dynamicName) {
  16470. return this.dynamicName;
  16471. }
  16472. if (this.fileName) {
  16473. return getAliasName(this.fileName);
  16474. }
  16475. return getAliasName(this.orderedModules[this.orderedModules.length - 1].id);
  16476. }
  16477. getImportSpecifiers() {
  16478. const { interop } = this.outputOptions;
  16479. const importsByDependency = new Map();
  16480. for (const variable of this.imports) {
  16481. const module = variable.module;
  16482. let dependency;
  16483. let imported;
  16484. if (module instanceof ExternalModule) {
  16485. dependency = this.externalChunkByModule.get(module);
  16486. imported = variable.name;
  16487. if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
  16488. return error(logUnexpectedNamedImport(module.id, imported, false));
  16489. }
  16490. }
  16491. else {
  16492. dependency = this.chunkByModule.get(module);
  16493. imported = dependency.getVariableExportName(variable);
  16494. }
  16495. getOrCreate(importsByDependency, dependency, getNewArray).push({
  16496. imported,
  16497. local: variable.getName(this.snippets.getPropertyAccess)
  16498. });
  16499. }
  16500. return importsByDependency;
  16501. }
  16502. getIncludedDynamicImports() {
  16503. if (this.includedDynamicImports) {
  16504. return this.includedDynamicImports;
  16505. }
  16506. const includedDynamicImports = [];
  16507. for (const module of this.orderedModules) {
  16508. for (const { node, resolution } of module.dynamicImports) {
  16509. if (!node.included) {
  16510. continue;
  16511. }
  16512. includedDynamicImports.push(resolution instanceof Module
  16513. ? {
  16514. chunk: this.chunkByModule.get(resolution),
  16515. externalChunk: null,
  16516. facadeChunk: this.facadeChunkByModule.get(resolution),
  16517. node,
  16518. resolution
  16519. }
  16520. : resolution instanceof ExternalModule
  16521. ? {
  16522. chunk: null,
  16523. externalChunk: this.externalChunkByModule.get(resolution),
  16524. facadeChunk: null,
  16525. node,
  16526. resolution
  16527. }
  16528. : { chunk: null, externalChunk: null, facadeChunk: null, node, resolution });
  16529. }
  16530. }
  16531. return (this.includedDynamicImports = includedDynamicImports);
  16532. }
  16533. getPreRenderedChunkInfo() {
  16534. if (this.preRenderedChunkInfo) {
  16535. return this.preRenderedChunkInfo;
  16536. }
  16537. const { dynamicEntryModules, facadeModule, implicitEntryModules, orderedModules } = this;
  16538. return (this.preRenderedChunkInfo = {
  16539. exports: this.getExportNames(),
  16540. facadeModuleId: facadeModule && facadeModule.id,
  16541. isDynamicEntry: dynamicEntryModules.length > 0,
  16542. isEntry: !!facadeModule?.info.isEntry,
  16543. isImplicitEntry: implicitEntryModules.length > 0,
  16544. moduleIds: orderedModules.map(({ id }) => id),
  16545. name: this.getChunkName(),
  16546. type: 'chunk'
  16547. });
  16548. }
  16549. getPreserveModulesChunkNameFromModule(module) {
  16550. const predefinedChunkName = getPredefinedChunkNameFromModule(module);
  16551. if (predefinedChunkName)
  16552. return predefinedChunkName;
  16553. const { preserveModulesRoot, sanitizeFileName } = this.outputOptions;
  16554. const sanitizedId = sanitizeFileName(normalize(module.id.split(QUERY_HASH_REGEX, 1)[0]));
  16555. const extensionName = extname(sanitizedId);
  16556. const idWithoutExtension = NON_ASSET_EXTENSIONS.has(extensionName)
  16557. ? sanitizedId.slice(0, -extensionName.length)
  16558. : sanitizedId;
  16559. if (isAbsolute$1(idWithoutExtension)) {
  16560. if (preserveModulesRoot && resolve$1(idWithoutExtension).startsWith(preserveModulesRoot)) {
  16561. return idWithoutExtension.slice(preserveModulesRoot.length).replace(/^[/\\]/, '');
  16562. }
  16563. else {
  16564. // handle edge case in Windows
  16565. if (this.inputBase === '/' && !idWithoutExtension.startsWith('/')) {
  16566. return relative$1(this.inputBase, idWithoutExtension.replace(/^[a-zA-Z]:[/\\]/, '/'));
  16567. }
  16568. return relative$1(this.inputBase, idWithoutExtension);
  16569. }
  16570. }
  16571. else {
  16572. return (this.outputOptions.virtualDirname.replace(/\/$/, '') + '/' + basename(idWithoutExtension));
  16573. }
  16574. }
  16575. getReexportSpecifiers() {
  16576. const { externalLiveBindings, interop } = this.outputOptions;
  16577. const reexportSpecifiers = new Map();
  16578. for (let exportName of this.getExportNames()) {
  16579. let dependency;
  16580. let imported;
  16581. let needsLiveBinding = false;
  16582. if (exportName[0] === '*') {
  16583. const id = exportName.slice(1);
  16584. if (interop(id) === 'defaultOnly') {
  16585. this.inputOptions.onLog(LOGLEVEL_WARN, logUnexpectedNamespaceReexport(id));
  16586. }
  16587. needsLiveBinding = externalLiveBindings;
  16588. dependency = this.externalChunkByModule.get(this.modulesById.get(id));
  16589. imported = exportName = '*';
  16590. }
  16591. else {
  16592. const variable = this.exportsByName.get(exportName);
  16593. if (variable instanceof SyntheticNamedExportVariable)
  16594. continue;
  16595. const module = variable.module;
  16596. if (module instanceof Module) {
  16597. dependency = this.chunkByModule.get(module);
  16598. if (dependency === this)
  16599. continue;
  16600. imported = dependency.getVariableExportName(variable);
  16601. needsLiveBinding = variable.isReassigned;
  16602. }
  16603. else {
  16604. dependency = this.externalChunkByModule.get(module);
  16605. imported = variable.name;
  16606. if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
  16607. return error(logUnexpectedNamedImport(module.id, imported, true));
  16608. }
  16609. needsLiveBinding =
  16610. externalLiveBindings &&
  16611. (imported !== 'default' || isDefaultAProperty(interop(module.id), true));
  16612. }
  16613. }
  16614. getOrCreate(reexportSpecifiers, dependency, getNewArray).push({
  16615. imported,
  16616. needsLiveBinding,
  16617. reexported: exportName
  16618. });
  16619. }
  16620. return reexportSpecifiers;
  16621. }
  16622. getReferencedFiles() {
  16623. const referencedFiles = new Set();
  16624. for (const module of this.orderedModules) {
  16625. for (const meta of module.importMetas) {
  16626. const fileName = meta.getReferencedFileName(this.pluginDriver);
  16627. if (fileName) {
  16628. referencedFiles.add(fileName);
  16629. }
  16630. }
  16631. }
  16632. return [...referencedFiles];
  16633. }
  16634. getRenderedDependencies() {
  16635. if (this.renderedDependencies) {
  16636. return this.renderedDependencies;
  16637. }
  16638. const importSpecifiers = this.getImportSpecifiers();
  16639. const reexportSpecifiers = this.getReexportSpecifiers();
  16640. const renderedDependencies = new Map();
  16641. const fileName = this.getFileName();
  16642. for (const dependency of this.dependencies) {
  16643. const imports = importSpecifiers.get(dependency) || null;
  16644. const reexports = reexportSpecifiers.get(dependency) || null;
  16645. const namedExportsMode = dependency instanceof ExternalChunk || dependency.exportMode !== 'default';
  16646. const importPath = dependency.getImportPath(fileName);
  16647. renderedDependencies.set(dependency, {
  16648. attributes: dependency instanceof ExternalChunk
  16649. ? dependency.getImportAttributes(this.snippets)
  16650. : null,
  16651. defaultVariableName: dependency.defaultVariableName,
  16652. globalName: dependency instanceof ExternalChunk &&
  16653. (this.outputOptions.format === 'umd' || this.outputOptions.format === 'iife') &&
  16654. getGlobalName(dependency, this.outputOptions.globals, (imports || reexports) !== null, this.inputOptions.onLog),
  16655. importPath,
  16656. imports,
  16657. isChunk: dependency instanceof Chunk,
  16658. name: dependency.variableName,
  16659. namedExportsMode,
  16660. namespaceVariableName: dependency.namespaceVariableName,
  16661. reexports
  16662. });
  16663. }
  16664. return (this.renderedDependencies = renderedDependencies);
  16665. }
  16666. inlineChunkDependencies(chunk) {
  16667. for (const dep of chunk.dependencies) {
  16668. if (this.dependencies.has(dep))
  16669. continue;
  16670. this.dependencies.add(dep);
  16671. if (dep instanceof Chunk) {
  16672. this.inlineChunkDependencies(dep);
  16673. }
  16674. }
  16675. }
  16676. // This method changes properties on the AST before rendering and must not be async
  16677. renderModules(fileName) {
  16678. const { accessedGlobalsByScope, dependencies, exportNamesByVariable, includedNamespaces, inputOptions: { onLog }, isEmpty, orderedModules, outputOptions, pluginDriver, renderedModules, snippets } = this;
  16679. const { compact, format, freeze, generatedCode: { symbols } } = outputOptions;
  16680. const { _, cnst, n } = snippets;
  16681. this.setDynamicImportResolutions(fileName);
  16682. this.setImportMetaResolutions(fileName);
  16683. this.setIdentifierRenderResolutions();
  16684. const magicString = new Bundle$1({ separator: `${n}${n}` });
  16685. const indent = getIndentString(orderedModules, outputOptions);
  16686. const usedModules = [];
  16687. let hoistedSource = '';
  16688. const accessedGlobals = new Set();
  16689. const renderedModuleSources = new Map();
  16690. const renderOptions = {
  16691. accessedDocumentCurrentScript: false,
  16692. exportNamesByVariable,
  16693. format,
  16694. freeze,
  16695. indent,
  16696. pluginDriver,
  16697. snippets,
  16698. symbols,
  16699. useOriginalName: null
  16700. };
  16701. let usesTopLevelAwait = false;
  16702. for (const module of orderedModules) {
  16703. let renderedLength = 0;
  16704. let source;
  16705. if (module.isIncluded() || includedNamespaces.has(module)) {
  16706. const rendered = module.render(renderOptions);
  16707. if (!renderOptions.accessedDocumentCurrentScript &&
  16708. formatsMaybeAccessDocumentCurrentScript.includes(format)) {
  16709. this.accessedGlobalsByScope.get(module.scope)?.delete(DOCUMENT_CURRENT_SCRIPT);
  16710. }
  16711. renderOptions.accessedDocumentCurrentScript = false;
  16712. ({ source } = rendered);
  16713. usesTopLevelAwait ||= rendered.usesTopLevelAwait;
  16714. renderedLength = source.length();
  16715. if (renderedLength) {
  16716. if (compact && source.lastLine().includes('//'))
  16717. source.append('\n');
  16718. renderedModuleSources.set(module, source);
  16719. magicString.addSource(source);
  16720. usedModules.push(module);
  16721. }
  16722. const namespace = module.namespace;
  16723. if (includedNamespaces.has(module)) {
  16724. const rendered = namespace.renderBlock(renderOptions);
  16725. if (namespace.renderFirst())
  16726. hoistedSource += n + rendered;
  16727. else
  16728. magicString.addSource(new MagicString(rendered));
  16729. }
  16730. const accessedGlobalVariables = accessedGlobalsByScope.get(module.scope);
  16731. if (accessedGlobalVariables) {
  16732. for (const name of accessedGlobalVariables) {
  16733. accessedGlobals.add(name);
  16734. }
  16735. }
  16736. }
  16737. const { renderedExports, removedExports } = module.getRenderedExports();
  16738. renderedModules[module.id] = {
  16739. get code() {
  16740. return source?.toString() ?? null;
  16741. },
  16742. originalLength: module.originalCode.length,
  16743. removedExports,
  16744. renderedExports,
  16745. renderedLength
  16746. };
  16747. }
  16748. if (hoistedSource)
  16749. magicString.prepend(hoistedSource + n + n);
  16750. if (this.needsExportsShim) {
  16751. magicString.prepend(`${n}${cnst} ${MISSING_EXPORT_SHIM_VARIABLE}${_}=${_}void 0;${n}${n}`);
  16752. }
  16753. const renderedSource = compact ? magicString : magicString.trim();
  16754. if (isEmpty && this.getExportNames().length === 0 && dependencies.size === 0) {
  16755. onLog(LOGLEVEL_WARN, logEmptyChunk(this.getChunkName()));
  16756. }
  16757. return { accessedGlobals, indent, magicString, renderedSource, usedModules, usesTopLevelAwait };
  16758. }
  16759. setDynamicImportResolutions(fileName) {
  16760. const { accessedGlobalsByScope, outputOptions, pluginDriver, snippets } = this;
  16761. for (const resolvedDynamicImport of this.getIncludedDynamicImports()) {
  16762. if (resolvedDynamicImport.chunk) {
  16763. const { chunk, facadeChunk, node, resolution } = resolvedDynamicImport;
  16764. if (chunk === this) {
  16765. node.setInternalResolution(resolution.namespace);
  16766. }
  16767. else {
  16768. node.setExternalResolution((facadeChunk || chunk).exportMode, resolution, outputOptions, snippets, pluginDriver, accessedGlobalsByScope, `'${(facadeChunk || chunk).getImportPath(fileName)}'`, !facadeChunk?.strictFacade && chunk.exportNamesByVariable.get(resolution.namespace)[0], null);
  16769. }
  16770. }
  16771. else {
  16772. const { node, resolution } = resolvedDynamicImport;
  16773. const [resolutionString, attributes] = this.getDynamicImportStringAndAttributes(resolution, fileName);
  16774. node.setExternalResolution('external', resolution, outputOptions, snippets, pluginDriver, accessedGlobalsByScope, resolutionString, false, attributes);
  16775. }
  16776. }
  16777. }
  16778. setIdentifierRenderResolutions() {
  16779. const { format, generatedCode: { symbols }, interop, preserveModules, externalLiveBindings } = this.outputOptions;
  16780. const syntheticExports = new Set();
  16781. for (const exportName of this.getExportNames()) {
  16782. const exportVariable = this.exportsByName.get(exportName);
  16783. if (format !== 'es' &&
  16784. format !== 'system' &&
  16785. exportVariable.isReassigned &&
  16786. !exportVariable.isId) {
  16787. exportVariable.setRenderNames('exports', exportName);
  16788. }
  16789. else if (exportVariable instanceof SyntheticNamedExportVariable) {
  16790. syntheticExports.add(exportVariable);
  16791. }
  16792. else {
  16793. exportVariable.setRenderNames(null, null);
  16794. }
  16795. }
  16796. for (const module of this.orderedModules) {
  16797. if (module.needsExportShim) {
  16798. this.needsExportsShim = true;
  16799. break;
  16800. }
  16801. }
  16802. const usedNames = new Set(['Object', 'Promise']);
  16803. if (this.needsExportsShim) {
  16804. usedNames.add(MISSING_EXPORT_SHIM_VARIABLE);
  16805. }
  16806. if (symbols) {
  16807. usedNames.add('Symbol');
  16808. }
  16809. switch (format) {
  16810. case 'system': {
  16811. usedNames.add('module').add('exports');
  16812. break;
  16813. }
  16814. case 'es': {
  16815. break;
  16816. }
  16817. case 'cjs': {
  16818. usedNames.add('module').add('require').add('__filename').add('__dirname');
  16819. }
  16820. // fallthrough
  16821. default: {
  16822. usedNames.add('exports');
  16823. for (const helper of HELPER_NAMES) {
  16824. usedNames.add(helper);
  16825. }
  16826. }
  16827. }
  16828. 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);
  16829. }
  16830. setImportMetaResolutions(fileName) {
  16831. const { accessedGlobalsByScope, includedNamespaces, orderedModules, outputOptions: { format } } = this;
  16832. for (const module of orderedModules) {
  16833. for (const importMeta of module.importMetas) {
  16834. importMeta.setResolution(format, accessedGlobalsByScope, fileName);
  16835. }
  16836. if (includedNamespaces.has(module)) {
  16837. module.namespace.prepare(accessedGlobalsByScope);
  16838. }
  16839. }
  16840. }
  16841. setUpChunkImportsAndExportsForModule(module) {
  16842. const moduleImports = new Set(module.includedImports);
  16843. // when we are not preserving modules, we need to make all namespace variables available for
  16844. // rendering the namespace object
  16845. if (!this.outputOptions.preserveModules && this.includedNamespaces.has(module)) {
  16846. const memberVariables = module.namespace.getMemberVariables();
  16847. for (const variable of Object.values(memberVariables)) {
  16848. if (variable.included) {
  16849. moduleImports.add(variable);
  16850. }
  16851. }
  16852. }
  16853. for (let variable of moduleImports) {
  16854. if (variable instanceof ExportDefaultVariable) {
  16855. variable = variable.getOriginalVariable();
  16856. }
  16857. if (variable instanceof SyntheticNamedExportVariable) {
  16858. variable = variable.getBaseVariable();
  16859. }
  16860. const chunk = this.chunkByModule.get(variable.module);
  16861. if (chunk !== this) {
  16862. this.imports.add(variable);
  16863. if (variable.module instanceof Module) {
  16864. this.checkCircularDependencyImport(variable, module);
  16865. // When preserving modules, we do not create namespace objects but directly
  16866. // use the actual namespaces, which would be broken by this logic.
  16867. if (!(variable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
  16868. chunk.exports.add(variable);
  16869. }
  16870. }
  16871. }
  16872. }
  16873. if (this.includedNamespaces.has(module) ||
  16874. (module.info.isEntry && module.preserveSignature !== false) ||
  16875. module.includedDynamicImporters.some(importer => this.chunkByModule.get(importer) !== this)) {
  16876. this.ensureReexportsAreAvailableForModule(module);
  16877. }
  16878. for (const { node, resolution } of module.dynamicImports) {
  16879. if (node.included &&
  16880. resolution instanceof Module &&
  16881. this.chunkByModule.get(resolution) === this &&
  16882. !this.includedNamespaces.has(resolution)) {
  16883. this.includedNamespaces.add(resolution);
  16884. this.ensureReexportsAreAvailableForModule(resolution);
  16885. }
  16886. }
  16887. }
  16888. }
  16889. function getChunkNameFromModule(module) {
  16890. return getPredefinedChunkNameFromModule(module) ?? getAliasName(module.id);
  16891. }
  16892. function getPredefinedChunkNameFromModule(module) {
  16893. return (module.chunkNames.find(({ isUserDefined }) => isUserDefined)?.name ?? module.chunkNames[0]?.name);
  16894. }
  16895. function getImportedBindingsPerDependency(renderedDependencies, resolveFileName) {
  16896. const importedBindingsPerDependency = {};
  16897. for (const [dependency, declaration] of renderedDependencies) {
  16898. const specifiers = new Set();
  16899. if (declaration.imports) {
  16900. for (const { imported } of declaration.imports) {
  16901. specifiers.add(imported);
  16902. }
  16903. }
  16904. if (declaration.reexports) {
  16905. for (const { imported } of declaration.reexports) {
  16906. specifiers.add(imported);
  16907. }
  16908. }
  16909. importedBindingsPerDependency[resolveFileName(dependency)] = [...specifiers];
  16910. }
  16911. return importedBindingsPerDependency;
  16912. }
  16913. const QUERY_HASH_REGEX = /[#?]/;
  16914. const resolveFileName = (dependency) => dependency.getFileName();
  16915. /**
  16916. * Concatenate a number of iterables to a new iterable without fully evaluating
  16917. * their iterators. Useful when e.g. working with large sets or lists and when
  16918. * there is a chance that the iterators will not be fully exhausted.
  16919. */
  16920. function* concatLazy(iterables) {
  16921. for (const iterable of iterables) {
  16922. yield* iterable;
  16923. }
  16924. }
  16925. /**
  16926. * At its core, the algorithm first starts from each static or dynamic entry
  16927. * point and then assigns that entry point to all modules than can be reached
  16928. * via static imports. We call this the *dependent entry points* of that
  16929. * module.
  16930. *
  16931. * Then we group all modules with the same dependent entry points into chunks
  16932. * as those modules will always be loaded together.
  16933. *
  16934. * One non-trivial optimization we can apply is that dynamic entries are
  16935. * different from static entries in so far as when a dynamic import occurs,
  16936. * some modules are already in memory. If some of these modules are also
  16937. * dependencies of the dynamic entry, then it does not make sense to create a
  16938. * separate chunk for them. Instead, the dynamic import target can load them
  16939. * from the importing chunk.
  16940. *
  16941. * With regard to chunking, if B is implicitly loaded after A, then this can be
  16942. * handled the same way as if there was a dynamic import A => B.
  16943. *
  16944. * Example:
  16945. * Assume A -> B (A imports B), A => C (A dynamically imports C) and C -> B.
  16946. * Then the initial algorithm would assign A into the A chunk, C into the C
  16947. * chunk and B into the AC chunk, i.e. the chunk with the dependent entry
  16948. * points A and C.
  16949. * However we know that C can only be loaded from A, so A and its dependency B
  16950. * must already be in memory when C is loaded. So it is enough to create only
  16951. * two chunks A containing [AB] and C containing [C].
  16952. *
  16953. * So we do not assign the dynamic entry C as dependent entry point to modules
  16954. * that are already loaded.
  16955. *
  16956. * In a more complex example, let us assume that we have entry points X and Y.
  16957. * Further, let us assume
  16958. * X -> A, X -> B, X -> C,
  16959. * Y -> A, Y -> B,
  16960. * A => D,
  16961. * D -> B, D -> C
  16962. * So without dynamic import optimization, the dependent entry points are
  16963. * A: XY, B: DXY, C: DX, D: D, X: X, Y: Y, so we would for now create six
  16964. * chunks.
  16965. *
  16966. * Now D is loaded only after A is loaded. But A is loaded if either X is
  16967. * loaded or Y is loaded. So the modules that are already in memory when D is
  16968. * loaded are the intersection of all modules that X depends on with all
  16969. * modules that Y depends on, which in this case are the modules A and B.
  16970. * We could also say they are all modules that have both X and Y as dependent
  16971. * entry points.
  16972. *
  16973. * So we can remove D as dependent entry point from A and B, which means they
  16974. * both now have only XY as dependent entry points and can be merged into the
  16975. * same chunk.
  16976. *
  16977. * Now let us extend this to the most general case where we have several
  16978. * dynamic importers for one dynamic entry point.
  16979. *
  16980. * In the most general form, it works like this:
  16981. * For each dynamic entry point, we have a number of dynamic importers, which
  16982. * are the modules importing it. Using the previous ideas, we can determine
  16983. * the modules already in memory for each dynamic importer by looking for all
  16984. * modules that have all the dependent entry points of the dynamic importer as
  16985. * dependent entry points.
  16986. * So the modules that are guaranteed to be in memory when the dynamic entry
  16987. * point is loaded are the intersection of the modules already in memory for
  16988. * each dynamic importer.
  16989. *
  16990. * Assuming that A => D and B => D and A has dependent entry points XY and B
  16991. * has dependent entry points YZ, then the modules guaranteed to be in memory
  16992. * are all modules that have at least XYZ as dependent entry points.
  16993. * We call XYZ the *dynamically dependent entry points* of D.
  16994. *
  16995. * Now there is one last case to consider: If one of the dynamically dependent
  16996. * entries is itself a dynamic entry, then any module is in memory that either
  16997. * is a dependency of that dynamic entry or again has the dynamic dependent
  16998. * entries of that dynamic entry as dependent entry points.
  16999. *
  17000. * A naive algorithm for this proved to be costly as it contained an O(n^3)
  17001. * complexity with regard to dynamic entries that blew up for very large
  17002. * projects.
  17003. *
  17004. * If we have an efficient way to do Set operations, an alternative approach
  17005. * would be to instead collect already loaded modules per dynamic entry. And as
  17006. * all chunks from the initial grouping would behave the same, we can instead
  17007. * collect already loaded chunks for a performance improvement.
  17008. *
  17009. * To do that efficiently, need
  17010. * - a Map of dynamic imports per dynamic entry, which contains all dynamic
  17011. * imports that can be triggered by a dynamic entry
  17012. * - a Map of static dependencies per entry
  17013. * - a Map of already loaded chunks per entry that we initially populate with
  17014. * empty Sets for static entries and Sets containing all entries for dynamic
  17015. * entries
  17016. *
  17017. * For efficient operations, we assign each entry a numerical index and
  17018. * represent Sets of Chunks as BigInt values where each chunk corresponds to a
  17019. * bit index. Then the last two maps can be represented as arrays of BigInt
  17020. * values.
  17021. *
  17022. * Then we iterate through each dynamic entry. We set the already loaded modules
  17023. * to the intersection of the previously already loaded modules with the union
  17024. * of the already loaded modules of that chunk with its static dependencies.
  17025. *
  17026. * If the already loaded modules changed, then we use the Map of dynamic imports
  17027. * per dynamic entry to marks all dynamic entry dependencies as "dirty" and put
  17028. * them back into the iteration. As an additional optimization, we note for
  17029. * each dynamic entry which dynamic dependent entries have changed and only
  17030. * intersect those entries again on subsequent interations.
  17031. *
  17032. * Then we remove the dynamic entries from the list of dependent entries for
  17033. * those chunks that are already loaded for that dynamic entry and create
  17034. * another round of chunks.
  17035. */
  17036. function getChunkAssignments(entries, manualChunkAliasByEntry, minChunkSize, log) {
  17037. const { chunkDefinitions, modulesInManualChunks } = getChunkDefinitionsFromManualChunks(manualChunkAliasByEntry);
  17038. const { allEntries, dependentEntriesByModule, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry } = analyzeModuleGraph(entries);
  17039. // Each chunk is identified by its position in this array
  17040. const chunkAtoms = getChunksWithSameDependentEntries(getModulesWithDependentEntries(dependentEntriesByModule, modulesInManualChunks));
  17041. const staticDependencyAtomsByEntry = getStaticDependencyAtomsByEntry(allEntries, chunkAtoms);
  17042. // Warning: This will consume dynamicallyDependentEntriesByDynamicEntry.
  17043. // If we no longer want this, we should make a copy here.
  17044. const alreadyLoadedAtomsByEntry = getAlreadyLoadedAtomsByEntry(staticDependencyAtomsByEntry, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry, allEntries);
  17045. // This mutates the dependentEntries in chunkAtoms
  17046. removeUnnecessaryDependentEntries(chunkAtoms, alreadyLoadedAtomsByEntry);
  17047. const { chunks, sideEffectAtoms, sizeByAtom } = getChunksWithSameDependentEntriesAndCorrelatedAtoms(chunkAtoms, staticDependencyAtomsByEntry, alreadyLoadedAtomsByEntry, minChunkSize);
  17048. chunkDefinitions.push(...getOptimizedChunks(chunks, minChunkSize, sideEffectAtoms, sizeByAtom, log).map(({ modules }) => ({
  17049. alias: null,
  17050. modules
  17051. })));
  17052. return chunkDefinitions;
  17053. }
  17054. function getChunkDefinitionsFromManualChunks(manualChunkAliasByEntry) {
  17055. const chunkDefinitions = [];
  17056. const modulesInManualChunks = new Set(manualChunkAliasByEntry.keys());
  17057. const manualChunkModulesByAlias = Object.create(null);
  17058. for (const [entry, alias] of manualChunkAliasByEntry) {
  17059. addStaticDependenciesToManualChunk(entry, (manualChunkModulesByAlias[alias] ||= []), modulesInManualChunks);
  17060. }
  17061. for (const [alias, modules] of Object.entries(manualChunkModulesByAlias)) {
  17062. chunkDefinitions.push({ alias, modules });
  17063. }
  17064. return { chunkDefinitions, modulesInManualChunks };
  17065. }
  17066. function addStaticDependenciesToManualChunk(entry, manualChunkModules, modulesInManualChunks) {
  17067. const modulesToHandle = new Set([entry]);
  17068. for (const module of modulesToHandle) {
  17069. modulesInManualChunks.add(module);
  17070. manualChunkModules.push(module);
  17071. for (const dependency of module.dependencies) {
  17072. if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
  17073. modulesToHandle.add(dependency);
  17074. }
  17075. }
  17076. }
  17077. }
  17078. function analyzeModuleGraph(entries) {
  17079. const dynamicEntryModules = new Set();
  17080. const dependentEntriesByModule = new Map();
  17081. const dynamicImportModulesByEntry = [];
  17082. const allEntriesSet = new Set(entries);
  17083. let entryIndex = 0;
  17084. for (const currentEntry of allEntriesSet) {
  17085. const dynamicImportsForCurrentEntry = new Set();
  17086. dynamicImportModulesByEntry.push(dynamicImportsForCurrentEntry);
  17087. const modulesToHandle = new Set([currentEntry]);
  17088. for (const module of modulesToHandle) {
  17089. getOrCreate(dependentEntriesByModule, module, (getNewSet)).add(entryIndex);
  17090. for (const dependency of module.getDependenciesToBeIncluded()) {
  17091. if (!(dependency instanceof ExternalModule)) {
  17092. modulesToHandle.add(dependency);
  17093. }
  17094. }
  17095. for (const { resolution } of module.dynamicImports) {
  17096. if (resolution instanceof Module &&
  17097. resolution.includedDynamicImporters.length > 0 &&
  17098. !allEntriesSet.has(resolution)) {
  17099. dynamicEntryModules.add(resolution);
  17100. allEntriesSet.add(resolution);
  17101. dynamicImportsForCurrentEntry.add(resolution);
  17102. }
  17103. }
  17104. for (const dependency of module.implicitlyLoadedBefore) {
  17105. if (!allEntriesSet.has(dependency)) {
  17106. dynamicEntryModules.add(dependency);
  17107. allEntriesSet.add(dependency);
  17108. }
  17109. }
  17110. }
  17111. entryIndex++;
  17112. }
  17113. const allEntries = [...allEntriesSet];
  17114. const { dynamicEntries, dynamicImportsByEntry } = getDynamicEntries(allEntries, dynamicEntryModules, dynamicImportModulesByEntry);
  17115. return {
  17116. allEntries,
  17117. dependentEntriesByModule,
  17118. dynamicallyDependentEntriesByDynamicEntry: getDynamicallyDependentEntriesByDynamicEntry(dependentEntriesByModule, dynamicEntries, allEntries),
  17119. dynamicImportsByEntry
  17120. };
  17121. }
  17122. function getDynamicEntries(allEntries, dynamicEntryModules, dynamicImportModulesByEntry) {
  17123. const entryIndexByModule = new Map();
  17124. const dynamicEntries = new Set();
  17125. for (const [entryIndex, entry] of allEntries.entries()) {
  17126. entryIndexByModule.set(entry, entryIndex);
  17127. if (dynamicEntryModules.has(entry)) {
  17128. dynamicEntries.add(entryIndex);
  17129. }
  17130. }
  17131. const dynamicImportsByEntry = [];
  17132. for (const dynamicImportModules of dynamicImportModulesByEntry) {
  17133. const dynamicImports = new Set();
  17134. for (const dynamicEntry of dynamicImportModules) {
  17135. dynamicImports.add(entryIndexByModule.get(dynamicEntry));
  17136. }
  17137. dynamicImportsByEntry.push(dynamicImports);
  17138. }
  17139. return { dynamicEntries, dynamicImportsByEntry };
  17140. }
  17141. function getDynamicallyDependentEntriesByDynamicEntry(dependentEntriesByModule, dynamicEntries, allEntries) {
  17142. const dynamicallyDependentEntriesByDynamicEntry = new Map();
  17143. for (const dynamicEntryIndex of dynamicEntries) {
  17144. const dynamicallyDependentEntries = getOrCreate(dynamicallyDependentEntriesByDynamicEntry, dynamicEntryIndex, (getNewSet));
  17145. const dynamicEntry = allEntries[dynamicEntryIndex];
  17146. for (const importer of concatLazy([
  17147. dynamicEntry.includedDynamicImporters,
  17148. dynamicEntry.implicitlyLoadedAfter
  17149. ])) {
  17150. for (const entry of dependentEntriesByModule.get(importer)) {
  17151. dynamicallyDependentEntries.add(entry);
  17152. }
  17153. }
  17154. }
  17155. return dynamicallyDependentEntriesByDynamicEntry;
  17156. }
  17157. function getChunksWithSameDependentEntries(modulesWithDependentEntries) {
  17158. const chunkModules = Object.create(null);
  17159. for (const { dependentEntries, modules } of modulesWithDependentEntries) {
  17160. let chunkSignature = 0n;
  17161. for (const entryIndex of dependentEntries) {
  17162. chunkSignature |= 1n << BigInt(entryIndex);
  17163. }
  17164. (chunkModules[String(chunkSignature)] ||= {
  17165. dependentEntries: new Set(dependentEntries),
  17166. modules: []
  17167. }).modules.push(...modules);
  17168. }
  17169. return Object.values(chunkModules);
  17170. }
  17171. function* getModulesWithDependentEntries(dependentEntriesByModule, modulesInManualChunks) {
  17172. for (const [module, dependentEntries] of dependentEntriesByModule) {
  17173. if (!modulesInManualChunks.has(module)) {
  17174. yield { dependentEntries, modules: [module] };
  17175. }
  17176. }
  17177. }
  17178. function getStaticDependencyAtomsByEntry(allEntries, chunkAtoms) {
  17179. // The indices correspond to the indices in allEntries. The atoms correspond
  17180. // to bits in the bigint values where chunk 0 is the lowest bit.
  17181. const staticDependencyAtomsByEntry = allEntries.map(() => 0n);
  17182. // This toggles the bits for each atom that is a dependency of an entry
  17183. let atomMask = 1n;
  17184. for (const { dependentEntries } of chunkAtoms) {
  17185. for (const entryIndex of dependentEntries) {
  17186. staticDependencyAtomsByEntry[entryIndex] |= atomMask;
  17187. }
  17188. atomMask <<= 1n;
  17189. }
  17190. return staticDependencyAtomsByEntry;
  17191. }
  17192. // Warning: This will consume dynamicallyDependentEntriesByDynamicEntry.
  17193. function getAlreadyLoadedAtomsByEntry(staticDependencyAtomsByEntry, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry, allEntries) {
  17194. // Dynamic entries have all atoms as already loaded initially because we then
  17195. // intersect with the static dependency atoms of all dynamic importers.
  17196. // Static entries cannot have already loaded atoms.
  17197. const alreadyLoadedAtomsByEntry = allEntries.map((_entry, entryIndex) => dynamicallyDependentEntriesByDynamicEntry.has(entryIndex) ? -1n : 0n);
  17198. for (const [dynamicEntryIndex, dynamicallyDependentEntries] of dynamicallyDependentEntriesByDynamicEntry) {
  17199. // We delete here so that they can be added again if necessary to be handled
  17200. // again by the loop
  17201. dynamicallyDependentEntriesByDynamicEntry.delete(dynamicEntryIndex);
  17202. const knownLoadedAtoms = alreadyLoadedAtomsByEntry[dynamicEntryIndex];
  17203. let updatedLoadedAtoms = knownLoadedAtoms;
  17204. for (const entryIndex of dynamicallyDependentEntries) {
  17205. updatedLoadedAtoms &=
  17206. staticDependencyAtomsByEntry[entryIndex] | alreadyLoadedAtomsByEntry[entryIndex];
  17207. }
  17208. // If the knownLoadedAtoms changed, all dependent dynamic entries need to be
  17209. // updated again
  17210. if (updatedLoadedAtoms !== knownLoadedAtoms) {
  17211. alreadyLoadedAtomsByEntry[dynamicEntryIndex] = updatedLoadedAtoms;
  17212. for (const dynamicImport of dynamicImportsByEntry[dynamicEntryIndex]) {
  17213. // If this adds an entry that was deleted before, it will be handled
  17214. // again. This is the reason why we delete every entry from this map
  17215. // that we processed.
  17216. getOrCreate(dynamicallyDependentEntriesByDynamicEntry, dynamicImport, (getNewSet)).add(dynamicEntryIndex);
  17217. }
  17218. }
  17219. }
  17220. return alreadyLoadedAtomsByEntry;
  17221. }
  17222. /**
  17223. * This removes all unnecessary dynamic entries from the dependentEntries in its
  17224. * first argument if a chunk is already loaded without that entry.
  17225. */
  17226. function removeUnnecessaryDependentEntries(chunkAtoms, alreadyLoadedAtomsByEntry) {
  17227. // Remove entries from dependent entries if a chunk is already loaded without
  17228. // that entry.
  17229. let chunkMask = 1n;
  17230. for (const { dependentEntries } of chunkAtoms) {
  17231. for (const entryIndex of dependentEntries) {
  17232. if ((alreadyLoadedAtomsByEntry[entryIndex] & chunkMask) === chunkMask) {
  17233. dependentEntries.delete(entryIndex);
  17234. }
  17235. }
  17236. chunkMask <<= 1n;
  17237. }
  17238. }
  17239. function getChunksWithSameDependentEntriesAndCorrelatedAtoms(chunkAtoms, staticDependencyAtomsByEntry, alreadyLoadedAtomsByEntry, minChunkSize) {
  17240. const chunksBySignature = Object.create(null);
  17241. const chunkByModule = new Map();
  17242. const sizeByAtom = [];
  17243. let sideEffectAtoms = 0n;
  17244. let atomMask = 1n;
  17245. for (const { dependentEntries, modules } of chunkAtoms) {
  17246. let chunkSignature = 0n;
  17247. let correlatedAtoms = -1n;
  17248. for (const entryIndex of dependentEntries) {
  17249. chunkSignature |= 1n << BigInt(entryIndex);
  17250. // Correlated atoms are the atoms that are guaranteed to be loaded as
  17251. // well when a given atom is loaded. It is the intersection of the already
  17252. // loaded modules of each chunk merged with its static dependencies.
  17253. correlatedAtoms &=
  17254. staticDependencyAtomsByEntry[entryIndex] | alreadyLoadedAtomsByEntry[entryIndex];
  17255. }
  17256. const chunk = (chunksBySignature[String(chunkSignature)] ||= {
  17257. containedAtoms: 0n,
  17258. correlatedAtoms,
  17259. dependencies: new Set(),
  17260. dependentChunks: new Set(),
  17261. dependentEntries: new Set(dependentEntries),
  17262. modules: [],
  17263. pure: true,
  17264. size: 0
  17265. });
  17266. let atomSize = 0;
  17267. let pure = true;
  17268. for (const module of modules) {
  17269. chunkByModule.set(module, chunk);
  17270. // Unfortunately, we cannot take tree-shaking into account here because
  17271. // rendering did not happen yet, but we can detect empty modules
  17272. if (module.isIncluded()) {
  17273. pure &&= !module.hasEffects();
  17274. // we use a trivial size for the default minChunkSize to improve
  17275. // performance
  17276. atomSize += minChunkSize > 1 ? module.estimateSize() : 1;
  17277. }
  17278. }
  17279. if (!pure) {
  17280. sideEffectAtoms |= atomMask;
  17281. }
  17282. sizeByAtom.push(atomSize);
  17283. chunk.containedAtoms |= atomMask;
  17284. chunk.modules.push(...modules);
  17285. chunk.pure &&= pure;
  17286. chunk.size += atomSize;
  17287. atomMask <<= 1n;
  17288. }
  17289. const chunks = Object.values(chunksBySignature);
  17290. sideEffectAtoms |= addChunkDependenciesAndGetExternalSideEffectAtoms(chunks, chunkByModule, atomMask);
  17291. return { chunks, sideEffectAtoms, sizeByAtom };
  17292. }
  17293. function addChunkDependenciesAndGetExternalSideEffectAtoms(chunks, chunkByModule, nextAvailableAtomMask) {
  17294. const signatureByExternalModule = new Map();
  17295. let externalSideEffectAtoms = 0n;
  17296. for (const chunk of chunks) {
  17297. const { dependencies, modules } = chunk;
  17298. for (const module of modules) {
  17299. for (const dependency of module.getDependenciesToBeIncluded()) {
  17300. if (dependency instanceof ExternalModule) {
  17301. if (dependency.info.moduleSideEffects) {
  17302. const signature = getOrCreate(signatureByExternalModule, dependency, () => {
  17303. const signature = nextAvailableAtomMask;
  17304. nextAvailableAtomMask <<= 1n;
  17305. externalSideEffectAtoms |= signature;
  17306. return signature;
  17307. });
  17308. chunk.containedAtoms |= signature;
  17309. chunk.correlatedAtoms |= signature;
  17310. }
  17311. }
  17312. else {
  17313. const dependencyChunk = chunkByModule.get(dependency);
  17314. if (dependencyChunk && dependencyChunk !== chunk) {
  17315. dependencies.add(dependencyChunk);
  17316. dependencyChunk.dependentChunks.add(chunk);
  17317. }
  17318. }
  17319. }
  17320. }
  17321. }
  17322. return externalSideEffectAtoms;
  17323. }
  17324. /**
  17325. * This function tries to get rid of small chunks by merging them with other
  17326. * chunks.
  17327. *
  17328. * We can only merge chunks safely if after the merge, loading any entry point
  17329. * in any allowed order will not trigger side effects that should not have been
  17330. * triggered. While side effects are usually things like global function calls,
  17331. * global variable mutations or potentially thrown errors, details do not
  17332. * matter here, and we just discern chunks without side effects (pure chunks)
  17333. * from other chunks.
  17334. *
  17335. * As a first step, we assign each pre-generated chunk with side effects a
  17336. * label. I.e. we have side effect "A" if the non-pure chunk "A" is loaded.
  17337. *
  17338. * Now to determine the side effects of loading a chunk, one also has to take
  17339. * the side effects of its dependencies into account. So if A depends on B
  17340. * (A -> B) and both have side effects, loading A triggers effects AB.
  17341. *
  17342. * Now from the previous step we know that each chunk is uniquely determine by
  17343. * the entry points that depend on it and cause it to load, which we will call
  17344. * its dependent entry points.
  17345. *
  17346. * E.g. if X -> A and Y -> A, then the dependent entry points of A are XY.
  17347. * Starting from that idea, we can determine a set of chunks—and thus a set
  17348. * of side effects—that must have been triggered if a certain chunk has been
  17349. * loaded. Basically, it is the intersection of all chunks loaded by the
  17350. * dependent entry points of a given chunk. We call the corresponding side
  17351. * effects the correlated side effects of that chunk.
  17352. *
  17353. * Example:
  17354. * X -> ABC, Y -> ADE, A-> F, B -> D
  17355. * Then taking dependencies into account, X -> ABCDF, Y -> ADEF
  17356. * The intersection is ADF. So we know that when A is loaded, D and F must also
  17357. * be in memory even though neither D nor A is a dependency of the other.
  17358. * If all have side effects, we call ADF the correlated side effects of A. The
  17359. * correlated side effects need to remain constant when merging chunks.
  17360. *
  17361. * In contrast, we have the dependency side effects of A, which represents
  17362. * the side effects we trigger if we directly load A. In this example, the
  17363. * dependency side effects are AF.
  17364. * For entry chunks, dependency and correlated side effects are the same.
  17365. *
  17366. * With these concepts, merging chunks is allowed if the correlated side
  17367. * effects of each entry do not change. Thus, we are allowed to merge two
  17368. * chunks if
  17369. *
  17370. * a) the dependency side effects of each chunk are a subset of the correlated
  17371. * side effects of the other chunk, so no additional side effects are
  17372. * triggered for any entry, or
  17373. * b) The dependent entry points of chunk A are a subset of the dependent entry
  17374. * points of chunk B while the dependency side effects of A are a subset of
  17375. * the correlated side effects of B. Because in that scenario, whenever A is
  17376. * loaded, B is loaded as well. But there are cases when B is loaded where A
  17377. * is not loaded. So if we merge the chunks, all dependency side effects of
  17378. * A will be added to the correlated side effects of B, and as the latter is
  17379. * not allowed to change, the former need to be a subset of the latter.
  17380. *
  17381. * Another consideration when merging small chunks into other chunks is to
  17382. * avoid
  17383. * that too much additional code is loaded. This is achieved when the dependent
  17384. * entries of the small chunk are a subset of the dependent entries of the
  17385. * other
  17386. * chunk. Because then when the small chunk is loaded, the other chunk was
  17387. * loaded/in memory anyway, so at most when the other chunk is loaded, the
  17388. * additional size of the small chunk is loaded unnecessarily.
  17389. *
  17390. * So the algorithm performs merges in two passes:
  17391. *
  17392. * 1. First we try to merge small chunks A only into other chunks B if the
  17393. * dependent entries of A are a subset of the dependent entries of B and the
  17394. * dependency side effects of A are a subset of the correlated side effects
  17395. * of B.
  17396. * 2. Only then for all remaining small chunks, we look for arbitrary merges
  17397. * following the rule (a), starting with the smallest chunks to look for
  17398. * possible merge targets.
  17399. */
  17400. function getOptimizedChunks(chunks, minChunkSize, sideEffectAtoms, sizeByAtom, log) {
  17401. timeStart('optimize chunks', 3);
  17402. const chunkPartition = getPartitionedChunks(chunks, minChunkSize);
  17403. if (!chunkPartition) {
  17404. timeEnd('optimize chunks', 3);
  17405. return chunks; // the actual modules
  17406. }
  17407. if (minChunkSize > 1) {
  17408. log('info', logOptimizeChunkStatus(chunks.length, chunkPartition.small.size, 'Initially'));
  17409. }
  17410. mergeChunks(chunkPartition, minChunkSize, sideEffectAtoms, sizeByAtom);
  17411. if (minChunkSize > 1) {
  17412. log('info', logOptimizeChunkStatus(chunkPartition.small.size + chunkPartition.big.size, chunkPartition.small.size, 'After merging chunks'));
  17413. }
  17414. timeEnd('optimize chunks', 3);
  17415. return [...chunkPartition.small, ...chunkPartition.big];
  17416. }
  17417. function getPartitionedChunks(chunks, minChunkSize) {
  17418. const smallChunks = [];
  17419. const bigChunks = [];
  17420. for (const chunk of chunks) {
  17421. (chunk.size < minChunkSize ? smallChunks : bigChunks).push(chunk);
  17422. }
  17423. if (smallChunks.length === 0) {
  17424. return null;
  17425. }
  17426. smallChunks.sort(compareChunkSize);
  17427. bigChunks.sort(compareChunkSize);
  17428. return {
  17429. big: new Set(bigChunks),
  17430. small: new Set(smallChunks)
  17431. };
  17432. }
  17433. function compareChunkSize({ size: sizeA }, { size: sizeB }) {
  17434. return sizeA - sizeB;
  17435. }
  17436. function mergeChunks(chunkPartition, minChunkSize, sideEffectAtoms, sizeByAtom) {
  17437. const { small } = chunkPartition;
  17438. for (const mergedChunk of small) {
  17439. const bestTargetChunk = findBestMergeTarget(mergedChunk, chunkPartition, sideEffectAtoms, sizeByAtom,
  17440. // In the default case, we do not accept size increases
  17441. minChunkSize <= 1 ? 1 : Infinity);
  17442. if (bestTargetChunk) {
  17443. const { containedAtoms, correlatedAtoms, modules, pure, size } = mergedChunk;
  17444. small.delete(mergedChunk);
  17445. getChunksInPartition(bestTargetChunk, minChunkSize, chunkPartition).delete(bestTargetChunk);
  17446. bestTargetChunk.modules.push(...modules);
  17447. bestTargetChunk.size += size;
  17448. bestTargetChunk.pure &&= pure;
  17449. const { dependencies, dependentChunks, dependentEntries } = bestTargetChunk;
  17450. bestTargetChunk.correlatedAtoms &= correlatedAtoms;
  17451. bestTargetChunk.containedAtoms |= containedAtoms;
  17452. for (const entry of mergedChunk.dependentEntries) {
  17453. dependentEntries.add(entry);
  17454. }
  17455. for (const dependency of mergedChunk.dependencies) {
  17456. dependencies.add(dependency);
  17457. dependency.dependentChunks.delete(mergedChunk);
  17458. dependency.dependentChunks.add(bestTargetChunk);
  17459. }
  17460. for (const dependentChunk of mergedChunk.dependentChunks) {
  17461. dependentChunks.add(dependentChunk);
  17462. dependentChunk.dependencies.delete(mergedChunk);
  17463. dependentChunk.dependencies.add(bestTargetChunk);
  17464. }
  17465. dependencies.delete(bestTargetChunk);
  17466. dependentChunks.delete(bestTargetChunk);
  17467. getChunksInPartition(bestTargetChunk, minChunkSize, chunkPartition).add(bestTargetChunk);
  17468. }
  17469. }
  17470. }
  17471. function findBestMergeTarget(mergedChunk, { big, small }, sideEffectAtoms, sizeByAtom, smallestAdditionalSize) {
  17472. let bestTargetChunk = null;
  17473. // In the default case, we do not accept size increases
  17474. for (const targetChunk of concatLazy([small, big])) {
  17475. if (mergedChunk === targetChunk)
  17476. continue;
  17477. const additionalSizeAfterMerge = getAdditionalSizeAfterMerge(mergedChunk, targetChunk, smallestAdditionalSize, sideEffectAtoms, sizeByAtom);
  17478. if (additionalSizeAfterMerge < smallestAdditionalSize) {
  17479. bestTargetChunk = targetChunk;
  17480. if (additionalSizeAfterMerge === 0)
  17481. break;
  17482. smallestAdditionalSize = additionalSizeAfterMerge;
  17483. }
  17484. }
  17485. return bestTargetChunk;
  17486. }
  17487. /**
  17488. * Determine the additional unused code size that would be added by merging the
  17489. * two chunks. This is not an exact measurement but rather an upper bound. If
  17490. * the merge produces cycles or adds non-correlated side effects, `Infinity`
  17491. * is returned.
  17492. * Merging will not produce cycles if none of the direct non-merged
  17493. * dependencies of a chunk have the other chunk as a transitive dependency.
  17494. */
  17495. function getAdditionalSizeAfterMerge(mergedChunk, targetChunk,
  17496. // The maximum additional unused code size allowed to be added by the merge,
  17497. // taking dependencies into account, needs to be below this number
  17498. currentAdditionalSize, sideEffectAtoms, sizeByAtom) {
  17499. const firstSize = getAdditionalSizeIfNoTransitiveDependencyOrNonCorrelatedSideEffect(mergedChunk, targetChunk, currentAdditionalSize, sideEffectAtoms, sizeByAtom);
  17500. return firstSize < currentAdditionalSize
  17501. ? firstSize +
  17502. getAdditionalSizeIfNoTransitiveDependencyOrNonCorrelatedSideEffect(targetChunk, mergedChunk, currentAdditionalSize - firstSize, sideEffectAtoms, sizeByAtom)
  17503. : Infinity;
  17504. }
  17505. function getAdditionalSizeIfNoTransitiveDependencyOrNonCorrelatedSideEffect(dependentChunk, dependencyChunk, currentAdditionalSize, sideEffectAtoms, sizeByAtom) {
  17506. const { correlatedAtoms } = dependencyChunk;
  17507. let dependencyAtoms = dependentChunk.containedAtoms;
  17508. const dependentContainedSideEffects = dependencyAtoms & sideEffectAtoms;
  17509. if ((correlatedAtoms & dependentContainedSideEffects) !== dependentContainedSideEffects) {
  17510. return Infinity;
  17511. }
  17512. const chunksToCheck = new Set(dependentChunk.dependencies);
  17513. for (const { dependencies, containedAtoms } of chunksToCheck) {
  17514. dependencyAtoms |= containedAtoms;
  17515. const containedSideEffects = containedAtoms & sideEffectAtoms;
  17516. if ((correlatedAtoms & containedSideEffects) !== containedSideEffects) {
  17517. return Infinity;
  17518. }
  17519. for (const dependency of dependencies) {
  17520. if (dependency === dependencyChunk) {
  17521. return Infinity;
  17522. }
  17523. chunksToCheck.add(dependency);
  17524. }
  17525. }
  17526. return getAtomsSizeIfBelowLimit(dependencyAtoms & ~correlatedAtoms, currentAdditionalSize, sizeByAtom);
  17527. }
  17528. function getAtomsSizeIfBelowLimit(atoms, currentAdditionalSize, sizeByAtom) {
  17529. let size = 0;
  17530. let atomIndex = 0;
  17531. let atomSignature = 1n;
  17532. const { length } = sizeByAtom;
  17533. for (; atomIndex < length; atomIndex++) {
  17534. if ((atoms & atomSignature) === atomSignature) {
  17535. size += sizeByAtom[atomIndex];
  17536. }
  17537. atomSignature <<= 1n;
  17538. if (size >= currentAdditionalSize) {
  17539. return Infinity;
  17540. }
  17541. }
  17542. return size;
  17543. }
  17544. function getChunksInPartition(chunk, minChunkSize, chunkPartition) {
  17545. return chunk.size < minChunkSize ? chunkPartition.small : chunkPartition.big;
  17546. }
  17547. // ported from https://github.com/substack/node-commondir
  17548. function commondir(files) {
  17549. if (files.length === 0)
  17550. return '/';
  17551. if (files.length === 1)
  17552. return dirname(files[0]);
  17553. const commonSegments = files.slice(1).reduce((commonSegments, file) => {
  17554. const pathSegments = file.split(/\/+|\\+/);
  17555. let index;
  17556. for (index = 0; commonSegments[index] === pathSegments[index] &&
  17557. index < Math.min(commonSegments.length, pathSegments.length); index++)
  17558. ;
  17559. return commonSegments.slice(0, index);
  17560. }, files[0].split(/\/+|\\+/));
  17561. // Windows correctly handles paths with forward-slashes
  17562. return commonSegments.length > 1 ? commonSegments.join('/') : '/';
  17563. }
  17564. const compareExecIndex = (unitA, unitB) => unitA.execIndex > unitB.execIndex ? 1 : -1;
  17565. function sortByExecutionOrder(units) {
  17566. units.sort(compareExecIndex);
  17567. }
  17568. // This process is currently faulty in so far as it only takes the first entry
  17569. // module into account and assumes that dynamic imports are imported in a
  17570. // certain order.
  17571. // A better algorithm would follow every possible execution path and mark which
  17572. // modules are executed before or after which other modules. THen the chunking
  17573. // would need to take care that in each chunk, all modules are always executed
  17574. // in the same sequence.
  17575. function analyseModuleExecution(entryModules) {
  17576. let nextExecIndex = 0;
  17577. const cyclePaths = [];
  17578. const analysedModules = new Set();
  17579. const dynamicImports = new Set();
  17580. const parents = new Map();
  17581. const orderedModules = [];
  17582. const analyseModule = (module) => {
  17583. if (module instanceof Module) {
  17584. for (const dependency of module.dependencies) {
  17585. if (parents.has(dependency)) {
  17586. if (!analysedModules.has(dependency)) {
  17587. cyclePaths.push(getCyclePath(dependency, module, parents));
  17588. }
  17589. continue;
  17590. }
  17591. parents.set(dependency, module);
  17592. analyseModule(dependency);
  17593. }
  17594. for (const dependency of module.implicitlyLoadedBefore) {
  17595. dynamicImports.add(dependency);
  17596. }
  17597. for (const { resolution } of module.dynamicImports) {
  17598. if (resolution instanceof Module) {
  17599. dynamicImports.add(resolution);
  17600. }
  17601. }
  17602. orderedModules.push(module);
  17603. }
  17604. module.execIndex = nextExecIndex++;
  17605. analysedModules.add(module);
  17606. };
  17607. for (const currentEntry of entryModules) {
  17608. if (!parents.has(currentEntry)) {
  17609. parents.set(currentEntry, null);
  17610. analyseModule(currentEntry);
  17611. }
  17612. }
  17613. for (const currentEntry of dynamicImports) {
  17614. if (!parents.has(currentEntry)) {
  17615. parents.set(currentEntry, null);
  17616. analyseModule(currentEntry);
  17617. }
  17618. }
  17619. return { cyclePaths, orderedModules };
  17620. }
  17621. function getCyclePath(module, parent, parents) {
  17622. const cycleSymbol = Symbol(module.id);
  17623. const path = [module.id];
  17624. let nextModule = parent;
  17625. module.cycles.add(cycleSymbol);
  17626. while (nextModule !== module) {
  17627. nextModule.cycles.add(cycleSymbol);
  17628. path.push(nextModule.id);
  17629. nextModule = parents.get(nextModule);
  17630. }
  17631. path.push(path[0]);
  17632. path.reverse();
  17633. return path;
  17634. }
  17635. function getGenerateCodeSnippets({ compact, generatedCode: { arrowFunctions, constBindings, objectShorthand, reservedNamesAsProps } }) {
  17636. const { _, n, s } = compact ? { _: '', n: '', s: '' } : { _: ' ', n: '\n', s: ';' };
  17637. const cnst = constBindings ? 'const' : 'var';
  17638. const getNonArrowFunctionIntro = (parameters, { isAsync, name }) => `${isAsync ? `async ` : ''}function${name ? ` ${name}` : ''}${_}(${parameters.join(`,${_}`)})${_}`;
  17639. const getFunctionIntro = arrowFunctions
  17640. ? (parameters, { isAsync, name }) => {
  17641. const singleParameter = parameters.length === 1;
  17642. const asyncString = isAsync ? `async${singleParameter ? ' ' : _}` : '';
  17643. return `${name ? `${cnst} ${name}${_}=${_}` : ''}${asyncString}${singleParameter ? parameters[0] : `(${parameters.join(`,${_}`)})`}${_}=>${_}`;
  17644. }
  17645. : getNonArrowFunctionIntro;
  17646. const getDirectReturnFunction = (parameters, { functionReturn, lineBreakIndent, name }) => [
  17647. `${getFunctionIntro(parameters, {
  17648. isAsync: false,
  17649. name
  17650. })}${arrowFunctions
  17651. ? lineBreakIndent
  17652. ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}`
  17653. : ''
  17654. : `{${lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _}${functionReturn ? 'return ' : ''}`}`,
  17655. arrowFunctions
  17656. ? `${name ? ';' : ''}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : ''}`
  17657. : `${s}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`
  17658. ];
  17659. const isValidPropertyName = reservedNamesAsProps
  17660. ? (name) => VALID_IDENTIFIER_REGEXP.test(name)
  17661. : (name) => !RESERVED_NAMES.has(name) && VALID_IDENTIFIER_REGEXP.test(name);
  17662. return {
  17663. _,
  17664. cnst,
  17665. getDirectReturnFunction,
  17666. getDirectReturnIifeLeft: (parameters, returned, { needsArrowReturnParens, needsWrappedFunction }) => {
  17667. const [left, right] = getDirectReturnFunction(parameters, {
  17668. functionReturn: true,
  17669. lineBreakIndent: null,
  17670. name: null
  17671. });
  17672. return `${wrapIfNeeded(`${left}${wrapIfNeeded(returned, arrowFunctions && needsArrowReturnParens)}${right}`, arrowFunctions || needsWrappedFunction)}(`;
  17673. },
  17674. getFunctionIntro,
  17675. getNonArrowFunctionIntro,
  17676. getObject(fields, { lineBreakIndent }) {
  17677. const prefix = lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _;
  17678. return `{${fields
  17679. .map(([key, value]) => {
  17680. if (key === null)
  17681. return `${prefix}${value}`;
  17682. const keyInObject = stringifyObjectKeyIfNeeded(key);
  17683. return key === value && objectShorthand && key === keyInObject
  17684. ? prefix + key
  17685. : `${prefix}${keyInObject}:${_}${value}`;
  17686. })
  17687. .join(`,`)}${fields.length === 0 ? '' : lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`;
  17688. },
  17689. getPropertyAccess: (name) => isValidPropertyName(name) ? `.${name}` : `[${JSON.stringify(name)}]`,
  17690. n,
  17691. s
  17692. };
  17693. }
  17694. const wrapIfNeeded = (code, needsParens) => needsParens ? `(${code})` : code;
  17695. class Source {
  17696. constructor(filename, content) {
  17697. this.isOriginal = true;
  17698. this.filename = filename;
  17699. this.content = content;
  17700. }
  17701. traceSegment(line, column, name) {
  17702. return { column, line, name, source: this };
  17703. }
  17704. }
  17705. class Link {
  17706. constructor(map, sources) {
  17707. this.sources = sources;
  17708. this.names = map.names;
  17709. this.mappings = map.mappings;
  17710. }
  17711. traceMappings() {
  17712. const sources = [];
  17713. const sourceIndexMap = new Map();
  17714. const sourcesContent = [];
  17715. const names = [];
  17716. const nameIndexMap = new Map();
  17717. const mappings = [];
  17718. for (const line of this.mappings) {
  17719. const tracedLine = [];
  17720. for (const segment of line) {
  17721. if (segment.length === 1)
  17722. continue;
  17723. const source = this.sources[segment[1]];
  17724. if (!source)
  17725. continue;
  17726. const traced = source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : '');
  17727. if (traced) {
  17728. const { column, line, name, source: { content, filename } } = traced;
  17729. let sourceIndex = sourceIndexMap.get(filename);
  17730. if (sourceIndex === undefined) {
  17731. sourceIndex = sources.length;
  17732. sources.push(filename);
  17733. sourceIndexMap.set(filename, sourceIndex);
  17734. sourcesContent[sourceIndex] = content;
  17735. }
  17736. else if (sourcesContent[sourceIndex] == null) {
  17737. sourcesContent[sourceIndex] = content;
  17738. }
  17739. else if (content != null && sourcesContent[sourceIndex] !== content) {
  17740. return error(logConflictingSourcemapSources(filename));
  17741. }
  17742. const tracedSegment = [segment[0], sourceIndex, line, column];
  17743. if (name) {
  17744. let nameIndex = nameIndexMap.get(name);
  17745. if (nameIndex === undefined) {
  17746. nameIndex = names.length;
  17747. names.push(name);
  17748. nameIndexMap.set(name, nameIndex);
  17749. }
  17750. tracedSegment[4] = nameIndex;
  17751. }
  17752. tracedLine.push(tracedSegment);
  17753. }
  17754. }
  17755. mappings.push(tracedLine);
  17756. }
  17757. return { mappings, names, sources, sourcesContent };
  17758. }
  17759. traceSegment(line, column, name) {
  17760. const segments = this.mappings[line];
  17761. if (!segments)
  17762. return null;
  17763. // binary search through segments for the given column
  17764. let searchStart = 0;
  17765. let searchEnd = segments.length - 1;
  17766. while (searchStart <= searchEnd) {
  17767. const m = (searchStart + searchEnd) >> 1;
  17768. const segment = segments[m];
  17769. // If a sourcemap does not have sufficient resolution to contain a
  17770. // necessary mapping, e.g. because it only contains line information, we
  17771. // use the best approximation we could find
  17772. if (segment[0] === column || searchStart === searchEnd) {
  17773. if (segment.length == 1)
  17774. return null;
  17775. const source = this.sources[segment[1]];
  17776. if (!source)
  17777. return null;
  17778. return source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : name);
  17779. }
  17780. if (segment[0] > column) {
  17781. searchEnd = m - 1;
  17782. }
  17783. else {
  17784. searchStart = m + 1;
  17785. }
  17786. }
  17787. return null;
  17788. }
  17789. }
  17790. function getLinkMap(log) {
  17791. return function linkMap(source, map) {
  17792. if (!map.missing) {
  17793. return new Link(map, [source]);
  17794. }
  17795. log(LOGLEVEL_WARN, logSourcemapBroken(map.plugin));
  17796. return new Link({
  17797. mappings: [],
  17798. names: []
  17799. }, [source]);
  17800. };
  17801. }
  17802. function getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, linkMap) {
  17803. let source;
  17804. if (originalSourcemap) {
  17805. const sources = originalSourcemap.sources;
  17806. const sourcesContent = originalSourcemap.sourcesContent || [];
  17807. const directory = dirname(id) || '.';
  17808. const sourceRoot = originalSourcemap.sourceRoot || '.';
  17809. const baseSources = sources.map((source, index) => new Source(resolve$1(directory, sourceRoot, source), sourcesContent[index]));
  17810. source = new Link(originalSourcemap, baseSources);
  17811. }
  17812. else {
  17813. source = new Source(id, originalCode);
  17814. }
  17815. return sourcemapChain.reduce(linkMap, source);
  17816. }
  17817. function collapseSourcemaps(file, map, modules, bundleSourcemapChain, excludeContent, log) {
  17818. const linkMap = getLinkMap(log);
  17819. const moduleSources = modules
  17820. .filter(module => !module.excludeFromSourcemap)
  17821. .map(module => getCollapsedSourcemap(module.id, module.originalCode, module.originalSourcemap, module.sourcemapChain, linkMap));
  17822. const link = new Link(map, moduleSources);
  17823. const source = bundleSourcemapChain.reduce(linkMap, link);
  17824. let { sources, sourcesContent, names, mappings } = source.traceMappings();
  17825. if (file) {
  17826. const directory = dirname(file);
  17827. sources = sources.map((source) => relative(directory, source));
  17828. file = basename(file);
  17829. }
  17830. sourcesContent = (excludeContent ? null : sourcesContent);
  17831. for (const module of modules) {
  17832. resetSourcemapCache(module.originalSourcemap, module.sourcemapChain);
  17833. }
  17834. return new SourceMap({ file, mappings, names, sources, sourcesContent });
  17835. }
  17836. function collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, log) {
  17837. if (sourcemapChain.length === 0) {
  17838. return originalSourcemap;
  17839. }
  17840. const source = getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, getLinkMap(log));
  17841. const map = source.traceMappings();
  17842. return decodedSourcemap({ version: 3, ...map });
  17843. }
  17844. let textEncoder;
  17845. const getHash64 = input => xxhashBase64Url(ensureBuffer(input));
  17846. const getHash36 = input => xxhashBase36(ensureBuffer(input));
  17847. const getHash16 = input => xxhashBase16(ensureBuffer(input));
  17848. const hasherByType = {
  17849. base36: getHash36,
  17850. base64: getHash64,
  17851. hex: getHash16
  17852. };
  17853. function ensureBuffer(input) {
  17854. if (typeof input === 'string') {
  17855. if (typeof Buffer === 'undefined') {
  17856. textEncoder ??= new TextEncoder();
  17857. return textEncoder.encode(input);
  17858. }
  17859. return Buffer.from(input);
  17860. }
  17861. return input;
  17862. }
  17863. // this looks ridiculous, but it prevents sourcemap tooling from mistaking
  17864. // this for an actual sourceMappingURL
  17865. let SOURCEMAPPING_URL = 'sourceMa';
  17866. SOURCEMAPPING_URL += 'ppingURL';
  17867. async function renderChunks(chunks, bundle, pluginDriver, outputOptions, log) {
  17868. timeStart('render chunks', 2);
  17869. reserveEntryChunksInBundle(chunks);
  17870. const renderedChunks = await Promise.all(chunks.map(chunk => chunk.render()));
  17871. timeEnd('render chunks', 2);
  17872. timeStart('transform chunks', 2);
  17873. const getHash = hasherByType[outputOptions.hashCharacters];
  17874. const chunkGraph = getChunkGraph(chunks);
  17875. const { hashDependenciesByPlaceholder, initialHashesByPlaceholder, nonHashedChunksWithPlaceholders, placeholders, renderedChunksByPlaceholder } = await transformChunksAndGenerateContentHashes(renderedChunks, chunkGraph, outputOptions, pluginDriver, getHash, log);
  17876. const hashesByPlaceholder = generateFinalHashes(renderedChunksByPlaceholder, hashDependenciesByPlaceholder, initialHashesByPlaceholder, placeholders, bundle, getHash);
  17877. addChunksToBundle(renderedChunksByPlaceholder, hashesByPlaceholder, bundle, nonHashedChunksWithPlaceholders, pluginDriver, outputOptions);
  17878. timeEnd('transform chunks', 2);
  17879. }
  17880. function reserveEntryChunksInBundle(chunks) {
  17881. for (const chunk of chunks) {
  17882. if (chunk.facadeModule && chunk.facadeModule.isUserDefinedEntryPoint) {
  17883. // reserves name in bundle as side effect if it does not contain a hash
  17884. chunk.getPreliminaryFileName();
  17885. }
  17886. }
  17887. }
  17888. function getChunkGraph(chunks) {
  17889. return Object.fromEntries(chunks.map(chunk => {
  17890. const renderedChunkInfo = chunk.getRenderedChunkInfo();
  17891. return [renderedChunkInfo.fileName, renderedChunkInfo];
  17892. }));
  17893. }
  17894. async function transformChunk(magicString, fileName, usedModules, chunkGraph, options, outputPluginDriver, log) {
  17895. let map = null;
  17896. const sourcemapChain = [];
  17897. let code = await outputPluginDriver.hookReduceArg0('renderChunk', [magicString.toString(), chunkGraph[fileName], options, { chunks: chunkGraph }], (code, result, plugin) => {
  17898. if (result == null)
  17899. return code;
  17900. if (typeof result === 'string')
  17901. result = {
  17902. code: result,
  17903. map: undefined
  17904. };
  17905. // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning
  17906. if (result.map !== null) {
  17907. const map = decodedSourcemap(result.map);
  17908. sourcemapChain.push(map || { missing: true, plugin: plugin.name });
  17909. }
  17910. return result.code;
  17911. });
  17912. const { compact, dir, file, sourcemap, sourcemapExcludeSources, sourcemapFile, sourcemapPathTransform, sourcemapIgnoreList } = options;
  17913. if (!compact && code[code.length - 1] !== '\n')
  17914. code += '\n';
  17915. if (sourcemap) {
  17916. timeStart('sourcemaps', 3);
  17917. let resultingFile;
  17918. if (file)
  17919. resultingFile = resolve$1(sourcemapFile || file);
  17920. else if (dir)
  17921. resultingFile = resolve$1(dir, fileName);
  17922. else
  17923. resultingFile = resolve$1(fileName);
  17924. const decodedMap = magicString.generateDecodedMap({});
  17925. map = collapseSourcemaps(resultingFile, decodedMap, usedModules, sourcemapChain, sourcemapExcludeSources, log);
  17926. for (let sourcesIndex = 0; sourcesIndex < map.sources.length; ++sourcesIndex) {
  17927. let sourcePath = map.sources[sourcesIndex];
  17928. const sourcemapPath = `${resultingFile}.map`;
  17929. const ignoreList = sourcemapIgnoreList(sourcePath, sourcemapPath);
  17930. if (typeof ignoreList !== 'boolean') {
  17931. error(logFailedValidation('sourcemapIgnoreList function must return a boolean.'));
  17932. }
  17933. if (ignoreList) {
  17934. if (map.x_google_ignoreList === undefined) {
  17935. map.x_google_ignoreList = [];
  17936. }
  17937. if (!map.x_google_ignoreList.includes(sourcesIndex)) {
  17938. map.x_google_ignoreList.push(sourcesIndex);
  17939. }
  17940. }
  17941. if (sourcemapPathTransform) {
  17942. sourcePath = sourcemapPathTransform(sourcePath, sourcemapPath);
  17943. if (typeof sourcePath !== 'string') {
  17944. error(logFailedValidation(`sourcemapPathTransform function must return a string.`));
  17945. }
  17946. }
  17947. map.sources[sourcesIndex] = normalize(sourcePath);
  17948. }
  17949. timeEnd('sourcemaps', 3);
  17950. }
  17951. return {
  17952. code,
  17953. map
  17954. };
  17955. }
  17956. async function transformChunksAndGenerateContentHashes(renderedChunks, chunkGraph, outputOptions, pluginDriver, getHash, log) {
  17957. const nonHashedChunksWithPlaceholders = [];
  17958. const renderedChunksByPlaceholder = new Map();
  17959. const hashDependenciesByPlaceholder = new Map();
  17960. const initialHashesByPlaceholder = new Map();
  17961. const placeholders = new Set();
  17962. for (const { preliminaryFileName: { hashPlaceholder } } of renderedChunks) {
  17963. if (hashPlaceholder)
  17964. placeholders.add(hashPlaceholder);
  17965. }
  17966. await Promise.all(renderedChunks.map(async ({ chunk, preliminaryFileName: { fileName, hashPlaceholder }, preliminarySourcemapFileName, magicString, usedModules }) => {
  17967. const transformedChunk = {
  17968. chunk,
  17969. fileName,
  17970. sourcemapFileName: preliminarySourcemapFileName?.fileName ?? null,
  17971. ...(await transformChunk(magicString, fileName, usedModules, chunkGraph, outputOptions, pluginDriver, log))
  17972. };
  17973. const { code, map } = transformedChunk;
  17974. if (hashPlaceholder) {
  17975. // To create a reproducible content-only hash, all placeholders are
  17976. // replaced with the same value before hashing
  17977. const { containedPlaceholders, transformedCode } = replacePlaceholdersWithDefaultAndGetContainedPlaceholders(code, placeholders);
  17978. let contentToHash = transformedCode;
  17979. const hashAugmentation = pluginDriver.hookReduceValueSync('augmentChunkHash', '', [chunk.getRenderedChunkInfo()], (augmentation, pluginHash) => {
  17980. if (pluginHash) {
  17981. augmentation += pluginHash;
  17982. }
  17983. return augmentation;
  17984. });
  17985. if (hashAugmentation) {
  17986. contentToHash += hashAugmentation;
  17987. }
  17988. renderedChunksByPlaceholder.set(hashPlaceholder, transformedChunk);
  17989. hashDependenciesByPlaceholder.set(hashPlaceholder, {
  17990. containedPlaceholders,
  17991. contentHash: getHash(contentToHash)
  17992. });
  17993. }
  17994. else {
  17995. nonHashedChunksWithPlaceholders.push(transformedChunk);
  17996. }
  17997. const sourcemapHashPlaceholder = preliminarySourcemapFileName?.hashPlaceholder;
  17998. if (map && sourcemapHashPlaceholder) {
  17999. initialHashesByPlaceholder.set(preliminarySourcemapFileName.hashPlaceholder, getHash(map.toString()).slice(0, preliminarySourcemapFileName.hashPlaceholder.length));
  18000. }
  18001. }));
  18002. return {
  18003. hashDependenciesByPlaceholder,
  18004. initialHashesByPlaceholder,
  18005. nonHashedChunksWithPlaceholders,
  18006. placeholders,
  18007. renderedChunksByPlaceholder
  18008. };
  18009. }
  18010. function generateFinalHashes(renderedChunksByPlaceholder, hashDependenciesByPlaceholder, initialHashesByPlaceholder, placeholders, bundle, getHash) {
  18011. const hashesByPlaceholder = new Map(initialHashesByPlaceholder);
  18012. for (const placeholder of placeholders) {
  18013. const { fileName } = renderedChunksByPlaceholder.get(placeholder);
  18014. let contentToHash = '';
  18015. const hashDependencyPlaceholders = new Set([placeholder]);
  18016. for (const dependencyPlaceholder of hashDependencyPlaceholders) {
  18017. const { containedPlaceholders, contentHash } = hashDependenciesByPlaceholder.get(dependencyPlaceholder);
  18018. contentToHash += contentHash;
  18019. for (const containedPlaceholder of containedPlaceholders) {
  18020. // When looping over a map, setting an entry only causes a new iteration if the key is new
  18021. hashDependencyPlaceholders.add(containedPlaceholder);
  18022. }
  18023. }
  18024. let finalFileName;
  18025. let finalHash;
  18026. do {
  18027. // In case of a hash collision, create a hash of the hash
  18028. if (finalHash) {
  18029. contentToHash = finalHash;
  18030. }
  18031. finalHash = getHash(contentToHash).slice(0, placeholder.length);
  18032. finalFileName = replaceSinglePlaceholder(fileName, placeholder, finalHash);
  18033. } while (bundle[lowercaseBundleKeys].has(finalFileName.toLowerCase()));
  18034. bundle[finalFileName] = FILE_PLACEHOLDER;
  18035. hashesByPlaceholder.set(placeholder, finalHash);
  18036. }
  18037. return hashesByPlaceholder;
  18038. }
  18039. function addChunksToBundle(renderedChunksByPlaceholder, hashesByPlaceholder, bundle, nonHashedChunksWithPlaceholders, pluginDriver, options) {
  18040. for (const { chunk, code, fileName, sourcemapFileName, map } of renderedChunksByPlaceholder.values()) {
  18041. let updatedCode = replacePlaceholders(code, hashesByPlaceholder);
  18042. const finalFileName = replacePlaceholders(fileName, hashesByPlaceholder);
  18043. let finalSourcemapFileName = null;
  18044. if (map) {
  18045. finalSourcemapFileName = sourcemapFileName
  18046. ? replacePlaceholders(sourcemapFileName, hashesByPlaceholder)
  18047. : `${finalFileName}.map`;
  18048. map.file = replacePlaceholders(map.file, hashesByPlaceholder);
  18049. updatedCode += emitSourceMapAndGetComment(finalSourcemapFileName, map, pluginDriver, options);
  18050. }
  18051. bundle[finalFileName] = chunk.finalizeChunk(updatedCode, map, finalSourcemapFileName, hashesByPlaceholder);
  18052. }
  18053. for (const { chunk, code, fileName, sourcemapFileName, map } of nonHashedChunksWithPlaceholders) {
  18054. let updatedCode = hashesByPlaceholder.size > 0 ? replacePlaceholders(code, hashesByPlaceholder) : code;
  18055. let finalSourcemapFileName = null;
  18056. if (map) {
  18057. finalSourcemapFileName = sourcemapFileName
  18058. ? replacePlaceholders(sourcemapFileName, hashesByPlaceholder)
  18059. : `${fileName}.map`;
  18060. updatedCode += emitSourceMapAndGetComment(finalSourcemapFileName, map, pluginDriver, options);
  18061. }
  18062. bundle[fileName] = chunk.finalizeChunk(updatedCode, map, finalSourcemapFileName, hashesByPlaceholder);
  18063. }
  18064. }
  18065. function emitSourceMapAndGetComment(fileName, map, pluginDriver, { sourcemap, sourcemapBaseUrl }) {
  18066. let url;
  18067. if (sourcemap === 'inline') {
  18068. url = map.toUrl();
  18069. }
  18070. else {
  18071. const sourcemapFileName = basename(fileName);
  18072. url = sourcemapBaseUrl
  18073. ? new URL(sourcemapFileName, sourcemapBaseUrl).toString()
  18074. : sourcemapFileName;
  18075. pluginDriver.emitFile({
  18076. fileName,
  18077. originalFileName: null,
  18078. source: map.toString(),
  18079. type: 'asset'
  18080. });
  18081. }
  18082. return sourcemap === 'hidden' ? '' : `//# ${SOURCEMAPPING_URL}=${url}\n`;
  18083. }
  18084. class Bundle {
  18085. constructor(outputOptions, unsetOptions, inputOptions, pluginDriver, graph) {
  18086. this.outputOptions = outputOptions;
  18087. this.unsetOptions = unsetOptions;
  18088. this.inputOptions = inputOptions;
  18089. this.pluginDriver = pluginDriver;
  18090. this.graph = graph;
  18091. this.facadeChunkByModule = new Map();
  18092. this.includedNamespaces = new Set();
  18093. }
  18094. async generate(isWrite) {
  18095. timeStart('GENERATE', 1);
  18096. const outputBundleBase = Object.create(null);
  18097. const outputBundle = getOutputBundle(outputBundleBase);
  18098. this.pluginDriver.setOutputBundle(outputBundle, this.outputOptions);
  18099. try {
  18100. timeStart('initialize render', 2);
  18101. await this.pluginDriver.hookParallel('renderStart', [this.outputOptions, this.inputOptions]);
  18102. timeEnd('initialize render', 2);
  18103. timeStart('generate chunks', 2);
  18104. const getHashPlaceholder = getHashPlaceholderGenerator();
  18105. const chunks = await this.generateChunks(outputBundle, getHashPlaceholder);
  18106. if (chunks.length > 1) {
  18107. validateOptionsForMultiChunkOutput(this.outputOptions, this.inputOptions.onLog);
  18108. }
  18109. this.pluginDriver.setChunkInformation(this.facadeChunkByModule);
  18110. for (const chunk of chunks) {
  18111. chunk.generateExports();
  18112. }
  18113. timeEnd('generate chunks', 2);
  18114. await renderChunks(chunks, outputBundle, this.pluginDriver, this.outputOptions, this.inputOptions.onLog);
  18115. }
  18116. catch (error_) {
  18117. await this.pluginDriver.hookParallel('renderError', [error_]);
  18118. throw error_;
  18119. }
  18120. removeUnreferencedAssets(outputBundle);
  18121. timeStart('generate bundle', 2);
  18122. await this.pluginDriver.hookSeq('generateBundle', [
  18123. this.outputOptions,
  18124. outputBundle,
  18125. isWrite
  18126. ]);
  18127. this.finaliseAssets(outputBundle);
  18128. timeEnd('generate bundle', 2);
  18129. timeEnd('GENERATE', 1);
  18130. return outputBundleBase;
  18131. }
  18132. async addManualChunks(manualChunks) {
  18133. const manualChunkAliasByEntry = new Map();
  18134. const chunkEntries = await Promise.all(Object.entries(manualChunks).map(async ([alias, files]) => ({
  18135. alias,
  18136. entries: await this.graph.moduleLoader.addAdditionalModules(files, true)
  18137. })));
  18138. for (const { alias, entries } of chunkEntries) {
  18139. for (const entry of entries) {
  18140. addModuleToManualChunk(alias, entry, manualChunkAliasByEntry);
  18141. }
  18142. }
  18143. return manualChunkAliasByEntry;
  18144. }
  18145. assignManualChunks(getManualChunk) {
  18146. const manualChunkAliasesWithEntry = [];
  18147. const manualChunksApi = {
  18148. getModuleIds: () => this.graph.modulesById.keys(),
  18149. getModuleInfo: this.graph.getModuleInfo
  18150. };
  18151. for (const module of this.graph.modulesById.values()) {
  18152. if (module instanceof Module) {
  18153. const manualChunkAlias = getManualChunk(module.id, manualChunksApi);
  18154. if (typeof manualChunkAlias === 'string') {
  18155. manualChunkAliasesWithEntry.push([manualChunkAlias, module]);
  18156. }
  18157. }
  18158. }
  18159. manualChunkAliasesWithEntry.sort(([aliasA], [aliasB]) => aliasA > aliasB ? 1 : aliasA < aliasB ? -1 : 0);
  18160. const manualChunkAliasByEntry = new Map();
  18161. for (const [alias, module] of manualChunkAliasesWithEntry) {
  18162. addModuleToManualChunk(alias, module, manualChunkAliasByEntry);
  18163. }
  18164. return manualChunkAliasByEntry;
  18165. }
  18166. finaliseAssets(bundle) {
  18167. if (this.outputOptions.validate) {
  18168. for (const file of Object.values(bundle)) {
  18169. if ('code' in file) {
  18170. try {
  18171. parseAst(file.code, { jsx: this.inputOptions.jsx !== false });
  18172. }
  18173. catch (error_) {
  18174. this.inputOptions.onLog(LOGLEVEL_WARN, logChunkInvalid(file, error_));
  18175. }
  18176. }
  18177. }
  18178. }
  18179. this.pluginDriver.finaliseAssets();
  18180. }
  18181. async generateChunks(bundle, getHashPlaceholder) {
  18182. const { experimentalMinChunkSize, inlineDynamicImports, manualChunks, preserveModules } = this.outputOptions;
  18183. const manualChunkAliasByEntry = typeof manualChunks === 'object'
  18184. ? await this.addManualChunks(manualChunks)
  18185. : this.assignManualChunks(manualChunks);
  18186. const snippets = getGenerateCodeSnippets(this.outputOptions);
  18187. const includedModules = getIncludedModules(this.graph.modulesById);
  18188. const inputBase = commondir(getAbsoluteEntryModulePaths(includedModules, preserveModules));
  18189. const externalChunkByModule = getExternalChunkByModule(this.graph.modulesById, this.outputOptions, inputBase);
  18190. const chunks = [];
  18191. const chunkByModule = new Map();
  18192. for (const { alias, modules } of inlineDynamicImports
  18193. ? [{ alias: null, modules: includedModules }]
  18194. : preserveModules
  18195. ? includedModules.map(module => ({ alias: null, modules: [module] }))
  18196. : getChunkAssignments(this.graph.entryModules, manualChunkAliasByEntry, experimentalMinChunkSize, this.inputOptions.onLog)) {
  18197. sortByExecutionOrder(modules);
  18198. 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);
  18199. chunks.push(chunk);
  18200. }
  18201. for (const chunk of chunks) {
  18202. chunk.link();
  18203. }
  18204. const facades = [];
  18205. for (const chunk of chunks) {
  18206. facades.push(...chunk.generateFacades());
  18207. }
  18208. return [...chunks, ...facades];
  18209. }
  18210. }
  18211. function validateOptionsForMultiChunkOutput(outputOptions, log) {
  18212. if (outputOptions.format === 'umd' || outputOptions.format === 'iife')
  18213. return error(logInvalidOption('output.format', URL_OUTPUT_FORMAT, 'UMD and IIFE output formats are not supported for code-splitting builds', outputOptions.format));
  18214. if (typeof outputOptions.file === 'string')
  18215. 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'));
  18216. if (outputOptions.sourcemapFile)
  18217. return error(logInvalidOption('output.sourcemapFile', URL_OUTPUT_SOURCEMAPFILE, '"output.sourcemapFile" is only supported for single-file builds'));
  18218. if (!outputOptions.amd.autoId && outputOptions.amd.id)
  18219. 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'));
  18220. }
  18221. function getIncludedModules(modulesById) {
  18222. const includedModules = [];
  18223. for (const module of modulesById.values()) {
  18224. if (module instanceof Module &&
  18225. (module.isIncluded() || module.info.isEntry || module.includedDynamicImporters.length > 0)) {
  18226. includedModules.push(module);
  18227. }
  18228. }
  18229. return includedModules;
  18230. }
  18231. function getAbsoluteEntryModulePaths(includedModules, preserveModules) {
  18232. const absoluteEntryModulePaths = [];
  18233. for (const module of includedModules) {
  18234. if ((module.info.isEntry || preserveModules) && isAbsolute$1(module.id)) {
  18235. absoluteEntryModulePaths.push(module.id);
  18236. }
  18237. }
  18238. return absoluteEntryModulePaths;
  18239. }
  18240. function getExternalChunkByModule(modulesById, outputOptions, inputBase) {
  18241. const externalChunkByModule = new Map();
  18242. for (const module of modulesById.values()) {
  18243. if (module instanceof ExternalModule) {
  18244. externalChunkByModule.set(module, new ExternalChunk(module, outputOptions, inputBase));
  18245. }
  18246. }
  18247. return externalChunkByModule;
  18248. }
  18249. function addModuleToManualChunk(alias, module, manualChunkAliasByEntry) {
  18250. const existingAlias = manualChunkAliasByEntry.get(module);
  18251. if (typeof existingAlias === 'string' && existingAlias !== alias) {
  18252. return error(logCannotAssignModuleToChunk(module.id, alias, existingAlias));
  18253. }
  18254. manualChunkAliasByEntry.set(module, alias);
  18255. }
  18256. function flru (max) {
  18257. var num, curr, prev;
  18258. var limit = max;
  18259. function keep(key, value) {
  18260. if (++num > limit) {
  18261. prev = curr;
  18262. reset(1);
  18263. ++num;
  18264. }
  18265. curr[key] = value;
  18266. }
  18267. function reset(isPartial) {
  18268. num = 0;
  18269. curr = Object.create(null);
  18270. isPartial || (prev=Object.create(null));
  18271. }
  18272. reset();
  18273. return {
  18274. clear: reset,
  18275. has: function (key) {
  18276. return curr[key] !== void 0 || prev[key] !== void 0;
  18277. },
  18278. get: function (key) {
  18279. var val = curr[key];
  18280. if (val !== void 0) return val;
  18281. if ((val=prev[key]) !== void 0) {
  18282. keep(key, val);
  18283. return val;
  18284. }
  18285. },
  18286. set: function (key, value) {
  18287. if (curr[key] !== void 0) {
  18288. curr[key] = value;
  18289. } else {
  18290. keep(key, value);
  18291. }
  18292. }
  18293. };
  18294. }
  18295. class GlobalScope extends Scope {
  18296. constructor() {
  18297. super();
  18298. this.parent = null;
  18299. this.variables.set('undefined', new UndefinedVariable());
  18300. }
  18301. findVariable(name) {
  18302. let variable = this.variables.get(name);
  18303. if (!variable) {
  18304. variable = new GlobalVariable(name);
  18305. this.variables.set(name, variable);
  18306. }
  18307. return variable;
  18308. }
  18309. }
  18310. function resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, attributes) {
  18311. let skipped = null;
  18312. let replaceContext = null;
  18313. if (skip) {
  18314. skipped = new Set();
  18315. for (const skippedCall of skip) {
  18316. if (source === skippedCall.source && importer === skippedCall.importer) {
  18317. skipped.add(skippedCall.plugin);
  18318. }
  18319. }
  18320. replaceContext = (pluginContext, plugin) => ({
  18321. ...pluginContext,
  18322. resolve: (source, importer, { attributes, custom, isEntry, skipSelf } = BLANK) => {
  18323. skipSelf ??= true;
  18324. return moduleLoaderResolveId(source, importer, custom, isEntry, attributes || EMPTY_OBJECT, skipSelf ? [...skip, { importer, plugin, source }] : skip);
  18325. }
  18326. });
  18327. }
  18328. return pluginDriver.hookFirstAndGetPlugin('resolveId', [source, importer, { attributes, custom: customOptions, isEntry }], replaceContext, skipped);
  18329. }
  18330. async function resolveId(source, importer, preserveSymlinks, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, attributes) {
  18331. const pluginResult = await resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, attributes);
  18332. if (pluginResult != null) {
  18333. const [resolveIdResult, plugin] = pluginResult;
  18334. if (typeof resolveIdResult === 'object' && !resolveIdResult.resolvedBy) {
  18335. return {
  18336. ...resolveIdResult,
  18337. resolvedBy: plugin.name
  18338. };
  18339. }
  18340. if (typeof resolveIdResult === 'string') {
  18341. return {
  18342. id: resolveIdResult,
  18343. resolvedBy: plugin.name
  18344. };
  18345. }
  18346. return resolveIdResult;
  18347. }
  18348. // external modules (non-entry modules that start with neither '.' or '/')
  18349. // are skipped at this stage.
  18350. if (importer !== undefined && !isAbsolute$1(source) && source[0] !== '.')
  18351. return null;
  18352. // `resolve` processes paths from right to left, prepending them until an
  18353. // absolute path is created. Absolute importees therefore shortcircuit the
  18354. // resolve call and require no special handing on our part.
  18355. // See https://nodejs.org/api/path.html#path_path_resolve_paths
  18356. return addJsExtensionIfNecessary(importer ? resolve$1(dirname(importer), source) : resolve$1(source), preserveSymlinks);
  18357. }
  18358. async function addJsExtensionIfNecessary(file, preserveSymlinks) {
  18359. return ((await findFile(file, preserveSymlinks)) ??
  18360. (await findFile(file + '.mjs', preserveSymlinks)) ??
  18361. (await findFile(file + '.js', preserveSymlinks)));
  18362. }
  18363. async function findFile(file, preserveSymlinks) {
  18364. try {
  18365. const stats = await lstat(file);
  18366. if (!preserveSymlinks && stats.isSymbolicLink())
  18367. return await findFile(await realpath(file), preserveSymlinks);
  18368. if ((preserveSymlinks && stats.isSymbolicLink()) || stats.isFile()) {
  18369. // check case
  18370. const name = basename(file);
  18371. const files = await readdir(dirname(file));
  18372. if (files.includes(name))
  18373. return file;
  18374. }
  18375. }
  18376. catch {
  18377. // suppress
  18378. }
  18379. }
  18380. const ANONYMOUS_PLUGIN_PREFIX = 'at position ';
  18381. const ANONYMOUS_OUTPUT_PLUGIN_PREFIX = 'at output position ';
  18382. function createPluginCache(cache) {
  18383. return {
  18384. delete(id) {
  18385. return delete cache[id];
  18386. },
  18387. get(id) {
  18388. const item = cache[id];
  18389. if (!item)
  18390. return;
  18391. item[0] = 0;
  18392. return item[1];
  18393. },
  18394. has(id) {
  18395. const item = cache[id];
  18396. if (!item)
  18397. return false;
  18398. item[0] = 0;
  18399. return true;
  18400. },
  18401. set(id, value) {
  18402. cache[id] = [0, value];
  18403. }
  18404. };
  18405. }
  18406. function getTrackedPluginCache(pluginCache, onUse) {
  18407. return {
  18408. delete(id) {
  18409. onUse();
  18410. return pluginCache.delete(id);
  18411. },
  18412. get(id) {
  18413. onUse();
  18414. return pluginCache.get(id);
  18415. },
  18416. has(id) {
  18417. onUse();
  18418. return pluginCache.has(id);
  18419. },
  18420. set(id, value) {
  18421. onUse();
  18422. return pluginCache.set(id, value);
  18423. }
  18424. };
  18425. }
  18426. const NO_CACHE = {
  18427. delete() {
  18428. return false;
  18429. },
  18430. get() {
  18431. return undefined;
  18432. },
  18433. has() {
  18434. return false;
  18435. },
  18436. set() { }
  18437. };
  18438. function uncacheablePluginError(pluginName) {
  18439. if (pluginName.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  18440. pluginName.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX)) {
  18441. return error(logAnonymousPluginCache());
  18442. }
  18443. return error(logDuplicatePluginName(pluginName));
  18444. }
  18445. function getCacheForUncacheablePlugin(pluginName) {
  18446. return {
  18447. delete() {
  18448. return uncacheablePluginError(pluginName);
  18449. },
  18450. get() {
  18451. return uncacheablePluginError(pluginName);
  18452. },
  18453. has() {
  18454. return uncacheablePluginError(pluginName);
  18455. },
  18456. set() {
  18457. return uncacheablePluginError(pluginName);
  18458. }
  18459. };
  18460. }
  18461. async function asyncFlatten(array) {
  18462. do {
  18463. array = (await Promise.all(array)).flat(Infinity);
  18464. } while (array.some((v) => v?.then));
  18465. return array;
  18466. }
  18467. const getOnLog = (config, logLevel, printLog = defaultPrintLog) => {
  18468. const { onwarn, onLog } = config;
  18469. const defaultOnLog = getDefaultOnLog(printLog, onwarn);
  18470. if (onLog) {
  18471. const minimalPriority = logLevelPriority[logLevel];
  18472. return (level, log) => onLog(level, addLogToString(log), (level, handledLog) => {
  18473. if (level === LOGLEVEL_ERROR) {
  18474. return error(normalizeLog(handledLog));
  18475. }
  18476. if (logLevelPriority[level] >= minimalPriority) {
  18477. defaultOnLog(level, normalizeLog(handledLog));
  18478. }
  18479. });
  18480. }
  18481. return defaultOnLog;
  18482. };
  18483. const getDefaultOnLog = (printLog, onwarn) => onwarn
  18484. ? (level, log) => {
  18485. if (level === LOGLEVEL_WARN) {
  18486. onwarn(addLogToString(log), warning => printLog(LOGLEVEL_WARN, normalizeLog(warning)));
  18487. }
  18488. else {
  18489. printLog(level, log);
  18490. }
  18491. }
  18492. : printLog;
  18493. const addLogToString = (log) => {
  18494. Object.defineProperty(log, 'toString', {
  18495. value: () => log.message,
  18496. writable: true
  18497. });
  18498. return log;
  18499. };
  18500. const normalizeLog = (log) => typeof log === 'string'
  18501. ? { message: log }
  18502. : typeof log === 'function'
  18503. ? normalizeLog(log())
  18504. : log;
  18505. const defaultPrintLog = (level, { message }) => {
  18506. switch (level) {
  18507. case LOGLEVEL_WARN: {
  18508. return console.warn(message);
  18509. }
  18510. case LOGLEVEL_DEBUG: {
  18511. return console.debug(message);
  18512. }
  18513. default: {
  18514. return console.info(message);
  18515. }
  18516. }
  18517. };
  18518. function warnUnknownOptions(passedOptions, validOptions, optionType, log, ignoredKeys = /$./) {
  18519. const validOptionSet = new Set(validOptions);
  18520. const unknownOptions = Object.keys(passedOptions).filter(key => !(validOptionSet.has(key) || ignoredKeys.test(key)));
  18521. if (unknownOptions.length > 0) {
  18522. log(LOGLEVEL_WARN, logUnknownOption(optionType, unknownOptions, [...validOptionSet].sort()));
  18523. }
  18524. }
  18525. const treeshakePresets = {
  18526. recommended: {
  18527. annotations: true,
  18528. correctVarValueBeforeDeclaration: false,
  18529. manualPureFunctions: EMPTY_ARRAY,
  18530. moduleSideEffects: () => true,
  18531. propertyReadSideEffects: true,
  18532. tryCatchDeoptimization: true,
  18533. unknownGlobalSideEffects: false
  18534. },
  18535. safest: {
  18536. annotations: true,
  18537. correctVarValueBeforeDeclaration: true,
  18538. manualPureFunctions: EMPTY_ARRAY,
  18539. moduleSideEffects: () => true,
  18540. propertyReadSideEffects: true,
  18541. tryCatchDeoptimization: true,
  18542. unknownGlobalSideEffects: true
  18543. },
  18544. smallest: {
  18545. annotations: true,
  18546. correctVarValueBeforeDeclaration: false,
  18547. manualPureFunctions: EMPTY_ARRAY,
  18548. moduleSideEffects: () => false,
  18549. propertyReadSideEffects: false,
  18550. tryCatchDeoptimization: false,
  18551. unknownGlobalSideEffects: false
  18552. }
  18553. };
  18554. const jsxPresets = {
  18555. preserve: {
  18556. factory: null,
  18557. fragment: null,
  18558. importSource: null,
  18559. mode: 'preserve'
  18560. },
  18561. 'preserve-react': {
  18562. factory: 'React.createElement',
  18563. fragment: 'React.Fragment',
  18564. importSource: 'react',
  18565. mode: 'preserve'
  18566. },
  18567. react: {
  18568. factory: 'React.createElement',
  18569. fragment: 'React.Fragment',
  18570. importSource: 'react',
  18571. mode: 'classic'
  18572. },
  18573. 'react-jsx': {
  18574. factory: 'React.createElement',
  18575. importSource: 'react',
  18576. jsxImportSource: 'react/jsx-runtime',
  18577. mode: 'automatic'
  18578. }
  18579. };
  18580. const generatedCodePresets = {
  18581. es2015: {
  18582. arrowFunctions: true,
  18583. constBindings: true,
  18584. objectShorthand: true,
  18585. reservedNamesAsProps: true,
  18586. symbols: true
  18587. },
  18588. es5: {
  18589. arrowFunctions: false,
  18590. constBindings: false,
  18591. objectShorthand: false,
  18592. reservedNamesAsProps: true,
  18593. symbols: false
  18594. }
  18595. };
  18596. const objectifyOption = (value) => value && typeof value === 'object' ? value : {};
  18597. const objectifyOptionWithPresets = (presets, optionName, urlSnippet, additionalValues) => (value) => {
  18598. if (typeof value === 'string') {
  18599. const preset = presets[value];
  18600. if (preset) {
  18601. return preset;
  18602. }
  18603. error(logInvalidOption(optionName, urlSnippet, `valid values are ${additionalValues}${printQuotedStringList(Object.keys(presets))}. You can also supply an object for more fine-grained control`, value));
  18604. }
  18605. return objectifyOption(value);
  18606. };
  18607. const getOptionWithPreset = (value, presets, optionName, urlSnippet, additionalValues) => {
  18608. const presetName = value?.preset;
  18609. if (presetName) {
  18610. const preset = presets[presetName];
  18611. if (preset) {
  18612. return { ...preset, ...value };
  18613. }
  18614. else {
  18615. error(logInvalidOption(`${optionName}.preset`, urlSnippet, `valid values are ${printQuotedStringList(Object.keys(presets))}`, presetName));
  18616. }
  18617. }
  18618. return objectifyOptionWithPresets(presets, optionName, urlSnippet, additionalValues)(value);
  18619. };
  18620. const normalizePluginOption = async (plugins) => (await asyncFlatten([plugins])).filter(Boolean);
  18621. async function transform(source, module, pluginDriver, log) {
  18622. const id = module.id;
  18623. const sourcemapChain = [];
  18624. let originalSourcemap = source.map === null ? null : decodedSourcemap(source.map);
  18625. const originalCode = source.code;
  18626. let ast = source.ast;
  18627. const transformDependencies = [];
  18628. const emittedFiles = [];
  18629. let customTransformCache = false;
  18630. const useCustomTransformCache = () => (customTransformCache = true);
  18631. let pluginName = '';
  18632. let currentSource = source.code;
  18633. function transformReducer(previousCode, result, plugin) {
  18634. let code;
  18635. let map;
  18636. if (typeof result === 'string') {
  18637. code = result;
  18638. }
  18639. else if (result && typeof result === 'object') {
  18640. module.updateOptions(result);
  18641. if (result.code == null) {
  18642. if (result.map || result.ast) {
  18643. log(LOGLEVEL_WARN, logNoTransformMapOrAstWithoutCode(plugin.name));
  18644. }
  18645. return previousCode;
  18646. }
  18647. ({ code, map, ast } = result);
  18648. }
  18649. else {
  18650. return previousCode;
  18651. }
  18652. // strict null check allows 'null' maps to not be pushed to the chain,
  18653. // while 'undefined' gets the missing map warning
  18654. if (map !== null) {
  18655. sourcemapChain.push(decodedSourcemap(typeof map === 'string' ? JSON.parse(map) : map) || {
  18656. missing: true,
  18657. plugin: plugin.name
  18658. });
  18659. }
  18660. currentSource = code;
  18661. return code;
  18662. }
  18663. const getLogHandler = (handler) => (log, pos) => {
  18664. log = normalizeLog(log);
  18665. if (pos)
  18666. augmentCodeLocation(log, pos, currentSource, id);
  18667. log.id = id;
  18668. log.hook = 'transform';
  18669. handler(log);
  18670. };
  18671. let code;
  18672. try {
  18673. code = await pluginDriver.hookReduceArg0('transform', [currentSource, id], transformReducer, (pluginContext, plugin) => {
  18674. pluginName = plugin.name;
  18675. return {
  18676. ...pluginContext,
  18677. addWatchFile(id) {
  18678. transformDependencies.push(id);
  18679. pluginContext.addWatchFile(id);
  18680. },
  18681. cache: customTransformCache
  18682. ? pluginContext.cache
  18683. : getTrackedPluginCache(pluginContext.cache, useCustomTransformCache),
  18684. debug: getLogHandler(pluginContext.debug),
  18685. emitFile(emittedFile) {
  18686. emittedFiles.push(emittedFile);
  18687. return pluginDriver.emitFile(emittedFile);
  18688. },
  18689. error(error_, pos) {
  18690. if (typeof error_ === 'string')
  18691. error_ = { message: error_ };
  18692. if (pos)
  18693. augmentCodeLocation(error_, pos, currentSource, id);
  18694. error_.id = id;
  18695. error_.hook = 'transform';
  18696. return pluginContext.error(error_);
  18697. },
  18698. getCombinedSourcemap() {
  18699. const combinedMap = collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, log);
  18700. if (!combinedMap) {
  18701. const magicString = new MagicString(originalCode);
  18702. return magicString.generateMap({ hires: true, includeContent: true, source: id });
  18703. }
  18704. if (originalSourcemap !== combinedMap) {
  18705. originalSourcemap = combinedMap;
  18706. sourcemapChain.length = 0;
  18707. }
  18708. return new SourceMap({
  18709. ...combinedMap,
  18710. file: null,
  18711. sourcesContent: combinedMap.sourcesContent
  18712. });
  18713. },
  18714. info: getLogHandler(pluginContext.info),
  18715. setAssetSource() {
  18716. return this.error(logInvalidSetAssetSourceCall());
  18717. },
  18718. warn: getLogHandler(pluginContext.warn)
  18719. };
  18720. });
  18721. }
  18722. catch (error_) {
  18723. return error(logPluginError(error_, pluginName, { hook: 'transform', id }));
  18724. }
  18725. if (!customTransformCache && // files emitted by a transform hook need to be emitted again if the hook is skipped
  18726. emittedFiles.length > 0)
  18727. module.transformFiles = emittedFiles;
  18728. return {
  18729. ast,
  18730. code,
  18731. customTransformCache,
  18732. originalCode,
  18733. originalSourcemap,
  18734. sourcemapChain,
  18735. transformDependencies
  18736. };
  18737. }
  18738. const RESOLVE_DEPENDENCIES = 'resolveDependencies';
  18739. class ModuleLoader {
  18740. constructor(graph, modulesById, options, pluginDriver) {
  18741. this.graph = graph;
  18742. this.modulesById = modulesById;
  18743. this.options = options;
  18744. this.pluginDriver = pluginDriver;
  18745. this.implicitEntryModules = new Set();
  18746. this.indexedEntryModules = [];
  18747. this.latestLoadModulesPromise = Promise.resolve();
  18748. this.moduleLoadPromises = new Map();
  18749. this.modulesWithLoadedDependencies = new Set();
  18750. this.nextChunkNamePriority = 0;
  18751. this.nextEntryModuleIndex = 0;
  18752. this.resolveId = async (source, importer, customOptions, isEntry, attributes, skip = null) => this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(this.options.external(source, importer, false)
  18753. ? false
  18754. : await resolveId(source, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, skip, customOptions, typeof isEntry === 'boolean' ? isEntry : !importer, attributes), importer, source), attributes);
  18755. this.hasModuleSideEffects = options.treeshake
  18756. ? options.treeshake.moduleSideEffects
  18757. : () => true;
  18758. }
  18759. async addAdditionalModules(unresolvedModules, isAddForManualChunks) {
  18760. const result = this.extendLoadModulesPromise(Promise.all(unresolvedModules.map(id => this.loadEntryModule(id, false, undefined, null, isAddForManualChunks))));
  18761. await this.awaitLoadModulesPromise();
  18762. return result;
  18763. }
  18764. async addEntryModules(unresolvedEntryModules, isUserDefined) {
  18765. const firstEntryModuleIndex = this.nextEntryModuleIndex;
  18766. this.nextEntryModuleIndex += unresolvedEntryModules.length;
  18767. const firstChunkNamePriority = this.nextChunkNamePriority;
  18768. this.nextChunkNamePriority += unresolvedEntryModules.length;
  18769. const newEntryModules = await this.extendLoadModulesPromise(Promise.all(unresolvedEntryModules.map(({ id, importer }) => this.loadEntryModule(id, true, importer, null))).then(entryModules => {
  18770. for (const [index, entryModule] of entryModules.entries()) {
  18771. entryModule.isUserDefinedEntryPoint =
  18772. entryModule.isUserDefinedEntryPoint || isUserDefined;
  18773. addChunkNamesToModule(entryModule, unresolvedEntryModules[index], isUserDefined, firstChunkNamePriority + index);
  18774. const existingIndexedModule = this.indexedEntryModules.find(indexedModule => indexedModule.module === entryModule);
  18775. if (existingIndexedModule) {
  18776. existingIndexedModule.index = Math.min(existingIndexedModule.index, firstEntryModuleIndex + index);
  18777. }
  18778. else {
  18779. this.indexedEntryModules.push({
  18780. index: firstEntryModuleIndex + index,
  18781. module: entryModule
  18782. });
  18783. }
  18784. }
  18785. this.indexedEntryModules.sort(({ index: indexA }, { index: indexB }) => indexA > indexB ? 1 : -1);
  18786. return entryModules;
  18787. }));
  18788. await this.awaitLoadModulesPromise();
  18789. return {
  18790. entryModules: this.indexedEntryModules.map(({ module }) => module),
  18791. implicitEntryModules: [...this.implicitEntryModules],
  18792. newEntryModules
  18793. };
  18794. }
  18795. async emitChunk({ fileName, id, importer, name, implicitlyLoadedAfterOneOf, preserveSignature }) {
  18796. const unresolvedModule = {
  18797. fileName: fileName || null,
  18798. id,
  18799. importer,
  18800. name: name || null
  18801. };
  18802. const module = implicitlyLoadedAfterOneOf
  18803. ? await this.addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfterOneOf)
  18804. : (await this.addEntryModules([unresolvedModule], false)).newEntryModules[0];
  18805. if (preserveSignature != null) {
  18806. module.preserveSignature = preserveSignature;
  18807. }
  18808. return module;
  18809. }
  18810. async preloadModule(resolvedId) {
  18811. const module = await this.fetchModule(this.getResolvedIdWithDefaults(resolvedId, EMPTY_OBJECT), undefined, false, resolvedId.resolveDependencies ? RESOLVE_DEPENDENCIES : true);
  18812. return module.info;
  18813. }
  18814. addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfter) {
  18815. const chunkNamePriority = this.nextChunkNamePriority++;
  18816. return this.extendLoadModulesPromise(this.loadEntryModule(unresolvedModule.id, false, unresolvedModule.importer, null).then(async (entryModule) => {
  18817. addChunkNamesToModule(entryModule, unresolvedModule, false, chunkNamePriority);
  18818. if (!entryModule.info.isEntry) {
  18819. const implicitlyLoadedAfterModules = await Promise.all(implicitlyLoadedAfter.map(id => this.loadEntryModule(id, false, unresolvedModule.importer, entryModule.id)));
  18820. // We need to check again if this is still an entry module as these
  18821. // changes need to be performed atomically to avoid race conditions
  18822. // if the same module is re-emitted as an entry module.
  18823. // The inverse changes happen in "handleExistingModule"
  18824. if (!entryModule.info.isEntry) {
  18825. this.implicitEntryModules.add(entryModule);
  18826. for (const module of implicitlyLoadedAfterModules) {
  18827. entryModule.implicitlyLoadedAfter.add(module);
  18828. }
  18829. for (const dependant of entryModule.implicitlyLoadedAfter) {
  18830. dependant.implicitlyLoadedBefore.add(entryModule);
  18831. }
  18832. }
  18833. }
  18834. return entryModule;
  18835. }));
  18836. }
  18837. async addModuleSource(id, importer, module) {
  18838. let source;
  18839. try {
  18840. source = await this.graph.fileOperationQueue.run(async () => {
  18841. const content = await this.pluginDriver.hookFirst('load', [id]);
  18842. if (content !== null)
  18843. return content;
  18844. this.graph.watchFiles[id] = true;
  18845. return await readFile(id, 'utf8');
  18846. });
  18847. }
  18848. catch (error_) {
  18849. let message = `Could not load ${id}`;
  18850. if (importer)
  18851. message += ` (imported by ${relativeId(importer)})`;
  18852. message += `: ${error_.message}`;
  18853. error_.message = message;
  18854. throw error_;
  18855. }
  18856. const sourceDescription = typeof source === 'string'
  18857. ? { code: source }
  18858. : source != null && typeof source === 'object' && typeof source.code === 'string'
  18859. ? source
  18860. : error(logBadLoader(id));
  18861. const code = sourceDescription.code;
  18862. if (code.charCodeAt(0) === 0xfe_ff) {
  18863. sourceDescription.code = code.slice(1);
  18864. }
  18865. const cachedModule = this.graph.cachedModules.get(id);
  18866. if (cachedModule &&
  18867. !cachedModule.customTransformCache &&
  18868. cachedModule.originalCode === sourceDescription.code &&
  18869. !(await this.pluginDriver.hookFirst('shouldTransformCachedModule', [
  18870. {
  18871. ast: cachedModule.ast,
  18872. code: cachedModule.code,
  18873. id: cachedModule.id,
  18874. meta: cachedModule.meta,
  18875. moduleSideEffects: cachedModule.moduleSideEffects,
  18876. resolvedSources: cachedModule.resolvedIds,
  18877. syntheticNamedExports: cachedModule.syntheticNamedExports
  18878. }
  18879. ]))) {
  18880. if (cachedModule.transformFiles) {
  18881. for (const emittedFile of cachedModule.transformFiles)
  18882. this.pluginDriver.emitFile(emittedFile);
  18883. }
  18884. await module.setSource(cachedModule);
  18885. }
  18886. else {
  18887. module.updateOptions(sourceDescription);
  18888. await module.setSource(await transform(sourceDescription, module, this.pluginDriver, this.options.onLog));
  18889. }
  18890. }
  18891. async awaitLoadModulesPromise() {
  18892. let startingPromise;
  18893. do {
  18894. startingPromise = this.latestLoadModulesPromise;
  18895. await startingPromise;
  18896. } while (startingPromise !== this.latestLoadModulesPromise);
  18897. }
  18898. extendLoadModulesPromise(loadNewModulesPromise) {
  18899. this.latestLoadModulesPromise = Promise.all([
  18900. loadNewModulesPromise,
  18901. this.latestLoadModulesPromise
  18902. ]);
  18903. this.latestLoadModulesPromise.catch(() => {
  18904. /* Avoid unhandled Promise rejections */
  18905. });
  18906. return loadNewModulesPromise;
  18907. }
  18908. async fetchDynamicDependencies(module, resolveDynamicImportPromises) {
  18909. const dependencies = await Promise.all(resolveDynamicImportPromises.map(resolveDynamicImportPromise => resolveDynamicImportPromise.then(async ([dynamicImport, resolvedId]) => {
  18910. if (resolvedId === null)
  18911. return null;
  18912. if (typeof resolvedId === 'string') {
  18913. dynamicImport.resolution = resolvedId;
  18914. return null;
  18915. }
  18916. return (dynamicImport.resolution = await this.fetchResolvedDependency(relativeId(resolvedId.id), module.id, resolvedId));
  18917. })));
  18918. for (const dependency of dependencies) {
  18919. if (dependency) {
  18920. module.dynamicDependencies.add(dependency);
  18921. dependency.dynamicImporters.push(module.id);
  18922. }
  18923. }
  18924. }
  18925. // If this is a preload, then this method always waits for the dependencies of
  18926. // the module to be resolved.
  18927. // Otherwise, if the module does not exist, it waits for the module and all
  18928. // its dependencies to be loaded.
  18929. // Otherwise, it returns immediately.
  18930. async fetchModule({ attributes, id, meta, moduleSideEffects, syntheticNamedExports }, importer, isEntry, isPreload) {
  18931. const existingModule = this.modulesById.get(id);
  18932. if (existingModule instanceof Module) {
  18933. if (importer && doAttributesDiffer(attributes, existingModule.info.attributes)) {
  18934. this.options.onLog(LOGLEVEL_WARN, logInconsistentImportAttributes(existingModule.info.attributes, attributes, id, importer));
  18935. }
  18936. await this.handleExistingModule(existingModule, isEntry, isPreload);
  18937. return existingModule;
  18938. }
  18939. if (existingModule instanceof ExternalModule) {
  18940. return error(logExternalModulesCannotBeTransformedToModules(existingModule.id));
  18941. }
  18942. const module = new Module(this.graph, id, this.options, isEntry, moduleSideEffects, syntheticNamedExports, meta, attributes);
  18943. this.modulesById.set(id, module);
  18944. const loadPromise = this.addModuleSource(id, importer, module).then(() => [
  18945. this.getResolveStaticDependencyPromises(module),
  18946. this.getResolveDynamicImportPromises(module),
  18947. loadAndResolveDependenciesPromise
  18948. ]);
  18949. const loadAndResolveDependenciesPromise = waitForDependencyResolution(loadPromise).then(() => this.pluginDriver.hookParallel('moduleParsed', [module.info]));
  18950. loadAndResolveDependenciesPromise.catch(() => {
  18951. /* avoid unhandled promise rejections */
  18952. });
  18953. this.moduleLoadPromises.set(module, loadPromise);
  18954. const resolveDependencyPromises = await loadPromise;
  18955. if (!isPreload) {
  18956. await this.fetchModuleDependencies(module, ...resolveDependencyPromises);
  18957. }
  18958. else if (isPreload === RESOLVE_DEPENDENCIES) {
  18959. await loadAndResolveDependenciesPromise;
  18960. }
  18961. return module;
  18962. }
  18963. async fetchModuleDependencies(module, resolveStaticDependencyPromises, resolveDynamicDependencyPromises, loadAndResolveDependenciesPromise) {
  18964. if (this.modulesWithLoadedDependencies.has(module)) {
  18965. return;
  18966. }
  18967. this.modulesWithLoadedDependencies.add(module);
  18968. await Promise.all([
  18969. this.fetchStaticDependencies(module, resolveStaticDependencyPromises),
  18970. this.fetchDynamicDependencies(module, resolveDynamicDependencyPromises)
  18971. ]);
  18972. module.linkImports();
  18973. // To handle errors when resolving dependencies or in moduleParsed
  18974. await loadAndResolveDependenciesPromise;
  18975. }
  18976. fetchResolvedDependency(source, importer, resolvedId) {
  18977. if (resolvedId.external) {
  18978. const { attributes, external, id, moduleSideEffects, meta } = resolvedId;
  18979. let externalModule = this.modulesById.get(id);
  18980. if (!externalModule) {
  18981. externalModule = new ExternalModule(this.options, id, moduleSideEffects, meta, external !== 'absolute' && isAbsolute$1(id), attributes);
  18982. this.modulesById.set(id, externalModule);
  18983. }
  18984. else if (!(externalModule instanceof ExternalModule)) {
  18985. return error(logInternalIdCannotBeExternal(source, importer));
  18986. }
  18987. else if (doAttributesDiffer(externalModule.info.attributes, attributes)) {
  18988. this.options.onLog(LOGLEVEL_WARN, logInconsistentImportAttributes(externalModule.info.attributes, attributes, source, importer));
  18989. }
  18990. return Promise.resolve(externalModule);
  18991. }
  18992. return this.fetchModule(resolvedId, importer, false, false);
  18993. }
  18994. async fetchStaticDependencies(module, resolveStaticDependencyPromises) {
  18995. for (const dependency of await Promise.all(resolveStaticDependencyPromises.map(resolveStaticDependencyPromise => resolveStaticDependencyPromise.then(([source, resolvedId]) => this.fetchResolvedDependency(source, module.id, resolvedId))))) {
  18996. module.dependencies.add(dependency);
  18997. dependency.importers.push(module.id);
  18998. }
  18999. if (!this.options.treeshake || module.info.moduleSideEffects === 'no-treeshake') {
  19000. for (const dependency of module.dependencies) {
  19001. if (dependency instanceof Module) {
  19002. dependency.importedFromNotTreeshaken = true;
  19003. }
  19004. }
  19005. }
  19006. }
  19007. getNormalizedResolvedIdWithoutDefaults(resolveIdResult, importer, source) {
  19008. const { makeAbsoluteExternalsRelative } = this.options;
  19009. if (resolveIdResult) {
  19010. if (typeof resolveIdResult === 'object') {
  19011. const external = resolveIdResult.external || this.options.external(resolveIdResult.id, importer, true);
  19012. return {
  19013. ...resolveIdResult,
  19014. external: external &&
  19015. (external === 'relative' ||
  19016. !isAbsolute$1(resolveIdResult.id) ||
  19017. (external === true &&
  19018. isNotAbsoluteExternal(resolveIdResult.id, source, makeAbsoluteExternalsRelative)) ||
  19019. 'absolute')
  19020. };
  19021. }
  19022. const external = this.options.external(resolveIdResult, importer, true);
  19023. return {
  19024. external: external &&
  19025. (isNotAbsoluteExternal(resolveIdResult, source, makeAbsoluteExternalsRelative) ||
  19026. 'absolute'),
  19027. id: external && makeAbsoluteExternalsRelative
  19028. ? normalizeRelativeExternalId(resolveIdResult, importer)
  19029. : resolveIdResult
  19030. };
  19031. }
  19032. const id = makeAbsoluteExternalsRelative
  19033. ? normalizeRelativeExternalId(source, importer)
  19034. : source;
  19035. if (resolveIdResult !== false && !this.options.external(id, importer, true)) {
  19036. return null;
  19037. }
  19038. return {
  19039. external: isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) || 'absolute',
  19040. id
  19041. };
  19042. }
  19043. getResolveDynamicImportPromises(module) {
  19044. return module.dynamicImports.map(async (dynamicImport) => {
  19045. const resolvedId = await this.resolveDynamicImport(module, dynamicImport.argument, module.id, getAttributesFromImportExpression(dynamicImport.node));
  19046. if (resolvedId && typeof resolvedId === 'object') {
  19047. dynamicImport.id = resolvedId.id;
  19048. }
  19049. return [dynamicImport, resolvedId];
  19050. });
  19051. }
  19052. getResolveStaticDependencyPromises(module) {
  19053. return Array.from(module.sourcesWithAttributes, async ([source, attributes]) => [
  19054. source,
  19055. (module.resolvedIds[source] =
  19056. module.resolvedIds[source] ||
  19057. this.handleInvalidResolvedId(await this.resolveId(source, module.id, EMPTY_OBJECT, false, attributes), source, module.id, attributes))
  19058. ]);
  19059. }
  19060. getResolvedIdWithDefaults(resolvedId, attributes) {
  19061. if (!resolvedId) {
  19062. return null;
  19063. }
  19064. const external = resolvedId.external || false;
  19065. return {
  19066. attributes: resolvedId.attributes || attributes,
  19067. external,
  19068. id: resolvedId.id,
  19069. meta: resolvedId.meta || {},
  19070. moduleSideEffects: resolvedId.moduleSideEffects ?? this.hasModuleSideEffects(resolvedId.id, !!external),
  19071. resolvedBy: resolvedId.resolvedBy ?? 'rollup',
  19072. syntheticNamedExports: resolvedId.syntheticNamedExports ?? false
  19073. };
  19074. }
  19075. async handleExistingModule(module, isEntry, isPreload) {
  19076. const loadPromise = this.moduleLoadPromises.get(module);
  19077. if (isPreload) {
  19078. return isPreload === RESOLVE_DEPENDENCIES
  19079. ? waitForDependencyResolution(loadPromise)
  19080. : loadPromise;
  19081. }
  19082. if (isEntry) {
  19083. // This reverts the changes in addEntryWithImplicitDependants and needs to
  19084. // be performed atomically
  19085. module.info.isEntry = true;
  19086. this.implicitEntryModules.delete(module);
  19087. for (const dependant of module.implicitlyLoadedAfter) {
  19088. dependant.implicitlyLoadedBefore.delete(module);
  19089. }
  19090. module.implicitlyLoadedAfter.clear();
  19091. }
  19092. return this.fetchModuleDependencies(module, ...(await loadPromise));
  19093. }
  19094. handleInvalidResolvedId(resolvedId, source, importer, attributes) {
  19095. if (resolvedId === null) {
  19096. if (isRelative(source)) {
  19097. return error(logUnresolvedImport(source, importer));
  19098. }
  19099. this.options.onLog(LOGLEVEL_WARN, logUnresolvedImportTreatedAsExternal(source, importer));
  19100. return {
  19101. attributes,
  19102. external: true,
  19103. id: source,
  19104. meta: {},
  19105. moduleSideEffects: this.hasModuleSideEffects(source, true),
  19106. resolvedBy: 'rollup',
  19107. syntheticNamedExports: false
  19108. };
  19109. }
  19110. else if (resolvedId.external && resolvedId.syntheticNamedExports) {
  19111. this.options.onLog(LOGLEVEL_WARN, logExternalSyntheticExports(source, importer));
  19112. }
  19113. return resolvedId;
  19114. }
  19115. async loadEntryModule(unresolvedId, isEntry, importer, implicitlyLoadedBefore, isLoadForManualChunks = false) {
  19116. const resolveIdResult = await resolveId(unresolvedId, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, null, EMPTY_OBJECT, true, EMPTY_OBJECT);
  19117. if (resolveIdResult == null) {
  19118. return error(implicitlyLoadedBefore === null
  19119. ? logUnresolvedEntry(unresolvedId)
  19120. : logUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore));
  19121. }
  19122. const isExternalModules = typeof resolveIdResult === 'object' && resolveIdResult.external;
  19123. if (resolveIdResult === false || isExternalModules) {
  19124. return error(implicitlyLoadedBefore === null
  19125. ? isExternalModules && isLoadForManualChunks
  19126. ? logExternalModulesCannotBeIncludedInManualChunks(unresolvedId)
  19127. : logEntryCannotBeExternal(unresolvedId)
  19128. : logImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore));
  19129. }
  19130. return this.fetchModule(this.getResolvedIdWithDefaults(typeof resolveIdResult === 'object'
  19131. ? resolveIdResult
  19132. : { id: resolveIdResult }, EMPTY_OBJECT), undefined, isEntry, false);
  19133. }
  19134. async resolveDynamicImport(module, specifier, importer, attributes) {
  19135. const resolution = await this.pluginDriver.hookFirst('resolveDynamicImport', [
  19136. specifier,
  19137. importer,
  19138. { attributes }
  19139. ]);
  19140. if (typeof specifier !== 'string') {
  19141. if (typeof resolution === 'string') {
  19142. return resolution;
  19143. }
  19144. if (!resolution) {
  19145. return null;
  19146. }
  19147. return this.getResolvedIdWithDefaults(resolution, attributes);
  19148. }
  19149. if (resolution == null) {
  19150. const existingResolution = module.resolvedIds[specifier];
  19151. if (existingResolution) {
  19152. if (doAttributesDiffer(existingResolution.attributes, attributes)) {
  19153. this.options.onLog(LOGLEVEL_WARN, logInconsistentImportAttributes(existingResolution.attributes, attributes, specifier, importer));
  19154. }
  19155. return existingResolution;
  19156. }
  19157. return (module.resolvedIds[specifier] = this.handleInvalidResolvedId(await this.resolveId(specifier, module.id, EMPTY_OBJECT, false, attributes), specifier, module.id, attributes));
  19158. }
  19159. return this.handleInvalidResolvedId(this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(resolution, importer, specifier), attributes), specifier, importer, attributes);
  19160. }
  19161. }
  19162. function normalizeRelativeExternalId(source, importer) {
  19163. return isRelative(source)
  19164. ? importer
  19165. ? resolve$1(importer, '..', source)
  19166. : resolve$1(source)
  19167. : source;
  19168. }
  19169. function addChunkNamesToModule(module, { fileName, name }, isUserDefined, priority) {
  19170. if (fileName !== null) {
  19171. module.chunkFileNames.add(fileName);
  19172. }
  19173. else if (name !== null) {
  19174. // Always keep chunkNames sorted by priority
  19175. let namePosition = 0;
  19176. while (module.chunkNames[namePosition]?.priority < priority)
  19177. namePosition++;
  19178. module.chunkNames.splice(namePosition, 0, { isUserDefined, name, priority });
  19179. }
  19180. }
  19181. function isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) {
  19182. return (makeAbsoluteExternalsRelative === true ||
  19183. (makeAbsoluteExternalsRelative === 'ifRelativeSource' && isRelative(source)) ||
  19184. !isAbsolute$1(id));
  19185. }
  19186. async function waitForDependencyResolution(loadPromise) {
  19187. const [resolveStaticDependencyPromises, resolveDynamicImportPromises] = await loadPromise;
  19188. return Promise.all([...resolveStaticDependencyPromises, ...resolveDynamicImportPromises]);
  19189. }
  19190. function generateAssetFileName(name, names, source, originalFileName, originalFileNames, sourceHash, outputOptions, bundle, inputOptions) {
  19191. const emittedName = outputOptions.sanitizeFileName(name || 'asset');
  19192. return makeUnique(renderNamePattern(typeof outputOptions.assetFileNames === 'function'
  19193. ? outputOptions.assetFileNames({
  19194. // Additionally, this should be non-enumerable in the next major
  19195. get name() {
  19196. warnDeprecation('Accessing the "name" property of emitted assets when generating the file name is deprecated. Use the "names" property instead.', URL_GENERATEBUNDLE, false, inputOptions);
  19197. return name;
  19198. },
  19199. names,
  19200. // Additionally, this should be non-enumerable in the next major
  19201. get originalFileName() {
  19202. warnDeprecation('Accessing the "originalFileName" property of emitted assets when generating the file name is deprecated. Use the "originalFileNames" property instead.', URL_GENERATEBUNDLE, false, inputOptions);
  19203. return originalFileName;
  19204. },
  19205. originalFileNames,
  19206. source,
  19207. type: 'asset'
  19208. })
  19209. : outputOptions.assetFileNames, 'output.assetFileNames', {
  19210. ext: () => extname(emittedName).slice(1),
  19211. extname: () => extname(emittedName),
  19212. hash: size => sourceHash.slice(0, Math.max(0, size || DEFAULT_HASH_SIZE)),
  19213. name: () => emittedName.slice(0, Math.max(0, emittedName.length - extname(emittedName).length))
  19214. }), bundle);
  19215. }
  19216. function reserveFileNameInBundle(fileName, { bundle }, log) {
  19217. if (bundle[lowercaseBundleKeys].has(fileName.toLowerCase())) {
  19218. log(LOGLEVEL_WARN, logFileNameConflict(fileName));
  19219. }
  19220. else {
  19221. bundle[fileName] = FILE_PLACEHOLDER;
  19222. }
  19223. }
  19224. const emittedFileTypes = new Set(['chunk', 'asset', 'prebuilt-chunk']);
  19225. function hasValidType(emittedFile) {
  19226. return Boolean(emittedFile &&
  19227. emittedFileTypes.has(emittedFile.type));
  19228. }
  19229. function hasValidName(emittedFile) {
  19230. const validatedName = emittedFile.fileName || emittedFile.name;
  19231. return !validatedName || (typeof validatedName === 'string' && !isPathFragment(validatedName));
  19232. }
  19233. function getValidSource(source, emittedFile, fileReferenceId) {
  19234. if (!(typeof source === 'string' || source instanceof Uint8Array)) {
  19235. const assetName = emittedFile.fileName || emittedFile.name || fileReferenceId;
  19236. 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.`));
  19237. }
  19238. return source;
  19239. }
  19240. function getAssetFileName(file, referenceId) {
  19241. if (typeof file.fileName !== 'string') {
  19242. return error(logAssetNotFinalisedForFileName(file.name || referenceId));
  19243. }
  19244. return file.fileName;
  19245. }
  19246. function getChunkFileName(file, facadeChunkByModule) {
  19247. if (file.fileName) {
  19248. return file.fileName;
  19249. }
  19250. if (facadeChunkByModule) {
  19251. return facadeChunkByModule.get(file.module).getFileName();
  19252. }
  19253. return error(logChunkNotGeneratedForFileName(file.fileName || file.name));
  19254. }
  19255. class FileEmitter {
  19256. constructor(graph, options, baseFileEmitter) {
  19257. this.graph = graph;
  19258. this.options = options;
  19259. this.facadeChunkByModule = null;
  19260. this.nextIdBase = 1;
  19261. this.output = null;
  19262. this.outputFileEmitters = [];
  19263. this.emitFile = (emittedFile) => {
  19264. if (!hasValidType(emittedFile)) {
  19265. return error(logFailedValidation(`Emitted files must be of type "asset", "chunk" or "prebuilt-chunk", received "${emittedFile && emittedFile.type}".`));
  19266. }
  19267. if (emittedFile.type === 'prebuilt-chunk') {
  19268. return this.emitPrebuiltChunk(emittedFile);
  19269. }
  19270. if (!hasValidName(emittedFile)) {
  19271. 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}".`));
  19272. }
  19273. if (emittedFile.type === 'chunk') {
  19274. return this.emitChunk(emittedFile);
  19275. }
  19276. return this.emitAsset(emittedFile);
  19277. };
  19278. this.finaliseAssets = () => {
  19279. for (const [referenceId, emittedFile] of this.filesByReferenceId) {
  19280. if (emittedFile.type === 'asset' && typeof emittedFile.fileName !== 'string')
  19281. return error(logNoAssetSourceSet(emittedFile.name || referenceId));
  19282. }
  19283. };
  19284. this.getFileName = (fileReferenceId) => {
  19285. const emittedFile = this.filesByReferenceId.get(fileReferenceId);
  19286. if (!emittedFile)
  19287. return error(logFileReferenceIdNotFoundForFilename(fileReferenceId));
  19288. if (emittedFile.type === 'chunk') {
  19289. return getChunkFileName(emittedFile, this.facadeChunkByModule);
  19290. }
  19291. if (emittedFile.type === 'prebuilt-chunk') {
  19292. return emittedFile.fileName;
  19293. }
  19294. return getAssetFileName(emittedFile, fileReferenceId);
  19295. };
  19296. this.setAssetSource = (referenceId, requestedSource) => {
  19297. const consumedFile = this.filesByReferenceId.get(referenceId);
  19298. if (!consumedFile)
  19299. return error(logAssetReferenceIdNotFoundForSetSource(referenceId));
  19300. if (consumedFile.type !== 'asset') {
  19301. return error(logFailedValidation(`Asset sources can only be set for emitted assets but "${referenceId}" is an emitted chunk.`));
  19302. }
  19303. if (consumedFile.source !== undefined) {
  19304. return error(logAssetSourceAlreadySet(consumedFile.name || referenceId));
  19305. }
  19306. const source = getValidSource(requestedSource, consumedFile, referenceId);
  19307. if (this.output) {
  19308. this.finalizeAdditionalAsset(consumedFile, source, this.output);
  19309. }
  19310. else {
  19311. consumedFile.source = source;
  19312. for (const emitter of this.outputFileEmitters) {
  19313. emitter.finalizeAdditionalAsset(consumedFile, source, emitter.output);
  19314. }
  19315. }
  19316. };
  19317. this.setChunkInformation = (facadeChunkByModule) => {
  19318. this.facadeChunkByModule = facadeChunkByModule;
  19319. };
  19320. this.setOutputBundle = (bundle, outputOptions) => {
  19321. const getHash = hasherByType[outputOptions.hashCharacters];
  19322. const output = (this.output = {
  19323. bundle,
  19324. fileNamesBySourceHash: new Map(),
  19325. getHash,
  19326. outputOptions
  19327. });
  19328. for (const emittedFile of this.filesByReferenceId.values()) {
  19329. if (emittedFile.fileName) {
  19330. reserveFileNameInBundle(emittedFile.fileName, output, this.options.onLog);
  19331. }
  19332. }
  19333. const consumedAssetsByHash = new Map();
  19334. for (const consumedFile of this.filesByReferenceId.values()) {
  19335. if (consumedFile.type === 'asset' && consumedFile.source !== undefined) {
  19336. if (consumedFile.fileName) {
  19337. this.finalizeAdditionalAsset(consumedFile, consumedFile.source, output);
  19338. }
  19339. else {
  19340. const sourceHash = getHash(consumedFile.source);
  19341. getOrCreate(consumedAssetsByHash, sourceHash, () => []).push(consumedFile);
  19342. }
  19343. }
  19344. else if (consumedFile.type === 'prebuilt-chunk') {
  19345. this.output.bundle[consumedFile.fileName] = this.createPrebuiltChunk(consumedFile);
  19346. }
  19347. }
  19348. for (const [sourceHash, consumedFiles] of consumedAssetsByHash) {
  19349. this.finalizeAssetsWithSameSource(consumedFiles, sourceHash, output);
  19350. }
  19351. };
  19352. this.filesByReferenceId = baseFileEmitter
  19353. ? new Map(baseFileEmitter.filesByReferenceId)
  19354. : new Map();
  19355. baseFileEmitter?.addOutputFileEmitter(this);
  19356. }
  19357. addOutputFileEmitter(outputFileEmitter) {
  19358. this.outputFileEmitters.push(outputFileEmitter);
  19359. }
  19360. assignReferenceId(file, idBase) {
  19361. let referenceId = idBase;
  19362. do {
  19363. referenceId = getHash64(referenceId).slice(0, 8).replaceAll('-', '$');
  19364. } while (this.filesByReferenceId.has(referenceId) ||
  19365. this.outputFileEmitters.some(({ filesByReferenceId }) => filesByReferenceId.has(referenceId)));
  19366. file.referenceId = referenceId;
  19367. this.filesByReferenceId.set(referenceId, file);
  19368. for (const { filesByReferenceId } of this.outputFileEmitters) {
  19369. filesByReferenceId.set(referenceId, file);
  19370. }
  19371. return referenceId;
  19372. }
  19373. createPrebuiltChunk(prebuiltChunk) {
  19374. return {
  19375. code: prebuiltChunk.code,
  19376. dynamicImports: [],
  19377. exports: prebuiltChunk.exports || [],
  19378. facadeModuleId: null,
  19379. fileName: prebuiltChunk.fileName,
  19380. implicitlyLoadedBefore: [],
  19381. importedBindings: {},
  19382. imports: [],
  19383. isDynamicEntry: false,
  19384. isEntry: false,
  19385. isImplicitEntry: false,
  19386. map: prebuiltChunk.map || null,
  19387. moduleIds: [],
  19388. modules: {},
  19389. name: prebuiltChunk.fileName,
  19390. preliminaryFileName: prebuiltChunk.fileName,
  19391. referencedFiles: [],
  19392. sourcemapFileName: prebuiltChunk.sourcemapFileName || null,
  19393. type: 'chunk'
  19394. };
  19395. }
  19396. emitAsset(emittedAsset) {
  19397. const source = emittedAsset.source === undefined
  19398. ? undefined
  19399. : getValidSource(emittedAsset.source, emittedAsset, null);
  19400. const originalFileName = emittedAsset.originalFileName || null;
  19401. if (typeof originalFileName === 'string') {
  19402. this.graph.watchFiles[originalFileName] = true;
  19403. }
  19404. const consumedAsset = {
  19405. fileName: emittedAsset.fileName,
  19406. name: emittedAsset.name,
  19407. needsCodeReference: !!emittedAsset.needsCodeReference,
  19408. originalFileName,
  19409. referenceId: '',
  19410. source,
  19411. type: 'asset'
  19412. };
  19413. const referenceId = this.assignReferenceId(consumedAsset, emittedAsset.fileName || emittedAsset.name || String(this.nextIdBase++));
  19414. if (this.output) {
  19415. this.emitAssetWithReferenceId(consumedAsset, this.output);
  19416. }
  19417. else {
  19418. for (const fileEmitter of this.outputFileEmitters) {
  19419. fileEmitter.emitAssetWithReferenceId(consumedAsset, fileEmitter.output);
  19420. }
  19421. }
  19422. return referenceId;
  19423. }
  19424. emitAssetWithReferenceId(consumedAsset, output) {
  19425. const { fileName, source } = consumedAsset;
  19426. if (fileName) {
  19427. reserveFileNameInBundle(fileName, output, this.options.onLog);
  19428. }
  19429. if (source !== undefined) {
  19430. this.finalizeAdditionalAsset(consumedAsset, source, output);
  19431. }
  19432. }
  19433. emitChunk(emittedChunk) {
  19434. if (this.graph.phase > BuildPhase.LOAD_AND_PARSE) {
  19435. return error(logInvalidRollupPhaseForChunkEmission());
  19436. }
  19437. if (typeof emittedChunk.id !== 'string') {
  19438. return error(logFailedValidation(`Emitted chunks need to have a valid string id, received "${emittedChunk.id}"`));
  19439. }
  19440. const consumedChunk = {
  19441. fileName: emittedChunk.fileName,
  19442. module: null,
  19443. name: emittedChunk.name || emittedChunk.id,
  19444. referenceId: '',
  19445. type: 'chunk'
  19446. };
  19447. this.graph.moduleLoader
  19448. .emitChunk(emittedChunk)
  19449. .then(module => (consumedChunk.module = module))
  19450. .catch(() => {
  19451. // Avoid unhandled Promise rejection as the error will be thrown later
  19452. // once module loading has finished
  19453. });
  19454. return this.assignReferenceId(consumedChunk, emittedChunk.id);
  19455. }
  19456. emitPrebuiltChunk(emitPrebuiltChunk) {
  19457. if (typeof emitPrebuiltChunk.code !== 'string') {
  19458. return error(logFailedValidation(`Emitted prebuilt chunks need to have a valid string code, received "${emitPrebuiltChunk.code}".`));
  19459. }
  19460. if (typeof emitPrebuiltChunk.fileName !== 'string' ||
  19461. isPathFragment(emitPrebuiltChunk.fileName)) {
  19462. return error(logFailedValidation(`The "fileName" property of emitted prebuilt chunks must be strings that are neither absolute nor relative paths, received "${emitPrebuiltChunk.fileName}".`));
  19463. }
  19464. const consumedPrebuiltChunk = {
  19465. code: emitPrebuiltChunk.code,
  19466. exports: emitPrebuiltChunk.exports,
  19467. fileName: emitPrebuiltChunk.fileName,
  19468. map: emitPrebuiltChunk.map,
  19469. referenceId: '',
  19470. type: 'prebuilt-chunk'
  19471. };
  19472. const referenceId = this.assignReferenceId(consumedPrebuiltChunk, consumedPrebuiltChunk.fileName);
  19473. if (this.output) {
  19474. this.output.bundle[consumedPrebuiltChunk.fileName] =
  19475. this.createPrebuiltChunk(consumedPrebuiltChunk);
  19476. }
  19477. return referenceId;
  19478. }
  19479. finalizeAdditionalAsset(consumedFile, source, { bundle, fileNamesBySourceHash, getHash, outputOptions }) {
  19480. let { fileName, name, needsCodeReference, originalFileName, referenceId } = consumedFile;
  19481. // Deduplicate assets if an explicit fileName is not provided
  19482. if (!fileName) {
  19483. const sourceHash = getHash(source);
  19484. fileName = fileNamesBySourceHash.get(sourceHash);
  19485. if (!fileName) {
  19486. fileName = generateAssetFileName(name, name ? [name] : [], source, originalFileName, originalFileName ? [originalFileName] : [], sourceHash, outputOptions, bundle, this.options);
  19487. fileNamesBySourceHash.set(sourceHash, fileName);
  19488. }
  19489. }
  19490. // We must not modify the original assets to avoid interaction between outputs
  19491. const assetWithFileName = { ...consumedFile, fileName, source };
  19492. this.filesByReferenceId.set(referenceId, assetWithFileName);
  19493. const existingAsset = bundle[fileName];
  19494. if (existingAsset?.type === 'asset') {
  19495. existingAsset.needsCodeReference &&= needsCodeReference;
  19496. if (name) {
  19497. existingAsset.names.push(name);
  19498. }
  19499. if (originalFileName) {
  19500. existingAsset.originalFileNames.push(originalFileName);
  19501. }
  19502. }
  19503. else {
  19504. const { options } = this;
  19505. bundle[fileName] = {
  19506. fileName,
  19507. get name() {
  19508. // Additionally, this should be non-enumerable in the next major
  19509. warnDeprecation('Accessing the "name" property of emitted assets in the bundle is deprecated. Use the "names" property instead.', URL_GENERATEBUNDLE, false, options);
  19510. return name;
  19511. },
  19512. names: name ? [name] : [],
  19513. needsCodeReference,
  19514. get originalFileName() {
  19515. // Additionally, this should be non-enumerable in the next major
  19516. warnDeprecation('Accessing the "originalFileName" property of emitted assets in the bundle is deprecated. Use the "originalFileNames" property instead.', URL_GENERATEBUNDLE, false, options);
  19517. return originalFileName;
  19518. },
  19519. originalFileNames: originalFileName ? [originalFileName] : [],
  19520. source,
  19521. type: 'asset'
  19522. };
  19523. }
  19524. }
  19525. finalizeAssetsWithSameSource(consumedFiles, sourceHash, { bundle, fileNamesBySourceHash, outputOptions }) {
  19526. const { names, originalFileNames } = getNamesFromAssets(consumedFiles);
  19527. let fileName = '';
  19528. let usedConsumedFile;
  19529. let needsCodeReference = true;
  19530. for (const consumedFile of consumedFiles) {
  19531. needsCodeReference &&= consumedFile.needsCodeReference;
  19532. const assetFileName = generateAssetFileName(consumedFile.name, names, consumedFile.source, consumedFile.originalFileName, originalFileNames, sourceHash, outputOptions, bundle, this.options);
  19533. if (!fileName ||
  19534. assetFileName.length < fileName.length ||
  19535. (assetFileName.length === fileName.length && assetFileName < fileName)) {
  19536. fileName = assetFileName;
  19537. usedConsumedFile = consumedFile;
  19538. }
  19539. }
  19540. fileNamesBySourceHash.set(sourceHash, fileName);
  19541. for (const consumedFile of consumedFiles) {
  19542. // We must not modify the original assets to avoid interaction between outputs
  19543. const assetWithFileName = { ...consumedFile, fileName };
  19544. this.filesByReferenceId.set(consumedFile.referenceId, assetWithFileName);
  19545. }
  19546. const { options } = this;
  19547. bundle[fileName] = {
  19548. fileName,
  19549. get name() {
  19550. // Additionally, this should be non-enumerable in the next major
  19551. warnDeprecation('Accessing the "name" property of emitted assets in the bundle is deprecated. Use the "names" property instead.', URL_GENERATEBUNDLE, false, options);
  19552. return usedConsumedFile.name;
  19553. },
  19554. names,
  19555. needsCodeReference,
  19556. get originalFileName() {
  19557. // Additionally, this should be non-enumerable in the next major
  19558. warnDeprecation('Accessing the "originalFileName" property of emitted assets in the bundle is deprecated. Use the "originalFileNames" property instead.', URL_GENERATEBUNDLE, false, options);
  19559. return usedConsumedFile.originalFileName;
  19560. },
  19561. originalFileNames,
  19562. source: usedConsumedFile.source,
  19563. type: 'asset'
  19564. };
  19565. }
  19566. }
  19567. function getNamesFromAssets(consumedFiles) {
  19568. const names = [];
  19569. const originalFileNames = [];
  19570. for (const { name, originalFileName } of consumedFiles) {
  19571. if (typeof name === 'string') {
  19572. names.push(name);
  19573. }
  19574. if (originalFileName) {
  19575. originalFileNames.push(originalFileName);
  19576. }
  19577. }
  19578. originalFileNames.sort();
  19579. // Sort by length first and then alphabetically so that the order is stable
  19580. // and the shortest names come first
  19581. names.sort((a, b) => a.length - b.length || (a > b ? 1 : a === b ? 0 : -1));
  19582. return { names, originalFileNames };
  19583. }
  19584. function getLogHandler(level, code, logger, pluginName, logLevel) {
  19585. if (logLevelPriority[level] < logLevelPriority[logLevel]) {
  19586. return doNothing;
  19587. }
  19588. return (log, pos) => {
  19589. if (pos != null) {
  19590. logger(LOGLEVEL_WARN, logInvalidLogPosition(pluginName));
  19591. }
  19592. log = normalizeLog(log);
  19593. if (log.code && !log.pluginCode) {
  19594. log.pluginCode = log.code;
  19595. }
  19596. log.code = code;
  19597. log.plugin = pluginName;
  19598. logger(level, log);
  19599. };
  19600. }
  19601. function getPluginContext(plugin, pluginCache, graph, options, fileEmitter, existingPluginNames) {
  19602. const { logLevel, onLog } = options;
  19603. let cacheable = true;
  19604. if (typeof plugin.cacheKey !== 'string') {
  19605. if (plugin.name.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  19606. plugin.name.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX) ||
  19607. existingPluginNames.has(plugin.name)) {
  19608. cacheable = false;
  19609. }
  19610. else {
  19611. existingPluginNames.add(plugin.name);
  19612. }
  19613. }
  19614. let cacheInstance;
  19615. if (!pluginCache) {
  19616. cacheInstance = NO_CACHE;
  19617. }
  19618. else if (cacheable) {
  19619. const cacheKey = plugin.cacheKey || plugin.name;
  19620. cacheInstance = createPluginCache(pluginCache[cacheKey] || (pluginCache[cacheKey] = Object.create(null)));
  19621. }
  19622. else {
  19623. cacheInstance = getCacheForUncacheablePlugin(plugin.name);
  19624. }
  19625. return {
  19626. addWatchFile(id) {
  19627. graph.watchFiles[id] = true;
  19628. },
  19629. cache: cacheInstance,
  19630. debug: getLogHandler(LOGLEVEL_DEBUG, 'PLUGIN_LOG', onLog, plugin.name, logLevel),
  19631. emitFile: fileEmitter.emitFile.bind(fileEmitter),
  19632. error(error_) {
  19633. return error(logPluginError(normalizeLog(error_), plugin.name));
  19634. },
  19635. getFileName: fileEmitter.getFileName,
  19636. getModuleIds: () => graph.modulesById.keys(),
  19637. getModuleInfo: graph.getModuleInfo,
  19638. getWatchFiles: () => Object.keys(graph.watchFiles),
  19639. info: getLogHandler(LOGLEVEL_INFO, 'PLUGIN_LOG', onLog, plugin.name, logLevel),
  19640. load(resolvedId) {
  19641. return graph.moduleLoader.preloadModule(resolvedId);
  19642. },
  19643. meta: {
  19644. rollupVersion: version,
  19645. watchMode: graph.watchMode
  19646. },
  19647. parse: parseAst,
  19648. resolve(source, importer, { attributes, custom, isEntry, skipSelf } = BLANK) {
  19649. skipSelf ??= true;
  19650. return graph.moduleLoader.resolveId(source, importer, custom, isEntry, attributes || EMPTY_OBJECT, skipSelf ? [{ importer, plugin, source }] : null);
  19651. },
  19652. setAssetSource: fileEmitter.setAssetSource,
  19653. warn: getLogHandler(LOGLEVEL_WARN, 'PLUGIN_WARNING', onLog, plugin.name, logLevel)
  19654. };
  19655. }
  19656. // This will make sure no input hook is omitted
  19657. const inputHookNames = {
  19658. buildEnd: 1,
  19659. buildStart: 1,
  19660. closeBundle: 1,
  19661. closeWatcher: 1,
  19662. load: 1,
  19663. moduleParsed: 1,
  19664. onLog: 1,
  19665. options: 1,
  19666. resolveDynamicImport: 1,
  19667. resolveId: 1,
  19668. shouldTransformCachedModule: 1,
  19669. transform: 1,
  19670. watchChange: 1
  19671. };
  19672. const inputHooks = Object.keys(inputHookNames);
  19673. class PluginDriver {
  19674. constructor(graph, options, userPlugins, pluginCache, basePluginDriver) {
  19675. this.graph = graph;
  19676. this.options = options;
  19677. this.pluginCache = pluginCache;
  19678. this.sortedPlugins = new Map();
  19679. this.unfulfilledActions = new Set();
  19680. this.fileEmitter = new FileEmitter(graph, options, basePluginDriver && basePluginDriver.fileEmitter);
  19681. this.emitFile = this.fileEmitter.emitFile.bind(this.fileEmitter);
  19682. this.getFileName = this.fileEmitter.getFileName.bind(this.fileEmitter);
  19683. this.finaliseAssets = this.fileEmitter.finaliseAssets.bind(this.fileEmitter);
  19684. this.setChunkInformation = this.fileEmitter.setChunkInformation.bind(this.fileEmitter);
  19685. this.setOutputBundle = this.fileEmitter.setOutputBundle.bind(this.fileEmitter);
  19686. this.plugins = [...(basePluginDriver ? basePluginDriver.plugins : []), ...userPlugins];
  19687. const existingPluginNames = new Set();
  19688. this.pluginContexts = new Map(this.plugins.map(plugin => [
  19689. plugin,
  19690. getPluginContext(plugin, pluginCache, graph, options, this.fileEmitter, existingPluginNames)
  19691. ]));
  19692. if (basePluginDriver) {
  19693. for (const plugin of userPlugins) {
  19694. for (const hook of inputHooks) {
  19695. if (hook in plugin) {
  19696. options.onLog(LOGLEVEL_WARN, logInputHookInOutputPlugin(plugin.name, hook));
  19697. }
  19698. }
  19699. }
  19700. }
  19701. }
  19702. createOutputPluginDriver(plugins) {
  19703. return new PluginDriver(this.graph, this.options, plugins, this.pluginCache, this);
  19704. }
  19705. getUnfulfilledHookActions() {
  19706. return this.unfulfilledActions;
  19707. }
  19708. // chains, first non-null result stops and returns
  19709. hookFirst(hookName, parameters, replaceContext, skipped) {
  19710. return this.hookFirstAndGetPlugin(hookName, parameters, replaceContext, skipped).then(result => result && result[0]);
  19711. }
  19712. // chains, first non-null result stops and returns result and last plugin
  19713. async hookFirstAndGetPlugin(hookName, parameters, replaceContext, skipped) {
  19714. for (const plugin of this.getSortedPlugins(hookName)) {
  19715. if (skipped?.has(plugin))
  19716. continue;
  19717. const result = await this.runHook(hookName, parameters, plugin, replaceContext);
  19718. if (result != null)
  19719. return [result, plugin];
  19720. }
  19721. return null;
  19722. }
  19723. // chains synchronously, first non-null result stops and returns
  19724. hookFirstSync(hookName, parameters, replaceContext) {
  19725. for (const plugin of this.getSortedPlugins(hookName)) {
  19726. const result = this.runHookSync(hookName, parameters, plugin, replaceContext);
  19727. if (result != null)
  19728. return result;
  19729. }
  19730. return null;
  19731. }
  19732. // parallel, ignores returns
  19733. async hookParallel(hookName, parameters, replaceContext) {
  19734. const parallelPromises = [];
  19735. for (const plugin of this.getSortedPlugins(hookName)) {
  19736. if (plugin[hookName].sequential) {
  19737. await Promise.all(parallelPromises);
  19738. parallelPromises.length = 0;
  19739. await this.runHook(hookName, parameters, plugin, replaceContext);
  19740. }
  19741. else {
  19742. parallelPromises.push(this.runHook(hookName, parameters, plugin, replaceContext));
  19743. }
  19744. }
  19745. await Promise.all(parallelPromises);
  19746. }
  19747. // chains, reduces returned value, handling the reduced value as the first hook argument
  19748. hookReduceArg0(hookName, [argument0, ...rest], reduce, replaceContext) {
  19749. let promise = Promise.resolve(argument0);
  19750. for (const plugin of this.getSortedPlugins(hookName)) {
  19751. promise = promise.then(argument0 => this.runHook(hookName, [argument0, ...rest], plugin, replaceContext).then(result => reduce.call(this.pluginContexts.get(plugin), argument0, result, plugin)));
  19752. }
  19753. return promise;
  19754. }
  19755. // chains synchronously, reduces returned value, handling the reduced value as the first hook argument
  19756. hookReduceArg0Sync(hookName, [argument0, ...rest], reduce, replaceContext) {
  19757. for (const plugin of this.getSortedPlugins(hookName)) {
  19758. const parameters = [argument0, ...rest];
  19759. const result = this.runHookSync(hookName, parameters, plugin, replaceContext);
  19760. argument0 = reduce.call(this.pluginContexts.get(plugin), argument0, result, plugin);
  19761. }
  19762. return argument0;
  19763. }
  19764. // chains, reduces returned value to type string, handling the reduced value separately. permits hooks as values.
  19765. async hookReduceValue(hookName, initialValue, parameters, reducer) {
  19766. const results = [];
  19767. const parallelResults = [];
  19768. for (const plugin of this.getSortedPlugins(hookName, validateAddonPluginHandler)) {
  19769. if (plugin[hookName].sequential) {
  19770. results.push(...(await Promise.all(parallelResults)));
  19771. parallelResults.length = 0;
  19772. results.push(await this.runHook(hookName, parameters, plugin));
  19773. }
  19774. else {
  19775. parallelResults.push(this.runHook(hookName, parameters, plugin));
  19776. }
  19777. }
  19778. results.push(...(await Promise.all(parallelResults)));
  19779. return results.reduce(reducer, await initialValue);
  19780. }
  19781. // chains synchronously, reduces returned value to type T, handling the reduced value separately. permits hooks as values.
  19782. hookReduceValueSync(hookName, initialValue, parameters, reduce, replaceContext) {
  19783. let accumulator = initialValue;
  19784. for (const plugin of this.getSortedPlugins(hookName)) {
  19785. const result = this.runHookSync(hookName, parameters, plugin, replaceContext);
  19786. accumulator = reduce.call(this.pluginContexts.get(plugin), accumulator, result, plugin);
  19787. }
  19788. return accumulator;
  19789. }
  19790. // chains, ignores returns
  19791. hookSeq(hookName, parameters, replaceContext) {
  19792. let promise = Promise.resolve();
  19793. for (const plugin of this.getSortedPlugins(hookName)) {
  19794. promise = promise.then(() => this.runHook(hookName, parameters, plugin, replaceContext));
  19795. }
  19796. return promise.then(noReturn);
  19797. }
  19798. getSortedPlugins(hookName, validateHandler) {
  19799. return getOrCreate(this.sortedPlugins, hookName, () => getSortedValidatedPlugins(hookName, this.plugins, validateHandler));
  19800. }
  19801. // Implementation signature
  19802. runHook(hookName, parameters, plugin, replaceContext) {
  19803. // We always filter for plugins that support the hook before running it
  19804. const hook = plugin[hookName];
  19805. const handler = typeof hook === 'object' ? hook.handler : hook;
  19806. let context = this.pluginContexts.get(plugin);
  19807. if (replaceContext) {
  19808. context = replaceContext(context, plugin);
  19809. }
  19810. let action = null;
  19811. return Promise.resolve()
  19812. .then(() => {
  19813. if (typeof handler !== 'function') {
  19814. return handler;
  19815. }
  19816. // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
  19817. const hookResult = handler.apply(context, parameters);
  19818. if (!hookResult?.then) {
  19819. // short circuit for non-thenables and non-Promises
  19820. return hookResult;
  19821. }
  19822. // Track pending hook actions to properly error out when
  19823. // unfulfilled promises cause rollup to abruptly and confusingly
  19824. // exit with a successful 0 return code but without producing any
  19825. // output, errors or warnings.
  19826. action = [plugin.name, hookName, parameters];
  19827. this.unfulfilledActions.add(action);
  19828. // Although it would be more elegant to just return hookResult here
  19829. // and put the .then() handler just above the .catch() handler below,
  19830. // doing so would subtly change the defacto async event dispatch order
  19831. // which at least one test and some plugins in the wild may depend on.
  19832. return Promise.resolve(hookResult).then(result => {
  19833. // action was fulfilled
  19834. this.unfulfilledActions.delete(action);
  19835. return result;
  19836. });
  19837. })
  19838. .catch(error_ => {
  19839. if (action !== null) {
  19840. // action considered to be fulfilled since error being handled
  19841. this.unfulfilledActions.delete(action);
  19842. }
  19843. return error(logPluginError(error_, plugin.name, { hook: hookName }));
  19844. });
  19845. }
  19846. /**
  19847. * Run a sync plugin hook and return the result.
  19848. * @param hookName Name of the plugin hook. Must be in `PluginHooks`.
  19849. * @param args Arguments passed to the plugin hook.
  19850. * @param plugin The acutal plugin
  19851. * @param replaceContext When passed, the plugin context can be overridden.
  19852. */
  19853. runHookSync(hookName, parameters, plugin, replaceContext) {
  19854. const hook = plugin[hookName];
  19855. const handler = typeof hook === 'object' ? hook.handler : hook;
  19856. let context = this.pluginContexts.get(plugin);
  19857. if (replaceContext) {
  19858. context = replaceContext(context, plugin);
  19859. }
  19860. try {
  19861. // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
  19862. return handler.apply(context, parameters);
  19863. }
  19864. catch (error_) {
  19865. return error(logPluginError(error_, plugin.name, { hook: hookName }));
  19866. }
  19867. }
  19868. }
  19869. function getSortedValidatedPlugins(hookName, plugins, validateHandler = validateFunctionPluginHandler) {
  19870. const pre = [];
  19871. const normal = [];
  19872. const post = [];
  19873. for (const plugin of plugins) {
  19874. const hook = plugin[hookName];
  19875. if (hook) {
  19876. if (typeof hook === 'object') {
  19877. validateHandler(hook.handler, hookName, plugin);
  19878. if (hook.order === 'pre') {
  19879. pre.push(plugin);
  19880. continue;
  19881. }
  19882. if (hook.order === 'post') {
  19883. post.push(plugin);
  19884. continue;
  19885. }
  19886. }
  19887. else {
  19888. validateHandler(hook, hookName, plugin);
  19889. }
  19890. normal.push(plugin);
  19891. }
  19892. }
  19893. return [...pre, ...normal, ...post];
  19894. }
  19895. function validateFunctionPluginHandler(handler, hookName, plugin) {
  19896. if (typeof handler !== 'function') {
  19897. error(logInvalidFunctionPluginHook(hookName, plugin.name));
  19898. }
  19899. }
  19900. function validateAddonPluginHandler(handler, hookName, plugin) {
  19901. if (typeof handler !== 'string' && typeof handler !== 'function') {
  19902. return error(logInvalidAddonPluginHook(hookName, plugin.name));
  19903. }
  19904. }
  19905. function noReturn() { }
  19906. class Queue {
  19907. constructor(maxParallel) {
  19908. this.maxParallel = maxParallel;
  19909. this.queue = [];
  19910. this.workerCount = 0;
  19911. }
  19912. run(task) {
  19913. return new Promise((resolve, reject) => {
  19914. this.queue.push({ reject, resolve, task });
  19915. this.work();
  19916. });
  19917. }
  19918. async work() {
  19919. if (this.workerCount >= this.maxParallel)
  19920. return;
  19921. this.workerCount++;
  19922. let entry;
  19923. while ((entry = this.queue.shift())) {
  19924. const { reject, resolve, task } = entry;
  19925. try {
  19926. const result = await task();
  19927. resolve(result);
  19928. }
  19929. catch (error) {
  19930. reject(error);
  19931. }
  19932. }
  19933. this.workerCount--;
  19934. }
  19935. }
  19936. function normalizeEntryModules(entryModules) {
  19937. if (Array.isArray(entryModules)) {
  19938. return entryModules.map(id => ({
  19939. fileName: null,
  19940. id,
  19941. implicitlyLoadedAfter: [],
  19942. importer: undefined,
  19943. name: null
  19944. }));
  19945. }
  19946. return Object.entries(entryModules).map(([name, id]) => ({
  19947. fileName: null,
  19948. id,
  19949. implicitlyLoadedAfter: [],
  19950. importer: undefined,
  19951. name
  19952. }));
  19953. }
  19954. class Graph {
  19955. constructor(options, watcher) {
  19956. this.options = options;
  19957. this.astLru = flru(5);
  19958. this.cachedModules = new Map();
  19959. this.deoptimizationTracker = new PathTracker();
  19960. this.entryModules = [];
  19961. this.modulesById = new Map();
  19962. this.needsTreeshakingPass = false;
  19963. this.phase = BuildPhase.LOAD_AND_PARSE;
  19964. this.scope = new GlobalScope();
  19965. this.watchFiles = Object.create(null);
  19966. this.watchMode = false;
  19967. this.externalModules = [];
  19968. this.implicitEntryModules = [];
  19969. this.modules = [];
  19970. this.getModuleInfo = (moduleId) => {
  19971. const foundModule = this.modulesById.get(moduleId);
  19972. if (!foundModule)
  19973. return null;
  19974. return foundModule.info;
  19975. };
  19976. if (options.cache !== false) {
  19977. if (options.cache?.modules) {
  19978. for (const module of options.cache.modules)
  19979. this.cachedModules.set(module.id, module);
  19980. }
  19981. this.pluginCache = options.cache?.plugins || Object.create(null);
  19982. // increment access counter
  19983. for (const name in this.pluginCache) {
  19984. const cache = this.pluginCache[name];
  19985. for (const value of Object.values(cache))
  19986. value[0]++;
  19987. }
  19988. }
  19989. if (watcher) {
  19990. this.watchMode = true;
  19991. const handleChange = (...parameters) => this.pluginDriver.hookParallel('watchChange', parameters);
  19992. const handleClose = () => this.pluginDriver.hookParallel('closeWatcher', []);
  19993. watcher.onCurrentRun('change', handleChange);
  19994. watcher.onCurrentRun('close', handleClose);
  19995. }
  19996. this.pluginDriver = new PluginDriver(this, options, options.plugins, this.pluginCache);
  19997. this.moduleLoader = new ModuleLoader(this, this.modulesById, this.options, this.pluginDriver);
  19998. this.fileOperationQueue = new Queue(options.maxParallelFileOps);
  19999. this.pureFunctions = getPureFunctions(options);
  20000. }
  20001. async build() {
  20002. timeStart('generate module graph', 2);
  20003. await this.generateModuleGraph();
  20004. timeEnd('generate module graph', 2);
  20005. timeStart('sort and bind modules', 2);
  20006. this.phase = BuildPhase.ANALYSE;
  20007. this.sortModules();
  20008. timeEnd('sort and bind modules', 2);
  20009. timeStart('mark included statements', 2);
  20010. this.includeStatements();
  20011. timeEnd('mark included statements', 2);
  20012. this.phase = BuildPhase.GENERATE;
  20013. }
  20014. getCache() {
  20015. // handle plugin cache eviction
  20016. for (const name in this.pluginCache) {
  20017. const cache = this.pluginCache[name];
  20018. let allDeleted = true;
  20019. for (const [key, value] of Object.entries(cache)) {
  20020. if (value[0] >= this.options.experimentalCacheExpiry)
  20021. delete cache[key];
  20022. else
  20023. allDeleted = false;
  20024. }
  20025. if (allDeleted)
  20026. delete this.pluginCache[name];
  20027. }
  20028. return {
  20029. modules: this.modules.map(module => module.toJSON()),
  20030. plugins: this.pluginCache
  20031. };
  20032. }
  20033. async generateModuleGraph() {
  20034. ({ entryModules: this.entryModules, implicitEntryModules: this.implicitEntryModules } =
  20035. await this.moduleLoader.addEntryModules(normalizeEntryModules(this.options.input), true));
  20036. if (this.entryModules.length === 0) {
  20037. throw new Error('You must supply options.input to rollup');
  20038. }
  20039. for (const module of this.modulesById.values()) {
  20040. module.cacheInfoGetters();
  20041. if (module instanceof Module) {
  20042. this.modules.push(module);
  20043. }
  20044. else {
  20045. this.externalModules.push(module);
  20046. }
  20047. }
  20048. }
  20049. includeStatements() {
  20050. const entryModules = [...this.entryModules, ...this.implicitEntryModules];
  20051. for (const module of entryModules) {
  20052. markModuleAndImpureDependenciesAsExecuted(module);
  20053. }
  20054. if (this.options.treeshake) {
  20055. let treeshakingPass = 1;
  20056. do {
  20057. timeStart(`treeshaking pass ${treeshakingPass}`, 3);
  20058. this.needsTreeshakingPass = false;
  20059. for (const module of this.modules) {
  20060. if (module.isExecuted) {
  20061. module.hasTreeShakingPassStarted = true;
  20062. if (module.info.moduleSideEffects === 'no-treeshake') {
  20063. module.includeAllInBundle();
  20064. }
  20065. else {
  20066. module.include();
  20067. }
  20068. }
  20069. }
  20070. if (treeshakingPass === 1) {
  20071. // We only include exports after the first pass to avoid issues with
  20072. // the TDZ detection logic
  20073. for (const module of entryModules) {
  20074. if (module.preserveSignature !== false) {
  20075. module.includeAllExports(false);
  20076. this.needsTreeshakingPass = true;
  20077. }
  20078. }
  20079. }
  20080. timeEnd(`treeshaking pass ${treeshakingPass++}`, 3);
  20081. } while (this.needsTreeshakingPass);
  20082. }
  20083. else {
  20084. for (const module of this.modules)
  20085. module.includeAllInBundle();
  20086. }
  20087. for (const externalModule of this.externalModules)
  20088. externalModule.warnUnusedImports();
  20089. for (const module of this.implicitEntryModules) {
  20090. for (const dependant of module.implicitlyLoadedAfter) {
  20091. if (!(dependant.info.isEntry || dependant.isIncluded())) {
  20092. error(logImplicitDependantIsNotIncluded(dependant));
  20093. }
  20094. }
  20095. }
  20096. }
  20097. sortModules() {
  20098. const { orderedModules, cyclePaths } = analyseModuleExecution(this.entryModules);
  20099. for (const cyclePath of cyclePaths) {
  20100. this.options.onLog(LOGLEVEL_WARN, logCircularDependency(cyclePath));
  20101. }
  20102. this.modules = orderedModules;
  20103. for (const module of this.modules) {
  20104. module.bindReferences();
  20105. }
  20106. this.warnForMissingExports();
  20107. }
  20108. warnForMissingExports() {
  20109. for (const module of this.modules) {
  20110. for (const importDescription of module.importDescriptions.values()) {
  20111. if (importDescription.name !== '*' &&
  20112. !importDescription.module.getVariableForExportName(importDescription.name)[0]) {
  20113. module.log(LOGLEVEL_WARN, logMissingExport(importDescription.name, module.id, importDescription.module.id), importDescription.start);
  20114. }
  20115. }
  20116. }
  20117. }
  20118. }
  20119. function formatAction([pluginName, hookName, parameters]) {
  20120. const action = `(${pluginName}) ${hookName}`;
  20121. const s = JSON.stringify;
  20122. switch (hookName) {
  20123. case 'resolveId': {
  20124. return `${action} ${s(parameters[0])} ${s(parameters[1])}`;
  20125. }
  20126. case 'load': {
  20127. return `${action} ${s(parameters[0])}`;
  20128. }
  20129. case 'transform': {
  20130. return `${action} ${s(parameters[1])}`;
  20131. }
  20132. case 'shouldTransformCachedModule': {
  20133. return `${action} ${s(parameters[0].id)}`;
  20134. }
  20135. case 'moduleParsed': {
  20136. return `${action} ${s(parameters[0].id)}`;
  20137. }
  20138. }
  20139. return action;
  20140. }
  20141. let handleBeforeExit = null;
  20142. const rejectByPluginDriver = new Map();
  20143. async function catchUnfinishedHookActions(pluginDriver, callback) {
  20144. const emptyEventLoopPromise = new Promise((_, reject) => {
  20145. rejectByPluginDriver.set(pluginDriver, reject);
  20146. if (!handleBeforeExit) {
  20147. // We only ever create a single event listener to avoid max listener and
  20148. // other issues
  20149. handleBeforeExit = () => {
  20150. for (const [pluginDriver, reject] of rejectByPluginDriver) {
  20151. const unfulfilledActions = pluginDriver.getUnfulfilledHookActions();
  20152. reject(new Error(`Unexpected early exit. This happens when Promises returned by plugins cannot resolve. Unfinished hook action(s) on exit:\n` +
  20153. [...unfulfilledActions].map(formatAction).join('\n')));
  20154. }
  20155. };
  20156. process$1.once('beforeExit', handleBeforeExit);
  20157. }
  20158. });
  20159. try {
  20160. return await Promise.race([callback(), emptyEventLoopPromise]);
  20161. }
  20162. finally {
  20163. rejectByPluginDriver.delete(pluginDriver);
  20164. if (rejectByPluginDriver.size === 0) {
  20165. process$1.off('beforeExit', handleBeforeExit);
  20166. handleBeforeExit = null;
  20167. }
  20168. }
  20169. }
  20170. async function initWasm() { }
  20171. function getLogger(plugins, onLog, watchMode, logLevel) {
  20172. plugins = getSortedValidatedPlugins('onLog', plugins);
  20173. const minimalPriority = logLevelPriority[logLevel];
  20174. const logger = (level, log, skipped = EMPTY_SET) => {
  20175. augmentLogMessage(log);
  20176. const logPriority = logLevelPriority[level];
  20177. if (logPriority < minimalPriority) {
  20178. return;
  20179. }
  20180. for (const plugin of plugins) {
  20181. if (skipped.has(plugin))
  20182. continue;
  20183. const { onLog: pluginOnLog } = plugin;
  20184. const getLogHandler = (level) => {
  20185. if (logLevelPriority[level] < minimalPriority) {
  20186. return doNothing;
  20187. }
  20188. return log => logger(level, normalizeLog(log), new Set(skipped).add(plugin));
  20189. };
  20190. const handler = 'handler' in pluginOnLog ? pluginOnLog.handler : pluginOnLog;
  20191. if (handler.call({
  20192. debug: getLogHandler(LOGLEVEL_DEBUG),
  20193. error: (log) => error(normalizeLog(log)),
  20194. info: getLogHandler(LOGLEVEL_INFO),
  20195. meta: { rollupVersion: version, watchMode },
  20196. warn: getLogHandler(LOGLEVEL_WARN)
  20197. }, level, log) === false) {
  20198. return;
  20199. }
  20200. }
  20201. onLog(level, log);
  20202. };
  20203. return logger;
  20204. }
  20205. function ensureArray(items) {
  20206. if (Array.isArray(items)) {
  20207. return items.filter(Boolean);
  20208. }
  20209. if (items) {
  20210. return [items];
  20211. }
  20212. return [];
  20213. }
  20214. async function normalizeInputOptions(config, watchMode) {
  20215. // These are options that may trigger special warnings or behaviour later
  20216. // if the user did not select an explicit value
  20217. const unsetOptions = new Set();
  20218. const context = config.context ?? 'undefined';
  20219. const plugins = await normalizePluginOption(config.plugins);
  20220. const logLevel = config.logLevel || LOGLEVEL_INFO;
  20221. const onLog = getLogger(plugins, getOnLog(config, logLevel), watchMode, logLevel);
  20222. const strictDeprecations = config.strictDeprecations || false;
  20223. const maxParallelFileOps = getMaxParallelFileOps(config);
  20224. const options = {
  20225. cache: getCache(config),
  20226. context,
  20227. experimentalCacheExpiry: config.experimentalCacheExpiry ?? 10,
  20228. experimentalLogSideEffects: config.experimentalLogSideEffects || false,
  20229. external: getIdMatcher(config.external),
  20230. input: getInput(config),
  20231. jsx: getJsx(config),
  20232. logLevel,
  20233. makeAbsoluteExternalsRelative: config.makeAbsoluteExternalsRelative ?? 'ifRelativeSource',
  20234. maxParallelFileOps,
  20235. moduleContext: getModuleContext(config, context),
  20236. onLog,
  20237. perf: config.perf || false,
  20238. plugins,
  20239. preserveEntrySignatures: config.preserveEntrySignatures ?? 'exports-only',
  20240. preserveSymlinks: config.preserveSymlinks || false,
  20241. shimMissingExports: config.shimMissingExports || false,
  20242. strictDeprecations,
  20243. treeshake: getTreeshake(config)
  20244. };
  20245. warnUnknownOptions(config, [...Object.keys(options), 'onwarn', 'watch'], 'input options', onLog, /^(output)$/);
  20246. return { options, unsetOptions };
  20247. }
  20248. const getCache = (config) => config.cache === true // `true` is the default
  20249. ? undefined
  20250. : config.cache?.cache || config.cache;
  20251. const getIdMatcher = (option) => {
  20252. if (option === true) {
  20253. return () => true;
  20254. }
  20255. if (typeof option === 'function') {
  20256. return (id, ...parameters) => (!id.startsWith('\0') && option(id, ...parameters)) || false;
  20257. }
  20258. if (option) {
  20259. const ids = new Set();
  20260. const matchers = [];
  20261. for (const value of ensureArray(option)) {
  20262. if (value instanceof RegExp) {
  20263. matchers.push(value);
  20264. }
  20265. else {
  20266. ids.add(value);
  20267. }
  20268. }
  20269. return (id, ..._arguments) => ids.has(id) || matchers.some(matcher => matcher.test(id));
  20270. }
  20271. return () => false;
  20272. };
  20273. const getInput = (config) => {
  20274. const configInput = config.input;
  20275. return configInput == null ? [] : typeof configInput === 'string' ? [configInput] : configInput;
  20276. };
  20277. const getJsx = (config) => {
  20278. const configJsx = config.jsx;
  20279. if (!configJsx)
  20280. return false;
  20281. const configWithPreset = getOptionWithPreset(configJsx, jsxPresets, 'jsx', URL_JSX, 'false, ');
  20282. const { factory, importSource, mode } = configWithPreset;
  20283. switch (mode) {
  20284. case 'automatic': {
  20285. return {
  20286. factory: factory || 'React.createElement',
  20287. importSource: importSource || 'react',
  20288. jsxImportSource: configWithPreset.jsxImportSource || 'react/jsx-runtime',
  20289. mode: 'automatic'
  20290. };
  20291. }
  20292. case 'preserve': {
  20293. if (importSource && !(factory || configWithPreset.fragment)) {
  20294. error(logInvalidOption('jsx', URL_JSX, 'when preserving JSX and specifying an importSource, you also need to specify a factory or fragment'));
  20295. }
  20296. return {
  20297. factory: factory || null,
  20298. fragment: configWithPreset.fragment || null,
  20299. importSource: importSource || null,
  20300. mode: 'preserve'
  20301. };
  20302. }
  20303. // case 'classic':
  20304. default: {
  20305. if (mode && mode !== 'classic') {
  20306. error(logInvalidOption('jsx.mode', URL_JSX, 'mode must be "automatic", "classic" or "preserve"', mode));
  20307. }
  20308. return {
  20309. factory: factory || 'React.createElement',
  20310. fragment: configWithPreset.fragment || 'React.Fragment',
  20311. importSource: importSource || null,
  20312. mode: 'classic'
  20313. };
  20314. }
  20315. }
  20316. };
  20317. const getMaxParallelFileOps = (config) => {
  20318. const maxParallelFileOps = config.maxParallelFileOps;
  20319. if (typeof maxParallelFileOps === 'number') {
  20320. if (maxParallelFileOps <= 0)
  20321. return Infinity;
  20322. return maxParallelFileOps;
  20323. }
  20324. return 20;
  20325. };
  20326. const getModuleContext = (config, context) => {
  20327. const configModuleContext = config.moduleContext;
  20328. if (typeof configModuleContext === 'function') {
  20329. return id => configModuleContext(id) ?? context;
  20330. }
  20331. if (configModuleContext) {
  20332. const contextByModuleId = Object.create(null);
  20333. for (const [key, moduleContext] of Object.entries(configModuleContext)) {
  20334. contextByModuleId[resolve$1(key)] = moduleContext;
  20335. }
  20336. return id => contextByModuleId[id] ?? context;
  20337. }
  20338. return () => context;
  20339. };
  20340. const getTreeshake = (config) => {
  20341. const configTreeshake = config.treeshake;
  20342. if (configTreeshake === false) {
  20343. return false;
  20344. }
  20345. const configWithPreset = getOptionWithPreset(config.treeshake, treeshakePresets, 'treeshake', URL_TREESHAKE, 'false, true, ');
  20346. return {
  20347. annotations: configWithPreset.annotations !== false,
  20348. correctVarValueBeforeDeclaration: configWithPreset.correctVarValueBeforeDeclaration === true,
  20349. manualPureFunctions: configWithPreset.manualPureFunctions ?? EMPTY_ARRAY,
  20350. moduleSideEffects: getHasModuleSideEffects(configWithPreset.moduleSideEffects),
  20351. propertyReadSideEffects: configWithPreset.propertyReadSideEffects === 'always'
  20352. ? 'always'
  20353. : configWithPreset.propertyReadSideEffects !== false,
  20354. tryCatchDeoptimization: configWithPreset.tryCatchDeoptimization !== false,
  20355. unknownGlobalSideEffects: configWithPreset.unknownGlobalSideEffects !== false
  20356. };
  20357. };
  20358. const getHasModuleSideEffects = (moduleSideEffectsOption) => {
  20359. if (typeof moduleSideEffectsOption === 'boolean') {
  20360. return () => moduleSideEffectsOption;
  20361. }
  20362. if (moduleSideEffectsOption === 'no-external') {
  20363. return (_id, external) => !external;
  20364. }
  20365. if (typeof moduleSideEffectsOption === 'function') {
  20366. return (id, external) => id.startsWith('\0') ? true : moduleSideEffectsOption(id, external) !== false;
  20367. }
  20368. if (Array.isArray(moduleSideEffectsOption)) {
  20369. const ids = new Set(moduleSideEffectsOption);
  20370. return id => ids.has(id);
  20371. }
  20372. if (moduleSideEffectsOption) {
  20373. error(logInvalidOption('treeshake.moduleSideEffects', URL_TREESHAKE_MODULESIDEEFFECTS, 'please use one of false, "no-external", a function or an array'));
  20374. }
  20375. return () => true;
  20376. };
  20377. // https://datatracker.ietf.org/doc/html/rfc2396
  20378. // eslint-disable-next-line no-control-regex
  20379. const INVALID_CHAR_REGEX = /[\u0000-\u001F"#$%&*+,:;<=>?[\]^`{|}\u007F]/g;
  20380. const DRIVE_LETTER_REGEX = /^[a-z]:/i;
  20381. function sanitizeFileName(name) {
  20382. const match = DRIVE_LETTER_REGEX.exec(name);
  20383. const driveLetter = match ? match[0] : '';
  20384. // A `:` is only allowed as part of a windows drive letter (ex: C:\foo)
  20385. // Otherwise, avoid them because they can refer to NTFS alternate data streams.
  20386. return driveLetter + name.slice(driveLetter.length).replace(INVALID_CHAR_REGEX, '_');
  20387. }
  20388. async function normalizeOutputOptions(config, inputOptions, unsetInputOptions) {
  20389. // These are options that may trigger special warnings or behaviour later
  20390. // if the user did not select an explicit value
  20391. const unsetOptions = new Set(unsetInputOptions);
  20392. const compact = config.compact || false;
  20393. const format = getFormat(config);
  20394. const inlineDynamicImports = getInlineDynamicImports(config, inputOptions);
  20395. const preserveModules = getPreserveModules(config, inlineDynamicImports, inputOptions);
  20396. const file = getFile(config, preserveModules, inputOptions);
  20397. const generatedCode = getGeneratedCode(config);
  20398. const externalImportAttributes = getExternalImportAttributes(config, inputOptions);
  20399. const outputOptions = {
  20400. amd: getAmd(config),
  20401. assetFileNames: config.assetFileNames ?? 'assets/[name]-[hash][extname]',
  20402. banner: getAddon(config, 'banner'),
  20403. chunkFileNames: config.chunkFileNames ?? '[name]-[hash].js',
  20404. compact,
  20405. dir: getDir(config, file),
  20406. dynamicImportInCjs: config.dynamicImportInCjs ?? true,
  20407. entryFileNames: getEntryFileNames(config, unsetOptions),
  20408. esModule: config.esModule ?? 'if-default-prop',
  20409. experimentalMinChunkSize: config.experimentalMinChunkSize ?? 1,
  20410. exports: getExports(config, unsetOptions),
  20411. extend: config.extend || false,
  20412. externalImportAssertions: externalImportAttributes,
  20413. externalImportAttributes,
  20414. externalLiveBindings: config.externalLiveBindings ?? true,
  20415. file,
  20416. footer: getAddon(config, 'footer'),
  20417. format,
  20418. freeze: config.freeze ?? true,
  20419. generatedCode,
  20420. globals: config.globals || {},
  20421. hashCharacters: config.hashCharacters ?? 'base64',
  20422. hoistTransitiveImports: config.hoistTransitiveImports ?? true,
  20423. importAttributesKey: config.importAttributesKey ?? 'assert',
  20424. indent: getIndent(config, compact),
  20425. inlineDynamicImports,
  20426. interop: getInterop(config),
  20427. intro: getAddon(config, 'intro'),
  20428. manualChunks: getManualChunks(config, inlineDynamicImports, preserveModules),
  20429. minifyInternalExports: getMinifyInternalExports(config, format, compact),
  20430. name: config.name,
  20431. noConflict: config.noConflict || false,
  20432. outro: getAddon(config, 'outro'),
  20433. paths: config.paths || {},
  20434. plugins: await normalizePluginOption(config.plugins),
  20435. preserveModules,
  20436. preserveModulesRoot: getPreserveModulesRoot(config),
  20437. reexportProtoFromExternal: config.reexportProtoFromExternal ?? true,
  20438. sanitizeFileName: typeof config.sanitizeFileName === 'function'
  20439. ? config.sanitizeFileName
  20440. : config.sanitizeFileName === false
  20441. ? id => id
  20442. : sanitizeFileName,
  20443. sourcemap: config.sourcemap || false,
  20444. sourcemapBaseUrl: getSourcemapBaseUrl(config),
  20445. sourcemapExcludeSources: config.sourcemapExcludeSources || false,
  20446. sourcemapFile: config.sourcemapFile,
  20447. sourcemapFileNames: getSourcemapFileNames(config, unsetOptions),
  20448. sourcemapIgnoreList: typeof config.sourcemapIgnoreList === 'function'
  20449. ? config.sourcemapIgnoreList
  20450. : config.sourcemapIgnoreList === false
  20451. ? () => false
  20452. : relativeSourcePath => relativeSourcePath.includes('node_modules'),
  20453. sourcemapPathTransform: config.sourcemapPathTransform,
  20454. strict: config.strict ?? true,
  20455. systemNullSetters: config.systemNullSetters ?? true,
  20456. validate: config.validate || false,
  20457. virtualDirname: config.virtualDirname || '_virtual'
  20458. };
  20459. warnUnknownOptions(config, Object.keys(outputOptions), 'output options', inputOptions.onLog);
  20460. return { options: outputOptions, unsetOptions };
  20461. }
  20462. const getFile = (config, preserveModules, inputOptions) => {
  20463. const { file } = config;
  20464. if (typeof file === 'string') {
  20465. if (preserveModules) {
  20466. return error(logInvalidOption('output.file', URL_OUTPUT_DIR, 'you must set "output.dir" instead of "output.file" when using the "output.preserveModules" option'));
  20467. }
  20468. if (!Array.isArray(inputOptions.input))
  20469. return error(logInvalidOption('output.file', URL_OUTPUT_DIR, 'you must set "output.dir" instead of "output.file" when providing named inputs'));
  20470. }
  20471. return file;
  20472. };
  20473. const getFormat = (config) => {
  20474. const configFormat = config.format;
  20475. switch (configFormat) {
  20476. case undefined:
  20477. case 'es':
  20478. case 'esm':
  20479. case 'module': {
  20480. return 'es';
  20481. }
  20482. case 'cjs':
  20483. case 'commonjs': {
  20484. return 'cjs';
  20485. }
  20486. case 'system':
  20487. case 'systemjs': {
  20488. return 'system';
  20489. }
  20490. case 'amd':
  20491. case 'iife':
  20492. case 'umd': {
  20493. return configFormat;
  20494. }
  20495. default: {
  20496. return error(logInvalidOption('output.format', URL_OUTPUT_FORMAT, `Valid values are "amd", "cjs", "system", "es", "iife" or "umd"`, configFormat));
  20497. }
  20498. }
  20499. };
  20500. const getInlineDynamicImports = (config, inputOptions) => {
  20501. const inlineDynamicImports = config.inlineDynamicImports || false;
  20502. const { input } = inputOptions;
  20503. if (inlineDynamicImports && (Array.isArray(input) ? input : Object.keys(input)).length > 1) {
  20504. return error(logInvalidOption('output.inlineDynamicImports', URL_OUTPUT_INLINEDYNAMICIMPORTS, 'multiple inputs are not supported when "output.inlineDynamicImports" is true'));
  20505. }
  20506. return inlineDynamicImports;
  20507. };
  20508. const getPreserveModules = (config, inlineDynamicImports, inputOptions) => {
  20509. const preserveModules = config.preserveModules || false;
  20510. if (preserveModules) {
  20511. if (inlineDynamicImports) {
  20512. return error(logInvalidOption('output.inlineDynamicImports', URL_OUTPUT_INLINEDYNAMICIMPORTS, `this option is not supported for "output.preserveModules"`));
  20513. }
  20514. if (inputOptions.preserveEntrySignatures === false) {
  20515. return error(logInvalidOption('preserveEntrySignatures', URL_PRESERVEENTRYSIGNATURES, 'setting this option to false is not supported for "output.preserveModules"'));
  20516. }
  20517. }
  20518. return preserveModules;
  20519. };
  20520. const getPreserveModulesRoot = (config) => {
  20521. const { preserveModulesRoot } = config;
  20522. if (preserveModulesRoot === null || preserveModulesRoot === undefined) {
  20523. return undefined;
  20524. }
  20525. return resolve$1(preserveModulesRoot);
  20526. };
  20527. const getAmd = (config) => {
  20528. const mergedOption = {
  20529. autoId: false,
  20530. basePath: '',
  20531. define: 'define',
  20532. forceJsExtensionForImports: false,
  20533. ...config.amd
  20534. };
  20535. if ((mergedOption.autoId || mergedOption.basePath) && mergedOption.id) {
  20536. return error(logInvalidOption('output.amd.id', URL_OUTPUT_AMD_ID, 'this option cannot be used together with "output.amd.autoId"/"output.amd.basePath"'));
  20537. }
  20538. if (mergedOption.basePath && !mergedOption.autoId) {
  20539. return error(logInvalidOption('output.amd.basePath', URL_OUTPUT_AMD_BASEPATH, 'this option only works with "output.amd.autoId"'));
  20540. }
  20541. return mergedOption.autoId
  20542. ? {
  20543. autoId: true,
  20544. basePath: mergedOption.basePath,
  20545. define: mergedOption.define,
  20546. forceJsExtensionForImports: mergedOption.forceJsExtensionForImports
  20547. }
  20548. : {
  20549. autoId: false,
  20550. define: mergedOption.define,
  20551. forceJsExtensionForImports: mergedOption.forceJsExtensionForImports,
  20552. id: mergedOption.id
  20553. };
  20554. };
  20555. const getAddon = (config, name) => {
  20556. const configAddon = config[name];
  20557. if (typeof configAddon === 'function') {
  20558. return configAddon;
  20559. }
  20560. return () => configAddon || '';
  20561. };
  20562. const getDir = (config, file) => {
  20563. const { dir } = config;
  20564. if (typeof dir === 'string' && typeof file === 'string') {
  20565. 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'));
  20566. }
  20567. return dir;
  20568. };
  20569. const getEntryFileNames = (config, unsetOptions) => {
  20570. const configEntryFileNames = config.entryFileNames;
  20571. if (configEntryFileNames == null) {
  20572. unsetOptions.add('entryFileNames');
  20573. }
  20574. return configEntryFileNames ?? '[name].js';
  20575. };
  20576. function getExports(config, unsetOptions) {
  20577. const configExports = config.exports;
  20578. if (configExports == null) {
  20579. unsetOptions.add('exports');
  20580. }
  20581. else if (!['default', 'named', 'none', 'auto'].includes(configExports)) {
  20582. return error(logInvalidExportOptionValue(configExports));
  20583. }
  20584. return configExports || 'auto';
  20585. }
  20586. const getExternalImportAttributes = (config, inputOptions) => {
  20587. if (config.externalImportAssertions != undefined) {
  20588. warnDeprecation(`The "output.externalImportAssertions" option is deprecated. Use the "output.externalImportAttributes" option instead.`, URL_OUTPUT_EXTERNALIMPORTATTRIBUTES, true, inputOptions);
  20589. }
  20590. return config.externalImportAttributes ?? config.externalImportAssertions ?? true;
  20591. };
  20592. const getGeneratedCode = (config) => {
  20593. const configWithPreset = getOptionWithPreset(config.generatedCode, generatedCodePresets, 'output.generatedCode', URL_OUTPUT_GENERATEDCODE, '');
  20594. return {
  20595. arrowFunctions: configWithPreset.arrowFunctions === true,
  20596. constBindings: configWithPreset.constBindings === true,
  20597. objectShorthand: configWithPreset.objectShorthand === true,
  20598. reservedNamesAsProps: configWithPreset.reservedNamesAsProps !== false,
  20599. symbols: configWithPreset.symbols === true
  20600. };
  20601. };
  20602. const getIndent = (config, compact) => {
  20603. if (compact) {
  20604. return '';
  20605. }
  20606. const configIndent = config.indent;
  20607. return configIndent === false ? '' : (configIndent ?? true);
  20608. };
  20609. const ALLOWED_INTEROP_TYPES = new Set([
  20610. 'compat',
  20611. 'auto',
  20612. 'esModule',
  20613. 'default',
  20614. 'defaultOnly'
  20615. ]);
  20616. const getInterop = (config) => {
  20617. const configInterop = config.interop;
  20618. if (typeof configInterop === 'function') {
  20619. const interopPerId = Object.create(null);
  20620. let defaultInterop = null;
  20621. return id => id === null
  20622. ? defaultInterop || validateInterop((defaultInterop = configInterop(id)))
  20623. : id in interopPerId
  20624. ? interopPerId[id]
  20625. : validateInterop((interopPerId[id] = configInterop(id)));
  20626. }
  20627. return configInterop === undefined ? () => 'default' : () => validateInterop(configInterop);
  20628. };
  20629. const validateInterop = (interop) => {
  20630. if (!ALLOWED_INTEROP_TYPES.has(interop)) {
  20631. return error(logInvalidOption('output.interop', URL_OUTPUT_INTEROP, `use one of ${Array.from(ALLOWED_INTEROP_TYPES, value => JSON.stringify(value)).join(', ')}`, interop));
  20632. }
  20633. return interop;
  20634. };
  20635. const getManualChunks = (config, inlineDynamicImports, preserveModules) => {
  20636. const configManualChunks = config.manualChunks;
  20637. if (configManualChunks) {
  20638. if (inlineDynamicImports) {
  20639. return error(logInvalidOption('output.manualChunks', URL_OUTPUT_MANUALCHUNKS, 'this option is not supported for "output.inlineDynamicImports"'));
  20640. }
  20641. if (preserveModules) {
  20642. return error(logInvalidOption('output.manualChunks', URL_OUTPUT_MANUALCHUNKS, 'this option is not supported for "output.preserveModules"'));
  20643. }
  20644. }
  20645. return configManualChunks || {};
  20646. };
  20647. const getMinifyInternalExports = (config, format, compact) => config.minifyInternalExports ?? (compact || format === 'es' || format === 'system');
  20648. const getSourcemapFileNames = (config, unsetOptions) => {
  20649. const configSourcemapFileNames = config.sourcemapFileNames;
  20650. if (configSourcemapFileNames == null) {
  20651. unsetOptions.add('sourcemapFileNames');
  20652. }
  20653. return configSourcemapFileNames;
  20654. };
  20655. const getSourcemapBaseUrl = (config) => {
  20656. const { sourcemapBaseUrl } = config;
  20657. if (sourcemapBaseUrl) {
  20658. if (isValidUrl(sourcemapBaseUrl)) {
  20659. return addTrailingSlashIfMissed(sourcemapBaseUrl);
  20660. }
  20661. return error(logInvalidOption('output.sourcemapBaseUrl', URL_OUTPUT_SOURCEMAPBASEURL, `must be a valid URL, received ${JSON.stringify(sourcemapBaseUrl)}`));
  20662. }
  20663. };
  20664. function rollup(rawInputOptions) {
  20665. return rollupInternal(rawInputOptions, null);
  20666. }
  20667. async function rollupInternal(rawInputOptions, watcher) {
  20668. const { options: inputOptions, unsetOptions: unsetInputOptions } = await getInputOptions(rawInputOptions, watcher !== null);
  20669. initialiseTimers(inputOptions);
  20670. await initWasm();
  20671. const graph = new Graph(inputOptions, watcher);
  20672. // remove the cache object from the memory after graph creation (cache is not used anymore)
  20673. const useCache = rawInputOptions.cache !== false;
  20674. if (rawInputOptions.cache) {
  20675. inputOptions.cache = undefined;
  20676. rawInputOptions.cache = undefined;
  20677. }
  20678. timeStart('BUILD', 1);
  20679. await catchUnfinishedHookActions(graph.pluginDriver, async () => {
  20680. try {
  20681. timeStart('initialize', 2);
  20682. await graph.pluginDriver.hookParallel('buildStart', [inputOptions]);
  20683. timeEnd('initialize', 2);
  20684. await graph.build();
  20685. }
  20686. catch (error_) {
  20687. const watchFiles = Object.keys(graph.watchFiles);
  20688. if (watchFiles.length > 0) {
  20689. error_.watchFiles = watchFiles;
  20690. }
  20691. await graph.pluginDriver.hookParallel('buildEnd', [error_]);
  20692. await graph.pluginDriver.hookParallel('closeBundle', []);
  20693. throw error_;
  20694. }
  20695. await graph.pluginDriver.hookParallel('buildEnd', []);
  20696. });
  20697. timeEnd('BUILD', 1);
  20698. const result = {
  20699. cache: useCache ? graph.getCache() : undefined,
  20700. async close() {
  20701. if (result.closed)
  20702. return;
  20703. result.closed = true;
  20704. await graph.pluginDriver.hookParallel('closeBundle', []);
  20705. },
  20706. closed: false,
  20707. async generate(rawOutputOptions) {
  20708. if (result.closed)
  20709. return error(logAlreadyClosed());
  20710. return handleGenerateWrite(false, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  20711. },
  20712. get watchFiles() {
  20713. return Object.keys(graph.watchFiles);
  20714. },
  20715. async write(rawOutputOptions) {
  20716. if (result.closed)
  20717. return error(logAlreadyClosed());
  20718. return handleGenerateWrite(true, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  20719. }
  20720. };
  20721. if (inputOptions.perf)
  20722. result.getTimings = getTimings;
  20723. return result;
  20724. }
  20725. async function getInputOptions(initialInputOptions, watchMode) {
  20726. if (!initialInputOptions) {
  20727. throw new Error('You must supply an options object to rollup');
  20728. }
  20729. const processedInputOptions = await getProcessedInputOptions(initialInputOptions, watchMode);
  20730. const { options, unsetOptions } = await normalizeInputOptions(processedInputOptions, watchMode);
  20731. normalizePlugins(options.plugins, ANONYMOUS_PLUGIN_PREFIX);
  20732. return { options, unsetOptions };
  20733. }
  20734. async function getProcessedInputOptions(inputOptions, watchMode) {
  20735. const plugins = getSortedValidatedPlugins('options', await normalizePluginOption(inputOptions.plugins));
  20736. const logLevel = inputOptions.logLevel || LOGLEVEL_INFO;
  20737. const logger = getLogger(plugins, getOnLog(inputOptions, logLevel), watchMode, logLevel);
  20738. for (const plugin of plugins) {
  20739. const { name, options } = plugin;
  20740. const handler = 'handler' in options ? options.handler : options;
  20741. const processedOptions = await handler.call({
  20742. debug: getLogHandler(LOGLEVEL_DEBUG, 'PLUGIN_LOG', logger, name, logLevel),
  20743. error: (error_) => error(logPluginError(normalizeLog(error_), name, { hook: 'onLog' })),
  20744. info: getLogHandler(LOGLEVEL_INFO, 'PLUGIN_LOG', logger, name, logLevel),
  20745. meta: { rollupVersion: version, watchMode },
  20746. warn: getLogHandler(LOGLEVEL_WARN, 'PLUGIN_WARNING', logger, name, logLevel)
  20747. }, inputOptions);
  20748. if (processedOptions) {
  20749. inputOptions = processedOptions;
  20750. }
  20751. }
  20752. return inputOptions;
  20753. }
  20754. function normalizePlugins(plugins, anonymousPrefix) {
  20755. for (const [index, plugin] of plugins.entries()) {
  20756. if (!plugin.name) {
  20757. plugin.name = `${anonymousPrefix}${index + 1}`;
  20758. }
  20759. }
  20760. }
  20761. async function handleGenerateWrite(isWrite, inputOptions, unsetInputOptions, rawOutputOptions, graph) {
  20762. const { options: outputOptions, outputPluginDriver, unsetOptions } = await getOutputOptionsAndPluginDriver(rawOutputOptions, graph.pluginDriver, inputOptions, unsetInputOptions);
  20763. return catchUnfinishedHookActions(outputPluginDriver, async () => {
  20764. const bundle = new Bundle(outputOptions, unsetOptions, inputOptions, outputPluginDriver, graph);
  20765. const generated = await bundle.generate(isWrite);
  20766. if (isWrite) {
  20767. timeStart('WRITE', 1);
  20768. if (!outputOptions.dir && !outputOptions.file) {
  20769. return error(logMissingFileOrDirOption());
  20770. }
  20771. await Promise.all(Object.values(generated).map(chunk => graph.fileOperationQueue.run(() => writeOutputFile(chunk, outputOptions))));
  20772. await outputPluginDriver.hookParallel('writeBundle', [outputOptions, generated]);
  20773. timeEnd('WRITE', 1);
  20774. }
  20775. return createOutput(generated);
  20776. });
  20777. }
  20778. async function getOutputOptionsAndPluginDriver(rawOutputOptions, inputPluginDriver, inputOptions, unsetInputOptions) {
  20779. if (!rawOutputOptions) {
  20780. throw new Error('You must supply an options object');
  20781. }
  20782. const rawPlugins = await normalizePluginOption(rawOutputOptions.plugins);
  20783. normalizePlugins(rawPlugins, ANONYMOUS_OUTPUT_PLUGIN_PREFIX);
  20784. const outputPluginDriver = inputPluginDriver.createOutputPluginDriver(rawPlugins);
  20785. return {
  20786. ...(await getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver)),
  20787. outputPluginDriver
  20788. };
  20789. }
  20790. function getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver) {
  20791. return normalizeOutputOptions(outputPluginDriver.hookReduceArg0Sync('outputOptions', [rawOutputOptions], (outputOptions, result) => result || outputOptions, pluginContext => {
  20792. const emitError = () => pluginContext.error(logCannotEmitFromOptionsHook());
  20793. return {
  20794. ...pluginContext,
  20795. emitFile: emitError,
  20796. setAssetSource: emitError
  20797. };
  20798. }), inputOptions, unsetInputOptions);
  20799. }
  20800. function createOutput(outputBundle) {
  20801. return {
  20802. output: Object.values(outputBundle).filter(outputFile => Object.keys(outputFile).length > 0).sort((outputFileA, outputFileB) => getSortingFileType(outputFileA) - getSortingFileType(outputFileB))
  20803. };
  20804. }
  20805. var SortingFileType;
  20806. (function (SortingFileType) {
  20807. SortingFileType[SortingFileType["ENTRY_CHUNK"] = 0] = "ENTRY_CHUNK";
  20808. SortingFileType[SortingFileType["SECONDARY_CHUNK"] = 1] = "SECONDARY_CHUNK";
  20809. SortingFileType[SortingFileType["ASSET"] = 2] = "ASSET";
  20810. })(SortingFileType || (SortingFileType = {}));
  20811. function getSortingFileType(file) {
  20812. if (file.type === 'asset') {
  20813. return SortingFileType.ASSET;
  20814. }
  20815. if (file.isEntry) {
  20816. return SortingFileType.ENTRY_CHUNK;
  20817. }
  20818. return SortingFileType.SECONDARY_CHUNK;
  20819. }
  20820. async function writeOutputFile(outputFile, outputOptions) {
  20821. const fileName = resolve$1(outputOptions.dir || dirname(outputOptions.file), outputFile.fileName);
  20822. // 'recursive: true' does not throw if the folder structure, or parts of it, already exist
  20823. await mkdir(dirname(fileName), { recursive: true });
  20824. return writeFile(fileName, outputFile.type === 'asset' ? outputFile.source : outputFile.code);
  20825. }
  20826. /**
  20827. * Auxiliary function for defining rollup configuration
  20828. * Mainly to facilitate IDE code prompts, after all, export default does not
  20829. * prompt, even if you add @type annotations, it is not accurate
  20830. * @param options
  20831. */
  20832. function defineConfig(options) {
  20833. return options;
  20834. }
  20835. const {
  20836. env = {},
  20837. argv = [],
  20838. platform = "",
  20839. } = typeof process === "undefined" ? {} : process;
  20840. const isDisabled = "NO_COLOR" in env || argv.includes("--no-color");
  20841. const isForced = "FORCE_COLOR" in env || argv.includes("--color");
  20842. const isWindows = platform === "win32";
  20843. const isDumbTerminal = env.TERM === "dumb";
  20844. const isCompatibleTerminal =
  20845. tty && tty.isatty && tty.isatty(1) && env.TERM && !isDumbTerminal;
  20846. const isCI =
  20847. "CI" in env &&
  20848. ("GITHUB_ACTIONS" in env || "GITLAB_CI" in env || "CIRCLECI" in env);
  20849. const isColorSupported =
  20850. !isDisabled &&
  20851. (isForced || (isWindows && !isDumbTerminal) || isCompatibleTerminal || isCI);
  20852. const replaceClose = (
  20853. index,
  20854. string,
  20855. close,
  20856. replace,
  20857. head = string.substring(0, index) + replace,
  20858. tail = string.substring(index + close.length),
  20859. next = tail.indexOf(close)
  20860. ) => head + (next < 0 ? tail : replaceClose(next, tail, close, replace));
  20861. const clearBleed = (index, string, open, close, replace) =>
  20862. index < 0
  20863. ? open + string + close
  20864. : open + replaceClose(index, string, close, replace) + close;
  20865. const filterEmpty =
  20866. (open, close, replace = open, at = open.length + 1) =>
  20867. (string) =>
  20868. string || !(string === "" || string === undefined)
  20869. ? clearBleed(
  20870. ("" + string).indexOf(close, at),
  20871. string,
  20872. open,
  20873. close,
  20874. replace
  20875. )
  20876. : "";
  20877. const init = (open, close, replace) =>
  20878. filterEmpty(`\x1b[${open}m`, `\x1b[${close}m`, replace);
  20879. const colors = {
  20880. reset: init(0, 0),
  20881. bold: init(1, 22, "\x1b[22m\x1b[1m"),
  20882. dim: init(2, 22, "\x1b[22m\x1b[2m"),
  20883. italic: init(3, 23),
  20884. underline: init(4, 24),
  20885. inverse: init(7, 27),
  20886. hidden: init(8, 28),
  20887. strikethrough: init(9, 29),
  20888. black: init(30, 39),
  20889. red: init(31, 39),
  20890. green: init(32, 39),
  20891. yellow: init(33, 39),
  20892. blue: init(34, 39),
  20893. magenta: init(35, 39),
  20894. cyan: init(36, 39),
  20895. white: init(37, 39),
  20896. gray: init(90, 39),
  20897. bgBlack: init(40, 49),
  20898. bgRed: init(41, 49),
  20899. bgGreen: init(42, 49),
  20900. bgYellow: init(43, 49),
  20901. bgBlue: init(44, 49),
  20902. bgMagenta: init(45, 49),
  20903. bgCyan: init(46, 49),
  20904. bgWhite: init(47, 49),
  20905. blackBright: init(90, 39),
  20906. redBright: init(91, 39),
  20907. greenBright: init(92, 39),
  20908. yellowBright: init(93, 39),
  20909. blueBright: init(94, 39),
  20910. magentaBright: init(95, 39),
  20911. cyanBright: init(96, 39),
  20912. whiteBright: init(97, 39),
  20913. bgBlackBright: init(100, 49),
  20914. bgRedBright: init(101, 49),
  20915. bgGreenBright: init(102, 49),
  20916. bgYellowBright: init(103, 49),
  20917. bgBlueBright: init(104, 49),
  20918. bgMagentaBright: init(105, 49),
  20919. bgCyanBright: init(106, 49),
  20920. bgWhiteBright: init(107, 49),
  20921. };
  20922. const createColors = ({ useColor = isColorSupported } = {}) =>
  20923. useColor
  20924. ? colors
  20925. : Object.keys(colors).reduce(
  20926. (colors, key) => ({ ...colors, [key]: String }),
  20927. {}
  20928. );
  20929. createColors();
  20930. // @see https://no-color.org
  20931. // @see https://www.npmjs.com/package/chalk
  20932. const { bold, cyan, dim, gray, green, red, underline, yellow } = createColors({
  20933. useColor: env$1.FORCE_COLOR !== '0' && !env$1.NO_COLOR
  20934. });
  20935. // log to stderr to keep `rollup main.js > bundle.js` from breaking
  20936. const stderr = (...parameters) => process$1.stderr.write(`${parameters.join('')}\n`);
  20937. function handleError(error, recover = false) {
  20938. const name = error.name || error.cause?.name;
  20939. const nameSection = name ? `${name}: ` : '';
  20940. const pluginSection = error.plugin ? `(plugin ${error.plugin}) ` : '';
  20941. const message = `${pluginSection}${nameSection}${error.message}`;
  20942. const outputLines = [bold(red(`[!] ${bold(message.toString())}`))];
  20943. if (error.url) {
  20944. outputLines.push(cyan(error.url));
  20945. }
  20946. if (error.loc) {
  20947. outputLines.push(`${relativeId((error.loc.file || error.id))} (${error.loc.line}:${error.loc.column})`);
  20948. }
  20949. else if (error.id) {
  20950. outputLines.push(relativeId(error.id));
  20951. }
  20952. if (error.frame) {
  20953. outputLines.push(dim(error.frame));
  20954. }
  20955. if (error.stack) {
  20956. outputLines.push(dim(error.stack?.replace(`${nameSection}${error.message}\n`, '')));
  20957. }
  20958. // ES2022: Error.prototype.cause is optional
  20959. if (error.cause) {
  20960. let cause = error.cause;
  20961. const causeErrorLines = [];
  20962. let indent = '';
  20963. while (cause) {
  20964. indent += ' ';
  20965. const message = cause.stack || cause;
  20966. causeErrorLines.push(...`[cause] ${message}`.split('\n').map(line => indent + line));
  20967. cause = cause.cause;
  20968. }
  20969. outputLines.push(dim(causeErrorLines.join('\n')));
  20970. }
  20971. outputLines.push('', '');
  20972. stderr(outputLines.join('\n'));
  20973. if (!recover)
  20974. process$1.exit(1);
  20975. }
  20976. const commandAliases = {
  20977. c: 'config',
  20978. d: 'dir',
  20979. e: 'external',
  20980. f: 'format',
  20981. g: 'globals',
  20982. h: 'help',
  20983. i: 'input',
  20984. m: 'sourcemap',
  20985. n: 'name',
  20986. o: 'file',
  20987. p: 'plugin',
  20988. v: 'version',
  20989. w: 'watch'
  20990. };
  20991. const EMPTY_COMMAND_OPTIONS = { external: [], globals: undefined };
  20992. async function mergeOptions(config, watchMode, rawCommandOptions = EMPTY_COMMAND_OPTIONS, printLog) {
  20993. const command = getCommandOptions(rawCommandOptions);
  20994. const plugins = await normalizePluginOption(config.plugins);
  20995. const logLevel = config.logLevel || LOGLEVEL_INFO;
  20996. const onLog = getOnLog(config, logLevel, printLog);
  20997. const log = getLogger(plugins, onLog, watchMode, logLevel);
  20998. const inputOptions = mergeInputOptions(config, command, plugins, log, onLog);
  20999. if (command.output) {
  21000. Object.assign(command, command.output);
  21001. }
  21002. const outputOptionsArray = ensureArray(config.output);
  21003. if (outputOptionsArray.length === 0)
  21004. outputOptionsArray.push({});
  21005. const outputOptions = await Promise.all(outputOptionsArray.map(singleOutputOptions => mergeOutputOptions(singleOutputOptions, command, log)));
  21006. warnUnknownOptions(command, [
  21007. ...Object.keys(inputOptions),
  21008. ...Object.keys(outputOptions[0]).filter(option => option !== 'sourcemapIgnoreList' && option !== 'sourcemapPathTransform'),
  21009. ...Object.keys(commandAliases),
  21010. 'bundleConfigAsCjs',
  21011. 'config',
  21012. 'configPlugin',
  21013. 'environment',
  21014. 'failAfterWarnings',
  21015. 'filterLogs',
  21016. 'forceExit',
  21017. 'plugin',
  21018. 'silent',
  21019. 'stdin',
  21020. 'waitForBundleInput'
  21021. ], 'CLI flags', log, /^_$|output$|config/);
  21022. inputOptions.output = outputOptions;
  21023. return inputOptions;
  21024. }
  21025. function getCommandOptions(rawCommandOptions) {
  21026. const external = rawCommandOptions.external && typeof rawCommandOptions.external === 'string'
  21027. ? rawCommandOptions.external.split(',')
  21028. : [];
  21029. return {
  21030. ...rawCommandOptions,
  21031. external,
  21032. globals: typeof rawCommandOptions.globals === 'string'
  21033. ? rawCommandOptions.globals.split(',').reduce((globals, globalDefinition) => {
  21034. const [id, variableName] = globalDefinition.split(':');
  21035. globals[id] = variableName;
  21036. if (!external.includes(id)) {
  21037. external.push(id);
  21038. }
  21039. return globals;
  21040. }, Object.create(null))
  21041. : undefined
  21042. };
  21043. }
  21044. function mergeInputOptions(config, overrides, plugins, log, onLog) {
  21045. const getOption = (name) => overrides[name] ?? config[name];
  21046. const inputOptions = {
  21047. cache: config.cache,
  21048. context: getOption('context'),
  21049. experimentalCacheExpiry: getOption('experimentalCacheExpiry'),
  21050. experimentalLogSideEffects: getOption('experimentalLogSideEffects'),
  21051. external: getExternal(config, overrides),
  21052. input: getOption('input') || [],
  21053. jsx: getObjectOption(config, overrides, 'jsx', objectifyOptionWithPresets(jsxPresets, 'jsx', URL_JSX, 'false, ')),
  21054. logLevel: getOption('logLevel'),
  21055. makeAbsoluteExternalsRelative: getOption('makeAbsoluteExternalsRelative'),
  21056. maxParallelFileOps: getOption('maxParallelFileOps'),
  21057. moduleContext: getOption('moduleContext'),
  21058. onLog,
  21059. onwarn: undefined,
  21060. perf: getOption('perf'),
  21061. plugins,
  21062. preserveEntrySignatures: getOption('preserveEntrySignatures'),
  21063. preserveSymlinks: getOption('preserveSymlinks'),
  21064. shimMissingExports: getOption('shimMissingExports'),
  21065. strictDeprecations: getOption('strictDeprecations'),
  21066. treeshake: getObjectOption(config, overrides, 'treeshake', objectifyOptionWithPresets(treeshakePresets, 'treeshake', URL_TREESHAKE, 'false, true, ')),
  21067. watch: getWatch(config, overrides)
  21068. };
  21069. warnUnknownOptions(config, Object.keys(inputOptions), 'input options', log, /^output$/);
  21070. return inputOptions;
  21071. }
  21072. const getExternal = (config, overrides) => {
  21073. const configExternal = config.external;
  21074. return typeof configExternal === 'function'
  21075. ? (source, importer, isResolved) => configExternal(source, importer, isResolved) || overrides.external.includes(source)
  21076. : [...ensureArray(configExternal), ...overrides.external];
  21077. };
  21078. const getObjectOption = (config, overrides, name, objectifyValue = objectifyOption) => {
  21079. const commandOption = normalizeObjectOptionValue(overrides[name], objectifyValue);
  21080. const configOption = normalizeObjectOptionValue(config[name], objectifyValue);
  21081. if (commandOption !== undefined) {
  21082. return commandOption && { ...configOption, ...commandOption };
  21083. }
  21084. return configOption;
  21085. };
  21086. const getWatch = (config, overrides) => config.watch !== false && getObjectOption(config, overrides, 'watch');
  21087. const normalizeObjectOptionValue = (optionValue, objectifyValue) => {
  21088. if (!optionValue) {
  21089. return optionValue;
  21090. }
  21091. if (Array.isArray(optionValue)) {
  21092. return optionValue.reduce((result, value) => value && result && { ...result, ...objectifyValue(value) }, {});
  21093. }
  21094. return objectifyValue(optionValue);
  21095. };
  21096. async function mergeOutputOptions(config, overrides, log) {
  21097. const getOption = (name) => overrides[name] ?? config[name];
  21098. const outputOptions = {
  21099. amd: getObjectOption(config, overrides, 'amd'),
  21100. assetFileNames: getOption('assetFileNames'),
  21101. banner: getOption('banner'),
  21102. chunkFileNames: getOption('chunkFileNames'),
  21103. compact: getOption('compact'),
  21104. dir: getOption('dir'),
  21105. dynamicImportInCjs: getOption('dynamicImportInCjs'),
  21106. entryFileNames: getOption('entryFileNames'),
  21107. esModule: getOption('esModule'),
  21108. experimentalMinChunkSize: getOption('experimentalMinChunkSize'),
  21109. exports: getOption('exports'),
  21110. extend: getOption('extend'),
  21111. externalImportAssertions: getOption('externalImportAssertions'),
  21112. externalImportAttributes: getOption('externalImportAttributes'),
  21113. externalLiveBindings: getOption('externalLiveBindings'),
  21114. file: getOption('file'),
  21115. footer: getOption('footer'),
  21116. format: getOption('format'),
  21117. freeze: getOption('freeze'),
  21118. generatedCode: getObjectOption(config, overrides, 'generatedCode', objectifyOptionWithPresets(generatedCodePresets, 'output.generatedCode', URL_OUTPUT_GENERATEDCODE, '')),
  21119. globals: getOption('globals'),
  21120. hashCharacters: getOption('hashCharacters'),
  21121. hoistTransitiveImports: getOption('hoistTransitiveImports'),
  21122. importAttributesKey: getOption('importAttributesKey'),
  21123. indent: getOption('indent'),
  21124. inlineDynamicImports: getOption('inlineDynamicImports'),
  21125. interop: getOption('interop'),
  21126. intro: getOption('intro'),
  21127. manualChunks: getOption('manualChunks'),
  21128. minifyInternalExports: getOption('minifyInternalExports'),
  21129. name: getOption('name'),
  21130. noConflict: getOption('noConflict'),
  21131. outro: getOption('outro'),
  21132. paths: getOption('paths'),
  21133. plugins: await normalizePluginOption(config.plugins),
  21134. preserveModules: getOption('preserveModules'),
  21135. preserveModulesRoot: getOption('preserveModulesRoot'),
  21136. reexportProtoFromExternal: getOption('reexportProtoFromExternal'),
  21137. sanitizeFileName: getOption('sanitizeFileName'),
  21138. sourcemap: getOption('sourcemap'),
  21139. sourcemapBaseUrl: getOption('sourcemapBaseUrl'),
  21140. sourcemapExcludeSources: getOption('sourcemapExcludeSources'),
  21141. sourcemapFile: getOption('sourcemapFile'),
  21142. sourcemapFileNames: getOption('sourcemapFileNames'),
  21143. sourcemapIgnoreList: getOption('sourcemapIgnoreList'),
  21144. sourcemapPathTransform: getOption('sourcemapPathTransform'),
  21145. strict: getOption('strict'),
  21146. systemNullSetters: getOption('systemNullSetters'),
  21147. validate: getOption('validate'),
  21148. virtualDirname: getOption('virtualDirname')
  21149. };
  21150. warnUnknownOptions(config, Object.keys(outputOptions), 'output options', log);
  21151. return outputOptions;
  21152. }
  21153. class WatchEmitter {
  21154. constructor() {
  21155. this.currentHandlers = Object.create(null);
  21156. this.persistentHandlers = Object.create(null);
  21157. }
  21158. // Will be overwritten by Rollup
  21159. async close() { }
  21160. emit(event, ...parameters) {
  21161. return Promise.all([...this.getCurrentHandlers(event), ...this.getPersistentHandlers(event)].map(handler => handler(...parameters)));
  21162. }
  21163. off(event, listener) {
  21164. const listeners = this.persistentHandlers[event];
  21165. if (listeners) {
  21166. // A hack stolen from "mitt": ">>> 0" does not change numbers >= 0, but -1
  21167. // (which would remove the last array element if used unchanged) is turned
  21168. // into max_int, which is outside the array and does not change anything.
  21169. listeners.splice(listeners.indexOf(listener) >>> 0, 1);
  21170. }
  21171. return this;
  21172. }
  21173. on(event, listener) {
  21174. this.getPersistentHandlers(event).push(listener);
  21175. return this;
  21176. }
  21177. onCurrentRun(event, listener) {
  21178. this.getCurrentHandlers(event).push(listener);
  21179. return this;
  21180. }
  21181. once(event, listener) {
  21182. const selfRemovingListener = (...parameters) => {
  21183. this.off(event, selfRemovingListener);
  21184. return listener(...parameters);
  21185. };
  21186. this.on(event, selfRemovingListener);
  21187. return this;
  21188. }
  21189. removeAllListeners() {
  21190. this.removeListenersForCurrentRun();
  21191. this.persistentHandlers = Object.create(null);
  21192. return this;
  21193. }
  21194. removeListenersForCurrentRun() {
  21195. this.currentHandlers = Object.create(null);
  21196. return this;
  21197. }
  21198. getCurrentHandlers(event) {
  21199. return this.currentHandlers[event] || (this.currentHandlers[event] = []);
  21200. }
  21201. getPersistentHandlers(event) {
  21202. return this.persistentHandlers[event] || (this.persistentHandlers[event] = []);
  21203. }
  21204. }
  21205. let fsEvents;
  21206. let fsEventsImportError;
  21207. async function loadFsEvents() {
  21208. try {
  21209. ({ default: fsEvents } = await import('fsevents'));
  21210. }
  21211. catch (error) {
  21212. fsEventsImportError = error;
  21213. }
  21214. }
  21215. // A call to this function will be injected into the chokidar code
  21216. function getFsEvents() {
  21217. if (fsEventsImportError)
  21218. throw fsEventsImportError;
  21219. return fsEvents;
  21220. }
  21221. const fseventsImporter = /*#__PURE__*/Object.defineProperty({
  21222. __proto__: null,
  21223. getFsEvents,
  21224. loadFsEvents
  21225. }, Symbol.toStringTag, { value: 'Module' });
  21226. function watch(configs) {
  21227. const emitter = new WatchEmitter();
  21228. watchInternal(configs, emitter).catch(error => {
  21229. handleError(error);
  21230. });
  21231. return emitter;
  21232. }
  21233. async function watchInternal(configs, emitter) {
  21234. const optionsList = await Promise.all(ensureArray(configs).map(config => mergeOptions(config, true)));
  21235. const watchOptionsList = optionsList.filter(config => config.watch !== false);
  21236. if (watchOptionsList.length === 0) {
  21237. return error(logInvalidOption('watch', URL_WATCH, 'there must be at least one config where "watch" is not set to "false"'));
  21238. }
  21239. await loadFsEvents();
  21240. const { Watcher } = await import('./watch.js');
  21241. new Watcher(watchOptionsList, emitter);
  21242. }
  21243. export { createFilter, defineConfig, fseventsImporter, getAugmentedNamespace, getDefaultExportFromCjs, rollup, rollupInternal, version, watch };